enet.h 214 KB

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