enet.h 239 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930
  1. /**
  2. * include/enet.h - a Single-Header auto-generated variant of enet.h library.
  3. *
  4. * Usage:
  5. * #define ENET_IMPLEMENTATION exactly in ONE source file right BEFORE including the library, like:
  6. *
  7. * #define ENET_IMPLEMENTATION
  8. * #include <enet.h>
  9. *
  10. * License:
  11. * The MIT License (MIT)
  12. *
  13. * Copyright (c) 2002-2016 Lee Salzman
  14. * Copyright (c) 2017-2021 Vladyslav Hrytsenko, Dominik Madarász
  15. *
  16. * Permission is hereby granted, free of charge, to any person obtaining a copy
  17. * of this software and associated documentation files (the "Software"), to deal
  18. * in the Software without restriction, including without limitation the rights
  19. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  20. * copies of the Software, and to permit persons to whom the Software is
  21. * furnished to do so, subject to the following conditions:
  22. *
  23. * The above copyright notice and this permission notice shall be included in all
  24. * copies or substantial portions of the Software.
  25. *
  26. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  27. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  28. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  30. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  31. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  32. * SOFTWARE.
  33. *
  34. */
  35. #ifndef ENET_INCLUDE_H
  36. #define ENET_INCLUDE_H
  37. #include <stdlib.h>
  38. #include <stdbool.h>
  39. #include <stdint.h>
  40. #include <time.h>
  41. #define ENET_VERSION_MAJOR 2
  42. #define ENET_VERSION_MINOR 2
  43. #define ENET_VERSION_PATCH 1
  44. #define ENET_VERSION_CREATE(major, minor, patch) (((major)<<16) | ((minor)<<8) | (patch))
  45. #define ENET_VERSION_GET_MAJOR(version) (((version)>>16)&0xFF)
  46. #define ENET_VERSION_GET_MINOR(version) (((version)>>8)&0xFF)
  47. #define ENET_VERSION_GET_PATCH(version) ((version)&0xFF)
  48. #define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH)
  49. #define ENET_TIME_OVERFLOW 86400000
  50. #define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW)
  51. #define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW)
  52. #define ENET_TIME_LESS_EQUAL(a, b) (! ENET_TIME_GREATER (a, b))
  53. #define ENET_TIME_GREATER_EQUAL(a, b) (! ENET_TIME_LESS (a, b))
  54. #define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b))
  55. // =======================================================================//
  56. // !
  57. // ! System differences
  58. // !
  59. // =======================================================================//
  60. #if defined(_WIN32)
  61. #if defined(_MSC_VER) && defined(ENET_IMPLEMENTATION)
  62. #pragma warning (disable: 4267) // size_t to int conversion
  63. #pragma warning (disable: 4244) // 64bit to 32bit int
  64. #pragma warning (disable: 4018) // signed/unsigned mismatch
  65. #pragma warning (disable: 4146) // unary minus operator applied to unsigned type
  66. #endif
  67. #ifndef ENET_NO_PRAGMA_LINK
  68. #pragma comment(lib, "ws2_32.lib")
  69. #pragma comment(lib, "winmm.lib")
  70. #endif
  71. #if _MSC_VER >= 1910
  72. /* It looks like there were changes as of Visual Studio 2017 and there are no 32/64 bit
  73. versions of _InterlockedExchange[operation], only InterlockedExchange[operation]
  74. (without leading underscore), so we have to distinguish between compiler versions */
  75. #define NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  76. #endif
  77. #ifdef __GNUC__
  78. #if (_WIN32_WINNT < 0x0501)
  79. #undef _WIN32_WINNT
  80. #define _WIN32_WINNT 0x0501
  81. #endif
  82. #endif
  83. #include <winsock2.h>
  84. #include <ws2tcpip.h>
  85. #include <mmsystem.h>
  86. #include <intrin.h>
  87. #if defined(_WIN32) && defined(_MSC_VER)
  88. #if _MSC_VER < 1900
  89. typedef struct timespec {
  90. long tv_sec;
  91. long tv_nsec;
  92. };
  93. #endif
  94. #define CLOCK_MONOTONIC 0
  95. #endif
  96. typedef SOCKET ENetSocket;
  97. #define ENET_SOCKET_NULL INVALID_SOCKET
  98. #define ENET_HOST_TO_NET_16(value) (htons(value))
  99. #define ENET_HOST_TO_NET_32(value) (htonl(value))
  100. #define ENET_NET_TO_HOST_16(value) (ntohs(value))
  101. #define ENET_NET_TO_HOST_32(value) (ntohl(value))
  102. typedef struct {
  103. size_t dataLength;
  104. void * data;
  105. } ENetBuffer;
  106. #define ENET_CALLBACK __cdecl
  107. #ifdef ENET_DLL
  108. #ifdef ENET_IMPLEMENTATION
  109. #define ENET_API __declspec( dllexport )
  110. #else
  111. #define ENET_API __declspec( dllimport )
  112. #endif // ENET_IMPLEMENTATION
  113. #else
  114. #define ENET_API extern
  115. #endif // ENET_DLL
  116. typedef fd_set ENetSocketSet;
  117. #define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO(&(sockset))
  118. #define ENET_SOCKETSET_ADD(sockset, socket) FD_SET(socket, &(sockset))
  119. #define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLR(socket, &(sockset))
  120. #define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET(socket, &(sockset))
  121. #else
  122. #include <sys/types.h>
  123. #include <sys/ioctl.h>
  124. #include <sys/time.h>
  125. #include <sys/socket.h>
  126. #include <poll.h>
  127. #include <arpa/inet.h>
  128. #include <netinet/in.h>
  129. #include <netinet/tcp.h>
  130. #include <netdb.h>
  131. #include <unistd.h>
  132. #include <string.h>
  133. #include <errno.h>
  134. #include <fcntl.h>
  135. #ifdef __APPLE__
  136. #include <mach/clock.h>
  137. #include <mach/mach.h>
  138. #include <Availability.h>
  139. #endif
  140. #ifndef MSG_NOSIGNAL
  141. #define MSG_NOSIGNAL 0
  142. #endif
  143. #ifdef MSG_MAXIOVLEN
  144. #define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN
  145. #endif
  146. typedef int ENetSocket;
  147. #define ENET_SOCKET_NULL -1
  148. #define ENET_HOST_TO_NET_16(value) (htons(value)) /**< macro that converts host to net byte-order of a 16-bit value */
  149. #define ENET_HOST_TO_NET_32(value) (htonl(value)) /**< macro that converts host to net byte-order of a 32-bit value */
  150. #define ENET_NET_TO_HOST_16(value) (ntohs(value)) /**< macro that converts net to host byte-order of a 16-bit value */
  151. #define ENET_NET_TO_HOST_32(value) (ntohl(value)) /**< macro that converts net to host byte-order of a 32-bit value */
  152. typedef struct {
  153. void * data;
  154. size_t dataLength;
  155. } ENetBuffer;
  156. #define ENET_CALLBACK
  157. #define ENET_API extern
  158. typedef fd_set ENetSocketSet;
  159. #define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO(&(sockset))
  160. #define ENET_SOCKETSET_ADD(sockset, socket) FD_SET(socket, &(sockset))
  161. #define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLR(socket, &(sockset))
  162. #define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET(socket, &(sockset))
  163. #endif
  164. #ifndef ENET_BUFFER_MAXIMUM
  165. #define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)
  166. #endif
  167. #define ENET_UNUSED(x) (void)x;
  168. #define ENET_MAX(x, y) ((x) > (y) ? (x) : (y))
  169. #define ENET_MIN(x, y) ((x) < (y) ? (x) : (y))
  170. #define ENET_IPV6 1
  171. const struct in6_addr enet_v4_anyaddr = {{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 }}};
  172. const struct in6_addr enet_v4_noaddr = {{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }}};
  173. const struct in6_addr enet_v4_localhost = {{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x01 }}};
  174. const struct in6_addr enet_v6_anyaddr = {{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }}};
  175. const struct in6_addr enet_v6_noaddr = {{{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }}};
  176. const struct in6_addr enet_v6_localhost = {{{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }}};
  177. #define ENET_HOST_ANY in6addr_any
  178. #define ENET_HOST_BROADCAST 0xFFFFFFFFU
  179. #define ENET_PORT_ANY 0
  180. #ifdef __cplusplus
  181. extern "C" {
  182. #endif
  183. // =======================================================================//
  184. // !
  185. // ! Basic stuff
  186. // !
  187. // =======================================================================//
  188. typedef uint8_t enet_uint8; /**< unsigned 8-bit type */
  189. typedef uint16_t enet_uint16; /**< unsigned 16-bit type */
  190. typedef uint32_t enet_uint32; /**< unsigned 32-bit type */
  191. typedef uint64_t enet_uint64; /**< unsigned 64-bit type */
  192. typedef enet_uint32 ENetVersion;
  193. typedef struct _ENetPacket ENetPacket;
  194. typedef struct _ENetCallbacks {
  195. void *(ENET_CALLBACK *malloc) (size_t size);
  196. void (ENET_CALLBACK *free) (void *memory);
  197. void (ENET_CALLBACK *no_memory) (void);
  198. ENetPacket *(ENET_CALLBACK *packet_create) (const void *data, size_t dataLength, enet_uint32 flags);
  199. void (ENET_CALLBACK *packet_destroy) (ENetPacket *packet);
  200. } ENetCallbacks;
  201. extern void *enet_malloc(size_t);
  202. extern void enet_free(void *);
  203. extern ENetPacket* enet_packet_create(const void*,size_t,enet_uint32);
  204. extern ENetPacket* enet_packet_copy(ENetPacket*);
  205. extern void enet_packet_destroy(ENetPacket*);
  206. // =======================================================================//
  207. // !
  208. // ! List
  209. // !
  210. // =======================================================================//
  211. typedef struct _ENetListNode {
  212. struct _ENetListNode *next;
  213. struct _ENetListNode *previous;
  214. } ENetListNode;
  215. typedef ENetListNode *ENetListIterator;
  216. typedef struct _ENetList {
  217. ENetListNode sentinel;
  218. } ENetList;
  219. extern ENetListIterator enet_list_insert(ENetListIterator, void *);
  220. extern ENetListIterator enet_list_move(ENetListIterator, void *, void *);
  221. extern void *enet_list_remove(ENetListIterator);
  222. extern void enet_list_clear(ENetList *);
  223. extern size_t enet_list_size(ENetList *);
  224. #define enet_list_begin(list) ((list)->sentinel.next)
  225. #define enet_list_end(list) (&(list)->sentinel)
  226. #define enet_list_empty(list) (enet_list_begin(list) == enet_list_end(list))
  227. #define enet_list_next(iterator) ((iterator)->next)
  228. #define enet_list_previous(iterator) ((iterator)->previous)
  229. #define enet_list_front(list) ((void *)(list)->sentinel.next)
  230. #define enet_list_back(list) ((void *)(list)->sentinel.previous)
  231. // =======================================================================//
  232. // !
  233. // ! Protocol
  234. // !
  235. // =======================================================================//
  236. enum {
  237. ENET_PROTOCOL_MINIMUM_MTU = 576,
  238. ENET_PROTOCOL_MAXIMUM_MTU = 4096,
  239. ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32,
  240. ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096,
  241. ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536,
  242. ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1,
  243. ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255,
  244. ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xFFF,
  245. ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024
  246. };
  247. typedef enum _ENetProtocolCommand {
  248. ENET_PROTOCOL_COMMAND_NONE = 0,
  249. ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1,
  250. ENET_PROTOCOL_COMMAND_CONNECT = 2,
  251. ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3,
  252. ENET_PROTOCOL_COMMAND_DISCONNECT = 4,
  253. ENET_PROTOCOL_COMMAND_PING = 5,
  254. ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6,
  255. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7,
  256. ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8,
  257. ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9,
  258. ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10,
  259. ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11,
  260. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12,
  261. ENET_PROTOCOL_COMMAND_COUNT = 13,
  262. ENET_PROTOCOL_COMMAND_MASK = 0x0F
  263. } ENetProtocolCommand;
  264. typedef enum _ENetProtocolFlag {
  265. ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7),
  266. ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6),
  267. ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 << 14),
  268. ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 << 15),
  269. ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED | ENET_PROTOCOL_HEADER_FLAG_SENT_TIME,
  270. ENET_PROTOCOL_HEADER_SESSION_MASK = (3 << 12),
  271. ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12
  272. } ENetProtocolFlag;
  273. #ifdef _MSC_VER
  274. #pragma pack(push, 1)
  275. #define ENET_PACKED
  276. #elif defined(__GNUC__) || defined(__clang__)
  277. #define ENET_PACKED __attribute__ ((packed))
  278. #else
  279. #define ENET_PACKED
  280. #endif
  281. typedef struct _ENetProtocolHeader {
  282. enet_uint16 peerID;
  283. enet_uint16 sentTime;
  284. } ENET_PACKED ENetProtocolHeader;
  285. typedef struct _ENetProtocolCommandHeader {
  286. enet_uint8 command;
  287. enet_uint8 channelID;
  288. enet_uint16 reliableSequenceNumber;
  289. } ENET_PACKED ENetProtocolCommandHeader;
  290. typedef struct _ENetProtocolAcknowledge {
  291. ENetProtocolCommandHeader header;
  292. enet_uint16 receivedReliableSequenceNumber;
  293. enet_uint16 receivedSentTime;
  294. } ENET_PACKED ENetProtocolAcknowledge;
  295. typedef struct _ENetProtocolConnect {
  296. ENetProtocolCommandHeader header;
  297. enet_uint16 outgoingPeerID;
  298. enet_uint8 incomingSessionID;
  299. enet_uint8 outgoingSessionID;
  300. enet_uint32 mtu;
  301. enet_uint32 windowSize;
  302. enet_uint32 channelCount;
  303. enet_uint32 incomingBandwidth;
  304. enet_uint32 outgoingBandwidth;
  305. enet_uint32 packetThrottleInterval;
  306. enet_uint32 packetThrottleAcceleration;
  307. enet_uint32 packetThrottleDeceleration;
  308. enet_uint32 connectID;
  309. enet_uint32 data;
  310. } ENET_PACKED ENetProtocolConnect;
  311. typedef struct _ENetProtocolVerifyConnect {
  312. ENetProtocolCommandHeader header;
  313. enet_uint16 outgoingPeerID;
  314. enet_uint8 incomingSessionID;
  315. enet_uint8 outgoingSessionID;
  316. enet_uint32 mtu;
  317. enet_uint32 windowSize;
  318. enet_uint32 channelCount;
  319. enet_uint32 incomingBandwidth;
  320. enet_uint32 outgoingBandwidth;
  321. enet_uint32 packetThrottleInterval;
  322. enet_uint32 packetThrottleAcceleration;
  323. enet_uint32 packetThrottleDeceleration;
  324. enet_uint32 connectID;
  325. } ENET_PACKED ENetProtocolVerifyConnect;
  326. typedef struct _ENetProtocolBandwidthLimit {
  327. ENetProtocolCommandHeader header;
  328. enet_uint32 incomingBandwidth;
  329. enet_uint32 outgoingBandwidth;
  330. } ENET_PACKED ENetProtocolBandwidthLimit;
  331. typedef struct _ENetProtocolThrottleConfigure {
  332. ENetProtocolCommandHeader header;
  333. enet_uint32 packetThrottleInterval;
  334. enet_uint32 packetThrottleAcceleration;
  335. enet_uint32 packetThrottleDeceleration;
  336. } ENET_PACKED ENetProtocolThrottleConfigure;
  337. typedef struct _ENetProtocolDisconnect {
  338. ENetProtocolCommandHeader header;
  339. enet_uint32 data;
  340. } ENET_PACKED ENetProtocolDisconnect;
  341. typedef struct _ENetProtocolPing {
  342. ENetProtocolCommandHeader header;
  343. } ENET_PACKED ENetProtocolPing;
  344. typedef struct _ENetProtocolSendReliable {
  345. ENetProtocolCommandHeader header;
  346. enet_uint16 dataLength;
  347. } ENET_PACKED ENetProtocolSendReliable;
  348. typedef struct _ENetProtocolSendUnreliable {
  349. ENetProtocolCommandHeader header;
  350. enet_uint16 unreliableSequenceNumber;
  351. enet_uint16 dataLength;
  352. } ENET_PACKED ENetProtocolSendUnreliable;
  353. typedef struct _ENetProtocolSendUnsequenced {
  354. ENetProtocolCommandHeader header;
  355. enet_uint16 unsequencedGroup;
  356. enet_uint16 dataLength;
  357. } ENET_PACKED ENetProtocolSendUnsequenced;
  358. typedef struct _ENetProtocolSendFragment {
  359. ENetProtocolCommandHeader header;
  360. enet_uint16 startSequenceNumber;
  361. enet_uint16 dataLength;
  362. enet_uint32 fragmentCount;
  363. enet_uint32 fragmentNumber;
  364. enet_uint32 totalLength;
  365. enet_uint32 fragmentOffset;
  366. } ENET_PACKED ENetProtocolSendFragment;
  367. typedef union _ENetProtocol {
  368. ENetProtocolCommandHeader header;
  369. ENetProtocolAcknowledge acknowledge;
  370. ENetProtocolConnect connect;
  371. ENetProtocolVerifyConnect verifyConnect;
  372. ENetProtocolDisconnect disconnect;
  373. ENetProtocolPing ping;
  374. ENetProtocolSendReliable sendReliable;
  375. ENetProtocolSendUnreliable sendUnreliable;
  376. ENetProtocolSendUnsequenced sendUnsequenced;
  377. ENetProtocolSendFragment sendFragment;
  378. ENetProtocolBandwidthLimit bandwidthLimit;
  379. ENetProtocolThrottleConfigure throttleConfigure;
  380. } ENET_PACKED ENetProtocol;
  381. #ifdef _MSC_VER
  382. #pragma pack(pop)
  383. #endif
  384. // =======================================================================//
  385. // !
  386. // ! General ENet structs/enums
  387. // !
  388. // =======================================================================//
  389. typedef enum _ENetSocketType {
  390. ENET_SOCKET_TYPE_STREAM = 1,
  391. ENET_SOCKET_TYPE_DATAGRAM = 2
  392. } ENetSocketType;
  393. typedef enum _ENetSocketWait {
  394. ENET_SOCKET_WAIT_NONE = 0,
  395. ENET_SOCKET_WAIT_SEND = (1 << 0),
  396. ENET_SOCKET_WAIT_RECEIVE = (1 << 1),
  397. ENET_SOCKET_WAIT_INTERRUPT = (1 << 2)
  398. } ENetSocketWait;
  399. typedef enum _ENetSocketOption {
  400. ENET_SOCKOPT_NONBLOCK = 1,
  401. ENET_SOCKOPT_BROADCAST = 2,
  402. ENET_SOCKOPT_RCVBUF = 3,
  403. ENET_SOCKOPT_SNDBUF = 4,
  404. ENET_SOCKOPT_REUSEADDR = 5,
  405. ENET_SOCKOPT_RCVTIMEO = 6,
  406. ENET_SOCKOPT_SNDTIMEO = 7,
  407. ENET_SOCKOPT_ERROR = 8,
  408. ENET_SOCKOPT_NODELAY = 9,
  409. ENET_SOCKOPT_IPV6_V6ONLY = 10,
  410. } ENetSocketOption;
  411. typedef enum _ENetSocketShutdown {
  412. ENET_SOCKET_SHUTDOWN_READ = 0,
  413. ENET_SOCKET_SHUTDOWN_WRITE = 1,
  414. ENET_SOCKET_SHUTDOWN_READ_WRITE = 2
  415. } ENetSocketShutdown;
  416. /**
  417. * Portable internet address structure.
  418. *
  419. * The host must be specified in network byte-order, and the port must be in host
  420. * byte-order. The constant ENET_HOST_ANY may be used to specify the default
  421. * server host. The constant ENET_HOST_BROADCAST may be used to specify the
  422. * broadcast address (255.255.255.255). This makes sense for enet_host_connect,
  423. * but not for enet_host_create. Once a server responds to a broadcast, the
  424. * address is updated from ENET_HOST_BROADCAST to the server's actual IP address.
  425. */
  426. typedef struct _ENetAddress {
  427. struct in6_addr host;
  428. enet_uint16 port;
  429. enet_uint16 sin6_scope_id;
  430. } ENetAddress;
  431. #define in6_equal(in6_addr_a, in6_addr_b) (memcmp(&in6_addr_a, &in6_addr_b, sizeof(struct in6_addr)) == 0)
  432. /**
  433. * Packet flag bit constants.
  434. *
  435. * The host must be specified in network byte-order, and the port must be in
  436. * host byte-order. The constant ENET_HOST_ANY may be used to specify the
  437. * default server host.
  438. *
  439. * @sa ENetPacket
  440. */
  441. typedef enum _ENetPacketFlag {
  442. ENET_PACKET_FLAG_RELIABLE = (1 << 0), /** packet must be received by the target peer and resend attempts should be made until the packet is delivered */
  443. ENET_PACKET_FLAG_UNSEQUENCED = (1 << 1), /** packet will not be sequenced with other packets not supported for reliable packets */
  444. ENET_PACKET_FLAG_NO_ALLOCATE = (1 << 2), /** packet will not allocate data, and user must supply it instead */
  445. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = (1 << 3), /** packet will be fragmented using unreliable (instead of reliable) sends if it exceeds the MTU */
  446. ENET_PACKET_FLAG_SENT = (1 << 8), /** whether the packet has been sent from all queues it has been entered into */
  447. } ENetPacketFlag;
  448. typedef void (ENET_CALLBACK *ENetPacketFreeCallback)(void *);
  449. /**
  450. * ENet packet structure.
  451. *
  452. * An ENet data packet that may be sent to or received from a peer. The shown
  453. * fields should only be read and never modified. The data field contains the
  454. * allocated data for the packet. The dataLength fields specifies the length
  455. * of the allocated data. The flags field is either 0 (specifying no flags),
  456. * or a bitwise-or of any combination of the following flags:
  457. *
  458. * ENET_PACKET_FLAG_RELIABLE - packet must be received by the target peer and resend attempts should be made until the packet is delivered
  459. * ENET_PACKET_FLAG_UNSEQUENCED - packet will not be sequenced with other packets (not supported for reliable packets)
  460. * ENET_PACKET_FLAG_NO_ALLOCATE - packet will not allocate data, and user must supply it instead
  461. * ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT - packet will be fragmented using unreliable (instead of reliable) sends if it exceeds the MTU
  462. * ENET_PACKET_FLAG_SENT - whether the packet has been sent from all queues it has been entered into
  463. * @sa ENetPacketFlag
  464. */
  465. typedef struct _ENetPacket {
  466. size_t referenceCount; /**< internal use only */
  467. enet_uint32 flags; /**< bitwise-or of ENetPacketFlag constants */
  468. enet_uint8 * data; /**< allocated data for packet */
  469. size_t dataLength; /**< length of data */
  470. ENetPacketFreeCallback freeCallback; /**< function to be called when the packet is no longer in use */
  471. void * userData; /**< application private data, may be freely modified */
  472. } ENetPacket;
  473. typedef struct _ENetAcknowledgement {
  474. ENetListNode acknowledgementList;
  475. enet_uint32 sentTime;
  476. ENetProtocol command;
  477. } ENetAcknowledgement;
  478. typedef struct _ENetOutgoingCommand {
  479. ENetListNode outgoingCommandList;
  480. enet_uint16 reliableSequenceNumber;
  481. enet_uint16 unreliableSequenceNumber;
  482. enet_uint32 sentTime;
  483. enet_uint32 roundTripTimeout;
  484. enet_uint32 roundTripTimeoutLimit;
  485. enet_uint32 fragmentOffset;
  486. enet_uint16 fragmentLength;
  487. enet_uint16 sendAttempts;
  488. ENetProtocol command;
  489. ENetPacket * packet;
  490. } ENetOutgoingCommand;
  491. typedef struct _ENetIncomingCommand {
  492. ENetListNode incomingCommandList;
  493. enet_uint16 reliableSequenceNumber;
  494. enet_uint16 unreliableSequenceNumber;
  495. ENetProtocol command;
  496. enet_uint32 fragmentCount;
  497. enet_uint32 fragmentsRemaining;
  498. enet_uint32 *fragments;
  499. ENetPacket * packet;
  500. } ENetIncomingCommand;
  501. typedef enum _ENetPeerState {
  502. ENET_PEER_STATE_DISCONNECTED = 0,
  503. ENET_PEER_STATE_CONNECTING = 1,
  504. ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2,
  505. ENET_PEER_STATE_CONNECTION_PENDING = 3,
  506. ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4,
  507. ENET_PEER_STATE_CONNECTED = 5,
  508. ENET_PEER_STATE_DISCONNECT_LATER = 6,
  509. ENET_PEER_STATE_DISCONNECTING = 7,
  510. ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8,
  511. ENET_PEER_STATE_ZOMBIE = 9
  512. } ENetPeerState;
  513. enum {
  514. ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024,
  515. ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024,
  516. ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000,
  517. ENET_HOST_DEFAULT_MTU = 1400,
  518. ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024,
  519. ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024,
  520. ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500,
  521. ENET_PEER_DEFAULT_PACKET_THROTTLE = 32,
  522. ENET_PEER_PACKET_THROTTLE_SCALE = 32,
  523. ENET_PEER_PACKET_THROTTLE_COUNTER = 7,
  524. ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2,
  525. ENET_PEER_PACKET_THROTTLE_DECELERATION = 2,
  526. ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000,
  527. ENET_PEER_PACKET_LOSS_SCALE = (1 << 16),
  528. ENET_PEER_PACKET_LOSS_INTERVAL = 10000,
  529. ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024,
  530. ENET_PEER_TIMEOUT_LIMIT = 32,
  531. ENET_PEER_TIMEOUT_MINIMUM = 5000,
  532. ENET_PEER_TIMEOUT_MAXIMUM = 30000,
  533. ENET_PEER_PING_INTERVAL = 500,
  534. ENET_PEER_UNSEQUENCED_WINDOWS = 64,
  535. ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024,
  536. ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32,
  537. ENET_PEER_RELIABLE_WINDOWS = 16,
  538. ENET_PEER_RELIABLE_WINDOW_SIZE = 0x1000,
  539. ENET_PEER_FREE_RELIABLE_WINDOWS = 8
  540. };
  541. typedef struct _ENetChannel {
  542. enet_uint16 outgoingReliableSequenceNumber;
  543. enet_uint16 outgoingUnreliableSequenceNumber;
  544. enet_uint16 usedReliableWindows;
  545. enet_uint16 reliableWindows[ENET_PEER_RELIABLE_WINDOWS];
  546. enet_uint16 incomingReliableSequenceNumber;
  547. enet_uint16 incomingUnreliableSequenceNumber;
  548. ENetList incomingReliableCommands;
  549. ENetList incomingUnreliableCommands;
  550. } ENetChannel;
  551. /**
  552. * An ENet peer which data packets may be sent or received from.
  553. *
  554. * No fields should be modified unless otherwise specified.
  555. */
  556. typedef struct _ENetPeer {
  557. ENetListNode dispatchList;
  558. struct _ENetHost *host;
  559. enet_uint16 outgoingPeerID;
  560. enet_uint16 incomingPeerID;
  561. enet_uint32 connectID;
  562. enet_uint8 outgoingSessionID;
  563. enet_uint8 incomingSessionID;
  564. ENetAddress address; /**< Internet address of the peer */
  565. void * data; /**< Application private data, may be freely modified */
  566. ENetPeerState state;
  567. ENetChannel * channels;
  568. size_t channelCount; /**< Number of channels allocated for communication with peer */
  569. enet_uint32 incomingBandwidth; /**< Downstream bandwidth of the client in bytes/second */
  570. enet_uint32 outgoingBandwidth; /**< Upstream bandwidth of the client in bytes/second */
  571. enet_uint32 incomingBandwidthThrottleEpoch;
  572. enet_uint32 outgoingBandwidthThrottleEpoch;
  573. enet_uint32 incomingDataTotal;
  574. enet_uint64 totalDataReceived;
  575. enet_uint32 outgoingDataTotal;
  576. enet_uint64 totalDataSent;
  577. enet_uint32 lastSendTime;
  578. enet_uint32 lastReceiveTime;
  579. enet_uint32 nextTimeout;
  580. enet_uint32 earliestTimeout;
  581. enet_uint32 packetLossEpoch;
  582. enet_uint32 packetsSent;
  583. enet_uint64 totalPacketsSent; /**< total number of packets sent during a session */
  584. enet_uint32 packetsLost;
  585. enet_uint32 totalPacketsLost; /**< total number of packets lost during a session */
  586. enet_uint32 packetLoss; /**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE */
  587. enet_uint32 packetLossVariance;
  588. enet_uint32 packetThrottle;
  589. enet_uint32 packetThrottleLimit;
  590. enet_uint32 packetThrottleCounter;
  591. enet_uint32 packetThrottleEpoch;
  592. enet_uint32 packetThrottleAcceleration;
  593. enet_uint32 packetThrottleDeceleration;
  594. enet_uint32 packetThrottleInterval;
  595. enet_uint32 pingInterval;
  596. enet_uint32 timeoutLimit;
  597. enet_uint32 timeoutMinimum;
  598. enet_uint32 timeoutMaximum;
  599. enet_uint32 lastRoundTripTime;
  600. enet_uint32 lowestRoundTripTime;
  601. enet_uint32 lastRoundTripTimeVariance;
  602. enet_uint32 highestRoundTripTimeVariance;
  603. enet_uint32 roundTripTime; /**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgement */
  604. enet_uint32 roundTripTimeVariance;
  605. enet_uint32 mtu;
  606. enet_uint32 windowSize;
  607. enet_uint32 reliableDataInTransit;
  608. enet_uint16 outgoingReliableSequenceNumber;
  609. ENetList acknowledgements;
  610. ENetList sentReliableCommands;
  611. ENetList sentUnreliableCommands;
  612. ENetList outgoingReliableCommands;
  613. ENetList outgoingUnreliableCommands;
  614. ENetList dispatchedCommands;
  615. int needsDispatch;
  616. enet_uint16 incomingUnsequencedGroup;
  617. enet_uint16 outgoingUnsequencedGroup;
  618. enet_uint32 unsequencedWindow[ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32];
  619. enet_uint32 eventData;
  620. size_t totalWaitingData;
  621. } ENetPeer;
  622. /** An ENet packet compressor for compressing UDP packets before socket sends or receives. */
  623. typedef struct _ENetCompressor {
  624. /** Context data for the compressor. Must be non-NULL. */
  625. void *context;
  626. /** Compresses from inBuffers[0:inBufferCount-1], containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */
  627. size_t(ENET_CALLBACK * compress) (void *context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit);
  628. /** Decompresses from inData, containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */
  629. size_t(ENET_CALLBACK * decompress) (void *context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit);
  630. /** Destroys the context when compression is disabled or the host is destroyed. May be NULL. */
  631. void (ENET_CALLBACK * destroy)(void *context);
  632. } ENetCompressor;
  633. /** Callback that computes the checksum of the data held in buffers[0:bufferCount-1] */
  634. typedef enet_uint32 (ENET_CALLBACK * ENetChecksumCallback)(const ENetBuffer *buffers, size_t bufferCount);
  635. /** Callback for intercepting received raw UDP packets. Should return 1 to intercept, 0 to ignore, or -1 to propagate an error. */
  636. typedef int (ENET_CALLBACK * ENetInterceptCallback)(struct _ENetHost *host, void *event);
  637. /** An ENet host for communicating with peers.
  638. *
  639. * No fields should be modified unless otherwise stated.
  640. *
  641. * @sa enet_host_create()
  642. * @sa enet_host_destroy()
  643. * @sa enet_host_connect()
  644. * @sa enet_host_service()
  645. * @sa enet_host_flush()
  646. * @sa enet_host_broadcast()
  647. * @sa enet_host_compress()
  648. * @sa enet_host_channel_limit()
  649. * @sa enet_host_bandwidth_limit()
  650. * @sa enet_host_bandwidth_throttle()
  651. */
  652. typedef struct _ENetHost {
  653. ENetSocket socket;
  654. ENetAddress address; /**< Internet address of the host */
  655. enet_uint32 incomingBandwidth; /**< downstream bandwidth of the host */
  656. enet_uint32 outgoingBandwidth; /**< upstream bandwidth of the host */
  657. enet_uint32 bandwidthThrottleEpoch;
  658. enet_uint32 mtu;
  659. enet_uint32 randomSeed;
  660. int recalculateBandwidthLimits;
  661. ENetPeer * peers; /**< array of peers allocated for this host */
  662. size_t peerCount; /**< number of peers allocated for this host */
  663. size_t channelLimit; /**< maximum number of channels allowed for connected peers */
  664. enet_uint32 serviceTime;
  665. ENetList dispatchQueue;
  666. int continueSending;
  667. size_t packetSize;
  668. enet_uint16 headerFlags;
  669. ENetProtocol commands[ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS];
  670. size_t commandCount;
  671. ENetBuffer buffers[ENET_BUFFER_MAXIMUM];
  672. size_t bufferCount;
  673. ENetChecksumCallback checksum; /**< callback the user can set to enable packet checksums for this host */
  674. ENetCompressor compressor;
  675. enet_uint8 packetData[2][ENET_PROTOCOL_MAXIMUM_MTU];
  676. ENetAddress receivedAddress;
  677. enet_uint8 * receivedData;
  678. size_t receivedDataLength;
  679. enet_uint32 totalSentData; /**< total data sent, user should reset to 0 as needed to prevent overflow */
  680. enet_uint32 totalSentPackets; /**< total UDP packets sent, user should reset to 0 as needed to prevent overflow */
  681. enet_uint32 totalReceivedData; /**< total data received, user should reset to 0 as needed to prevent overflow */
  682. enet_uint32 totalReceivedPackets; /**< total UDP packets received, user should reset to 0 as needed to prevent overflow */
  683. ENetInterceptCallback intercept; /**< callback the user can set to intercept received raw UDP packets */
  684. size_t connectedPeers;
  685. size_t bandwidthLimitedPeers;
  686. size_t duplicatePeers; /**< optional number of allowed peers from duplicate IPs, defaults to ENET_PROTOCOL_MAXIMUM_PEER_ID */
  687. size_t maximumPacketSize; /**< the maximum allowable packet size that may be sent or received on a peer */
  688. size_t maximumWaitingData; /**< the maximum aggregate amount of buffer space a peer may use waiting for packets to be delivered */
  689. } ENetHost;
  690. /**
  691. * An ENet event type, as specified in @ref ENetEvent.
  692. */
  693. typedef enum _ENetEventType {
  694. /** no event occurred within the specified time limit */
  695. ENET_EVENT_TYPE_NONE = 0,
  696. /** a connection request initiated by enet_host_connect has completed.
  697. * The peer field contains the peer which successfully connected.
  698. */
  699. ENET_EVENT_TYPE_CONNECT = 1,
  700. /** a peer has disconnected. This event is generated on a successful
  701. * completion of a disconnect initiated by enet_peer_disconnect, if
  702. * a peer has timed out. The peer field contains the peer
  703. * which disconnected. The data field contains user supplied data
  704. * describing the disconnection, or 0, if none is available.
  705. */
  706. ENET_EVENT_TYPE_DISCONNECT = 2,
  707. /** a packet has been received from a peer. The peer field specifies the
  708. * peer which sent the packet. The channelID field specifies the channel
  709. * number upon which the packet was received. The packet field contains
  710. * the packet that was received; this packet must be destroyed with
  711. * enet_packet_destroy after use.
  712. */
  713. ENET_EVENT_TYPE_RECEIVE = 3,
  714. /** a peer is disconnected because the host didn't receive the acknowledgment
  715. * packet within certain maximum time out. The reason could be because of bad
  716. * network connection or host crashed.
  717. */
  718. ENET_EVENT_TYPE_DISCONNECT_TIMEOUT = 4,
  719. } ENetEventType;
  720. /**
  721. * An ENet event as returned by enet_host_service().
  722. *
  723. * @sa enet_host_service
  724. */
  725. typedef struct _ENetEvent {
  726. ENetEventType type; /**< type of the event */
  727. ENetPeer * peer; /**< peer that generated a connect, disconnect or receive event */
  728. enet_uint8 channelID; /**< channel on the peer that generated the event, if appropriate */
  729. enet_uint32 data; /**< data associated with the event, if appropriate */
  730. ENetPacket * packet; /**< packet associated with the event, if appropriate */
  731. } ENetEvent;
  732. // =======================================================================//
  733. // !
  734. // ! Public API
  735. // !
  736. // =======================================================================//
  737. /**
  738. * Initializes ENet globally. Must be called prior to using any functions in ENet.
  739. * @returns 0 on success, < 0 on failure
  740. */
  741. ENET_API int enet_initialize(void);
  742. /**
  743. * Initializes ENet globally and supplies user-overridden callbacks. Must be called prior to using any functions in ENet. Do not use enet_initialize() if you use this variant. Make sure the ENetCallbacks structure is zeroed out so that any additional callbacks added in future versions will be properly ignored.
  744. *
  745. * @param version the constant ENET_VERSION should be supplied so ENet knows which version of ENetCallbacks struct to use
  746. * @param inits user-overridden callbacks where any NULL callbacks will use ENet's defaults
  747. * @returns 0 on success, < 0 on failure
  748. */
  749. ENET_API int enet_initialize_with_callbacks(ENetVersion version, const ENetCallbacks * inits);
  750. /**
  751. * Shuts down ENet globally. Should be called when a program that has initialized ENet exits.
  752. */
  753. ENET_API void enet_deinitialize(void);
  754. /**
  755. * Gives the linked version of the ENet library.
  756. * @returns the version number
  757. */
  758. ENET_API ENetVersion enet_linked_version(void);
  759. /** Returns the monotonic time in milliseconds. Its initial value is unspecified unless otherwise set. */
  760. ENET_API enet_uint32 enet_time_get(void);
  761. /** ENet socket functions */
  762. ENET_API ENetSocket enet_socket_create(ENetSocketType);
  763. ENET_API int enet_socket_bind(ENetSocket, const ENetAddress *);
  764. ENET_API int enet_socket_get_address(ENetSocket, ENetAddress *);
  765. ENET_API int enet_socket_listen(ENetSocket, int);
  766. ENET_API ENetSocket enet_socket_accept(ENetSocket, ENetAddress *);
  767. ENET_API int enet_socket_connect(ENetSocket, const ENetAddress *);
  768. ENET_API int enet_socket_send(ENetSocket, const ENetAddress *, const ENetBuffer *, size_t);
  769. ENET_API int enet_socket_receive(ENetSocket, ENetAddress *, ENetBuffer *, size_t);
  770. ENET_API int enet_socket_wait(ENetSocket, enet_uint32 *, enet_uint64);
  771. ENET_API int enet_socket_set_option(ENetSocket, ENetSocketOption, int);
  772. ENET_API int enet_socket_get_option(ENetSocket, ENetSocketOption, int *);
  773. ENET_API int enet_socket_shutdown(ENetSocket, ENetSocketShutdown);
  774. ENET_API void enet_socket_destroy(ENetSocket);
  775. ENET_API int enet_socketset_select(ENetSocket, ENetSocketSet *, ENetSocketSet *, enet_uint32);
  776. /** Attempts to parse the printable form of the IP address in the parameter hostName
  777. and sets the host field in the address parameter if successful.
  778. @param address destination to store the parsed IP address
  779. @param hostName IP address to parse
  780. @retval 0 on success
  781. @retval < 0 on failure
  782. @returns the address of the given hostName in address on success
  783. */
  784. ENET_API int enet_address_set_host_ip(ENetAddress * address, const char * hostName);
  785. /** Attempts to resolve the host named by the parameter hostName and sets
  786. the host field in the address parameter if successful.
  787. @param address destination to store resolved address
  788. @param hostName host name to lookup
  789. @retval 0 on success
  790. @retval < 0 on failure
  791. @returns the address of the given hostName in address on success
  792. */
  793. ENET_API int enet_address_set_host(ENetAddress * address, const char * hostName);
  794. /** Gives the printable form of the IP address specified in the address parameter.
  795. @param address address printed
  796. @param hostName destination for name, must not be NULL
  797. @param nameLength maximum length of hostName.
  798. @returns the null-terminated name of the host in hostName on success
  799. @retval 0 on success
  800. @retval < 0 on failure
  801. */
  802. ENET_API int enet_address_get_host_ip(const ENetAddress * address, char * hostName, size_t nameLength);
  803. /** Attempts to do a reverse lookup of the host field in the address parameter.
  804. @param address address used for reverse lookup
  805. @param hostName destination for name, must not be NULL
  806. @param nameLength maximum length of hostName.
  807. @returns the null-terminated name of the host in hostName on success
  808. @retval 0 on success
  809. @retval < 0 on failure
  810. */
  811. ENET_API int enet_address_get_host(const ENetAddress * address, char * hostName, size_t nameLength);
  812. ENET_API enet_uint32 enet_host_get_peers_count(ENetHost *);
  813. ENET_API enet_uint32 enet_host_get_packets_sent(ENetHost *);
  814. ENET_API enet_uint32 enet_host_get_packets_received(ENetHost *);
  815. ENET_API enet_uint32 enet_host_get_bytes_sent(ENetHost *);
  816. ENET_API enet_uint32 enet_host_get_bytes_received(ENetHost *);
  817. ENET_API enet_uint32 enet_host_get_received_data(ENetHost *, enet_uint8** data);
  818. ENET_API enet_uint32 enet_host_get_mtu(ENetHost *);
  819. ENET_API enet_uint32 enet_peer_get_id(ENetPeer *);
  820. ENET_API enet_uint32 enet_peer_get_ip(ENetPeer *, char * ip, size_t ipLength);
  821. ENET_API enet_uint16 enet_peer_get_port(ENetPeer *);
  822. ENET_API enet_uint32 enet_peer_get_rtt(ENetPeer *);
  823. ENET_API enet_uint64 enet_peer_get_packets_sent(ENetPeer *);
  824. ENET_API enet_uint32 enet_peer_get_packets_lost(ENetPeer *);
  825. ENET_API enet_uint64 enet_peer_get_bytes_sent(ENetPeer *);
  826. ENET_API enet_uint64 enet_peer_get_bytes_received(ENetPeer *);
  827. ENET_API ENetPeerState enet_peer_get_state(ENetPeer *);
  828. ENET_API void * enet_peer_get_data(ENetPeer *);
  829. ENET_API void enet_peer_set_data(ENetPeer *, const void *);
  830. ENET_API void * enet_packet_get_data(ENetPacket *);
  831. ENET_API enet_uint32 enet_packet_get_length(ENetPacket *);
  832. ENET_API void enet_packet_set_free_callback(ENetPacket *, void *);
  833. ENET_API ENetPacket * enet_packet_create_offset(const void *, size_t, size_t, enet_uint32);
  834. ENET_API enet_uint32 enet_crc32(const ENetBuffer *, size_t);
  835. ENET_API ENetHost * enet_host_create(const ENetAddress *, size_t, size_t, enet_uint32, enet_uint32);
  836. ENET_API void enet_host_destroy(ENetHost *);
  837. ENET_API ENetPeer * enet_host_connect(ENetHost *, const ENetAddress *, size_t, enet_uint32);
  838. ENET_API int enet_host_check_events(ENetHost *, ENetEvent *);
  839. ENET_API int enet_host_service(ENetHost *, ENetEvent *, enet_uint32);
  840. ENET_API int enet_host_send_raw(ENetHost *, const ENetAddress *, enet_uint8 *, size_t);
  841. ENET_API int enet_host_send_raw_ex(ENetHost *host, const ENetAddress* address, enet_uint8* data, size_t skipBytes, size_t bytesToSend);
  842. ENET_API void enet_host_set_intercept(ENetHost *, const ENetInterceptCallback);
  843. ENET_API void enet_host_flush(ENetHost *);
  844. ENET_API void enet_host_broadcast(ENetHost *, enet_uint8, ENetPacket *);
  845. ENET_API void enet_host_compress(ENetHost *, const ENetCompressor *);
  846. ENET_API void enet_host_channel_limit(ENetHost *, size_t);
  847. ENET_API void enet_host_bandwidth_limit(ENetHost *, enet_uint32, enet_uint32);
  848. extern void enet_host_bandwidth_throttle(ENetHost *);
  849. extern enet_uint64 enet_host_random_seed(void);
  850. ENET_API int enet_peer_send(ENetPeer *, enet_uint8, ENetPacket *);
  851. ENET_API ENetPacket * enet_peer_receive(ENetPeer *, enet_uint8 * channelID);
  852. ENET_API void enet_peer_ping(ENetPeer *);
  853. ENET_API void enet_peer_ping_interval(ENetPeer *, enet_uint32);
  854. ENET_API void enet_peer_timeout(ENetPeer *, enet_uint32, enet_uint32, enet_uint32);
  855. ENET_API void enet_peer_reset(ENetPeer *);
  856. ENET_API void enet_peer_disconnect(ENetPeer *, enet_uint32);
  857. ENET_API void enet_peer_disconnect_now(ENetPeer *, enet_uint32);
  858. ENET_API void enet_peer_disconnect_later(ENetPeer *, enet_uint32);
  859. ENET_API void enet_peer_throttle_configure(ENetPeer *, enet_uint32, enet_uint32, enet_uint32);
  860. extern int enet_peer_throttle(ENetPeer *, enet_uint32);
  861. extern void enet_peer_reset_queues(ENetPeer *);
  862. extern void enet_peer_setup_outgoing_command(ENetPeer *, ENetOutgoingCommand *);
  863. extern ENetOutgoingCommand * enet_peer_queue_outgoing_command(ENetPeer *, const ENetProtocol *, ENetPacket *, enet_uint32, enet_uint16);
  864. extern ENetIncomingCommand * enet_peer_queue_incoming_command(ENetPeer *, const ENetProtocol *, const void *, size_t, enet_uint32, enet_uint32);
  865. extern ENetAcknowledgement * enet_peer_queue_acknowledgement(ENetPeer *, const ENetProtocol *, enet_uint16);
  866. extern void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer *, ENetChannel *);
  867. extern void enet_peer_dispatch_incoming_reliable_commands(ENetPeer *, ENetChannel *);
  868. extern void enet_peer_on_connect(ENetPeer *);
  869. extern void enet_peer_on_disconnect(ENetPeer *);
  870. extern size_t enet_protocol_command_size (enet_uint8);
  871. #ifdef __cplusplus
  872. }
  873. #endif
  874. #if defined(ENET_IMPLEMENTATION) && !defined(ENET_IMPLEMENTATION_DONE)
  875. #define ENET_IMPLEMENTATION_DONE 1
  876. #ifdef __cplusplus
  877. extern "C" {
  878. #endif
  879. // =======================================================================//
  880. // !
  881. // ! Atomics
  882. // !
  883. // =======================================================================//
  884. #if defined(_MSC_VER)
  885. #define ENET_AT_CASSERT_PRED(predicate) sizeof(char[2 * !!(predicate)-1])
  886. #define ENET_IS_SUPPORTED_ATOMIC(size) ENET_AT_CASSERT_PRED(size == 1 || size == 2 || size == 4 || size == 8)
  887. #define ENET_ATOMIC_SIZEOF(variable) (ENET_IS_SUPPORTED_ATOMIC(sizeof(*(variable))), sizeof(*(variable)))
  888. __inline int64_t enet_at_atomic_read(char *ptr, size_t size)
  889. {
  890. switch (size) {
  891. case 1:
  892. return _InterlockedExchangeAdd8((volatile char *)ptr, 0);
  893. case 2:
  894. return _InterlockedExchangeAdd16((volatile SHORT *)ptr, 0);
  895. case 4:
  896. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  897. return InterlockedExchangeAdd((volatile LONG *)ptr, 0);
  898. #else
  899. return _InterlockedExchangeAdd((volatile LONG *)ptr, 0);
  900. #endif
  901. case 8:
  902. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  903. return InterlockedExchangeAdd64((volatile LONGLONG *)ptr, 0);
  904. #else
  905. return _InterlockedExchangeAdd64((volatile LONGLONG *)ptr, 0);
  906. #endif
  907. default:
  908. return 0xbad13bad; /* never reached */
  909. }
  910. }
  911. __inline int64_t enet_at_atomic_write(char *ptr, int64_t value, size_t size)
  912. {
  913. switch (size) {
  914. case 1:
  915. return _InterlockedExchange8((volatile char *)ptr, (char)value);
  916. case 2:
  917. return _InterlockedExchange16((volatile SHORT *)ptr, (SHORT)value);
  918. case 4:
  919. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  920. return InterlockedExchange((volatile LONG *)ptr, (LONG)value);
  921. #else
  922. return _InterlockedExchange((volatile LONG *)ptr, (LONG)value);
  923. #endif
  924. case 8:
  925. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  926. return InterlockedExchange64((volatile LONGLONG *)ptr, (LONGLONG)value);
  927. #else
  928. return _InterlockedExchange64((volatile LONGLONG *)ptr, (LONGLONG)value);
  929. #endif
  930. default:
  931. return 0xbad13bad; /* never reached */
  932. }
  933. }
  934. __inline int64_t enet_at_atomic_cas(char *ptr, int64_t new_val, int64_t old_val, size_t size)
  935. {
  936. switch (size) {
  937. case 1:
  938. return _InterlockedCompareExchange8((volatile char *)ptr, (char)new_val, (char)old_val);
  939. case 2:
  940. return _InterlockedCompareExchange16((volatile SHORT *)ptr, (SHORT)new_val,
  941. (SHORT)old_val);
  942. case 4:
  943. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  944. return InterlockedCompareExchange((volatile LONG *)ptr, (LONG)new_val, (LONG)old_val);
  945. #else
  946. return _InterlockedCompareExchange((volatile LONG *)ptr, (LONG)new_val, (LONG)old_val);
  947. #endif
  948. case 8:
  949. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  950. return InterlockedCompareExchange64((volatile LONGLONG *)ptr, (LONGLONG)new_val,
  951. (LONGLONG)old_val);
  952. #else
  953. return _InterlockedCompareExchange64((volatile LONGLONG *)ptr, (LONGLONG)new_val,
  954. (LONGLONG)old_val);
  955. #endif
  956. default:
  957. return 0xbad13bad; /* never reached */
  958. }
  959. }
  960. __inline int64_t enet_at_atomic_inc(char *ptr, int64_t delta, size_t data_size)
  961. {
  962. switch (data_size) {
  963. case 1:
  964. return _InterlockedExchangeAdd8((volatile char *)ptr, (char)delta);
  965. case 2:
  966. return _InterlockedExchangeAdd16((volatile SHORT *)ptr, (SHORT)delta);
  967. case 4:
  968. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  969. return InterlockedExchangeAdd((volatile LONG *)ptr, (LONG)delta);
  970. #else
  971. return _InterlockedExchangeAdd((volatile LONG *)ptr, (LONG)delta);
  972. #endif
  973. case 8:
  974. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  975. return InterlockedExchangeAdd64((volatile LONGLONG *)ptr, (LONGLONG)delta);
  976. #else
  977. return _InterlockedExchangeAdd64((volatile LONGLONG *)ptr, (LONGLONG)delta);
  978. #endif
  979. default:
  980. return 0xbad13bad; /* never reached */
  981. }
  982. }
  983. #define ENET_ATOMIC_READ(variable) enet_at_atomic_read((char *)(variable), ENET_ATOMIC_SIZEOF(variable))
  984. #define ENET_ATOMIC_WRITE(variable, new_val) \
  985. enet_at_atomic_write((char *)(variable), (int64_t)(new_val), ENET_ATOMIC_SIZEOF(variable))
  986. #define ENET_ATOMIC_CAS(variable, old_value, new_val) \
  987. enet_at_atomic_cas((char *)(variable), (int64_t)(new_val), (int64_t)(old_value), \
  988. ENET_ATOMIC_SIZEOF(variable))
  989. #define ENET_ATOMIC_INC(variable) enet_at_atomic_inc((char *)(variable), 1, ENET_ATOMIC_SIZEOF(variable))
  990. #define ENET_ATOMIC_DEC(variable) enet_at_atomic_inc((char *)(variable), -1, ENET_ATOMIC_SIZEOF(variable))
  991. #define ENET_ATOMIC_INC_BY(variable, delta) \
  992. enet_at_atomic_inc((char *)(variable), (delta), ENET_ATOMIC_SIZEOF(variable))
  993. #define ENET_ATOMIC_DEC_BY(variable, delta) \
  994. enet_at_atomic_inc((char *)(variable), -(delta), ENET_ATOMIC_SIZEOF(variable))
  995. #elif defined(__GNUC__) || defined(__clang__)
  996. #if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
  997. #define AT_HAVE_ATOMICS
  998. #endif
  999. /* We want to use __atomic built-ins if possible because the __sync primitives are
  1000. deprecated, because the __atomic build-ins allow us to use ENET_ATOMIC_WRITE on
  1001. uninitialized memory without running into undefined behavior, and because the
  1002. __atomic versions generate more efficient code since we don't need to rely on
  1003. CAS when we don't actually want it.
  1004. Note that we use acquire-release memory order (like mutexes do). We could use
  1005. sequentially consistent memory order but that has lower performance and is
  1006. almost always unneeded. */
  1007. #ifdef AT_HAVE_ATOMICS
  1008. #define ENET_ATOMIC_READ(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
  1009. #define ENET_ATOMIC_WRITE(ptr, value) __atomic_store_n((ptr), (value), __ATOMIC_RELEASE)
  1010. #ifndef typeof
  1011. #define typeof __typeof__
  1012. #endif
  1013. /* clang_analyzer doesn't know that CAS writes to memory so it complains about
  1014. potentially lost data. Replace the code with the equivalent non-sync code. */
  1015. #ifdef __clang_analyzer__
  1016. #define ENET_ATOMIC_CAS(ptr, old_value, new_value) \
  1017. ({ \
  1018. typeof(*(ptr)) ENET_ATOMIC_CAS_old_actual_ = (*(ptr)); \
  1019. if (ATOMIC_CAS_old_actual_ == (old_value)) { \
  1020. *(ptr) = new_value; \
  1021. } \
  1022. ENET_ATOMIC_CAS_old_actual_; \
  1023. })
  1024. #else
  1025. /* Could use __auto_type instead of typeof but that shouldn't work in C++.
  1026. The ({ }) syntax is a GCC extension called statement expression. It lets
  1027. us return a value out of the macro.
  1028. TODO We should return bool here instead of the old value to avoid the ABA
  1029. problem. */
  1030. #define ENET_ATOMIC_CAS(ptr, old_value, new_value) \
  1031. ({ \
  1032. typeof(*(ptr)) ENET_ATOMIC_CAS_expected_ = (old_value); \
  1033. __atomic_compare_exchange_n((ptr), &ENET_ATOMIC_CAS_expected_, (new_value), false, \
  1034. __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE); \
  1035. ENET_ATOMIC_CAS_expected_; \
  1036. })
  1037. #endif /* __clang_analyzer__ */
  1038. #define ENET_ATOMIC_INC(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_ACQ_REL)
  1039. #define ENET_ATOMIC_DEC(ptr) __atomic_fetch_sub((ptr), 1, __ATOMIC_ACQ_REL)
  1040. #define ENET_ATOMIC_INC_BY(ptr, delta) __atomic_fetch_add((ptr), (delta), __ATOMIC_ACQ_REL)
  1041. #define ENET_ATOMIC_DEC_BY(ptr, delta) __atomic_fetch_sub((ptr), (delta), __ATOMIC_ACQ_REL)
  1042. #else
  1043. #define ENET_ATOMIC_READ(variable) __sync_fetch_and_add(variable, 0)
  1044. #define ENET_ATOMIC_WRITE(variable, new_val) \
  1045. (void) __sync_val_compare_and_swap((variable), *(variable), (new_val))
  1046. #define ENET_ATOMIC_CAS(variable, old_value, new_val) \
  1047. __sync_val_compare_and_swap((variable), (old_value), (new_val))
  1048. #define ENET_ATOMIC_INC(variable) __sync_fetch_and_add((variable), 1)
  1049. #define ENET_ATOMIC_DEC(variable) __sync_fetch_and_sub((variable), 1)
  1050. #define ENET_ATOMIC_INC_BY(variable, delta) __sync_fetch_and_add((variable), (delta), 1)
  1051. #define ENET_ATOMIC_DEC_BY(variable, delta) __sync_fetch_and_sub((variable), (delta), 1)
  1052. #endif /* AT_HAVE_ATOMICS */
  1053. #undef AT_HAVE_ATOMICS
  1054. #endif /* defined(_MSC_VER) */
  1055. // =======================================================================//
  1056. // !
  1057. // ! Callbacks
  1058. // !
  1059. // =======================================================================//
  1060. static ENetCallbacks callbacks = { malloc, free, abort, enet_packet_create, enet_packet_destroy };
  1061. int enet_initialize_with_callbacks(ENetVersion version, const ENetCallbacks *inits) {
  1062. if (version < ENET_VERSION_CREATE(1, 3, 0)) {
  1063. return -1;
  1064. }
  1065. if (inits->malloc != NULL || inits->free != NULL) {
  1066. if (inits->malloc == NULL || inits->free == NULL) {
  1067. return -1;
  1068. }
  1069. callbacks.malloc = inits->malloc;
  1070. callbacks.free = inits->free;
  1071. }
  1072. if (inits->no_memory != NULL) {
  1073. callbacks.no_memory = inits->no_memory;
  1074. }
  1075. if (inits->packet_create != NULL || inits->packet_destroy != NULL) {
  1076. if (inits->packet_create == NULL || inits->packet_destroy == NULL) {
  1077. return -1;
  1078. }
  1079. callbacks.packet_create = inits->packet_create;
  1080. callbacks.packet_destroy = inits->packet_destroy;
  1081. }
  1082. return enet_initialize();
  1083. }
  1084. ENetVersion enet_linked_version(void) {
  1085. return ENET_VERSION;
  1086. }
  1087. void * enet_malloc(size_t size) {
  1088. void *memory = callbacks.malloc(size);
  1089. if (memory == NULL) {
  1090. callbacks.no_memory();
  1091. }
  1092. return memory;
  1093. }
  1094. void enet_free(void *memory) {
  1095. callbacks.free(memory);
  1096. }
  1097. // =======================================================================//
  1098. // !
  1099. // ! List
  1100. // !
  1101. // =======================================================================//
  1102. void enet_list_clear(ENetList *list) {
  1103. list->sentinel.next = &list->sentinel;
  1104. list->sentinel.previous = &list->sentinel;
  1105. }
  1106. ENetListIterator enet_list_insert(ENetListIterator position, void *data) {
  1107. ENetListIterator result = (ENetListIterator)data;
  1108. result->previous = position->previous;
  1109. result->next = position;
  1110. result->previous->next = result;
  1111. position->previous = result;
  1112. return result;
  1113. }
  1114. void *enet_list_remove(ENetListIterator position) {
  1115. position->previous->next = position->next;
  1116. position->next->previous = position->previous;
  1117. return position;
  1118. }
  1119. ENetListIterator enet_list_move(ENetListIterator position, void *dataFirst, void *dataLast) {
  1120. ENetListIterator first = (ENetListIterator)dataFirst;
  1121. ENetListIterator last = (ENetListIterator)dataLast;
  1122. first->previous->next = last->next;
  1123. last->next->previous = first->previous;
  1124. first->previous = position->previous;
  1125. last->next = position;
  1126. first->previous->next = first;
  1127. position->previous = last;
  1128. return first;
  1129. }
  1130. size_t enet_list_size(ENetList *list) {
  1131. size_t size = 0;
  1132. ENetListIterator position;
  1133. for (position = enet_list_begin(list); position != enet_list_end(list); position = enet_list_next(position)) {
  1134. ++size;
  1135. }
  1136. return size;
  1137. }
  1138. // =======================================================================//
  1139. // !
  1140. // ! Packet
  1141. // !
  1142. // =======================================================================//
  1143. /**
  1144. * Creates a packet that may be sent to a peer.
  1145. * @param data initial contents of the packet's data; the packet's data will remain uninitialized if data is NULL.
  1146. * @param dataLength size of the data allocated for this packet
  1147. * @param flags flags for this packet as described for the ENetPacket structure.
  1148. * @returns the packet on success, NULL on failure
  1149. */
  1150. ENetPacket *enet_packet_create(const void *data, size_t dataLength, enet_uint32 flags) {
  1151. ENetPacket *packet;
  1152. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1153. packet = (ENetPacket *)enet_malloc(sizeof (ENetPacket));
  1154. if (packet == NULL) {
  1155. return NULL;
  1156. }
  1157. packet->data = (enet_uint8 *)data;
  1158. }
  1159. else {
  1160. packet = (ENetPacket *)enet_malloc(sizeof (ENetPacket) + dataLength);
  1161. if (packet == NULL) {
  1162. return NULL;
  1163. }
  1164. packet->data = (enet_uint8 *)packet + sizeof(ENetPacket);
  1165. if (data != NULL) {
  1166. memcpy(packet->data, data, dataLength);
  1167. }
  1168. }
  1169. packet->referenceCount = 0;
  1170. packet->flags = flags;
  1171. packet->dataLength = dataLength;
  1172. packet->freeCallback = NULL;
  1173. packet->userData = NULL;
  1174. return packet;
  1175. }
  1176. ENetPacket *enet_packet_create_offset(const void *data, size_t dataLength, size_t dataOffset, enet_uint32 flags) {
  1177. ENetPacket *packet;
  1178. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1179. packet = (ENetPacket *)enet_malloc(sizeof (ENetPacket));
  1180. if (packet == NULL) {
  1181. return NULL;
  1182. }
  1183. packet->data = (enet_uint8 *)data;
  1184. }
  1185. else {
  1186. packet = (ENetPacket *)enet_malloc(sizeof (ENetPacket) + dataLength + dataOffset);
  1187. if (packet == NULL) {
  1188. return NULL;
  1189. }
  1190. packet->data = (enet_uint8 *)packet + sizeof(ENetPacket);
  1191. if (data != NULL) {
  1192. memcpy(packet->data + dataOffset, data, dataLength);
  1193. }
  1194. }
  1195. packet->referenceCount = 0;
  1196. packet->flags = flags;
  1197. packet->dataLength = dataLength + dataOffset;
  1198. packet->freeCallback = NULL;
  1199. packet->userData = NULL;
  1200. return packet;
  1201. }
  1202. ENetPacket *enet_packet_copy(ENetPacket *packet) {
  1203. return enet_packet_create(packet->data, packet->dataLength, packet->flags);
  1204. }
  1205. /**
  1206. * Destroys the packet and deallocates its data.
  1207. * @param packet packet to be destroyed
  1208. */
  1209. void enet_packet_destroy(ENetPacket *packet) {
  1210. if (packet == NULL) {
  1211. return;
  1212. }
  1213. if (packet->freeCallback != NULL) {
  1214. (*packet->freeCallback)((void *)packet);
  1215. }
  1216. enet_free(packet);
  1217. }
  1218. static int initializedCRC32 = 0;
  1219. static enet_uint32 crcTable[256];
  1220. static enet_uint32 reflect_crc(int val, int bits) {
  1221. int result = 0, bit;
  1222. for (bit = 0; bit < bits; bit++) {
  1223. if (val & 1) { result |= 1 << (bits - 1 - bit); }
  1224. val >>= 1;
  1225. }
  1226. return result;
  1227. }
  1228. static void initialize_crc32(void) {
  1229. int byte;
  1230. for (byte = 0; byte < 256; ++byte) {
  1231. enet_uint32 crc = reflect_crc(byte, 8) << 24;
  1232. int offset;
  1233. for (offset = 0; offset < 8; ++offset) {
  1234. if (crc & 0x80000000) {
  1235. crc = (crc << 1) ^ 0x04c11db7;
  1236. } else {
  1237. crc <<= 1;
  1238. }
  1239. }
  1240. crcTable[byte] = reflect_crc(crc, 32);
  1241. }
  1242. initializedCRC32 = 1;
  1243. }
  1244. enet_uint32 enet_crc32(const ENetBuffer *buffers, size_t bufferCount) {
  1245. enet_uint32 crc = 0xFFFFFFFF;
  1246. if (!initializedCRC32) { initialize_crc32(); }
  1247. while (bufferCount-- > 0) {
  1248. const enet_uint8 *data = (const enet_uint8 *)buffers->data;
  1249. const enet_uint8 *dataEnd = &data[buffers->dataLength];
  1250. while (data < dataEnd) {
  1251. crc = (crc >> 8) ^ crcTable[(crc & 0xFF) ^ *data++];
  1252. }
  1253. ++buffers;
  1254. }
  1255. return ENET_HOST_TO_NET_32(~crc);
  1256. }
  1257. // =======================================================================//
  1258. // !
  1259. // ! Protocol
  1260. // !
  1261. // =======================================================================//
  1262. static size_t commandSizes[ENET_PROTOCOL_COMMAND_COUNT] = {
  1263. 0,
  1264. sizeof(ENetProtocolAcknowledge),
  1265. sizeof(ENetProtocolConnect),
  1266. sizeof(ENetProtocolVerifyConnect),
  1267. sizeof(ENetProtocolDisconnect),
  1268. sizeof(ENetProtocolPing),
  1269. sizeof(ENetProtocolSendReliable),
  1270. sizeof(ENetProtocolSendUnreliable),
  1271. sizeof(ENetProtocolSendFragment),
  1272. sizeof(ENetProtocolSendUnsequenced),
  1273. sizeof(ENetProtocolBandwidthLimit),
  1274. sizeof(ENetProtocolThrottleConfigure),
  1275. sizeof(ENetProtocolSendFragment)
  1276. };
  1277. size_t enet_protocol_command_size(enet_uint8 commandNumber) {
  1278. return commandSizes[commandNumber & ENET_PROTOCOL_COMMAND_MASK];
  1279. }
  1280. static void enet_protocol_change_state(ENetHost *host, ENetPeer *peer, ENetPeerState state) {
  1281. ENET_UNUSED(host)
  1282. if (state == ENET_PEER_STATE_CONNECTED || state == ENET_PEER_STATE_DISCONNECT_LATER) {
  1283. enet_peer_on_connect(peer);
  1284. } else {
  1285. enet_peer_on_disconnect(peer);
  1286. }
  1287. peer->state = state;
  1288. }
  1289. static void enet_protocol_dispatch_state(ENetHost *host, ENetPeer *peer, ENetPeerState state) {
  1290. enet_protocol_change_state(host, peer, state);
  1291. if (!peer->needsDispatch) {
  1292. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1293. peer->needsDispatch = 1;
  1294. }
  1295. }
  1296. static int enet_protocol_dispatch_incoming_commands(ENetHost *host, ENetEvent *event) {
  1297. while (!enet_list_empty(&host->dispatchQueue)) {
  1298. ENetPeer *peer = (ENetPeer *) enet_list_remove(enet_list_begin(&host->dispatchQueue));
  1299. peer->needsDispatch = 0;
  1300. switch (peer->state) {
  1301. case ENET_PEER_STATE_CONNECTION_PENDING:
  1302. case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
  1303. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1304. event->type = ENET_EVENT_TYPE_CONNECT;
  1305. event->peer = peer;
  1306. event->data = peer->eventData;
  1307. return 1;
  1308. case ENET_PEER_STATE_ZOMBIE:
  1309. host->recalculateBandwidthLimits = 1;
  1310. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1311. event->peer = peer;
  1312. event->data = peer->eventData;
  1313. enet_peer_reset(peer);
  1314. return 1;
  1315. case ENET_PEER_STATE_CONNECTED:
  1316. if (enet_list_empty(&peer->dispatchedCommands)) {
  1317. continue;
  1318. }
  1319. event->packet = enet_peer_receive(peer, &event->channelID);
  1320. if (event->packet == NULL) {
  1321. continue;
  1322. }
  1323. event->type = ENET_EVENT_TYPE_RECEIVE;
  1324. event->peer = peer;
  1325. if (!enet_list_empty(&peer->dispatchedCommands)) {
  1326. peer->needsDispatch = 1;
  1327. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1328. }
  1329. return 1;
  1330. default:
  1331. break;
  1332. }
  1333. }
  1334. return 0;
  1335. } /* enet_protocol_dispatch_incoming_commands */
  1336. static void enet_protocol_notify_connect(ENetHost *host, ENetPeer *peer, ENetEvent *event) {
  1337. host->recalculateBandwidthLimits = 1;
  1338. if (event != NULL) {
  1339. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1340. peer->totalDataSent = 0;
  1341. peer->totalDataReceived = 0;
  1342. peer->totalPacketsSent = 0;
  1343. peer->totalPacketsLost = 0;
  1344. event->type = ENET_EVENT_TYPE_CONNECT;
  1345. event->peer = peer;
  1346. event->data = peer->eventData;
  1347. } else {
  1348. enet_protocol_dispatch_state(host, peer, peer->state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING);
  1349. }
  1350. }
  1351. static void enet_protocol_notify_disconnect(ENetHost *host, ENetPeer *peer, ENetEvent *event) {
  1352. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING) {
  1353. host->recalculateBandwidthLimits = 1;
  1354. }
  1355. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1356. enet_peer_reset(peer);
  1357. } else if (event != NULL) {
  1358. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1359. event->peer = peer;
  1360. event->data = 0;
  1361. enet_peer_reset(peer);
  1362. } else {
  1363. peer->eventData = 0;
  1364. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1365. }
  1366. }
  1367. static void enet_protocol_notify_disconnect_timeout (ENetHost * host, ENetPeer * peer, ENetEvent * event) {
  1368. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING) {
  1369. host->recalculateBandwidthLimits = 1;
  1370. }
  1371. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1372. enet_peer_reset (peer);
  1373. }
  1374. else if (event != NULL) {
  1375. event->type = ENET_EVENT_TYPE_DISCONNECT_TIMEOUT;
  1376. event->peer = peer;
  1377. event->data = 0;
  1378. enet_peer_reset(peer);
  1379. }
  1380. else {
  1381. peer->eventData = 0;
  1382. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1383. }
  1384. }
  1385. static void enet_protocol_remove_sent_unreliable_commands(ENetPeer *peer) {
  1386. ENetOutgoingCommand *outgoingCommand;
  1387. while (!enet_list_empty(&peer->sentUnreliableCommands)) {
  1388. outgoingCommand = (ENetOutgoingCommand *) enet_list_front(&peer->sentUnreliableCommands);
  1389. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1390. if (outgoingCommand->packet != NULL) {
  1391. --outgoingCommand->packet->referenceCount;
  1392. if (outgoingCommand->packet->referenceCount == 0) {
  1393. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1394. callbacks.packet_destroy(outgoingCommand->packet);
  1395. }
  1396. }
  1397. enet_free(outgoingCommand);
  1398. }
  1399. }
  1400. static ENetProtocolCommand enet_protocol_remove_sent_reliable_command(ENetPeer *peer, enet_uint16 reliableSequenceNumber, enet_uint8 channelID) {
  1401. ENetOutgoingCommand *outgoingCommand = NULL;
  1402. ENetListIterator currentCommand;
  1403. ENetProtocolCommand commandNumber;
  1404. int wasSent = 1;
  1405. for (currentCommand = enet_list_begin(&peer->sentReliableCommands);
  1406. currentCommand != enet_list_end(&peer->sentReliableCommands);
  1407. currentCommand = enet_list_next(currentCommand)
  1408. ) {
  1409. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  1410. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID) {
  1411. break;
  1412. }
  1413. }
  1414. if (currentCommand == enet_list_end(&peer->sentReliableCommands)) {
  1415. for (currentCommand = enet_list_begin(&peer->outgoingReliableCommands);
  1416. currentCommand != enet_list_end(&peer->outgoingReliableCommands);
  1417. currentCommand = enet_list_next(currentCommand)
  1418. ) {
  1419. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  1420. if (outgoingCommand->sendAttempts < 1) { return ENET_PROTOCOL_COMMAND_NONE; }
  1421. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID) {
  1422. break;
  1423. }
  1424. }
  1425. if (currentCommand == enet_list_end(&peer->outgoingReliableCommands)) {
  1426. return ENET_PROTOCOL_COMMAND_NONE;
  1427. }
  1428. wasSent = 0;
  1429. }
  1430. if (outgoingCommand == NULL) {
  1431. return ENET_PROTOCOL_COMMAND_NONE;
  1432. }
  1433. if (channelID < peer->channelCount) {
  1434. ENetChannel *channel = &peer->channels[channelID];
  1435. enet_uint16 reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1436. if (channel->reliableWindows[reliableWindow] > 0) {
  1437. --channel->reliableWindows[reliableWindow];
  1438. if (!channel->reliableWindows[reliableWindow]) {
  1439. channel->usedReliableWindows &= ~(1 << reliableWindow);
  1440. }
  1441. }
  1442. }
  1443. commandNumber = (ENetProtocolCommand) (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK);
  1444. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1445. if (outgoingCommand->packet != NULL) {
  1446. if (wasSent) {
  1447. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  1448. }
  1449. --outgoingCommand->packet->referenceCount;
  1450. if (outgoingCommand->packet->referenceCount == 0) {
  1451. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1452. callbacks.packet_destroy(outgoingCommand->packet);
  1453. }
  1454. }
  1455. enet_free(outgoingCommand);
  1456. if (enet_list_empty(&peer->sentReliableCommands)) {
  1457. return commandNumber;
  1458. }
  1459. outgoingCommand = (ENetOutgoingCommand *) enet_list_front(&peer->sentReliableCommands);
  1460. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  1461. return commandNumber;
  1462. } /* enet_protocol_remove_sent_reliable_command */
  1463. static ENetPeer * enet_protocol_handle_connect(ENetHost *host, ENetProtocolHeader *header, ENetProtocol *command) {
  1464. ENET_UNUSED(header)
  1465. enet_uint8 incomingSessionID, outgoingSessionID;
  1466. enet_uint32 mtu, windowSize;
  1467. ENetChannel *channel;
  1468. size_t channelCount, duplicatePeers = 0;
  1469. ENetPeer *currentPeer, *peer = NULL;
  1470. ENetProtocol verifyCommand;
  1471. channelCount = ENET_NET_TO_HOST_32(command->connect.channelCount);
  1472. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) {
  1473. return NULL;
  1474. }
  1475. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  1476. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
  1477. if (peer == NULL) {
  1478. peer = currentPeer;
  1479. }
  1480. } else if (currentPeer->state != ENET_PEER_STATE_CONNECTING && in6_equal(currentPeer->address.host, host->receivedAddress.host)) {
  1481. if (currentPeer->address.port == host->receivedAddress.port && currentPeer->connectID == command->connect.connectID) {
  1482. return NULL;
  1483. }
  1484. ++duplicatePeers;
  1485. }
  1486. }
  1487. if (peer == NULL || duplicatePeers >= host->duplicatePeers) {
  1488. return NULL;
  1489. }
  1490. if (channelCount > host->channelLimit) {
  1491. channelCount = host->channelLimit;
  1492. }
  1493. peer->channels = (ENetChannel *) enet_malloc(channelCount * sizeof(ENetChannel));
  1494. if (peer->channels == NULL) {
  1495. return NULL;
  1496. }
  1497. peer->channelCount = channelCount;
  1498. peer->state = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT;
  1499. peer->connectID = command->connect.connectID;
  1500. peer->address = host->receivedAddress;
  1501. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->connect.outgoingPeerID);
  1502. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->connect.incomingBandwidth);
  1503. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->connect.outgoingBandwidth);
  1504. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->connect.packetThrottleInterval);
  1505. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleAcceleration);
  1506. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleDeceleration);
  1507. peer->eventData = ENET_NET_TO_HOST_32(command->connect.data);
  1508. incomingSessionID = command->connect.incomingSessionID == 0xFF ? peer->outgoingSessionID : command->connect.incomingSessionID;
  1509. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1510. if (incomingSessionID == peer->outgoingSessionID) {
  1511. incomingSessionID = (incomingSessionID + 1)
  1512. & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1513. }
  1514. peer->outgoingSessionID = incomingSessionID;
  1515. outgoingSessionID = command->connect.outgoingSessionID == 0xFF ? peer->incomingSessionID : command->connect.outgoingSessionID;
  1516. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1517. if (outgoingSessionID == peer->incomingSessionID) {
  1518. outgoingSessionID = (outgoingSessionID + 1)
  1519. & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1520. }
  1521. peer->incomingSessionID = outgoingSessionID;
  1522. for (channel = peer->channels; channel < &peer->channels[channelCount]; ++channel) {
  1523. channel->outgoingReliableSequenceNumber = 0;
  1524. channel->outgoingUnreliableSequenceNumber = 0;
  1525. channel->incomingReliableSequenceNumber = 0;
  1526. channel->incomingUnreliableSequenceNumber = 0;
  1527. enet_list_clear(&channel->incomingReliableCommands);
  1528. enet_list_clear(&channel->incomingUnreliableCommands);
  1529. channel->usedReliableWindows = 0;
  1530. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  1531. }
  1532. mtu = ENET_NET_TO_HOST_32(command->connect.mtu);
  1533. if (mtu < ENET_PROTOCOL_MINIMUM_MTU) {
  1534. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1535. } else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) {
  1536. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1537. }
  1538. peer->mtu = mtu;
  1539. if (host->outgoingBandwidth == 0 && peer->incomingBandwidth == 0) {
  1540. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1541. } else if (host->outgoingBandwidth == 0 || peer->incomingBandwidth == 0) {
  1542. peer->windowSize = (ENET_MAX(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1543. } else {
  1544. peer->windowSize = (ENET_MIN(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1545. }
  1546. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) {
  1547. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1548. } else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) {
  1549. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1550. }
  1551. if (host->incomingBandwidth == 0) {
  1552. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1553. } else {
  1554. windowSize = (host->incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1555. }
  1556. if (windowSize > ENET_NET_TO_HOST_32(command->connect.windowSize)) {
  1557. windowSize = ENET_NET_TO_HOST_32(command->connect.windowSize);
  1558. }
  1559. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) {
  1560. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1561. } else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) {
  1562. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1563. }
  1564. verifyCommand.header.command = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  1565. verifyCommand.header.channelID = 0xFF;
  1566. verifyCommand.verifyConnect.outgoingPeerID = ENET_HOST_TO_NET_16(peer->incomingPeerID);
  1567. verifyCommand.verifyConnect.incomingSessionID = incomingSessionID;
  1568. verifyCommand.verifyConnect.outgoingSessionID = outgoingSessionID;
  1569. verifyCommand.verifyConnect.mtu = ENET_HOST_TO_NET_32(peer->mtu);
  1570. verifyCommand.verifyConnect.windowSize = ENET_HOST_TO_NET_32(windowSize);
  1571. verifyCommand.verifyConnect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  1572. verifyCommand.verifyConnect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  1573. verifyCommand.verifyConnect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  1574. verifyCommand.verifyConnect.packetThrottleInterval = ENET_HOST_TO_NET_32(peer->packetThrottleInterval);
  1575. verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(peer->packetThrottleAcceleration);
  1576. verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(peer->packetThrottleDeceleration);
  1577. verifyCommand.verifyConnect.connectID = peer->connectID;
  1578. enet_peer_queue_outgoing_command(peer, &verifyCommand, NULL, 0, 0);
  1579. return peer;
  1580. } /* enet_protocol_handle_connect */
  1581. static int enet_protocol_handle_send_reliable(ENetHost *host, ENetPeer *peer, const ENetProtocol *command, enet_uint8 **currentData) {
  1582. size_t dataLength;
  1583. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1584. return -1;
  1585. }
  1586. dataLength = ENET_NET_TO_HOST_16(command->sendReliable.dataLength);
  1587. *currentData += dataLength;
  1588. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength]) {
  1589. return -1;
  1590. }
  1591. if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8 *) command + sizeof(ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) == NULL) {
  1592. return -1;
  1593. }
  1594. return 0;
  1595. }
  1596. static int enet_protocol_handle_send_unsequenced(ENetHost *host, ENetPeer *peer, const ENetProtocol *command, enet_uint8 **currentData) {
  1597. enet_uint32 unsequencedGroup, index;
  1598. size_t dataLength;
  1599. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1600. return -1;
  1601. }
  1602. dataLength = ENET_NET_TO_HOST_16(command->sendUnsequenced.dataLength);
  1603. *currentData += dataLength;
  1604. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength]) {
  1605. return -1;
  1606. }
  1607. unsequencedGroup = ENET_NET_TO_HOST_16(command->sendUnsequenced.unsequencedGroup);
  1608. index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE;
  1609. if (unsequencedGroup < peer->incomingUnsequencedGroup) {
  1610. unsequencedGroup += 0x10000;
  1611. }
  1612. if (unsequencedGroup >= (enet_uint32) peer->incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE) {
  1613. return 0;
  1614. }
  1615. unsequencedGroup &= 0xFFFF;
  1616. if (unsequencedGroup - index != peer->incomingUnsequencedGroup) {
  1617. peer->incomingUnsequencedGroup = unsequencedGroup - index;
  1618. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  1619. } else if (peer->unsequencedWindow[index / 32] & (1 << (index % 32))) {
  1620. return 0;
  1621. }
  1622. if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8 *) command + sizeof(ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED,0) == NULL) {
  1623. return -1;
  1624. }
  1625. peer->unsequencedWindow[index / 32] |= 1 << (index % 32);
  1626. return 0;
  1627. } /* enet_protocol_handle_send_unsequenced */
  1628. static int enet_protocol_handle_send_unreliable(ENetHost *host, ENetPeer *peer, const ENetProtocol *command,
  1629. enet_uint8 **currentData) {
  1630. size_t dataLength;
  1631. if (command->header.channelID >= peer->channelCount ||
  1632. (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1633. {
  1634. return -1;
  1635. }
  1636. dataLength = ENET_NET_TO_HOST_16(command->sendUnreliable.dataLength);
  1637. *currentData += dataLength;
  1638. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength]) {
  1639. return -1;
  1640. }
  1641. if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8 *) command + sizeof(ENetProtocolSendUnreliable), dataLength, 0, 0) == NULL) {
  1642. return -1;
  1643. }
  1644. return 0;
  1645. }
  1646. static int enet_protocol_handle_send_fragment(ENetHost *host, ENetPeer *peer, const ENetProtocol *command, enet_uint8 **currentData) {
  1647. enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength;
  1648. ENetChannel *channel;
  1649. enet_uint16 startWindow, currentWindow;
  1650. ENetListIterator currentCommand;
  1651. ENetIncomingCommand *startCommand = NULL;
  1652. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1653. return -1;
  1654. }
  1655. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1656. *currentData += fragmentLength;
  1657. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength]) {
  1658. return -1;
  1659. }
  1660. channel = &peer->channels[command->header.channelID];
  1661. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1662. startWindow = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1663. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1664. if (startSequenceNumber < channel->incomingReliableSequenceNumber) {
  1665. startWindow += ENET_PEER_RELIABLE_WINDOWS;
  1666. }
  1667. if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) {
  1668. return 0;
  1669. }
  1670. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1671. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1672. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1673. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1674. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT ||
  1675. fragmentNumber >= fragmentCount ||
  1676. totalLength > host->maximumPacketSize ||
  1677. fragmentOffset >= totalLength ||
  1678. fragmentLength > totalLength - fragmentOffset
  1679. ) {
  1680. return -1;
  1681. }
  1682. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands));
  1683. currentCommand != enet_list_end(&channel->incomingReliableCommands);
  1684. currentCommand = enet_list_previous(currentCommand)
  1685. ) {
  1686. ENetIncomingCommand *incomingCommand = (ENetIncomingCommand *) currentCommand;
  1687. if (startSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1688. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  1689. continue;
  1690. }
  1691. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1692. break;
  1693. }
  1694. if (incomingCommand->reliableSequenceNumber <= startSequenceNumber) {
  1695. if (incomingCommand->reliableSequenceNumber < startSequenceNumber) {
  1696. break;
  1697. }
  1698. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) !=
  1699. ENET_PROTOCOL_COMMAND_SEND_FRAGMENT ||
  1700. totalLength != incomingCommand->packet->dataLength ||
  1701. fragmentCount != incomingCommand->fragmentCount
  1702. ) {
  1703. return -1;
  1704. }
  1705. startCommand = incomingCommand;
  1706. break;
  1707. }
  1708. }
  1709. if (startCommand == NULL) {
  1710. ENetProtocol hostCommand = *command;
  1711. hostCommand.header.reliableSequenceNumber = startSequenceNumber;
  1712. startCommand = enet_peer_queue_incoming_command(peer, &hostCommand, NULL, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount);
  1713. if (startCommand == NULL) {
  1714. return -1;
  1715. }
  1716. }
  1717. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1718. --startCommand->fragmentsRemaining;
  1719. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1720. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength) {
  1721. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1722. }
  1723. memcpy(startCommand->packet->data + fragmentOffset, (enet_uint8 *) command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1724. if (startCommand->fragmentsRemaining <= 0) {
  1725. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  1726. }
  1727. }
  1728. return 0;
  1729. } /* enet_protocol_handle_send_fragment */
  1730. static int enet_protocol_handle_send_unreliable_fragment(ENetHost *host, ENetPeer *peer, const ENetProtocol *command, enet_uint8 **currentData) {
  1731. enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength;
  1732. enet_uint16 reliableWindow, currentWindow;
  1733. ENetChannel *channel;
  1734. ENetListIterator currentCommand;
  1735. ENetIncomingCommand *startCommand = NULL;
  1736. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1737. return -1;
  1738. }
  1739. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1740. *currentData += fragmentLength;
  1741. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength]) {
  1742. return -1;
  1743. }
  1744. channel = &peer->channels[command->header.channelID];
  1745. reliableSequenceNumber = command->header.reliableSequenceNumber;
  1746. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1747. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1748. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1749. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  1750. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  1751. }
  1752. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) {
  1753. return 0;
  1754. }
  1755. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && startSequenceNumber <= channel->incomingUnreliableSequenceNumber) {
  1756. return 0;
  1757. }
  1758. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1759. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1760. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1761. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1762. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT ||
  1763. fragmentNumber >= fragmentCount ||
  1764. totalLength > host->maximumPacketSize ||
  1765. fragmentOffset >= totalLength ||
  1766. fragmentLength > totalLength - fragmentOffset
  1767. ) {
  1768. return -1;
  1769. }
  1770. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands));
  1771. currentCommand != enet_list_end(&channel->incomingUnreliableCommands);
  1772. currentCommand = enet_list_previous(currentCommand)
  1773. ) {
  1774. ENetIncomingCommand *incomingCommand = (ENetIncomingCommand *) currentCommand;
  1775. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1776. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  1777. continue;
  1778. }
  1779. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1780. break;
  1781. }
  1782. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber) {
  1783. break;
  1784. }
  1785. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber) {
  1786. continue;
  1787. }
  1788. if (incomingCommand->unreliableSequenceNumber <= startSequenceNumber) {
  1789. if (incomingCommand->unreliableSequenceNumber < startSequenceNumber) {
  1790. break;
  1791. }
  1792. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) !=
  1793. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT ||
  1794. totalLength != incomingCommand->packet->dataLength ||
  1795. fragmentCount != incomingCommand->fragmentCount
  1796. ) {
  1797. return -1;
  1798. }
  1799. startCommand = incomingCommand;
  1800. break;
  1801. }
  1802. }
  1803. if (startCommand == NULL) {
  1804. startCommand = enet_peer_queue_incoming_command(peer, command, NULL, totalLength,
  1805. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, fragmentCount);
  1806. if (startCommand == NULL) {
  1807. return -1;
  1808. }
  1809. }
  1810. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1811. --startCommand->fragmentsRemaining;
  1812. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1813. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength) {
  1814. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1815. }
  1816. memcpy(startCommand->packet->data + fragmentOffset, (enet_uint8 *) command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1817. if (startCommand->fragmentsRemaining <= 0) {
  1818. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  1819. }
  1820. }
  1821. return 0;
  1822. } /* enet_protocol_handle_send_unreliable_fragment */
  1823. static int enet_protocol_handle_ping(ENetHost *host, ENetPeer *peer, const ENetProtocol *command) {
  1824. ENET_UNUSED(host)
  1825. ENET_UNUSED(command)
  1826. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1827. return -1;
  1828. }
  1829. return 0;
  1830. }
  1831. static int enet_protocol_handle_bandwidth_limit(ENetHost *host, ENetPeer *peer, const ENetProtocol *command) {
  1832. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1833. return -1;
  1834. }
  1835. if (peer->incomingBandwidth != 0) {
  1836. --host->bandwidthLimitedPeers;
  1837. }
  1838. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.incomingBandwidth);
  1839. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.outgoingBandwidth);
  1840. if (peer->incomingBandwidth != 0) {
  1841. ++host->bandwidthLimitedPeers;
  1842. }
  1843. if (peer->incomingBandwidth == 0 && host->outgoingBandwidth == 0) {
  1844. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1845. } else if (peer->incomingBandwidth == 0 || host->outgoingBandwidth == 0) {
  1846. peer->windowSize = (ENET_MAX(peer->incomingBandwidth, host->outgoingBandwidth)
  1847. / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1848. } else {
  1849. peer->windowSize = (ENET_MIN(peer->incomingBandwidth, host->outgoingBandwidth)
  1850. / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1851. }
  1852. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) {
  1853. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1854. } else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) {
  1855. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1856. }
  1857. return 0;
  1858. } /* enet_protocol_handle_bandwidth_limit */
  1859. static int enet_protocol_handle_throttle_configure(ENetHost *host, ENetPeer *peer, const ENetProtocol *command) {
  1860. ENET_UNUSED(host)
  1861. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1862. return -1;
  1863. }
  1864. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleInterval);
  1865. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleAcceleration);
  1866. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleDeceleration);
  1867. return 0;
  1868. }
  1869. static int enet_protocol_handle_disconnect(ENetHost *host, ENetPeer *peer, const ENetProtocol *command) {
  1870. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE ||
  1871. peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT
  1872. ) {
  1873. return 0;
  1874. }
  1875. enet_peer_reset_queues(peer);
  1876. if (peer->state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_CONNECTING) {
  1877. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1878. }
  1879. else if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1880. if (peer->state == ENET_PEER_STATE_CONNECTION_PENDING) { host->recalculateBandwidthLimits = 1; }
  1881. enet_peer_reset(peer);
  1882. }
  1883. else if (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  1884. enet_protocol_change_state(host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT);
  1885. }
  1886. else {
  1887. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1888. }
  1889. if (peer->state != ENET_PEER_STATE_DISCONNECTED) {
  1890. peer->eventData = ENET_NET_TO_HOST_32(command->disconnect.data);
  1891. }
  1892. return 0;
  1893. }
  1894. static int enet_protocol_handle_acknowledge(ENetHost *host, ENetEvent *event, ENetPeer *peer, const ENetProtocol *command) {
  1895. enet_uint32 roundTripTime, receivedSentTime, receivedReliableSequenceNumber;
  1896. ENetProtocolCommand commandNumber;
  1897. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE) {
  1898. return 0;
  1899. }
  1900. receivedSentTime = ENET_NET_TO_HOST_16(command->acknowledge.receivedSentTime);
  1901. receivedSentTime |= host->serviceTime & 0xFFFF0000;
  1902. if ((receivedSentTime & 0x8000) > (host->serviceTime & 0x8000)) {
  1903. receivedSentTime -= 0x10000;
  1904. }
  1905. if (ENET_TIME_LESS(host->serviceTime, receivedSentTime)) {
  1906. return 0;
  1907. }
  1908. peer->lastReceiveTime = host->serviceTime;
  1909. peer->earliestTimeout = 0;
  1910. roundTripTime = ENET_TIME_DIFFERENCE(host->serviceTime, receivedSentTime);
  1911. enet_peer_throttle(peer, roundTripTime);
  1912. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1913. if (roundTripTime >= peer->roundTripTime) {
  1914. peer->roundTripTime += (roundTripTime - peer->roundTripTime) / 8;
  1915. peer->roundTripTimeVariance += (roundTripTime - peer->roundTripTime) / 4;
  1916. } else {
  1917. peer->roundTripTime -= (peer->roundTripTime - roundTripTime) / 8;
  1918. peer->roundTripTimeVariance += (peer->roundTripTime - roundTripTime) / 4;
  1919. }
  1920. if (peer->roundTripTime < peer->lowestRoundTripTime) {
  1921. peer->lowestRoundTripTime = peer->roundTripTime;
  1922. }
  1923. if (peer->roundTripTimeVariance > peer->highestRoundTripTimeVariance) {
  1924. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1925. }
  1926. if (peer->packetThrottleEpoch == 0 ||
  1927. ENET_TIME_DIFFERENCE(host->serviceTime, peer->packetThrottleEpoch) >= peer->packetThrottleInterval
  1928. ) {
  1929. peer->lastRoundTripTime = peer->lowestRoundTripTime;
  1930. peer->lastRoundTripTimeVariance = peer->highestRoundTripTimeVariance;
  1931. peer->lowestRoundTripTime = peer->roundTripTime;
  1932. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1933. peer->packetThrottleEpoch = host->serviceTime;
  1934. }
  1935. receivedReliableSequenceNumber = ENET_NET_TO_HOST_16(command->acknowledge.receivedReliableSequenceNumber);
  1936. commandNumber = enet_protocol_remove_sent_reliable_command(peer, receivedReliableSequenceNumber, command->header.channelID);
  1937. switch (peer->state) {
  1938. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1939. if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT) {
  1940. return -1;
  1941. }
  1942. enet_protocol_notify_connect(host, peer, event);
  1943. break;
  1944. case ENET_PEER_STATE_DISCONNECTING:
  1945. if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT) {
  1946. return -1;
  1947. }
  1948. enet_protocol_notify_disconnect(host, peer, event);
  1949. break;
  1950. case ENET_PEER_STATE_DISCONNECT_LATER:
  1951. if (enet_list_empty(&peer->outgoingReliableCommands) &&
  1952. enet_list_empty(&peer->outgoingUnreliableCommands) &&
  1953. enet_list_empty(&peer->sentReliableCommands))
  1954. {
  1955. enet_peer_disconnect(peer, peer->eventData);
  1956. }
  1957. break;
  1958. default:
  1959. break;
  1960. }
  1961. return 0;
  1962. } /* enet_protocol_handle_acknowledge */
  1963. static int enet_protocol_handle_verify_connect(ENetHost *host, ENetEvent *event, ENetPeer *peer, const ENetProtocol *command) {
  1964. enet_uint32 mtu, windowSize;
  1965. size_t channelCount;
  1966. if (peer->state != ENET_PEER_STATE_CONNECTING) {
  1967. return 0;
  1968. }
  1969. channelCount = ENET_NET_TO_HOST_32(command->verifyConnect.channelCount);
  1970. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT ||
  1971. ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleInterval) != peer->packetThrottleInterval ||
  1972. ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleAcceleration) != peer->packetThrottleAcceleration ||
  1973. ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleDeceleration) != peer->packetThrottleDeceleration ||
  1974. command->verifyConnect.connectID != peer->connectID
  1975. ) {
  1976. peer->eventData = 0;
  1977. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1978. return -1;
  1979. }
  1980. enet_protocol_remove_sent_reliable_command(peer, 1, 0xFF);
  1981. if (channelCount < peer->channelCount) {
  1982. peer->channelCount = channelCount;
  1983. }
  1984. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->verifyConnect.outgoingPeerID);
  1985. peer->incomingSessionID = command->verifyConnect.incomingSessionID;
  1986. peer->outgoingSessionID = command->verifyConnect.outgoingSessionID;
  1987. mtu = ENET_NET_TO_HOST_32(command->verifyConnect.mtu);
  1988. if (mtu < ENET_PROTOCOL_MINIMUM_MTU) {
  1989. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1990. } else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) {
  1991. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1992. }
  1993. if (mtu < peer->mtu) {
  1994. peer->mtu = mtu;
  1995. }
  1996. windowSize = ENET_NET_TO_HOST_32(command->verifyConnect.windowSize);
  1997. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) {
  1998. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1999. }
  2000. if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) {
  2001. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2002. }
  2003. if (windowSize < peer->windowSize) {
  2004. peer->windowSize = windowSize;
  2005. }
  2006. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.incomingBandwidth);
  2007. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.outgoingBandwidth);
  2008. enet_protocol_notify_connect(host, peer, event);
  2009. return 0;
  2010. } /* enet_protocol_handle_verify_connect */
  2011. static int enet_protocol_handle_incoming_commands(ENetHost *host, ENetEvent *event) {
  2012. ENetProtocolHeader *header;
  2013. ENetProtocol *command;
  2014. ENetPeer *peer;
  2015. enet_uint8 *currentData;
  2016. size_t headerSize;
  2017. enet_uint16 peerID, flags;
  2018. enet_uint8 sessionID;
  2019. if (host->receivedDataLength < (size_t) &((ENetProtocolHeader *) 0)->sentTime) {
  2020. return 0;
  2021. }
  2022. header = (ENetProtocolHeader *) host->receivedData;
  2023. peerID = ENET_NET_TO_HOST_16(header->peerID);
  2024. sessionID = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  2025. flags = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK;
  2026. peerID &= ~(ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK);
  2027. headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof(ENetProtocolHeader) : (size_t) &((ENetProtocolHeader *) 0)->sentTime);
  2028. if (host->checksum != NULL) {
  2029. headerSize += sizeof(enet_uint32);
  2030. }
  2031. if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  2032. peer = NULL;
  2033. } else if (peerID >= host->peerCount) {
  2034. return 0;
  2035. } else {
  2036. peer = &host->peers[peerID];
  2037. if (peer->state == ENET_PEER_STATE_DISCONNECTED ||
  2038. peer->state == ENET_PEER_STATE_ZOMBIE ||
  2039. ((!in6_equal(host->receivedAddress.host , peer->address.host) ||
  2040. host->receivedAddress.port != peer->address.port) &&
  2041. 1 /* no broadcast in ipv6 !in6_equal(peer->address.host , ENET_HOST_BROADCAST)*/) ||
  2042. (peer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID &&
  2043. sessionID != peer->incomingSessionID)
  2044. ) {
  2045. return 0;
  2046. }
  2047. }
  2048. if (flags & ENET_PROTOCOL_HEADER_FLAG_COMPRESSED) {
  2049. size_t originalSize;
  2050. if (host->compressor.context == NULL || host->compressor.decompress == NULL) {
  2051. return 0;
  2052. }
  2053. originalSize = host->compressor.decompress(host->compressor.context,
  2054. host->receivedData + headerSize,
  2055. host->receivedDataLength - headerSize,
  2056. host->packetData[1] + headerSize,
  2057. sizeof(host->packetData[1]) - headerSize
  2058. );
  2059. if (originalSize <= 0 || originalSize > sizeof(host->packetData[1]) - headerSize) {
  2060. return 0;
  2061. }
  2062. memcpy(host->packetData[1], header, headerSize);
  2063. host->receivedData = host->packetData[1];
  2064. host->receivedDataLength = headerSize + originalSize;
  2065. }
  2066. if (host->checksum != NULL) {
  2067. enet_uint32 *checksum = (enet_uint32 *) &host->receivedData[headerSize - sizeof(enet_uint32)];
  2068. enet_uint32 desiredChecksum = *checksum;
  2069. ENetBuffer buffer;
  2070. *checksum = peer != NULL ? peer->connectID : 0;
  2071. buffer.data = host->receivedData;
  2072. buffer.dataLength = host->receivedDataLength;
  2073. if (host->checksum(&buffer, 1) != desiredChecksum) {
  2074. return 0;
  2075. }
  2076. }
  2077. if (peer != NULL) {
  2078. peer->address.host = host->receivedAddress.host;
  2079. peer->address.port = host->receivedAddress.port;
  2080. peer->incomingDataTotal += host->receivedDataLength;
  2081. peer->totalDataReceived += host->receivedDataLength;
  2082. }
  2083. currentData = host->receivedData + headerSize;
  2084. while (currentData < &host->receivedData[host->receivedDataLength]) {
  2085. enet_uint8 commandNumber;
  2086. size_t commandSize;
  2087. command = (ENetProtocol *) currentData;
  2088. if (currentData + sizeof(ENetProtocolCommandHeader) > &host->receivedData[host->receivedDataLength]) {
  2089. break;
  2090. }
  2091. commandNumber = command->header.command & ENET_PROTOCOL_COMMAND_MASK;
  2092. if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT) {
  2093. break;
  2094. }
  2095. commandSize = commandSizes[commandNumber];
  2096. if (commandSize == 0 || currentData + commandSize > &host->receivedData[host->receivedDataLength]) {
  2097. break;
  2098. }
  2099. currentData += commandSize;
  2100. if (peer == NULL && (commandNumber != ENET_PROTOCOL_COMMAND_CONNECT || currentData < &host->receivedData[host->receivedDataLength])) {
  2101. break;
  2102. }
  2103. command->header.reliableSequenceNumber = ENET_NET_TO_HOST_16(command->header.reliableSequenceNumber);
  2104. switch (commandNumber) {
  2105. case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE:
  2106. if (enet_protocol_handle_acknowledge(host, event, peer, command)) {
  2107. goto commandError;
  2108. }
  2109. break;
  2110. case ENET_PROTOCOL_COMMAND_CONNECT:
  2111. if (peer != NULL) {
  2112. goto commandError;
  2113. }
  2114. peer = enet_protocol_handle_connect(host, header, command);
  2115. if (peer == NULL) {
  2116. goto commandError;
  2117. }
  2118. break;
  2119. case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT:
  2120. if (enet_protocol_handle_verify_connect(host, event, peer, command)) {
  2121. goto commandError;
  2122. }
  2123. break;
  2124. case ENET_PROTOCOL_COMMAND_DISCONNECT:
  2125. if (enet_protocol_handle_disconnect(host, peer, command)) {
  2126. goto commandError;
  2127. }
  2128. break;
  2129. case ENET_PROTOCOL_COMMAND_PING:
  2130. if (enet_protocol_handle_ping(host, peer, command)) {
  2131. goto commandError;
  2132. }
  2133. break;
  2134. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2135. if (enet_protocol_handle_send_reliable(host, peer, command, &currentData)) {
  2136. goto commandError;
  2137. }
  2138. break;
  2139. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2140. if (enet_protocol_handle_send_unreliable(host, peer, command, &currentData)) {
  2141. goto commandError;
  2142. }
  2143. break;
  2144. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2145. if (enet_protocol_handle_send_unsequenced(host, peer, command, &currentData)) {
  2146. goto commandError;
  2147. }
  2148. break;
  2149. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2150. if (enet_protocol_handle_send_fragment(host, peer, command, &currentData)) {
  2151. goto commandError;
  2152. }
  2153. break;
  2154. case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT:
  2155. if (enet_protocol_handle_bandwidth_limit(host, peer, command)) {
  2156. goto commandError;
  2157. }
  2158. break;
  2159. case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE:
  2160. if (enet_protocol_handle_throttle_configure(host, peer, command)) {
  2161. goto commandError;
  2162. }
  2163. break;
  2164. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  2165. if (enet_protocol_handle_send_unreliable_fragment(host, peer, command, &currentData)) {
  2166. goto commandError;
  2167. }
  2168. break;
  2169. default:
  2170. goto commandError;
  2171. }
  2172. if (peer != NULL && (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) {
  2173. enet_uint16 sentTime;
  2174. if (!(flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME)) {
  2175. break;
  2176. }
  2177. sentTime = ENET_NET_TO_HOST_16(header->sentTime);
  2178. switch (peer->state) {
  2179. case ENET_PEER_STATE_DISCONNECTING:
  2180. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  2181. case ENET_PEER_STATE_DISCONNECTED:
  2182. case ENET_PEER_STATE_ZOMBIE:
  2183. break;
  2184. case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
  2185. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT) {
  2186. enet_peer_queue_acknowledgement(peer, command, sentTime);
  2187. }
  2188. break;
  2189. default:
  2190. enet_peer_queue_acknowledgement(peer, command, sentTime);
  2191. break;
  2192. }
  2193. }
  2194. }
  2195. commandError:
  2196. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE) {
  2197. return 1;
  2198. }
  2199. return 0;
  2200. } /* enet_protocol_handle_incoming_commands */
  2201. static int enet_protocol_receive_incoming_commands(ENetHost *host, ENetEvent *event) {
  2202. int packets;
  2203. for (packets = 0; packets < 256; ++packets) {
  2204. int receivedLength;
  2205. ENetBuffer buffer;
  2206. buffer.data = host->packetData[0];
  2207. // buffer.dataLength = sizeof (host->packetData[0]);
  2208. buffer.dataLength = host->mtu;
  2209. receivedLength = enet_socket_receive(host->socket, &host->receivedAddress, &buffer, 1);
  2210. if (receivedLength == -2)
  2211. continue;
  2212. if (receivedLength < 0) {
  2213. return -1;
  2214. }
  2215. if (receivedLength == 0) {
  2216. return 0;
  2217. }
  2218. host->receivedData = host->packetData[0];
  2219. host->receivedDataLength = receivedLength;
  2220. host->totalReceivedData += receivedLength;
  2221. host->totalReceivedPackets++;
  2222. if (host->intercept != NULL) {
  2223. switch (host->intercept(host, (void *)event)) {
  2224. case 1:
  2225. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE) {
  2226. return 1;
  2227. }
  2228. continue;
  2229. case -1:
  2230. return -1;
  2231. default:
  2232. break;
  2233. }
  2234. }
  2235. switch (enet_protocol_handle_incoming_commands(host, event)) {
  2236. case 1:
  2237. return 1;
  2238. case -1:
  2239. return -1;
  2240. default:
  2241. break;
  2242. }
  2243. }
  2244. return -1;
  2245. } /* enet_protocol_receive_incoming_commands */
  2246. static void enet_protocol_send_acknowledgements(ENetHost *host, ENetPeer *peer) {
  2247. ENetProtocol *command = &host->commands[host->commandCount];
  2248. ENetBuffer *buffer = &host->buffers[host->bufferCount];
  2249. ENetAcknowledgement *acknowledgement;
  2250. ENetListIterator currentAcknowledgement;
  2251. enet_uint16 reliableSequenceNumber;
  2252. currentAcknowledgement = enet_list_begin(&peer->acknowledgements);
  2253. while (currentAcknowledgement != enet_list_end(&peer->acknowledgements)) {
  2254. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] ||
  2255. buffer >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] ||
  2256. peer->mtu - host->packetSize < sizeof(ENetProtocolAcknowledge)
  2257. ) {
  2258. host->continueSending = 1;
  2259. break;
  2260. }
  2261. acknowledgement = (ENetAcknowledgement *) currentAcknowledgement;
  2262. currentAcknowledgement = enet_list_next(currentAcknowledgement);
  2263. buffer->data = command;
  2264. buffer->dataLength = sizeof(ENetProtocolAcknowledge);
  2265. host->packetSize += buffer->dataLength;
  2266. reliableSequenceNumber = ENET_HOST_TO_NET_16(acknowledgement->command.header.reliableSequenceNumber);
  2267. command->header.command = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
  2268. command->header.channelID = acknowledgement->command.header.channelID;
  2269. command->header.reliableSequenceNumber = reliableSequenceNumber;
  2270. command->acknowledge.receivedReliableSequenceNumber = reliableSequenceNumber;
  2271. command->acknowledge.receivedSentTime = ENET_HOST_TO_NET_16(acknowledgement->sentTime);
  2272. if ((acknowledgement->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT) {
  2273. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  2274. }
  2275. enet_list_remove(&acknowledgement->acknowledgementList);
  2276. enet_free(acknowledgement);
  2277. ++command;
  2278. ++buffer;
  2279. }
  2280. host->commandCount = command - host->commands;
  2281. host->bufferCount = buffer - host->buffers;
  2282. } /* enet_protocol_send_acknowledgements */
  2283. static void enet_protocol_send_unreliable_outgoing_commands(ENetHost *host, ENetPeer *peer) {
  2284. ENetProtocol *command = &host->commands[host->commandCount];
  2285. ENetBuffer *buffer = &host->buffers[host->bufferCount];
  2286. ENetOutgoingCommand *outgoingCommand;
  2287. ENetListIterator currentCommand;
  2288. currentCommand = enet_list_begin(&peer->outgoingUnreliableCommands);
  2289. while (currentCommand != enet_list_end(&peer->outgoingUnreliableCommands)) {
  2290. size_t commandSize;
  2291. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  2292. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2293. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] ||
  2294. buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] ||
  2295. peer->mtu - host->packetSize < commandSize ||
  2296. (outgoingCommand->packet != NULL &&
  2297. peer->mtu - host->packetSize < commandSize + outgoingCommand->fragmentLength)
  2298. ) {
  2299. host->continueSending = 1;
  2300. break;
  2301. }
  2302. currentCommand = enet_list_next(currentCommand);
  2303. if (outgoingCommand->packet != NULL && outgoingCommand->fragmentOffset == 0) {
  2304. peer->packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER;
  2305. peer->packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE;
  2306. if (peer->packetThrottleCounter > peer->packetThrottle) {
  2307. enet_uint16 reliableSequenceNumber = outgoingCommand->reliableSequenceNumber;
  2308. enet_uint16 unreliableSequenceNumber = outgoingCommand->unreliableSequenceNumber;
  2309. for (;;) {
  2310. --outgoingCommand->packet->referenceCount;
  2311. if (outgoingCommand->packet->referenceCount == 0) {
  2312. callbacks.packet_destroy(outgoingCommand->packet);
  2313. }
  2314. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2315. enet_free(outgoingCommand);
  2316. if (currentCommand == enet_list_end(&peer->outgoingUnreliableCommands)) {
  2317. break;
  2318. }
  2319. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  2320. if (outgoingCommand->reliableSequenceNumber != reliableSequenceNumber || outgoingCommand->unreliableSequenceNumber != unreliableSequenceNumber) {
  2321. break;
  2322. }
  2323. currentCommand = enet_list_next(currentCommand);
  2324. }
  2325. continue;
  2326. }
  2327. }
  2328. buffer->data = command;
  2329. buffer->dataLength = commandSize;
  2330. host->packetSize += buffer->dataLength;
  2331. *command = outgoingCommand->command;
  2332. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2333. if (outgoingCommand->packet != NULL) {
  2334. ++buffer;
  2335. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2336. buffer->dataLength = outgoingCommand->fragmentLength;
  2337. host->packetSize += buffer->dataLength;
  2338. enet_list_insert(enet_list_end(&peer->sentUnreliableCommands), outgoingCommand);
  2339. } else {
  2340. enet_free(outgoingCommand);
  2341. }
  2342. ++command;
  2343. ++buffer;
  2344. }
  2345. host->commandCount = command - host->commands;
  2346. host->bufferCount = buffer - host->buffers;
  2347. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER &&
  2348. enet_list_empty(&peer->outgoingReliableCommands) &&
  2349. enet_list_empty(&peer->outgoingUnreliableCommands) &&
  2350. enet_list_empty(&peer->sentReliableCommands))
  2351. {
  2352. enet_peer_disconnect(peer, peer->eventData);
  2353. }
  2354. } /* enet_protocol_send_unreliable_outgoing_commands */
  2355. static int enet_protocol_check_timeouts(ENetHost *host, ENetPeer *peer, ENetEvent *event) {
  2356. ENetOutgoingCommand *outgoingCommand;
  2357. ENetListIterator currentCommand, insertPosition;
  2358. currentCommand = enet_list_begin(&peer->sentReliableCommands);
  2359. insertPosition = enet_list_begin(&peer->outgoingReliableCommands);
  2360. while (currentCommand != enet_list_end(&peer->sentReliableCommands)) {
  2361. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  2362. currentCommand = enet_list_next(currentCommand);
  2363. if (ENET_TIME_DIFFERENCE(host->serviceTime, outgoingCommand->sentTime) < outgoingCommand->roundTripTimeout) {
  2364. continue;
  2365. }
  2366. if (peer->earliestTimeout == 0 || ENET_TIME_LESS(outgoingCommand->sentTime, peer->earliestTimeout)) {
  2367. peer->earliestTimeout = outgoingCommand->sentTime;
  2368. }
  2369. if (peer->earliestTimeout != 0 &&
  2370. (ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMaximum ||
  2371. (outgoingCommand->roundTripTimeout >= outgoingCommand->roundTripTimeoutLimit &&
  2372. ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMinimum))
  2373. ) {
  2374. enet_protocol_notify_disconnect_timeout(host, peer, event);
  2375. return 1;
  2376. }
  2377. if (outgoingCommand->packet != NULL) {
  2378. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  2379. }
  2380. ++peer->packetsLost;
  2381. ++peer->totalPacketsLost;
  2382. /* Replaced exponential backoff time with something more linear */
  2383. /* Source: http://lists.cubik.org/pipermail/enet-discuss/2014-May/002308.html */
  2384. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2385. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2386. enet_list_insert(insertPosition, enet_list_remove(&outgoingCommand->outgoingCommandList));
  2387. if (currentCommand == enet_list_begin(&peer->sentReliableCommands) && !enet_list_empty(&peer->sentReliableCommands)) {
  2388. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  2389. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  2390. }
  2391. }
  2392. return 0;
  2393. } /* enet_protocol_check_timeouts */
  2394. static int enet_protocol_send_reliable_outgoing_commands(ENetHost *host, ENetPeer *peer) {
  2395. ENetProtocol *command = &host->commands[host->commandCount];
  2396. ENetBuffer *buffer = &host->buffers[host->bufferCount];
  2397. ENetOutgoingCommand *outgoingCommand;
  2398. ENetListIterator currentCommand;
  2399. ENetChannel *channel;
  2400. enet_uint16 reliableWindow;
  2401. size_t commandSize;
  2402. int windowExceeded = 0, windowWrap = 0, canPing = 1;
  2403. currentCommand = enet_list_begin(&peer->outgoingReliableCommands);
  2404. while (currentCommand != enet_list_end(&peer->outgoingReliableCommands)) {
  2405. outgoingCommand = (ENetOutgoingCommand *) currentCommand;
  2406. channel = outgoingCommand->command.header.channelID < peer->channelCount ? &peer->channels[outgoingCommand->command.header.channelID] : NULL;
  2407. reliableWindow = outgoingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2408. if (channel != NULL) {
  2409. if (!windowWrap &&
  2410. outgoingCommand->sendAttempts < 1 &&
  2411. !(outgoingCommand->reliableSequenceNumber % ENET_PEER_RELIABLE_WINDOW_SIZE) &&
  2412. (channel->reliableWindows[(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1)
  2413. % ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE ||
  2414. channel->usedReliableWindows & ((((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) << reliableWindow)
  2415. | (((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) >> (ENET_PEER_RELIABLE_WINDOWS - reliableWindow))))
  2416. ) {
  2417. windowWrap = 1;
  2418. }
  2419. if (windowWrap) {
  2420. currentCommand = enet_list_next(currentCommand);
  2421. continue;
  2422. }
  2423. }
  2424. if (outgoingCommand->packet != NULL) {
  2425. if (!windowExceeded) {
  2426. enet_uint32 windowSize = (peer->packetThrottle * peer->windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE;
  2427. if (peer->reliableDataInTransit + outgoingCommand->fragmentLength > ENET_MAX(windowSize, peer->mtu)) {
  2428. windowExceeded = 1;
  2429. }
  2430. }
  2431. if (windowExceeded) {
  2432. currentCommand = enet_list_next(currentCommand);
  2433. continue;
  2434. }
  2435. }
  2436. canPing = 0;
  2437. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2438. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] ||
  2439. buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] ||
  2440. peer->mtu - host->packetSize < commandSize ||
  2441. (outgoingCommand->packet != NULL &&
  2442. (enet_uint16) (peer->mtu - host->packetSize) < (enet_uint16) (commandSize + outgoingCommand->fragmentLength))
  2443. ) {
  2444. host->continueSending = 1;
  2445. break;
  2446. }
  2447. currentCommand = enet_list_next(currentCommand);
  2448. if (channel != NULL && outgoingCommand->sendAttempts < 1) {
  2449. channel->usedReliableWindows |= 1 << reliableWindow;
  2450. ++channel->reliableWindows[reliableWindow];
  2451. }
  2452. ++outgoingCommand->sendAttempts;
  2453. if (outgoingCommand->roundTripTimeout == 0) {
  2454. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2455. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2456. }
  2457. if (enet_list_empty(&peer->sentReliableCommands)) {
  2458. peer->nextTimeout = host->serviceTime + outgoingCommand->roundTripTimeout;
  2459. }
  2460. enet_list_insert(enet_list_end(&peer->sentReliableCommands), enet_list_remove(&outgoingCommand->outgoingCommandList));
  2461. outgoingCommand->sentTime = host->serviceTime;
  2462. buffer->data = command;
  2463. buffer->dataLength = commandSize;
  2464. host->packetSize += buffer->dataLength;
  2465. host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
  2466. *command = outgoingCommand->command;
  2467. if (outgoingCommand->packet != NULL) {
  2468. ++buffer;
  2469. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2470. buffer->dataLength = outgoingCommand->fragmentLength;
  2471. host->packetSize += outgoingCommand->fragmentLength;
  2472. peer->reliableDataInTransit += outgoingCommand->fragmentLength;
  2473. }
  2474. ++peer->packetsSent;
  2475. ++peer->totalPacketsSent;
  2476. ++command;
  2477. ++buffer;
  2478. }
  2479. host->commandCount = command - host->commands;
  2480. host->bufferCount = buffer - host->buffers;
  2481. return canPing;
  2482. } /* enet_protocol_send_reliable_outgoing_commands */
  2483. static int enet_protocol_send_outgoing_commands(ENetHost *host, ENetEvent *event, int checkForTimeouts) {
  2484. enet_uint8 headerData[sizeof(ENetProtocolHeader) + sizeof(enet_uint32)];
  2485. ENetProtocolHeader *header = (ENetProtocolHeader *) headerData;
  2486. ENetPeer *currentPeer;
  2487. int sentLength;
  2488. size_t shouldCompress = 0;
  2489. host->continueSending = 1;
  2490. while (host->continueSending)
  2491. for (host->continueSending = 0, currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2492. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED || currentPeer->state == ENET_PEER_STATE_ZOMBIE) {
  2493. continue;
  2494. }
  2495. host->headerFlags = 0;
  2496. host->commandCount = 0;
  2497. host->bufferCount = 1;
  2498. host->packetSize = sizeof(ENetProtocolHeader);
  2499. if (!enet_list_empty(&currentPeer->acknowledgements)) {
  2500. enet_protocol_send_acknowledgements(host, currentPeer);
  2501. }
  2502. if (checkForTimeouts != 0 &&
  2503. !enet_list_empty(&currentPeer->sentReliableCommands) &&
  2504. ENET_TIME_GREATER_EQUAL(host->serviceTime, currentPeer->nextTimeout) &&
  2505. enet_protocol_check_timeouts(host, currentPeer, event) == 1
  2506. ) {
  2507. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE) {
  2508. return 1;
  2509. } else {
  2510. continue;
  2511. }
  2512. }
  2513. if ((enet_list_empty(&currentPeer->outgoingReliableCommands) ||
  2514. enet_protocol_send_reliable_outgoing_commands(host, currentPeer)) &&
  2515. enet_list_empty(&currentPeer->sentReliableCommands) &&
  2516. ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->lastReceiveTime) >= currentPeer->pingInterval &&
  2517. currentPeer->mtu - host->packetSize >= sizeof(ENetProtocolPing)
  2518. ) {
  2519. enet_peer_ping(currentPeer);
  2520. enet_protocol_send_reliable_outgoing_commands(host, currentPeer);
  2521. }
  2522. if (!enet_list_empty(&currentPeer->outgoingUnreliableCommands)) {
  2523. enet_protocol_send_unreliable_outgoing_commands(host, currentPeer);
  2524. }
  2525. if (host->commandCount == 0) {
  2526. continue;
  2527. }
  2528. if (currentPeer->packetLossEpoch == 0) {
  2529. currentPeer->packetLossEpoch = host->serviceTime;
  2530. } else if (ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL && currentPeer->packetsSent > 0) {
  2531. enet_uint32 packetLoss = currentPeer->packetsLost * ENET_PEER_PACKET_LOSS_SCALE / currentPeer->packetsSent;
  2532. #ifdef ENET_DEBUG
  2533. printf(
  2534. "peer %u: %f%%+-%f%% packet loss, %u+-%u ms round trip time, %f%% throttle, %u/%u outgoing, %u/%u incoming\n", currentPeer->incomingPeerID,
  2535. currentPeer->packetLoss / (float) ENET_PEER_PACKET_LOSS_SCALE,
  2536. currentPeer->packetLossVariance / (float) ENET_PEER_PACKET_LOSS_SCALE, currentPeer->roundTripTime, currentPeer->roundTripTimeVariance,
  2537. currentPeer->packetThrottle / (float) ENET_PEER_PACKET_THROTTLE_SCALE,
  2538. enet_list_size(&currentPeer->outgoingReliableCommands),
  2539. enet_list_size(&currentPeer->outgoingUnreliableCommands),
  2540. currentPeer->channels != NULL ? enet_list_size( &currentPeer->channels->incomingReliableCommands) : 0,
  2541. currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingUnreliableCommands) : 0
  2542. );
  2543. #endif
  2544. currentPeer->packetLossVariance -= currentPeer->packetLossVariance / 4;
  2545. if (packetLoss >= currentPeer->packetLoss) {
  2546. currentPeer->packetLoss += (packetLoss - currentPeer->packetLoss) / 8;
  2547. currentPeer->packetLossVariance += (packetLoss - currentPeer->packetLoss) / 4;
  2548. } else {
  2549. currentPeer->packetLoss -= (currentPeer->packetLoss - packetLoss) / 8;
  2550. currentPeer->packetLossVariance += (currentPeer->packetLoss - packetLoss) / 4;
  2551. }
  2552. currentPeer->packetLossEpoch = host->serviceTime;
  2553. currentPeer->packetsSent = 0;
  2554. currentPeer->packetsLost = 0;
  2555. }
  2556. host->buffers->data = headerData;
  2557. if (host->headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) {
  2558. header->sentTime = ENET_HOST_TO_NET_16(host->serviceTime & 0xFFFF);
  2559. host->buffers->dataLength = sizeof(ENetProtocolHeader);
  2560. } else {
  2561. host->buffers->dataLength = (size_t) &((ENetProtocolHeader *) 0)->sentTime;
  2562. }
  2563. shouldCompress = 0;
  2564. if (host->compressor.context != NULL && host->compressor.compress != NULL) {
  2565. size_t originalSize = host->packetSize - sizeof(ENetProtocolHeader),
  2566. compressedSize = host->compressor.compress(host->compressor.context, &host->buffers[1], host->bufferCount - 1, originalSize, host->packetData[1], originalSize);
  2567. if (compressedSize > 0 && compressedSize < originalSize) {
  2568. host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_COMPRESSED;
  2569. shouldCompress = compressedSize;
  2570. #ifdef ENET_DEBUG_COMPRESS
  2571. printf("peer %u: compressed %u->%u (%u%%)\n", currentPeer->incomingPeerID, originalSize, compressedSize, (compressedSize * 100) / originalSize);
  2572. #endif
  2573. }
  2574. }
  2575. if (currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  2576. host->headerFlags |= currentPeer->outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  2577. }
  2578. header->peerID = ENET_HOST_TO_NET_16(currentPeer->outgoingPeerID | host->headerFlags);
  2579. if (host->checksum != NULL) {
  2580. enet_uint32 *checksum = (enet_uint32 *) &headerData[host->buffers->dataLength];
  2581. *checksum = currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer->connectID : 0;
  2582. host->buffers->dataLength += sizeof(enet_uint32);
  2583. *checksum = host->checksum(host->buffers, host->bufferCount);
  2584. }
  2585. if (shouldCompress > 0) {
  2586. host->buffers[1].data = host->packetData[1];
  2587. host->buffers[1].dataLength = shouldCompress;
  2588. host->bufferCount = 2;
  2589. }
  2590. currentPeer->lastSendTime = host->serviceTime;
  2591. sentLength = enet_socket_send(host->socket, &currentPeer->address, host->buffers, host->bufferCount);
  2592. enet_protocol_remove_sent_unreliable_commands(currentPeer);
  2593. if (sentLength < 0) {
  2594. return -1;
  2595. }
  2596. host->totalSentData += sentLength;
  2597. currentPeer->totalDataSent += sentLength;
  2598. host->totalSentPackets++;
  2599. }
  2600. return 0;
  2601. } /* enet_protocol_send_outgoing_commands */
  2602. /** Sends any queued packets on the host specified to its designated peers.
  2603. *
  2604. * @param host host to flush
  2605. * @remarks this function need only be used in circumstances where one wishes to send queued packets earlier than in a call to enet_host_service().
  2606. * @ingroup host
  2607. */
  2608. void enet_host_flush(ENetHost *host) {
  2609. host->serviceTime = enet_time_get();
  2610. enet_protocol_send_outgoing_commands(host, NULL, 0);
  2611. }
  2612. /** Checks for any queued events on the host and dispatches one if available.
  2613. *
  2614. * @param host host to check for events
  2615. * @param event an event structure where event details will be placed if available
  2616. * @retval > 0 if an event was dispatched
  2617. * @retval 0 if no events are available
  2618. * @retval < 0 on failure
  2619. * @ingroup host
  2620. */
  2621. int enet_host_check_events(ENetHost *host, ENetEvent *event) {
  2622. if (event == NULL) { return -1; }
  2623. event->type = ENET_EVENT_TYPE_NONE;
  2624. event->peer = NULL;
  2625. event->packet = NULL;
  2626. return enet_protocol_dispatch_incoming_commands(host, event);
  2627. }
  2628. /** Waits for events on the host specified and shuttles packets between
  2629. * the host and its peers.
  2630. *
  2631. * @param host host to service
  2632. * @param event an event structure where event details will be placed if one occurs
  2633. * if event == NULL then no events will be delivered
  2634. * @param timeout number of milliseconds that ENet should wait for events
  2635. * @retval > 0 if an event occurred within the specified time limit
  2636. * @retval 0 if no event occurred
  2637. * @retval < 0 on failure
  2638. * @remarks enet_host_service should be called fairly regularly for adequate performance
  2639. * @ingroup host
  2640. */
  2641. int enet_host_service(ENetHost *host, ENetEvent *event, enet_uint32 timeout) {
  2642. enet_uint32 waitCondition;
  2643. if (event != NULL) {
  2644. event->type = ENET_EVENT_TYPE_NONE;
  2645. event->peer = NULL;
  2646. event->packet = NULL;
  2647. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2648. case 1:
  2649. return 1;
  2650. case -1:
  2651. #ifdef ENET_DEBUG
  2652. perror("Error dispatching incoming packets");
  2653. #endif
  2654. return -1;
  2655. default:
  2656. break;
  2657. }
  2658. }
  2659. host->serviceTime = enet_time_get();
  2660. timeout += host->serviceTime;
  2661. do {
  2662. if (ENET_TIME_DIFFERENCE(host->serviceTime, host->bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) {
  2663. enet_host_bandwidth_throttle(host);
  2664. }
  2665. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2666. case 1:
  2667. return 1;
  2668. case -1:
  2669. #ifdef ENET_DEBUG
  2670. perror("Error sending outgoing packets");
  2671. #endif
  2672. return -1;
  2673. default:
  2674. break;
  2675. }
  2676. switch (enet_protocol_receive_incoming_commands(host, event)) {
  2677. case 1:
  2678. return 1;
  2679. case -1:
  2680. #ifdef ENET_DEBUG
  2681. perror("Error receiving incoming packets");
  2682. #endif
  2683. return -1;
  2684. default:
  2685. break;
  2686. }
  2687. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2688. case 1:
  2689. return 1;
  2690. case -1:
  2691. #ifdef ENET_DEBUG
  2692. perror("Error sending outgoing packets");
  2693. #endif
  2694. return -1;
  2695. default:
  2696. break;
  2697. }
  2698. if (event != NULL) {
  2699. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2700. case 1:
  2701. return 1;
  2702. case -1:
  2703. #ifdef ENET_DEBUG
  2704. perror("Error dispatching incoming packets");
  2705. #endif
  2706. return -1;
  2707. default:
  2708. break;
  2709. }
  2710. }
  2711. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout)) {
  2712. return 0;
  2713. }
  2714. do {
  2715. host->serviceTime = enet_time_get();
  2716. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout)) {
  2717. return 0;
  2718. }
  2719. waitCondition = ENET_SOCKET_WAIT_RECEIVE | ENET_SOCKET_WAIT_INTERRUPT;
  2720. if (enet_socket_wait(host->socket, &waitCondition, ENET_TIME_DIFFERENCE(timeout, host->serviceTime)) != 0) {
  2721. return -1;
  2722. }
  2723. } while (waitCondition & ENET_SOCKET_WAIT_INTERRUPT);
  2724. host->serviceTime = enet_time_get();
  2725. } while (waitCondition & ENET_SOCKET_WAIT_RECEIVE);
  2726. return 0;
  2727. } /* enet_host_service */
  2728. // =======================================================================//
  2729. // !
  2730. // ! Peer
  2731. // !
  2732. // =======================================================================//
  2733. /** Configures throttle parameter for a peer.
  2734. *
  2735. * Unreliable packets are dropped by ENet in response to the varying conditions
  2736. * of the Internet connection to the peer. The throttle represents a probability
  2737. * that an unreliable packet should not be dropped and thus sent by ENet to the peer.
  2738. * The lowest mean round trip time from the sending of a reliable packet to the
  2739. * receipt of its acknowledgement is measured over an amount of time specified by
  2740. * the interval parameter in milliseconds. If a measured round trip time happens to
  2741. * be significantly less than the mean round trip time measured over the interval,
  2742. * then the throttle probability is increased to allow more traffic by an amount
  2743. * specified in the acceleration parameter, which is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE
  2744. * constant. If a measured round trip time happens to be significantly greater than
  2745. * the mean round trip time measured over the interval, then the throttle probability
  2746. * is decreased to limit traffic by an amount specified in the deceleration parameter, which
  2747. * is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE constant. When the throttle has
  2748. * a value of ENET_PEER_PACKET_THROTTLE_SCALE, no unreliable packets are dropped by
  2749. * ENet, and so 100% of all unreliable packets will be sent. When the throttle has a
  2750. * value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable
  2751. * packets will be sent. Intermediate values for the throttle represent intermediate
  2752. * probabilities between 0% and 100% of unreliable packets being sent. The bandwidth
  2753. * limits of the local and foreign hosts are taken into account to determine a
  2754. * sensible limit for the throttle probability above which it should not raise even in
  2755. * the best of conditions.
  2756. *
  2757. * @param peer peer to configure
  2758. * @param interval interval, in milliseconds, over which to measure lowest mean RTT; the default value is ENET_PEER_PACKET_THROTTLE_INTERVAL.
  2759. * @param acceleration rate at which to increase the throttle probability as mean RTT declines
  2760. * @param deceleration rate at which to decrease the throttle probability as mean RTT increases
  2761. */
  2762. void enet_peer_throttle_configure(ENetPeer *peer, enet_uint32 interval, enet_uint32 acceleration, enet_uint32 deceleration) {
  2763. ENetProtocol command;
  2764. peer->packetThrottleInterval = interval;
  2765. peer->packetThrottleAcceleration = acceleration;
  2766. peer->packetThrottleDeceleration = deceleration;
  2767. command.header.command = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2768. command.header.channelID = 0xFF;
  2769. command.throttleConfigure.packetThrottleInterval = ENET_HOST_TO_NET_32(interval);
  2770. command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32(acceleration);
  2771. command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32(deceleration);
  2772. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2773. }
  2774. int enet_peer_throttle(ENetPeer *peer, enet_uint32 rtt) {
  2775. if (peer->lastRoundTripTime <= peer->lastRoundTripTimeVariance) {
  2776. peer->packetThrottle = peer->packetThrottleLimit;
  2777. }
  2778. else if (rtt < peer->lastRoundTripTime) {
  2779. peer->packetThrottle += peer->packetThrottleAcceleration;
  2780. if (peer->packetThrottle > peer->packetThrottleLimit) {
  2781. peer->packetThrottle = peer->packetThrottleLimit;
  2782. }
  2783. return 1;
  2784. }
  2785. else if (rtt > peer->lastRoundTripTime + 2 * peer->lastRoundTripTimeVariance) {
  2786. if (peer->packetThrottle > peer->packetThrottleDeceleration) {
  2787. peer->packetThrottle -= peer->packetThrottleDeceleration;
  2788. } else {
  2789. peer->packetThrottle = 0;
  2790. }
  2791. return -1;
  2792. }
  2793. return 0;
  2794. }
  2795. /* Extended functionality for easier binding in other programming languages */
  2796. enet_uint32 enet_host_get_peers_count(ENetHost *host) {
  2797. return host->connectedPeers;
  2798. }
  2799. enet_uint32 enet_host_get_packets_sent(ENetHost *host) {
  2800. return host->totalSentPackets;
  2801. }
  2802. enet_uint32 enet_host_get_packets_received(ENetHost *host) {
  2803. return host->totalReceivedPackets;
  2804. }
  2805. enet_uint32 enet_host_get_bytes_sent(ENetHost *host) {
  2806. return host->totalSentData;
  2807. }
  2808. enet_uint32 enet_host_get_bytes_received(ENetHost *host) {
  2809. return host->totalReceivedData;
  2810. }
  2811. /** Gets received data buffer. Returns buffer length.
  2812. * @param host host to access recevie buffer
  2813. * @param data ouput parameter for recevied data
  2814. * @retval buffer length
  2815. */
  2816. enet_uint32 enet_host_get_received_data(ENetHost *host, /*out*/ enet_uint8** data) {
  2817. *data = host->receivedData;
  2818. return host->receivedDataLength;
  2819. }
  2820. enet_uint32 enet_host_get_mtu(ENetHost *host) {
  2821. return host->mtu;
  2822. }
  2823. enet_uint32 enet_peer_get_id(ENetPeer *peer) {
  2824. return peer->connectID;
  2825. }
  2826. enet_uint32 enet_peer_get_ip(ENetPeer *peer, char *ip, size_t ipLength) {
  2827. return enet_address_get_host_ip(&peer->address, ip, ipLength);
  2828. }
  2829. enet_uint16 enet_peer_get_port(ENetPeer *peer) {
  2830. return peer->address.port;
  2831. }
  2832. ENetPeerState enet_peer_get_state(ENetPeer *peer) {
  2833. return peer->state;
  2834. }
  2835. enet_uint32 enet_peer_get_rtt(ENetPeer *peer) {
  2836. return peer->roundTripTime;
  2837. }
  2838. enet_uint64 enet_peer_get_packets_sent(ENetPeer *peer) {
  2839. return peer->totalPacketsSent;
  2840. }
  2841. enet_uint32 enet_peer_get_packets_lost(ENetPeer *peer) {
  2842. return peer->totalPacketsLost;
  2843. }
  2844. enet_uint64 enet_peer_get_bytes_sent(ENetPeer *peer) {
  2845. return peer->totalDataSent;
  2846. }
  2847. enet_uint64 enet_peer_get_bytes_received(ENetPeer *peer) {
  2848. return peer->totalDataReceived;
  2849. }
  2850. void * enet_peer_get_data(ENetPeer *peer) {
  2851. return (void *) peer->data;
  2852. }
  2853. void enet_peer_set_data(ENetPeer *peer, const void *data) {
  2854. peer->data = (enet_uint32 *) data;
  2855. }
  2856. void * enet_packet_get_data(ENetPacket *packet) {
  2857. return (void *) packet->data;
  2858. }
  2859. enet_uint32 enet_packet_get_length(ENetPacket *packet) {
  2860. return packet->dataLength;
  2861. }
  2862. void enet_packet_set_free_callback(ENetPacket *packet, void *callback) {
  2863. packet->freeCallback = (ENetPacketFreeCallback)callback;
  2864. }
  2865. /** Queues a packet to be sent.
  2866. * @param peer destination for the packet
  2867. * @param channelID channel on which to send
  2868. * @param packet packet to send
  2869. * @retval 0 on success
  2870. * @retval < 0 on failure
  2871. */
  2872. int enet_peer_send(ENetPeer *peer, enet_uint8 channelID, ENetPacket *packet) {
  2873. ENetChannel *channel = &peer->channels[channelID];
  2874. ENetProtocol command;
  2875. size_t fragmentLength;
  2876. if (peer->state != ENET_PEER_STATE_CONNECTED || channelID >= peer->channelCount || packet->dataLength > peer->host->maximumPacketSize) {
  2877. return -1;
  2878. }
  2879. fragmentLength = peer->mtu - sizeof(ENetProtocolHeader) - sizeof(ENetProtocolSendFragment);
  2880. if (peer->host->checksum != NULL) {
  2881. fragmentLength -= sizeof(enet_uint32);
  2882. }
  2883. if (packet->dataLength > fragmentLength) {
  2884. enet_uint32 fragmentCount = (packet->dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset;
  2885. enet_uint8 commandNumber;
  2886. enet_uint16 startSequenceNumber;
  2887. ENetList fragments;
  2888. ENetOutgoingCommand *fragment;
  2889. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) {
  2890. return -1;
  2891. }
  2892. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT)) ==
  2893. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT &&
  2894. channel->outgoingUnreliableSequenceNumber < 0xFFFF)
  2895. {
  2896. commandNumber = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
  2897. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingUnreliableSequenceNumber + 1);
  2898. } else {
  2899. commandNumber = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2900. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingReliableSequenceNumber + 1);
  2901. }
  2902. enet_list_clear(&fragments);
  2903. for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet->dataLength; ++fragmentNumber, fragmentOffset += fragmentLength) {
  2904. if (packet->dataLength - fragmentOffset < fragmentLength) {
  2905. fragmentLength = packet->dataLength - fragmentOffset;
  2906. }
  2907. fragment = (ENetOutgoingCommand *) enet_malloc(sizeof(ENetOutgoingCommand));
  2908. if (fragment == NULL) {
  2909. while (!enet_list_empty(&fragments)) {
  2910. fragment = (ENetOutgoingCommand *) enet_list_remove(enet_list_begin(&fragments));
  2911. enet_free(fragment);
  2912. }
  2913. return -1;
  2914. }
  2915. fragment->fragmentOffset = fragmentOffset;
  2916. fragment->fragmentLength = fragmentLength;
  2917. fragment->packet = packet;
  2918. fragment->command.header.command = commandNumber;
  2919. fragment->command.header.channelID = channelID;
  2920. fragment->command.sendFragment.startSequenceNumber = startSequenceNumber;
  2921. fragment->command.sendFragment.dataLength = ENET_HOST_TO_NET_16(fragmentLength);
  2922. fragment->command.sendFragment.fragmentCount = ENET_HOST_TO_NET_32(fragmentCount);
  2923. fragment->command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32(fragmentNumber);
  2924. fragment->command.sendFragment.totalLength = ENET_HOST_TO_NET_32(packet->dataLength);
  2925. fragment->command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32(fragmentOffset);
  2926. enet_list_insert(enet_list_end(&fragments), fragment);
  2927. }
  2928. packet->referenceCount += fragmentNumber;
  2929. while (!enet_list_empty(&fragments)) {
  2930. fragment = (ENetOutgoingCommand *) enet_list_remove(enet_list_begin(&fragments));
  2931. enet_peer_setup_outgoing_command(peer, fragment);
  2932. }
  2933. return 0;
  2934. }
  2935. command.header.channelID = channelID;
  2936. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) {
  2937. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2938. command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2939. }
  2940. else if (packet->flags & ENET_PACKET_FLAG_RELIABLE || channel->outgoingUnreliableSequenceNumber >= 0xFFFF) {
  2941. command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2942. command.sendReliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2943. }
  2944. else {
  2945. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
  2946. command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2947. }
  2948. if (enet_peer_queue_outgoing_command(peer, &command, packet, 0, packet->dataLength) == NULL) {
  2949. return -1;
  2950. }
  2951. return 0;
  2952. } // enet_peer_send
  2953. /** Attempts to dequeue any incoming queued packet.
  2954. * @param peer peer to dequeue packets from
  2955. * @param channelID holds the channel ID of the channel the packet was received on success
  2956. * @returns a pointer to the packet, or NULL if there are no available incoming queued packets
  2957. */
  2958. ENetPacket * enet_peer_receive(ENetPeer *peer, enet_uint8 *channelID) {
  2959. ENetIncomingCommand *incomingCommand;
  2960. ENetPacket *packet;
  2961. if (enet_list_empty(&peer->dispatchedCommands)) {
  2962. return NULL;
  2963. }
  2964. incomingCommand = (ENetIncomingCommand *) enet_list_remove(enet_list_begin(&peer->dispatchedCommands));
  2965. if (channelID != NULL) {
  2966. *channelID = incomingCommand->command.header.channelID;
  2967. }
  2968. packet = incomingCommand->packet;
  2969. --packet->referenceCount;
  2970. if (incomingCommand->fragments != NULL) {
  2971. enet_free(incomingCommand->fragments);
  2972. }
  2973. enet_free(incomingCommand);
  2974. peer->totalWaitingData -= packet->dataLength;
  2975. return packet;
  2976. }
  2977. static void enet_peer_reset_outgoing_commands(ENetList *queue) {
  2978. ENetOutgoingCommand *outgoingCommand;
  2979. while (!enet_list_empty(queue)) {
  2980. outgoingCommand = (ENetOutgoingCommand *) enet_list_remove(enet_list_begin(queue));
  2981. if (outgoingCommand->packet != NULL) {
  2982. --outgoingCommand->packet->referenceCount;
  2983. if (outgoingCommand->packet->referenceCount == 0) {
  2984. callbacks.packet_destroy(outgoingCommand->packet);
  2985. }
  2986. }
  2987. enet_free(outgoingCommand);
  2988. }
  2989. }
  2990. static void enet_peer_remove_incoming_commands(ENetList *queue, ENetListIterator startCommand, ENetListIterator endCommand) {
  2991. ENET_UNUSED(queue)
  2992. ENetListIterator currentCommand;
  2993. for (currentCommand = startCommand; currentCommand != endCommand;) {
  2994. ENetIncomingCommand *incomingCommand = (ENetIncomingCommand *) currentCommand;
  2995. currentCommand = enet_list_next(currentCommand);
  2996. enet_list_remove(&incomingCommand->incomingCommandList);
  2997. if (incomingCommand->packet != NULL) {
  2998. --incomingCommand->packet->referenceCount;
  2999. if (incomingCommand->packet->referenceCount == 0) {
  3000. callbacks.packet_destroy(incomingCommand->packet);
  3001. }
  3002. }
  3003. if (incomingCommand->fragments != NULL) {
  3004. enet_free(incomingCommand->fragments);
  3005. }
  3006. enet_free(incomingCommand);
  3007. }
  3008. }
  3009. static void enet_peer_reset_incoming_commands(ENetList *queue) {
  3010. enet_peer_remove_incoming_commands(queue, enet_list_begin(queue), enet_list_end(queue));
  3011. }
  3012. void enet_peer_reset_queues(ENetPeer *peer) {
  3013. ENetChannel *channel;
  3014. if (peer->needsDispatch) {
  3015. enet_list_remove(&peer->dispatchList);
  3016. peer->needsDispatch = 0;
  3017. }
  3018. while (!enet_list_empty(&peer->acknowledgements)) {
  3019. enet_free(enet_list_remove(enet_list_begin(&peer->acknowledgements)));
  3020. }
  3021. enet_peer_reset_outgoing_commands(&peer->sentReliableCommands);
  3022. enet_peer_reset_outgoing_commands(&peer->sentUnreliableCommands);
  3023. enet_peer_reset_outgoing_commands(&peer->outgoingReliableCommands);
  3024. enet_peer_reset_outgoing_commands(&peer->outgoingUnreliableCommands);
  3025. enet_peer_reset_incoming_commands(&peer->dispatchedCommands);
  3026. if (peer->channels != NULL && peer->channelCount > 0) {
  3027. for (channel = peer->channels; channel < &peer->channels[peer->channelCount]; ++channel) {
  3028. enet_peer_reset_incoming_commands(&channel->incomingReliableCommands);
  3029. enet_peer_reset_incoming_commands(&channel->incomingUnreliableCommands);
  3030. }
  3031. enet_free(peer->channels);
  3032. }
  3033. peer->channels = NULL;
  3034. peer->channelCount = 0;
  3035. }
  3036. void enet_peer_on_connect(ENetPeer *peer) {
  3037. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  3038. if (peer->incomingBandwidth != 0) {
  3039. ++peer->host->bandwidthLimitedPeers;
  3040. }
  3041. ++peer->host->connectedPeers;
  3042. }
  3043. }
  3044. void enet_peer_on_disconnect(ENetPeer *peer) {
  3045. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  3046. if (peer->incomingBandwidth != 0) {
  3047. --peer->host->bandwidthLimitedPeers;
  3048. }
  3049. --peer->host->connectedPeers;
  3050. }
  3051. }
  3052. /** Forcefully disconnects a peer.
  3053. * @param peer peer to forcefully disconnect
  3054. * @remarks The foreign host represented by the peer is not notified of the disconnection and will timeout
  3055. * on its connection to the local host.
  3056. */
  3057. void enet_peer_reset(ENetPeer *peer) {
  3058. enet_peer_on_disconnect(peer);
  3059. // We don't want to reset connectID here, otherwise, we can't get it in the Disconnect event
  3060. // peer->connectID = 0;
  3061. peer->outgoingPeerID = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  3062. peer->state = ENET_PEER_STATE_DISCONNECTED;
  3063. peer->incomingBandwidth = 0;
  3064. peer->outgoingBandwidth = 0;
  3065. peer->incomingBandwidthThrottleEpoch = 0;
  3066. peer->outgoingBandwidthThrottleEpoch = 0;
  3067. peer->incomingDataTotal = 0;
  3068. peer->totalDataReceived = 0;
  3069. peer->outgoingDataTotal = 0;
  3070. peer->totalDataSent = 0;
  3071. peer->lastSendTime = 0;
  3072. peer->lastReceiveTime = 0;
  3073. peer->nextTimeout = 0;
  3074. peer->earliestTimeout = 0;
  3075. peer->packetLossEpoch = 0;
  3076. peer->packetsSent = 0;
  3077. peer->totalPacketsSent = 0;
  3078. peer->packetsLost = 0;
  3079. peer->totalPacketsLost = 0;
  3080. peer->packetLoss = 0;
  3081. peer->packetLossVariance = 0;
  3082. peer->packetThrottle = ENET_PEER_DEFAULT_PACKET_THROTTLE;
  3083. peer->packetThrottleLimit = ENET_PEER_PACKET_THROTTLE_SCALE;
  3084. peer->packetThrottleCounter = 0;
  3085. peer->packetThrottleEpoch = 0;
  3086. peer->packetThrottleAcceleration = ENET_PEER_PACKET_THROTTLE_ACCELERATION;
  3087. peer->packetThrottleDeceleration = ENET_PEER_PACKET_THROTTLE_DECELERATION;
  3088. peer->packetThrottleInterval = ENET_PEER_PACKET_THROTTLE_INTERVAL;
  3089. peer->pingInterval = ENET_PEER_PING_INTERVAL;
  3090. peer->timeoutLimit = ENET_PEER_TIMEOUT_LIMIT;
  3091. peer->timeoutMinimum = ENET_PEER_TIMEOUT_MINIMUM;
  3092. peer->timeoutMaximum = ENET_PEER_TIMEOUT_MAXIMUM;
  3093. peer->lastRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  3094. peer->lowestRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  3095. peer->lastRoundTripTimeVariance = 0;
  3096. peer->highestRoundTripTimeVariance = 0;
  3097. peer->roundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  3098. peer->roundTripTimeVariance = 0;
  3099. peer->mtu = peer->host->mtu;
  3100. peer->reliableDataInTransit = 0;
  3101. peer->outgoingReliableSequenceNumber = 0;
  3102. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3103. peer->incomingUnsequencedGroup = 0;
  3104. peer->outgoingUnsequencedGroup = 0;
  3105. peer->eventData = 0;
  3106. peer->totalWaitingData = 0;
  3107. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  3108. enet_peer_reset_queues(peer);
  3109. }
  3110. /** Sends a ping request to a peer.
  3111. * @param peer destination for the ping request
  3112. * @remarks ping requests factor into the mean round trip time as designated by the
  3113. * roundTripTime field in the ENetPeer structure. ENet automatically pings all connected
  3114. * peers at regular intervals, however, this function may be called to ensure more
  3115. * frequent ping requests.
  3116. */
  3117. void enet_peer_ping(ENetPeer *peer) {
  3118. ENetProtocol command;
  3119. if (peer->state != ENET_PEER_STATE_CONNECTED) {
  3120. return;
  3121. }
  3122. command.header.command = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3123. command.header.channelID = 0xFF;
  3124. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3125. }
  3126. /** Sets the interval at which pings will be sent to a peer.
  3127. *
  3128. * Pings are used both to monitor the liveness of the connection and also to dynamically
  3129. * adjust the throttle during periods of low traffic so that the throttle has reasonable
  3130. * responsiveness during traffic spikes.
  3131. *
  3132. * @param peer the peer to adjust
  3133. * @param pingInterval the interval at which to send pings; defaults to ENET_PEER_PING_INTERVAL if 0
  3134. */
  3135. void enet_peer_ping_interval(ENetPeer *peer, enet_uint32 pingInterval) {
  3136. peer->pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL;
  3137. }
  3138. /** Sets the timeout parameters for a peer.
  3139. *
  3140. * The timeout parameter control how and when a peer will timeout from a failure to acknowledge
  3141. * reliable traffic. Timeout values use an exponential backoff mechanism, where if a reliable
  3142. * packet is not acknowledge within some multiple of the average RTT plus a variance tolerance,
  3143. * the timeout will be doubled until it reaches a set limit. If the timeout is thus at this
  3144. * limit and reliable packets have been sent but not acknowledged within a certain minimum time
  3145. * period, the peer will be disconnected. Alternatively, if reliable packets have been sent
  3146. * but not acknowledged for a certain maximum time period, the peer will be disconnected regardless
  3147. * of the current timeout limit value.
  3148. *
  3149. * @param peer the peer to adjust
  3150. * @param timeoutLimit the timeout limit; defaults to ENET_PEER_TIMEOUT_LIMIT if 0
  3151. * @param timeoutMinimum the timeout minimum; defaults to ENET_PEER_TIMEOUT_MINIMUM if 0
  3152. * @param timeoutMaximum the timeout maximum; defaults to ENET_PEER_TIMEOUT_MAXIMUM if 0
  3153. */
  3154. void enet_peer_timeout(ENetPeer *peer, enet_uint32 timeoutLimit, enet_uint32 timeoutMinimum, enet_uint32 timeoutMaximum) {
  3155. peer->timeoutLimit = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT;
  3156. peer->timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM;
  3157. peer->timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM;
  3158. }
  3159. /** Force an immediate disconnection from a peer.
  3160. * @param peer peer to disconnect
  3161. * @param data data describing the disconnection
  3162. * @remarks No ENET_EVENT_DISCONNECT event will be generated. The foreign peer is not
  3163. * guaranteed to receive the disconnect notification, and is reset immediately upon
  3164. * return from this function.
  3165. */
  3166. void enet_peer_disconnect_now(ENetPeer *peer, enet_uint32 data) {
  3167. ENetProtocol command;
  3168. if (peer->state == ENET_PEER_STATE_DISCONNECTED) {
  3169. return;
  3170. }
  3171. if (peer->state != ENET_PEER_STATE_ZOMBIE && peer->state != ENET_PEER_STATE_DISCONNECTING) {
  3172. enet_peer_reset_queues(peer);
  3173. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  3174. command.header.channelID = 0xFF;
  3175. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  3176. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3177. enet_host_flush(peer->host);
  3178. }
  3179. enet_peer_reset(peer);
  3180. }
  3181. /** Request a disconnection from a peer.
  3182. * @param peer peer to request a disconnection
  3183. * @param data data describing the disconnection
  3184. * @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
  3185. * once the disconnection is complete.
  3186. */
  3187. void enet_peer_disconnect(ENetPeer *peer, enet_uint32 data) {
  3188. ENetProtocol command;
  3189. if (peer->state == ENET_PEER_STATE_DISCONNECTING ||
  3190. peer->state == ENET_PEER_STATE_DISCONNECTED ||
  3191. peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT ||
  3192. peer->state == ENET_PEER_STATE_ZOMBIE
  3193. ) {
  3194. return;
  3195. }
  3196. enet_peer_reset_queues(peer);
  3197. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT;
  3198. command.header.channelID = 0xFF;
  3199. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  3200. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  3201. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3202. } else {
  3203. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  3204. }
  3205. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3206. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  3207. enet_peer_on_disconnect(peer);
  3208. peer->state = ENET_PEER_STATE_DISCONNECTING;
  3209. } else {
  3210. enet_host_flush(peer->host);
  3211. enet_peer_reset(peer);
  3212. }
  3213. }
  3214. /** Request a disconnection from a peer, but only after all queued outgoing packets are sent.
  3215. * @param peer peer to request a disconnection
  3216. * @param data data describing the disconnection
  3217. * @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
  3218. * once the disconnection is complete.
  3219. */
  3220. void enet_peer_disconnect_later(ENetPeer *peer, enet_uint32 data) {
  3221. if ((peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) &&
  3222. !(enet_list_empty(&peer->outgoingReliableCommands) &&
  3223. enet_list_empty(&peer->outgoingUnreliableCommands) &&
  3224. enet_list_empty(&peer->sentReliableCommands))
  3225. ) {
  3226. peer->state = ENET_PEER_STATE_DISCONNECT_LATER;
  3227. peer->eventData = data;
  3228. } else {
  3229. enet_peer_disconnect(peer, data);
  3230. }
  3231. }
  3232. ENetAcknowledgement *enet_peer_queue_acknowledgement(ENetPeer *peer, const ENetProtocol *command, enet_uint16 sentTime) {
  3233. ENetAcknowledgement *acknowledgement;
  3234. if (command->header.channelID < peer->channelCount) {
  3235. ENetChannel *channel = &peer->channels[command->header.channelID];
  3236. enet_uint16 reliableWindow = command->header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3237. enet_uint16 currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3238. if (command->header.reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  3239. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  3240. }
  3241. if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS) {
  3242. return NULL;
  3243. }
  3244. }
  3245. acknowledgement = (ENetAcknowledgement *) enet_malloc(sizeof(ENetAcknowledgement));
  3246. if (acknowledgement == NULL) {
  3247. return NULL;
  3248. }
  3249. peer->outgoingDataTotal += sizeof(ENetProtocolAcknowledge);
  3250. acknowledgement->sentTime = sentTime;
  3251. acknowledgement->command = *command;
  3252. enet_list_insert(enet_list_end(&peer->acknowledgements), acknowledgement);
  3253. return acknowledgement;
  3254. }
  3255. void enet_peer_setup_outgoing_command(ENetPeer *peer, ENetOutgoingCommand *outgoingCommand) {
  3256. ENetChannel *channel = &peer->channels[outgoingCommand->command.header.channelID];
  3257. peer->outgoingDataTotal += enet_protocol_command_size(outgoingCommand->command.header.command) + outgoingCommand->fragmentLength;
  3258. if (outgoingCommand->command.header.channelID == 0xFF) {
  3259. ++peer->outgoingReliableSequenceNumber;
  3260. outgoingCommand->reliableSequenceNumber = peer->outgoingReliableSequenceNumber;
  3261. outgoingCommand->unreliableSequenceNumber = 0;
  3262. }
  3263. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  3264. ++channel->outgoingReliableSequenceNumber;
  3265. channel->outgoingUnreliableSequenceNumber = 0;
  3266. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  3267. outgoingCommand->unreliableSequenceNumber = 0;
  3268. }
  3269. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) {
  3270. ++peer->outgoingUnsequencedGroup;
  3271. outgoingCommand->reliableSequenceNumber = 0;
  3272. outgoingCommand->unreliableSequenceNumber = 0;
  3273. }
  3274. else {
  3275. if (outgoingCommand->fragmentOffset == 0) {
  3276. ++channel->outgoingUnreliableSequenceNumber;
  3277. }
  3278. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  3279. outgoingCommand->unreliableSequenceNumber = channel->outgoingUnreliableSequenceNumber;
  3280. }
  3281. outgoingCommand->sendAttempts = 0;
  3282. outgoingCommand->sentTime = 0;
  3283. outgoingCommand->roundTripTimeout = 0;
  3284. outgoingCommand->roundTripTimeoutLimit = 0;
  3285. outgoingCommand->command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->reliableSequenceNumber);
  3286. switch (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) {
  3287. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  3288. outgoingCommand->command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->unreliableSequenceNumber);
  3289. break;
  3290. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  3291. outgoingCommand->command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16(peer->outgoingUnsequencedGroup);
  3292. break;
  3293. default:
  3294. break;
  3295. }
  3296. if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  3297. enet_list_insert(enet_list_end(&peer->outgoingReliableCommands), outgoingCommand);
  3298. } else {
  3299. enet_list_insert(enet_list_end(&peer->outgoingUnreliableCommands), outgoingCommand);
  3300. }
  3301. }
  3302. ENetOutgoingCommand * enet_peer_queue_outgoing_command(ENetPeer *peer, const ENetProtocol *command, ENetPacket *packet, enet_uint32 offset, enet_uint16 length) {
  3303. ENetOutgoingCommand *outgoingCommand = (ENetOutgoingCommand *) enet_malloc(sizeof(ENetOutgoingCommand));
  3304. if (outgoingCommand == NULL) {
  3305. return NULL;
  3306. }
  3307. outgoingCommand->command = *command;
  3308. outgoingCommand->fragmentOffset = offset;
  3309. outgoingCommand->fragmentLength = length;
  3310. outgoingCommand->packet = packet;
  3311. if (packet != NULL) {
  3312. ++packet->referenceCount;
  3313. }
  3314. enet_peer_setup_outgoing_command(peer, outgoingCommand);
  3315. return outgoingCommand;
  3316. }
  3317. void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer *peer, ENetChannel *channel) {
  3318. ENetListIterator droppedCommand, startCommand, currentCommand;
  3319. for (droppedCommand = startCommand = currentCommand = enet_list_begin(&channel->incomingUnreliableCommands);
  3320. currentCommand != enet_list_end(&channel->incomingUnreliableCommands);
  3321. currentCommand = enet_list_next(currentCommand)
  3322. ) {
  3323. ENetIncomingCommand *incomingCommand = (ENetIncomingCommand *) currentCommand;
  3324. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  3325. continue;
  3326. }
  3327. if (incomingCommand->reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
  3328. if (incomingCommand->fragmentsRemaining <= 0) {
  3329. channel->incomingUnreliableSequenceNumber = incomingCommand->unreliableSequenceNumber;
  3330. continue;
  3331. }
  3332. if (startCommand != currentCommand) {
  3333. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  3334. if (!peer->needsDispatch) {
  3335. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  3336. peer->needsDispatch = 1;
  3337. }
  3338. droppedCommand = currentCommand;
  3339. } else if (droppedCommand != currentCommand) {
  3340. droppedCommand = enet_list_previous(currentCommand);
  3341. }
  3342. } else {
  3343. enet_uint16 reliableWindow = incomingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3344. enet_uint16 currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3345. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  3346. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  3347. }
  3348. if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) {
  3349. break;
  3350. }
  3351. droppedCommand = enet_list_next(currentCommand);
  3352. if (startCommand != currentCommand) {
  3353. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  3354. if (!peer->needsDispatch) {
  3355. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  3356. peer->needsDispatch = 1;
  3357. }
  3358. }
  3359. }
  3360. startCommand = enet_list_next(currentCommand);
  3361. }
  3362. if (startCommand != currentCommand) {
  3363. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  3364. if (!peer->needsDispatch) {
  3365. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  3366. peer->needsDispatch = 1;
  3367. }
  3368. droppedCommand = currentCommand;
  3369. }
  3370. enet_peer_remove_incoming_commands(&channel->incomingUnreliableCommands,enet_list_begin(&channel->incomingUnreliableCommands), droppedCommand);
  3371. }
  3372. void enet_peer_dispatch_incoming_reliable_commands(ENetPeer *peer, ENetChannel *channel) {
  3373. ENetListIterator currentCommand;
  3374. for (currentCommand = enet_list_begin(&channel->incomingReliableCommands);
  3375. currentCommand != enet_list_end(&channel->incomingReliableCommands);
  3376. currentCommand = enet_list_next(currentCommand)
  3377. ) {
  3378. ENetIncomingCommand *incomingCommand = (ENetIncomingCommand *) currentCommand;
  3379. if (incomingCommand->fragmentsRemaining > 0 || incomingCommand->reliableSequenceNumber != (enet_uint16) (channel->incomingReliableSequenceNumber + 1)) {
  3380. break;
  3381. }
  3382. channel->incomingReliableSequenceNumber = incomingCommand->reliableSequenceNumber;
  3383. if (incomingCommand->fragmentCount > 0) {
  3384. channel->incomingReliableSequenceNumber += incomingCommand->fragmentCount - 1;
  3385. }
  3386. }
  3387. if (currentCommand == enet_list_begin(&channel->incomingReliableCommands)) {
  3388. return;
  3389. }
  3390. channel->incomingUnreliableSequenceNumber = 0;
  3391. enet_list_move(enet_list_end(&peer->dispatchedCommands), enet_list_begin(&channel->incomingReliableCommands), enet_list_previous(currentCommand));
  3392. if (!peer->needsDispatch) {
  3393. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  3394. peer->needsDispatch = 1;
  3395. }
  3396. if (!enet_list_empty(&channel->incomingUnreliableCommands)) {
  3397. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  3398. }
  3399. }
  3400. ENetIncomingCommand * enet_peer_queue_incoming_command(ENetPeer *peer, const ENetProtocol *command, const void *data, size_t dataLength, enet_uint32 flags, enet_uint32 fragmentCount) {
  3401. static ENetIncomingCommand dummyCommand;
  3402. ENetChannel *channel = &peer->channels[command->header.channelID];
  3403. enet_uint32 unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
  3404. enet_uint16 reliableWindow, currentWindow;
  3405. ENetIncomingCommand *incomingCommand;
  3406. ENetListIterator currentCommand;
  3407. ENetPacket *packet = NULL;
  3408. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  3409. goto discardCommand;
  3410. }
  3411. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  3412. reliableSequenceNumber = command->header.reliableSequenceNumber;
  3413. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3414. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  3415. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  3416. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  3417. }
  3418. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) {
  3419. goto discardCommand;
  3420. }
  3421. }
  3422. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  3423. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  3424. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  3425. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
  3426. goto discardCommand;
  3427. }
  3428. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands));
  3429. currentCommand != enet_list_end(&channel->incomingReliableCommands);
  3430. currentCommand = enet_list_previous(currentCommand)
  3431. ) {
  3432. incomingCommand = (ENetIncomingCommand *) currentCommand;
  3433. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  3434. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  3435. continue;
  3436. }
  3437. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  3438. break;
  3439. }
  3440. if (incomingCommand->reliableSequenceNumber <= reliableSequenceNumber) {
  3441. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber) {
  3442. break;
  3443. }
  3444. goto discardCommand;
  3445. }
  3446. }
  3447. break;
  3448. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  3449. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  3450. unreliableSequenceNumber = ENET_NET_TO_HOST_16(command->sendUnreliable.unreliableSequenceNumber);
  3451. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && unreliableSequenceNumber <= channel->incomingUnreliableSequenceNumber) {
  3452. goto discardCommand;
  3453. }
  3454. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands));
  3455. currentCommand != enet_list_end(&channel->incomingUnreliableCommands);
  3456. currentCommand = enet_list_previous(currentCommand)
  3457. ) {
  3458. incomingCommand = (ENetIncomingCommand *) currentCommand;
  3459. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  3460. continue;
  3461. }
  3462. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  3463. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber) {
  3464. continue;
  3465. }
  3466. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  3467. break;
  3468. }
  3469. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber) {
  3470. break;
  3471. }
  3472. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber) {
  3473. continue;
  3474. }
  3475. if (incomingCommand->unreliableSequenceNumber <= unreliableSequenceNumber) {
  3476. if (incomingCommand->unreliableSequenceNumber < unreliableSequenceNumber) {
  3477. break;
  3478. }
  3479. goto discardCommand;
  3480. }
  3481. }
  3482. break;
  3483. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  3484. currentCommand = enet_list_end(&channel->incomingUnreliableCommands);
  3485. break;
  3486. default:
  3487. goto discardCommand;
  3488. }
  3489. if (peer->totalWaitingData >= peer->host->maximumWaitingData) {
  3490. goto notifyError;
  3491. }
  3492. packet = callbacks.packet_create(data, dataLength, flags);
  3493. if (packet == NULL) {
  3494. goto notifyError;
  3495. }
  3496. incomingCommand = (ENetIncomingCommand *) enet_malloc(sizeof(ENetIncomingCommand));
  3497. if (incomingCommand == NULL) {
  3498. goto notifyError;
  3499. }
  3500. incomingCommand->reliableSequenceNumber = command->header.reliableSequenceNumber;
  3501. incomingCommand->unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF;
  3502. incomingCommand->command = *command;
  3503. incomingCommand->fragmentCount = fragmentCount;
  3504. incomingCommand->fragmentsRemaining = fragmentCount;
  3505. incomingCommand->packet = packet;
  3506. incomingCommand->fragments = NULL;
  3507. if (fragmentCount > 0) {
  3508. if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) {
  3509. incomingCommand->fragments = (enet_uint32 *) enet_malloc((fragmentCount + 31) / 32 * sizeof(enet_uint32));
  3510. }
  3511. if (incomingCommand->fragments == NULL) {
  3512. enet_free(incomingCommand);
  3513. goto notifyError;
  3514. }
  3515. memset(incomingCommand->fragments, 0, (fragmentCount + 31) / 32 * sizeof(enet_uint32));
  3516. }
  3517. if (packet != NULL) {
  3518. ++packet->referenceCount;
  3519. peer->totalWaitingData += packet->dataLength;
  3520. }
  3521. enet_list_insert(enet_list_next(currentCommand), incomingCommand);
  3522. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  3523. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  3524. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  3525. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  3526. break;
  3527. default:
  3528. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  3529. break;
  3530. }
  3531. return incomingCommand;
  3532. discardCommand:
  3533. if (fragmentCount > 0) {
  3534. goto notifyError;
  3535. }
  3536. if (packet != NULL && packet->referenceCount == 0) {
  3537. callbacks.packet_destroy(packet);
  3538. }
  3539. return &dummyCommand;
  3540. notifyError:
  3541. if (packet != NULL && packet->referenceCount == 0) {
  3542. callbacks.packet_destroy(packet);
  3543. }
  3544. return NULL;
  3545. } /* enet_peer_queue_incoming_command */
  3546. // =======================================================================//
  3547. // !
  3548. // ! Host
  3549. // !
  3550. // =======================================================================//
  3551. /** Creates a host for communicating to peers.
  3552. *
  3553. * @param address the address at which other peers may connect to this host. If NULL, then no peers may connect to the host.
  3554. * @param peerCount the maximum number of peers that should be allocated for the host.
  3555. * @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
  3556. * @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
  3557. * @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
  3558. *
  3559. * @returns the host on success and NULL on failure
  3560. *
  3561. * @remarks ENet will strategically drop packets on specific sides of a connection between hosts
  3562. * to ensure the host's bandwidth is not overwhelmed. The bandwidth parameters also determine
  3563. * the window size of a connection which limits the amount of reliable packets that may be in transit
  3564. * at any given time.
  3565. */
  3566. ENetHost * enet_host_create(const ENetAddress *address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) {
  3567. ENetHost *host;
  3568. ENetPeer *currentPeer;
  3569. if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  3570. return NULL;
  3571. }
  3572. host = (ENetHost *) enet_malloc(sizeof(ENetHost));
  3573. if (host == NULL) { return NULL; }
  3574. memset(host, 0, sizeof(ENetHost));
  3575. host->peers = (ENetPeer *) enet_malloc(peerCount * sizeof(ENetPeer));
  3576. if (host->peers == NULL) {
  3577. enet_free(host);
  3578. return NULL;
  3579. }
  3580. memset(host->peers, 0, peerCount * sizeof(ENetPeer));
  3581. host->socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
  3582. if (host->socket != ENET_SOCKET_NULL) {
  3583. enet_socket_set_option (host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
  3584. }
  3585. if (host->socket == ENET_SOCKET_NULL || (address != NULL && enet_socket_bind(host->socket, address) < 0)) {
  3586. if (host->socket != ENET_SOCKET_NULL) {
  3587. enet_socket_destroy(host->socket);
  3588. }
  3589. enet_free(host->peers);
  3590. enet_free(host);
  3591. return NULL;
  3592. }
  3593. enet_socket_set_option(host->socket, ENET_SOCKOPT_NONBLOCK, 1);
  3594. enet_socket_set_option(host->socket, ENET_SOCKOPT_BROADCAST, 1);
  3595. enet_socket_set_option(host->socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE);
  3596. enet_socket_set_option(host->socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE);
  3597. enet_socket_set_option(host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
  3598. if (address != NULL && enet_socket_get_address(host->socket, &host->address) < 0) {
  3599. host->address = *address;
  3600. }
  3601. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) {
  3602. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3603. } else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) {
  3604. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3605. }
  3606. host->randomSeed = (enet_uint32) (size_t) host;
  3607. host->randomSeed += enet_host_random_seed();
  3608. host->randomSeed = (host->randomSeed << 16) | (host->randomSeed >> 16);
  3609. host->channelLimit = channelLimit;
  3610. host->incomingBandwidth = incomingBandwidth;
  3611. host->outgoingBandwidth = outgoingBandwidth;
  3612. host->bandwidthThrottleEpoch = 0;
  3613. host->recalculateBandwidthLimits = 0;
  3614. host->mtu = ENET_HOST_DEFAULT_MTU;
  3615. host->peerCount = peerCount;
  3616. host->commandCount = 0;
  3617. host->bufferCount = 0;
  3618. host->checksum = NULL;
  3619. host->receivedAddress.host = ENET_HOST_ANY;
  3620. host->receivedAddress.port = 0;
  3621. host->receivedData = NULL;
  3622. host->receivedDataLength = 0;
  3623. host->totalSentData = 0;
  3624. host->totalSentPackets = 0;
  3625. host->totalReceivedData = 0;
  3626. host->totalReceivedPackets = 0;
  3627. host->connectedPeers = 0;
  3628. host->bandwidthLimitedPeers = 0;
  3629. host->duplicatePeers = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  3630. host->maximumPacketSize = ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE;
  3631. host->maximumWaitingData = ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA;
  3632. host->compressor.context = NULL;
  3633. host->compressor.compress = NULL;
  3634. host->compressor.decompress = NULL;
  3635. host->compressor.destroy = NULL;
  3636. host->intercept = NULL;
  3637. enet_list_clear(&host->dispatchQueue);
  3638. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3639. currentPeer->host = host;
  3640. currentPeer->incomingPeerID = currentPeer - host->peers;
  3641. currentPeer->outgoingSessionID = currentPeer->incomingSessionID = 0xFF;
  3642. currentPeer->data = NULL;
  3643. enet_list_clear(&currentPeer->acknowledgements);
  3644. enet_list_clear(&currentPeer->sentReliableCommands);
  3645. enet_list_clear(&currentPeer->sentUnreliableCommands);
  3646. enet_list_clear(&currentPeer->outgoingReliableCommands);
  3647. enet_list_clear(&currentPeer->outgoingUnreliableCommands);
  3648. enet_list_clear(&currentPeer->dispatchedCommands);
  3649. enet_peer_reset(currentPeer);
  3650. }
  3651. return host;
  3652. } /* enet_host_create */
  3653. /** Destroys the host and all resources associated with it.
  3654. * @param host pointer to the host to destroy
  3655. */
  3656. void enet_host_destroy(ENetHost *host) {
  3657. ENetPeer *currentPeer;
  3658. if (host == NULL) {
  3659. return;
  3660. }
  3661. enet_socket_destroy(host->socket);
  3662. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3663. enet_peer_reset(currentPeer);
  3664. }
  3665. if (host->compressor.context != NULL && host->compressor.destroy) {
  3666. (*host->compressor.destroy)(host->compressor.context);
  3667. }
  3668. enet_free(host->peers);
  3669. enet_free(host);
  3670. }
  3671. /** Initiates a connection to a foreign host.
  3672. * @param host host seeking the connection
  3673. * @param address destination for the connection
  3674. * @param channelCount number of channels to allocate
  3675. * @param data user data supplied to the receiving host
  3676. * @returns a peer representing the foreign host on success, NULL on failure
  3677. * @remarks The peer returned will have not completed the connection until enet_host_service()
  3678. * notifies of an ENET_EVENT_TYPE_CONNECT event for the peer.
  3679. */
  3680. ENetPeer * enet_host_connect(ENetHost *host, const ENetAddress *address, size_t channelCount, enet_uint32 data) {
  3681. ENetPeer *currentPeer;
  3682. ENetChannel *channel;
  3683. ENetProtocol command;
  3684. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) {
  3685. channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3686. } else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) {
  3687. channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3688. }
  3689. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3690. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
  3691. break;
  3692. }
  3693. }
  3694. if (currentPeer >= &host->peers[host->peerCount]) {
  3695. return NULL;
  3696. }
  3697. currentPeer->channels = (ENetChannel *) enet_malloc(channelCount * sizeof(ENetChannel));
  3698. if (currentPeer->channels == NULL) {
  3699. return NULL;
  3700. }
  3701. currentPeer->channelCount = channelCount;
  3702. currentPeer->state = ENET_PEER_STATE_CONNECTING;
  3703. currentPeer->address = *address;
  3704. currentPeer->connectID = ++host->randomSeed;
  3705. if (host->outgoingBandwidth == 0) {
  3706. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3707. } else {
  3708. currentPeer->windowSize = (host->outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3709. }
  3710. if (currentPeer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) {
  3711. currentPeer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3712. } else if (currentPeer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) {
  3713. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3714. }
  3715. for (channel = currentPeer->channels; channel < &currentPeer->channels[channelCount]; ++channel) {
  3716. channel->outgoingReliableSequenceNumber = 0;
  3717. channel->outgoingUnreliableSequenceNumber = 0;
  3718. channel->incomingReliableSequenceNumber = 0;
  3719. channel->incomingUnreliableSequenceNumber = 0;
  3720. enet_list_clear(&channel->incomingReliableCommands);
  3721. enet_list_clear(&channel->incomingUnreliableCommands);
  3722. channel->usedReliableWindows = 0;
  3723. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  3724. }
  3725. command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3726. command.header.channelID = 0xFF;
  3727. command.connect.outgoingPeerID = ENET_HOST_TO_NET_16(currentPeer->incomingPeerID);
  3728. command.connect.incomingSessionID = currentPeer->incomingSessionID;
  3729. command.connect.outgoingSessionID = currentPeer->outgoingSessionID;
  3730. command.connect.mtu = ENET_HOST_TO_NET_32(currentPeer->mtu);
  3731. command.connect.windowSize = ENET_HOST_TO_NET_32(currentPeer->windowSize);
  3732. command.connect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  3733. command.connect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  3734. command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3735. command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32(currentPeer->packetThrottleInterval);
  3736. command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleAcceleration);
  3737. command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleDeceleration);
  3738. command.connect.connectID = currentPeer->connectID;
  3739. command.connect.data = ENET_HOST_TO_NET_32(data);
  3740. enet_peer_queue_outgoing_command(currentPeer, &command, NULL, 0, 0);
  3741. return currentPeer;
  3742. } /* enet_host_connect */
  3743. /** Queues a packet to be sent to all peers associated with the host.
  3744. * @param host host on which to broadcast the packet
  3745. * @param channelID channel on which to broadcast
  3746. * @param packet packet to broadcast
  3747. */
  3748. void enet_host_broadcast(ENetHost *host, enet_uint8 channelID, ENetPacket *packet) {
  3749. ENetPeer *currentPeer;
  3750. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3751. if (currentPeer->state != ENET_PEER_STATE_CONNECTED) {
  3752. continue;
  3753. }
  3754. enet_peer_send(currentPeer, channelID, packet);
  3755. }
  3756. if (packet->referenceCount == 0) {
  3757. callbacks.packet_destroy(packet);
  3758. }
  3759. }
  3760. /** Sends raw data to specified address. Useful when you want to send unconnected data using host's socket.
  3761. * @param host host sending data
  3762. * @param address destination address
  3763. * @param data data pointer
  3764. * @param dataLength length of data to send
  3765. * @retval >=0 bytes sent
  3766. * @retval <0 error
  3767. * @sa enet_socket_send
  3768. */
  3769. int enet_host_send_raw(ENetHost *host, const ENetAddress* address, enet_uint8* data, size_t dataLength) {
  3770. ENetBuffer buffer;
  3771. buffer.data = data;
  3772. buffer.dataLength = dataLength;
  3773. return enet_socket_send(host->socket, address, &buffer, 1);
  3774. }
  3775. /** Sends raw data to specified address with extended arguments. Allows to send only part of data, handy for other programming languages.
  3776. * I.e. if you have data =- { 0, 1, 2, 3 } and call function as enet_host_send_raw_ex(data, 1, 2) then it will skip 1 byte and send 2 bytes { 1, 2 }.
  3777. * @param host host sending data
  3778. * @param address destination address
  3779. * @param data data pointer
  3780. * @param skipBytes number of bytes to skip from start of data
  3781. * @param bytesToSend number of bytes to send
  3782. * @retval >=0 bytes sent
  3783. * @retval <0 error
  3784. * @sa enet_socket_send
  3785. */
  3786. int enet_host_send_raw_ex(ENetHost *host, const ENetAddress* address, enet_uint8* data, size_t skipBytes, size_t bytesToSend) {
  3787. ENetBuffer buffer;
  3788. buffer.data = data + skipBytes;
  3789. buffer.dataLength = bytesToSend;
  3790. return enet_socket_send(host->socket, address, &buffer, 1);
  3791. }
  3792. /** Sets intercept callback for the host.
  3793. * @param host host to set a callback
  3794. * @param callback intercept callback
  3795. */
  3796. void enet_host_set_intercept(ENetHost *host, const ENetInterceptCallback callback) {
  3797. host->intercept = callback;
  3798. }
  3799. /** Sets the packet compressor the host should use to compress and decompress packets.
  3800. * @param host host to enable or disable compression for
  3801. * @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled
  3802. */
  3803. void enet_host_compress(ENetHost *host, const ENetCompressor *compressor) {
  3804. if (host->compressor.context != NULL && host->compressor.destroy) {
  3805. (*host->compressor.destroy)(host->compressor.context);
  3806. }
  3807. if (compressor) {
  3808. host->compressor = *compressor;
  3809. } else {
  3810. host->compressor.context = NULL;
  3811. }
  3812. }
  3813. /** Limits the maximum allowed channels of future incoming connections.
  3814. * @param host host to limit
  3815. * @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
  3816. */
  3817. void enet_host_channel_limit(ENetHost *host, size_t channelLimit) {
  3818. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) {
  3819. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3820. } else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) {
  3821. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3822. }
  3823. host->channelLimit = channelLimit;
  3824. }
  3825. /** Adjusts the bandwidth limits of a host.
  3826. * @param host host to adjust
  3827. * @param incomingBandwidth new incoming bandwidth
  3828. * @param outgoingBandwidth new outgoing bandwidth
  3829. * @remarks the incoming and outgoing bandwidth parameters are identical in function to those
  3830. * specified in enet_host_create().
  3831. */
  3832. void enet_host_bandwidth_limit(ENetHost *host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) {
  3833. host->incomingBandwidth = incomingBandwidth;
  3834. host->outgoingBandwidth = outgoingBandwidth;
  3835. host->recalculateBandwidthLimits = 1;
  3836. }
  3837. void enet_host_bandwidth_throttle(ENetHost *host) {
  3838. enet_uint32 timeCurrent = enet_time_get();
  3839. enet_uint32 elapsedTime = timeCurrent - host->bandwidthThrottleEpoch;
  3840. enet_uint32 peersRemaining = (enet_uint32) host->connectedPeers;
  3841. enet_uint32 dataTotal = ~0;
  3842. enet_uint32 bandwidth = ~0;
  3843. enet_uint32 throttle = 0;
  3844. enet_uint32 bandwidthLimit = 0;
  3845. int needsAdjustment = host->bandwidthLimitedPeers > 0 ? 1 : 0;
  3846. ENetPeer *peer;
  3847. ENetProtocol command;
  3848. if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) {
  3849. return;
  3850. }
  3851. if (host->outgoingBandwidth == 0 && host->incomingBandwidth == 0) {
  3852. return;
  3853. }
  3854. host->bandwidthThrottleEpoch = timeCurrent;
  3855. if (peersRemaining == 0) {
  3856. return;
  3857. }
  3858. if (host->outgoingBandwidth != 0) {
  3859. dataTotal = 0;
  3860. bandwidth = (host->outgoingBandwidth * elapsedTime) / 1000;
  3861. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3862. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  3863. continue;
  3864. }
  3865. dataTotal += peer->outgoingDataTotal;
  3866. }
  3867. }
  3868. while (peersRemaining > 0 && needsAdjustment != 0) {
  3869. needsAdjustment = 0;
  3870. if (dataTotal <= bandwidth) {
  3871. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3872. } else {
  3873. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3874. }
  3875. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3876. enet_uint32 peerBandwidth;
  3877. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) ||
  3878. peer->incomingBandwidth == 0 ||
  3879. peer->outgoingBandwidthThrottleEpoch == timeCurrent
  3880. ) {
  3881. continue;
  3882. }
  3883. peerBandwidth = (peer->incomingBandwidth * elapsedTime) / 1000;
  3884. if ((throttle * peer->outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth) {
  3885. continue;
  3886. }
  3887. peer->packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer->outgoingDataTotal;
  3888. if (peer->packetThrottleLimit == 0) {
  3889. peer->packetThrottleLimit = 1;
  3890. }
  3891. if (peer->packetThrottle > peer->packetThrottleLimit) {
  3892. peer->packetThrottle = peer->packetThrottleLimit;
  3893. }
  3894. peer->outgoingBandwidthThrottleEpoch = timeCurrent;
  3895. peer->incomingDataTotal = 0;
  3896. peer->outgoingDataTotal = 0;
  3897. needsAdjustment = 1;
  3898. --peersRemaining;
  3899. bandwidth -= peerBandwidth;
  3900. dataTotal -= peerBandwidth;
  3901. }
  3902. }
  3903. if (peersRemaining > 0) {
  3904. if (dataTotal <= bandwidth) {
  3905. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3906. } else {
  3907. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3908. }
  3909. for (peer = host->peers;
  3910. peer < &host->peers[host->peerCount];
  3911. ++peer)
  3912. {
  3913. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->outgoingBandwidthThrottleEpoch == timeCurrent) {
  3914. continue;
  3915. }
  3916. peer->packetThrottleLimit = throttle;
  3917. if (peer->packetThrottle > peer->packetThrottleLimit) {
  3918. peer->packetThrottle = peer->packetThrottleLimit;
  3919. }
  3920. peer->incomingDataTotal = 0;
  3921. peer->outgoingDataTotal = 0;
  3922. }
  3923. }
  3924. if (host->recalculateBandwidthLimits) {
  3925. host->recalculateBandwidthLimits = 0;
  3926. peersRemaining = (enet_uint32) host->connectedPeers;
  3927. bandwidth = host->incomingBandwidth;
  3928. needsAdjustment = 1;
  3929. if (bandwidth == 0) {
  3930. bandwidthLimit = 0;
  3931. } else {
  3932. while (peersRemaining > 0 && needsAdjustment != 0) {
  3933. needsAdjustment = 0;
  3934. bandwidthLimit = bandwidth / peersRemaining;
  3935. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3936. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) ||
  3937. peer->incomingBandwidthThrottleEpoch == timeCurrent
  3938. ) {
  3939. continue;
  3940. }
  3941. if (peer->outgoingBandwidth > 0 && peer->outgoingBandwidth >= bandwidthLimit) {
  3942. continue;
  3943. }
  3944. peer->incomingBandwidthThrottleEpoch = timeCurrent;
  3945. needsAdjustment = 1;
  3946. --peersRemaining;
  3947. bandwidth -= peer->outgoingBandwidth;
  3948. }
  3949. }
  3950. }
  3951. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3952. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  3953. continue;
  3954. }
  3955. command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3956. command.header.channelID = 0xFF;
  3957. command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3958. if (peer->incomingBandwidthThrottleEpoch == timeCurrent) {
  3959. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(peer->outgoingBandwidth);
  3960. } else {
  3961. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(bandwidthLimit);
  3962. }
  3963. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3964. }
  3965. }
  3966. } /* enet_host_bandwidth_throttle */
  3967. // =======================================================================//
  3968. // !
  3969. // ! Time
  3970. // !
  3971. // =======================================================================//
  3972. #ifdef _WIN32
  3973. static LARGE_INTEGER getFILETIMEoffset() {
  3974. SYSTEMTIME s;
  3975. FILETIME f;
  3976. LARGE_INTEGER t;
  3977. s.wYear = 1970;
  3978. s.wMonth = 1;
  3979. s.wDay = 1;
  3980. s.wHour = 0;
  3981. s.wMinute = 0;
  3982. s.wSecond = 0;
  3983. s.wMilliseconds = 0;
  3984. SystemTimeToFileTime(&s, &f);
  3985. t.QuadPart = f.dwHighDateTime;
  3986. t.QuadPart <<= 32;
  3987. t.QuadPart |= f.dwLowDateTime;
  3988. return (t);
  3989. }
  3990. int clock_gettime(int X, struct timespec *tv) {
  3991. LARGE_INTEGER t;
  3992. FILETIME f;
  3993. double microseconds;
  3994. static LARGE_INTEGER offset;
  3995. static double frequencyToMicroseconds;
  3996. static int initialized = 0;
  3997. static BOOL usePerformanceCounter = 0;
  3998. if (!initialized) {
  3999. LARGE_INTEGER performanceFrequency;
  4000. initialized = 1;
  4001. usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
  4002. if (usePerformanceCounter) {
  4003. QueryPerformanceCounter(&offset);
  4004. frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
  4005. } else {
  4006. offset = getFILETIMEoffset();
  4007. frequencyToMicroseconds = 10.;
  4008. }
  4009. }
  4010. if (usePerformanceCounter) {
  4011. QueryPerformanceCounter(&t);
  4012. } else {
  4013. GetSystemTimeAsFileTime(&f);
  4014. t.QuadPart = f.dwHighDateTime;
  4015. t.QuadPart <<= 32;
  4016. t.QuadPart |= f.dwLowDateTime;
  4017. }
  4018. t.QuadPart -= offset.QuadPart;
  4019. microseconds = (double)t.QuadPart / frequencyToMicroseconds;
  4020. t.QuadPart = (LONGLONG)microseconds;
  4021. tv->tv_sec = (long)(t.QuadPart / 1000000);
  4022. tv->tv_nsec = t.QuadPart % 1000000 * 1000;
  4023. return (0);
  4024. }
  4025. #elif __APPLE__ && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
  4026. #define CLOCK_MONOTONIC 0
  4027. int clock_gettime(int X, struct timespec *ts) {
  4028. clock_serv_t cclock;
  4029. mach_timespec_t mts;
  4030. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  4031. clock_get_time(cclock, &mts);
  4032. mach_port_deallocate(mach_task_self(), cclock);
  4033. ts->tv_sec = mts.tv_sec;
  4034. ts->tv_nsec = mts.tv_nsec;
  4035. return 0;
  4036. }
  4037. #endif
  4038. enet_uint32 enet_time_get() {
  4039. // TODO enet uses 32 bit timestamps. We should modify it to use
  4040. // 64 bit timestamps, but this is not trivial since we'd end up
  4041. // changing half the structs in enet. For now, retain 32 bits, but
  4042. // use an offset so we don't run out of bits. Basically, the first
  4043. // call of enet_time_get() will always return 1, and follow-up calls
  4044. // indicate elapsed time since the first call.
  4045. //
  4046. // Note that we don't want to return 0 from the first call, in case
  4047. // some part of enet uses 0 as a special value (meaning time not set
  4048. // for example).
  4049. static uint64_t start_time_ns = 0;
  4050. struct timespec ts;
  4051. #if defined(CLOCK_MONOTONIC_RAW)
  4052. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  4053. #else
  4054. clock_gettime(CLOCK_MONOTONIC, &ts);
  4055. #endif
  4056. static const uint64_t ns_in_s = 1000 * 1000 * 1000;
  4057. static const uint64_t ns_in_ms = 1000 * 1000;
  4058. uint64_t current_time_ns = ts.tv_nsec + (uint64_t)ts.tv_sec * ns_in_s;
  4059. // Most of the time we just want to atomically read the start time. We
  4060. // could just use a single CAS instruction instead of this if, but it
  4061. // would be slower in the average case.
  4062. //
  4063. // Note that statics are auto-initialized to zero, and starting a thread
  4064. // implies a memory barrier. So we know that whatever thread calls this,
  4065. // it correctly sees the start_time_ns as 0 initially.
  4066. uint64_t offset_ns = ENET_ATOMIC_READ(&start_time_ns);
  4067. if (offset_ns == 0) {
  4068. // We still need to CAS, since two different threads can get here
  4069. // at the same time.
  4070. //
  4071. // We assume that current_time_ns is > 1ms.
  4072. //
  4073. // Set the value of the start_time_ns, such that the first timestamp
  4074. // is at 1ms. This ensures 0 remains a special value.
  4075. uint64_t want_value = current_time_ns - 1 * ns_in_ms;
  4076. uint64_t old_value = ENET_ATOMIC_CAS(&start_time_ns, 0, want_value);
  4077. offset_ns = old_value == 0 ? want_value : old_value;
  4078. }
  4079. uint64_t result_in_ns = current_time_ns - offset_ns;
  4080. return (enet_uint32)(result_in_ns / ns_in_ms);
  4081. }
  4082. inline void enet_inaddr_map4to6(struct in_addr in, struct in6_addr *out)
  4083. {
  4084. if (in.s_addr == 0x00000000) { /* 0.0.0.0 */
  4085. *out = enet_v6_anyaddr;
  4086. } else if (in.s_addr == 0xFFFFFFFF) { /* 255.255.255.255 */
  4087. *out = enet_v6_noaddr;
  4088. } else {
  4089. *out = enet_v4_anyaddr;
  4090. out->s6_addr[10] = 0xFF;
  4091. out->s6_addr[11] = 0xFF;
  4092. out->s6_addr[12] = ((uint8_t *)&in.s_addr)[0];
  4093. out->s6_addr[13] = ((uint8_t *)&in.s_addr)[1];
  4094. out->s6_addr[14] = ((uint8_t *)&in.s_addr)[2];
  4095. out->s6_addr[15] = ((uint8_t *)&in.s_addr)[3];
  4096. }
  4097. }
  4098. inline void enet_inaddr_map6to4(const struct in6_addr *in, struct in_addr *out)
  4099. {
  4100. memset(out, 0, sizeof(struct in_addr));
  4101. ((uint8_t *)&out->s_addr)[0] = in->s6_addr[12];
  4102. ((uint8_t *)&out->s_addr)[1] = in->s6_addr[13];
  4103. ((uint8_t *)&out->s_addr)[2] = in->s6_addr[14];
  4104. ((uint8_t *)&out->s_addr)[3] = in->s6_addr[15];
  4105. }
  4106. int enet_in6addr_lookup_host(const char *name, bool nodns, struct in6_addr *out) {
  4107. struct addrinfo hints, *resultList = NULL, *result = NULL;
  4108. memset(&hints, 0, sizeof(hints));
  4109. hints.ai_family = AF_UNSPEC;
  4110. if (nodns)
  4111. {
  4112. hints.ai_flags = AI_NUMERICHOST; /* prevent actual DNS lookups! */
  4113. }
  4114. if (getaddrinfo(name, NULL, &hints, &resultList) != 0) {
  4115. if (resultList != NULL) {
  4116. freeaddrinfo(resultList);
  4117. }
  4118. return -1;
  4119. }
  4120. for (result = resultList; result != NULL; result = result->ai_next) {
  4121. if (result->ai_addr != NULL) {
  4122. if (result->ai_family == AF_INET || (result->ai_family == AF_UNSPEC && result->ai_addrlen == sizeof(struct sockaddr_in))) {
  4123. enet_inaddr_map4to6(((struct sockaddr_in*)result->ai_addr)->sin_addr, out);
  4124. if (resultList != NULL) {
  4125. freeaddrinfo(resultList);
  4126. }
  4127. return 0;
  4128. } else if (result->ai_family == AF_INET6 || (result->ai_family == AF_UNSPEC && result->ai_addrlen == sizeof(struct sockaddr_in6))) {
  4129. memcpy(out, &((struct sockaddr_in6*)result->ai_addr)->sin6_addr, sizeof(struct sockaddr_in6));
  4130. if (resultList != NULL) {
  4131. freeaddrinfo(resultList);
  4132. }
  4133. return 0;
  4134. }
  4135. }
  4136. }
  4137. if (resultList != NULL) {
  4138. freeaddrinfo(resultList);
  4139. }
  4140. return -1;
  4141. }
  4142. int enet_address_set_host_ip(ENetAddress *address, const char *name) {
  4143. return enet_in6addr_lookup_host(name, true, &address->host);
  4144. }
  4145. int enet_address_set_host(ENetAddress *address, const char *name) {
  4146. return enet_in6addr_lookup_host(name, false, &address->host);
  4147. }
  4148. int enet_address_get_host_ip(const ENetAddress *address, char *name, size_t nameLength) {
  4149. if (IN6_IS_ADDR_V4MAPPED(&address->host))
  4150. {
  4151. struct in_addr buf;
  4152. enet_inaddr_map6to4(&address->host, &buf);
  4153. if (inet_ntop(AF_INET, &buf, name, nameLength) == NULL) {
  4154. return -1;
  4155. }
  4156. }
  4157. else
  4158. {
  4159. if (inet_ntop(AF_INET6, &address->host, name, nameLength) == NULL) {
  4160. return -1;
  4161. }
  4162. }
  4163. return 0;
  4164. }
  4165. // =======================================================================//
  4166. // !
  4167. // ! Platform Specific (Unix)
  4168. // !
  4169. // =======================================================================//
  4170. #ifndef _WIN32
  4171. #if defined(__MINGW32__) && defined(ENET_MINGW_COMPAT)
  4172. // inet_ntop/inet_pton for MinGW from http://mingw-users.1079350.n2.nabble.com/IPv6-getaddrinfo-amp-inet-ntop-td5891996.html
  4173. const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) {
  4174. if (af == AF_INET) {
  4175. struct sockaddr_in in;
  4176. memset(&in, 0, sizeof(in));
  4177. in.sin_family = AF_INET;
  4178. memcpy(&in.sin_addr, src, sizeof(struct in_addr));
  4179. getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
  4180. return dst;
  4181. }
  4182. else if (af == AF_INET6) {
  4183. struct sockaddr_in6 in;
  4184. memset(&in, 0, sizeof(in));
  4185. in.sin6_family = AF_INET6;
  4186. memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
  4187. getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
  4188. return dst;
  4189. }
  4190. return NULL;
  4191. }
  4192. #define NS_INADDRSZ 4
  4193. #define NS_IN6ADDRSZ 16
  4194. #define NS_INT16SZ 2
  4195. int inet_pton4(const char *src, char *dst) {
  4196. uint8_t tmp[NS_INADDRSZ], *tp;
  4197. int saw_digit = 0;
  4198. int octets = 0;
  4199. *(tp = tmp) = 0;
  4200. int ch;
  4201. while ((ch = *src++) != '\0')
  4202. {
  4203. if (ch >= '0' && ch <= '9')
  4204. {
  4205. uint32_t n = *tp * 10 + (ch - '0');
  4206. if (saw_digit && *tp == 0)
  4207. return 0;
  4208. if (n > 255)
  4209. return 0;
  4210. *tp = n;
  4211. if (!saw_digit)
  4212. {
  4213. if (++octets > 4)
  4214. return 0;
  4215. saw_digit = 1;
  4216. }
  4217. }
  4218. else if (ch == '.' && saw_digit)
  4219. {
  4220. if (octets == 4)
  4221. return 0;
  4222. *++tp = 0;
  4223. saw_digit = 0;
  4224. }
  4225. else
  4226. return 0;
  4227. }
  4228. if (octets < 4)
  4229. return 0;
  4230. memcpy(dst, tmp, NS_INADDRSZ);
  4231. return 1;
  4232. }
  4233. int inet_pton6(const char *src, char *dst) {
  4234. static const char xdigits[] = "0123456789abcdef";
  4235. uint8_t tmp[NS_IN6ADDRSZ];
  4236. uint8_t *tp = (uint8_t*) memset(tmp, '\0', NS_IN6ADDRSZ);
  4237. uint8_t *endp = tp + NS_IN6ADDRSZ;
  4238. uint8_t *colonp = NULL;
  4239. /* Leading :: requires some special handling. */
  4240. if (*src == ':')
  4241. {
  4242. if (*++src != ':')
  4243. return 0;
  4244. }
  4245. const char *curtok = src;
  4246. int saw_xdigit = 0;
  4247. uint32_t val = 0;
  4248. int ch;
  4249. while ((ch = tolower(*src++)) != '\0')
  4250. {
  4251. const char *pch = strchr(xdigits, ch);
  4252. if (pch != NULL)
  4253. {
  4254. val <<= 4;
  4255. val |= (pch - xdigits);
  4256. if (val > 0xffff)
  4257. return 0;
  4258. saw_xdigit = 1;
  4259. continue;
  4260. }
  4261. if (ch == ':')
  4262. {
  4263. curtok = src;
  4264. if (!saw_xdigit)
  4265. {
  4266. if (colonp)
  4267. return 0;
  4268. colonp = tp;
  4269. continue;
  4270. }
  4271. else if (*src == '\0')
  4272. {
  4273. return 0;
  4274. }
  4275. if (tp + NS_INT16SZ > endp)
  4276. return 0;
  4277. *tp++ = (uint8_t) (val >> 8) & 0xff;
  4278. *tp++ = (uint8_t) val & 0xff;
  4279. saw_xdigit = 0;
  4280. val = 0;
  4281. continue;
  4282. }
  4283. if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
  4284. inet_pton4(curtok, (char*) tp) > 0)
  4285. {
  4286. tp += NS_INADDRSZ;
  4287. saw_xdigit = 0;
  4288. break; /* '\0' was seen by inet_pton4(). */
  4289. }
  4290. return 0;
  4291. }
  4292. if (saw_xdigit)
  4293. {
  4294. if (tp + NS_INT16SZ > endp)
  4295. return 0;
  4296. *tp++ = (uint8_t) (val >> 8) & 0xff;
  4297. *tp++ = (uint8_t) val & 0xff;
  4298. }
  4299. if (colonp != NULL)
  4300. {
  4301. /*
  4302. * Since some memmove()'s erroneously fail to handle
  4303. * overlapping regions, we'll do the shift by hand.
  4304. */
  4305. const int n = tp - colonp;
  4306. if (tp == endp)
  4307. return 0;
  4308. for (int i = 1; i <= n; i++)
  4309. {
  4310. endp[-i] = colonp[n - i];
  4311. colonp[n - i] = 0;
  4312. }
  4313. tp = endp;
  4314. }
  4315. if (tp != endp)
  4316. return 0;
  4317. memcpy(dst, tmp, NS_IN6ADDRSZ);
  4318. return 1;
  4319. }
  4320. int inet_pton(int af, const char *src, struct in6_addr *dst) {
  4321. switch (af)
  4322. {
  4323. case AF_INET:
  4324. return inet_pton4(src, (char *)dst);
  4325. case AF_INET6:
  4326. return inet_pton6(src, (char *)dst);
  4327. default:
  4328. return -1;
  4329. }
  4330. }
  4331. #endif // __MINGW__
  4332. int enet_initialize(void) {
  4333. return 0;
  4334. }
  4335. void enet_deinitialize(void) {}
  4336. enet_uint64 enet_host_random_seed(void) {
  4337. return (enet_uint64) time(NULL);
  4338. }
  4339. int enet_address_get_host(const ENetAddress *address, char *name, size_t nameLength) {
  4340. struct sockaddr_in6 sin;
  4341. int err;
  4342. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4343. sin.sin6_family = AF_INET6;
  4344. sin.sin6_port = ENET_HOST_TO_NET_16 (address->port);
  4345. sin.sin6_addr = address->host;
  4346. sin.sin6_scope_id = address->sin6_scope_id;
  4347. err = getnameinfo((struct sockaddr *) &sin, sizeof(sin), name, nameLength, NULL, 0, NI_NAMEREQD);
  4348. if (!err) {
  4349. if (name != NULL && nameLength > 0 && !memchr(name, '\0', nameLength)) {
  4350. return -1;
  4351. }
  4352. return 0;
  4353. }
  4354. if (err != EAI_NONAME) {
  4355. return -1;
  4356. }
  4357. return enet_address_get_host_ip(address, name, nameLength);
  4358. } /* enet_address_get_host */
  4359. int enet_socket_bind(ENetSocket socket, const ENetAddress *address) {
  4360. struct sockaddr_in6 sin;
  4361. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4362. sin.sin6_family = AF_INET6;
  4363. if (address != NULL) {
  4364. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  4365. sin.sin6_addr = address->host;
  4366. sin.sin6_scope_id = address->sin6_scope_id;
  4367. } else {
  4368. sin.sin6_port = 0;
  4369. sin.sin6_addr = ENET_HOST_ANY;
  4370. sin.sin6_scope_id = 0;
  4371. }
  4372. return bind(socket, (struct sockaddr *)&sin, sizeof(struct sockaddr_in6));
  4373. }
  4374. int enet_socket_get_address(ENetSocket socket, ENetAddress *address) {
  4375. struct sockaddr_in6 sin;
  4376. socklen_t sinLength = sizeof(struct sockaddr_in6);
  4377. if (getsockname(socket, (struct sockaddr *) &sin, &sinLength) == -1) {
  4378. return -1;
  4379. }
  4380. address->host = sin.sin6_addr;
  4381. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  4382. address->sin6_scope_id = sin.sin6_scope_id;
  4383. return 0;
  4384. }
  4385. int enet_socket_listen(ENetSocket socket, int backlog) {
  4386. return listen(socket, backlog < 0 ? SOMAXCONN : backlog);
  4387. }
  4388. ENetSocket enet_socket_create(ENetSocketType type) {
  4389. return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
  4390. }
  4391. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  4392. int result = -1;
  4393. switch (option) {
  4394. case ENET_SOCKOPT_NONBLOCK:
  4395. result = fcntl(socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl(socket, F_GETFL) & ~O_NONBLOCK));
  4396. break;
  4397. case ENET_SOCKOPT_BROADCAST:
  4398. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&value, sizeof(int));
  4399. break;
  4400. case ENET_SOCKOPT_REUSEADDR:
  4401. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char *)&value, sizeof(int));
  4402. break;
  4403. case ENET_SOCKOPT_RCVBUF:
  4404. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)&value, sizeof(int));
  4405. break;
  4406. case ENET_SOCKOPT_SNDBUF:
  4407. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)&value, sizeof(int));
  4408. break;
  4409. case ENET_SOCKOPT_RCVTIMEO: {
  4410. struct timeval timeVal;
  4411. timeVal.tv_sec = value / 1000;
  4412. timeVal.tv_usec = (value % 1000) * 1000;
  4413. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeVal, sizeof(struct timeval));
  4414. break;
  4415. }
  4416. case ENET_SOCKOPT_SNDTIMEO: {
  4417. struct timeval timeVal;
  4418. timeVal.tv_sec = value / 1000;
  4419. timeVal.tv_usec = (value % 1000) * 1000;
  4420. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeVal, sizeof(struct timeval));
  4421. break;
  4422. }
  4423. case ENET_SOCKOPT_NODELAY:
  4424. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char *)&value, sizeof(int));
  4425. break;
  4426. case ENET_SOCKOPT_IPV6_V6ONLY:
  4427. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&value, sizeof(int));
  4428. break;
  4429. default:
  4430. break;
  4431. }
  4432. return result == -1 ? -1 : 0;
  4433. } /* enet_socket_set_option */
  4434. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int *value) {
  4435. int result = -1;
  4436. socklen_t len;
  4437. switch (option) {
  4438. case ENET_SOCKOPT_ERROR:
  4439. len = sizeof(int);
  4440. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, value, &len);
  4441. break;
  4442. default:
  4443. break;
  4444. }
  4445. return result == -1 ? -1 : 0;
  4446. }
  4447. int enet_socket_connect(ENetSocket socket, const ENetAddress *address) {
  4448. struct sockaddr_in6 sin;
  4449. int result;
  4450. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4451. sin.sin6_family = AF_INET6;
  4452. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  4453. sin.sin6_addr = address->host;
  4454. sin.sin6_scope_id = address->sin6_scope_id;
  4455. result = connect(socket, (struct sockaddr *)&sin, sizeof(struct sockaddr_in6));
  4456. if (result == -1 && errno == EINPROGRESS) {
  4457. return 0;
  4458. }
  4459. return result;
  4460. }
  4461. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress *address) {
  4462. int result;
  4463. struct sockaddr_in6 sin;
  4464. socklen_t sinLength = sizeof(struct sockaddr_in6);
  4465. result = accept(socket,address != NULL ? (struct sockaddr *) &sin : NULL, address != NULL ? &sinLength : NULL);
  4466. if (result == -1) {
  4467. return ENET_SOCKET_NULL;
  4468. }
  4469. if (address != NULL) {
  4470. address->host = sin.sin6_addr;
  4471. address->port = ENET_NET_TO_HOST_16 (sin.sin6_port);
  4472. address->sin6_scope_id = sin.sin6_scope_id;
  4473. }
  4474. return result;
  4475. }
  4476. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  4477. return shutdown(socket, (int) how);
  4478. }
  4479. void enet_socket_destroy(ENetSocket socket) {
  4480. if (socket != -1) {
  4481. close(socket);
  4482. }
  4483. }
  4484. int enet_socket_send(ENetSocket socket, const ENetAddress *address, const ENetBuffer *buffers, size_t bufferCount) {
  4485. struct msghdr msgHdr;
  4486. struct sockaddr_in6 sin;
  4487. int sentLength;
  4488. memset(&msgHdr, 0, sizeof(struct msghdr));
  4489. if (address != NULL) {
  4490. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4491. sin.sin6_family = AF_INET6;
  4492. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  4493. sin.sin6_addr = address->host;
  4494. sin.sin6_scope_id = address->sin6_scope_id;
  4495. msgHdr.msg_name = &sin;
  4496. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  4497. }
  4498. msgHdr.msg_iov = (struct iovec *) buffers;
  4499. msgHdr.msg_iovlen = bufferCount;
  4500. sentLength = sendmsg(socket, &msgHdr, MSG_NOSIGNAL);
  4501. if (sentLength == -1) {
  4502. if (errno == EWOULDBLOCK) {
  4503. return 0;
  4504. }
  4505. return -1;
  4506. }
  4507. return sentLength;
  4508. } /* enet_socket_send */
  4509. int enet_socket_receive(ENetSocket socket, ENetAddress *address, ENetBuffer *buffers, size_t bufferCount) {
  4510. struct msghdr msgHdr;
  4511. struct sockaddr_in6 sin;
  4512. int recvLength;
  4513. memset(&msgHdr, 0, sizeof(struct msghdr));
  4514. if (address != NULL) {
  4515. msgHdr.msg_name = &sin;
  4516. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  4517. }
  4518. msgHdr.msg_iov = (struct iovec *) buffers;
  4519. msgHdr.msg_iovlen = bufferCount;
  4520. recvLength = recvmsg(socket, &msgHdr, MSG_NOSIGNAL);
  4521. if (recvLength == -1) {
  4522. if (errno == EWOULDBLOCK) {
  4523. return 0;
  4524. }
  4525. return -1;
  4526. }
  4527. if (msgHdr.msg_flags & MSG_TRUNC) {
  4528. return -1;
  4529. }
  4530. if (address != NULL) {
  4531. address->host = sin.sin6_addr;
  4532. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  4533. address->sin6_scope_id = sin.sin6_scope_id;
  4534. }
  4535. return recvLength;
  4536. } /* enet_socket_receive */
  4537. int enet_socketset_select(ENetSocket maxSocket, ENetSocketSet *readSet, ENetSocketSet *writeSet, enet_uint32 timeout) {
  4538. struct timeval timeVal;
  4539. timeVal.tv_sec = timeout / 1000;
  4540. timeVal.tv_usec = (timeout % 1000) * 1000;
  4541. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  4542. }
  4543. int enet_socket_wait(ENetSocket socket, enet_uint32 *condition, enet_uint64 timeout) {
  4544. struct pollfd pollSocket;
  4545. int pollCount;
  4546. pollSocket.fd = socket;
  4547. pollSocket.events = 0;
  4548. if (*condition & ENET_SOCKET_WAIT_SEND) {
  4549. pollSocket.events |= POLLOUT;
  4550. }
  4551. if (*condition & ENET_SOCKET_WAIT_RECEIVE) {
  4552. pollSocket.events |= POLLIN;
  4553. }
  4554. pollCount = poll(&pollSocket, 1, timeout);
  4555. if (pollCount < 0) {
  4556. if (errno == EINTR && *condition & ENET_SOCKET_WAIT_INTERRUPT) {
  4557. *condition = ENET_SOCKET_WAIT_INTERRUPT;
  4558. return 0;
  4559. }
  4560. return -1;
  4561. }
  4562. *condition = ENET_SOCKET_WAIT_NONE;
  4563. if (pollCount == 0) {
  4564. return 0;
  4565. }
  4566. if (pollSocket.revents & POLLOUT) {
  4567. *condition |= ENET_SOCKET_WAIT_SEND;
  4568. }
  4569. if (pollSocket.revents & POLLIN) {
  4570. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  4571. }
  4572. return 0;
  4573. } /* enet_socket_wait */
  4574. #endif // !_WIN32
  4575. // =======================================================================//
  4576. // !
  4577. // ! Platform Specific (Win)
  4578. // !
  4579. // =======================================================================//
  4580. #ifdef _WIN32
  4581. int enet_initialize(void) {
  4582. WORD versionRequested = MAKEWORD(1, 1);
  4583. WSADATA wsaData;
  4584. if (WSAStartup(versionRequested, &wsaData)) {
  4585. return -1;
  4586. }
  4587. if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
  4588. WSACleanup();
  4589. return -1;
  4590. }
  4591. timeBeginPeriod(1);
  4592. return 0;
  4593. }
  4594. void enet_deinitialize(void) {
  4595. timeEndPeriod(1);
  4596. WSACleanup();
  4597. }
  4598. enet_uint64 enet_host_random_seed(void) {
  4599. return (enet_uint64) timeGetTime();
  4600. }
  4601. int enet_address_get_host(const ENetAddress *address, char *name, size_t nameLength) {
  4602. struct in6_addr in;
  4603. struct hostent *hostEntry = NULL;
  4604. in = address->host;
  4605. hostEntry = gethostbyaddr((char *)&in, sizeof(struct in6_addr), AF_INET6);
  4606. if (hostEntry == NULL) {
  4607. return enet_address_get_host_ip(address, name, nameLength);
  4608. } else {
  4609. size_t hostLen = strlen(hostEntry->h_name);
  4610. if (hostLen >= nameLength) {
  4611. return -1;
  4612. }
  4613. memcpy(name, hostEntry->h_name, hostLen + 1);
  4614. }
  4615. return 0;
  4616. }
  4617. int enet_socket_bind(ENetSocket socket, const ENetAddress *address) {
  4618. struct sockaddr_in6 sin;
  4619. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4620. sin.sin6_family = AF_INET6;
  4621. if (address != NULL) {
  4622. sin.sin6_port = ENET_HOST_TO_NET_16 (address->port);
  4623. sin.sin6_addr = address->host;
  4624. sin.sin6_scope_id = address->sin6_scope_id;
  4625. } else {
  4626. sin.sin6_port = 0;
  4627. sin.sin6_addr = in6addr_any;
  4628. sin.sin6_scope_id = 0;
  4629. }
  4630. return bind(socket, (struct sockaddr *) &sin, sizeof(struct sockaddr_in6)) == SOCKET_ERROR ? -1 : 0;
  4631. }
  4632. int enet_socket_get_address(ENetSocket socket, ENetAddress *address) {
  4633. struct sockaddr_in6 sin;
  4634. int sinLength = sizeof(struct sockaddr_in6);
  4635. if (getsockname(socket, (struct sockaddr *) &sin, &sinLength) == -1) {
  4636. return -1;
  4637. }
  4638. address->host = sin.sin6_addr;
  4639. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  4640. address->sin6_scope_id = sin.sin6_scope_id;
  4641. return 0;
  4642. }
  4643. int enet_socket_listen(ENetSocket socket, int backlog) {
  4644. return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
  4645. }
  4646. ENetSocket enet_socket_create(ENetSocketType type) {
  4647. return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
  4648. }
  4649. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  4650. int result = SOCKET_ERROR;
  4651. switch (option) {
  4652. case ENET_SOCKOPT_NONBLOCK: {
  4653. u_long nonBlocking = (u_long) value;
  4654. result = ioctlsocket(socket, FIONBIO, &nonBlocking);
  4655. break;
  4656. }
  4657. case ENET_SOCKOPT_BROADCAST:
  4658. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char *)&value, sizeof(int));
  4659. break;
  4660. case ENET_SOCKOPT_REUSEADDR:
  4661. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char *)&value, sizeof(int));
  4662. break;
  4663. case ENET_SOCKOPT_RCVBUF:
  4664. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)&value, sizeof(int));
  4665. break;
  4666. case ENET_SOCKOPT_SNDBUF:
  4667. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *)&value, sizeof(int));
  4668. break;
  4669. case ENET_SOCKOPT_RCVTIMEO:
  4670. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&value, sizeof(int));
  4671. break;
  4672. case ENET_SOCKOPT_SNDTIMEO:
  4673. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&value, sizeof(int));
  4674. break;
  4675. case ENET_SOCKOPT_NODELAY:
  4676. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char *)&value, sizeof(int));
  4677. break;
  4678. case ENET_SOCKOPT_IPV6_V6ONLY:
  4679. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&value, sizeof(int));
  4680. break;
  4681. default:
  4682. break;
  4683. }
  4684. return result == SOCKET_ERROR ? -1 : 0;
  4685. } /* enet_socket_set_option */
  4686. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int *value) {
  4687. int result = SOCKET_ERROR, len;
  4688. switch (option) {
  4689. case ENET_SOCKOPT_ERROR:
  4690. len = sizeof(int);
  4691. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char *)value, &len);
  4692. break;
  4693. default:
  4694. break;
  4695. }
  4696. return result == SOCKET_ERROR ? -1 : 0;
  4697. }
  4698. int enet_socket_connect(ENetSocket socket, const ENetAddress *address) {
  4699. struct sockaddr_in6 sin;
  4700. int result;
  4701. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4702. sin.sin6_family = AF_INET6;
  4703. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  4704. sin.sin6_addr = address->host;
  4705. sin.sin6_scope_id = address->sin6_scope_id;
  4706. result = connect(socket, (struct sockaddr *) &sin, sizeof(struct sockaddr_in6));
  4707. if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) {
  4708. return -1;
  4709. }
  4710. return 0;
  4711. }
  4712. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress *address) {
  4713. SOCKET result;
  4714. struct sockaddr_in6 sin;
  4715. int sinLength = sizeof(struct sockaddr_in6);
  4716. result = accept(socket, address != NULL ? (struct sockaddr *)&sin : NULL, address != NULL ? &sinLength : NULL);
  4717. if (result == INVALID_SOCKET) {
  4718. return ENET_SOCKET_NULL;
  4719. }
  4720. if (address != NULL) {
  4721. address->host = sin.sin6_addr;
  4722. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  4723. address->sin6_scope_id = sin.sin6_scope_id;
  4724. }
  4725. return result;
  4726. }
  4727. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  4728. return shutdown(socket, (int) how) == SOCKET_ERROR ? -1 : 0;
  4729. }
  4730. void enet_socket_destroy(ENetSocket socket) {
  4731. if (socket != INVALID_SOCKET) {
  4732. closesocket(socket);
  4733. }
  4734. }
  4735. int enet_socket_send(ENetSocket socket, const ENetAddress *address, const ENetBuffer *buffers, size_t bufferCount) {
  4736. struct sockaddr_in6 sin;
  4737. DWORD sentLength;
  4738. if (address != NULL) {
  4739. memset(&sin, 0, sizeof(struct sockaddr_in6));
  4740. sin.sin6_family = AF_INET6;
  4741. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  4742. sin.sin6_addr = address->host;
  4743. sin.sin6_scope_id = address->sin6_scope_id;
  4744. }
  4745. if (WSASendTo(socket,
  4746. (LPWSABUF) buffers,
  4747. (DWORD) bufferCount,
  4748. &sentLength,
  4749. 0,
  4750. address != NULL ? (struct sockaddr *) &sin : NULL,
  4751. address != NULL ? sizeof(struct sockaddr_in6) : 0,
  4752. NULL,
  4753. NULL) == SOCKET_ERROR
  4754. ) {
  4755. return (WSAGetLastError() == WSAEWOULDBLOCK) ? 0 : -1;
  4756. }
  4757. return (int) sentLength;
  4758. }
  4759. int enet_socket_receive(ENetSocket socket, ENetAddress *address, ENetBuffer *buffers, size_t bufferCount) {
  4760. INT sinLength = sizeof(struct sockaddr_in6);
  4761. DWORD flags = 0, recvLength;
  4762. struct sockaddr_in6 sin;
  4763. if (WSARecvFrom(socket,
  4764. (LPWSABUF) buffers,
  4765. (DWORD) bufferCount,
  4766. &recvLength,
  4767. &flags,
  4768. address != NULL ? (struct sockaddr *) &sin : NULL,
  4769. address != NULL ? &sinLength : NULL,
  4770. NULL,
  4771. NULL) == SOCKET_ERROR
  4772. ) {
  4773. switch (WSAGetLastError()) {
  4774. case WSAEWOULDBLOCK:
  4775. case WSAECONNRESET:
  4776. return 0;
  4777. }
  4778. return -1;
  4779. }
  4780. if (flags & MSG_PARTIAL) {
  4781. return -1;
  4782. }
  4783. if (address != NULL) {
  4784. address->host = sin.sin6_addr;
  4785. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  4786. address->sin6_scope_id = sin.sin6_scope_id;
  4787. }
  4788. return (int) recvLength;
  4789. } /* enet_socket_receive */
  4790. int enet_socketset_select(ENetSocket maxSocket, ENetSocketSet *readSet, ENetSocketSet *writeSet, enet_uint32 timeout) {
  4791. struct timeval timeVal;
  4792. timeVal.tv_sec = timeout / 1000;
  4793. timeVal.tv_usec = (timeout % 1000) * 1000;
  4794. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  4795. }
  4796. int enet_socket_wait(ENetSocket socket, enet_uint32 *condition, enet_uint64 timeout) {
  4797. fd_set readSet, writeSet;
  4798. struct timeval timeVal;
  4799. int selectCount;
  4800. timeVal.tv_sec = timeout / 1000;
  4801. timeVal.tv_usec = (timeout % 1000) * 1000;
  4802. FD_ZERO(&readSet);
  4803. FD_ZERO(&writeSet);
  4804. if (*condition & ENET_SOCKET_WAIT_SEND) {
  4805. FD_SET(socket, &writeSet);
  4806. }
  4807. if (*condition & ENET_SOCKET_WAIT_RECEIVE) {
  4808. FD_SET(socket, &readSet);
  4809. }
  4810. selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
  4811. if (selectCount < 0) {
  4812. return -1;
  4813. }
  4814. *condition = ENET_SOCKET_WAIT_NONE;
  4815. if (selectCount == 0) {
  4816. return 0;
  4817. }
  4818. if (FD_ISSET(socket, &writeSet)) {
  4819. *condition |= ENET_SOCKET_WAIT_SEND;
  4820. }
  4821. if (FD_ISSET(socket, &readSet)) {
  4822. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  4823. }
  4824. return 0;
  4825. } /* enet_socket_wait */
  4826. #endif // _WIN32
  4827. #ifdef __cplusplus
  4828. }
  4829. #endif
  4830. #endif // ENET_IMPLEMENTATION
  4831. #endif // ENET_INCLUDE_H