enet.h 175 KB

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