enet.h 167 KB

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