enet.h 245 KB

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