enet.h 234 KB

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