enet.h 237 KB

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