enet.h 239 KB

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