enet.h 230 KB

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