2
0

enet.h 172 KB

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