enet.h 229 KB

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