enet.h 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215
  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. // [Replay from a past commit... >>]
  1035. // c6: what the [redacted] fuck is clock_monotonic_raw??????
  1036. // c6: just use clock monotonic
  1037. // Coburn: sir yes sir
  1038. clock_gettime(CLOCK_MONOTONIC, &ts);
  1039. // [End replay]
  1040. static const uint64_t ns_in_s = 1000 * 1000 * 1000;
  1041. static const uint64_t ns_in_ms = 1000 * 1000;
  1042. uint64_t current_time_ns = ts.tv_nsec + (uint64_t)ts.tv_sec * ns_in_s;
  1043. uint64_t offset_ns = ENET_ATOMIC_READ(&start_time_ns);
  1044. if (offset_ns == 0) {
  1045. uint64_t want_value = current_time_ns - 1 * ns_in_ms;
  1046. uint64_t old_value = ENET_ATOMIC_CAS(&start_time_ns, 0, want_value);
  1047. offset_ns = old_value == 0 ? want_value : old_value;
  1048. }
  1049. uint64_t result_in_ns = current_time_ns - offset_ns;
  1050. return (uint32_t)(result_in_ns / ns_in_ms);
  1051. }
  1052. /*
  1053. =======================================================================
  1054. Checksum
  1055. =======================================================================
  1056. */
  1057. static int initializedCRC32 = 0;
  1058. static uint32_t crcTable[256];
  1059. static uint32_t reflect_crc(int val, int bits) {
  1060. int result = 0, bit;
  1061. for (bit = 0; bit < bits; bit++) {
  1062. if (val & 1)
  1063. result |= 1 << (bits - 1 - bit);
  1064. val >>= 1;
  1065. }
  1066. return result;
  1067. }
  1068. static void initialize_crc32(void) {
  1069. int byte;
  1070. for (byte = 0; byte < 256; ++byte) {
  1071. uint32_t crc = reflect_crc(byte, 8) << 24;
  1072. int offset;
  1073. for (offset = 0; offset < 8; ++offset) {
  1074. if (crc & 0x80000000)
  1075. crc = (crc << 1) ^ 0x04c11db7;
  1076. else
  1077. crc <<= 1;
  1078. }
  1079. crcTable[byte] = reflect_crc(crc, 32);
  1080. }
  1081. initializedCRC32 = 1;
  1082. }
  1083. uint32_t enet_crc32(const ENetBuffer* buffers, size_t bufferCount) {
  1084. uint32_t crc = 0xFFFFFFFF;
  1085. if (!initializedCRC32)
  1086. initialize_crc32();
  1087. while (bufferCount-- > 0) {
  1088. const uint8_t* data = (const uint8_t*)buffers->data;
  1089. const uint8_t* dataEnd = &data[buffers->dataLength];
  1090. while (data < dataEnd) {
  1091. crc = (crc >> 8) ^ crcTable[(crc & 0xFF) ^ *data++];
  1092. }
  1093. ++buffers;
  1094. }
  1095. return ENET_HOST_TO_NET_32(~crc);
  1096. }
  1097. /*
  1098. =======================================================================
  1099. Packet
  1100. =======================================================================
  1101. */
  1102. ENetPacket* enet_packet_create(const void* data, size_t dataLength, uint32_t flags) {
  1103. ENetPacket* packet;
  1104. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1105. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1106. if (packet == NULL)
  1107. return NULL;
  1108. packet->data = (uint8_t*)data;
  1109. }
  1110. else {
  1111. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength);
  1112. if (packet == NULL)
  1113. return NULL;
  1114. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1115. if (data != NULL)
  1116. memcpy(packet->data, data, dataLength);
  1117. }
  1118. packet->referenceCount = 0;
  1119. packet->flags = flags;
  1120. packet->dataLength = dataLength;
  1121. packet->freeCallback = NULL;
  1122. packet->userData = NULL;
  1123. return packet;
  1124. }
  1125. ENetPacket* enet_packet_create_offset(const void* data, size_t dataLength, size_t dataOffset, uint32_t flags) {
  1126. ENetPacket* packet;
  1127. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1128. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1129. if (packet == NULL)
  1130. return NULL;
  1131. packet->data = (uint8_t*)data;
  1132. }
  1133. else {
  1134. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength - dataOffset);
  1135. if (packet == NULL)
  1136. return NULL;
  1137. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1138. if (data != NULL)
  1139. memcpy(packet->data, (char*)data + dataOffset, dataLength - dataOffset);
  1140. }
  1141. packet->referenceCount = 0;
  1142. packet->flags = flags;
  1143. packet->dataLength = dataLength - dataOffset;
  1144. packet->freeCallback = NULL;
  1145. packet->userData = NULL;
  1146. return packet;
  1147. }
  1148. void enet_packet_destroy(ENetPacket* packet) {
  1149. if (packet == NULL)
  1150. return;
  1151. if (packet->freeCallback != NULL)
  1152. (*packet->freeCallback)((void*)packet);
  1153. enet_free(packet);
  1154. }
  1155. /*
  1156. =======================================================================
  1157. Protocol
  1158. =======================================================================
  1159. */
  1160. static size_t commandSizes[ENET_PROTOCOL_COMMAND_COUNT] = {
  1161. 0,
  1162. sizeof(ENetProtocolAcknowledge),
  1163. sizeof(ENetProtocolConnect),
  1164. sizeof(ENetProtocolVerifyConnect),
  1165. sizeof(ENetProtocolDisconnect),
  1166. sizeof(ENetProtocolPing),
  1167. sizeof(ENetProtocolSendReliable),
  1168. sizeof(ENetProtocolSendUnreliable),
  1169. sizeof(ENetProtocolSendFragment),
  1170. sizeof(ENetProtocolSendUnsequenced),
  1171. sizeof(ENetProtocolBandwidthLimit),
  1172. sizeof(ENetProtocolThrottleConfigure),
  1173. sizeof(ENetProtocolSendFragment)
  1174. };
  1175. size_t enet_protocol_command_size(uint8_t commandNumber) {
  1176. return commandSizes[commandNumber & ENET_PROTOCOL_COMMAND_MASK];
  1177. }
  1178. static void enet_protocol_change_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1179. if (state == ENET_PEER_STATE_CONNECTED || state == ENET_PEER_STATE_DISCONNECT_LATER)
  1180. enet_peer_on_connect(peer);
  1181. else
  1182. enet_peer_on_disconnect(peer);
  1183. peer->state = state;
  1184. }
  1185. static void enet_protocol_dispatch_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1186. enet_protocol_change_state(host, peer, state);
  1187. if (!peer->needsDispatch) {
  1188. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1189. peer->needsDispatch = 1;
  1190. }
  1191. }
  1192. static int enet_protocol_dispatch_incoming_commands(ENetHost* host, ENetEvent* event) {
  1193. while (!enet_list_empty(&host->dispatchQueue)) {
  1194. ENetPeer* peer = (ENetPeer*)enet_list_remove(enet_list_begin(&host->dispatchQueue));
  1195. peer->needsDispatch = 0;
  1196. switch (peer->state) {
  1197. case ENET_PEER_STATE_CONNECTION_PENDING:
  1198. case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
  1199. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1200. event->type = ENET_EVENT_TYPE_CONNECT;
  1201. event->peer = peer;
  1202. event->data = peer->eventData;
  1203. return 1;
  1204. case ENET_PEER_STATE_ZOMBIE:
  1205. host->recalculateBandwidthLimits = 1;
  1206. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1207. event->peer = peer;
  1208. event->data = peer->eventData;
  1209. enet_peer_reset(peer);
  1210. return 1;
  1211. case ENET_PEER_STATE_CONNECTED:
  1212. if (enet_list_empty(&peer->dispatchedCommands))
  1213. continue;
  1214. event->packet = enet_peer_receive(peer, &event->channelID);
  1215. if (event->packet == NULL)
  1216. continue;
  1217. event->type = ENET_EVENT_TYPE_RECEIVE;
  1218. event->peer = peer;
  1219. if (!enet_list_empty(&peer->dispatchedCommands)) {
  1220. peer->needsDispatch = 1;
  1221. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1222. }
  1223. return 1;
  1224. default:
  1225. break;
  1226. }
  1227. }
  1228. return 0;
  1229. }
  1230. static void enet_protocol_notify_connect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1231. host->recalculateBandwidthLimits = 1;
  1232. if (event != NULL) {
  1233. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1234. peer->totalDataSent = 0;
  1235. peer->totalDataReceived = 0;
  1236. peer->totalPacketsSent = 0;
  1237. peer->totalPacketsLost = 0;
  1238. event->type = ENET_EVENT_TYPE_CONNECT;
  1239. event->peer = peer;
  1240. event->data = peer->eventData;
  1241. }
  1242. else {
  1243. enet_protocol_dispatch_state(host, peer, peer->state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING);
  1244. }
  1245. }
  1246. static void enet_protocol_notify_disconnect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1247. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1248. host->recalculateBandwidthLimits = 1;
  1249. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1250. enet_peer_reset(peer);
  1251. }
  1252. else if (event != NULL) {
  1253. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1254. event->peer = peer;
  1255. event->data = 0;
  1256. enet_peer_reset(peer);
  1257. }
  1258. else {
  1259. peer->eventData = 0;
  1260. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1261. }
  1262. }
  1263. static void enet_protocol_notify_disconnect_timeout(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1264. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1265. host->recalculateBandwidthLimits = 1;
  1266. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1267. enet_peer_reset(peer);
  1268. }
  1269. else if (event != NULL) {
  1270. event->type = ENET_EVENT_TYPE_DISCONNECT_TIMEOUT;
  1271. event->peer = peer;
  1272. event->data = 0;
  1273. enet_peer_reset(peer);
  1274. }
  1275. else {
  1276. peer->eventData = 0;
  1277. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1278. }
  1279. }
  1280. static void enet_protocol_remove_sent_unreliable_commands(ENetPeer* peer) {
  1281. ENetOutgoingCommand* outgoingCommand;
  1282. if (enet_list_empty(&peer->sentUnreliableCommands))
  1283. return;
  1284. do {
  1285. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentUnreliableCommands);
  1286. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1287. if (outgoingCommand->packet != NULL) {
  1288. --outgoingCommand->packet->referenceCount;
  1289. if (outgoingCommand->packet->referenceCount == 0) {
  1290. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1291. enet_packet_destroy(outgoingCommand->packet);
  1292. }
  1293. }
  1294. enet_free(outgoingCommand);
  1295. }
  1296. while (!enet_list_empty(&peer->sentUnreliableCommands));
  1297. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
  1298. enet_peer_disconnect(peer, peer->eventData);
  1299. }
  1300. static ENetProtocolCommand enet_protocol_remove_sent_reliable_command(ENetPeer* peer, uint16_t reliableSequenceNumber, uint8_t channelID) {
  1301. ENetOutgoingCommand* outgoingCommand = NULL;
  1302. ENetListIterator currentCommand;
  1303. ENetProtocolCommand commandNumber;
  1304. int wasSent = 1;
  1305. for (currentCommand = enet_list_begin(&peer->sentReliableCommands); currentCommand != enet_list_end(&peer->sentReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  1306. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1307. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1308. break;
  1309. }
  1310. if (currentCommand == enet_list_end(&peer->sentReliableCommands)) {
  1311. for (currentCommand = enet_list_begin(&peer->outgoingReliableCommands); currentCommand != enet_list_end(&peer->outgoingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  1312. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1313. if (outgoingCommand->sendAttempts < 1)
  1314. return ENET_PROTOCOL_COMMAND_NONE;
  1315. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1316. break;
  1317. }
  1318. if (currentCommand == enet_list_end(&peer->outgoingReliableCommands))
  1319. return ENET_PROTOCOL_COMMAND_NONE;
  1320. wasSent = 0;
  1321. }
  1322. if (outgoingCommand == NULL)
  1323. return ENET_PROTOCOL_COMMAND_NONE;
  1324. if (channelID < peer->channelCount) {
  1325. ENetChannel* channel = &peer->channels[channelID];
  1326. uint16_t reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1327. if (channel->reliableWindows[reliableWindow] > 0) {
  1328. --channel->reliableWindows[reliableWindow];
  1329. if (!channel->reliableWindows[reliableWindow])
  1330. channel->usedReliableWindows &= ~(1 << reliableWindow);
  1331. }
  1332. }
  1333. commandNumber = (ENetProtocolCommand)(outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK);
  1334. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1335. if (outgoingCommand->packet != NULL) {
  1336. if (wasSent)
  1337. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  1338. --outgoingCommand->packet->referenceCount;
  1339. if (outgoingCommand->packet->referenceCount == 0) {
  1340. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1341. enet_packet_destroy(outgoingCommand->packet);
  1342. }
  1343. }
  1344. enet_free(outgoingCommand);
  1345. if (enet_list_empty(&peer->sentReliableCommands))
  1346. return commandNumber;
  1347. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentReliableCommands);
  1348. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  1349. return commandNumber;
  1350. }
  1351. static ENetPeer* enet_protocol_handle_connect(ENetHost* host, ENetProtocolHeader* header, ENetProtocol* command) {
  1352. uint8_t incomingSessionID, outgoingSessionID;
  1353. uint32_t mtu, windowSize;
  1354. ENetChannel* channel;
  1355. size_t channelCount, duplicatePeers = 0;
  1356. ENetPeer* currentPeer, * peer = NULL;
  1357. ENetProtocol verifyCommand;
  1358. channelCount = ENET_NET_TO_HOST_32(command->connect.channelCount);
  1359. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  1360. return NULL;
  1361. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  1362. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
  1363. if (peer == NULL)
  1364. peer = currentPeer;
  1365. }
  1366. else if (currentPeer->state != ENET_PEER_STATE_CONNECTING && enet_in6_equal(currentPeer->address.ipv6, host->receivedAddress.ipv6)) {
  1367. if (currentPeer->address.port == host->receivedAddress.port && currentPeer->connectID == command->connect.connectID)
  1368. return NULL;
  1369. ++duplicatePeers;
  1370. }
  1371. }
  1372. if (peer == NULL || duplicatePeers >= host->duplicatePeers)
  1373. return NULL;
  1374. if (channelCount > host->channelLimit)
  1375. channelCount = host->channelLimit;
  1376. peer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  1377. if (peer->channels == NULL)
  1378. return NULL;
  1379. peer->channelCount = channelCount;
  1380. peer->state = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT;
  1381. peer->connectID = command->connect.connectID;
  1382. peer->address = host->receivedAddress;
  1383. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->connect.outgoingPeerID);
  1384. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->connect.incomingBandwidth);
  1385. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->connect.outgoingBandwidth);
  1386. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->connect.packetThrottleInterval);
  1387. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleAcceleration);
  1388. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleDeceleration);
  1389. peer->eventData = ENET_NET_TO_HOST_32(command->connect.data);
  1390. incomingSessionID = command->connect.incomingSessionID == 0xFF ? peer->outgoingSessionID : command->connect.incomingSessionID;
  1391. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1392. if (incomingSessionID == peer->outgoingSessionID)
  1393. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1394. peer->outgoingSessionID = incomingSessionID;
  1395. outgoingSessionID = command->connect.outgoingSessionID == 0xFF ? peer->incomingSessionID : command->connect.outgoingSessionID;
  1396. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1397. if (outgoingSessionID == peer->incomingSessionID)
  1398. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1399. peer->incomingSessionID = outgoingSessionID;
  1400. for (channel = peer->channels; channel < &peer->channels[channelCount]; ++channel) {
  1401. channel->outgoingReliableSequenceNumber = 0;
  1402. channel->outgoingUnreliableSequenceNumber = 0;
  1403. channel->incomingReliableSequenceNumber = 0;
  1404. channel->incomingUnreliableSequenceNumber = 0;
  1405. enet_list_clear(&channel->incomingReliableCommands);
  1406. enet_list_clear(&channel->incomingUnreliableCommands);
  1407. channel->usedReliableWindows = 0;
  1408. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  1409. }
  1410. mtu = ENET_NET_TO_HOST_32(command->connect.mtu);
  1411. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1412. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1413. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1414. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1415. peer->mtu = mtu;
  1416. if (host->outgoingBandwidth == 0 && peer->incomingBandwidth == 0)
  1417. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1418. else if (host->outgoingBandwidth == 0 || peer->incomingBandwidth == 0)
  1419. peer->windowSize = (ENET_MAX(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1420. else
  1421. peer->windowSize = (ENET_MIN(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1422. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1423. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1424. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1425. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1426. if (host->incomingBandwidth == 0)
  1427. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1428. else
  1429. windowSize = (host->incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1430. if (windowSize > ENET_NET_TO_HOST_32(command->connect.windowSize))
  1431. windowSize = ENET_NET_TO_HOST_32(command->connect.windowSize);
  1432. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1433. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1434. else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1435. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1436. verifyCommand.header.command = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  1437. verifyCommand.header.channelID = 0xFF;
  1438. verifyCommand.verifyConnect.outgoingPeerID = ENET_HOST_TO_NET_16(peer->incomingPeerID);
  1439. verifyCommand.verifyConnect.incomingSessionID = incomingSessionID;
  1440. verifyCommand.verifyConnect.outgoingSessionID = outgoingSessionID;
  1441. verifyCommand.verifyConnect.mtu = ENET_HOST_TO_NET_32(peer->mtu);
  1442. verifyCommand.verifyConnect.windowSize = ENET_HOST_TO_NET_32(windowSize);
  1443. verifyCommand.verifyConnect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  1444. verifyCommand.verifyConnect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  1445. verifyCommand.verifyConnect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  1446. verifyCommand.verifyConnect.packetThrottleInterval = ENET_HOST_TO_NET_32(peer->packetThrottleInterval);
  1447. verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(peer->packetThrottleAcceleration);
  1448. verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(peer->packetThrottleDeceleration);
  1449. verifyCommand.verifyConnect.connectID = peer->connectID;
  1450. enet_peer_queue_outgoing_command(peer, &verifyCommand, NULL, 0, 0);
  1451. return peer;
  1452. }
  1453. static int enet_protocol_handle_send_reliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1454. size_t dataLength;
  1455. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1456. 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");
  1457. return -1;
  1458. }
  1459. dataLength = ENET_NET_TO_HOST_16(command->sendReliable.dataLength);
  1460. *currentData += dataLength;
  1461. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1462. ENET_LOG_ERROR("packet data length error");
  1463. return -1;
  1464. }
  1465. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) == NULL) {
  1466. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1467. return -1;
  1468. }
  1469. return 0;
  1470. }
  1471. static int enet_protocol_handle_send_unsequenced(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1472. uint32_t unsequencedGroup, index;
  1473. size_t dataLength;
  1474. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1475. 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");
  1476. return -1;
  1477. }
  1478. dataLength = ENET_NET_TO_HOST_16(command->sendUnsequenced.dataLength);
  1479. *currentData += dataLength;
  1480. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1481. ENET_LOG_ERROR("packet data length error");
  1482. return -1;
  1483. }
  1484. unsequencedGroup = ENET_NET_TO_HOST_16(command->sendUnsequenced.unsequencedGroup);
  1485. index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE;
  1486. if (unsequencedGroup < peer->incomingUnsequencedGroup)
  1487. unsequencedGroup += 0x10000;
  1488. if (unsequencedGroup >= (uint32_t)peer->incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE)
  1489. return 0;
  1490. unsequencedGroup &= 0xFFFF;
  1491. if (unsequencedGroup - index != peer->incomingUnsequencedGroup) {
  1492. peer->incomingUnsequencedGroup = unsequencedGroup - index;
  1493. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  1494. }
  1495. else if (peer->unsequencedWindow[index / 32] & (1 << (index % 32))) {
  1496. return 0;
  1497. }
  1498. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED, 0) == NULL) {
  1499. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1500. return -1;
  1501. }
  1502. peer->unsequencedWindow[index / 32] |= 1 << (index % 32);
  1503. return 0;
  1504. }
  1505. static int enet_protocol_handle_send_unreliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1506. size_t dataLength;
  1507. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1508. 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");
  1509. return -1;
  1510. }
  1511. dataLength = ENET_NET_TO_HOST_16(command->sendUnreliable.dataLength);
  1512. *currentData += dataLength;
  1513. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1514. ENET_LOG_ERROR("packet data length error");
  1515. return -1;
  1516. }
  1517. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnreliable), dataLength, 0, 0) == NULL) {
  1518. ENET_LOG_ERROR("Could not queue incoming command, it returned NULL");
  1519. return -1;
  1520. }
  1521. return 0;
  1522. }
  1523. static int enet_protocol_handle_send_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1524. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength;
  1525. ENetChannel* channel;
  1526. uint16_t startWindow, currentWindow;
  1527. ENetListIterator currentCommand;
  1528. ENetIncomingCommand* startCommand = NULL;
  1529. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1530. 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");
  1531. return -1;
  1532. }
  1533. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1534. *currentData += fragmentLength;
  1535. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1536. ENET_LOG_ERROR("packet data length error");
  1537. return -1;
  1538. }
  1539. channel = &peer->channels[command->header.channelID];
  1540. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1541. startWindow = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1542. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1543. if (startSequenceNumber < channel->incomingReliableSequenceNumber)
  1544. startWindow += ENET_PEER_RELIABLE_WINDOWS;
  1545. if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1546. return 0;
  1547. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1548. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1549. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1550. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1551. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
  1552. {
  1553. ENET_LOG_ERROR("fragmented packet error");
  1554. return -1;
  1555. }
  1556. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1557. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1558. if (startSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1559. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1560. continue;
  1561. }
  1562. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1563. break;
  1564. }
  1565. if (incomingCommand->reliableSequenceNumber <= startSequenceNumber) {
  1566. if (incomingCommand->reliableSequenceNumber < startSequenceNumber)
  1567. break;
  1568. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1569. {
  1570. ENET_LOG_ERROR("fragmented packet error");
  1571. return -1;
  1572. }
  1573. startCommand = incomingCommand;
  1574. break;
  1575. }
  1576. }
  1577. if (startCommand == NULL) {
  1578. ENetProtocol hostCommand = *command;
  1579. hostCommand.header.reliableSequenceNumber = startSequenceNumber;
  1580. startCommand = enet_peer_queue_incoming_command(peer, &hostCommand, NULL, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount);
  1581. if (startCommand == NULL)
  1582. {
  1583. ENET_LOG_ERROR("startCommand was NULL");
  1584. return -1;
  1585. }
  1586. }
  1587. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1588. --startCommand->fragmentsRemaining;
  1589. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1590. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1591. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1592. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1593. if (startCommand->fragmentsRemaining <= 0)
  1594. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  1595. }
  1596. return 0;
  1597. }
  1598. static int enet_protocol_handle_send_unreliable_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1599. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength;
  1600. uint16_t reliableWindow, currentWindow;
  1601. ENetChannel* channel;
  1602. ENetListIterator currentCommand;
  1603. ENetIncomingCommand* startCommand = NULL;
  1604. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)) {
  1605. 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");
  1606. return -1;
  1607. }
  1608. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1609. *currentData += fragmentLength;
  1610. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > & host->receivedData[host->receivedDataLength]) {
  1611. ENET_LOG_ERROR("fragmented packet error");
  1612. return -1;
  1613. }
  1614. channel = &peer->channels[command->header.channelID];
  1615. reliableSequenceNumber = command->header.reliableSequenceNumber;
  1616. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1617. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1618. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1619. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1620. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  1621. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1622. return 0;
  1623. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && startSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  1624. return 0;
  1625. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1626. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1627. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1628. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1629. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset) {
  1630. 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");
  1631. return -1;
  1632. }
  1633. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1634. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1635. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1636. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1637. continue;
  1638. }
  1639. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1640. break;
  1641. }
  1642. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  1643. break;
  1644. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  1645. continue;
  1646. if (incomingCommand->unreliableSequenceNumber <= startSequenceNumber) {
  1647. if (incomingCommand->unreliableSequenceNumber < startSequenceNumber)
  1648. break;
  1649. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1650. {
  1651. ENET_LOG_ERROR("fragmented packet error");
  1652. return -1;
  1653. }
  1654. startCommand = incomingCommand;
  1655. break;
  1656. }
  1657. }
  1658. if (startCommand == NULL) {
  1659. startCommand = enet_peer_queue_incoming_command(peer, command, NULL, totalLength,
  1660. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED, fragmentCount);
  1661. if (startCommand == NULL) {
  1662. ENET_LOG_ERROR("startCommand was NULL");
  1663. return -1;
  1664. }
  1665. }
  1666. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1667. --startCommand->fragmentsRemaining;
  1668. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1669. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1670. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1671. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1672. if (startCommand->fragmentsRemaining <= 0)
  1673. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  1674. }
  1675. return 0;
  1676. }
  1677. static int enet_protocol_handle_ping(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1678. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1679. return -1;
  1680. return 0;
  1681. }
  1682. static int enet_protocol_handle_bandwidth_limit(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1683. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1684. {
  1685. ENET_LOG_ERROR("Doing jack squat on a peer that is not connected correctly");
  1686. return -1;
  1687. }
  1688. if (peer->incomingBandwidth != 0)
  1689. --host->bandwidthLimitedPeers;
  1690. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.incomingBandwidth);
  1691. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.outgoingBandwidth);
  1692. if (peer->incomingBandwidth != 0)
  1693. ++host->bandwidthLimitedPeers;
  1694. if (peer->incomingBandwidth == 0 && host->outgoingBandwidth == 0)
  1695. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1696. else if (peer->incomingBandwidth == 0 || host->outgoingBandwidth == 0)
  1697. peer->windowSize = (ENET_MAX(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1698. else
  1699. peer->windowSize = (ENET_MIN(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1700. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1701. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1702. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1703. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1704. return 0;
  1705. }
  1706. static int enet_protocol_handle_throttle_configure(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1707. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1708. {
  1709. ENET_LOG_ERROR("Doing jack squat on a peer that is not connected correctly");
  1710. return -1;
  1711. }
  1712. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleInterval);
  1713. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleAcceleration);
  1714. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleDeceleration);
  1715. return 0;
  1716. }
  1717. static int enet_protocol_handle_disconnect(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1718. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT)
  1719. return 0;
  1720. enet_peer_reset_queues(peer);
  1721. if (peer->state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_CONNECTING) {
  1722. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1723. }
  1724. else if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1725. if (peer->state == ENET_PEER_STATE_CONNECTION_PENDING)
  1726. host->recalculateBandwidthLimits = 1;
  1727. enet_peer_reset(peer);
  1728. }
  1729. else if (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  1730. enet_protocol_change_state(host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT);
  1731. }
  1732. else {
  1733. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1734. }
  1735. if (peer->state != ENET_PEER_STATE_DISCONNECTED)
  1736. peer->eventData = ENET_NET_TO_HOST_32(command->disconnect.data);
  1737. return 0;
  1738. }
  1739. static int enet_protocol_handle_acknowledge(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1740. uint32_t roundTripTime, receivedSentTime, receivedReliableSequenceNumber;
  1741. ENetProtocolCommand commandNumber;
  1742. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE)
  1743. return 0;
  1744. receivedSentTime = ENET_NET_TO_HOST_16(command->acknowledge.receivedSentTime);
  1745. receivedSentTime |= host->serviceTime & 0xFFFF0000;
  1746. if ((receivedSentTime & 0x8000) > (host->serviceTime & 0x8000))
  1747. receivedSentTime -= 0x10000;
  1748. if (ENET_TIME_LESS(host->serviceTime, receivedSentTime))
  1749. return 0;
  1750. roundTripTime = ENET_TIME_DIFFERENCE(host->serviceTime, receivedSentTime);
  1751. if (roundTripTime == 0)
  1752. roundTripTime = 1;
  1753. enet_peer_throttle(peer, roundTripTime);
  1754. if (peer->lastReceiveTime > 0) {
  1755. if (roundTripTime >= peer->roundTripTime) {
  1756. uint32_t diff = roundTripTime - peer->roundTripTime;
  1757. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1758. peer->roundTripTimeVariance += diff / 4;
  1759. peer->roundTripTime += diff / 8;
  1760. }
  1761. else {
  1762. uint32_t diff = peer->roundTripTime - roundTripTime;
  1763. if (diff <= peer->roundTripTimeVariance) {
  1764. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1765. peer->roundTripTimeVariance += diff / 4;
  1766. }
  1767. else {
  1768. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 32;
  1769. peer->roundTripTimeVariance += diff / 32;
  1770. }
  1771. peer->roundTripTime -= diff / 8;
  1772. }
  1773. }
  1774. else {
  1775. peer->roundTripTime = roundTripTime;
  1776. peer->roundTripTimeVariance = roundTripTime / 2;
  1777. }
  1778. if (peer->roundTripTime < peer->lowestRoundTripTime)
  1779. peer->lowestRoundTripTime = peer->roundTripTime;
  1780. if (peer->roundTripTimeVariance > peer->highestRoundTripTimeVariance)
  1781. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1782. if (peer->packetThrottleEpoch == 0 || ENET_TIME_DIFFERENCE(host->serviceTime, peer->packetThrottleEpoch) >= peer->packetThrottleInterval) {
  1783. peer->lastRoundTripTime = peer->lowestRoundTripTime;
  1784. peer->lastRoundTripTimeVariance = peer->highestRoundTripTimeVariance;
  1785. peer->lowestRoundTripTime = peer->roundTripTime;
  1786. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1787. peer->packetThrottleEpoch = host->serviceTime;
  1788. }
  1789. peer->lastReceiveTime = ENET_MAX(host->serviceTime, 1);
  1790. peer->earliestTimeout = 0;
  1791. receivedReliableSequenceNumber = ENET_NET_TO_HOST_16(command->acknowledge.receivedReliableSequenceNumber);
  1792. commandNumber = enet_protocol_remove_sent_reliable_command(peer, receivedReliableSequenceNumber, command->header.channelID);
  1793. switch (peer->state) {
  1794. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1795. if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT) {
  1796. ENET_LOG_ERROR("Wrong command number. Got %u vs %u", commandNumber, ENET_PROTOCOL_COMMAND_VERIFY_CONNECT);
  1797. return -1;
  1798. }
  1799. enet_protocol_notify_connect(host, peer, event);
  1800. break;
  1801. case ENET_PEER_STATE_DISCONNECTING:
  1802. if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT)
  1803. {
  1804. ENET_LOG_ERROR("Wrong command number. Got %u vs %u", commandNumber, ENET_PROTOCOL_COMMAND_DISCONNECT);
  1805. return -1;
  1806. }
  1807. enet_protocol_notify_disconnect(host, peer, event);
  1808. break;
  1809. case ENET_PEER_STATE_DISCONNECT_LATER:
  1810. if (enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
  1811. enet_peer_disconnect(peer, peer->eventData);
  1812. break;
  1813. default:
  1814. break;
  1815. }
  1816. return 0;
  1817. }
  1818. static int enet_protocol_handle_verify_connect(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1819. uint32_t mtu, windowSize;
  1820. size_t channelCount;
  1821. if (peer->state != ENET_PEER_STATE_CONNECTING)
  1822. return 0;
  1823. channelCount = ENET_NET_TO_HOST_32(command->verifyConnect.channelCount);
  1824. 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) {
  1825. peer->eventData = 0;
  1826. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1827. ENET_LOG_ERROR("Zombie peer detected");
  1828. return -1;
  1829. }
  1830. enet_protocol_remove_sent_reliable_command(peer, 1, 0xFF);
  1831. if (channelCount < peer->channelCount)
  1832. peer->channelCount = channelCount;
  1833. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->verifyConnect.outgoingPeerID);
  1834. peer->incomingSessionID = command->verifyConnect.incomingSessionID;
  1835. peer->outgoingSessionID = command->verifyConnect.outgoingSessionID;
  1836. mtu = ENET_NET_TO_HOST_32(command->verifyConnect.mtu);
  1837. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1838. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1839. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1840. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1841. if (mtu < peer->mtu)
  1842. peer->mtu = mtu;
  1843. windowSize = ENET_NET_TO_HOST_32(command->verifyConnect.windowSize);
  1844. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1845. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1846. if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1847. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1848. if (windowSize < peer->windowSize)
  1849. peer->windowSize = windowSize;
  1850. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.incomingBandwidth);
  1851. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.outgoingBandwidth);
  1852. enet_protocol_notify_connect(host, peer, event);
  1853. return 0;
  1854. }
  1855. static int enet_protocol_handle_incoming_commands(ENetHost* host, ENetEvent* event) {
  1856. ENetProtocolHeader* header;
  1857. ENetProtocol* command;
  1858. ENetPeer* peer;
  1859. uint8_t* currentData;
  1860. size_t headerSize;
  1861. uint16_t peerID, flags;
  1862. uint8_t sessionID;
  1863. if (host->receivedDataLength < (size_t) & ((ENetProtocolHeader*)0)->sentTime)
  1864. return 0;
  1865. header = (ENetProtocolHeader*)host->receivedData;
  1866. peerID = ENET_NET_TO_HOST_16(header->peerID);
  1867. sessionID = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  1868. flags = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK;
  1869. peerID &= ~(ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK);
  1870. headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof(ENetProtocolHeader) : (size_t) & ((ENetProtocolHeader*)0)->sentTime);
  1871. if (host->checksumCallback != NULL)
  1872. headerSize += sizeof(uint32_t);
  1873. if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  1874. peer = NULL;
  1875. }
  1876. else if (peerID >= host->peerCount) {
  1877. return 0;
  1878. }
  1879. else {
  1880. peer = &host->peers[peerID];
  1881. 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))
  1882. return 0;
  1883. }
  1884. if (host->checksumCallback != NULL) {
  1885. uint32_t* checksum = (uint32_t*)&host->receivedData[headerSize - sizeof(uint32_t)];
  1886. uint32_t desiredChecksum = *checksum;
  1887. ENetBuffer buffer;
  1888. *checksum = peer != NULL ? peer->connectID : 0;
  1889. buffer.data = host->receivedData;
  1890. buffer.dataLength = host->receivedDataLength;
  1891. if (host->checksumCallback(&buffer, 1) != desiredChecksum)
  1892. return 0;
  1893. }
  1894. if (peer != NULL) {
  1895. peer->address.ipv6 = host->receivedAddress.ipv6;
  1896. peer->address.port = host->receivedAddress.port;
  1897. peer->incomingDataTotal += host->receivedDataLength;
  1898. peer->totalDataReceived += host->receivedDataLength;
  1899. }
  1900. currentData = host->receivedData + headerSize;
  1901. while (currentData < &host->receivedData[host->receivedDataLength]) {
  1902. uint8_t commandNumber;
  1903. size_t commandSize;
  1904. command = (ENetProtocol*)currentData;
  1905. if (currentData + sizeof(ENetProtocolCommandHeader) > & host->receivedData[host->receivedDataLength])
  1906. break;
  1907. commandNumber = command->header.command & ENET_PROTOCOL_COMMAND_MASK;
  1908. if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT)
  1909. break;
  1910. commandSize = commandSizes[commandNumber];
  1911. if (commandSize == 0 || currentData + commandSize > & host->receivedData[host->receivedDataLength])
  1912. break;
  1913. currentData += commandSize;
  1914. if (peer == NULL && (commandNumber != ENET_PROTOCOL_COMMAND_CONNECT || currentData < &host->receivedData[host->receivedDataLength]))
  1915. break;
  1916. command->header.reliableSequenceNumber = ENET_NET_TO_HOST_16(command->header.reliableSequenceNumber);
  1917. switch (commandNumber) {
  1918. case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE:
  1919. if (enet_protocol_handle_acknowledge(host, event, peer, command))
  1920. goto commandError;
  1921. break;
  1922. case ENET_PROTOCOL_COMMAND_CONNECT:
  1923. if (peer != NULL)
  1924. goto commandError;
  1925. if (host->preventConnections == 0) {
  1926. peer = enet_protocol_handle_connect(host, header, command);
  1927. if (peer == NULL)
  1928. goto commandError;
  1929. }
  1930. break;
  1931. case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT:
  1932. if (enet_protocol_handle_verify_connect(host, event, peer, command))
  1933. goto commandError;
  1934. break;
  1935. case ENET_PROTOCOL_COMMAND_DISCONNECT:
  1936. if (enet_protocol_handle_disconnect(host, peer, command))
  1937. goto commandError;
  1938. break;
  1939. case ENET_PROTOCOL_COMMAND_PING:
  1940. if (enet_protocol_handle_ping(host, peer, command))
  1941. goto commandError;
  1942. break;
  1943. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  1944. if (enet_protocol_handle_send_reliable(host, peer, command, &currentData))
  1945. goto commandError;
  1946. break;
  1947. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  1948. if (enet_protocol_handle_send_unreliable(host, peer, command, &currentData))
  1949. goto commandError;
  1950. break;
  1951. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  1952. if (enet_protocol_handle_send_unsequenced(host, peer, command, &currentData))
  1953. goto commandError;
  1954. break;
  1955. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  1956. if (enet_protocol_handle_send_fragment(host, peer, command, &currentData))
  1957. goto commandError;
  1958. break;
  1959. case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT:
  1960. if (enet_protocol_handle_bandwidth_limit(host, peer, command))
  1961. goto commandError;
  1962. break;
  1963. case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE:
  1964. if (enet_protocol_handle_throttle_configure(host, peer, command))
  1965. goto commandError;
  1966. break;
  1967. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  1968. if (enet_protocol_handle_send_unreliable_fragment(host, peer, command, &currentData))
  1969. goto commandError;
  1970. break;
  1971. default:
  1972. goto commandError;
  1973. }
  1974. if (peer != NULL && (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) {
  1975. uint16_t sentTime;
  1976. if (!(flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME))
  1977. break;
  1978. sentTime = ENET_NET_TO_HOST_16(header->sentTime);
  1979. switch (peer->state) {
  1980. case ENET_PEER_STATE_DISCONNECTING:
  1981. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1982. case ENET_PEER_STATE_DISCONNECTED:
  1983. case ENET_PEER_STATE_ZOMBIE:
  1984. break;
  1985. case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
  1986. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  1987. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1988. break;
  1989. default:
  1990. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1991. break;
  1992. }
  1993. }
  1994. }
  1995. commandError:
  1996. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  1997. return 1;
  1998. return 0;
  1999. }
  2000. static int enet_protocol_receive_incoming_commands(ENetHost* host, ENetEvent* event) {
  2001. int packets;
  2002. for (packets = 0; packets < 256; ++packets) {
  2003. int receivedLength;
  2004. ENetBuffer buffer;
  2005. buffer.data = host->packetData[0];
  2006. buffer.dataLength = host->mtu;
  2007. receivedLength = enet_socket_receive(host->socket, &host->receivedAddress, &buffer, 1);
  2008. if (receivedLength == -2)
  2009. continue;
  2010. if (receivedLength < 0) {
  2011. ENET_LOG_ERROR("received length was negative: %i", receivedLength);
  2012. return -1;
  2013. }
  2014. if (receivedLength == 0)
  2015. return 0;
  2016. host->receivedData = host->packetData[0];
  2017. host->receivedDataLength = receivedLength;
  2018. host->totalReceivedData += receivedLength;
  2019. host->totalReceivedPackets++;
  2020. if (host->interceptCallback != NULL) {
  2021. switch (host->interceptCallback(host, (void*)event)) {
  2022. case 1:
  2023. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  2024. return 1;
  2025. continue;
  2026. case -1:
  2027. ENET_LOG_ERROR("intercept callback failure");
  2028. return -1;
  2029. default:
  2030. break;
  2031. }
  2032. }
  2033. switch (enet_protocol_handle_incoming_commands(host, event)) {
  2034. case 1:
  2035. return 1;
  2036. case -1:
  2037. ENET_LOG_ERROR("enet_protocol_handle_incoming_commands failure");
  2038. return -1;
  2039. default:
  2040. break;
  2041. }
  2042. }
  2043. // Fix as described here: https://github.com/lsalzman/enet/pull/120
  2044. return 0;
  2045. }
  2046. static void enet_protocol_send_acknowledgements(ENetHost* host, ENetPeer* peer) {
  2047. ENetProtocol* command = &host->commands[host->commandCount];
  2048. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2049. ENetAcknowledgement* acknowledgement;
  2050. ENetListIterator currentAcknowledgement;
  2051. uint16_t reliableSequenceNumber;
  2052. currentAcknowledgement = enet_list_begin(&peer->acknowledgements);
  2053. while (currentAcknowledgement != enet_list_end(&peer->acknowledgements)) {
  2054. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < sizeof(ENetProtocolAcknowledge)) {
  2055. host->continueSending = 1;
  2056. break;
  2057. }
  2058. acknowledgement = (ENetAcknowledgement*)currentAcknowledgement;
  2059. currentAcknowledgement = enet_list_next(currentAcknowledgement);
  2060. buffer->data = command;
  2061. buffer->dataLength = sizeof(ENetProtocolAcknowledge);
  2062. host->packetSize += buffer->dataLength;
  2063. reliableSequenceNumber = ENET_HOST_TO_NET_16(acknowledgement->command.header.reliableSequenceNumber);
  2064. command->header.command = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
  2065. command->header.channelID = acknowledgement->command.header.channelID;
  2066. command->header.reliableSequenceNumber = reliableSequenceNumber;
  2067. command->acknowledge.receivedReliableSequenceNumber = reliableSequenceNumber;
  2068. command->acknowledge.receivedSentTime = ENET_HOST_TO_NET_16(acknowledgement->sentTime);
  2069. if ((acknowledgement->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  2070. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  2071. enet_list_remove(&acknowledgement->acknowledgementList);
  2072. enet_free(acknowledgement);
  2073. ++command;
  2074. ++buffer;
  2075. }
  2076. host->commandCount = command - host->commands;
  2077. host->bufferCount = buffer - host->buffers;
  2078. }
  2079. static void enet_protocol_send_unreliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
  2080. ENetProtocol* command = &host->commands[host->commandCount];
  2081. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2082. ENetOutgoingCommand* outgoingCommand;
  2083. ENetListIterator currentCommand;
  2084. currentCommand = enet_list_begin(&peer->outgoingUnreliableCommands);
  2085. while (currentCommand != enet_list_end(&peer->outgoingUnreliableCommands)) {
  2086. size_t commandSize;
  2087. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2088. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2089. 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)) {
  2090. host->continueSending = 1;
  2091. break;
  2092. }
  2093. currentCommand = enet_list_next(currentCommand);
  2094. if (outgoingCommand->packet != NULL && outgoingCommand->fragmentOffset == 0) {
  2095. peer->packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER;
  2096. peer->packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE;
  2097. if (!(outgoingCommand->packet->flags & (ENET_PACKET_FLAG_CRUCIAL)) && peer->packetThrottleCounter > peer->packetThrottle) {
  2098. uint16_t reliableSequenceNumber = outgoingCommand->reliableSequenceNumber;
  2099. uint16_t unreliableSequenceNumber = outgoingCommand->unreliableSequenceNumber;
  2100. for (;;) {
  2101. --outgoingCommand->packet->referenceCount;
  2102. if (outgoingCommand->packet->referenceCount == 0)
  2103. enet_packet_destroy(outgoingCommand->packet);
  2104. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2105. enet_free(outgoingCommand);
  2106. if (currentCommand == enet_list_end(&peer->outgoingUnreliableCommands))
  2107. break;
  2108. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2109. if (outgoingCommand->reliableSequenceNumber != reliableSequenceNumber || outgoingCommand->unreliableSequenceNumber != unreliableSequenceNumber)
  2110. break;
  2111. currentCommand = enet_list_next(currentCommand);
  2112. }
  2113. continue;
  2114. }
  2115. }
  2116. buffer->data = command;
  2117. buffer->dataLength = commandSize;
  2118. host->packetSize += buffer->dataLength;
  2119. *command = outgoingCommand->command;
  2120. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2121. if (outgoingCommand->packet != NULL) {
  2122. ++buffer;
  2123. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2124. buffer->dataLength = outgoingCommand->fragmentLength;
  2125. host->packetSize += buffer->dataLength;
  2126. enet_list_insert(enet_list_end(&peer->sentUnreliableCommands), outgoingCommand);
  2127. }
  2128. else {
  2129. enet_free(outgoingCommand);
  2130. }
  2131. ++command;
  2132. ++buffer;
  2133. }
  2134. host->commandCount = command - host->commands;
  2135. host->bufferCount = buffer - host->buffers;
  2136. 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))
  2137. enet_peer_disconnect(peer, peer->eventData);
  2138. }
  2139. static int enet_protocol_check_timeouts(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  2140. ENetOutgoingCommand* outgoingCommand;
  2141. ENetListIterator currentCommand, insertPosition;
  2142. currentCommand = enet_list_begin(&peer->sentReliableCommands);
  2143. insertPosition = enet_list_begin(&peer->outgoingReliableCommands);
  2144. while (currentCommand != enet_list_end(&peer->sentReliableCommands)) {
  2145. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2146. currentCommand = enet_list_next(currentCommand);
  2147. if (ENET_TIME_DIFFERENCE(host->serviceTime, outgoingCommand->sentTime) < outgoingCommand->roundTripTimeout)
  2148. continue;
  2149. if (peer->earliestTimeout == 0 || ENET_TIME_LESS(outgoingCommand->sentTime, peer->earliestTimeout))
  2150. peer->earliestTimeout = outgoingCommand->sentTime;
  2151. 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))) {
  2152. enet_protocol_notify_disconnect_timeout(host, peer, event);
  2153. return 1;
  2154. }
  2155. if (outgoingCommand->packet != NULL)
  2156. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  2157. ++peer->packetsLost;
  2158. ++peer->totalPacketsLost;
  2159. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2160. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2161. enet_list_insert(insertPosition, enet_list_remove(&outgoingCommand->outgoingCommandList));
  2162. if (currentCommand == enet_list_begin(&peer->sentReliableCommands) && !enet_list_empty(&peer->sentReliableCommands)) {
  2163. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2164. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  2165. }
  2166. }
  2167. return 0;
  2168. }
  2169. static int enet_protocol_send_reliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
  2170. ENetProtocol* command = &host->commands[host->commandCount];
  2171. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2172. ENetOutgoingCommand* outgoingCommand;
  2173. ENetListIterator currentCommand;
  2174. ENetChannel* channel;
  2175. uint16_t reliableWindow;
  2176. size_t commandSize;
  2177. int windowExceeded = 0, windowWrap = 0, canPing = 1;
  2178. currentCommand = enet_list_begin(&peer->outgoingReliableCommands);
  2179. while (currentCommand != enet_list_end(&peer->outgoingReliableCommands)) {
  2180. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2181. channel = outgoingCommand->command.header.channelID < peer->channelCount ? &peer->channels[outgoingCommand->command.header.channelID] : NULL;
  2182. reliableWindow = outgoingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2183. if (channel != NULL) {
  2184. 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)))))
  2185. windowWrap = 1;
  2186. if (windowWrap) {
  2187. currentCommand = enet_list_next(currentCommand);
  2188. continue;
  2189. }
  2190. }
  2191. if (outgoingCommand->packet != NULL) {
  2192. if (!windowExceeded) {
  2193. uint32_t windowSize = (peer->packetThrottle * peer->windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE;
  2194. if (peer->reliableDataInTransit + outgoingCommand->fragmentLength > ENET_MAX(windowSize, peer->mtu))
  2195. windowExceeded = 1;
  2196. }
  2197. if (windowExceeded) {
  2198. currentCommand = enet_list_next(currentCommand);
  2199. continue;
  2200. }
  2201. }
  2202. canPing = 0;
  2203. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2204. 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))) {
  2205. host->continueSending = 1;
  2206. break;
  2207. }
  2208. currentCommand = enet_list_next(currentCommand);
  2209. if (channel != NULL && outgoingCommand->sendAttempts < 1) {
  2210. channel->usedReliableWindows |= 1 << reliableWindow;
  2211. ++channel->reliableWindows[reliableWindow];
  2212. }
  2213. ++outgoingCommand->sendAttempts;
  2214. if (outgoingCommand->roundTripTimeout == 0) {
  2215. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2216. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2217. }
  2218. if (enet_list_empty(&peer->sentReliableCommands))
  2219. peer->nextTimeout = host->serviceTime + outgoingCommand->roundTripTimeout;
  2220. enet_list_insert(enet_list_end(&peer->sentReliableCommands), enet_list_remove(&outgoingCommand->outgoingCommandList));
  2221. outgoingCommand->sentTime = host->serviceTime;
  2222. buffer->data = command;
  2223. buffer->dataLength = commandSize;
  2224. host->packetSize += buffer->dataLength;
  2225. host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
  2226. *command = outgoingCommand->command;
  2227. if (outgoingCommand->packet != NULL) {
  2228. ++buffer;
  2229. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2230. buffer->dataLength = outgoingCommand->fragmentLength;
  2231. host->packetSize += outgoingCommand->fragmentLength;
  2232. peer->reliableDataInTransit += outgoingCommand->fragmentLength;
  2233. }
  2234. ++peer->packetsSent;
  2235. ++peer->totalPacketsSent;
  2236. ++command;
  2237. ++buffer;
  2238. }
  2239. host->commandCount = command - host->commands;
  2240. host->bufferCount = buffer - host->buffers;
  2241. return canPing;
  2242. }
  2243. static int enet_protocol_send_outgoing_commands(ENetHost* host, ENetEvent* event, int checkForTimeouts) {
  2244. uint8_t headerData[sizeof(ENetProtocolHeader) + sizeof(uint32_t)];
  2245. ENetProtocolHeader* header = (ENetProtocolHeader*)headerData;
  2246. ENetPeer* currentPeer;
  2247. int sentLength;
  2248. host->continueSending = 1;
  2249. while (host->continueSending) {
  2250. for (host->continueSending = 0, currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2251. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED || currentPeer->state == ENET_PEER_STATE_ZOMBIE)
  2252. continue;
  2253. host->headerFlags = 0;
  2254. host->commandCount = 0;
  2255. host->bufferCount = 1;
  2256. host->packetSize = sizeof(ENetProtocolHeader);
  2257. if (!enet_list_empty(&currentPeer->acknowledgements))
  2258. enet_protocol_send_acknowledgements(host, currentPeer);
  2259. if (checkForTimeouts != 0 && !enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_GREATER_EQUAL(host->serviceTime, currentPeer->nextTimeout) && enet_protocol_check_timeouts(host, currentPeer, event) == 1) {
  2260. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  2261. return 1;
  2262. else
  2263. continue;
  2264. }
  2265. 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)) {
  2266. enet_peer_ping(currentPeer);
  2267. enet_protocol_send_reliable_outgoing_commands(host, currentPeer);
  2268. }
  2269. if (!enet_list_empty(&currentPeer->outgoingUnreliableCommands))
  2270. enet_protocol_send_unreliable_outgoing_commands(host, currentPeer);
  2271. if (host->commandCount == 0)
  2272. continue;
  2273. if (currentPeer->packetLossEpoch == 0) {
  2274. currentPeer->packetLossEpoch = host->serviceTime;
  2275. }
  2276. else if (ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL && currentPeer->packetsSent > 0) {
  2277. uint32_t packetLoss = currentPeer->packetsLost * ENET_PEER_PACKET_LOSS_SCALE / currentPeer->packetsSent;
  2278. ENET_LOG_TRACE(
  2279. "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,
  2280. (currentPeer->packetLoss / (float)ENET_PEER_PACKET_LOSS_SCALE) * 100,
  2281. (currentPeer->packetLossVariance / (float)ENET_PEER_PACKET_LOSS_SCALE) * 100, currentPeer->roundTripTime, currentPeer->roundTripTimeVariance,
  2282. (currentPeer->packetThrottle / (float)ENET_PEER_PACKET_THROTTLE_SCALE) * 100,
  2283. enet_list_size(&currentPeer->outgoingReliableCommands),
  2284. enet_list_size(&currentPeer->outgoingUnreliableCommands),
  2285. currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingReliableCommands) : 0,
  2286. currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingUnreliableCommands) : 0
  2287. );
  2288. currentPeer->packetLossVariance -= currentPeer->packetLossVariance / 4;
  2289. if (packetLoss >= currentPeer->packetLoss) {
  2290. currentPeer->packetLoss += (packetLoss - currentPeer->packetLoss) / 8;
  2291. currentPeer->packetLossVariance += (packetLoss - currentPeer->packetLoss) / 4;
  2292. }
  2293. else {
  2294. currentPeer->packetLoss -= (currentPeer->packetLoss - packetLoss) / 8;
  2295. currentPeer->packetLossVariance += (currentPeer->packetLoss - packetLoss) / 4;
  2296. }
  2297. currentPeer->packetLossEpoch = host->serviceTime;
  2298. currentPeer->packetsSent = 0;
  2299. currentPeer->packetsLost = 0;
  2300. }
  2301. host->buffers->data = headerData;
  2302. if (host->headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) {
  2303. header->sentTime = ENET_HOST_TO_NET_16(host->serviceTime & 0xFFFF);
  2304. host->buffers->dataLength = sizeof(ENetProtocolHeader);
  2305. }
  2306. else {
  2307. host->buffers->dataLength = (size_t) & ((ENetProtocolHeader*)0)->sentTime;
  2308. }
  2309. if (currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID)
  2310. host->headerFlags |= currentPeer->outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  2311. header->peerID = ENET_HOST_TO_NET_16(currentPeer->outgoingPeerID | host->headerFlags);
  2312. if (host->checksumCallback != NULL) {
  2313. uint32_t* checksum = (uint32_t*)&headerData[host->buffers->dataLength];
  2314. *checksum = currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer->connectID : 0;
  2315. host->buffers->dataLength += sizeof(uint32_t);
  2316. *checksum = host->checksumCallback(host->buffers, host->bufferCount);
  2317. }
  2318. currentPeer->lastSendTime = host->serviceTime;
  2319. sentLength = enet_socket_send(host->socket, &currentPeer->address, host->buffers, host->bufferCount);
  2320. enet_protocol_remove_sent_unreliable_commands(currentPeer);
  2321. if (sentLength < 0) {
  2322. ENET_LOG_ERROR("sentLength was negative: %i", sentLength);
  2323. return -1;
  2324. }
  2325. host->totalSentData += sentLength;
  2326. currentPeer->totalDataSent += sentLength;
  2327. host->totalSentPackets++;
  2328. }
  2329. }
  2330. return 0;
  2331. }
  2332. void enet_host_flush(ENetHost* host) {
  2333. host->serviceTime = enet_time_get();
  2334. enet_protocol_send_outgoing_commands(host, NULL, 0);
  2335. }
  2336. int enet_host_check_events(ENetHost* host, ENetEvent* event) {
  2337. if (event == NULL)
  2338. return -1;
  2339. event->type = ENET_EVENT_TYPE_NONE;
  2340. event->peer = NULL;
  2341. event->packet = NULL;
  2342. return enet_protocol_dispatch_incoming_commands(host, event);
  2343. }
  2344. int enet_host_service(ENetHost* host, ENetEvent* event, uint32_t timeout) {
  2345. uint32_t waitCondition;
  2346. if (event != NULL) {
  2347. event->type = ENET_EVENT_TYPE_NONE;
  2348. event->peer = NULL;
  2349. event->packet = NULL;
  2350. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2351. case 1:
  2352. return 1;
  2353. case -1:
  2354. ENET_LOG_ERROR("Error dispatching incoming packets!");
  2355. return -1;
  2356. default:
  2357. break;
  2358. }
  2359. }
  2360. host->serviceTime = enet_time_get();
  2361. timeout += host->serviceTime;
  2362. do {
  2363. if (ENET_TIME_DIFFERENCE(host->serviceTime, host->bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  2364. enet_host_bandwidth_throttle(host);
  2365. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2366. case 1:
  2367. return 1;
  2368. case -1:
  2369. ENET_LOG_ERROR("Error sending outgoing packets!");
  2370. return -1;
  2371. default:
  2372. break;
  2373. }
  2374. switch (enet_protocol_receive_incoming_commands(host, event)) {
  2375. case 1:
  2376. return 1;
  2377. case -1:
  2378. ENET_LOG_ERROR("Error receiving incoming packets!");
  2379. return -1;
  2380. default:
  2381. break;
  2382. }
  2383. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2384. case 1:
  2385. return 1;
  2386. case -1:
  2387. ENET_LOG_ERROR("Error dispatching outgoing packets!");
  2388. return -1;
  2389. default:
  2390. break;
  2391. }
  2392. if (event != NULL) {
  2393. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2394. case 1:
  2395. return 1;
  2396. case -1:
  2397. ENET_LOG_ERROR("Error dispatching incoming packets!");
  2398. return -1;
  2399. default:
  2400. break;
  2401. }
  2402. }
  2403. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2404. return 0;
  2405. do {
  2406. host->serviceTime = enet_time_get();
  2407. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2408. return 0;
  2409. waitCondition = ENET_SOCKET_WAIT_RECEIVE | ENET_SOCKET_WAIT_INTERRUPT;
  2410. if (enet_socket_wait(host->socket, &waitCondition, ENET_TIME_DIFFERENCE(timeout, host->serviceTime)) != 0)
  2411. return -1;
  2412. }
  2413. while (waitCondition & ENET_SOCKET_WAIT_INTERRUPT);
  2414. host->serviceTime = enet_time_get();
  2415. }
  2416. while (waitCondition & ENET_SOCKET_WAIT_RECEIVE);
  2417. return 0;
  2418. }
  2419. /*
  2420. =======================================================================
  2421. Peer
  2422. =======================================================================
  2423. */
  2424. void enet_peer_throttle_configure(ENetPeer* peer, uint32_t interval, uint32_t acceleration, uint32_t deceleration, uint32_t threshold) {
  2425. ENetProtocol command;
  2426. peer->packetThrottleThreshold = threshold;
  2427. peer->packetThrottleInterval = interval;
  2428. peer->packetThrottleAcceleration = acceleration;
  2429. peer->packetThrottleDeceleration = deceleration;
  2430. command.header.command = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2431. command.header.channelID = 0xFF;
  2432. command.throttleConfigure.packetThrottleInterval = ENET_HOST_TO_NET_32(interval);
  2433. command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32(acceleration);
  2434. command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32(deceleration);
  2435. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2436. }
  2437. int enet_peer_throttle(ENetPeer* peer, uint32_t rtt) {
  2438. if (peer->lastRoundTripTime <= peer->lastRoundTripTimeVariance) {
  2439. peer->packetThrottle = peer->packetThrottleLimit;
  2440. }
  2441. else if (rtt < peer->lastRoundTripTime) {
  2442. peer->packetThrottle += peer->packetThrottleAcceleration;
  2443. if (peer->packetThrottle > peer->packetThrottleLimit)
  2444. peer->packetThrottle = peer->packetThrottleLimit;
  2445. return 1;
  2446. }
  2447. else if (rtt > peer->lastRoundTripTime + peer->packetThrottleThreshold + 2 * peer->lastRoundTripTimeVariance) {
  2448. if (peer->packetThrottle > peer->packetThrottleDeceleration)
  2449. peer->packetThrottle -= peer->packetThrottleDeceleration;
  2450. else
  2451. peer->packetThrottle = 0;
  2452. return -1;
  2453. }
  2454. return 0;
  2455. }
  2456. int enet_peer_send(ENetPeer* peer, uint8_t channelID, ENetPacket* packet) {
  2457. ENetChannel* channel = &peer->channels[channelID];
  2458. ENetProtocol command;
  2459. size_t fragmentLength;
  2460. if (peer->state != ENET_PEER_STATE_CONNECTED || channelID >= peer->channelCount || packet->dataLength > peer->host->maximumPacketSize) {
  2461. 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");
  2462. return -1;
  2463. }
  2464. fragmentLength = peer->mtu - sizeof(ENetProtocolHeader) - sizeof(ENetProtocolSendFragment);
  2465. if (peer->host->checksumCallback != NULL)
  2466. fragmentLength -= sizeof(uint32_t);
  2467. if (packet->dataLength > fragmentLength) {
  2468. uint32_t fragmentCount = (packet->dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset;
  2469. uint8_t commandNumber;
  2470. uint16_t startSequenceNumber;
  2471. ENetList fragments;
  2472. ENetOutgoingCommand* fragment;
  2473. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) {
  2474. ENET_LOG_ERROR("Cannot send data. Too many fragments (%u vs %u)\n", fragmentCount, ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT);
  2475. return -1;
  2476. }
  2477. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED)) == ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED && channel->outgoingUnreliableSequenceNumber < 0xFFFF) {
  2478. commandNumber = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
  2479. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingUnreliableSequenceNumber + 1);
  2480. }
  2481. else {
  2482. commandNumber = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2483. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingReliableSequenceNumber + 1);
  2484. }
  2485. enet_list_clear(&fragments);
  2486. for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet->dataLength; ++fragmentNumber, fragmentOffset += fragmentLength) {
  2487. if (packet->dataLength - fragmentOffset < fragmentLength)
  2488. fragmentLength = packet->dataLength - fragmentOffset;
  2489. fragment = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2490. if (fragment == NULL) {
  2491. while (!enet_list_empty(&fragments)) {
  2492. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2493. enet_free(fragment);
  2494. }
  2495. ENET_LOG_ERROR("Cannot send data. A fragment was null.");
  2496. return -1;
  2497. }
  2498. fragment->fragmentOffset = fragmentOffset;
  2499. fragment->fragmentLength = fragmentLength;
  2500. fragment->packet = packet;
  2501. fragment->command.header.command = commandNumber;
  2502. fragment->command.header.channelID = channelID;
  2503. fragment->command.sendFragment.startSequenceNumber = startSequenceNumber;
  2504. fragment->command.sendFragment.dataLength = ENET_HOST_TO_NET_16(fragmentLength);
  2505. fragment->command.sendFragment.fragmentCount = ENET_HOST_TO_NET_32(fragmentCount);
  2506. fragment->command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32(fragmentNumber);
  2507. fragment->command.sendFragment.totalLength = ENET_HOST_TO_NET_32(packet->dataLength);
  2508. fragment->command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32(fragmentOffset);
  2509. enet_list_insert(enet_list_end(&fragments), fragment);
  2510. }
  2511. packet->referenceCount += fragmentNumber;
  2512. while (!enet_list_empty(&fragments)) {
  2513. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2514. enet_peer_setup_outgoing_command(peer, fragment);
  2515. }
  2516. return 0;
  2517. }
  2518. command.header.channelID = channelID;
  2519. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) {
  2520. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2521. command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2522. }
  2523. else if (packet->flags & ENET_PACKET_FLAG_RELIABLE || channel->outgoingUnreliableSequenceNumber >= 0xFFFF) {
  2524. command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2525. command.sendReliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2526. }
  2527. else {
  2528. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
  2529. command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2530. }
  2531. if (enet_peer_queue_outgoing_command(peer, &command, packet, 0, packet->dataLength) == NULL) {
  2532. ENET_LOG_ERROR("A queued outgoing command was NULL\n");
  2533. return -1;
  2534. }
  2535. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  2536. enet_host_flush(peer->host);
  2537. return 0;
  2538. }
  2539. ENetPacket* enet_peer_receive(ENetPeer* peer, uint8_t* channelID) {
  2540. ENetIncomingCommand* incomingCommand;
  2541. ENetPacket* packet;
  2542. if (enet_list_empty(&peer->dispatchedCommands))
  2543. return NULL;
  2544. incomingCommand = (ENetIncomingCommand*)enet_list_remove(enet_list_begin(&peer->dispatchedCommands));
  2545. if (channelID != NULL)
  2546. *channelID = incomingCommand->command.header.channelID;
  2547. packet = incomingCommand->packet;
  2548. --packet->referenceCount;
  2549. if (incomingCommand->fragments != NULL)
  2550. enet_free(incomingCommand->fragments);
  2551. enet_free(incomingCommand);
  2552. peer->totalWaitingData -= packet->dataLength;
  2553. return packet;
  2554. }
  2555. static void enet_peer_reset_outgoing_commands(ENetList* queue) {
  2556. ENetOutgoingCommand* outgoingCommand;
  2557. while (!enet_list_empty(queue)) {
  2558. outgoingCommand = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(queue));
  2559. if (outgoingCommand->packet != NULL) {
  2560. --outgoingCommand->packet->referenceCount;
  2561. if (outgoingCommand->packet->referenceCount == 0)
  2562. enet_packet_destroy(outgoingCommand->packet);
  2563. }
  2564. enet_free(outgoingCommand);
  2565. }
  2566. }
  2567. static void enet_peer_remove_incoming_commands(ENetList* queue, ENetListIterator startCommand, ENetListIterator endCommand) {
  2568. ENetListIterator currentCommand;
  2569. for (currentCommand = startCommand; currentCommand != endCommand;) {
  2570. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2571. currentCommand = enet_list_next(currentCommand);
  2572. enet_list_remove(&incomingCommand->incomingCommandList);
  2573. if (incomingCommand->packet != NULL) {
  2574. --incomingCommand->packet->referenceCount;
  2575. if (incomingCommand->packet->referenceCount == 0)
  2576. enet_packet_destroy(incomingCommand->packet);
  2577. }
  2578. if (incomingCommand->fragments != NULL)
  2579. enet_free(incomingCommand->fragments);
  2580. enet_free(incomingCommand);
  2581. }
  2582. }
  2583. static void enet_peer_reset_incoming_commands(ENetList* queue) {
  2584. enet_peer_remove_incoming_commands(queue, enet_list_begin(queue), enet_list_end(queue));
  2585. }
  2586. void enet_peer_reset_queues(ENetPeer* peer) {
  2587. ENetChannel* channel;
  2588. if (peer->needsDispatch) {
  2589. enet_list_remove(&peer->dispatchList);
  2590. peer->needsDispatch = 0;
  2591. }
  2592. while (!enet_list_empty(&peer->acknowledgements)) {
  2593. enet_free(enet_list_remove(enet_list_begin(&peer->acknowledgements)));
  2594. }
  2595. enet_peer_reset_outgoing_commands(&peer->sentReliableCommands);
  2596. enet_peer_reset_outgoing_commands(&peer->sentUnreliableCommands);
  2597. enet_peer_reset_outgoing_commands(&peer->outgoingReliableCommands);
  2598. enet_peer_reset_outgoing_commands(&peer->outgoingUnreliableCommands);
  2599. enet_peer_reset_incoming_commands(&peer->dispatchedCommands);
  2600. if (peer->channels != NULL && peer->channelCount > 0) {
  2601. for (channel = peer->channels; channel < &peer->channels[peer->channelCount]; ++channel) {
  2602. enet_peer_reset_incoming_commands(&channel->incomingReliableCommands);
  2603. enet_peer_reset_incoming_commands(&channel->incomingUnreliableCommands);
  2604. }
  2605. enet_free(peer->channels);
  2606. }
  2607. peer->channels = NULL;
  2608. peer->channelCount = 0;
  2609. }
  2610. void enet_peer_on_connect(ENetPeer* peer) {
  2611. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  2612. if (peer->incomingBandwidth != 0)
  2613. ++peer->host->bandwidthLimitedPeers;
  2614. ++peer->host->connectedPeers;
  2615. }
  2616. }
  2617. void enet_peer_on_disconnect(ENetPeer* peer) {
  2618. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2619. if (peer->incomingBandwidth != 0)
  2620. --peer->host->bandwidthLimitedPeers;
  2621. --peer->host->connectedPeers;
  2622. }
  2623. }
  2624. void enet_peer_reset(ENetPeer* peer) {
  2625. enet_peer_on_disconnect(peer);
  2626. peer->outgoingPeerID = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  2627. peer->state = ENET_PEER_STATE_DISCONNECTED;
  2628. peer->incomingBandwidth = 0;
  2629. peer->outgoingBandwidth = 0;
  2630. peer->incomingBandwidthThrottleEpoch = 0;
  2631. peer->outgoingBandwidthThrottleEpoch = 0;
  2632. peer->incomingDataTotal = 0;
  2633. peer->totalDataReceived = 0;
  2634. peer->outgoingDataTotal = 0;
  2635. peer->totalDataSent = 0;
  2636. peer->lastSendTime = 0;
  2637. peer->lastReceiveTime = 0;
  2638. peer->nextTimeout = 0;
  2639. peer->earliestTimeout = 0;
  2640. peer->packetLossEpoch = 0;
  2641. peer->packetsSent = 0;
  2642. peer->totalPacketsSent = 0;
  2643. peer->packetsLost = 0;
  2644. peer->totalPacketsLost = 0;
  2645. peer->packetLoss = 0;
  2646. peer->packetLossVariance = 0;
  2647. peer->packetThrottle = ENET_PEER_DEFAULT_PACKET_THROTTLE;
  2648. peer->packetThrottleThreshold = ENET_PEER_PACKET_THROTTLE_THRESHOLD;
  2649. peer->packetThrottleLimit = ENET_PEER_PACKET_THROTTLE_SCALE;
  2650. peer->packetThrottleCounter = 0;
  2651. peer->packetThrottleEpoch = 0;
  2652. peer->packetThrottleAcceleration = ENET_PEER_PACKET_THROTTLE_ACCELERATION;
  2653. peer->packetThrottleDeceleration = ENET_PEER_PACKET_THROTTLE_DECELERATION;
  2654. peer->packetThrottleInterval = ENET_PEER_PACKET_THROTTLE_INTERVAL;
  2655. peer->pingInterval = ENET_PEER_PING_INTERVAL;
  2656. peer->timeoutLimit = ENET_PEER_TIMEOUT_LIMIT;
  2657. peer->timeoutMinimum = ENET_PEER_TIMEOUT_MINIMUM;
  2658. peer->timeoutMaximum = ENET_PEER_TIMEOUT_MAXIMUM;
  2659. peer->lastRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2660. peer->lowestRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2661. peer->lastRoundTripTimeVariance = 0;
  2662. peer->highestRoundTripTimeVariance = 0;
  2663. peer->roundTripTime = 1;
  2664. peer->roundTripTimeVariance = 0;
  2665. peer->mtu = peer->host->mtu;
  2666. peer->reliableDataInTransit = 0;
  2667. peer->outgoingReliableSequenceNumber = 0;
  2668. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2669. peer->incomingUnsequencedGroup = 0;
  2670. peer->outgoingUnsequencedGroup = 0;
  2671. peer->eventData = 0;
  2672. peer->totalWaitingData = 0;
  2673. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  2674. enet_peer_reset_queues(peer);
  2675. }
  2676. void enet_peer_ping(ENetPeer* peer) {
  2677. ENetProtocol command;
  2678. if (peer->state != ENET_PEER_STATE_CONNECTED)
  2679. return;
  2680. command.header.command = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2681. command.header.channelID = 0xFF;
  2682. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2683. }
  2684. void enet_peer_ping_interval(ENetPeer* peer, uint32_t pingInterval) {
  2685. peer->pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL;
  2686. }
  2687. void enet_peer_timeout(ENetPeer* peer, uint32_t timeoutLimit, uint32_t timeoutMinimum, uint32_t timeoutMaximum) {
  2688. peer->timeoutLimit = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT;
  2689. peer->timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM;
  2690. peer->timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM;
  2691. }
  2692. void enet_peer_disconnect_now(ENetPeer* peer, uint32_t data) {
  2693. ENetProtocol command;
  2694. if (peer->state == ENET_PEER_STATE_DISCONNECTED)
  2695. return;
  2696. if (peer->state != ENET_PEER_STATE_ZOMBIE && peer->state != ENET_PEER_STATE_DISCONNECTING) {
  2697. enet_peer_reset_queues(peer);
  2698. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2699. command.header.channelID = 0xFF;
  2700. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2701. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2702. enet_host_flush(peer->host);
  2703. }
  2704. enet_peer_reset(peer);
  2705. }
  2706. void enet_peer_disconnect(ENetPeer* peer, uint32_t data) {
  2707. ENetProtocol command;
  2708. 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)
  2709. return;
  2710. enet_peer_reset_queues(peer);
  2711. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT;
  2712. command.header.channelID = 0xFF;
  2713. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2714. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2715. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2716. else
  2717. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2718. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2719. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2720. enet_peer_on_disconnect(peer);
  2721. peer->state = ENET_PEER_STATE_DISCONNECTING;
  2722. }
  2723. else {
  2724. enet_host_flush(peer->host);
  2725. enet_peer_reset(peer);
  2726. }
  2727. }
  2728. void enet_peer_disconnect_later(ENetPeer* peer, uint32_t data) {
  2729. 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))) {
  2730. peer->state = ENET_PEER_STATE_DISCONNECT_LATER;
  2731. peer->eventData = data;
  2732. }
  2733. else {
  2734. enet_peer_disconnect(peer, data);
  2735. }
  2736. }
  2737. ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer* peer, const ENetProtocol* command, uint16_t sentTime) {
  2738. ENetAcknowledgement* acknowledgement;
  2739. if (command->header.channelID < peer->channelCount) {
  2740. ENetChannel* channel = &peer->channels[command->header.channelID];
  2741. uint16_t reliableWindow = command->header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2742. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2743. if (command->header.reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2744. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2745. if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS)
  2746. return NULL;
  2747. }
  2748. acknowledgement = (ENetAcknowledgement*)enet_malloc(sizeof(ENetAcknowledgement));
  2749. if (acknowledgement == NULL)
  2750. return NULL;
  2751. peer->outgoingDataTotal += sizeof(ENetProtocolAcknowledge);
  2752. acknowledgement->sentTime = sentTime;
  2753. acknowledgement->command = *command;
  2754. enet_list_insert(enet_list_end(&peer->acknowledgements), acknowledgement);
  2755. return acknowledgement;
  2756. }
  2757. void enet_peer_setup_outgoing_command(ENetPeer* peer, ENetOutgoingCommand* outgoingCommand) {
  2758. ENetChannel* channel = &peer->channels[outgoingCommand->command.header.channelID];
  2759. peer->outgoingDataTotal += enet_protocol_command_size(outgoingCommand->command.header.command) + outgoingCommand->fragmentLength;
  2760. if (outgoingCommand->command.header.channelID == 0xFF) {
  2761. ++peer->outgoingReliableSequenceNumber;
  2762. outgoingCommand->reliableSequenceNumber = peer->outgoingReliableSequenceNumber;
  2763. outgoingCommand->unreliableSequenceNumber = 0;
  2764. }
  2765. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  2766. ++channel->outgoingReliableSequenceNumber;
  2767. channel->outgoingUnreliableSequenceNumber = 0;
  2768. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2769. outgoingCommand->unreliableSequenceNumber = 0;
  2770. }
  2771. else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) {
  2772. ++peer->outgoingUnsequencedGroup;
  2773. outgoingCommand->reliableSequenceNumber = 0;
  2774. outgoingCommand->unreliableSequenceNumber = 0;
  2775. }
  2776. else {
  2777. if (outgoingCommand->fragmentOffset == 0)
  2778. ++channel->outgoingUnreliableSequenceNumber;
  2779. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2780. outgoingCommand->unreliableSequenceNumber = channel->outgoingUnreliableSequenceNumber;
  2781. }
  2782. outgoingCommand->sendAttempts = 0;
  2783. outgoingCommand->sentTime = 0;
  2784. outgoingCommand->roundTripTimeout = 0;
  2785. outgoingCommand->roundTripTimeoutLimit = 0;
  2786. outgoingCommand->command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->reliableSequenceNumber);
  2787. switch (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2788. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2789. outgoingCommand->command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->unreliableSequenceNumber);
  2790. break;
  2791. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2792. outgoingCommand->command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16(peer->outgoingUnsequencedGroup);
  2793. break;
  2794. default:
  2795. break;
  2796. }
  2797. if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)
  2798. enet_list_insert(enet_list_end(&peer->outgoingReliableCommands), outgoingCommand);
  2799. else
  2800. enet_list_insert(enet_list_end(&peer->outgoingUnreliableCommands), outgoingCommand);
  2801. }
  2802. ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer* peer, const ENetProtocol* command, ENetPacket* packet, uint32_t offset, uint16_t length) {
  2803. ENetOutgoingCommand* outgoingCommand = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2804. if (outgoingCommand == NULL)
  2805. return NULL;
  2806. outgoingCommand->command = *command;
  2807. outgoingCommand->fragmentOffset = offset;
  2808. outgoingCommand->fragmentLength = length;
  2809. outgoingCommand->packet = packet;
  2810. if (packet != NULL)
  2811. ++packet->referenceCount;
  2812. enet_peer_setup_outgoing_command(peer, outgoingCommand);
  2813. return outgoingCommand;
  2814. }
  2815. void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer* peer, ENetChannel* channel) {
  2816. ENetListIterator droppedCommand, startCommand, currentCommand;
  2817. for (droppedCommand = startCommand = currentCommand = enet_list_begin(&channel->incomingUnreliableCommands); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2818. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2819. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2820. continue;
  2821. if (incomingCommand->reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
  2822. if (incomingCommand->fragmentsRemaining <= 0) {
  2823. channel->incomingUnreliableSequenceNumber = incomingCommand->unreliableSequenceNumber;
  2824. continue;
  2825. }
  2826. if (startCommand != currentCommand) {
  2827. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2828. if (!peer->needsDispatch) {
  2829. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2830. peer->needsDispatch = 1;
  2831. }
  2832. droppedCommand = currentCommand;
  2833. }
  2834. else if (droppedCommand != currentCommand) {
  2835. droppedCommand = enet_list_previous(currentCommand);
  2836. }
  2837. }
  2838. else {
  2839. uint16_t reliableWindow = incomingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2840. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2841. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2842. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2843. if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2844. break;
  2845. droppedCommand = enet_list_next(currentCommand);
  2846. if (startCommand != currentCommand) {
  2847. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2848. if (!peer->needsDispatch) {
  2849. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2850. peer->needsDispatch = 1;
  2851. }
  2852. }
  2853. }
  2854. startCommand = enet_list_next(currentCommand);
  2855. }
  2856. if (startCommand != currentCommand) {
  2857. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2858. if (!peer->needsDispatch) {
  2859. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2860. peer->needsDispatch = 1;
  2861. }
  2862. droppedCommand = currentCommand;
  2863. }
  2864. enet_peer_remove_incoming_commands(&channel->incomingUnreliableCommands, enet_list_begin(&channel->incomingUnreliableCommands), droppedCommand);
  2865. }
  2866. void enet_peer_dispatch_incoming_reliable_commands(ENetPeer* peer, ENetChannel* channel) {
  2867. ENetListIterator currentCommand;
  2868. for (currentCommand = enet_list_begin(&channel->incomingReliableCommands); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2869. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2870. if (incomingCommand->fragmentsRemaining > 0 || incomingCommand->reliableSequenceNumber != (uint16_t)(channel->incomingReliableSequenceNumber + 1))
  2871. break;
  2872. channel->incomingReliableSequenceNumber = incomingCommand->reliableSequenceNumber;
  2873. if (incomingCommand->fragmentCount > 0)
  2874. channel->incomingReliableSequenceNumber += incomingCommand->fragmentCount - 1;
  2875. }
  2876. if (currentCommand == enet_list_begin(&channel->incomingReliableCommands))
  2877. return;
  2878. channel->incomingUnreliableSequenceNumber = 0;
  2879. enet_list_move(enet_list_end(&peer->dispatchedCommands), enet_list_begin(&channel->incomingReliableCommands), enet_list_previous(currentCommand));
  2880. if (!peer->needsDispatch) {
  2881. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2882. peer->needsDispatch = 1;
  2883. }
  2884. if (!enet_list_empty(&channel->incomingUnreliableCommands))
  2885. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  2886. }
  2887. ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer* peer, const ENetProtocol* command, const void* data, size_t dataLength, uint32_t flags, uint32_t fragmentCount) {
  2888. static ENetIncomingCommand dummyCommand;
  2889. ENetChannel* channel = &peer->channels[command->header.channelID];
  2890. uint32_t unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
  2891. uint16_t reliableWindow, currentWindow;
  2892. ENetIncomingCommand* incomingCommand;
  2893. ENetListIterator currentCommand;
  2894. ENetPacket* packet = NULL;
  2895. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2896. goto discardCommand;
  2897. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  2898. reliableSequenceNumber = command->header.reliableSequenceNumber;
  2899. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2900. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2901. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2902. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2903. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2904. goto discardCommand;
  2905. }
  2906. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2907. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2908. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2909. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber)
  2910. goto discardCommand;
  2911. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2912. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2913. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2914. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2915. continue;
  2916. }
  2917. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2918. break;
  2919. }
  2920. if (incomingCommand->reliableSequenceNumber <= reliableSequenceNumber) {
  2921. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2922. break;
  2923. goto discardCommand;
  2924. }
  2925. }
  2926. break;
  2927. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2928. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  2929. unreliableSequenceNumber = ENET_NET_TO_HOST_16(command->sendUnreliable.unreliableSequenceNumber);
  2930. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && unreliableSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  2931. goto discardCommand;
  2932. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2933. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2934. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2935. continue;
  2936. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2937. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2938. continue;
  2939. }
  2940. else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2941. break;
  2942. }
  2943. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2944. break;
  2945. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  2946. continue;
  2947. if (incomingCommand->unreliableSequenceNumber <= unreliableSequenceNumber) {
  2948. if (incomingCommand->unreliableSequenceNumber < unreliableSequenceNumber)
  2949. break;
  2950. goto discardCommand;
  2951. }
  2952. }
  2953. break;
  2954. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2955. currentCommand = enet_list_end(&channel->incomingUnreliableCommands);
  2956. break;
  2957. default:
  2958. goto discardCommand;
  2959. }
  2960. if (peer->totalWaitingData >= peer->host->maximumWaitingData)
  2961. goto notifyError;
  2962. packet = enet_packet_create(data, dataLength, flags);
  2963. if (packet == NULL)
  2964. goto notifyError;
  2965. incomingCommand = (ENetIncomingCommand*)enet_malloc(sizeof(ENetIncomingCommand));
  2966. if (incomingCommand == NULL)
  2967. goto notifyError;
  2968. incomingCommand->reliableSequenceNumber = command->header.reliableSequenceNumber;
  2969. incomingCommand->unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF;
  2970. incomingCommand->command = *command;
  2971. incomingCommand->fragmentCount = fragmentCount;
  2972. incomingCommand->fragmentsRemaining = fragmentCount;
  2973. incomingCommand->packet = packet;
  2974. incomingCommand->fragments = NULL;
  2975. if (fragmentCount > 0) {
  2976. if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
  2977. incomingCommand->fragments = (uint32_t*)enet_malloc((fragmentCount + 31) / 32 * sizeof(uint32_t));
  2978. if (incomingCommand->fragments == NULL) {
  2979. enet_free(incomingCommand);
  2980. goto notifyError;
  2981. }
  2982. memset(incomingCommand->fragments, 0, (fragmentCount + 31) / 32 * sizeof(uint32_t));
  2983. }
  2984. if (packet != NULL) {
  2985. ++packet->referenceCount;
  2986. peer->totalWaitingData += packet->dataLength;
  2987. }
  2988. enet_list_insert(enet_list_next(currentCommand), incomingCommand);
  2989. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2990. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2991. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2992. enet_peer_dispatch_incoming_reliable_commands(peer, channel);
  2993. break;
  2994. default:
  2995. enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
  2996. break;
  2997. }
  2998. return incomingCommand;
  2999. discardCommand:
  3000. if (fragmentCount > 0)
  3001. goto notifyError;
  3002. if (packet != NULL && packet->referenceCount == 0)
  3003. enet_packet_destroy(packet);
  3004. return &dummyCommand;
  3005. notifyError:
  3006. if (packet != NULL && packet->referenceCount == 0)
  3007. enet_packet_destroy(packet);
  3008. return NULL;
  3009. }
  3010. /*
  3011. =======================================================================
  3012. Host
  3013. =======================================================================
  3014. */
  3015. ENetHost* enet_host_create(const ENetAddress* address, size_t peerCount, size_t channelLimit, uint32_t incomingBandwidth, uint32_t outgoingBandwidth, int bufferSize) {
  3016. ENET_LOG_TRACE("ENET Host being created.");
  3017. ENetHost* host;
  3018. ENetPeer* currentPeer;
  3019. if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  3020. ENET_LOG_ERROR("peer count greater than %u", ENET_PROTOCOL_MAXIMUM_PEER_ID);
  3021. return NULL;
  3022. }
  3023. host = (ENetHost*)enet_malloc(sizeof(ENetHost));
  3024. if (host == NULL) {
  3025. ENET_LOG_ERROR("host malloc failure; wanted %u bytes", sizeof(ENetHost));
  3026. return NULL;
  3027. }
  3028. memset(host, 0, sizeof(ENetHost));
  3029. host->peers = (ENetPeer*)enet_malloc(peerCount * sizeof(ENetPeer));
  3030. if (host->peers == NULL) {
  3031. ENET_LOG_ERROR("host peer malloc failure; wanted %u bytes", peerCount * sizeof(ENetPeer));
  3032. enet_free(host);
  3033. return NULL;
  3034. }
  3035. memset(host->peers, 0, peerCount * sizeof(ENetPeer));
  3036. host->socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
  3037. if (host->socket != ENET_SOCKET_NULL) {
  3038. ENET_LOG_TRACE("Switching socket to IPv6 version 6 only mode");
  3039. enet_socket_set_option(host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
  3040. }
  3041. int socketBindResult = enet_socket_bind(host->socket, address);
  3042. if (host->socket == ENET_SOCKET_NULL || (address != NULL && socketBindResult < 0)) {
  3043. if (host->socket != ENET_SOCKET_NULL) {
  3044. ENET_LOG_TRACE("Destroying old socket");
  3045. enet_socket_destroy(host->socket);
  3046. }
  3047. ENET_LOG_ERROR("Bind socket failed; error code %i", socketBindResult);
  3048. enet_free(host->peers);
  3049. enet_free(host);
  3050. return NULL;
  3051. }
  3052. ENET_LOG_TRACE("START: Buffer Setup");
  3053. if (bufferSize > ENET_HOST_BUFFER_SIZE_MAX)
  3054. bufferSize = ENET_HOST_BUFFER_SIZE_MAX;
  3055. else if (bufferSize < ENET_HOST_BUFFER_SIZE_MIN)
  3056. bufferSize = ENET_HOST_BUFFER_SIZE_MIN;
  3057. ENET_LOG_TRACE("START: Setup socket options");
  3058. enet_socket_set_option(host->socket, ENET_SOCKOPT_NONBLOCK, 1);
  3059. enet_socket_set_option(host->socket, ENET_SOCKOPT_BROADCAST, 1);
  3060. enet_socket_set_option(host->socket, ENET_SOCKOPT_RCVBUF, bufferSize);
  3061. enet_socket_set_option(host->socket, ENET_SOCKOPT_SNDBUF, bufferSize);
  3062. ENET_LOG_TRACE("START: Address Setup");
  3063. if (address != NULL && enet_socket_get_address(host->socket, &host->address) < 0)
  3064. host->address = *address;
  3065. ENET_LOG_TRACE("START: Channels Setup");
  3066. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3067. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3068. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3069. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3070. host->randomSeed = (uint32_t)(size_t)host;
  3071. host->randomSeed += enet_host_random_seed();
  3072. host->randomSeed = (host->randomSeed << 16) | (host->randomSeed >> 16);
  3073. host->channelLimit = channelLimit;
  3074. host->incomingBandwidth = incomingBandwidth;
  3075. host->outgoingBandwidth = outgoingBandwidth;
  3076. host->bandwidthThrottleEpoch = 0;
  3077. host->recalculateBandwidthLimits = 0;
  3078. host->preventConnections = 0;
  3079. host->mtu = ENET_HOST_DEFAULT_MTU;
  3080. host->peerCount = peerCount;
  3081. host->commandCount = 0;
  3082. host->bufferCount = 0;
  3083. host->checksumCallback = NULL;
  3084. host->receivedAddress.ipv6 = ENET_HOST_ANY;
  3085. host->receivedAddress.port = 0;
  3086. host->receivedData = NULL;
  3087. host->receivedDataLength = 0;
  3088. host->totalSentData = 0;
  3089. host->totalSentPackets = 0;
  3090. host->totalReceivedData = 0;
  3091. host->totalReceivedPackets = 0;
  3092. host->connectedPeers = 0;
  3093. host->bandwidthLimitedPeers = 0;
  3094. host->duplicatePeers = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  3095. host->maximumPacketSize = ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE;
  3096. host->maximumWaitingData = ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA;
  3097. host->interceptCallback = NULL;
  3098. ENET_LOG_TRACE("Clearing dispatch queue");
  3099. enet_list_clear(&host->dispatchQueue);
  3100. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3101. currentPeer->host = host;
  3102. currentPeer->incomingPeerID = currentPeer - host->peers;
  3103. currentPeer->outgoingSessionID = currentPeer->incomingSessionID = 0xFF;
  3104. currentPeer->data = NULL;
  3105. enet_list_clear(&currentPeer->acknowledgements);
  3106. enet_list_clear(&currentPeer->sentReliableCommands);
  3107. enet_list_clear(&currentPeer->sentUnreliableCommands);
  3108. enet_list_clear(&currentPeer->outgoingReliableCommands);
  3109. enet_list_clear(&currentPeer->outgoingUnreliableCommands);
  3110. enet_list_clear(&currentPeer->dispatchedCommands);
  3111. enet_peer_reset(currentPeer);
  3112. }
  3113. ENET_LOG_TRACE("SHOWTIME: Host created successfully.");
  3114. return host;
  3115. }
  3116. void enet_host_destroy(ENetHost* host) {
  3117. ENET_LOG_TRACE("ENET Host being destroyed.");
  3118. ENetPeer* currentPeer;
  3119. if (host == NULL)
  3120. return;
  3121. enet_socket_destroy(host->socket);
  3122. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3123. enet_peer_reset(currentPeer);
  3124. }
  3125. enet_free(host->peers);
  3126. enet_free(host);
  3127. }
  3128. void enet_host_prevent_connections(ENetHost* host, uint8_t state) {
  3129. if (host == NULL)
  3130. return;
  3131. host->preventConnections = state;
  3132. }
  3133. ENetPeer* enet_host_connect(ENetHost* host, const ENetAddress* address, size_t channelCount, uint32_t data) {
  3134. ENET_LOG_TRACE("Connection to host going up");
  3135. ENetPeer* currentPeer;
  3136. ENetChannel* channel;
  3137. ENetProtocol command;
  3138. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3139. channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3140. else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3141. channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3142. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3143. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED)
  3144. break;
  3145. }
  3146. if (currentPeer >= &host->peers[host->peerCount])
  3147. return NULL;
  3148. currentPeer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  3149. if (currentPeer->channels == NULL)
  3150. return NULL;
  3151. currentPeer->channelCount = channelCount;
  3152. currentPeer->state = ENET_PEER_STATE_CONNECTING;
  3153. currentPeer->address = *address;
  3154. currentPeer->connectID = ++host->randomSeed;
  3155. if (host->outgoingBandwidth == 0)
  3156. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3157. else
  3158. currentPeer->windowSize = (host->outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3159. if (currentPeer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  3160. currentPeer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  3161. else if (currentPeer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  3162. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  3163. for (channel = currentPeer->channels; channel < &currentPeer->channels[channelCount]; ++channel) {
  3164. channel->outgoingReliableSequenceNumber = 0;
  3165. channel->outgoingUnreliableSequenceNumber = 0;
  3166. channel->incomingReliableSequenceNumber = 0;
  3167. channel->incomingUnreliableSequenceNumber = 0;
  3168. enet_list_clear(&channel->incomingReliableCommands);
  3169. enet_list_clear(&channel->incomingUnreliableCommands);
  3170. channel->usedReliableWindows = 0;
  3171. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  3172. }
  3173. command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3174. command.header.channelID = 0xFF;
  3175. command.connect.outgoingPeerID = ENET_HOST_TO_NET_16(currentPeer->incomingPeerID);
  3176. command.connect.incomingSessionID = currentPeer->incomingSessionID;
  3177. command.connect.outgoingSessionID = currentPeer->outgoingSessionID;
  3178. command.connect.mtu = ENET_HOST_TO_NET_32(currentPeer->mtu);
  3179. command.connect.windowSize = ENET_HOST_TO_NET_32(currentPeer->windowSize);
  3180. command.connect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  3181. command.connect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  3182. command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3183. command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32(currentPeer->packetThrottleInterval);
  3184. command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleAcceleration);
  3185. command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleDeceleration);
  3186. command.connect.connectID = currentPeer->connectID;
  3187. command.connect.data = ENET_HOST_TO_NET_32(data);
  3188. enet_peer_queue_outgoing_command(currentPeer, &command, NULL, 0, 0);
  3189. return currentPeer;
  3190. }
  3191. void enet_host_broadcast(ENetHost* host, uint8_t channelID, ENetPacket* packet) {
  3192. ENetPeer* currentPeer;
  3193. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3194. ++packet->referenceCount;
  3195. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3196. if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
  3197. continue;
  3198. enet_peer_send(currentPeer, channelID, packet);
  3199. }
  3200. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3201. --packet->referenceCount;
  3202. if (packet->referenceCount == 0)
  3203. enet_packet_destroy(packet);
  3204. }
  3205. void enet_host_broadcast_exclude(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer* excludedPeer) {
  3206. ENetPeer* currentPeer;
  3207. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3208. ++packet->referenceCount;
  3209. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3210. if (currentPeer->state != ENET_PEER_STATE_CONNECTED || currentPeer == excludedPeer)
  3211. continue;
  3212. enet_peer_send(currentPeer, channelID, packet);
  3213. }
  3214. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3215. --packet->referenceCount;
  3216. if (packet->referenceCount == 0)
  3217. enet_packet_destroy(packet);
  3218. }
  3219. void enet_host_broadcast_selective(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer** peers, size_t length) {
  3220. ENetPeer* currentPeer;
  3221. size_t i;
  3222. if (host == NULL)
  3223. return;
  3224. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3225. ++packet->referenceCount;
  3226. for (i = 0; i < length; i++) {
  3227. currentPeer = peers[i];
  3228. if (currentPeer == NULL || currentPeer->state != ENET_PEER_STATE_CONNECTED)
  3229. continue;
  3230. enet_peer_send(currentPeer, channelID, packet);
  3231. }
  3232. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3233. --packet->referenceCount;
  3234. if (packet->referenceCount == 0)
  3235. enet_packet_destroy(packet);
  3236. }
  3237. void enet_host_channel_limit(ENetHost* host, size_t channelLimit) {
  3238. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3239. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3240. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3241. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3242. host->channelLimit = channelLimit;
  3243. }
  3244. void enet_host_bandwidth_limit(ENetHost* host, uint32_t incomingBandwidth, uint32_t outgoingBandwidth) {
  3245. host->incomingBandwidth = incomingBandwidth;
  3246. host->outgoingBandwidth = outgoingBandwidth;
  3247. host->recalculateBandwidthLimits = 1;
  3248. }
  3249. void enet_host_bandwidth_throttle(ENetHost* host) {
  3250. uint32_t timeCurrent = enet_time_get();
  3251. uint32_t elapsedTime = timeCurrent - host->bandwidthThrottleEpoch;
  3252. uint32_t peersRemaining = (uint32_t)host->connectedPeers;
  3253. uint32_t dataTotal = ~0;
  3254. uint32_t bandwidth = ~0;
  3255. uint32_t throttle = 0;
  3256. uint32_t bandwidthLimit = 0;
  3257. int needsAdjustment = host->bandwidthLimitedPeers > 0 ? 1 : 0;
  3258. ENetPeer* peer;
  3259. ENetProtocol command;
  3260. if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  3261. return;
  3262. if (host->outgoingBandwidth == 0 && host->incomingBandwidth == 0)
  3263. return;
  3264. host->bandwidthThrottleEpoch = timeCurrent;
  3265. if (peersRemaining == 0)
  3266. return;
  3267. if (host->outgoingBandwidth != 0) {
  3268. dataTotal = 0;
  3269. bandwidth = (host->outgoingBandwidth * elapsedTime) / 1000;
  3270. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3271. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3272. continue;
  3273. dataTotal += peer->outgoingDataTotal;
  3274. }
  3275. }
  3276. while (peersRemaining > 0 && needsAdjustment != 0) {
  3277. needsAdjustment = 0;
  3278. if (dataTotal <= bandwidth)
  3279. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3280. else
  3281. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3282. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3283. uint32_t peerBandwidth;
  3284. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidth == 0 || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3285. continue;
  3286. peerBandwidth = (peer->incomingBandwidth * elapsedTime) / 1000;
  3287. if ((throttle * peer->outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
  3288. continue;
  3289. peer->packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer->outgoingDataTotal;
  3290. if (peer->packetThrottleLimit == 0)
  3291. peer->packetThrottleLimit = 1;
  3292. if (peer->packetThrottle > peer->packetThrottleLimit)
  3293. peer->packetThrottle = peer->packetThrottleLimit;
  3294. peer->outgoingBandwidthThrottleEpoch = timeCurrent;
  3295. peer->incomingDataTotal = 0;
  3296. peer->outgoingDataTotal = 0;
  3297. needsAdjustment = 1;
  3298. --peersRemaining;
  3299. bandwidth -= peerBandwidth;
  3300. dataTotal -= peerBandwidth;
  3301. }
  3302. }
  3303. if (peersRemaining > 0) {
  3304. if (dataTotal <= bandwidth)
  3305. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3306. else
  3307. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3308. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3309. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3310. continue;
  3311. peer->packetThrottleLimit = throttle;
  3312. if (peer->packetThrottle > peer->packetThrottleLimit)
  3313. peer->packetThrottle = peer->packetThrottleLimit;
  3314. peer->incomingDataTotal = 0;
  3315. peer->outgoingDataTotal = 0;
  3316. }
  3317. }
  3318. if (host->recalculateBandwidthLimits) {
  3319. host->recalculateBandwidthLimits = 0;
  3320. peersRemaining = (uint32_t)host->connectedPeers;
  3321. bandwidth = host->incomingBandwidth;
  3322. needsAdjustment = 1;
  3323. if (bandwidth == 0) {
  3324. bandwidthLimit = 0;
  3325. }
  3326. else {
  3327. while (peersRemaining > 0 && needsAdjustment != 0) {
  3328. needsAdjustment = 0;
  3329. bandwidthLimit = bandwidth / peersRemaining;
  3330. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3331. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3332. continue;
  3333. if (peer->outgoingBandwidth > 0 && peer->outgoingBandwidth >= bandwidthLimit)
  3334. continue;
  3335. peer->incomingBandwidthThrottleEpoch = timeCurrent;
  3336. needsAdjustment = 1;
  3337. --peersRemaining;
  3338. bandwidth -= peer->outgoingBandwidth;
  3339. }
  3340. }
  3341. }
  3342. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3343. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3344. continue;
  3345. command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3346. command.header.channelID = 0xFF;
  3347. command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3348. if (peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3349. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(peer->outgoingBandwidth);
  3350. else
  3351. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(bandwidthLimit);
  3352. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3353. }
  3354. }
  3355. }
  3356. /*
  3357. =======================================================================
  3358. Address
  3359. =======================================================================
  3360. */
  3361. int enet_address_set_ip(ENetAddress* address, const char* ip) {
  3362. int type = AF_INET6;
  3363. void* destination = &address->ipv6;
  3364. if (strchr(ip, ':') == NULL) {
  3365. type = AF_INET;
  3366. memset(address, 0, sizeof(address->ipv4.zeros));
  3367. address->ipv4.ffff = 0xFFFF;
  3368. destination = &address->ipv4.ip;
  3369. }
  3370. if (!inet_pton(type, ip, destination)) {
  3371. ENET_LOG_ERROR("Error returned from inet_pton");
  3372. return -1;
  3373. }
  3374. return 0;
  3375. }
  3376. int enet_address_set_hostname(ENetAddress* address, const char* name) {
  3377. struct addrinfo hints, * resultList = NULL, * result = NULL;
  3378. memset(&hints, 0, sizeof(hints));
  3379. hints.ai_family = AF_UNSPEC;
  3380. if (getaddrinfo(name, NULL, &hints, &resultList) != 0) {
  3381. ENET_LOG_ERROR("Error returned from getaddrinfo");
  3382. return -1;
  3383. }
  3384. for (result = resultList; result != NULL; result = result->ai_next) {
  3385. if (result->ai_addr != NULL && result->ai_addrlen >= sizeof(struct sockaddr_in)) {
  3386. if (result->ai_family == AF_INET) {
  3387. struct sockaddr_in* sin = (struct sockaddr_in*)result->ai_addr;
  3388. memset(address, 0, sizeof(address->ipv4.zeros));
  3389. address->ipv4.ffff = 0xFFFF;
  3390. address->ipv4.ip.s_addr = sin->sin_addr.s_addr;
  3391. freeaddrinfo(resultList);
  3392. return 0;
  3393. }
  3394. else if (result->ai_family == AF_INET6) {
  3395. struct sockaddr_in6* sin = (struct sockaddr_in6*)result->ai_addr;
  3396. address->ipv6 = sin->sin6_addr;
  3397. freeaddrinfo(resultList);
  3398. return 0;
  3399. }
  3400. }
  3401. }
  3402. if (resultList != NULL)
  3403. freeaddrinfo(resultList);
  3404. return enet_address_set_ip(address, name);
  3405. }
  3406. int enet_address_get_ip(const ENetAddress* address, char* ip, size_t ipLength) {
  3407. if (address->ipv4.ffff == 0xFFFF && enet_array_is_zeroed(address->ipv4.zeros, sizeof(address->ipv4.zeros)) == 0) {
  3408. if (inet_ntop(AF_INET, &address->ipv4.ip, ip, ipLength) == NULL) {
  3409. ENET_LOG_ERROR("Error returned from inet_pton: NULL");
  3410. return -1;
  3411. }
  3412. }
  3413. else if (inet_ntop(AF_INET6, &address->ipv6, ip, ipLength) == NULL) {
  3414. ENET_LOG_ERROR("Error returned from inet_pton: NULL");
  3415. return -1;
  3416. }
  3417. return 0;
  3418. }
  3419. int enet_address_get_hostname(const ENetAddress* address, char* name, size_t nameLength) {
  3420. struct sockaddr_in6 sin;
  3421. int err;
  3422. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3423. sin.sin6_family = AF_INET6;
  3424. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3425. sin.sin6_addr = address->ipv6;
  3426. err = getnameinfo((struct sockaddr*) & sin, sizeof(sin), name, nameLength, NULL, 0, NI_NAMEREQD);
  3427. if (!err) {
  3428. if (name != NULL && nameLength > 0 && !memchr(name, '\0', nameLength))
  3429. return -1;
  3430. return 0;
  3431. }
  3432. if (err != EAI_NONAME) {
  3433. ENET_LOG_ERROR("getnameinfo error occurred: %i", err);
  3434. return -1;
  3435. }
  3436. return enet_address_get_ip(address, name, nameLength);
  3437. }
  3438. /*
  3439. =======================================================================
  3440. Platform-specific (Unix)
  3441. =======================================================================
  3442. */
  3443. #ifndef _WIN32
  3444. int enet_initialize(void) {
  3445. return 0;
  3446. }
  3447. void enet_deinitialize(void) { }
  3448. uint64_t enet_host_random_seed(void) {
  3449. struct timeval timeVal;
  3450. gettimeofday(&timeVal, NULL);
  3451. return (timeVal.tv_sec * 1000) ^ (timeVal.tv_usec / 1000);
  3452. }
  3453. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3454. struct sockaddr_in6 sin;
  3455. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3456. sin.sin6_family = AF_INET6;
  3457. if (address != NULL) {
  3458. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3459. sin.sin6_addr = address->ipv6;
  3460. }
  3461. else {
  3462. sin.sin6_port = 0;
  3463. sin.sin6_addr = ENET_HOST_ANY;
  3464. }
  3465. return bind(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3466. }
  3467. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3468. struct sockaddr_storage ss;
  3469. socklen_t saLength = sizeof(ss);
  3470. if (getsockname(socket, (struct sockaddr*) & ss, &saLength) == -1) {
  3471. ENET_LOG_ERROR("getsockname failure");
  3472. return -1;
  3473. }
  3474. if (ss.ss_family == AF_INET) {
  3475. struct sockaddr_in* sin = (struct sockaddr_in*) & ss;
  3476. memset(address, 0, sizeof(address->ipv4.zeros));
  3477. address->ipv4.ffff = 0xFFFF;
  3478. address->ipv4.ip = sin->sin_addr;
  3479. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3480. }
  3481. else if (ss.ss_family == AF_INET6) {
  3482. struct sockaddr_in6* sin = (struct sockaddr_in6*) & ss;
  3483. address->ipv6 = sin->sin6_addr;
  3484. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3485. }
  3486. return 0;
  3487. }
  3488. int enet_socket_listen(ENetSocket socket, int backlog) {
  3489. return listen(socket, backlog < 0 ? SOMAXCONN : backlog);
  3490. }
  3491. ENetSocket enet_socket_create(ENetSocketType type) {
  3492. int socketType = (type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM);
  3493. #ifdef SOCK_CLOEXEC
  3494. socketType |= SOCK_CLOEXEC;
  3495. #endif
  3496. return socket(PF_INET6, socketType, 0);
  3497. }
  3498. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3499. int result = -1;
  3500. switch (option) {
  3501. case ENET_SOCKOPT_NONBLOCK:
  3502. result = fcntl(socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl(socket, F_GETFL) & ~O_NONBLOCK));
  3503. break;
  3504. case ENET_SOCKOPT_BROADCAST:
  3505. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3506. break;
  3507. case ENET_SOCKOPT_REUSEADDR:
  3508. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3509. break;
  3510. case ENET_SOCKOPT_RCVBUF:
  3511. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3512. break;
  3513. case ENET_SOCKOPT_SNDBUF:
  3514. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3515. break;
  3516. case ENET_SOCKOPT_RCVTIMEO: {
  3517. struct timeval timeVal;
  3518. timeVal.tv_sec = value / 1000;
  3519. timeVal.tv_usec = (value % 1000) * 1000;
  3520. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3521. break;
  3522. }
  3523. case ENET_SOCKOPT_SNDTIMEO: {
  3524. struct timeval timeVal;
  3525. timeVal.tv_sec = value / 1000;
  3526. timeVal.tv_usec = (value % 1000) * 1000;
  3527. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3528. break;
  3529. }
  3530. case ENET_SOCKOPT_NODELAY:
  3531. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3532. break;
  3533. case ENET_SOCKOPT_IPV6_V6ONLY:
  3534. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3535. break;
  3536. default:
  3537. break;
  3538. }
  3539. return result == -1 ? -1 : 0;
  3540. }
  3541. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3542. int result = -1;
  3543. socklen_t len;
  3544. switch (option) {
  3545. case ENET_SOCKOPT_ERROR:
  3546. len = sizeof(int);
  3547. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, value, &len);
  3548. break;
  3549. default:
  3550. break;
  3551. }
  3552. return result == -1 ? -1 : 0;
  3553. }
  3554. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3555. int result = -1;
  3556. struct sockaddr_in6 sin;
  3557. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3558. sin.sin6_family = AF_INET6;
  3559. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3560. sin.sin6_addr = address->ipv6;
  3561. result = connect(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3562. if (result == -1 && errno == EINPROGRESS)
  3563. return 0;
  3564. return result;
  3565. }
  3566. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3567. int result = -1;
  3568. struct sockaddr_in6 sin;
  3569. socklen_t sinLength = sizeof(struct sockaddr_in6);
  3570. result = accept(socket, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL);
  3571. if (result == -1)
  3572. return ENET_SOCKET_NULL;
  3573. if (address != NULL) {
  3574. address->ipv6 = sin.sin6_addr;
  3575. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3576. }
  3577. return result;
  3578. }
  3579. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3580. return shutdown(socket, (int)how);
  3581. }
  3582. void enet_socket_destroy(ENetSocket socket) {
  3583. if (socket != ENET_SOCKET_NULL)
  3584. close(socket);
  3585. }
  3586. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3587. struct msghdr msgHdr;
  3588. struct sockaddr_in6 sin;
  3589. int sentLength;
  3590. memset(&msgHdr, 0, sizeof(struct msghdr));
  3591. if (address != NULL) {
  3592. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3593. sin.sin6_family = AF_INET6;
  3594. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3595. sin.sin6_addr = address->ipv6;
  3596. msgHdr.msg_name = &sin;
  3597. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3598. }
  3599. msgHdr.msg_iov = (struct iovec*)buffers;
  3600. msgHdr.msg_iovlen = bufferCount;
  3601. sentLength = sendmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3602. if (sentLength == -1) {
  3603. if (errno == EWOULDBLOCK)
  3604. return 0;
  3605. return -1;
  3606. }
  3607. return sentLength;
  3608. }
  3609. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3610. struct msghdr msgHdr;
  3611. struct sockaddr_in6 sin;
  3612. int recvLength;
  3613. memset(&msgHdr, 0, sizeof(struct msghdr));
  3614. if (address != NULL) {
  3615. msgHdr.msg_name = &sin;
  3616. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3617. }
  3618. msgHdr.msg_iov = (struct iovec*)buffers;
  3619. msgHdr.msg_iovlen = bufferCount;
  3620. recvLength = recvmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3621. if (recvLength == -1) {
  3622. if (errno == EWOULDBLOCK)
  3623. return 0;
  3624. return -1;
  3625. }
  3626. if (msgHdr.msg_flags & MSG_TRUNC) {
  3627. ENET_LOG_ERROR("this enet message header was truncated...\n");
  3628. // commit 5f0e1b475caa019157c3cf881a8d08009150f1e2 from upstream
  3629. return -2;
  3630. }
  3631. if (address != NULL) {
  3632. address->ipv6 = sin.sin6_addr;
  3633. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3634. }
  3635. return recvLength;
  3636. }
  3637. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3638. struct timeval timeVal;
  3639. timeVal.tv_sec = timeout / 1000;
  3640. timeVal.tv_usec = (timeout % 1000) * 1000;
  3641. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3642. }
  3643. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3644. struct pollfd pollSocket;
  3645. int pollCount;
  3646. pollSocket.fd = socket;
  3647. pollSocket.events = 0;
  3648. if (*condition & ENET_SOCKET_WAIT_SEND)
  3649. pollSocket.events |= POLLOUT;
  3650. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3651. pollSocket.events |= POLLIN;
  3652. pollCount = poll(&pollSocket, 1, timeout);
  3653. if (pollCount < 0) {
  3654. if (errno == EINTR && *condition & ENET_SOCKET_WAIT_INTERRUPT) {
  3655. *condition = ENET_SOCKET_WAIT_INTERRUPT;
  3656. return 0;
  3657. }
  3658. ENET_LOG_ERROR("pollCount < 0: %i", pollCount);
  3659. return -1;
  3660. }
  3661. *condition = ENET_SOCKET_WAIT_NONE;
  3662. if (pollCount == 0)
  3663. return 0;
  3664. if (pollSocket.revents & POLLOUT)
  3665. *condition |= ENET_SOCKET_WAIT_SEND;
  3666. if (pollSocket.revents & POLLIN)
  3667. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3668. return 0;
  3669. }
  3670. #endif
  3671. /*
  3672. =======================================================================
  3673. Platform-specific (Windows)
  3674. =======================================================================
  3675. */
  3676. #ifdef _WIN32
  3677. int enet_initialize(void) {
  3678. WORD versionRequested = MAKEWORD(2, 2);
  3679. WSADATA wsaData;
  3680. if (WSAStartup(versionRequested, &wsaData)) {
  3681. ENET_LOG_ERROR("WSAStartup failure");
  3682. return -1;
  3683. }
  3684. if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
  3685. ENET_LOG_ERROR("Winsock version mismatch");
  3686. WSACleanup();
  3687. return -1;
  3688. }
  3689. timeBeginPeriod(1);
  3690. ENET_LOG_TRACE("Windows Environment: ENet Initialization");
  3691. return 0;
  3692. }
  3693. void enet_deinitialize(void) {
  3694. timeEndPeriod(1);
  3695. WSACleanup();
  3696. ENET_LOG_TRACE("Windows Environment: ENet Deinitialization");
  3697. }
  3698. uint64_t enet_host_random_seed(void) {
  3699. return (uint64_t)timeGetTime();
  3700. }
  3701. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3702. struct sockaddr_in6 sin;
  3703. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3704. sin.sin6_family = AF_INET6;
  3705. if (address != NULL) {
  3706. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3707. sin.sin6_addr = address->ipv6;
  3708. }
  3709. else {
  3710. sin.sin6_port = 0;
  3711. sin.sin6_addr = in6addr_any;
  3712. }
  3713. return bind(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6)) == SOCKET_ERROR ? -1 : 0;
  3714. }
  3715. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3716. struct sockaddr_storage ss;
  3717. int saLength = sizeof(ss);
  3718. if (getsockname(socket, (struct sockaddr*) & ss, &saLength) == -1) {
  3719. ENET_LOG_ERROR("getsockname failure");
  3720. return -1;
  3721. }
  3722. if (ss.ss_family == AF_INET) {
  3723. struct sockaddr_in* sin = (struct sockaddr_in*) & ss;
  3724. memset(address, 0, sizeof(address->ipv4.zeros));
  3725. address->ipv4.ffff = 0xFFFF;
  3726. address->ipv4.ip = sin->sin_addr;
  3727. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3728. }
  3729. else if (ss.ss_family == AF_INET6) {
  3730. struct sockaddr_in6* sin = (struct sockaddr_in6*) & ss;
  3731. address->ipv6 = sin->sin6_addr;
  3732. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3733. }
  3734. return 0;
  3735. }
  3736. int enet_socket_listen(ENetSocket socket, int backlog) {
  3737. return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
  3738. }
  3739. ENetSocket enet_socket_create(ENetSocketType type) {
  3740. return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
  3741. }
  3742. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3743. int result = SOCKET_ERROR;
  3744. switch (option) {
  3745. case ENET_SOCKOPT_NONBLOCK: {
  3746. u_long nonBlocking = (u_long)value;
  3747. result = ioctlsocket(socket, FIONBIO, &nonBlocking);
  3748. break;
  3749. }
  3750. case ENET_SOCKOPT_BROADCAST:
  3751. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3752. break;
  3753. case ENET_SOCKOPT_REUSEADDR:
  3754. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3755. break;
  3756. case ENET_SOCKOPT_RCVBUF:
  3757. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3758. break;
  3759. case ENET_SOCKOPT_SNDBUF:
  3760. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3761. break;
  3762. case ENET_SOCKOPT_RCVTIMEO:
  3763. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&value, sizeof(int));
  3764. break;
  3765. case ENET_SOCKOPT_SNDTIMEO:
  3766. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&value, sizeof(int));
  3767. break;
  3768. case ENET_SOCKOPT_NODELAY:
  3769. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3770. break;
  3771. case ENET_SOCKOPT_IPV6_V6ONLY:
  3772. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3773. break;
  3774. default:
  3775. break;
  3776. }
  3777. return result == SOCKET_ERROR ? -1 : 0;
  3778. }
  3779. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3780. int result = SOCKET_ERROR, len;
  3781. switch (option) {
  3782. case ENET_SOCKOPT_ERROR:
  3783. len = sizeof(int);
  3784. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)value, &len);
  3785. break;
  3786. default:
  3787. break;
  3788. }
  3789. return result == SOCKET_ERROR ? -1 : 0;
  3790. }
  3791. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3792. int result = -1;
  3793. struct sockaddr_in6 sin;
  3794. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3795. sin.sin6_family = AF_INET6;
  3796. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3797. sin.sin6_addr = address->ipv6;
  3798. result = connect(socket, (struct sockaddr*) & sin, sizeof(struct sockaddr_in6));
  3799. if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) {
  3800. int winSockWhat = WSAGetLastError();
  3801. ENET_LOG_ERROR("Socket connect failure, return code: %i, WSAGetLastError: %i", result, winSockWhat);
  3802. return -1;
  3803. }
  3804. ENET_LOG_TRACE("Socket Connect");
  3805. return 0;
  3806. }
  3807. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3808. SOCKET result;
  3809. struct sockaddr_in6 sin;
  3810. int sinLength = sizeof(struct sockaddr_in6);
  3811. result = accept(socket, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL);
  3812. if (result == INVALID_SOCKET)
  3813. {
  3814. ENET_LOG_ERROR("Tried to accept from an invalid socket");
  3815. return ENET_SOCKET_NULL;
  3816. }
  3817. if (address != NULL) {
  3818. address->ipv6 = sin.sin6_addr;
  3819. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3820. }
  3821. return result;
  3822. }
  3823. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3824. return shutdown(socket, (int)how) == SOCKET_ERROR ? -1 : 0;
  3825. }
  3826. void enet_socket_destroy(ENetSocket socket) {
  3827. if (socket != INVALID_SOCKET)
  3828. closesocket(socket);
  3829. }
  3830. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3831. struct sockaddr_in6 sin;
  3832. DWORD sentLength = 0;
  3833. if (address != NULL) {
  3834. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3835. sin.sin6_family = AF_INET6;
  3836. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3837. sin.sin6_addr = address->ipv6;
  3838. }
  3839. 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)
  3840. return (WSAGetLastError() == WSAEWOULDBLOCK) ? 0 : -1;
  3841. return (int)sentLength;
  3842. }
  3843. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3844. INT sinLength = sizeof(struct sockaddr_in6);
  3845. DWORD flags = 0, recvLength = 0;
  3846. struct sockaddr_in6 sin;
  3847. if (WSARecvFrom(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &recvLength, &flags, address != NULL ? (struct sockaddr*) & sin : NULL, address != NULL ? &sinLength : NULL, NULL, NULL) == SOCKET_ERROR) {
  3848. int retCode = WSAGetLastError();
  3849. switch (WSAGetLastError()) {
  3850. case WSAEWOULDBLOCK:
  3851. case WSAECONNRESET:
  3852. return 0;
  3853. }
  3854. ENET_LOG_ERROR("Socket receive failure, WSA return code %d", retCode);
  3855. return -1;
  3856. }
  3857. if (flags & MSG_PARTIAL) {
  3858. ENET_LOG_ERROR("Partial socket receive message");
  3859. return -2;
  3860. }
  3861. if (address != NULL) {
  3862. address->ipv6 = sin.sin6_addr;
  3863. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3864. }
  3865. return (int)recvLength;
  3866. }
  3867. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3868. struct timeval timeVal;
  3869. timeVal.tv_sec = timeout / 1000;
  3870. timeVal.tv_usec = (timeout % 1000) * 1000;
  3871. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3872. }
  3873. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3874. fd_set readSet, writeSet;
  3875. struct timeval timeVal;
  3876. int selectCount;
  3877. timeVal.tv_sec = timeout / 1000;
  3878. timeVal.tv_usec = (timeout % 1000) * 1000;
  3879. FD_ZERO(&readSet);
  3880. FD_ZERO(&writeSet);
  3881. if (*condition & ENET_SOCKET_WAIT_SEND)
  3882. FD_SET(socket, &writeSet);
  3883. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3884. FD_SET(socket, &readSet);
  3885. selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
  3886. if (selectCount < 0) {
  3887. ENET_LOG_ERROR("selectCount < 0; was %d", selectCount);
  3888. return -1;
  3889. }
  3890. *condition = ENET_SOCKET_WAIT_NONE;
  3891. if (selectCount == 0)
  3892. return 0;
  3893. if (FD_ISSET(socket, &writeSet))
  3894. *condition |= ENET_SOCKET_WAIT_SEND;
  3895. if (FD_ISSET(socket, &readSet))
  3896. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3897. return 0;
  3898. }
  3899. #endif
  3900. /*
  3901. =======================================================================
  3902. Extended functionality
  3903. =======================================================================
  3904. */
  3905. void* enet_packet_get_data(const ENetPacket* packet) {
  3906. return (void*)packet->data;
  3907. }
  3908. void* enet_packet_get_user_data(const ENetPacket* packet) {
  3909. return packet->userData;
  3910. }
  3911. void enet_packet_set_user_data(ENetPacket* packet, void* userData) {
  3912. packet->userData = userData;
  3913. }
  3914. int enet_packet_get_length(const ENetPacket* packet) {
  3915. return packet->dataLength;
  3916. }
  3917. void enet_packet_set_free_callback(ENetPacket* packet, const void* callback) {
  3918. packet->freeCallback = (ENetPacketFreeCallback)callback;
  3919. }
  3920. int enet_packet_check_references(const ENetPacket* packet) {
  3921. return (int)packet->referenceCount;
  3922. }
  3923. void enet_packet_dispose(ENetPacket* packet) {
  3924. if (packet->referenceCount == 0)
  3925. enet_packet_destroy(packet);
  3926. }
  3927. uint32_t enet_host_get_peers_count(const ENetHost* host) {
  3928. return host->connectedPeers;
  3929. }
  3930. uint32_t enet_host_get_packets_sent(const ENetHost* host) {
  3931. return host->totalSentPackets;
  3932. }
  3933. uint32_t enet_host_get_packets_received(const ENetHost* host) {
  3934. return host->totalReceivedPackets;
  3935. }
  3936. uint32_t enet_host_get_bytes_sent(const ENetHost* host) {
  3937. return host->totalSentData;
  3938. }
  3939. uint32_t enet_host_get_bytes_received(const ENetHost* host) {
  3940. return host->totalReceivedData;
  3941. }
  3942. uint32_t enet_peer_get_id(const ENetPeer* peer) {
  3943. return peer->incomingPeerID;
  3944. }
  3945. int enet_peer_get_ip(const ENetPeer* peer, char* ip, size_t ipLength) {
  3946. return enet_address_get_ip(&peer->address, ip, ipLength);
  3947. }
  3948. uint16_t enet_peer_get_port(const ENetPeer* peer) {
  3949. return peer->address.port;
  3950. }
  3951. uint32_t enet_peer_get_mtu(const ENetPeer* peer) {
  3952. return peer->mtu;
  3953. }
  3954. ENetPeerState enet_peer_get_state(const ENetPeer* peer) {
  3955. return peer->state;
  3956. }
  3957. uint32_t enet_peer_get_rtt(const ENetPeer* peer) {
  3958. return peer->roundTripTime;
  3959. }
  3960. uint32_t enet_peer_get_last_rtt(const ENetPeer* peer) {
  3961. return peer->lastRoundTripTime;
  3962. }
  3963. uint32_t enet_peer_get_lastsendtime(const ENetPeer* peer) {
  3964. return peer->lastSendTime;
  3965. }
  3966. uint32_t enet_peer_get_lastreceivetime(const ENetPeer* peer) {
  3967. return peer->lastReceiveTime;
  3968. }
  3969. uint64_t enet_peer_get_packets_sent(const ENetPeer* peer) {
  3970. return peer->totalPacketsSent;
  3971. }
  3972. uint64_t enet_peer_get_packets_lost(const ENetPeer* peer) {
  3973. return peer->totalPacketsLost;
  3974. }
  3975. uint64_t enet_peer_get_bytes_sent(const ENetPeer* peer) {
  3976. return peer->totalDataSent;
  3977. }
  3978. uint64_t enet_peer_get_bytes_received(const ENetPeer* peer) {
  3979. return peer->totalDataReceived;
  3980. }
  3981. void* enet_peer_get_data(const ENetPeer* peer) {
  3982. return (void*)peer->data;
  3983. }
  3984. void enet_peer_set_data(ENetPeer* peer, const void* data) {
  3985. peer->data = (uint32_t*)data;
  3986. }
  3987. #ifdef _MSC_VER
  3988. #pragma warning(pop)
  3989. #endif
  3990. #endif // ENET_IMPLEMENTATION
  3991. #endif // ENET_H