enet.h.us.c 219 KB

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