enet.h 171 KB

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