enet.h 171 KB

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