enet.h 244 KB

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