enet.h 208 KB

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