enet.h 213 KB

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