enet.h 230 KB

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