enet.h 234 KB

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