enet.h 234 KB

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