enet.h 245 KB

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