enet.h 231 KB

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