enet.h 224 KB

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