enet.h 238 KB

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