enet.h 231 KB

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