enet.h 230 KB

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