enet.h 168 KB

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