enet.h 223 KB

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