enet.h 213 KB

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