2
0

enet.h 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157
  1. /*
  2. * ENet reliable UDP networking library
  3. * This is a fork from upstream and is available at http://github.com/SoftwareGuy/ENet-CSharp
  4. *
  5. * Copyright (c) 2019-2020 Matt Coburn (SoftwareGuy/Coburn64), Chris Burns (c6burns)
  6. * Copyright (c) 2018 Lee Salzman, Vladyslav Hrytsenko, Dominik Madarász, Stanislav Denisov
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. *
  26. * Oh hey NX, whatcha doin' looking at this forks' source code? :)
  27. */
  28. #ifndef ENET_H
  29. #define ENET_H
  30. #include <stdlib.h>
  31. #include <stdbool.h>
  32. #include <stdint.h>
  33. #include <time.h>
  34. // include custom data.
  35. #include "custom/enet_logging.h"
  36. #include "enet_malloc.h"
  37. #define ENET_VERSION_MAJOR 2
  38. #define ENET_VERSION_MINOR 4
  39. #define ENET_VERSION_PATCH 0
  40. #define ENET_VERSION_CREATE(major, minor, patch) (((major) << 16) | ((minor) << 8) | (patch))
  41. #define ENET_VERSION_GET_MAJOR(version) (((version) >> 16) & 0xFF)
  42. #define ENET_VERSION_GET_MINOR(version) (((version) >> 8) & 0xFF)
  43. #define ENET_VERSION_GET_PATCH(version) ((version) & 0xFF)
  44. #define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH)
  45. #define ENET_TIME_OVERFLOW 86400000
  46. #define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW)
  47. #define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW)
  48. #define ENET_TIME_LESS_EQUAL(a, b) (!ENET_TIME_GREATER(a, b))
  49. #define ENET_TIME_GREATER_EQUAL(a, b) (!ENET_TIME_LESS(a, b))
  50. #define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b))
  51. #define ENET_MAX(x, y) ((x) > (y) ? (x) : (y))
  52. #define ENET_MIN(x, y) ((x) < (y) ? (x) : (y))
  53. /*
  54. =======================================================================
  55. System differences
  56. =======================================================================
  57. */
  58. #ifdef _WIN32
  59. #ifndef ENET_NO_PRAGMA_LINK
  60. #pragma comment(lib, "ws2_32.lib")
  61. #pragma comment(lib, "winmm.lib")
  62. #endif
  63. #if _MSC_VER >= 1910
  64. /* It looks like there were changes as of Visual Studio 2017 and there are no 32/64 bit
  65. versions of _InterlockedExchange[operation], only InterlockedExchange[operation]
  66. (without leading underscore), so we have to distinguish between compiler versions */
  67. #define NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  68. #endif
  69. #include <winsock2.h>
  70. #include <ws2tcpip.h>
  71. #include <mmsystem.h>
  72. #include <intrin.h>
  73. #if defined(_WIN32) && defined(_MSC_VER)
  74. #if _MSC_VER < 1900
  75. typedef struct timespec {
  76. long tv_sec;
  77. long tv_nsec;
  78. };
  79. #endif
  80. #define CLOCK_MONOTONIC 0
  81. #endif
  82. typedef SOCKET ENetSocket;
  83. #define ENET_SOCKET_NULL INVALID_SOCKET
  84. typedef struct {
  85. size_t dataLength;
  86. void* data;
  87. } ENetBuffer;
  88. #define ENET_CALLBACK __cdecl
  89. #ifdef ENET_DLL
  90. #ifdef ENET_IMPLEMENTATION
  91. #define ENET_API __declspec(dllexport)
  92. #else
  93. #define ENET_API __declspec(dllimport)
  94. #endif
  95. #else
  96. #define ENET_API extern
  97. #endif
  98. #else
  99. #include <sys/types.h>
  100. #include <sys/ioctl.h>
  101. #include <sys/time.h>
  102. #include <sys/socket.h>
  103. #include <poll.h>
  104. #include <arpa/inet.h>
  105. #include <netinet/in.h>
  106. #include <netinet/tcp.h>
  107. #include <netdb.h>
  108. #include <unistd.h>
  109. #include <string.h>
  110. #include <errno.h>
  111. #include <fcntl.h>
  112. #ifdef __APPLE__
  113. #include <mach/clock.h>
  114. #include <mach/mach.h>
  115. #include <Availability.h>
  116. #endif
  117. #ifndef MSG_NOSIGNAL
  118. #define MSG_NOSIGNAL 0
  119. #endif
  120. #ifdef MSG_MAXIOVLEN
  121. #define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN
  122. #endif
  123. typedef int ENetSocket;
  124. #define ENET_SOCKET_NULL -1
  125. typedef struct {
  126. void* data;
  127. size_t dataLength;
  128. } ENetBuffer;
  129. #define ENET_CALLBACK
  130. #define ENET_API extern
  131. #endif
  132. #ifndef ENET_BUFFER_MAXIMUM
  133. #define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)
  134. #endif
  135. #define ENET_HOST_ANY in6addr_any
  136. #define ENET_PORT_ANY 0
  137. #define ENET_HOST_SIZE 1025
  138. #define ENET_HOST_TO_NET_16(value) (htons(value))
  139. #define ENET_HOST_TO_NET_32(value) (htonl(value))
  140. #define ENET_NET_TO_HOST_16(value) (ntohs(value))
  141. #define ENET_NET_TO_HOST_32(value) (ntohl(value))
  142. #ifdef __cplusplus
  143. extern "C" {
  144. #endif
  145. /*
  146. =======================================================================
  147. Internals
  148. =======================================================================
  149. */
  150. typedef uint32_t ENetVersion;
  151. typedef fd_set ENetSocketSet;
  152. typedef struct _ENetCallbacks {
  153. void* (ENET_CALLBACK* malloc)(size_t size);
  154. void (ENET_CALLBACK* free)(void* memory);
  155. void (ENET_CALLBACK* noMemory)(void);
  156. } ENetCallbacks;
  157. extern void* enet_malloc(size_t);
  158. extern void enet_free(void*);
  159. typedef struct _ENetListNode {
  160. struct _ENetListNode* next;
  161. struct _ENetListNode* previous;
  162. } ENetListNode;
  163. typedef ENetListNode* ENetListIterator;
  164. typedef struct _ENetList {
  165. ENetListNode sentinel;
  166. } ENetList;
  167. extern ENetListIterator enet_list_insert(ENetListIterator, void*);
  168. extern ENetListIterator enet_list_move(ENetListIterator, void*, void*);
  169. extern void* enet_list_remove(ENetListIterator);
  170. extern void enet_list_clear(ENetList*);
  171. extern size_t enet_list_size(ENetList*);
  172. #define enet_list_begin(list) ((list)->sentinel.next)
  173. #define enet_list_end(list) (&(list)->sentinel)
  174. #define enet_list_empty(list) (enet_list_begin(list) == enet_list_end(list))
  175. #define enet_list_next(iterator) ((iterator)->next)
  176. #define enet_list_previous(iterator) ((iterator)->previous)
  177. #define enet_list_front(list) ((void*)(list)->sentinel.next)
  178. #define enet_list_back(list) ((void*)(list)->sentinel.previous)
  179. #define enet_in6_equal(a, b) (memcmp(&a, &b, sizeof(struct in6_addr)) == 0)
  180. /*
  181. =======================================================================
  182. Protocol
  183. =======================================================================
  184. */
  185. enum {
  186. ENET_PROTOCOL_MINIMUM_MTU = 576,
  187. ENET_PROTOCOL_MAXIMUM_MTU = 4096,
  188. ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32,
  189. ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096,
  190. ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536,
  191. ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1,
  192. ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255,
  193. ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xFFF,
  194. ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024
  195. };
  196. typedef enum _ENetProtocolCommand {
  197. ENET_PROTOCOL_COMMAND_NONE = 0,
  198. ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1,
  199. ENET_PROTOCOL_COMMAND_CONNECT = 2,
  200. ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3,
  201. ENET_PROTOCOL_COMMAND_DISCONNECT = 4,
  202. ENET_PROTOCOL_COMMAND_PING = 5,
  203. ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6,
  204. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7,
  205. ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8,
  206. ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9,
  207. ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10,
  208. ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11,
  209. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12,
  210. ENET_PROTOCOL_COMMAND_COUNT = 13,
  211. ENET_PROTOCOL_COMMAND_MASK = 0x0F
  212. } ENetProtocolCommand;
  213. typedef enum _ENetProtocolFlag {
  214. ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7),
  215. ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6),
  216. ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 << 14),
  217. ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_SENT_TIME,
  218. ENET_PROTOCOL_HEADER_SESSION_MASK = (3 << 12),
  219. ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12
  220. } ENetProtocolFlag;
  221. #ifdef _MSC_VER
  222. #pragma pack(push, 1)
  223. #define ENET_PACKED
  224. #elif defined(__GNUC__) || defined(__clang__)
  225. #define ENET_PACKED __attribute__ ((packed))
  226. #else
  227. #define ENET_PACKED
  228. #endif
  229. typedef struct _ENetProtocolHeader {
  230. uint16_t peerID;
  231. uint16_t sentTime;
  232. } ENET_PACKED ENetProtocolHeader;
  233. typedef struct _ENetProtocolCommandHeader {
  234. uint8_t command;
  235. uint8_t channelID;
  236. uint16_t reliableSequenceNumber;
  237. } ENET_PACKED ENetProtocolCommandHeader;
  238. typedef struct _ENetProtocolAcknowledge {
  239. ENetProtocolCommandHeader header;
  240. uint16_t receivedReliableSequenceNumber;
  241. uint16_t receivedSentTime;
  242. } ENET_PACKED ENetProtocolAcknowledge;
  243. typedef struct _ENetProtocolConnect {
  244. ENetProtocolCommandHeader header;
  245. uint16_t outgoingPeerID;
  246. uint8_t incomingSessionID;
  247. uint8_t outgoingSessionID;
  248. uint32_t mtu;
  249. uint32_t windowSize;
  250. uint32_t channelCount;
  251. uint32_t incomingBandwidth;
  252. uint32_t outgoingBandwidth;
  253. uint32_t packetThrottleInterval;
  254. uint32_t packetThrottleAcceleration;
  255. uint32_t packetThrottleDeceleration;
  256. uint32_t connectID;
  257. uint32_t data;
  258. } ENET_PACKED ENetProtocolConnect;
  259. typedef struct _ENetProtocolVerifyConnect {
  260. ENetProtocolCommandHeader header;
  261. uint16_t outgoingPeerID;
  262. uint8_t incomingSessionID;
  263. uint8_t outgoingSessionID;
  264. uint32_t mtu;
  265. uint32_t windowSize;
  266. uint32_t channelCount;
  267. uint32_t incomingBandwidth;
  268. uint32_t outgoingBandwidth;
  269. uint32_t packetThrottleInterval;
  270. uint32_t packetThrottleAcceleration;
  271. uint32_t packetThrottleDeceleration;
  272. uint32_t connectID;
  273. } ENET_PACKED ENetProtocolVerifyConnect;
  274. typedef struct _ENetProtocolBandwidthLimit {
  275. ENetProtocolCommandHeader header;
  276. uint32_t incomingBandwidth;
  277. uint32_t outgoingBandwidth;
  278. } ENET_PACKED ENetProtocolBandwidthLimit;
  279. typedef struct _ENetProtocolThrottleConfigure {
  280. ENetProtocolCommandHeader header;
  281. uint32_t packetThrottleInterval;
  282. uint32_t packetThrottleAcceleration;
  283. uint32_t packetThrottleDeceleration;
  284. } ENET_PACKED ENetProtocolThrottleConfigure;
  285. typedef struct _ENetProtocolDisconnect {
  286. ENetProtocolCommandHeader header;
  287. uint32_t data;
  288. } ENET_PACKED ENetProtocolDisconnect;
  289. typedef struct _ENetProtocolPing {
  290. ENetProtocolCommandHeader header;
  291. } ENET_PACKED ENetProtocolPing;
  292. typedef struct _ENetProtocolSendReliable {
  293. ENetProtocolCommandHeader header;
  294. uint16_t dataLength;
  295. } ENET_PACKED ENetProtocolSendReliable;
  296. typedef struct _ENetProtocolSendUnreliable {
  297. ENetProtocolCommandHeader header;
  298. uint16_t unreliableSequenceNumber;
  299. uint16_t dataLength;
  300. } ENET_PACKED ENetProtocolSendUnreliable;
  301. typedef struct _ENetProtocolSendUnsequenced {
  302. ENetProtocolCommandHeader header;
  303. uint16_t unsequencedGroup;
  304. uint16_t dataLength;
  305. } ENET_PACKED ENetProtocolSendUnsequenced;
  306. typedef struct _ENetProtocolSendFragment {
  307. ENetProtocolCommandHeader header;
  308. uint16_t startSequenceNumber;
  309. uint16_t dataLength;
  310. uint32_t fragmentCount;
  311. uint32_t fragmentNumber;
  312. uint32_t totalLength;
  313. uint32_t fragmentOffset;
  314. } ENET_PACKED ENetProtocolSendFragment;
  315. typedef union _ENetProtocol {
  316. ENetProtocolCommandHeader header;
  317. ENetProtocolAcknowledge acknowledge;
  318. ENetProtocolConnect connect;
  319. ENetProtocolVerifyConnect verifyConnect;
  320. ENetProtocolDisconnect disconnect;
  321. ENetProtocolPing ping;
  322. ENetProtocolSendReliable sendReliable;
  323. ENetProtocolSendUnreliable sendUnreliable;
  324. ENetProtocolSendUnsequenced sendUnsequenced;
  325. ENetProtocolSendFragment sendFragment;
  326. ENetProtocolBandwidthLimit bandwidthLimit;
  327. ENetProtocolThrottleConfigure throttleConfigure;
  328. } ENET_PACKED ENetProtocol;
  329. #ifdef _MSC_VER
  330. #pragma pack(pop)
  331. #endif
  332. /*
  333. =======================================================================
  334. General structs/enums
  335. =======================================================================
  336. */
  337. typedef enum _ENetSocketType {
  338. ENET_SOCKET_TYPE_STREAM = 1,
  339. ENET_SOCKET_TYPE_DATAGRAM = 2
  340. } ENetSocketType;
  341. typedef enum _ENetSocketWait {
  342. ENET_SOCKET_WAIT_NONE = 0,
  343. ENET_SOCKET_WAIT_SEND = (1 << 0),
  344. ENET_SOCKET_WAIT_RECEIVE = (1 << 1),
  345. ENET_SOCKET_WAIT_INTERRUPT = (1 << 2)
  346. } ENetSocketWait;
  347. typedef enum _ENetSocketOption {
  348. ENET_SOCKOPT_NONBLOCK = 1,
  349. ENET_SOCKOPT_BROADCAST = 2,
  350. ENET_SOCKOPT_RCVBUF = 3,
  351. ENET_SOCKOPT_SNDBUF = 4,
  352. ENET_SOCKOPT_REUSEADDR = 5,
  353. ENET_SOCKOPT_RCVTIMEO = 6,
  354. ENET_SOCKOPT_SNDTIMEO = 7,
  355. ENET_SOCKOPT_ERROR = 8,
  356. ENET_SOCKOPT_NODELAY = 9,
  357. ENET_SOCKOPT_IPV6_V6ONLY = 10
  358. } ENetSocketOption;
  359. typedef enum _ENetSocketShutdown {
  360. ENET_SOCKET_SHUTDOWN_READ = 0,
  361. ENET_SOCKET_SHUTDOWN_WRITE = 1,
  362. ENET_SOCKET_SHUTDOWN_READ_WRITE = 2
  363. } ENetSocketShutdown;
  364. typedef struct _ENetAddress {
  365. union {
  366. struct in6_addr ipv6;
  367. struct {
  368. uint8_t zeros[10];
  369. uint16_t ffff;
  370. struct in_addr ip;
  371. } ipv4;
  372. };
  373. uint16_t port;
  374. } ENetAddress;
  375. typedef enum _ENetPacketFlag {
  376. ENET_PACKET_FLAG_NONE = 0,
  377. ENET_PACKET_FLAG_RELIABLE = (1 << 0),
  378. ENET_PACKET_FLAG_UNSEQUENCED = (1 << 1),
  379. ENET_PACKET_FLAG_NO_ALLOCATE = (1 << 2),
  380. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED = (1 << 3),
  381. ENET_PACKET_FLAG_INSTANT = (1 << 4),
  382. ENET_PACKET_FLAG_CRUCIAL = (1 << 5),
  383. ENET_PACKET_FLAG_SENT = (1 << 8)
  384. } ENetPacketFlag;
  385. typedef void (ENET_CALLBACK* ENetPacketFreeCallback)(void*);
  386. typedef struct _ENetPacket {
  387. uint32_t flags;
  388. uint32_t dataLength;
  389. uint8_t* data;
  390. ENetPacketFreeCallback freeCallback;
  391. uint32_t referenceCount;
  392. void* userData;
  393. } ENetPacket;
  394. typedef struct _ENetAcknowledgement {
  395. ENetListNode acknowledgementList;
  396. uint32_t sentTime;
  397. ENetProtocol command;
  398. } ENetAcknowledgement;
  399. typedef struct _ENetOutgoingCommand {
  400. ENetListNode outgoingCommandList;
  401. uint16_t reliableSequenceNumber;
  402. uint16_t unreliableSequenceNumber;
  403. uint32_t sentTime;
  404. uint32_t roundTripTimeout;
  405. uint32_t roundTripTimeoutLimit;
  406. uint32_t fragmentOffset;
  407. uint16_t fragmentLength;
  408. uint16_t sendAttempts;
  409. ENetProtocol command;
  410. ENetPacket* packet;
  411. } ENetOutgoingCommand;
  412. typedef struct _ENetIncomingCommand {
  413. ENetListNode incomingCommandList;
  414. uint16_t reliableSequenceNumber;
  415. uint16_t unreliableSequenceNumber;
  416. ENetProtocol command;
  417. uint32_t fragmentCount;
  418. uint32_t fragmentsRemaining;
  419. uint32_t* fragments;
  420. ENetPacket* packet;
  421. } ENetIncomingCommand;
  422. typedef enum _ENetPeerState {
  423. ENET_PEER_STATE_DISCONNECTED = 0,
  424. ENET_PEER_STATE_CONNECTING = 1,
  425. ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2,
  426. ENET_PEER_STATE_CONNECTION_PENDING = 3,
  427. ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4,
  428. ENET_PEER_STATE_CONNECTED = 5,
  429. ENET_PEER_STATE_DISCONNECT_LATER = 6,
  430. ENET_PEER_STATE_DISCONNECTING = 7,
  431. ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8,
  432. ENET_PEER_STATE_ZOMBIE = 9
  433. } ENetPeerState;
  434. enum {
  435. ENET_HOST_BUFFER_SIZE_MIN = 256 * 1024,
  436. ENET_HOST_BUFFER_SIZE_MAX = 1024 * 1024,
  437. ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000,
  438. ENET_HOST_DEFAULT_MTU = 1280,
  439. ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024,
  440. ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024,
  441. ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500,
  442. ENET_PEER_DEFAULT_PACKET_THROTTLE = 32,
  443. ENET_PEER_PACKET_THROTTLE_THRESHOLD = 20,
  444. ENET_PEER_PACKET_THROTTLE_SCALE = 32,
  445. ENET_PEER_PACKET_THROTTLE_COUNTER = 7,
  446. ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2,
  447. ENET_PEER_PACKET_THROTTLE_DECELERATION = 2,
  448. ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000,
  449. ENET_PEER_PACKET_LOSS_SCALE = (1 << 16),
  450. ENET_PEER_PACKET_LOSS_INTERVAL = 10000,
  451. ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024,
  452. ENET_PEER_TIMEOUT_LIMIT = 32,
  453. ENET_PEER_TIMEOUT_MINIMUM = 5000,
  454. ENET_PEER_TIMEOUT_MAXIMUM = 30000,
  455. ENET_PEER_PING_INTERVAL = 500,
  456. ENET_PEER_UNSEQUENCED_WINDOWS = 64,
  457. ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024,
  458. ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32,
  459. ENET_PEER_RELIABLE_WINDOWS = 16,
  460. ENET_PEER_RELIABLE_WINDOW_SIZE = 0x1000,
  461. ENET_PEER_FREE_RELIABLE_WINDOWS = 8
  462. };
  463. typedef struct _ENetChannel {
  464. uint16_t outgoingReliableSequenceNumber;
  465. uint16_t outgoingUnreliableSequenceNumber;
  466. uint16_t usedReliableWindows;
  467. uint16_t reliableWindows[ENET_PEER_RELIABLE_WINDOWS];
  468. uint16_t incomingReliableSequenceNumber;
  469. uint16_t incomingUnreliableSequenceNumber;
  470. ENetList incomingReliableCommands;
  471. ENetList incomingUnreliableCommands;
  472. } ENetChannel;
  473. typedef struct _ENetPeer {
  474. ENetListNode dispatchList;
  475. struct _ENetHost* host;
  476. uint16_t outgoingPeerID;
  477. uint16_t incomingPeerID;
  478. uint32_t connectID;
  479. uint8_t outgoingSessionID;
  480. uint8_t incomingSessionID;
  481. ENetAddress address;
  482. void* data;
  483. ENetPeerState state;
  484. ENetChannel* channels;
  485. size_t channelCount;
  486. uint32_t incomingBandwidth;
  487. uint32_t outgoingBandwidth;
  488. uint32_t incomingBandwidthThrottleEpoch;
  489. uint32_t outgoingBandwidthThrottleEpoch;
  490. uint32_t incomingDataTotal;
  491. uint64_t totalDataReceived;
  492. uint32_t outgoingDataTotal;
  493. uint64_t totalDataSent;
  494. uint32_t lastSendTime;
  495. uint32_t lastReceiveTime;
  496. uint32_t nextTimeout;
  497. uint32_t earliestTimeout;
  498. uint32_t packetLossEpoch;
  499. uint32_t packetsSent;
  500. uint64_t totalPacketsSent;
  501. uint32_t packetsLost;
  502. uint64_t totalPacketsLost;
  503. uint32_t packetLoss;
  504. uint32_t packetLossVariance;
  505. uint32_t packetThrottle;
  506. uint32_t packetThrottleThreshold;
  507. uint32_t packetThrottleLimit;
  508. uint32_t packetThrottleCounter;
  509. uint32_t packetThrottleEpoch;
  510. uint32_t packetThrottleAcceleration;
  511. uint32_t packetThrottleDeceleration;
  512. uint32_t packetThrottleInterval;
  513. uint32_t pingInterval;
  514. uint32_t timeoutLimit;
  515. uint32_t timeoutMinimum;
  516. uint32_t timeoutMaximum;
  517. uint32_t lastRoundTripTime;
  518. uint32_t lowestRoundTripTime;
  519. uint32_t lastRoundTripTimeVariance;
  520. uint32_t highestRoundTripTimeVariance;
  521. uint32_t roundTripTime;
  522. uint32_t roundTripTimeVariance;
  523. uint32_t mtu;
  524. uint32_t windowSize;
  525. uint32_t reliableDataInTransit;
  526. uint16_t outgoingReliableSequenceNumber;
  527. ENetList acknowledgements;
  528. ENetList sentReliableCommands;
  529. ENetList sentUnreliableCommands;
  530. ENetList outgoingReliableCommands;
  531. ENetList outgoingUnreliableCommands;
  532. ENetList dispatchedCommands;
  533. int needsDispatch;
  534. uint16_t incomingUnsequencedGroup;
  535. uint16_t outgoingUnsequencedGroup;
  536. uint32_t unsequencedWindow[ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32];
  537. uint32_t eventData;
  538. size_t totalWaitingData;
  539. } ENetPeer;
  540. typedef uint32_t(ENET_CALLBACK* ENetChecksumCallback)(const ENetBuffer* buffers, size_t bufferCount);
  541. typedef int (ENET_CALLBACK* ENetInterceptCallback)(struct _ENetHost* host, void* event);
  542. typedef struct _ENetHost {
  543. ENetSocket socket;
  544. ENetAddress address;
  545. uint32_t incomingBandwidth;
  546. uint32_t outgoingBandwidth;
  547. uint32_t bandwidthThrottleEpoch;
  548. uint32_t mtu;
  549. uint32_t randomSeed;
  550. int recalculateBandwidthLimits;
  551. uint8_t preventConnections;
  552. ENetPeer* peers;
  553. size_t peerCount;
  554. size_t channelLimit;
  555. uint32_t serviceTime;
  556. ENetList dispatchQueue;
  557. int continueSending;
  558. size_t packetSize;
  559. uint16_t headerFlags;
  560. uint32_t totalSentData;
  561. uint32_t totalSentPackets;
  562. uint32_t totalReceivedData;
  563. uint32_t totalReceivedPackets;
  564. ENetProtocol commands[ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS];
  565. size_t commandCount;
  566. ENetBuffer buffers[ENET_BUFFER_MAXIMUM];
  567. size_t bufferCount;
  568. ENetChecksumCallback checksumCallback;
  569. uint8_t packetData[2][ENET_PROTOCOL_MAXIMUM_MTU];
  570. ENetAddress receivedAddress;
  571. uint8_t* receivedData;
  572. size_t receivedDataLength;
  573. ENetInterceptCallback interceptCallback;
  574. size_t connectedPeers;
  575. size_t bandwidthLimitedPeers;
  576. size_t duplicatePeers;
  577. size_t maximumPacketSize;
  578. size_t maximumWaitingData;
  579. } ENetHost;
  580. typedef enum _ENetEventType {
  581. ENET_EVENT_TYPE_NONE = 0,
  582. ENET_EVENT_TYPE_CONNECT = 1,
  583. ENET_EVENT_TYPE_DISCONNECT = 2,
  584. ENET_EVENT_TYPE_RECEIVE = 3,
  585. ENET_EVENT_TYPE_DISCONNECT_TIMEOUT = 4
  586. } ENetEventType;
  587. typedef struct _ENetEvent {
  588. ENetEventType type;
  589. ENetPeer* peer;
  590. uint8_t channelID;
  591. uint32_t data;
  592. ENetPacket* packet;
  593. } ENetEvent;
  594. /*
  595. =======================================================================
  596. Public API
  597. =======================================================================
  598. */
  599. ENET_API int enet_initialize(void);
  600. ENET_API void* enet_mem_acquire(size_t sz) { return enet_malloc(sz); }
  601. ENET_API void enet_mem_release(void* alloc) { enet_free(alloc); }
  602. ENET_API void enet_deinitialize(void);
  603. ENET_API ENetVersion enet_linked_version(void);
  604. ENET_API int enet_array_is_zeroed(const uint8_t*, int);
  605. ENET_API uint32_t enet_time_get(void);
  606. ENET_API uint32_t enet_crc32(const ENetBuffer*, size_t);
  607. ENET_API ENetPacket* enet_packet_create(const void*, size_t, uint32_t);
  608. ENET_API ENetPacket* enet_packet_create_offset(const void*, size_t, size_t, uint32_t);
  609. ENET_API void enet_packet_destroy(ENetPacket*);
  610. ENET_API int enet_peer_send(ENetPeer*, uint8_t, ENetPacket*);
  611. ENET_API ENetPacket* enet_peer_receive(ENetPeer*, uint8_t*);
  612. ENET_API void enet_peer_ping(ENetPeer*);
  613. ENET_API void enet_peer_ping_interval(ENetPeer*, uint32_t);
  614. ENET_API void enet_peer_timeout(ENetPeer*, uint32_t, uint32_t, uint32_t);
  615. ENET_API void enet_peer_reset(ENetPeer*);
  616. ENET_API void enet_peer_disconnect(ENetPeer*, uint32_t);
  617. ENET_API void enet_peer_disconnect_now(ENetPeer*, uint32_t);
  618. ENET_API void enet_peer_disconnect_later(ENetPeer*, uint32_t);
  619. ENET_API void enet_peer_throttle_configure(ENetPeer*, uint32_t, uint32_t, uint32_t, uint32_t);
  620. ENET_API ENetHost* enet_host_create(const ENetAddress*, size_t, size_t, uint32_t, uint32_t, int);
  621. ENET_API void enet_host_destroy(ENetHost*);
  622. ENET_API void enet_host_prevent_connections(ENetHost*, uint8_t);
  623. ENET_API ENetPeer* enet_host_connect(ENetHost*, const ENetAddress*, size_t, uint32_t);
  624. ENET_API int enet_host_check_events(ENetHost*, ENetEvent*);
  625. ENET_API int enet_host_service(ENetHost*, ENetEvent*, uint32_t);
  626. ENET_API void enet_host_flush(ENetHost*);
  627. ENET_API void enet_host_broadcast(ENetHost*, uint8_t, ENetPacket*);
  628. ENET_API void enet_host_broadcast_exclude(ENetHost*, uint8_t, ENetPacket*, ENetPeer*);
  629. ENET_API void enet_host_broadcast_selective(ENetHost*, uint8_t, ENetPacket*, ENetPeer**, size_t);
  630. ENET_API void enet_host_channel_limit(ENetHost*, size_t);
  631. ENET_API void enet_host_bandwidth_limit(ENetHost*, uint32_t, uint32_t);
  632. ENET_API int enet_address_set_ip(ENetAddress*, const char*);
  633. ENET_API int enet_address_set_hostname(ENetAddress*, const char*);
  634. ENET_API int enet_address_get_ip(const ENetAddress*, char*, size_t);
  635. ENET_API int enet_address_get_hostname(const ENetAddress*, char*, size_t);
  636. ENET_API ENetSocket enet_socket_create(ENetSocketType);
  637. ENET_API int enet_socket_bind(ENetSocket, const ENetAddress*);
  638. ENET_API int enet_socket_get_address(ENetSocket, ENetAddress*);
  639. ENET_API int enet_socket_listen(ENetSocket, int);
  640. ENET_API ENetSocket enet_socket_accept(ENetSocket, ENetAddress*);
  641. ENET_API int enet_socket_connect(ENetSocket, const ENetAddress*);
  642. ENET_API int enet_socket_send(ENetSocket, const ENetAddress*, const ENetBuffer*, size_t);
  643. ENET_API int enet_socket_receive(ENetSocket, ENetAddress*, ENetBuffer*, size_t);
  644. ENET_API int enet_socket_wait(ENetSocket, uint32_t*, uint64_t);
  645. ENET_API int enet_socket_set_option(ENetSocket, ENetSocketOption, int);
  646. ENET_API int enet_socket_get_option(ENetSocket, ENetSocketOption, int*);
  647. ENET_API int enet_socket_shutdown(ENetSocket, ENetSocketShutdown);
  648. ENET_API void enet_socket_destroy(ENetSocket);
  649. ENET_API int enet_socket_set_select(ENetSocket, ENetSocketSet*, ENetSocketSet*, uint32_t);
  650. /* Extended API for easier binding in other programming languages */
  651. ENET_API void* enet_packet_get_data(const ENetPacket*);
  652. ENET_API void* enet_packet_get_user_data(const ENetPacket*);
  653. ENET_API void enet_packet_set_user_data(ENetPacket*, void* userData);
  654. ENET_API int enet_packet_get_length(const ENetPacket*);
  655. ENET_API void enet_packet_set_free_callback(ENetPacket*, const void*);
  656. ENET_API int enet_packet_check_references(const ENetPacket*);
  657. ENET_API void enet_packet_dispose(ENetPacket*);
  658. ENET_API uint32_t enet_host_get_peers_count(const ENetHost*);
  659. ENET_API uint32_t enet_host_get_packets_sent(const ENetHost*);
  660. ENET_API uint32_t enet_host_get_packets_received(const ENetHost*);
  661. ENET_API uint32_t enet_host_get_bytes_sent(const ENetHost*);
  662. ENET_API uint32_t enet_host_get_bytes_received(const ENetHost*);
  663. ENET_API uint32_t enet_peer_get_id(const ENetPeer*);
  664. ENET_API int enet_peer_get_ip(const ENetPeer*, char*, size_t);
  665. ENET_API uint16_t enet_peer_get_port(const ENetPeer*);
  666. ENET_API uint32_t enet_peer_get_mtu(const ENetPeer*);
  667. ENET_API ENetPeerState enet_peer_get_state(const ENetPeer*);
  668. ENET_API uint32_t enet_peer_get_rtt(const ENetPeer*);
  669. ENET_API uint32_t enet_peer_get_last_rtt(const ENetPeer* peer);
  670. ENET_API uint32_t enet_peer_get_lastsendtime(const ENetPeer*);
  671. ENET_API uint32_t enet_peer_get_lastreceivetime(const ENetPeer*);
  672. ENET_API uint64_t enet_peer_get_packets_sent(const ENetPeer*);
  673. ENET_API uint64_t enet_peer_get_packets_lost(const ENetPeer*);
  674. ENET_API uint64_t enet_peer_get_bytes_sent(const ENetPeer*);
  675. ENET_API uint64_t enet_peer_get_bytes_received(const ENetPeer*);
  676. ENET_API void* enet_peer_get_data(const ENetPeer*);
  677. ENET_API void enet_peer_set_data(ENetPeer*, const void*);
  678. /*
  679. =======================================================================
  680. Private API
  681. =======================================================================
  682. */
  683. extern void enet_host_bandwidth_throttle(ENetHost*);
  684. extern uint64_t enet_host_random_seed(void);
  685. extern int enet_peer_throttle(ENetPeer*, uint32_t);
  686. extern void enet_peer_reset_queues(ENetPeer*);
  687. extern void enet_peer_setup_outgoing_command(ENetPeer*, ENetOutgoingCommand*);
  688. extern ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer*, const ENetProtocol*, ENetPacket*, uint32_t, uint16_t);
  689. extern ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer*, const ENetProtocol*, const void*, size_t, uint32_t, uint32_t);
  690. extern ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer*, const ENetProtocol*, uint16_t);
  691. extern void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer*, ENetChannel*);
  692. extern void enet_peer_dispatch_incoming_reliable_commands(ENetPeer*, ENetChannel*);
  693. extern void enet_peer_on_connect(ENetPeer*);
  694. extern void enet_peer_on_disconnect(ENetPeer*);
  695. extern size_t enet_protocol_command_size(uint8_t);
  696. #ifdef __cplusplus
  697. }
  698. #endif
  699. #if defined(ENET_IMPLEMENTATION) && !defined(ENET_IMPLEMENTATION_DONE)
  700. #define ENET_IMPLEMENTATION_DONE 1
  701. #ifdef _MSC_VER
  702. #pragma warning(push)
  703. #pragma warning(disable: 4244) /* 64-bit to 32-bit integer conversion */
  704. #pragma warning(disable: 4267) /* size_t to integer conversion */
  705. #endif
  706. /*
  707. =======================================================================
  708. Atomics
  709. =======================================================================
  710. */
  711. #ifdef _MSC_VER
  712. #define ENET_AT_CASSERT_PRED(predicate) sizeof(char[2 * !!(predicate) - 1])
  713. #define ENET_IS_SUPPORTED_ATOMIC(size) ENET_AT_CASSERT_PRED(size == 1 || size == 2 || size == 4 || size == 8)
  714. #define ENET_ATOMIC_SIZEOF(variable) (ENET_IS_SUPPORTED_ATOMIC(sizeof(*(variable))), sizeof(*(variable)))
  715. __inline int64_t enet_at_atomic_read(char* ptr, size_t size) {
  716. switch (size) {
  717. case 1:
  718. return _InterlockedExchangeAdd8((volatile char*)ptr, 0);
  719. case 2:
  720. return _InterlockedExchangeAdd16((volatile SHORT*)ptr, 0);
  721. case 4:
  722. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  723. return InterlockedExchangeAdd((volatile LONG*)ptr, 0);
  724. #else
  725. return _InterlockedExchangeAdd((volatile LONG*)ptr, 0);
  726. #endif
  727. case 8:
  728. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  729. return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
  730. #else
  731. return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
  732. #endif
  733. default:
  734. return 0x0;
  735. }
  736. }
  737. __inline int64_t enet_at_atomic_write(char* ptr, int64_t value, size_t size) {
  738. switch (size) {
  739. case 1:
  740. return _InterlockedExchange8((volatile char*)ptr, (char)value);
  741. case 2:
  742. return _InterlockedExchange16((volatile SHORT*)ptr, (SHORT)value);
  743. case 4:
  744. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  745. return InterlockedExchange((volatile LONG*)ptr, (LONG)value);
  746. #else
  747. return _InterlockedExchange((volatile LONG*)ptr, (LONG)value);
  748. #endif
  749. case 8:
  750. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  751. return InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
  752. #else
  753. return _InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
  754. #endif
  755. default:
  756. return 0x0;
  757. }
  758. }
  759. __inline int64_t enet_at_atomic_cas(char* ptr, int64_t new_val, int64_t old_val, size_t size) {
  760. switch (size) {
  761. case 1:
  762. return _InterlockedCompareExchange8((volatile char*)ptr, (char)new_val, (char)old_val);
  763. case 2:
  764. return _InterlockedCompareExchange16((volatile SHORT*)ptr, (SHORT)new_val, (SHORT)old_val);
  765. case 4:
  766. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  767. return InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
  768. #else
  769. return _InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
  770. #endif
  771. case 8:
  772. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  773. return InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
  774. #else
  775. return _InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
  776. #endif
  777. default:
  778. return 0x0;
  779. }
  780. }
  781. __inline int64_t enet_at_atomic_inc(char* ptr, int64_t delta, size_t data_size) {
  782. switch (data_size) {
  783. case 1:
  784. return _InterlockedExchangeAdd8((volatile char*)ptr, (char)delta);
  785. case 2:
  786. return _InterlockedExchangeAdd16((volatile SHORT*)ptr, (SHORT)delta);
  787. case 4:
  788. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  789. return InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
  790. #else
  791. return _InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
  792. #endif
  793. case 8:
  794. #ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  795. return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
  796. #else
  797. return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
  798. #endif
  799. default:
  800. return 0x0;
  801. }
  802. }
  803. #define ENET_ATOMIC_READ(variable) enet_at_atomic_read((char*)(variable), ENET_ATOMIC_SIZEOF(variable))
  804. #define ENET_ATOMIC_WRITE(variable, new_val) enet_at_atomic_write((char*)(variable), (int64_t)(new_val), ENET_ATOMIC_SIZEOF(variable))
  805. #define ENET_ATOMIC_CAS(variable, old_value, new_val) enet_at_atomic_cas((char*)(variable), (int64_t)(new_val), (int64_t)(old_value), ENET_ATOMIC_SIZEOF(variable))
  806. #define ENET_ATOMIC_INC(variable) enet_at_atomic_inc((char*)(variable), 1, ENET_ATOMIC_SIZEOF(variable))
  807. #define ENET_ATOMIC_DEC(variable) enet_at_atomic_inc((char*)(variable), -1, ENET_ATOMIC_SIZEOF(variable))
  808. #define ENET_ATOMIC_INC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), (delta), ENET_ATOMIC_SIZEOF(variable))
  809. #define ENET_ATOMIC_DEC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), -(delta), ENET_ATOMIC_SIZEOF(variable))
  810. #elif defined(__GNUC__) || defined(__clang__)
  811. #if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
  812. #define AT_HAVE_ATOMICS
  813. #endif
  814. /* We want to use __atomic built-ins if possible because the __sync primitives are
  815. deprecated, because the __atomic build-ins allow us to use ENET_ATOMIC_WRITE on
  816. uninitialized memory without running into undefined behavior, and because the
  817. __atomic versions generate more efficient code since we don't need to rely on
  818. CAS when we don't actually want it.
  819. Note that we use acquire-release memory order (like mutexes do). We could use
  820. sequentially consistent memory order but that has lower performance and is
  821. almost always unneeded. */
  822. #ifdef AT_HAVE_ATOMICS
  823. #define ENET_ATOMIC_READ(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
  824. #define ENET_ATOMIC_WRITE(ptr, value) __atomic_store_n((ptr), (value), __ATOMIC_RELEASE)
  825. #ifndef typeof
  826. #define typeof __typeof__
  827. #endif
  828. /* clang_analyzer doesn't know that CAS writes to memory so it complains about
  829. potentially lost data. Replace the code with the equivalent non-sync code. */
  830. #ifdef __clang_analyzer__
  831. #define ENET_ATOMIC_CAS(ptr, old_value, new_value) \
  832. ({ \
  833. typeof(*(ptr)) ENET_ATOMIC_CAS_old_actual_ = (*(ptr)); \
  834. if (ATOMIC_CAS_old_actual_ == (old_value)) \
  835. *(ptr) = new_value; \
  836. ENET_ATOMIC_CAS_old_actual_; \
  837. })
  838. #else
  839. /* Could use __auto_type instead of typeof but that shouldn't work in C++.
  840. The ({ }) syntax is a GCC extension called statement expression. It lets
  841. us return a value out of the macro.
  842. TODO We should return bool here instead of the old value to avoid the ABA
  843. problem. */
  844. #define ENET_ATOMIC_CAS(ptr, old_value, new_value) \
  845. ({ \
  846. typeof(*(ptr)) ENET_ATOMIC_CAS_expected_ = (old_value); \
  847. __atomic_compare_exchange_n((ptr), &ENET_ATOMIC_CAS_expected_, (new_value), false, \
  848. __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE); \
  849. ENET_ATOMIC_CAS_expected_; \
  850. })
  851. #endif
  852. #define ENET_ATOMIC_INC(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_ACQ_REL)
  853. #define ENET_ATOMIC_DEC(ptr) __atomic_fetch_sub((ptr), 1, __ATOMIC_ACQ_REL)
  854. #define ENET_ATOMIC_INC_BY(ptr, delta) __atomic_fetch_add((ptr), (delta), __ATOMIC_ACQ_REL)
  855. #define ENET_ATOMIC_DEC_BY(ptr, delta) __atomic_fetch_sub((ptr), (delta), __ATOMIC_ACQ_REL)
  856. #else
  857. #define ENET_ATOMIC_READ(variable) __sync_fetch_and_add(variable, 0)
  858. #define ENET_ATOMIC_WRITE(variable, new_val) (void)__sync_val_compare_and_swap((variable), *(variable), (new_val))
  859. #define ENET_ATOMIC_CAS(variable, old_value, new_val) __sync_val_compare_and_swap((variable), (old_value), (new_val))
  860. #define ENET_ATOMIC_INC(variable) __sync_fetch_and_add((variable), 1)
  861. #define ENET_ATOMIC_DEC(variable) __sync_fetch_and_sub((variable), 1)
  862. #define ENET_ATOMIC_INC_BY(variable, delta) __sync_fetch_and_add((variable), (delta), 1)
  863. #define ENET_ATOMIC_DEC_BY(variable, delta) __sync_fetch_and_sub((variable), (delta), 1)
  864. #endif
  865. #undef AT_HAVE_ATOMICS
  866. #endif
  867. /*
  868. =======================================================================
  869. List
  870. =======================================================================
  871. */
  872. void enet_list_clear(ENetList* list) {
  873. list->sentinel.next = &list->sentinel;
  874. list->sentinel.previous = &list->sentinel;
  875. }
  876. ENetListIterator enet_list_insert(ENetListIterator position, void* data) {
  877. ENetListIterator result = (ENetListIterator)data;
  878. result->previous = position->previous;
  879. result->next = position;
  880. result->previous->next = result;
  881. position->previous = result;
  882. return result;
  883. }
  884. void* enet_list_remove(ENetListIterator position) {
  885. position->previous->next = position->next;
  886. position->next->previous = position->previous;
  887. return position;
  888. }
  889. ENetListIterator enet_list_move(ENetListIterator position, void* dataFirst, void* dataLast) {
  890. ENetListIterator first = (ENetListIterator)dataFirst;
  891. ENetListIterator last = (ENetListIterator)dataLast;
  892. first->previous->next = last->next;
  893. last->next->previous = first->previous;
  894. first->previous = position->previous;
  895. last->next = position;
  896. first->previous->next = first;
  897. position->previous = last;
  898. return first;
  899. }
  900. size_t enet_list_size(ENetList* list) {
  901. size_t size = 0;
  902. ENetListIterator position;
  903. for (position = enet_list_begin(list); position != enet_list_end(list); position = enet_list_next(position)) {
  904. ++size;
  905. }
  906. return size;
  907. }
  908. /*
  909. =======================================================================
  910. Utilities
  911. =======================================================================
  912. */
  913. ENetVersion enet_linked_version(void) {
  914. return ENET_VERSION;
  915. }
  916. int enet_array_is_zeroed(const uint8_t* array, int length) {
  917. size_t i;
  918. for (i = 0; i < length; i++) {
  919. if (array[i] != 0)
  920. return -1;
  921. }
  922. return 0;
  923. }
  924. /*
  925. =======================================================================
  926. Time
  927. =======================================================================
  928. */
  929. #ifdef _WIN32
  930. static LARGE_INTEGER gettime_offset(void) {
  931. SYSTEMTIME s;
  932. FILETIME f;
  933. LARGE_INTEGER t;
  934. s.wYear = 1970;
  935. s.wMonth = 1;
  936. s.wDay = 1;
  937. s.wHour = 0;
  938. s.wMinute = 0;
  939. s.wSecond = 0;
  940. s.wMilliseconds = 0;
  941. SystemTimeToFileTime(&s, &f);
  942. t.QuadPart = f.dwHighDateTime;
  943. t.QuadPart <<= 32;
  944. t.QuadPart |= f.dwLowDateTime;
  945. return t;
  946. }
  947. int clock_gettime(int X, struct timespec* tv) {
  948. LARGE_INTEGER t;
  949. FILETIME f;
  950. double microseconds;
  951. static LARGE_INTEGER offset;
  952. static double frequencyToMicroseconds;
  953. static int initialized = 0;
  954. static BOOL usePerformanceCounter = 0;
  955. if (!initialized) {
  956. LARGE_INTEGER performanceFrequency;
  957. initialized = 1;
  958. usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
  959. if (usePerformanceCounter) {
  960. QueryPerformanceCounter(&offset);
  961. frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
  962. }
  963. else {
  964. offset = gettime_offset();
  965. frequencyToMicroseconds = 10.;
  966. }
  967. }
  968. if (usePerformanceCounter) {
  969. QueryPerformanceCounter(&t);
  970. }
  971. else {
  972. GetSystemTimeAsFileTime(&f);
  973. t.QuadPart = f.dwHighDateTime;
  974. t.QuadPart <<= 32;
  975. t.QuadPart |= f.dwLowDateTime;
  976. }
  977. t.QuadPart -= offset.QuadPart;
  978. microseconds = (double)t.QuadPart / frequencyToMicroseconds;
  979. t.QuadPart = (LONGLONG)microseconds;
  980. tv->tv_sec = (long)(t.QuadPart / 1000000);
  981. tv->tv_nsec = t.QuadPart % 1000000 * 1000;
  982. return 0;
  983. }
  984. #elif __APPLE__ && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200 || __IPHONE_OS_VERSION_MIN_REQUIRED < 100000) && !defined(CLOCK_MONOTONIC)
  985. #define CLOCK_MONOTONIC 0
  986. int clock_gettime(int X, struct timespec* ts) {
  987. clock_serv_t cclock;
  988. mach_timespec_t mts;
  989. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  990. clock_get_time(cclock, &mts);
  991. mach_port_deallocate(mach_task_self(), cclock);
  992. ts->tv_sec = mts.tv_sec;
  993. ts->tv_nsec = mts.tv_nsec;
  994. return 0;
  995. }
  996. #endif
  997. uint32_t enet_time_get(void) {
  998. static uint64_t start_time_ns = 0;
  999. struct timespec ts;
  1000. #ifdef CLOCK_MONOTONIC_RAW
  1001. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  1002. #else
  1003. clock_gettime(CLOCK_MONOTONIC, &ts);
  1004. #endif
  1005. static const uint64_t ns_in_s = 1000 * 1000 * 1000;
  1006. static const uint64_t ns_in_ms = 1000 * 1000;
  1007. uint64_t current_time_ns = ts.tv_nsec + (uint64_t)ts.tv_sec * ns_in_s;
  1008. uint64_t offset_ns = ENET_ATOMIC_READ(&start_time_ns);
  1009. if (offset_ns == 0) {
  1010. uint64_t want_value = current_time_ns - 1 * ns_in_ms;
  1011. uint64_t old_value = ENET_ATOMIC_CAS(&start_time_ns, 0, want_value);
  1012. offset_ns = old_value == 0 ? want_value : old_value;
  1013. }
  1014. uint64_t result_in_ns = current_time_ns - offset_ns;
  1015. return (uint32_t)(result_in_ns / ns_in_ms);
  1016. }
  1017. /*
  1018. =======================================================================
  1019. Checksum
  1020. =======================================================================
  1021. */
  1022. static int initializedCRC32 = 0;
  1023. static uint32_t crcTable[256];
  1024. static uint32_t reflect_crc(int val, int bits) {
  1025. int result = 0, bit;
  1026. for (bit = 0; bit < bits; bit++) {
  1027. if (val & 1)
  1028. result |= 1 << (bits - 1 - bit);
  1029. val >>= 1;
  1030. }
  1031. return result;
  1032. }
  1033. static void initialize_crc32(void) {
  1034. int byte;
  1035. for (byte = 0; byte < 256; ++byte) {
  1036. uint32_t crc = reflect_crc(byte, 8) << 24;
  1037. int offset;
  1038. for (offset = 0; offset < 8; ++offset) {
  1039. if (crc & 0x80000000)
  1040. crc = (crc << 1) ^ 0x04c11db7;
  1041. else
  1042. crc <<= 1;
  1043. }
  1044. crcTable[byte] = reflect_crc(crc, 32);
  1045. }
  1046. initializedCRC32 = 1;
  1047. }
  1048. uint32_t enet_crc32(const ENetBuffer* buffers, size_t bufferCount) {
  1049. uint32_t crc = 0xFFFFFFFF;
  1050. if (!initializedCRC32)
  1051. initialize_crc32();
  1052. while (bufferCount-- > 0) {
  1053. const uint8_t* data = (const uint8_t*)buffers->data;
  1054. const uint8_t* dataEnd = &data[buffers->dataLength];
  1055. while (data < dataEnd) {
  1056. crc = (crc >> 8) ^ crcTable[(crc & 0xFF) ^ *data++];
  1057. }
  1058. ++buffers;
  1059. }
  1060. return ENET_HOST_TO_NET_32(~crc);
  1061. }
  1062. /*
  1063. =======================================================================
  1064. Packet
  1065. =======================================================================
  1066. */
  1067. ENetPacket* enet_packet_create(const void* data, size_t dataLength, uint32_t flags) {
  1068. ENetPacket* packet;
  1069. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1070. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1071. if (packet == NULL)
  1072. return NULL;
  1073. packet->data = (uint8_t*)data;
  1074. }
  1075. else {
  1076. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength);
  1077. if (packet == NULL)
  1078. return NULL;
  1079. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1080. if (data != NULL)
  1081. memcpy(packet->data, data, dataLength);
  1082. }
  1083. packet->referenceCount = 0;
  1084. packet->flags = flags;
  1085. packet->dataLength = dataLength;
  1086. packet->freeCallback = NULL;
  1087. packet->userData = NULL;
  1088. return packet;
  1089. }
  1090. ENetPacket* enet_packet_create_offset(const void* data, size_t dataLength, size_t dataOffset, uint32_t flags) {
  1091. ENetPacket* packet;
  1092. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1093. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1094. if (packet == NULL)
  1095. return NULL;
  1096. packet->data = (uint8_t*)data;
  1097. }
  1098. else {
  1099. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength - dataOffset);
  1100. if (packet == NULL)
  1101. return NULL;
  1102. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1103. if (data != NULL)
  1104. memcpy(packet->data, (char*)data + dataOffset, dataLength - dataOffset);
  1105. }
  1106. packet->referenceCount = 0;
  1107. packet->flags = flags;
  1108. packet->dataLength = dataLength - dataOffset;
  1109. packet->freeCallback = NULL;
  1110. packet->userData = NULL;
  1111. return packet;
  1112. }
  1113. void enet_packet_destroy(ENetPacket* packet) {
  1114. if (packet == NULL)
  1115. return;
  1116. if (packet->freeCallback != NULL)
  1117. (*packet->freeCallback)((void*)packet);
  1118. enet_free(packet);
  1119. }
  1120. /*
  1121. =======================================================================
  1122. Protocol
  1123. =======================================================================
  1124. */
  1125. static size_t commandSizes[ENET_PROTOCOL_COMMAND_COUNT] = {
  1126. 0,
  1127. sizeof(ENetProtocolAcknowledge),
  1128. sizeof(ENetProtocolConnect),
  1129. sizeof(ENetProtocolVerifyConnect),
  1130. sizeof(ENetProtocolDisconnect),
  1131. sizeof(ENetProtocolPing),
  1132. sizeof(ENetProtocolSendReliable),
  1133. sizeof(ENetProtocolSendUnreliable),
  1134. sizeof(ENetProtocolSendFragment),
  1135. sizeof(ENetProtocolSendUnsequenced),
  1136. sizeof(ENetProtocolBandwidthLimit),
  1137. sizeof(ENetProtocolThrottleConfigure),
  1138. sizeof(ENetProtocolSendFragment)
  1139. };
  1140. size_t enet_protocol_command_size(uint8_t commandNumber) {
  1141. return commandSizes[commandNumber & ENET_PROTOCOL_COMMAND_MASK];
  1142. }
  1143. static void enet_protocol_change_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1144. if (state == ENET_PEER_STATE_CONNECTED || state == ENET_PEER_STATE_DISCONNECT_LATER)
  1145. enet_peer_on_connect(peer);
  1146. else
  1147. enet_peer_on_disconnect(peer);
  1148. peer->state = state;
  1149. }
  1150. static void enet_protocol_dispatch_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1151. enet_protocol_change_state(host, peer, state);
  1152. if (!peer->needsDispatch) {
  1153. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1154. peer->needsDispatch = 1;
  1155. }
  1156. }
  1157. static int enet_protocol_dispatch_incoming_commands(ENetHost* host, ENetEvent* event) {
  1158. while (!enet_list_empty(&host->dispatchQueue)) {
  1159. ENetPeer* peer = (ENetPeer*)enet_list_remove(enet_list_begin(&host->dispatchQueue));
  1160. peer->needsDispatch = 0;
  1161. switch (peer->state) {
  1162. case ENET_PEER_STATE_CONNECTION_PENDING:
  1163. case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
  1164. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1165. event->type = ENET_EVENT_TYPE_CONNECT;
  1166. event->peer = peer;
  1167. event->data = peer->eventData;
  1168. return 1;
  1169. case ENET_PEER_STATE_ZOMBIE:
  1170. host->recalculateBandwidthLimits = 1;
  1171. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1172. event->peer = peer;
  1173. event->data = peer->eventData;
  1174. enet_peer_reset(peer);
  1175. return 1;
  1176. case ENET_PEER_STATE_CONNECTED:
  1177. if (enet_list_empty(&peer->dispatchedCommands))
  1178. continue;
  1179. event->packet = enet_peer_receive(peer, &event->channelID);
  1180. if (event->packet == NULL)
  1181. continue;
  1182. event->type = ENET_EVENT_TYPE_RECEIVE;
  1183. event->peer = peer;
  1184. if (!enet_list_empty(&peer->dispatchedCommands)) {
  1185. peer->needsDispatch = 1;
  1186. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1187. }
  1188. return 1;
  1189. default:
  1190. break;
  1191. }
  1192. }
  1193. return 0;
  1194. }
  1195. static void enet_protocol_notify_connect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1196. host->recalculateBandwidthLimits = 1;
  1197. if (event != NULL) {
  1198. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1199. peer->totalDataSent = 0;
  1200. peer->totalDataReceived = 0;
  1201. peer->totalPacketsSent = 0;
  1202. peer->totalPacketsLost = 0;
  1203. event->type = ENET_EVENT_TYPE_CONNECT;
  1204. event->peer = peer;
  1205. event->data = peer->eventData;
  1206. }
  1207. else {
  1208. enet_protocol_dispatch_state(host, peer, peer->state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING);
  1209. }
  1210. }
  1211. static void enet_protocol_notify_disconnect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1212. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1213. host->recalculateBandwidthLimits = 1;
  1214. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1215. enet_peer_reset(peer);
  1216. }
  1217. else if (event != NULL) {
  1218. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1219. event->peer = peer;
  1220. event->data = 0;
  1221. enet_peer_reset(peer);
  1222. }
  1223. else {
  1224. peer->eventData = 0;
  1225. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1226. }
  1227. }
  1228. static void enet_protocol_notify_disconnect_timeout(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1229. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1230. host->recalculateBandwidthLimits = 1;
  1231. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1232. enet_peer_reset(peer);
  1233. }
  1234. else if (event != NULL) {
  1235. event->type = ENET_EVENT_TYPE_DISCONNECT_TIMEOUT;
  1236. event->peer = peer;
  1237. event->data = 0;
  1238. enet_peer_reset(peer);
  1239. }
  1240. else {
  1241. peer->eventData = 0;
  1242. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1243. }
  1244. }
  1245. static void enet_protocol_remove_sent_unreliable_commands(ENetPeer* peer) {
  1246. ENetOutgoingCommand* outgoingCommand;
  1247. if (enet_list_empty(&peer->sentUnreliableCommands))
  1248. return;
  1249. do {
  1250. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentUnreliableCommands);
  1251. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1252. if (outgoingCommand->packet != NULL) {
  1253. --outgoingCommand->packet->referenceCount;
  1254. if (outgoingCommand->packet->referenceCount == 0) {
  1255. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1256. enet_packet_destroy(outgoingCommand->packet);
  1257. }
  1258. }
  1259. enet_free(outgoingCommand);
  1260. }
  1261. while (!enet_list_empty(&peer->sentUnreliableCommands));
  1262. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
  1263. enet_peer_disconnect(peer, peer->eventData);
  1264. }
  1265. static ENetProtocolCommand enet_protocol_remove_sent_reliable_command(ENetPeer* peer, uint16_t reliableSequenceNumber, uint8_t channelID) {
  1266. ENetOutgoingCommand* outgoingCommand = NULL;
  1267. ENetListIterator currentCommand;
  1268. ENetProtocolCommand commandNumber;
  1269. int wasSent = 1;
  1270. for (currentCommand = enet_list_begin(&peer->sentReliableCommands); currentCommand != enet_list_end(&peer->sentReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  1271. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1272. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1273. break;
  1274. }
  1275. if (currentCommand == enet_list_end(&peer->sentReliableCommands)) {
  1276. for (currentCommand = enet_list_begin(&peer->outgoingReliableCommands); currentCommand != enet_list_end(&peer->outgoingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  1277. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1278. if (outgoingCommand->sendAttempts < 1)
  1279. return ENET_PROTOCOL_COMMAND_NONE;
  1280. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1281. break;
  1282. }
  1283. if (currentCommand == enet_list_end(&peer->outgoingReliableCommands))
  1284. return ENET_PROTOCOL_COMMAND_NONE;
  1285. wasSent = 0;
  1286. }
  1287. if (outgoingCommand == NULL)
  1288. return ENET_PROTOCOL_COMMAND_NONE;
  1289. if (channelID < peer->channelCount) {
  1290. ENetChannel* channel = &peer->channels[channelID];
  1291. uint16_t reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1292. if (channel->reliableWindows[reliableWindow] > 0) {
  1293. --channel->reliableWindows[reliableWindow];
  1294. if (!channel->reliableWindows[reliableWindow])
  1295. channel->usedReliableWindows &= ~(1 << reliableWindow);
  1296. }
  1297. }
  1298. commandNumber = (ENetProtocolCommand)(outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK);
  1299. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1300. if (outgoingCommand->packet != NULL) {
  1301. if (wasSent)
  1302. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  1303. --outgoingCommand->packet->referenceCount;
  1304. if (outgoingCommand->packet->referenceCount == 0) {
  1305. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1306. enet_packet_destroy(outgoingCommand->packet);
  1307. }
  1308. }
  1309. enet_free(outgoingCommand);
  1310. if (enet_list_empty(&peer->sentReliableCommands))
  1311. return commandNumber;
  1312. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentReliableCommands);
  1313. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  1314. return commandNumber;
  1315. }
  1316. static ENetPeer* enet_protocol_handle_connect(ENetHost* host, ENetProtocolHeader* header, ENetProtocol* command) {
  1317. uint8_t incomingSessionID, outgoingSessionID;
  1318. uint32_t mtu, windowSize;
  1319. ENetChannel* channel;
  1320. size_t channelCount, duplicatePeers = 0;
  1321. ENetPeer* currentPeer, * peer = NULL;
  1322. ENetProtocol verifyCommand;
  1323. channelCount = ENET_NET_TO_HOST_32(command->connect.channelCount);
  1324. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  1325. return NULL;
  1326. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  1327. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
  1328. if (peer == NULL)
  1329. peer = currentPeer;
  1330. }
  1331. else if (currentPeer->state != ENET_PEER_STATE_CONNECTING && enet_in6_equal(currentPeer->address.ipv6, host->receivedAddress.ipv6)) {
  1332. if (currentPeer->address.port == host->receivedAddress.port && currentPeer->connectID == command->connect.connectID)
  1333. return NULL;
  1334. ++duplicatePeers;
  1335. }
  1336. }
  1337. if (peer == NULL || duplicatePeers >= host->duplicatePeers)
  1338. return NULL;
  1339. if (channelCount > host->channelLimit)
  1340. channelCount = host->channelLimit;
  1341. peer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  1342. if (peer->channels == NULL)
  1343. return NULL;
  1344. peer->channelCount = channelCount;
  1345. peer->state = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT;
  1346. peer->connectID = command->connect.connectID;
  1347. peer->address = host->receivedAddress;
  1348. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->connect.outgoingPeerID);
  1349. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->connect.incomingBandwidth);
  1350. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->connect.outgoingBandwidth);
  1351. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->connect.packetThrottleInterval);
  1352. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleAcceleration);
  1353. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleDeceleration);
  1354. peer->eventData = ENET_NET_TO_HOST_32(command->connect.data);
  1355. incomingSessionID = command->connect.incomingSessionID == 0xFF ? peer->outgoingSessionID : command->connect.incomingSessionID;
  1356. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1357. if (incomingSessionID == peer->outgoingSessionID)
  1358. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1359. peer->outgoingSessionID = incomingSessionID;
  1360. outgoingSessionID = command->connect.outgoingSessionID == 0xFF ? peer->incomingSessionID : command->connect.outgoingSessionID;
  1361. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1362. if (outgoingSessionID == peer->incomingSessionID)
  1363. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1364. peer->incomingSessionID = outgoingSessionID;
  1365. for (channel = peer->channels; channel < &peer->channels[channelCount]; ++channel) {
  1366. channel->outgoingReliableSequenceNumber = 0;
  1367. channel->outgoingUnreliableSequenceNumber = 0;
  1368. channel->incomingReliableSequenceNumber = 0;
  1369. channel->incomingUnreliableSequenceNumber = 0;
  1370. enet_list_clear(&channel->incomingReliableCommands);
  1371. enet_list_clear(&channel->incomingUnreliableCommands);
  1372. channel->usedReliableWindows = 0;
  1373. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  1374. }
  1375. mtu = ENET_NET_TO_HOST_32(command->connect.mtu);
  1376. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1377. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1378. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1379. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1380. peer->mtu = mtu;
  1381. if (host->outgoingBandwidth == 0 && peer->incomingBandwidth == 0)
  1382. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1383. else if (host->outgoingBandwidth == 0 || peer->incomingBandwidth == 0)
  1384. peer->windowSize = (ENET_MAX(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1385. else
  1386. peer->windowSize = (ENET_MIN(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1387. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1388. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1389. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1390. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1391. if (host->incomingBandwidth == 0)
  1392. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1393. else
  1394. windowSize = (host->incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1395. if (windowSize > ENET_NET_TO_HOST_32(command->connect.windowSize))
  1396. windowSize = ENET_NET_TO_HOST_32(command->connect.windowSize);
  1397. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1398. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1399. else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1400. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1401. verifyCommand.header.command = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  1402. verifyCommand.header.channelID = 0xFF;
  1403. verifyCommand.verifyConnect.outgoingPeerID = ENET_HOST_TO_NET_16(peer->incomingPeerID);
  1404. verifyCommand.verifyConnect.incomingSessionID = incomingSessionID;
  1405. verifyCommand.verifyConnect.outgoingSessionID = outgoingSessionID;
  1406. verifyCommand.verifyConnect.mtu = ENET_HOST_TO_NET_32(peer->mtu);
  1407. verifyCommand.verifyConnect.windowSize = ENET_HOST_TO_NET_32(windowSize);
  1408. verifyCommand.verifyConnect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  1409. verifyCommand.verifyConnect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  1410. verifyCommand.verifyConnect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  1411. verifyCommand.verifyConnect.packetThrottleInterval = ENET_HOST_TO_NET_32(peer->packetThrottleInterval);
  1412. verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(peer->packetThrottleAcceleration);
  1413. verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(peer->packetThrottleDeceleration);
  1414. verifyCommand.verifyConnect.connectID = peer->connectID;
  1415. enet_peer_queue_outgoing_command(peer, &verifyCommand, NULL, 0, 0);
  1416. return peer;
  1417. }
  1418. static int enet_protocol_handle_send_reliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1419. size_t dataLength;
  1420. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1421. ENET_LOG_ERROR("channel id is greater than the peer's channel count or the peer isn't in connected state and isn't pending disconnection later");
  1422. return -1;
  1423. }
  1424. dataLength = ENET_NET_TO_HOST_16(command->sendReliable.dataLength);
  1425. *currentData += dataLength;
  1426. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1427. ENET_LOG_ERROR("packet data length error");
  1428. return -1;
  1429. }
  1430. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) == NULL) {
  1431. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1432. return -1;
  1433. }
  1434. return 0;
  1435. }
  1436. static int enet_protocol_handle_send_unsequenced(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1437. uint32_t unsequencedGroup, index;
  1438. size_t dataLength;
  1439. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1440. ENET_LOG_ERROR("channel id is greater than the peer's channel count or the peer isn't in connected state and isn't pending disconnection later");
  1441. return -1;
  1442. }
  1443. dataLength = ENET_NET_TO_HOST_16(command->sendUnsequenced.dataLength);
  1444. *currentData += dataLength;
  1445. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1446. ENET_LOG_ERROR("packet data length error");
  1447. return -1;
  1448. }
  1449. unsequencedGroup = ENET_NET_TO_HOST_16(command->sendUnsequenced.unsequencedGroup);
  1450. index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE;
  1451. if (unsequencedGroup < peer->incomingUnsequencedGroup)
  1452. unsequencedGroup += 0x10000;
  1453. if (unsequencedGroup >= (uint32_t)peer->incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE)
  1454. return 0;
  1455. unsequencedGroup &= 0xFFFF;
  1456. if (unsequencedGroup - index != peer->incomingUnsequencedGroup) {
  1457. peer->incomingUnsequencedGroup = unsequencedGroup - index;
  1458. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  1459. }
  1460. else if (peer->unsequencedWindow[index / 32] & (1 << (index % 32))) {
  1461. return 0;
  1462. }
  1463. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED, 0) == NULL) {
  1464. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1465. return -1;
  1466. }
  1467. peer->unsequencedWindow[index / 32] |= 1 << (index % 32);
  1468. return 0;
  1469. }
  1470. static int enet_protocol_handle_send_unreliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1471. size_t dataLength;
  1472. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1473. ENET_LOG_ERROR("channel id is greater than the peer's channel count or the peer isn't in connected state and isn't pending disconnection later");
  1474. return -1;
  1475. }
  1476. dataLength = ENET_NET_TO_HOST_16(command->sendUnreliable.dataLength);
  1477. *currentData += dataLength;
  1478. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1479. ENET_LOG_ERROR("packet data length error");
  1480. return -1;
  1481. }
  1482. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnreliable), dataLength, 0, 0) == NULL) {
  1483. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1484. return -1;
  1485. }
  1486. return 0;
  1487. }
  1488. static int enet_protocol_handle_send_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1489. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength;
  1490. ENetChannel* channel;
  1491. uint16_t startWindow, currentWindow;
  1492. ENetListIterator currentCommand;
  1493. ENetIncomingCommand* startCommand = NULL;
  1494. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1495. ENET_LOG_ERROR("channel id is greater than the peer's channel count or the peer isn't in connected state and isn't pending disconnection later");
  1496. return -1;
  1497. }
  1498. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1499. *currentData += fragmentLength;
  1500. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1501. ENET_LOG_ERROR("packet data length error");
  1502. return -1;
  1503. }
  1504. channel = &peer->channels[command->header.channelID];
  1505. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1506. startWindow = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1507. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1508. if (startSequenceNumber < channel->incomingReliableSequenceNumber)
  1509. startWindow += ENET_PEER_RELIABLE_WINDOWS;
  1510. if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1511. return 0;
  1512. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1513. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1514. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1515. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1516. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
  1517. {
  1518. ENET_LOG_ERROR("fragmented packet error");
  1519. return -1;
  1520. }
  1521. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1522. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1523. if (startSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1524. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1525. continue;
  1526. }
  1527. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1528. break;
  1529. }
  1530. if (incomingCommand->reliableSequenceNumber <= startSequenceNumber) {
  1531. if (incomingCommand->reliableSequenceNumber < startSequenceNumber)
  1532. break;
  1533. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1534. {
  1535. ENET_LOG_ERROR("fragmented packet error");
  1536. return -1;
  1537. }
  1538. startCommand = incomingCommand;
  1539. break;
  1540. }
  1541. }
  1542. if (startCommand == NULL) {
  1543. ENetProtocol hostCommand = *command;
  1544. hostCommand.header.reliableSequenceNumber = startSequenceNumber;
  1545. startCommand = enet_peer_queue_incoming_command(peer, &hostCommand, NULL, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount);
  1546. if (startCommand == NULL)
  1547. {
  1548. ENET_LOG_ERROR("startCommand was NULL");
  1549. return -1;
  1550. }
  1551. }
  1552. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1553. --startCommand->fragmentsRemaining;
  1554. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1555. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1556. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1557. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1558. if (startCommand->fragmentsRemaining <= 0)
  1559. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  1560. }
  1561. return 0;
  1562. }
  1563. static int enet_protocol_handle_send_unreliable_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1564. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength;
  1565. uint16_t reliableWindow, currentWindow;
  1566. ENetChannel* channel;
  1567. ENetListIterator currentCommand;
  1568. ENetIncomingCommand* startCommand = NULL;
  1569. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1570. ENET_LOG_ERROR("channel id is greater than the peer's channel count or the peer isn't in connected state and isn't pending disconnection later");
  1571. return -1;
  1572. }
  1573. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1574. *currentData += fragmentLength;
  1575. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1576. ENET_LOG_ERROR("fragmented packet error");
  1577. return -1;
  1578. }
  1579. channel = &peer->channels[command->header.channelID];
  1580. reliableSequenceNumber = command->header.reliableSequenceNumber;
  1581. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1582. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1583. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1584. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1585. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  1586. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1587. return 0;
  1588. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && startSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  1589. return 0;
  1590. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1591. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1592. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1593. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1594. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset) {
  1595. ENET_LOG_ERROR("Exceeded maximum number of fragments, the total length is more than the packet size, the offset is out of bounds or the fragment is too big");
  1596. return -1;
  1597. }
  1598. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1599. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1600. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1601. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1602. continue;
  1603. }
  1604. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1605. break;
  1606. }
  1607. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  1608. break;
  1609. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  1610. continue;
  1611. if (incomingCommand->unreliableSequenceNumber <= startSequenceNumber) {
  1612. if (incomingCommand->unreliableSequenceNumber < startSequenceNumber)
  1613. break;
  1614. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1615. {
  1616. ENET_LOG_ERROR("fragmented packet error");
  1617. return -1;
  1618. }
  1619. startCommand = incomingCommand;
  1620. break;
  1621. }
  1622. }
  1623. if (startCommand == NULL) {
  1624. startCommand = enet_peer_queue_incoming_command(peer, command, NULL, totalLength,
  1625. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED, fragmentCount);
  1626. if (startCommand == NULL) {
  1627. ENET_LOG_ERROR("startCommand was NULL");
  1628. return -1;
  1629. }
  1630. }
  1631. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1632. --startCommand->fragmentsRemaining;
  1633. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1634. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1635. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1636. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1637. if (startCommand->fragmentsRemaining <= 0)
  1638. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  1639. }
  1640. return 0;
  1641. }
  1642. static int enet_protocol_handle_ping(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1643. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1644. return -1;
  1645. return 0;
  1646. }
  1647. static int enet_protocol_handle_bandwidth_limit(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1648. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1649. {
  1650. ENET_LOG_ERROR("Doing jack squat on a peer that is not connected correctly");
  1651. return -1;
  1652. }
  1653. if (peer->incomingBandwidth != 0)
  1654. --host->bandwidthLimitedPeers;
  1655. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.incomingBandwidth);
  1656. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.outgoingBandwidth);
  1657. if (peer->incomingBandwidth != 0)
  1658. ++host->bandwidthLimitedPeers;
  1659. if (peer->incomingBandwidth == 0 && host->outgoingBandwidth == 0)
  1660. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1661. else if (peer->incomingBandwidth == 0 || host->outgoingBandwidth == 0)
  1662. peer->windowSize = (ENET_MAX(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1663. else
  1664. peer->windowSize = (ENET_MIN(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1665. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1666. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1667. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1668. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1669. return 0;
  1670. }
  1671. static int enet_protocol_handle_throttle_configure(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1672. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1673. {
  1674. ENET_LOG_ERROR("Doing jack squat on a peer that is not connected correctly");
  1675. return -1;
  1676. }
  1677. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleInterval);
  1678. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleAcceleration);
  1679. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleDeceleration);
  1680. return 0;
  1681. }
  1682. static int enet_protocol_handle_disconnect(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1683. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT)
  1684. return 0;
  1685. enet_peer_reset_queues(peer);
  1686. if (peer->state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_CONNECTING) {
  1687. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1688. }
  1689. else if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1690. if (peer->state == ENET_PEER_STATE_CONNECTION_PENDING)
  1691. host->recalculateBandwidthLimits = 1;
  1692. enet_peer_reset(peer);
  1693. }
  1694. else if (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  1695. enet_protocol_change_state(host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT);
  1696. }
  1697. else {
  1698. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1699. }
  1700. if (peer->state != ENET_PEER_STATE_DISCONNECTED)
  1701. peer->eventData = ENET_NET_TO_HOST_32(command->disconnect.data);
  1702. return 0;
  1703. }
  1704. static int enet_protocol_handle_acknowledge(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1705. uint32_t roundTripTime, receivedSentTime, receivedReliableSequenceNumber;
  1706. ENetProtocolCommand commandNumber;
  1707. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE)
  1708. return 0;
  1709. receivedSentTime = ENET_NET_TO_HOST_16(command->acknowledge.receivedSentTime);
  1710. receivedSentTime |= host->serviceTime & 0xFFFF0000;
  1711. if ((receivedSentTime & 0x8000) > (host->serviceTime & 0x8000))
  1712. receivedSentTime -= 0x10000;
  1713. if (ENET_TIME_LESS(host->serviceTime, receivedSentTime))
  1714. return 0;
  1715. roundTripTime = ENET_TIME_DIFFERENCE(host->serviceTime, receivedSentTime);
  1716. if (roundTripTime == 0)
  1717. roundTripTime = 1;
  1718. enet_peer_throttle(peer, roundTripTime);
  1719. if (peer->lastReceiveTime > 0) {
  1720. if (roundTripTime >= peer->roundTripTime) {
  1721. uint32_t diff = roundTripTime - peer->roundTripTime;
  1722. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1723. peer->roundTripTimeVariance += diff / 4;
  1724. peer->roundTripTime += diff / 8;
  1725. }
  1726. else {
  1727. uint32_t diff = peer->roundTripTime - roundTripTime;
  1728. if (diff <= peer->roundTripTimeVariance) {
  1729. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1730. peer->roundTripTimeVariance += diff / 4;
  1731. }
  1732. else {
  1733. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 32;
  1734. peer->roundTripTimeVariance += diff / 32;
  1735. }
  1736. peer->roundTripTime -= diff / 8;
  1737. }
  1738. }
  1739. else {
  1740. peer->roundTripTime = roundTripTime;
  1741. peer->roundTripTimeVariance = roundTripTime / 2;
  1742. }
  1743. if (peer->roundTripTime < peer->lowestRoundTripTime)
  1744. peer->lowestRoundTripTime = peer->roundTripTime;
  1745. if (peer->roundTripTimeVariance > peer->highestRoundTripTimeVariance)
  1746. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1747. if (peer->packetThrottleEpoch == 0 || ENET_TIME_DIFFERENCE(host->serviceTime, peer->packetThrottleEpoch) >= peer->packetThrottleInterval) {
  1748. peer->lastRoundTripTime = peer->lowestRoundTripTime;
  1749. peer->lastRoundTripTimeVariance = peer->highestRoundTripTimeVariance;
  1750. peer->lowestRoundTripTime = peer->roundTripTime;
  1751. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1752. peer->packetThrottleEpoch = host->serviceTime;
  1753. }
  1754. peer->lastReceiveTime = ENET_MAX(host->serviceTime, 1);
  1755. peer->earliestTimeout = 0;
  1756. receivedReliableSequenceNumber = ENET_NET_TO_HOST_16(command->acknowledge.receivedReliableSequenceNumber);
  1757. commandNumber = enet_protocol_remove_sent_reliable_command(peer, receivedReliableSequenceNumber, command->header.channelID);
  1758. switch (peer->state) {
  1759. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1760. if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT) {
  1761. ENET_LOG_ERROR("Wrong command number. Got %u vs %u", commandNumber, ENET_PROTOCOL_COMMAND_VERIFY_CONNECT);
  1762. return -1;
  1763. }
  1764. enet_protocol_notify_connect(host, peer, event);
  1765. break;
  1766. case ENET_PEER_STATE_DISCONNECTING:
  1767. if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT)
  1768. {
  1769. ENET_LOG_ERROR("Wrong command number. Got %u vs %u", commandNumber, ENET_PROTOCOL_COMMAND_DISCONNECT);
  1770. return -1;
  1771. }
  1772. enet_protocol_notify_disconnect(host, peer, event);
  1773. break;
  1774. case ENET_PEER_STATE_DISCONNECT_LATER:
  1775. if (enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
  1776. enet_peer_disconnect(peer, peer->eventData);
  1777. break;
  1778. default:
  1779. break;
  1780. }
  1781. return 0;
  1782. }
  1783. static int enet_protocol_handle_verify_connect(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1784. uint32_t mtu, windowSize;
  1785. size_t channelCount;
  1786. if (peer->state != ENET_PEER_STATE_CONNECTING)
  1787. return 0;
  1788. channelCount = ENET_NET_TO_HOST_32(command->verifyConnect.channelCount);
  1789. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleInterval) != peer->packetThrottleInterval || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleAcceleration) != peer->packetThrottleAcceleration || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleDeceleration) != peer->packetThrottleDeceleration || command->verifyConnect.connectID != peer->connectID) {
  1790. peer->eventData = 0;
  1791. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1792. ENET_LOG_ERROR("Zombie peer detected");
  1793. return -1;
  1794. }
  1795. enet_protocol_remove_sent_reliable_command(peer, 1, 0xFF);
  1796. if (channelCount < peer->channelCount)
  1797. peer->channelCount = channelCount;
  1798. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->verifyConnect.outgoingPeerID);
  1799. peer->incomingSessionID = command->verifyConnect.incomingSessionID;
  1800. peer->outgoingSessionID = command->verifyConnect.outgoingSessionID;
  1801. mtu = ENET_NET_TO_HOST_32(command->verifyConnect.mtu);
  1802. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1803. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1804. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1805. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1806. if (mtu < peer->mtu)
  1807. peer->mtu = mtu;
  1808. windowSize = ENET_NET_TO_HOST_32(command->verifyConnect.windowSize);
  1809. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1810. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1811. if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1812. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1813. if (windowSize < peer->windowSize)
  1814. peer->windowSize = windowSize;
  1815. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.incomingBandwidth);
  1816. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.outgoingBandwidth);
  1817. enet_protocol_notify_connect(host, peer, event);
  1818. return 0;
  1819. }
  1820. static int enet_protocol_handle_incoming_commands(ENetHost* host, ENetEvent* event) {
  1821. ENetProtocolHeader* header;
  1822. ENetProtocol* command;
  1823. ENetPeer* peer;
  1824. uint8_t* currentData;
  1825. size_t headerSize;
  1826. uint16_t peerID, flags;
  1827. uint8_t sessionID;
  1828. if (host->receivedDataLength < (size_t) & ((ENetProtocolHeader*)0)->sentTime)
  1829. return 0;
  1830. header = (ENetProtocolHeader*)host->receivedData;
  1831. peerID = ENET_NET_TO_HOST_16(header->peerID);
  1832. sessionID = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  1833. flags = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK;
  1834. peerID &= ~(ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK);
  1835. headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof(ENetProtocolHeader) : (size_t) & ((ENetProtocolHeader*)0)->sentTime);
  1836. if (host->checksumCallback != NULL)
  1837. headerSize += sizeof(uint32_t);
  1838. if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  1839. peer = NULL;
  1840. }
  1841. else if (peerID >= host->peerCount) {
  1842. return 0;
  1843. }
  1844. else {
  1845. peer = &host->peers[peerID];
  1846. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || ((!enet_in6_equal(host->receivedAddress.ipv6, peer->address.ipv6) || host->receivedAddress.port != peer->address.port) && peer->address.ipv4.ip.s_addr != INADDR_BROADCAST) || (peer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID && sessionID != peer->incomingSessionID))
  1847. return 0;
  1848. }
  1849. if (host->checksumCallback != NULL) {
  1850. uint32_t* checksum = (uint32_t*)&host->receivedData[headerSize - sizeof(uint32_t)];
  1851. uint32_t desiredChecksum = *checksum;
  1852. ENetBuffer buffer;
  1853. *checksum = peer != NULL ? peer->connectID : 0;
  1854. buffer.data = host->receivedData;
  1855. buffer.dataLength = host->receivedDataLength;
  1856. if (host->checksumCallback(&buffer, 1) != desiredChecksum)
  1857. return 0;
  1858. }
  1859. if (peer != NULL) {
  1860. peer->address.ipv6 = host->receivedAddress.ipv6;
  1861. peer->address.port = host->receivedAddress.port;
  1862. peer->incomingDataTotal += host->receivedDataLength;
  1863. peer->totalDataReceived += host->receivedDataLength;
  1864. }
  1865. currentData = host->receivedData + headerSize;
  1866. while (currentData < &host->receivedData[host->receivedDataLength]) {
  1867. uint8_t commandNumber;
  1868. size_t commandSize;
  1869. command = (ENetProtocol*)currentData;
  1870. if (currentData + sizeof(ENetProtocolCommandHeader) > & host->receivedData[host->receivedDataLength])
  1871. break;
  1872. commandNumber = command->header.command & ENET_PROTOCOL_COMMAND_MASK;
  1873. if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT)
  1874. break;
  1875. commandSize = commandSizes[commandNumber];
  1876. if (commandSize == 0 || currentData + commandSize > & host->receivedData[host->receivedDataLength])
  1877. break;
  1878. currentData += commandSize;
  1879. if (peer == NULL && (commandNumber != ENET_PROTOCOL_COMMAND_CONNECT || currentData < &host->receivedData[host->receivedDataLength]))
  1880. break;
  1881. command->header.reliableSequenceNumber = ENET_NET_TO_HOST_16(command->header.reliableSequenceNumber);
  1882. switch (commandNumber) {
  1883. case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE:
  1884. if (enet_protocol_handle_acknowledge(host, event, peer, command))
  1885. goto commandError;
  1886. break;
  1887. case ENET_PROTOCOL_COMMAND_CONNECT:
  1888. if (peer != NULL)
  1889. goto commandError;
  1890. if (host->preventConnections == 0) {
  1891. peer = enet_protocol_handle_connect(host, header, command);
  1892. if (peer == NULL)
  1893. goto commandError;
  1894. }
  1895. break;
  1896. case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT:
  1897. if (enet_protocol_handle_verify_connect(host, event, peer, command))
  1898. goto commandError;
  1899. break;
  1900. case ENET_PROTOCOL_COMMAND_DISCONNECT:
  1901. if (enet_protocol_handle_disconnect(host, peer, command))
  1902. goto commandError;
  1903. break;
  1904. case ENET_PROTOCOL_COMMAND_PING:
  1905. if (enet_protocol_handle_ping(host, peer, command))
  1906. goto commandError;
  1907. break;
  1908. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  1909. if (enet_protocol_handle_send_reliable(host, peer, command, &currentData))
  1910. goto commandError;
  1911. break;
  1912. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  1913. if (enet_protocol_handle_send_unreliable(host, peer, command, &currentData))
  1914. goto commandError;
  1915. break;
  1916. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  1917. if (enet_protocol_handle_send_unsequenced(host, peer, command, &currentData))
  1918. goto commandError;
  1919. break;
  1920. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  1921. if (enet_protocol_handle_send_fragment(host, peer, command, &currentData))
  1922. goto commandError;
  1923. break;
  1924. case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT:
  1925. if (enet_protocol_handle_bandwidth_limit(host, peer, command))
  1926. goto commandError;
  1927. break;
  1928. case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE:
  1929. if (enet_protocol_handle_throttle_configure(host, peer, command))
  1930. goto commandError;
  1931. break;
  1932. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  1933. if (enet_protocol_handle_send_unreliable_fragment(host, peer, command, &currentData))
  1934. goto commandError;
  1935. break;
  1936. default:
  1937. goto commandError;
  1938. }
  1939. if (peer != NULL && (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) {
  1940. uint16_t sentTime;
  1941. if (!(flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME))
  1942. break;
  1943. sentTime = ENET_NET_TO_HOST_16(header->sentTime);
  1944. switch (peer->state) {
  1945. case ENET_PEER_STATE_DISCONNECTING:
  1946. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1947. case ENET_PEER_STATE_DISCONNECTED:
  1948. case ENET_PEER_STATE_ZOMBIE:
  1949. break;
  1950. case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
  1951. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  1952. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1953. break;
  1954. default:
  1955. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1956. break;
  1957. }
  1958. }
  1959. }
  1960. commandError:
  1961. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  1962. return 1;
  1963. return 0;
  1964. }
  1965. static int enet_protocol_receive_incoming_commands(ENetHost* host, ENetEvent* event) {
  1966. int packets;
  1967. for (packets = 0; packets < 256; ++packets) {
  1968. int receivedLength;
  1969. ENetBuffer buffer;
  1970. buffer.data = host->packetData[0];
  1971. buffer.dataLength = host->mtu;
  1972. receivedLength = enet_socket_receive(host->socket, &host->receivedAddress, &buffer, 1);
  1973. if (receivedLength == -2)
  1974. continue;
  1975. if (receivedLength < 0) {
  1976. ENET_LOG_ERROR("received length was negative: %i", receivedLength);
  1977. return -1;
  1978. }
  1979. if (receivedLength == 0)
  1980. return 0;
  1981. host->receivedData = host->packetData[0];
  1982. host->receivedDataLength = receivedLength;
  1983. host->totalReceivedData += receivedLength;
  1984. host->totalReceivedPackets++;
  1985. if (host->interceptCallback != NULL) {
  1986. switch (host->interceptCallback(host, (void*)event)) {
  1987. case 1:
  1988. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  1989. return 1;
  1990. continue;
  1991. case -1:
  1992. ENET_LOG_ERROR("intercept callback failure");
  1993. return -1;
  1994. default:
  1995. break;
  1996. }
  1997. }
  1998. switch (enet_protocol_handle_incoming_commands(host, event)) {
  1999. case 1:
  2000. return 1;
  2001. case -1:
  2002. ENET_LOG_ERROR("enet_protocol_handle_incoming_commands failure");
  2003. return -1;
  2004. default:
  2005. break;
  2006. }
  2007. }
  2008. // Fix as described here: https://github.com/lsalzman/enet/pull/120
  2009. return 0;
  2010. }
  2011. static void enet_protocol_send_acknowledgements(ENetHost* host, ENetPeer* peer) {
  2012. ENetProtocol* command = &host->commands[host->commandCount];
  2013. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2014. ENetAcknowledgement* acknowledgement;
  2015. ENetListIterator currentAcknowledgement;
  2016. uint16_t reliableSequenceNumber;
  2017. currentAcknowledgement = enet_list_begin(&peer->acknowledgements);
  2018. while (currentAcknowledgement != enet_list_end(&peer->acknowledgements)) {
  2019. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < sizeof(ENetProtocolAcknowledge)) {
  2020. host->continueSending = 1;
  2021. break;
  2022. }
  2023. acknowledgement = (ENetAcknowledgement*)currentAcknowledgement;
  2024. currentAcknowledgement = enet_list_next(currentAcknowledgement);
  2025. buffer->data = command;
  2026. buffer->dataLength = sizeof(ENetProtocolAcknowledge);
  2027. host->packetSize += buffer->dataLength;
  2028. reliableSequenceNumber = ENET_HOST_TO_NET_16(acknowledgement->command.header.reliableSequenceNumber);
  2029. command->header.command = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
  2030. command->header.channelID = acknowledgement->command.header.channelID;
  2031. command->header.reliableSequenceNumber = reliableSequenceNumber;
  2032. command->acknowledge.receivedReliableSequenceNumber = reliableSequenceNumber;
  2033. command->acknowledge.receivedSentTime = ENET_HOST_TO_NET_16(acknowledgement->sentTime);
  2034. if ((acknowledgement->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  2035. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  2036. enet_list_remove(&acknowledgement->acknowledgementList);
  2037. enet_free(acknowledgement);
  2038. ++command;
  2039. ++buffer;
  2040. }
  2041. host->commandCount = command - host->commands;
  2042. host->bufferCount = buffer - host->buffers;
  2043. }
  2044. static void enet_protocol_send_unreliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
  2045. ENetProtocol* command = &host->commands[host->commandCount];
  2046. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2047. ENetOutgoingCommand* outgoingCommand;
  2048. ENetListIterator currentCommand;
  2049. currentCommand = enet_list_begin(&peer->outgoingUnreliableCommands);
  2050. while (currentCommand != enet_list_end(&peer->outgoingUnreliableCommands)) {
  2051. size_t commandSize;
  2052. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2053. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2054. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < commandSize || (outgoingCommand->packet != NULL && peer->mtu - host->packetSize < commandSize + outgoingCommand->fragmentLength)) {
  2055. host->continueSending = 1;
  2056. break;
  2057. }
  2058. currentCommand = enet_list_next(currentCommand);
  2059. if (outgoingCommand->packet != NULL && outgoingCommand->fragmentOffset == 0) {
  2060. peer->packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER;
  2061. peer->packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE;
  2062. if (!(outgoingCommand->packet->flags & (ENET_PACKET_FLAG_CRUCIAL)) && peer->packetThrottleCounter > peer->packetThrottle) {
  2063. uint16_t reliableSequenceNumber = outgoingCommand->reliableSequenceNumber;
  2064. uint16_t unreliableSequenceNumber = outgoingCommand->unreliableSequenceNumber;
  2065. for (;;) {
  2066. --outgoingCommand->packet->referenceCount;
  2067. if (outgoingCommand->packet->referenceCount == 0)
  2068. enet_packet_destroy(outgoingCommand->packet);
  2069. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2070. enet_free(outgoingCommand);
  2071. if (currentCommand == enet_list_end(&peer->outgoingUnreliableCommands))
  2072. break;
  2073. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2074. if (outgoingCommand->reliableSequenceNumber != reliableSequenceNumber || outgoingCommand->unreliableSequenceNumber != unreliableSequenceNumber)
  2075. break;
  2076. currentCommand = enet_list_next(currentCommand);
  2077. }
  2078. continue;
  2079. }
  2080. }
  2081. buffer->data = command;
  2082. buffer->dataLength = commandSize;
  2083. host->packetSize += buffer->dataLength;
  2084. *command = outgoingCommand->command;
  2085. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2086. if (outgoingCommand->packet != NULL) {
  2087. ++buffer;
  2088. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2089. buffer->dataLength = outgoingCommand->fragmentLength;
  2090. host->packetSize += buffer->dataLength;
  2091. enet_list_insert(enet_list_end(&peer->sentUnreliableCommands), outgoingCommand);
  2092. }
  2093. else {
  2094. enet_free(outgoingCommand);
  2095. }
  2096. ++command;
  2097. ++buffer;
  2098. }
  2099. host->commandCount = command - host->commands;
  2100. host->bufferCount = buffer - host->buffers;
  2101. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands) && enet_list_empty(&peer->sentUnreliableCommands))
  2102. enet_peer_disconnect(peer, peer->eventData);
  2103. }
  2104. static int enet_protocol_check_timeouts(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  2105. ENetOutgoingCommand* outgoingCommand;
  2106. ENetListIterator currentCommand, insertPosition;
  2107. currentCommand = enet_list_begin(&peer->sentReliableCommands);
  2108. insertPosition = enet_list_begin(&peer->outgoingReliableCommands);
  2109. while (currentCommand != enet_list_end(&peer->sentReliableCommands)) {
  2110. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2111. currentCommand = enet_list_next(currentCommand);
  2112. if (ENET_TIME_DIFFERENCE(host->serviceTime, outgoingCommand->sentTime) < outgoingCommand->roundTripTimeout)
  2113. continue;
  2114. if (peer->earliestTimeout == 0 || ENET_TIME_LESS(outgoingCommand->sentTime, peer->earliestTimeout))
  2115. peer->earliestTimeout = outgoingCommand->sentTime;
  2116. if (peer->earliestTimeout != 0 && (ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMaximum || (outgoingCommand->roundTripTimeout >= outgoingCommand->roundTripTimeoutLimit && ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMinimum))) {
  2117. enet_protocol_notify_disconnect_timeout(host, peer, event);
  2118. return 1;
  2119. }
  2120. if (outgoingCommand->packet != NULL)
  2121. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  2122. ++peer->packetsLost;
  2123. ++peer->totalPacketsLost;
  2124. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2125. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2126. enet_list_insert(insertPosition, enet_list_remove(&outgoingCommand->outgoingCommandList));
  2127. if (currentCommand == enet_list_begin(&peer->sentReliableCommands) && !enet_list_empty(&peer->sentReliableCommands)) {
  2128. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2129. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  2130. }
  2131. }
  2132. return 0;
  2133. }
  2134. static int enet_protocol_send_reliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
  2135. ENetProtocol* command = &host->commands[host->commandCount];
  2136. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2137. ENetOutgoingCommand* outgoingCommand;
  2138. ENetListIterator currentCommand;
  2139. ENetChannel* channel;
  2140. uint16_t reliableWindow;
  2141. size_t commandSize;
  2142. int windowExceeded = 0, windowWrap = 0, canPing = 1;
  2143. currentCommand = enet_list_begin(&peer->outgoingReliableCommands);
  2144. while (currentCommand != enet_list_end(&peer->outgoingReliableCommands)) {
  2145. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2146. channel = outgoingCommand->command.header.channelID < peer->channelCount ? &peer->channels[outgoingCommand->command.header.channelID] : NULL;
  2147. reliableWindow = outgoingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2148. if (channel != NULL) {
  2149. if (!windowWrap && outgoingCommand->sendAttempts < 1 && !(outgoingCommand->reliableSequenceNumber % ENET_PEER_RELIABLE_WINDOW_SIZE) && (channel->reliableWindows[(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1) % ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE || channel->usedReliableWindows & ((((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) << reliableWindow) | (((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) >> (ENET_PEER_RELIABLE_WINDOWS - reliableWindow)))))
  2150. windowWrap = 1;
  2151. if (windowWrap) {
  2152. currentCommand = enet_list_next(currentCommand);
  2153. continue;
  2154. }
  2155. }
  2156. if (outgoingCommand->packet != NULL) {
  2157. if (!windowExceeded) {
  2158. uint32_t windowSize = (peer->packetThrottle * peer->windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE;
  2159. if (peer->reliableDataInTransit + outgoingCommand->fragmentLength > ENET_MAX(windowSize, peer->mtu))
  2160. windowExceeded = 1;
  2161. }
  2162. if (windowExceeded) {
  2163. currentCommand = enet_list_next(currentCommand);
  2164. continue;
  2165. }
  2166. }
  2167. canPing = 0;
  2168. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2169. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < commandSize || (outgoingCommand->packet != NULL && (uint16_t)(peer->mtu - host->packetSize) < (uint16_t)(commandSize + outgoingCommand->fragmentLength))) {
  2170. host->continueSending = 1;
  2171. break;
  2172. }
  2173. currentCommand = enet_list_next(currentCommand);
  2174. if (channel != NULL && outgoingCommand->sendAttempts < 1) {
  2175. channel->usedReliableWindows |= 1 << reliableWindow;
  2176. ++channel->reliableWindows[reliableWindow];
  2177. }
  2178. ++outgoingCommand->sendAttempts;
  2179. if (outgoingCommand->roundTripTimeout == 0) {
  2180. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2181. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2182. }
  2183. if (enet_list_empty(&peer->sentReliableCommands))
  2184. peer->nextTimeout = host->serviceTime + outgoingCommand->roundTripTimeout;
  2185. enet_list_insert(enet_list_end(&peer->sentReliableCommands), enet_list_remove(&outgoingCommand->outgoingCommandList));
  2186. outgoingCommand->sentTime = host->serviceTime;
  2187. buffer->data = command;
  2188. buffer->dataLength = commandSize;
  2189. host->packetSize += buffer->dataLength;
  2190. host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
  2191. *command = outgoingCommand->command;
  2192. if (outgoingCommand->packet != NULL) {
  2193. ++buffer;
  2194. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2195. buffer->dataLength = outgoingCommand->fragmentLength;
  2196. host->packetSize += outgoingCommand->fragmentLength;
  2197. peer->reliableDataInTransit += outgoingCommand->fragmentLength;
  2198. }
  2199. ++peer->packetsSent;
  2200. ++peer->totalPacketsSent;
  2201. ++command;
  2202. ++buffer;
  2203. }
  2204. host->commandCount = command - host->commands;
  2205. host->bufferCount = buffer - host->buffers;
  2206. return canPing;
  2207. }
  2208. static int enet_protocol_send_outgoing_commands(ENetHost* host, ENetEvent* event, int checkForTimeouts) {
  2209. uint8_t headerData[sizeof(ENetProtocolHeader) + sizeof(uint32_t)];
  2210. ENetProtocolHeader* header = (ENetProtocolHeader*)headerData;
  2211. ENetPeer* currentPeer;
  2212. int sentLength;
  2213. host->continueSending = 1;
  2214. while (host->continueSending) {
  2215. for (host->continueSending = 0, currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2216. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED || currentPeer->state == ENET_PEER_STATE_ZOMBIE)
  2217. continue;
  2218. host->headerFlags = 0;
  2219. host->commandCount = 0;
  2220. host->bufferCount = 1;
  2221. host->packetSize = sizeof(ENetProtocolHeader);
  2222. if (!enet_list_empty(&currentPeer->acknowledgements))
  2223. enet_protocol_send_acknowledgements(host, currentPeer);
  2224. if (checkForTimeouts != 0 && !enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_GREATER_EQUAL(host->serviceTime, currentPeer->nextTimeout) && enet_protocol_check_timeouts(host, currentPeer, event) == 1) {
  2225. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  2226. return 1;
  2227. else
  2228. continue;
  2229. }
  2230. if ((enet_list_empty(&currentPeer->outgoingReliableCommands) || enet_protocol_send_reliable_outgoing_commands(host, currentPeer)) && enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->lastReceiveTime) >= currentPeer->pingInterval && currentPeer->mtu - host->packetSize >= sizeof(ENetProtocolPing)) {
  2231. enet_peer_ping(currentPeer);
  2232. enet_protocol_send_reliable_outgoing_commands(host, currentPeer);
  2233. }
  2234. if (!enet_list_empty(&currentPeer->outgoingUnreliableCommands))
  2235. enet_protocol_send_unreliable_outgoing_commands(host, currentPeer);
  2236. if (host->commandCount == 0)
  2237. continue;
  2238. if (currentPeer->packetLossEpoch == 0) {
  2239. currentPeer->packetLossEpoch = host->serviceTime;
  2240. }
  2241. else if (ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL && currentPeer->packetsSent > 0) {
  2242. uint32_t packetLoss = currentPeer->packetsLost * ENET_PEER_PACKET_LOSS_SCALE / currentPeer->packetsSent;
  2243. ENET_LOG_TRACE(
  2244. "Peer %u: %3.3f%% (+-%3.3f%%) pkt loss, %u ms RTT (+-%u ms Jitter), %3.2f%% Throttle, rel. list sizes: %u/%u out, %u/%u in", currentPeer->incomingPeerID,
  2245. (currentPeer->packetLoss / (float)ENET_PEER_PACKET_LOSS_SCALE) * 100,
  2246. (currentPeer->packetLossVariance / (float)ENET_PEER_PACKET_LOSS_SCALE) * 100, currentPeer->roundTripTime, currentPeer->roundTripTimeVariance,
  2247. (currentPeer->packetThrottle / (float)ENET_PEER_PACKET_THROTTLE_SCALE) * 100,
  2248. enet_list_size(&currentPeer->outgoingReliableCommands),
  2249. enet_list_size(&currentPeer->outgoingUnreliableCommands),
  2250. currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingReliableCommands) : 0,
  2251. currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingUnreliableCommands) : 0
  2252. );
  2253. currentPeer->packetLossVariance -= currentPeer->packetLossVariance / 4;
  2254. if (packetLoss >= currentPeer->packetLoss) {
  2255. currentPeer->packetLoss += (packetLoss - currentPeer->packetLoss) / 8;
  2256. currentPeer->packetLossVariance += (packetLoss - currentPeer->packetLoss) / 4;
  2257. }
  2258. else {
  2259. currentPeer->packetLoss -= (currentPeer->packetLoss - packetLoss) / 8;
  2260. currentPeer->packetLossVariance += (currentPeer->packetLoss - packetLoss) / 4;
  2261. }
  2262. currentPeer->packetLossEpoch = host->serviceTime;
  2263. currentPeer->packetsSent = 0;
  2264. currentPeer->packetsLost = 0;
  2265. }
  2266. host->buffers->data = headerData;
  2267. if (host->headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) {
  2268. header->sentTime = ENET_HOST_TO_NET_16(host->serviceTime & 0xFFFF);
  2269. host->buffers->dataLength = sizeof(ENetProtocolHeader);
  2270. }
  2271. else {
  2272. host->buffers->dataLength = (size_t) & ((ENetProtocolHeader*)0)->sentTime;
  2273. }
  2274. if (currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID)
  2275. host->headerFlags |= currentPeer->outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  2276. header->peerID = ENET_HOST_TO_NET_16(currentPeer->outgoingPeerID | host->headerFlags);
  2277. if (host->checksumCallback != NULL) {
  2278. uint32_t* checksum = (uint32_t*)&headerData[host->buffers->dataLength];
  2279. *checksum = currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer->connectID : 0;
  2280. host->buffers->dataLength += sizeof(uint32_t);
  2281. *checksum = host->checksumCallback(host->buffers, host->bufferCount);
  2282. }
  2283. currentPeer->lastSendTime = host->serviceTime;
  2284. sentLength = enet_socket_send(host->socket, &currentPeer->address, host->buffers, host->bufferCount);
  2285. enet_protocol_remove_sent_unreliable_commands(currentPeer);
  2286. if (sentLength < 0) {
  2287. ENET_LOG_ERROR("sentLength was negative: %i", sentLength);
  2288. return -1;
  2289. }
  2290. host->totalSentData += sentLength;
  2291. currentPeer->totalDataSent += sentLength;
  2292. host->totalSentPackets++;
  2293. }
  2294. }
  2295. return 0;
  2296. }
  2297. void enet_host_flush(ENetHost* host) {
  2298. host->serviceTime = enet_time_get();
  2299. enet_protocol_send_outgoing_commands(host, NULL, 0);
  2300. }
  2301. int enet_host_check_events(ENetHost* host, ENetEvent* event) {
  2302. if (event == NULL)
  2303. return -1;
  2304. event->type = ENET_EVENT_TYPE_NONE;
  2305. event->peer = NULL;
  2306. event->packet = NULL;
  2307. return enet_protocol_dispatch_incoming_commands(host, event);
  2308. }
  2309. int enet_host_service(ENetHost* host, ENetEvent* event, uint32_t timeout) {
  2310. uint32_t waitCondition;
  2311. if (event != NULL) {
  2312. event->type = ENET_EVENT_TYPE_NONE;
  2313. event->peer = NULL;
  2314. event->packet = NULL;
  2315. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2316. case 1:
  2317. return 1;
  2318. case -1:
  2319. ENET_LOG_ERROR("Error dispatching incoming packets!");
  2320. return -1;
  2321. default:
  2322. break;
  2323. }
  2324. }
  2325. host->serviceTime = enet_time_get();
  2326. timeout += host->serviceTime;
  2327. do {
  2328. if (ENET_TIME_DIFFERENCE(host->serviceTime, host->bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  2329. enet_host_bandwidth_throttle(host);
  2330. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2331. case 1:
  2332. return 1;
  2333. case -1:
  2334. ENET_LOG_ERROR("Error sending outgoing packets!");
  2335. return -1;
  2336. default:
  2337. break;
  2338. }
  2339. switch (enet_protocol_receive_incoming_commands(host, event)) {
  2340. case 1:
  2341. return 1;
  2342. case -1:
  2343. ENET_LOG_ERROR("Error receiving incoming packets!");
  2344. return -1;
  2345. default:
  2346. break;
  2347. }
  2348. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2349. case 1:
  2350. return 1;
  2351. case -1:
  2352. ENET_LOG_ERROR("Error dispatching outgoing packets!");
  2353. return -1;
  2354. default:
  2355. break;
  2356. }
  2357. if (event != NULL) {
  2358. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2359. case 1:
  2360. return 1;
  2361. case -1:
  2362. ENET_LOG_ERROR("Error dispatching incoming packets!");
  2363. return -1;
  2364. default:
  2365. break;
  2366. }
  2367. }
  2368. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2369. return 0;
  2370. do {
  2371. host->serviceTime = enet_time_get();
  2372. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2373. return 0;
  2374. waitCondition = ENET_SOCKET_WAIT_RECEIVE | ENET_SOCKET_WAIT_INTERRUPT;
  2375. if (enet_socket_wait(host->socket, &waitCondition, ENET_TIME_DIFFERENCE(timeout, host->serviceTime)) != 0)
  2376. return -1;
  2377. }
  2378. while (waitCondition & ENET_SOCKET_WAIT_INTERRUPT);
  2379. host->serviceTime = enet_time_get();
  2380. }
  2381. while (waitCondition & ENET_SOCKET_WAIT_RECEIVE);
  2382. return 0;
  2383. }
  2384. /*
  2385. =======================================================================
  2386. Peer
  2387. =======================================================================
  2388. */
  2389. void enet_peer_throttle_configure(ENetPeer* peer, uint32_t interval, uint32_t acceleration, uint32_t deceleration, uint32_t threshold) {
  2390. ENetProtocol command;
  2391. peer->packetThrottleThreshold = threshold;
  2392. peer->packetThrottleInterval = interval;
  2393. peer->packetThrottleAcceleration = acceleration;
  2394. peer->packetThrottleDeceleration = deceleration;
  2395. command.header.command = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2396. command.header.channelID = 0xFF;
  2397. command.throttleConfigure.packetThrottleInterval = ENET_HOST_TO_NET_32(interval);
  2398. command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32(acceleration);
  2399. command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32(deceleration);
  2400. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2401. }
  2402. int enet_peer_throttle(ENetPeer* peer, uint32_t rtt) {
  2403. if (peer->lastRoundTripTime <= peer->lastRoundTripTimeVariance) {
  2404. peer->packetThrottle = peer->packetThrottleLimit;
  2405. }
  2406. else if (rtt < peer->lastRoundTripTime) {
  2407. peer->packetThrottle += peer->packetThrottleAcceleration;
  2408. if (peer->packetThrottle > peer->packetThrottleLimit)
  2409. peer->packetThrottle = peer->packetThrottleLimit;
  2410. return 1;
  2411. }
  2412. else if (rtt > peer->lastRoundTripTime + peer->packetThrottleThreshold + 2 * peer->lastRoundTripTimeVariance) {
  2413. if (peer->packetThrottle > peer->packetThrottleDeceleration)
  2414. peer->packetThrottle -= peer->packetThrottleDeceleration;
  2415. else
  2416. peer->packetThrottle = 0;
  2417. return -1;
  2418. }
  2419. return 0;
  2420. }
  2421. int enet_peer_send(ENetPeer* peer, uint8_t channelID, ENetPacket* packet) {
  2422. ENetChannel* channel = &peer->channels[channelID];
  2423. ENetProtocol command;
  2424. size_t fragmentLength;
  2425. if (peer->state != ENET_PEER_STATE_CONNECTED || channelID >= peer->channelCount || packet->dataLength > peer->host->maximumPacketSize) {
  2426. ENET_LOG_ERROR("Cannot send data. Peer is not connected, the channel id is above the maximum channels supported or the packet data length is above the maximum packet size\n");
  2427. return -1;
  2428. }
  2429. fragmentLength = peer->mtu - sizeof(ENetProtocolHeader) - sizeof(ENetProtocolSendFragment);
  2430. if (peer->host->checksumCallback != NULL)
  2431. fragmentLength -= sizeof(uint32_t);
  2432. if (packet->dataLength > fragmentLength) {
  2433. uint32_t fragmentCount = (packet->dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset;
  2434. uint8_t commandNumber;
  2435. uint16_t startSequenceNumber;
  2436. ENetList fragments;
  2437. ENetOutgoingCommand* fragment;
  2438. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) {
  2439. ENET_LOG_ERROR("Cannot send data. Too many fragments (%u vs %u)\n", fragmentCount, ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT);
  2440. return -1;
  2441. }
  2442. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED)) == ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED && channel->outgoingUnreliableSequenceNumber < 0xFFFF) {
  2443. commandNumber = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
  2444. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingUnreliableSequenceNumber + 1);
  2445. }
  2446. else {
  2447. commandNumber = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2448. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingReliableSequenceNumber + 1);
  2449. }
  2450. enet_list_clear(&fragments);
  2451. for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet->dataLength; ++fragmentNumber, fragmentOffset += fragmentLength) {
  2452. if (packet->dataLength - fragmentOffset < fragmentLength)
  2453. fragmentLength = packet->dataLength - fragmentOffset;
  2454. fragment = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2455. if (fragment == NULL) {
  2456. while (!enet_list_empty(&fragments)) {
  2457. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2458. enet_free(fragment);
  2459. }
  2460. ENET_LOG_ERROR("Cannot send data. A fragment was null.");
  2461. return -1;
  2462. }
  2463. fragment->fragmentOffset = fragmentOffset;
  2464. fragment->fragmentLength = fragmentLength;
  2465. fragment->packet = packet;
  2466. fragment->command.header.command = commandNumber;
  2467. fragment->command.header.channelID = channelID;
  2468. fragment->command.sendFragment.startSequenceNumber = startSequenceNumber;
  2469. fragment->command.sendFragment.dataLength = ENET_HOST_TO_NET_16(fragmentLength);
  2470. fragment->command.sendFragment.fragmentCount = ENET_HOST_TO_NET_32(fragmentCount);
  2471. fragment->command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32(fragmentNumber);
  2472. fragment->command.sendFragment.totalLength = ENET_HOST_TO_NET_32(packet->dataLength);
  2473. fragment->command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32(fragmentOffset);
  2474. enet_list_insert(enet_list_end(&fragments), fragment);
  2475. }
  2476. packet->referenceCount += fragmentNumber;
  2477. while (!enet_list_empty(&fragments)) {
  2478. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2479. enet_peer_setup_outgoing_command(peer, fragment);
  2480. }
  2481. return 0;
  2482. }
  2483. command.header.channelID = channelID;
  2484. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) {
  2485. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2486. command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2487. }
  2488. else if (packet->flags & ENET_PACKET_FLAG_RELIABLE || channel->outgoingUnreliableSequenceNumber >= 0xFFFF) {
  2489. command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2490. command.sendReliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2491. }
  2492. else {
  2493. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
  2494. command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2495. }
  2496. if (enet_peer_queue_outgoing_command(peer, &command, packet, 0, packet->dataLength) == NULL) {
  2497. ENET_LOG_ERROR("A queued outgoing command was NULL\n");
  2498. return -1;
  2499. }
  2500. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  2501. enet_host_flush(peer->host);
  2502. return 0;
  2503. }
  2504. ENetPacket* enet_peer_receive(ENetPeer* peer, uint8_t* channelID) {
  2505. ENetIncomingCommand* incomingCommand;
  2506. ENetPacket* packet;
  2507. if (enet_list_empty(&peer->dispatchedCommands))
  2508. return NULL;
  2509. incomingCommand = (ENetIncomingCommand*)enet_list_remove(enet_list_begin(&peer->dispatchedCommands));
  2510. if (channelID != NULL)
  2511. *channelID = incomingCommand->command.header.channelID;
  2512. packet = incomingCommand->packet;
  2513. --packet->referenceCount;
  2514. if (incomingCommand->fragments != NULL)
  2515. enet_free(incomingCommand->fragments);
  2516. enet_free(incomingCommand);
  2517. peer->totalWaitingData -= packet->dataLength;
  2518. return packet;
  2519. }
  2520. static void enet_peer_reset_outgoing_commands(ENetList* queue) {
  2521. ENetOutgoingCommand* outgoingCommand;
  2522. while (!enet_list_empty(queue)) {
  2523. outgoingCommand = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(queue));
  2524. if (outgoingCommand->packet != NULL) {
  2525. --outgoingCommand->packet->referenceCount;
  2526. if (outgoingCommand->packet->referenceCount == 0)
  2527. enet_packet_destroy(outgoingCommand->packet);
  2528. }
  2529. enet_free(outgoingCommand);
  2530. }
  2531. }
  2532. static void enet_peer_remove_incoming_commands(ENetList* queue, ENetListIterator startCommand, ENetListIterator endCommand) {
  2533. ENetListIterator currentCommand;
  2534. for (currentCommand = startCommand; currentCommand != endCommand;) {
  2535. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2536. currentCommand = enet_list_next(currentCommand);
  2537. enet_list_remove(&incomingCommand->incomingCommandList);
  2538. if (incomingCommand->packet != NULL) {
  2539. --incomingCommand->packet->referenceCount;
  2540. if (incomingCommand->packet->referenceCount == 0)
  2541. enet_packet_destroy(incomingCommand->packet);
  2542. }
  2543. if (incomingCommand->fragments != NULL)
  2544. enet_free(incomingCommand->fragments);
  2545. enet_free(incomingCommand);
  2546. }
  2547. }
  2548. static void enet_peer_reset_incoming_commands(ENetList* queue) {
  2549. enet_peer_remove_incoming_commands(queue, enet_list_begin(queue), enet_list_end(queue));
  2550. }
  2551. void enet_peer_reset_queues(ENetPeer* peer) {
  2552. ENetChannel* channel;
  2553. if (peer->needsDispatch) {
  2554. enet_list_remove(&peer->dispatchList);
  2555. peer->needsDispatch = 0;
  2556. }
  2557. while (!enet_list_empty(&peer->acknowledgements)) {
  2558. enet_free(enet_list_remove(enet_list_begin(&peer->acknowledgements)));
  2559. }
  2560. enet_peer_reset_outgoing_commands(&peer->sentReliableCommands);
  2561. enet_peer_reset_outgoing_commands(&peer->sentUnreliableCommands);
  2562. enet_peer_reset_outgoing_commands(&peer->outgoingReliableCommands);
  2563. enet_peer_reset_outgoing_commands(&peer->outgoingUnreliableCommands);
  2564. enet_peer_reset_incoming_commands(&peer->dispatchedCommands);
  2565. if (peer->channels != NULL && peer->channelCount > 0) {
  2566. for (channel = peer->channels; channel < &peer->channels[peer->channelCount]; ++channel) {
  2567. enet_peer_reset_incoming_commands(&channel->incomingReliableCommands);
  2568. enet_peer_reset_incoming_commands(&channel->incomingUnreliableCommands);
  2569. }
  2570. enet_free(peer->channels);
  2571. }
  2572. peer->channels = NULL;
  2573. peer->channelCount = 0;
  2574. }
  2575. void enet_peer_on_connect(ENetPeer* peer) {
  2576. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  2577. if (peer->incomingBandwidth != 0)
  2578. ++peer->host->bandwidthLimitedPeers;
  2579. ++peer->host->connectedPeers;
  2580. }
  2581. }
  2582. void enet_peer_on_disconnect(ENetPeer* peer) {
  2583. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2584. if (peer->incomingBandwidth != 0)
  2585. --peer->host->bandwidthLimitedPeers;
  2586. --peer->host->connectedPeers;
  2587. }
  2588. }
  2589. void enet_peer_reset(ENetPeer* peer) {
  2590. enet_peer_on_disconnect(peer);
  2591. peer->outgoingPeerID = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  2592. peer->state = ENET_PEER_STATE_DISCONNECTED;
  2593. peer->incomingBandwidth = 0;
  2594. peer->outgoingBandwidth = 0;
  2595. peer->incomingBandwidthThrottleEpoch = 0;
  2596. peer->outgoingBandwidthThrottleEpoch = 0;
  2597. peer->incomingDataTotal = 0;
  2598. peer->totalDataReceived = 0;
  2599. peer->outgoingDataTotal = 0;
  2600. peer->totalDataSent = 0;
  2601. peer->lastSendTime = 0;
  2602. peer->lastReceiveTime = 0;
  2603. peer->nextTimeout = 0;
  2604. peer->earliestTimeout = 0;
  2605. peer->packetLossEpoch = 0;
  2606. peer->packetsSent = 0;
  2607. peer->totalPacketsSent = 0;
  2608. peer->packetsLost = 0;
  2609. peer->totalPacketsLost = 0;
  2610. peer->packetLoss = 0;
  2611. peer->packetLossVariance = 0;
  2612. peer->packetThrottle = ENET_PEER_DEFAULT_PACKET_THROTTLE;
  2613. peer->packetThrottleThreshold = ENET_PEER_PACKET_THROTTLE_THRESHOLD;
  2614. peer->packetThrottleLimit = ENET_PEER_PACKET_THROTTLE_SCALE;
  2615. peer->packetThrottleCounter = 0;
  2616. peer->packetThrottleEpoch = 0;
  2617. peer->packetThrottleAcceleration = ENET_PEER_PACKET_THROTTLE_ACCELERATION;
  2618. peer->packetThrottleDeceleration = ENET_PEER_PACKET_THROTTLE_DECELERATION;
  2619. peer->packetThrottleInterval = ENET_PEER_PACKET_THROTTLE_INTERVAL;
  2620. peer->pingInterval = ENET_PEER_PING_INTERVAL;
  2621. peer->timeoutLimit = ENET_PEER_TIMEOUT_LIMIT;
  2622. peer->timeoutMinimum = ENET_PEER_TIMEOUT_MINIMUM;
  2623. peer->timeoutMaximum = ENET_PEER_TIMEOUT_MAXIMUM;
  2624. peer->lastRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2625. peer->lowestRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2626. peer->lastRoundTripTimeVariance = 0;
  2627. peer->highestRoundTripTimeVariance = 0;
  2628. peer->roundTripTime = 1;
  2629. peer->roundTripTimeVariance = 0;
  2630. peer->mtu = peer->host->mtu;
  2631. peer->reliableDataInTransit = 0;
  2632. peer->outgoingReliableSequenceNumber = 0;
  2633. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2634. peer->incomingUnsequencedGroup = 0;
  2635. peer->outgoingUnsequencedGroup = 0;
  2636. peer->eventData = 0;
  2637. peer->totalWaitingData = 0;
  2638. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  2639. enet_peer_reset_queues(peer);
  2640. }
  2641. void enet_peer_ping(ENetPeer* peer) {
  2642. ENetProtocol command;
  2643. if (peer->state != ENET_PEER_STATE_CONNECTED)
  2644. return;
  2645. command.header.command = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2646. command.header.channelID = 0xFF;
  2647. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2648. }
  2649. void enet_peer_ping_interval(ENetPeer* peer, uint32_t pingInterval) {
  2650. peer->pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL;
  2651. }
  2652. void enet_peer_timeout(ENetPeer* peer, uint32_t timeoutLimit, uint32_t timeoutMinimum, uint32_t timeoutMaximum) {
  2653. peer->timeoutLimit = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT;
  2654. peer->timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM;
  2655. peer->timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM;
  2656. }
  2657. void enet_peer_disconnect_now(ENetPeer* peer, uint32_t data) {
  2658. ENetProtocol command;
  2659. if (peer->state == ENET_PEER_STATE_DISCONNECTED)
  2660. return;
  2661. if (peer->state != ENET_PEER_STATE_ZOMBIE && peer->state != ENET_PEER_STATE_DISCONNECTING) {
  2662. enet_peer_reset_queues(peer);
  2663. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2664. command.header.channelID = 0xFF;
  2665. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2666. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2667. enet_host_flush(peer->host);
  2668. }
  2669. enet_peer_reset(peer);
  2670. }
  2671. void enet_peer_disconnect(ENetPeer* peer, uint32_t data) {
  2672. ENetProtocol command;
  2673. if (peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT || peer->state == ENET_PEER_STATE_ZOMBIE)
  2674. return;
  2675. enet_peer_reset_queues(peer);
  2676. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT;
  2677. command.header.channelID = 0xFF;
  2678. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2679. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2680. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2681. else
  2682. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2683. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2684. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2685. enet_peer_on_disconnect(peer);
  2686. peer->state = ENET_PEER_STATE_DISCONNECTING;
  2687. }
  2688. else {
  2689. enet_host_flush(peer->host);
  2690. enet_peer_reset(peer);
  2691. }
  2692. }
  2693. void enet_peer_disconnect_later(ENetPeer* peer, uint32_t data) {
  2694. if ((peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) && !(enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))) {
  2695. peer->state = ENET_PEER_STATE_DISCONNECT_LATER;
  2696. peer->eventData = data;
  2697. }
  2698. else {
  2699. enet_peer_disconnect(peer, data);
  2700. }
  2701. }
  2702. ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer* peer, const ENetProtocol* command, uint16_t sentTime) {
  2703. ENetAcknowledgement* acknowledgement;
  2704. if (command->header.channelID < peer->channelCount) {
  2705. ENetChannel* channel = &peer->channels[command->header.channelID];
  2706. uint16_t reliableWindow = command->header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2707. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2708. if (command->header.reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2709. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2710. if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS)
  2711. return NULL;
  2712. }
  2713. acknowledgement = (ENetAcknowledgement*)enet_malloc(sizeof(ENetAcknowledgement));
  2714. if (acknowledgement == NULL)
  2715. return NULL;
  2716. peer->outgoingDataTotal += sizeof(ENetProtocolAcknowledge);
  2717. acknowledgement->sentTime = sentTime;
  2718. acknowledgement->command = *command;
  2719. enet_list_insert(enet_list_end(&peer->acknowledgements), acknowledgement);
  2720. return acknowledgement;
  2721. }
  2722. void enet_peer_setup_outgoing_command(ENetPeer* peer, ENetOutgoingCommand* outgoingCommand) {
  2723. ENetChannel* channel = &peer->channels[outgoingCommand->command.header.channelID];
  2724. peer->outgoingDataTotal += enet_protocol_command_size(outgoingCommand->command.header.command) + outgoingCommand->fragmentLength;
  2725. if (outgoingCommand->command.header.channelID == 0xFF) {
  2726. ++peer->outgoingReliableSequenceNumber;
  2727. outgoingCommand->reliableSequenceNumber = peer->outgoingReliableSequenceNumber;
  2728. outgoingCommand->unreliableSequenceNumber = 0;
  2729. }
  2730. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  2731. ++channel->outgoingReliableSequenceNumber;
  2732. channel->outgoingUnreliableSequenceNumber = 0;
  2733. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2734. outgoingCommand->unreliableSequenceNumber = 0;
  2735. }
  2736. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) {
  2737. ++peer->outgoingUnsequencedGroup;
  2738. outgoingCommand->reliableSequenceNumber = 0;
  2739. outgoingCommand->unreliableSequenceNumber = 0;
  2740. }
  2741. else {
  2742. if (outgoingCommand->fragmentOffset == 0)
  2743. ++channel->outgoingUnreliableSequenceNumber;
  2744. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2745. outgoingCommand->unreliableSequenceNumber = channel->outgoingUnreliableSequenceNumber;
  2746. }
  2747. outgoingCommand->sendAttempts = 0;
  2748. outgoingCommand->sentTime = 0;
  2749. outgoingCommand->roundTripTimeout = 0;
  2750. outgoingCommand->roundTripTimeoutLimit = 0;
  2751. outgoingCommand->command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->reliableSequenceNumber);
  2752. switch (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2753. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2754. outgoingCommand->command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->unreliableSequenceNumber);
  2755. break;
  2756. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2757. outgoingCommand->command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16(peer->outgoingUnsequencedGroup);
  2758. break;
  2759. default:
  2760. break;
  2761. }
  2762. if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)
  2763. enet_list_insert(enet_list_end(&peer->outgoingReliableCommands), outgoingCommand);
  2764. else
  2765. enet_list_insert(enet_list_end(&peer->outgoingUnreliableCommands), outgoingCommand);
  2766. }
  2767. ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer* peer, const ENetProtocol* command, ENetPacket* packet, uint32_t offset, uint16_t length) {
  2768. ENetOutgoingCommand* outgoingCommand = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2769. if (outgoingCommand == NULL)
  2770. return NULL;
  2771. outgoingCommand->command = *command;
  2772. outgoingCommand->fragmentOffset = offset;
  2773. outgoingCommand->fragmentLength = length;
  2774. outgoingCommand->packet = packet;
  2775. if (packet != NULL)
  2776. ++packet->referenceCount;
  2777. enet_peer_setup_outgoing_command(peer, outgoingCommand);
  2778. return outgoingCommand;
  2779. }
  2780. void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer* peer, ENetChannel* channel) {
  2781. ENetListIterator droppedCommand, startCommand, currentCommand;
  2782. for (droppedCommand = startCommand = currentCommand = enet_list_begin(&channel->incomingUnreliableCommands); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2783. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2784. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2785. continue;
  2786. if (incomingCommand->reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
  2787. if (incomingCommand->fragmentsRemaining <= 0) {
  2788. channel->incomingUnreliableSequenceNumber = incomingCommand->unreliableSequenceNumber;
  2789. continue;
  2790. }
  2791. if (startCommand != currentCommand) {
  2792. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2793. if (!peer->needsDispatch) {
  2794. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2795. peer->needsDispatch = 1;
  2796. }
  2797. droppedCommand = currentCommand;
  2798. }
  2799. else if (droppedCommand != currentCommand) {
  2800. droppedCommand = enet_list_previous(currentCommand);
  2801. }
  2802. }
  2803. else {
  2804. uint16_t reliableWindow = incomingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2805. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2806. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2807. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2808. if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2809. break;
  2810. droppedCommand = enet_list_next(currentCommand);
  2811. if (startCommand != currentCommand) {
  2812. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2813. if (!peer->needsDispatch) {
  2814. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2815. peer->needsDispatch = 1;
  2816. }
  2817. }
  2818. }
  2819. startCommand = enet_list_next(currentCommand);
  2820. }
  2821. if (startCommand != currentCommand) {
  2822. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2823. if (!peer->needsDispatch) {
  2824. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2825. peer->needsDispatch = 1;
  2826. }
  2827. droppedCommand = currentCommand;
  2828. }
  2829. enet_peer_remove_incoming_commands(&channel->incomingUnreliableCommands, enet_list_begin(&channel->incomingUnreliableCommands), droppedCommand);
  2830. }
  2831. void enet_peer_dispatch_incoming_reliable_commands(ENetPeer* peer, ENetChannel* channel) {
  2832. ENetListIterator currentCommand;
  2833. for (currentCommand = enet_list_begin(&channel->incomingReliableCommands); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2834. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2835. if (incomingCommand->fragmentsRemaining > 0 || incomingCommand->reliableSequenceNumber != (uint16_t)(channel->incomingReliableSequenceNumber + 1))
  2836. break;
  2837. channel->incomingReliableSequenceNumber = incomingCommand->reliableSequenceNumber;
  2838. if (incomingCommand->fragmentCount > 0)
  2839. channel->incomingReliableSequenceNumber += incomingCommand->fragmentCount - 1;
  2840. }
  2841. if (currentCommand == enet_list_begin(&channel->incomingReliableCommands))
  2842. return;
  2843. channel->incomingUnreliableSequenceNumber = 0;
  2844. enet_list_move(enet_list_end(&peer->dispatchedCommands), enet_list_begin(&channel->incomingReliableCommands), enet_list_previous(currentCommand));
  2845. if (!peer->needsDispatch) {
  2846. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2847. peer->needsDispatch = 1;
  2848. }
  2849. if (!enet_list_empty(&channel->incomingUnreliableCommands))
  2850. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  2851. }
  2852. ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer* peer, const ENetProtocol* command, const void* data, size_t dataLength, uint32_t flags, uint32_t fragmentCount) {
  2853. static ENetIncomingCommand dummyCommand;
  2854. ENetChannel* channel = &peer->channels[command->header.channelID];
  2855. uint32_t unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
  2856. uint16_t reliableWindow, currentWindow;
  2857. ENetIncomingCommand* incomingCommand;
  2858. ENetListIterator currentCommand;
  2859. ENetPacket* packet = NULL;
  2860. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2861. goto discardCommand;
  2862. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  2863. reliableSequenceNumber = command->header.reliableSequenceNumber;
  2864. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2865. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2866. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2867. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2868. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2869. goto discardCommand;
  2870. }
  2871. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2872. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2873. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2874. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber)
  2875. goto discardCommand;
  2876. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2877. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2878. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2879. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2880. continue;
  2881. }
  2882. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2883. break;
  2884. }
  2885. if (incomingCommand->reliableSequenceNumber <= reliableSequenceNumber) {
  2886. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2887. break;
  2888. goto discardCommand;
  2889. }
  2890. }
  2891. break;
  2892. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2893. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  2894. unreliableSequenceNumber = ENET_NET_TO_HOST_16(command->sendUnreliable.unreliableSequenceNumber);
  2895. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && unreliableSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  2896. goto discardCommand;
  2897. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2898. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2899. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2900. continue;
  2901. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2902. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2903. continue;
  2904. }
  2905. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2906. break;
  2907. }
  2908. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2909. break;
  2910. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  2911. continue;
  2912. if (incomingCommand->unreliableSequenceNumber <= unreliableSequenceNumber) {
  2913. if (incomingCommand->unreliableSequenceNumber < unreliableSequenceNumber)
  2914. break;
  2915. goto discardCommand;
  2916. }
  2917. }
  2918. break;
  2919. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2920. currentCommand = enet_list_end(&channel->incomingUnreliableCommands);
  2921. break;
  2922. default:
  2923. goto discardCommand;
  2924. }
  2925. if (peer->totalWaitingData >= peer->host->maximumWaitingData)
  2926. goto notifyError;
  2927. packet = enet_packet_create(data, dataLength, flags);
  2928. if (packet == NULL)
  2929. goto notifyError;
  2930. incomingCommand = (ENetIncomingCommand*)enet_malloc(sizeof(ENetIncomingCommand));
  2931. if (incomingCommand == NULL)
  2932. goto notifyError;
  2933. incomingCommand->reliableSequenceNumber = command->header.reliableSequenceNumber;
  2934. incomingCommand->unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF;
  2935. incomingCommand->command = *command;
  2936. incomingCommand->fragmentCount = fragmentCount;
  2937. incomingCommand->fragmentsRemaining = fragmentCount;
  2938. incomingCommand->packet = packet;
  2939. incomingCommand->fragments = NULL;
  2940. if (fragmentCount > 0) {
  2941. if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
  2942. incomingCommand->fragments = (uint32_t*)enet_malloc((fragmentCount + 31) / 32 * sizeof(uint32_t));
  2943. if (incomingCommand->fragments == NULL) {
  2944. enet_free(incomingCommand);
  2945. goto notifyError;
  2946. }
  2947. memset(incomingCommand->fragments, 0, (fragmentCount + 31) / 32 * sizeof(uint32_t));
  2948. }
  2949. if (packet != NULL) {
  2950. ++packet->referenceCount;
  2951. peer->totalWaitingData += packet->dataLength;
  2952. }
  2953. enet_list_insert(enet_list_next(currentCommand), incomingCommand);
  2954. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2955. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2956. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2957. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  2958. break;
  2959. default:
  2960. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  2961. break;
  2962. }
  2963. return incomingCommand;
  2964. discardCommand:
  2965. if (fragmentCount > 0)
  2966. goto notifyError;
  2967. if (packet != NULL && packet->referenceCount == 0)
  2968. enet_packet_destroy(packet);
  2969. return &dummyCommand;
  2970. notifyError:
  2971. if (packet != NULL && packet->referenceCount == 0)
  2972. enet_packet_destroy(packet);
  2973. return NULL;
  2974. }
  2975. /*
  2976. =======================================================================
  2977. Host
  2978. =======================================================================
  2979. */
  2980. ENetHost* enet_host_create(const ENetAddress* address, size_t peerCount, size_t channelLimit, uint32_t incomingBandwidth, uint32_t outgoingBandwidth, int bufferSize) {
  2981. ENET_LOG_TRACE("ENET Host being created.");
  2982. ENetHost* host;
  2983. ENetPeer* currentPeer;
  2984. if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  2985. ENET_LOG_ERROR("peer count greater than %u", ENET_PROTOCOL_MAXIMUM_PEER_ID);
  2986. return NULL;
  2987. }
  2988. host = (ENetHost*)enet_malloc(sizeof(ENetHost));
  2989. if (host == NULL) {
  2990. ENET_LOG_ERROR("host malloc failure; wanted %u bytes", sizeof(ENetHost));
  2991. return NULL;
  2992. }
  2993. memset(host, 0, sizeof(ENetHost));
  2994. host->peers = (ENetPeer*)enet_malloc(peerCount * sizeof(ENetPeer));
  2995. if (host->peers == NULL) {
  2996. ENET_LOG_ERROR("host peer malloc failure; wanted %u bytes", peerCount * sizeof(ENetPeer));
  2997. enet_free(host);
  2998. return NULL;
  2999. }
  3000. memset(host->peers, 0, peerCount * sizeof(ENetPeer));
  3001. host->socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
  3002. if (host->socket != ENET_SOCKET_NULL) {
  3003. ENET_LOG_TRACE("Switching socket to IPv6 version 6 only mode");
  3004. enet_socket_set_option(host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
  3005. }
  3006. int socketBindResult = enet_socket_bind(host->socket, address);
  3007. if (host->socket == ENET_SOCKET_NULL || (address != NULL && socketBindResult < 0)) {
  3008. if (host->socket != ENET_SOCKET_NULL) {
  3009. ENET_LOG_TRACE("Destroying old socket");
  3010. enet_socket_destroy(host->socket);
  3011. }
  3012. ENET_LOG_ERROR("Bind socket failed; error code %i", socketBindResult);
  3013. enet_free(host->peers);
  3014. enet_free(host);
  3015. return NULL;
  3016. }
  3017. ENET_LOG_TRACE("START: Buffer Setup");
  3018. if (bufferSize > ENET_HOST_BUFFER_SIZE_MAX)
  3019. bufferSize = ENET_HOST_BUFFER_SIZE_MAX;
  3020. else if (bufferSize < ENET_HOST_BUFFER_SIZE_MIN)
  3021. bufferSize = ENET_HOST_BUFFER_SIZE_MIN;
  3022. ENET_LOG_TRACE("START: Setup socket options");
  3023. enet_socket_set_option(host->socket, ENET_SOCKOPT_NONBLOCK, 1);
  3024. enet_socket_set_option(host->socket, ENET_SOCKOPT_BROADCAST, 1);
  3025. enet_socket_set_option(host->socket, ENET_SOCKOPT_RCVBUF, bufferSize);
  3026. enet_socket_set_option(host->socket, ENET_SOCKOPT_SNDBUF, bufferSize);
  3027. ENET_LOG_TRACE("START: Address Setup");
  3028. if (address != NULL && enet_socket_get_address(host->socket, &host->address) < 0)
  3029. host->address = *address;
  3030. ENET_LOG_TRACE("START: Channels Setup");
  3031. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3032. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3033. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3034. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3035. host->randomSeed = (uint32_t)(size_t)host;
  3036. host->randomSeed += enet_host_random_seed();
  3037. host->randomSeed = (host->randomSeed << 16) | (host->randomSeed >> 16);
  3038. host->channelLimit = channelLimit;
  3039. host->incomingBandwidth = incomingBandwidth;
  3040. host->outgoingBandwidth = outgoingBandwidth;
  3041. host->bandwidthThrottleEpoch = 0;
  3042. host->recalculateBandwidthLimits = 0;
  3043. host->preventConnections = 0;
  3044. host->mtu = ENET_HOST_DEFAULT_MTU;
  3045. host->peerCount = peerCount;
  3046. host->commandCount = 0;
  3047. host->bufferCount = 0;
  3048. host->checksumCallback = NULL;
  3049. host->receivedAddress.ipv6 = ENET_HOST_ANY;
  3050. host->receivedAddress.port = 0;
  3051. host->receivedData = NULL;
  3052. host->receivedDataLength = 0;
  3053. host->totalSentData = 0;
  3054. host->totalSentPackets = 0;
  3055. host->totalReceivedData = 0;
  3056. host->totalReceivedPackets = 0;
  3057. host->connectedPeers = 0;
  3058. host->bandwidthLimitedPeers = 0;
  3059. host->duplicatePeers = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  3060. host->maximumPacketSize = ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE;
  3061. host->maximumWaitingData = ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA;
  3062. host->interceptCallback = NULL;
  3063. ENET_LOG_TRACE("Clearing dispatch queue");
  3064. enet_list_clear(&host->dispatchQueue);
  3065. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3066. currentPeer->host = host;
  3067. currentPeer->incomingPeerID = currentPeer - host->peers;
  3068. currentPeer->outgoingSessionID = currentPeer->incomingSessionID = 0xFF;
  3069. currentPeer->data = NULL;
  3070. enet_list_clear(&currentPeer->acknowledgements);
  3071. enet_list_clear(&currentPeer->sentReliableCommands);
  3072. enet_list_clear(&currentPeer->sentUnreliableCommands);
  3073. enet_list_clear(&currentPeer->outgoingReliableCommands);
  3074. enet_list_clear(&currentPeer->outgoingUnreliableCommands);
  3075. enet_list_clear(&currentPeer->dispatchedCommands);
  3076. enet_peer_reset(currentPeer);
  3077. }
  3078. ENET_LOG_TRACE("SHOWTIME: Host created successfully.");
  3079. return host;
  3080. }
  3081. void enet_host_destroy(ENetHost* host) {
  3082. ENET_LOG_TRACE("ENET Host being destroyed.");
  3083. ENetPeer* currentPeer;
  3084. if (host == NULL)
  3085. return;
  3086. enet_socket_destroy(host->socket);
  3087. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3088. enet_peer_reset(currentPeer);
  3089. }
  3090. enet_free(host->peers);
  3091. enet_free(host);
  3092. }
  3093. void enet_host_prevent_connections(ENetHost* host, uint8_t state) {
  3094. if (host == NULL)
  3095. return;
  3096. host->preventConnections = state;
  3097. }
  3098. ENetPeer* enet_host_connect(ENetHost* host, const ENetAddress* address, size_t channelCount, uint32_t data) {
  3099. ENET_LOG_TRACE("Connection to host going up");
  3100. ENetPeer* currentPeer;
  3101. ENetChannel* channel;
  3102. ENetProtocol command;
  3103. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3104. channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3105. else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3106. channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3107. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3108. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED)
  3109. break;
  3110. }
  3111. if (currentPeer >= &host->peers[host->peerCount])
  3112. return NULL;
  3113. currentPeer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  3114. if (currentPeer->channels == NULL)
  3115. return NULL;
  3116. currentPeer->channelCount = channelCount;
  3117. currentPeer->state = ENET_PEER_STATE_CONNECTING;
  3118. currentPeer->address = *address;
  3119. currentPeer->connectID = ++host->randomSeed;
  3120. if (host->outgoingBandwidth == 0)
  3121. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3122. else
  3123. currentPeer->windowSize = (host->outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3124. if (currentPeer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  3125. currentPeer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3126. else if (currentPeer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  3127. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3128. for (channel = currentPeer->channels; channel < &currentPeer->channels[channelCount]; ++channel) {
  3129. channel->outgoingReliableSequenceNumber = 0;
  3130. channel->outgoingUnreliableSequenceNumber = 0;
  3131. channel->incomingReliableSequenceNumber = 0;
  3132. channel->incomingUnreliableSequenceNumber = 0;
  3133. enet_list_clear(&channel->incomingReliableCommands);
  3134. enet_list_clear(&channel->incomingUnreliableCommands);
  3135. channel->usedReliableWindows = 0;
  3136. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  3137. }
  3138. command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3139. command.header.channelID = 0xFF;
  3140. command.connect.outgoingPeerID = ENET_HOST_TO_NET_16(currentPeer->incomingPeerID);
  3141. command.connect.incomingSessionID = currentPeer->incomingSessionID;
  3142. command.connect.outgoingSessionID = currentPeer->outgoingSessionID;
  3143. command.connect.mtu = ENET_HOST_TO_NET_32(currentPeer->mtu);
  3144. command.connect.windowSize = ENET_HOST_TO_NET_32(currentPeer->windowSize);
  3145. command.connect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  3146. command.connect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  3147. command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3148. command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32(currentPeer->packetThrottleInterval);
  3149. command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleAcceleration);
  3150. command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleDeceleration);
  3151. command.connect.connectID = currentPeer->connectID;
  3152. command.connect.data = ENET_HOST_TO_NET_32(data);
  3153. enet_peer_queue_outgoing_command(currentPeer, &command, NULL, 0, 0);
  3154. return currentPeer;
  3155. }
  3156. void enet_host_broadcast(ENetHost* host, uint8_t channelID, ENetPacket* packet) {
  3157. ENetPeer* currentPeer;
  3158. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3159. ++packet->referenceCount;
  3160. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3161. if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
  3162. continue;
  3163. enet_peer_send(currentPeer, channelID, packet);
  3164. }
  3165. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3166. --packet->referenceCount;
  3167. if (packet->referenceCount == 0)
  3168. enet_packet_destroy(packet);
  3169. }
  3170. void enet_host_broadcast_exclude(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer* excludedPeer) {
  3171. ENetPeer* currentPeer;
  3172. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3173. ++packet->referenceCount;
  3174. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3175. if (currentPeer->state != ENET_PEER_STATE_CONNECTED || currentPeer == excludedPeer)
  3176. continue;
  3177. enet_peer_send(currentPeer, channelID, packet);
  3178. }
  3179. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3180. --packet->referenceCount;
  3181. if (packet->referenceCount == 0)
  3182. enet_packet_destroy(packet);
  3183. }
  3184. void enet_host_broadcast_selective(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer** peers, size_t length) {
  3185. ENetPeer* currentPeer;
  3186. size_t i;
  3187. if (host == NULL)
  3188. return;
  3189. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3190. ++packet->referenceCount;
  3191. for (i = 0; i < length; i++) {
  3192. currentPeer = peers[i];
  3193. if (currentPeer == NULL || currentPeer->state != ENET_PEER_STATE_CONNECTED)
  3194. continue;
  3195. enet_peer_send(currentPeer, channelID, packet);
  3196. }
  3197. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3198. --packet->referenceCount;
  3199. if (packet->referenceCount == 0)
  3200. enet_packet_destroy(packet);
  3201. }
  3202. void enet_host_channel_limit(ENetHost* host, size_t channelLimit) {
  3203. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3204. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3205. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3206. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3207. host->channelLimit = channelLimit;
  3208. }
  3209. void enet_host_bandwidth_limit(ENetHost* host, uint32_t incomingBandwidth, uint32_t outgoingBandwidth) {
  3210. host->incomingBandwidth = incomingBandwidth;
  3211. host->outgoingBandwidth = outgoingBandwidth;
  3212. host->recalculateBandwidthLimits = 1;
  3213. }
  3214. void enet_host_bandwidth_throttle(ENetHost* host) {
  3215. uint32_t timeCurrent = enet_time_get();
  3216. uint32_t elapsedTime = timeCurrent - host->bandwidthThrottleEpoch;
  3217. uint32_t peersRemaining = (uint32_t)host->connectedPeers;
  3218. uint32_t dataTotal = ~0;
  3219. uint32_t bandwidth = ~0;
  3220. uint32_t throttle = 0;
  3221. uint32_t bandwidthLimit = 0;
  3222. int needsAdjustment = host->bandwidthLimitedPeers > 0 ? 1 : 0;
  3223. ENetPeer* peer;
  3224. ENetProtocol command;
  3225. if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  3226. return;
  3227. if (host->outgoingBandwidth == 0 && host->incomingBandwidth == 0)
  3228. return;
  3229. host->bandwidthThrottleEpoch = timeCurrent;
  3230. if (peersRemaining == 0)
  3231. return;
  3232. if (host->outgoingBandwidth != 0) {
  3233. dataTotal = 0;
  3234. bandwidth = (host->outgoingBandwidth * elapsedTime) / 1000;
  3235. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3236. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3237. continue;
  3238. dataTotal += peer->outgoingDataTotal;
  3239. }
  3240. }
  3241. while (peersRemaining > 0 && needsAdjustment != 0) {
  3242. needsAdjustment = 0;
  3243. if (dataTotal <= bandwidth)
  3244. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3245. else
  3246. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3247. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3248. uint32_t peerBandwidth;
  3249. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidth == 0 || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3250. continue;
  3251. peerBandwidth = (peer->incomingBandwidth * elapsedTime) / 1000;
  3252. if ((throttle * peer->outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
  3253. continue;
  3254. peer->packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer->outgoingDataTotal;
  3255. if (peer->packetThrottleLimit == 0)
  3256. peer->packetThrottleLimit = 1;
  3257. if (peer->packetThrottle > peer->packetThrottleLimit)
  3258. peer->packetThrottle = peer->packetThrottleLimit;
  3259. peer->outgoingBandwidthThrottleEpoch = timeCurrent;
  3260. peer->incomingDataTotal = 0;
  3261. peer->outgoingDataTotal = 0;
  3262. needsAdjustment = 1;
  3263. --peersRemaining;
  3264. bandwidth -= peerBandwidth;
  3265. dataTotal -= peerBandwidth;
  3266. }
  3267. }
  3268. if (peersRemaining > 0) {
  3269. if (dataTotal <= bandwidth)
  3270. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3271. else
  3272. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3273. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3274. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3275. continue;
  3276. peer->packetThrottleLimit = throttle;
  3277. if (peer->packetThrottle > peer->packetThrottleLimit)
  3278. peer->packetThrottle = peer->packetThrottleLimit;
  3279. peer->incomingDataTotal = 0;
  3280. peer->outgoingDataTotal = 0;
  3281. }
  3282. }
  3283. if (host->recalculateBandwidthLimits) {
  3284. host->recalculateBandwidthLimits = 0;
  3285. peersRemaining = (uint32_t)host->connectedPeers;
  3286. bandwidth = host->incomingBandwidth;
  3287. needsAdjustment = 1;
  3288. if (bandwidth == 0) {
  3289. bandwidthLimit = 0;
  3290. }
  3291. else {
  3292. while (peersRemaining > 0 && needsAdjustment != 0) {
  3293. needsAdjustment = 0;
  3294. bandwidthLimit = bandwidth / peersRemaining;
  3295. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3296. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3297. continue;
  3298. if (peer->outgoingBandwidth > 0 && peer->outgoingBandwidth >= bandwidthLimit)
  3299. continue;
  3300. peer->incomingBandwidthThrottleEpoch = timeCurrent;
  3301. needsAdjustment = 1;
  3302. --peersRemaining;
  3303. bandwidth -= peer->outgoingBandwidth;
  3304. }
  3305. }
  3306. }
  3307. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3308. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3309. continue;
  3310. command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3311. command.header.channelID = 0xFF;
  3312. command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3313. if (peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3314. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(peer->outgoingBandwidth);
  3315. else
  3316. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(bandwidthLimit);
  3317. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3318. }
  3319. }
  3320. }
  3321. /*
  3322. =======================================================================
  3323. Address
  3324. =======================================================================
  3325. */
  3326. int enet_address_set_ip(ENetAddress* address, const char* ip) {
  3327. int type = AF_INET6;
  3328. void* destination = &address->ipv6;
  3329. if (strchr(ip, ':') == NULL) {
  3330. type = AF_INET;
  3331. memset(address, 0, sizeof(address->ipv4.zeros));
  3332. address->ipv4.ffff = 0xFFFF;
  3333. destination = &address->ipv4.ip;
  3334. }
  3335. if (!inet_pton(type, ip, destination)) {
  3336. ENET_LOG_ERROR("Error returned from inet_pton");
  3337. return -1;
  3338. }
  3339. return 0;
  3340. }
  3341. int enet_address_set_hostname(ENetAddress* address, const char* name) {
  3342. struct addrinfo hints, * resultList = NULL, * result = NULL;
  3343. memset(&hints, 0, sizeof(hints));
  3344. hints.ai_family = AF_UNSPEC;
  3345. if (getaddrinfo(name, NULL, &hints, &resultList) != 0) {
  3346. ENET_LOG_ERROR("Error returned from getaddrinfo");
  3347. return -1;
  3348. }
  3349. for (result = resultList; result != NULL; result = result->ai_next) {
  3350. if (result->ai_addr != NULL && result->ai_addrlen >= sizeof(struct sockaddr_in)) {
  3351. if (result->ai_family == AF_INET) {
  3352. struct sockaddr_in* sin = (struct sockaddr_in*)result->ai_addr;
  3353. memset(address, 0, sizeof(address->ipv4.zeros));
  3354. address->ipv4.ffff = 0xFFFF;
  3355. address->ipv4.ip.s_addr = sin->sin_addr.s_addr;
  3356. freeaddrinfo(resultList);
  3357. return 0;
  3358. }
  3359. else if (result->ai_family == AF_INET6) {
  3360. struct sockaddr_in6* sin = (struct sockaddr_in6*)result->ai_addr;
  3361. address->ipv6 = sin->sin6_addr;
  3362. freeaddrinfo(resultList);
  3363. return 0;
  3364. }
  3365. }
  3366. }
  3367. if (resultList != NULL)
  3368. freeaddrinfo(resultList);
  3369. return enet_address_set_ip(address, name);
  3370. }
  3371. int enet_address_get_ip(const ENetAddress* address, char* ip, size_t ipLength) {
  3372. if (address->ipv4.ffff == 0xFFFF && enet_array_is_zeroed(address->ipv4.zeros, sizeof(address->ipv4.zeros)) == 0) {
  3373. if (inet_ntop(AF_INET, &address->ipv4.ip, ip, ipLength) == NULL) {
  3374. ENET_LOG_ERROR("Error returned from inet_pton: NULL");
  3375. return -1;
  3376. }
  3377. }
  3378. else if (inet_ntop(AF_INET6, &address->ipv6, ip, ipLength) == NULL) {
  3379. ENET_LOG_ERROR("Error returned from inet_pton: NULL");
  3380. return -1;
  3381. }
  3382. return 0;
  3383. }
  3384. int enet_address_get_hostname(const ENetAddress* address, char* name, size_t nameLength) {
  3385. struct sockaddr_in6 sin;
  3386. int err;
  3387. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3388. sin.sin6_family = AF_INET6;
  3389. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3390. sin.sin6_addr = address->ipv6;
  3391. err = getnameinfo((struct sockaddr*) & sin, sizeof(sin), name, nameLength, NULL, 0, NI_NAMEREQD);
  3392. if (!err) {
  3393. if (name != NULL && nameLength > 0 && !memchr(name, '\0', nameLength))
  3394. return -1;
  3395. return 0;
  3396. }
  3397. if (err != EAI_NONAME) {
  3398. ENET_LOG_ERROR("getnameinfo error occurred: %i", err);
  3399. return -1;
  3400. }
  3401. return enet_address_get_ip(address, name, nameLength);
  3402. }
  3403. /*
  3404. =======================================================================
  3405. Platform-specific (Unix)
  3406. =======================================================================
  3407. */
  3408. #ifndef _WIN32
  3409. int enet_initialize(void) {
  3410. return 0;
  3411. }
  3412. void enet_deinitialize(void) { }
  3413. uint64_t enet_host_random_seed(void) {
  3414. struct timeval timeVal;
  3415. gettimeofday(&timeVal, NULL);
  3416. return (timeVal.tv_sec * 1000) ^ (timeVal.tv_usec / 1000);
  3417. }
  3418. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3419. struct sockaddr_in6 sin;
  3420. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3421. sin.sin6_family = AF_INET6;
  3422. if (address != NULL) {
  3423. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3424. sin.sin6_addr = address->ipv6;
  3425. }
  3426. else {
  3427. sin.sin6_port = 0;
  3428. sin.sin6_addr = ENET_HOST_ANY;
  3429. }
  3430. return bind(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3431. }
  3432. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3433. struct sockaddr_storage ss;
  3434. socklen_t saLength = sizeof(ss);
  3435. if (getsockname(socket, (struct sockaddr*) & ss, &saLength) == -1) {
  3436. ENET_LOG_ERROR("getsockname failure");
  3437. return -1;
  3438. }
  3439. if (ss.ss_family == AF_INET) {
  3440. struct sockaddr_in* sin = (struct sockaddr_in*) & ss;
  3441. memset(address, 0, sizeof(address->ipv4.zeros));
  3442. address->ipv4.ffff = 0xFFFF;
  3443. address->ipv4.ip = sin->sin_addr;
  3444. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3445. }
  3446. else if (ss.ss_family == AF_INET6) {
  3447. struct sockaddr_in6* sin = (struct sockaddr_in6*) & ss;
  3448. address->ipv6 = sin->sin6_addr;
  3449. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3450. }
  3451. return 0;
  3452. }
  3453. int enet_socket_listen(ENetSocket socket, int backlog) {
  3454. return listen(socket, backlog < 0 ? SOMAXCONN : backlog);
  3455. }
  3456. ENetSocket enet_socket_create(ENetSocketType type) {
  3457. int socketType = (type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM);
  3458. #ifdef SOCK_CLOEXEC
  3459. socketType |= SOCK_CLOEXEC;
  3460. #endif
  3461. return socket(PF_INET6, socketType, 0);
  3462. }
  3463. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3464. int result = -1;
  3465. switch (option) {
  3466. case ENET_SOCKOPT_NONBLOCK:
  3467. result = fcntl(socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl(socket, F_GETFL) & ~O_NONBLOCK));
  3468. break;
  3469. case ENET_SOCKOPT_BROADCAST:
  3470. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3471. break;
  3472. case ENET_SOCKOPT_REUSEADDR:
  3473. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3474. break;
  3475. case ENET_SOCKOPT_RCVBUF:
  3476. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3477. break;
  3478. case ENET_SOCKOPT_SNDBUF:
  3479. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3480. break;
  3481. case ENET_SOCKOPT_RCVTIMEO: {
  3482. struct timeval timeVal;
  3483. timeVal.tv_sec = value / 1000;
  3484. timeVal.tv_usec = (value % 1000) * 1000;
  3485. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3486. break;
  3487. }
  3488. case ENET_SOCKOPT_SNDTIMEO: {
  3489. struct timeval timeVal;
  3490. timeVal.tv_sec = value / 1000;
  3491. timeVal.tv_usec = (value % 1000) * 1000;
  3492. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3493. break;
  3494. }
  3495. case ENET_SOCKOPT_NODELAY:
  3496. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3497. break;
  3498. case ENET_SOCKOPT_IPV6_V6ONLY:
  3499. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3500. break;
  3501. default:
  3502. break;
  3503. }
  3504. return result == -1 ? -1 : 0;
  3505. }
  3506. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3507. int result = -1;
  3508. socklen_t len;
  3509. switch (option) {
  3510. case ENET_SOCKOPT_ERROR:
  3511. len = sizeof(int);
  3512. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, value, &len);
  3513. break;
  3514. default:
  3515. break;
  3516. }
  3517. return result == -1 ? -1 : 0;
  3518. }
  3519. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3520. int result = -1;
  3521. struct sockaddr_in6 sin;
  3522. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3523. sin.sin6_family = AF_INET6;
  3524. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3525. sin.sin6_addr = address->ipv6;
  3526. result = connect(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3527. if (result == -1 && errno == EINPROGRESS)
  3528. return 0;
  3529. return result;
  3530. }
  3531. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3532. int result = -1;
  3533. struct sockaddr_in6 sin;
  3534. socklen_t sinLength = sizeof(struct sockaddr_in6);
  3535. result = accept(socket, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL);
  3536. if (result == -1)
  3537. return ENET_SOCKET_NULL;
  3538. if (address != NULL) {
  3539. address->ipv6 = sin.sin6_addr;
  3540. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3541. }
  3542. return result;
  3543. }
  3544. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3545. return shutdown(socket, (int)how);
  3546. }
  3547. void enet_socket_destroy(ENetSocket socket) {
  3548. if (socket != ENET_SOCKET_NULL)
  3549. close(socket);
  3550. }
  3551. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3552. struct msghdr msgHdr;
  3553. struct sockaddr_in6 sin;
  3554. int sentLength;
  3555. memset(&msgHdr, 0, sizeof(struct msghdr));
  3556. if (address != NULL) {
  3557. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3558. sin.sin6_family = AF_INET6;
  3559. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3560. sin.sin6_addr = address->ipv6;
  3561. msgHdr.msg_name = &sin;
  3562. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3563. }
  3564. msgHdr.msg_iov = (struct iovec*)buffers;
  3565. msgHdr.msg_iovlen = bufferCount;
  3566. sentLength = sendmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3567. if (sentLength == -1) {
  3568. if (errno == EWOULDBLOCK)
  3569. return 0;
  3570. return -1;
  3571. }
  3572. return sentLength;
  3573. }
  3574. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3575. struct msghdr msgHdr;
  3576. struct sockaddr_in6 sin;
  3577. int recvLength;
  3578. memset(&msgHdr, 0, sizeof(struct msghdr));
  3579. if (address != NULL) {
  3580. msgHdr.msg_name = &sin;
  3581. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3582. }
  3583. msgHdr.msg_iov = (struct iovec*)buffers;
  3584. msgHdr.msg_iovlen = bufferCount;
  3585. recvLength = recvmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3586. if (recvLength == -1) {
  3587. if (errno == EWOULDBLOCK)
  3588. return 0;
  3589. return -1;
  3590. }
  3591. if (msgHdr.msg_flags & MSG_TRUNC) {
  3592. ENET_LOG_ERROR("this enet message header was truncated...\n");
  3593. // commit 5f0e1b475caa019157c3cf881a8d08009150f1e2 from upstream
  3594. return -2;
  3595. }
  3596. if (address != NULL) {
  3597. address->ipv6 = sin.sin6_addr;
  3598. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3599. }
  3600. return recvLength;
  3601. }
  3602. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3603. struct timeval timeVal;
  3604. timeVal.tv_sec = timeout / 1000;
  3605. timeVal.tv_usec = (timeout % 1000) * 1000;
  3606. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3607. }
  3608. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3609. struct pollfd pollSocket;
  3610. int pollCount;
  3611. pollSocket.fd = socket;
  3612. pollSocket.events = 0;
  3613. if (*condition & ENET_SOCKET_WAIT_SEND)
  3614. pollSocket.events |= POLLOUT;
  3615. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3616. pollSocket.events |= POLLIN;
  3617. pollCount = poll(&pollSocket, 1, timeout);
  3618. if (pollCount < 0) {
  3619. if (errno == EINTR && *condition & ENET_SOCKET_WAIT_INTERRUPT) {
  3620. *condition = ENET_SOCKET_WAIT_INTERRUPT;
  3621. return 0;
  3622. }
  3623. ENET_LOG_ERROR("pollCount < 0: %i", pollCount);
  3624. return -1;
  3625. }
  3626. *condition = ENET_SOCKET_WAIT_NONE;
  3627. if (pollCount == 0)
  3628. return 0;
  3629. if (pollSocket.revents & POLLOUT)
  3630. *condition |= ENET_SOCKET_WAIT_SEND;
  3631. if (pollSocket.revents & POLLIN)
  3632. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3633. return 0;
  3634. }
  3635. #endif
  3636. /*
  3637. =======================================================================
  3638. Platform-specific (Windows)
  3639. =======================================================================
  3640. */
  3641. #ifdef _WIN32
  3642. int enet_initialize(void) {
  3643. WORD versionRequested = MAKEWORD(2, 2);
  3644. WSADATA wsaData;
  3645. if (WSAStartup(versionRequested, &wsaData)) {
  3646. ENET_LOG_ERROR("WSAStartup failure");
  3647. return -1;
  3648. }
  3649. if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
  3650. ENET_LOG_ERROR("Winsock version mismatch");
  3651. WSACleanup();
  3652. return -1;
  3653. }
  3654. timeBeginPeriod(1);
  3655. ENET_LOG_TRACE("Windows Environment: ENet Initialization");
  3656. return 0;
  3657. }
  3658. void enet_deinitialize(void) {
  3659. timeEndPeriod(1);
  3660. WSACleanup();
  3661. ENET_LOG_TRACE("Windows Environment: ENet Deinitialization");
  3662. }
  3663. uint64_t enet_host_random_seed(void) {
  3664. return (uint64_t)timeGetTime();
  3665. }
  3666. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3667. struct sockaddr_in6 sin;
  3668. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3669. sin.sin6_family = AF_INET6;
  3670. if (address != NULL) {
  3671. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3672. sin.sin6_addr = address->ipv6;
  3673. }
  3674. else {
  3675. sin.sin6_port = 0;
  3676. sin.sin6_addr = in6addr_any;
  3677. }
  3678. return bind(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6)) == SOCKET_ERROR ? -1 : 0;
  3679. }
  3680. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3681. struct sockaddr_storage ss;
  3682. int saLength = sizeof(ss);
  3683. if (getsockname(socket, (struct sockaddr*) & ss, &saLength) == -1) {
  3684. ENET_LOG_ERROR("getsockname failure");
  3685. return -1;
  3686. }
  3687. if (ss.ss_family == AF_INET) {
  3688. struct sockaddr_in* sin = (struct sockaddr_in*) & ss;
  3689. memset(address, 0, sizeof(address->ipv4.zeros));
  3690. address->ipv4.ffff = 0xFFFF;
  3691. address->ipv4.ip = sin->sin_addr;
  3692. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3693. }
  3694. else if (ss.ss_family == AF_INET6) {
  3695. struct sockaddr_in6* sin = (struct sockaddr_in6*) & ss;
  3696. address->ipv6 = sin->sin6_addr;
  3697. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3698. }
  3699. return 0;
  3700. }
  3701. int enet_socket_listen(ENetSocket socket, int backlog) {
  3702. return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
  3703. }
  3704. ENetSocket enet_socket_create(ENetSocketType type) {
  3705. return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
  3706. }
  3707. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3708. int result = SOCKET_ERROR;
  3709. switch (option) {
  3710. case ENET_SOCKOPT_NONBLOCK: {
  3711. u_long nonBlocking = (u_long)value;
  3712. result = ioctlsocket(socket, FIONBIO, &nonBlocking);
  3713. break;
  3714. }
  3715. case ENET_SOCKOPT_BROADCAST:
  3716. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3717. break;
  3718. case ENET_SOCKOPT_REUSEADDR:
  3719. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3720. break;
  3721. case ENET_SOCKOPT_RCVBUF:
  3722. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3723. break;
  3724. case ENET_SOCKOPT_SNDBUF:
  3725. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3726. break;
  3727. case ENET_SOCKOPT_RCVTIMEO:
  3728. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&value, sizeof(int));
  3729. break;
  3730. case ENET_SOCKOPT_SNDTIMEO:
  3731. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&value, sizeof(int));
  3732. break;
  3733. case ENET_SOCKOPT_NODELAY:
  3734. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3735. break;
  3736. case ENET_SOCKOPT_IPV6_V6ONLY:
  3737. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3738. break;
  3739. default:
  3740. break;
  3741. }
  3742. return result == SOCKET_ERROR ? -1 : 0;
  3743. }
  3744. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3745. int result = SOCKET_ERROR, len;
  3746. switch (option) {
  3747. case ENET_SOCKOPT_ERROR:
  3748. len = sizeof(int);
  3749. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)value, &len);
  3750. break;
  3751. default:
  3752. break;
  3753. }
  3754. return result == SOCKET_ERROR ? -1 : 0;
  3755. }
  3756. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3757. int result = -1;
  3758. struct sockaddr_in6 sin;
  3759. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3760. sin.sin6_family = AF_INET6;
  3761. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3762. sin.sin6_addr = address->ipv6;
  3763. result = connect(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3764. if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) {
  3765. int winSockWhat = WSAGetLastError();
  3766. ENET_LOG_ERROR("Socket connect failure, return code: %i, WSAGetLastError: %i", result, winSockWhat);
  3767. return -1;
  3768. }
  3769. ENET_LOG_TRACE("Socket Connect");
  3770. return 0;
  3771. }
  3772. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3773. SOCKET result;
  3774. struct sockaddr_in6 sin;
  3775. int sinLength = sizeof(struct sockaddr_in6);
  3776. result = accept(socket, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL);
  3777. if (result == INVALID_SOCKET)
  3778. {
  3779. ENET_LOG_ERROR("Tried to accept from an invalid socket");
  3780. return ENET_SOCKET_NULL;
  3781. }
  3782. if (address != NULL) {
  3783. address->ipv6 = sin.sin6_addr;
  3784. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3785. }
  3786. return result;
  3787. }
  3788. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3789. return shutdown(socket, (int)how) == SOCKET_ERROR ? -1 : 0;
  3790. }
  3791. void enet_socket_destroy(ENetSocket socket) {
  3792. if (socket != INVALID_SOCKET)
  3793. closesocket(socket);
  3794. }
  3795. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3796. struct sockaddr_in6 sin;
  3797. DWORD sentLength = 0;
  3798. if (address != NULL) {
  3799. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3800. sin.sin6_family = AF_INET6;
  3801. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3802. sin.sin6_addr = address->ipv6;
  3803. }
  3804. if (WSASendTo(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &sentLength, 0, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? sizeof(struct sockaddr_in6) : 0, NULL, NULL) == SOCKET_ERROR)
  3805. return (WSAGetLastError() == WSAEWOULDBLOCK) ? 0 : -1;
  3806. return (int)sentLength;
  3807. }
  3808. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3809. INT sinLength = sizeof(struct sockaddr_in6);
  3810. DWORD flags = 0, recvLength = 0;
  3811. struct sockaddr_in6 sin;
  3812. if (WSARecvFrom(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &recvLength, &flags, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL, NULL, NULL) == SOCKET_ERROR) {
  3813. int retCode = WSAGetLastError();
  3814. switch (WSAGetLastError()) {
  3815. case WSAEWOULDBLOCK:
  3816. case WSAECONNRESET:
  3817. return 0;
  3818. }
  3819. ENET_LOG_ERROR("Socket receive failure, WSA return code %d", retCode);
  3820. return -1;
  3821. }
  3822. if (flags & MSG_PARTIAL) {
  3823. ENET_LOG_ERROR("Partial socket receive message");
  3824. return -2;
  3825. }
  3826. if (address != NULL) {
  3827. address->ipv6 = sin.sin6_addr;
  3828. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3829. }
  3830. return (int)recvLength;
  3831. }
  3832. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3833. struct timeval timeVal;
  3834. timeVal.tv_sec = timeout / 1000;
  3835. timeVal.tv_usec = (timeout % 1000) * 1000;
  3836. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3837. }
  3838. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3839. fd_set readSet, writeSet;
  3840. struct timeval timeVal;
  3841. int selectCount;
  3842. timeVal.tv_sec = timeout / 1000;
  3843. timeVal.tv_usec = (timeout % 1000) * 1000;
  3844. FD_ZERO(&readSet);
  3845. FD_ZERO(&writeSet);
  3846. if (*condition & ENET_SOCKET_WAIT_SEND)
  3847. FD_SET(socket, &writeSet);
  3848. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3849. FD_SET(socket, &readSet);
  3850. selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
  3851. if (selectCount < 0) {
  3852. ENET_LOG_ERROR("selectCount < 0; was %d", selectCount);
  3853. return -1;
  3854. }
  3855. *condition = ENET_SOCKET_WAIT_NONE;
  3856. if (selectCount == 0)
  3857. return 0;
  3858. if (FD_ISSET(socket, &writeSet))
  3859. *condition |= ENET_SOCKET_WAIT_SEND;
  3860. if (FD_ISSET(socket, &readSet))
  3861. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3862. return 0;
  3863. }
  3864. #endif
  3865. /*
  3866. =======================================================================
  3867. Extended functionality
  3868. =======================================================================
  3869. */
  3870. void* enet_packet_get_data(const ENetPacket* packet) {
  3871. return (void*)packet->data;
  3872. }
  3873. void* enet_packet_get_user_data(const ENetPacket* packet) {
  3874. return packet->userData;
  3875. }
  3876. void enet_packet_set_user_data(ENetPacket* packet, void* userData) {
  3877. packet->userData = userData;
  3878. }
  3879. int enet_packet_get_length(const ENetPacket* packet) {
  3880. return packet->dataLength;
  3881. }
  3882. void enet_packet_set_free_callback(ENetPacket* packet, const void* callback) {
  3883. packet->freeCallback = (ENetPacketFreeCallback)callback;
  3884. }
  3885. int enet_packet_check_references(const ENetPacket* packet) {
  3886. return (int)packet->referenceCount;
  3887. }
  3888. void enet_packet_dispose(ENetPacket* packet) {
  3889. if (packet->referenceCount == 0)
  3890. enet_packet_destroy(packet);
  3891. }
  3892. uint32_t enet_host_get_peers_count(const ENetHost* host) {
  3893. return host->connectedPeers;
  3894. }
  3895. uint32_t enet_host_get_packets_sent(const ENetHost* host) {
  3896. return host->totalSentPackets;
  3897. }
  3898. uint32_t enet_host_get_packets_received(const ENetHost* host) {
  3899. return host->totalReceivedPackets;
  3900. }
  3901. uint32_t enet_host_get_bytes_sent(const ENetHost* host) {
  3902. return host->totalSentData;
  3903. }
  3904. uint32_t enet_host_get_bytes_received(const ENetHost* host) {
  3905. return host->totalReceivedData;
  3906. }
  3907. uint32_t enet_peer_get_id(const ENetPeer* peer) {
  3908. return peer->incomingPeerID;
  3909. }
  3910. int enet_peer_get_ip(const ENetPeer* peer, char* ip, size_t ipLength) {
  3911. return enet_address_get_ip(&peer->address, ip, ipLength);
  3912. }
  3913. uint16_t enet_peer_get_port(const ENetPeer* peer) {
  3914. return peer->address.port;
  3915. }
  3916. uint32_t enet_peer_get_mtu(const ENetPeer* peer) {
  3917. return peer->mtu;
  3918. }
  3919. ENetPeerState enet_peer_get_state(const ENetPeer* peer) {
  3920. return peer->state;
  3921. }
  3922. uint32_t enet_peer_get_rtt(const ENetPeer* peer) {
  3923. return peer->roundTripTime;
  3924. }
  3925. uint32_t enet_peer_get_last_rtt(const ENetPeer* peer) {
  3926. return peer->lastRoundTripTime;
  3927. }
  3928. uint32_t enet_peer_get_lastsendtime(const ENetPeer* peer) {
  3929. return peer->lastSendTime;
  3930. }
  3931. uint32_t enet_peer_get_lastreceivetime(const ENetPeer* peer) {
  3932. return peer->lastReceiveTime;
  3933. }
  3934. uint64_t enet_peer_get_packets_sent(const ENetPeer* peer) {
  3935. return peer->totalPacketsSent;
  3936. }
  3937. uint64_t enet_peer_get_packets_lost(const ENetPeer* peer) {
  3938. return peer->totalPacketsLost;
  3939. }
  3940. uint64_t enet_peer_get_bytes_sent(const ENetPeer* peer) {
  3941. return peer->totalDataSent;
  3942. }
  3943. uint64_t enet_peer_get_bytes_received(const ENetPeer* peer) {
  3944. return peer->totalDataReceived;
  3945. }
  3946. void* enet_peer_get_data(const ENetPeer* peer) {
  3947. return (void*)peer->data;
  3948. }
  3949. void enet_peer_set_data(ENetPeer* peer, const void* data) {
  3950. peer->data = (uint32_t*)data;
  3951. }
  3952. #ifdef _MSC_VER
  3953. #pragma warning(pop)
  3954. #endif
  3955. #endif // ENET_IMPLEMENTATION
  3956. #endif // ENET_H