enet.h 245 KB

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