enet.h 238 KB

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