enet.h 237 KB

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