enet.h 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982
  1. /*
  2. * ENet reliable UDP networking library
  3. * Copyright (c) 2018 Lee Salzman, Vladyslav Hrytsenko, Dominik Madarász, Stanislav Denisov
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. #ifndef ENET_H
  24. #define ENET_H
  25. #include <stdlib.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <time.h>
  29. #define ENET_VERSION_MAJOR 2
  30. #define ENET_VERSION_MINOR 4
  31. #define ENET_VERSION_PATCH 1
  32. #define ENET_VERSION_CREATE(major, minor, patch) (((major) << 16) | ((minor) << 8) | (patch))
  33. #define ENET_VERSION_GET_MAJOR(version) (((version) >> 16) & 0xFF)
  34. #define ENET_VERSION_GET_MINOR(version) (((version) >> 8) & 0xFF)
  35. #define ENET_VERSION_GET_PATCH(version) ((version) & 0xFF)
  36. #define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH)
  37. #define ENET_TIME_OVERFLOW 86400000
  38. #define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW)
  39. #define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW)
  40. #define ENET_TIME_LESS_EQUAL(a, b) (!ENET_TIME_GREATER(a, b))
  41. #define ENET_TIME_GREATER_EQUAL(a, b) (!ENET_TIME_LESS(a, b))
  42. #define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b))
  43. #define ENET_MAX(x, y) ((x) > (y) ? (x) : (y))
  44. #define ENET_MIN(x, y) ((x) < (y) ? (x) : (y))
  45. /*
  46. =======================================================================
  47. System differences
  48. =======================================================================
  49. */
  50. #ifdef _WIN32
  51. #ifndef ENET_NO_PRAGMA_LINK
  52. #pragma comment(lib, "ws2_32.lib")
  53. #pragma comment(lib, "winmm.lib")
  54. #endif
  55. #if _MSC_VER >= 1910
  56. /* It looks like there were changes as of Visual Studio 2017 and there are no 32/64 bit
  57. versions of _InterlockedExchange[operation], only InterlockedExchange[operation]
  58. (without leading underscore), so we have to distinguish between compiler versions */
  59. #define ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  60. #endif
  61. #include <winsock2.h>
  62. #include <ws2tcpip.h>
  63. #include <mmsystem.h>
  64. #include <intrin.h>
  65. #if defined(_WIN32) && defined(_MSC_VER)
  66. #if _MSC_VER < 1900
  67. typedef struct timespec {
  68. long tv_sec;
  69. long tv_nsec;
  70. };
  71. #endif
  72. #define CLOCK_MONOTONIC 0
  73. #endif
  74. typedef SOCKET ENetSocket;
  75. #define ENET_SOCKET_NULL INVALID_SOCKET
  76. typedef struct {
  77. size_t dataLength;
  78. void* data;
  79. } ENetBuffer;
  80. #define ENET_CALLBACK __cdecl
  81. #ifdef ENET_DLL
  82. #ifdef ENET_IMPLEMENTATION
  83. #define ENET_API __declspec(dllexport)
  84. #else
  85. #define ENET_API __declspec(dllimport)
  86. #endif
  87. #else
  88. #define ENET_API extern
  89. #endif
  90. #else
  91. #include <sys/types.h>
  92. #include <sys/ioctl.h>
  93. #include <sys/time.h>
  94. #include <sys/socket.h>
  95. #include <poll.h>
  96. #include <arpa/inet.h>
  97. #include <netinet/in.h>
  98. #include <netinet/tcp.h>
  99. #include <netdb.h>
  100. #include <unistd.h>
  101. #include <string.h>
  102. #include <errno.h>
  103. #include <fcntl.h>
  104. #ifdef __APPLE__
  105. #include <mach/clock.h>
  106. #include <mach/mach.h>
  107. #include <Availability.h>
  108. #endif
  109. #ifndef MSG_NOSIGNAL
  110. #define MSG_NOSIGNAL 0
  111. #endif
  112. #ifdef MSG_MAXIOVLEN
  113. #define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN
  114. #endif
  115. typedef int ENetSocket;
  116. #define ENET_SOCKET_NULL -1
  117. typedef struct {
  118. void* data;
  119. size_t dataLength;
  120. } ENetBuffer;
  121. #define ENET_CALLBACK
  122. #define ENET_API extern
  123. #endif
  124. #ifndef ENET_BUFFER_MAXIMUM
  125. #define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)
  126. #endif
  127. #define ENET_HOST_ANY in6addr_any
  128. #define ENET_PORT_ANY 0
  129. #define ENET_HOST_SIZE 1025
  130. #define ENET_HOST_TO_NET_16(value) (htons(value))
  131. #define ENET_HOST_TO_NET_32(value) (htonl(value))
  132. #define ENET_NET_TO_HOST_16(value) (ntohs(value))
  133. #define ENET_NET_TO_HOST_32(value) (ntohl(value))
  134. #ifdef __cplusplus
  135. extern "C" {
  136. #endif
  137. /*
  138. =======================================================================
  139. Internals
  140. =======================================================================
  141. */
  142. typedef uint32_t ENetVersion;
  143. typedef fd_set ENetSocketSet;
  144. typedef struct _ENetCallbacks {
  145. void* (ENET_CALLBACK *malloc)(size_t size);
  146. void (ENET_CALLBACK *free)(void* memory);
  147. void (ENET_CALLBACK *noMemory)(void);
  148. } ENetCallbacks;
  149. extern void* enet_malloc(size_t);
  150. extern void enet_free(void*);
  151. typedef struct _ENetListNode {
  152. struct _ENetListNode* next;
  153. struct _ENetListNode* previous;
  154. } ENetListNode;
  155. typedef ENetListNode* ENetListIterator;
  156. typedef struct _ENetList {
  157. ENetListNode sentinel;
  158. } ENetList;
  159. extern ENetListIterator enet_list_insert(ENetListIterator, void*);
  160. extern ENetListIterator enet_list_move(ENetListIterator, void*, void*);
  161. extern void* enet_list_remove(ENetListIterator);
  162. extern void enet_list_clear(ENetList*);
  163. extern size_t enet_list_size(ENetList*);
  164. #define enet_list_begin(list) ((list)->sentinel.next)
  165. #define enet_list_end(list) (&(list)->sentinel)
  166. #define enet_list_empty(list) (enet_list_begin(list) == enet_list_end(list))
  167. #define enet_list_next(iterator) ((iterator)->next)
  168. #define enet_list_previous(iterator) ((iterator)->previous)
  169. #define enet_list_front(list) ((void*)(list)->sentinel.next)
  170. #define enet_list_back(list) ((void*)(list)->sentinel.previous)
  171. #define enet_in6_equal(a, b) (memcmp(&a, &b, sizeof(struct in6_addr)) == 0)
  172. /*
  173. =======================================================================
  174. Protocol
  175. =======================================================================
  176. */
  177. enum {
  178. ENET_PROTOCOL_MINIMUM_MTU = 576,
  179. ENET_PROTOCOL_MAXIMUM_MTU = 4096,
  180. ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32,
  181. ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096,
  182. ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536,
  183. ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1,
  184. ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255,
  185. ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xFFF,
  186. ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024
  187. };
  188. typedef enum _ENetProtocolCommand {
  189. ENET_PROTOCOL_COMMAND_NONE = 0,
  190. ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1,
  191. ENET_PROTOCOL_COMMAND_CONNECT = 2,
  192. ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3,
  193. ENET_PROTOCOL_COMMAND_DISCONNECT = 4,
  194. ENET_PROTOCOL_COMMAND_PING = 5,
  195. ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6,
  196. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7,
  197. ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8,
  198. ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9,
  199. ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10,
  200. ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11,
  201. ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12,
  202. ENET_PROTOCOL_COMMAND_COUNT = 13,
  203. ENET_PROTOCOL_COMMAND_MASK = 0x0F
  204. } ENetProtocolCommand;
  205. typedef enum _ENetProtocolFlag {
  206. ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7),
  207. ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6),
  208. ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 << 14),
  209. ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_SENT_TIME,
  210. ENET_PROTOCOL_HEADER_SESSION_MASK = (3 << 12),
  211. ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12
  212. } ENetProtocolFlag;
  213. #ifdef _MSC_VER
  214. #pragma pack(push, 1)
  215. #define ENET_PACKED
  216. #elif defined(__GNUC__) || defined(__clang__)
  217. #define ENET_PACKED __attribute__ ((packed))
  218. #else
  219. #define ENET_PACKED
  220. #endif
  221. typedef struct _ENetProtocolHeader {
  222. uint16_t peerID;
  223. uint16_t sentTime;
  224. } ENET_PACKED ENetProtocolHeader;
  225. typedef struct _ENetProtocolCommandHeader {
  226. uint8_t command;
  227. uint8_t channelID;
  228. uint16_t reliableSequenceNumber;
  229. } ENET_PACKED ENetProtocolCommandHeader;
  230. typedef struct _ENetProtocolAcknowledge {
  231. ENetProtocolCommandHeader header;
  232. uint16_t receivedReliableSequenceNumber;
  233. uint16_t receivedSentTime;
  234. } ENET_PACKED ENetProtocolAcknowledge;
  235. typedef struct _ENetProtocolConnect {
  236. ENetProtocolCommandHeader header;
  237. uint16_t outgoingPeerID;
  238. uint8_t incomingSessionID;
  239. uint8_t outgoingSessionID;
  240. uint32_t mtu;
  241. uint32_t windowSize;
  242. uint32_t channelCount;
  243. uint32_t incomingBandwidth;
  244. uint32_t outgoingBandwidth;
  245. uint32_t packetThrottleInterval;
  246. uint32_t packetThrottleAcceleration;
  247. uint32_t packetThrottleDeceleration;
  248. uint32_t connectID;
  249. uint32_t data;
  250. } ENET_PACKED ENetProtocolConnect;
  251. typedef struct _ENetProtocolVerifyConnect {
  252. ENetProtocolCommandHeader header;
  253. uint16_t outgoingPeerID;
  254. uint8_t incomingSessionID;
  255. uint8_t outgoingSessionID;
  256. uint32_t mtu;
  257. uint32_t windowSize;
  258. uint32_t channelCount;
  259. uint32_t incomingBandwidth;
  260. uint32_t outgoingBandwidth;
  261. uint32_t packetThrottleInterval;
  262. uint32_t packetThrottleAcceleration;
  263. uint32_t packetThrottleDeceleration;
  264. uint32_t connectID;
  265. } ENET_PACKED ENetProtocolVerifyConnect;
  266. typedef struct _ENetProtocolBandwidthLimit {
  267. ENetProtocolCommandHeader header;
  268. uint32_t incomingBandwidth;
  269. uint32_t outgoingBandwidth;
  270. } ENET_PACKED ENetProtocolBandwidthLimit;
  271. typedef struct _ENetProtocolThrottleConfigure {
  272. ENetProtocolCommandHeader header;
  273. uint32_t packetThrottleInterval;
  274. uint32_t packetThrottleAcceleration;
  275. uint32_t packetThrottleDeceleration;
  276. } ENET_PACKED ENetProtocolThrottleConfigure;
  277. typedef struct _ENetProtocolDisconnect {
  278. ENetProtocolCommandHeader header;
  279. uint32_t data;
  280. } ENET_PACKED ENetProtocolDisconnect;
  281. typedef struct _ENetProtocolPing {
  282. ENetProtocolCommandHeader header;
  283. } ENET_PACKED ENetProtocolPing;
  284. typedef struct _ENetProtocolSendReliable {
  285. ENetProtocolCommandHeader header;
  286. uint16_t dataLength;
  287. } ENET_PACKED ENetProtocolSendReliable;
  288. typedef struct _ENetProtocolSendUnreliable {
  289. ENetProtocolCommandHeader header;
  290. uint16_t unreliableSequenceNumber;
  291. uint16_t dataLength;
  292. } ENET_PACKED ENetProtocolSendUnreliable;
  293. typedef struct _ENetProtocolSendUnsequenced {
  294. ENetProtocolCommandHeader header;
  295. uint16_t unsequencedGroup;
  296. uint16_t dataLength;
  297. } ENET_PACKED ENetProtocolSendUnsequenced;
  298. typedef struct _ENetProtocolSendFragment {
  299. ENetProtocolCommandHeader header;
  300. uint16_t startSequenceNumber;
  301. uint16_t dataLength;
  302. uint32_t fragmentCount;
  303. uint32_t fragmentNumber;
  304. uint32_t totalLength;
  305. uint32_t fragmentOffset;
  306. } ENET_PACKED ENetProtocolSendFragment;
  307. typedef union _ENetProtocol {
  308. ENetProtocolCommandHeader header;
  309. ENetProtocolAcknowledge acknowledge;
  310. ENetProtocolConnect connect;
  311. ENetProtocolVerifyConnect verifyConnect;
  312. ENetProtocolDisconnect disconnect;
  313. ENetProtocolPing ping;
  314. ENetProtocolSendReliable sendReliable;
  315. ENetProtocolSendUnreliable sendUnreliable;
  316. ENetProtocolSendUnsequenced sendUnsequenced;
  317. ENetProtocolSendFragment sendFragment;
  318. ENetProtocolBandwidthLimit bandwidthLimit;
  319. ENetProtocolThrottleConfigure throttleConfigure;
  320. } ENET_PACKED ENetProtocol;
  321. #ifdef _MSC_VER
  322. #pragma pack(pop)
  323. #endif
  324. /*
  325. =======================================================================
  326. General structs/enums
  327. =======================================================================
  328. */
  329. typedef enum _ENetSocketType {
  330. ENET_SOCKET_TYPE_STREAM = 1,
  331. ENET_SOCKET_TYPE_DATAGRAM = 2
  332. } ENetSocketType;
  333. typedef enum _ENetSocketWait {
  334. ENET_SOCKET_WAIT_NONE = 0,
  335. ENET_SOCKET_WAIT_SEND = (1 << 0),
  336. ENET_SOCKET_WAIT_RECEIVE = (1 << 1),
  337. ENET_SOCKET_WAIT_INTERRUPT = (1 << 2)
  338. } ENetSocketWait;
  339. typedef enum _ENetSocketOption {
  340. ENET_SOCKOPT_NONBLOCK = 1,
  341. ENET_SOCKOPT_BROADCAST = 2,
  342. ENET_SOCKOPT_RCVBUF = 3,
  343. ENET_SOCKOPT_SNDBUF = 4,
  344. ENET_SOCKOPT_REUSEADDR = 5,
  345. ENET_SOCKOPT_RCVTIMEO = 6,
  346. ENET_SOCKOPT_SNDTIMEO = 7,
  347. ENET_SOCKOPT_ERROR = 8,
  348. ENET_SOCKOPT_NODELAY = 9,
  349. ENET_SOCKOPT_IPV6_V6ONLY = 10
  350. } ENetSocketOption;
  351. typedef enum _ENetSocketShutdown {
  352. ENET_SOCKET_SHUTDOWN_READ = 0,
  353. ENET_SOCKET_SHUTDOWN_WRITE = 1,
  354. ENET_SOCKET_SHUTDOWN_READ_WRITE = 2
  355. } ENetSocketShutdown;
  356. typedef struct _ENetAddress {
  357. union {
  358. struct in6_addr ipv6;
  359. struct {
  360. uint8_t zeros[10];
  361. uint16_t ffff;
  362. struct in_addr ip;
  363. } ipv4;
  364. };
  365. uint16_t port;
  366. } ENetAddress;
  367. typedef enum _ENetPacketFlag {
  368. ENET_PACKET_FLAG_NONE = 0,
  369. ENET_PACKET_FLAG_RELIABLE = (1 << 0),
  370. ENET_PACKET_FLAG_UNSEQUENCED = (1 << 1),
  371. ENET_PACKET_FLAG_NO_ALLOCATE = (1 << 2),
  372. ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED = (1 << 3),
  373. ENET_PACKET_FLAG_INSTANT = (1 << 4),
  374. ENET_PACKET_FLAG_CRUCIAL = (1 << 5),
  375. ENET_PACKET_FLAG_SENT = (1 << 8)
  376. } ENetPacketFlag;
  377. typedef void (ENET_CALLBACK *ENetPacketFreeCallback)(void*);
  378. typedef struct _ENetPacket {
  379. uint32_t flags;
  380. uint32_t dataLength;
  381. uint8_t* data;
  382. ENetPacketFreeCallback freeCallback;
  383. uint32_t referenceCount;
  384. void* userData;
  385. } ENetPacket;
  386. typedef struct _ENetAcknowledgement {
  387. ENetListNode acknowledgementList;
  388. uint32_t sentTime;
  389. ENetProtocol command;
  390. } ENetAcknowledgement;
  391. typedef struct _ENetOutgoingCommand {
  392. ENetListNode outgoingCommandList;
  393. uint16_t reliableSequenceNumber;
  394. uint16_t unreliableSequenceNumber;
  395. uint32_t sentTime;
  396. uint32_t roundTripTimeout;
  397. uint32_t roundTripTimeoutLimit;
  398. uint32_t fragmentOffset;
  399. uint16_t fragmentLength;
  400. uint16_t sendAttempts;
  401. ENetProtocol command;
  402. ENetPacket* packet;
  403. } ENetOutgoingCommand;
  404. typedef struct _ENetIncomingCommand {
  405. ENetListNode incomingCommandList;
  406. uint16_t reliableSequenceNumber;
  407. uint16_t unreliableSequenceNumber;
  408. ENetProtocol command;
  409. uint32_t fragmentCount;
  410. uint32_t fragmentsRemaining;
  411. uint32_t* fragments;
  412. ENetPacket* packet;
  413. } ENetIncomingCommand;
  414. typedef enum _ENetPeerState {
  415. ENET_PEER_STATE_DISCONNECTED = 0,
  416. ENET_PEER_STATE_CONNECTING = 1,
  417. ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2,
  418. ENET_PEER_STATE_CONNECTION_PENDING = 3,
  419. ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4,
  420. ENET_PEER_STATE_CONNECTED = 5,
  421. ENET_PEER_STATE_DISCONNECT_LATER = 6,
  422. ENET_PEER_STATE_DISCONNECTING = 7,
  423. ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8,
  424. ENET_PEER_STATE_ZOMBIE = 9
  425. } ENetPeerState;
  426. enum {
  427. ENET_HOST_BUFFER_SIZE_MIN = 256 * 1024,
  428. ENET_HOST_BUFFER_SIZE_MAX = 1024 * 1024,
  429. ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000,
  430. ENET_HOST_DEFAULT_MTU = 1280,
  431. ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024,
  432. ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024,
  433. ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 1,
  434. ENET_PEER_DEFAULT_PACKET_THROTTLE = 32,
  435. ENET_PEER_PACKET_THROTTLE_THRESHOLD = 40,
  436. ENET_PEER_PACKET_THROTTLE_SCALE = 32,
  437. ENET_PEER_PACKET_THROTTLE_COUNTER = 7,
  438. ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2,
  439. ENET_PEER_PACKET_THROTTLE_DECELERATION = 2,
  440. ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000,
  441. ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024,
  442. ENET_PEER_TIMEOUT_LIMIT = 32,
  443. ENET_PEER_TIMEOUT_MINIMUM = 5000,
  444. ENET_PEER_TIMEOUT_MAXIMUM = 30000,
  445. ENET_PEER_PING_INTERVAL = 250,
  446. ENET_PEER_UNSEQUENCED_WINDOWS = 64,
  447. ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024,
  448. ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32,
  449. ENET_PEER_RELIABLE_WINDOWS = 16,
  450. ENET_PEER_RELIABLE_WINDOW_SIZE = 0x1000,
  451. ENET_PEER_FREE_RELIABLE_WINDOWS = 8
  452. };
  453. typedef struct _ENetChannel {
  454. uint16_t outgoingReliableSequenceNumber;
  455. uint16_t outgoingUnreliableSequenceNumber;
  456. uint16_t usedReliableWindows;
  457. uint16_t reliableWindows[ENET_PEER_RELIABLE_WINDOWS];
  458. uint16_t incomingReliableSequenceNumber;
  459. uint16_t incomingUnreliableSequenceNumber;
  460. ENetList incomingReliableCommands;
  461. ENetList incomingUnreliableCommands;
  462. } ENetChannel;
  463. typedef struct _ENetPeer {
  464. ENetListNode dispatchList;
  465. struct _ENetHost* host;
  466. uint16_t outgoingPeerID;
  467. uint16_t incomingPeerID;
  468. uint32_t connectID;
  469. uint8_t outgoingSessionID;
  470. uint8_t incomingSessionID;
  471. ENetAddress address;
  472. void* data;
  473. ENetPeerState state;
  474. ENetChannel* channels;
  475. size_t channelCount;
  476. uint32_t incomingBandwidth;
  477. uint32_t outgoingBandwidth;
  478. uint32_t incomingBandwidthThrottleEpoch;
  479. uint32_t outgoingBandwidthThrottleEpoch;
  480. uint32_t incomingDataTotal;
  481. uint64_t totalDataReceived;
  482. uint32_t outgoingDataTotal;
  483. uint64_t totalDataSent;
  484. uint32_t lastSendTime;
  485. uint32_t lastReceiveTime;
  486. uint32_t nextTimeout;
  487. uint32_t earliestTimeout;
  488. uint64_t totalPacketsSent;
  489. uint64_t totalPacketsLost;
  490. uint32_t packetThrottle;
  491. uint32_t packetThrottleThreshold;
  492. uint32_t packetThrottleLimit;
  493. uint32_t packetThrottleCounter;
  494. uint32_t packetThrottleEpoch;
  495. uint32_t packetThrottleAcceleration;
  496. uint32_t packetThrottleDeceleration;
  497. uint32_t packetThrottleInterval;
  498. uint32_t pingInterval;
  499. uint32_t timeoutLimit;
  500. uint32_t timeoutMinimum;
  501. uint32_t timeoutMaximum;
  502. uint32_t lastRoundTripTime;
  503. uint32_t lowestRoundTripTime;
  504. uint32_t lastRoundTripTimeVariance;
  505. uint32_t highestRoundTripTimeVariance;
  506. uint32_t roundTripTime;
  507. uint32_t roundTripTimeVariance;
  508. uint32_t mtu;
  509. uint32_t windowSize;
  510. uint32_t reliableDataInTransit;
  511. uint16_t outgoingReliableSequenceNumber;
  512. ENetList acknowledgements;
  513. ENetList sentReliableCommands;
  514. ENetList sentUnreliableCommands;
  515. ENetList outgoingCommands;
  516. ENetList dispatchedCommands;
  517. int needsDispatch;
  518. uint16_t incomingUnsequencedGroup;
  519. uint16_t outgoingUnsequencedGroup;
  520. uint32_t unsequencedWindow[ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32];
  521. uint32_t eventData;
  522. size_t totalWaitingData;
  523. } ENetPeer;
  524. typedef uint32_t (ENET_CALLBACK *ENetChecksumCallback)(const ENetBuffer* buffers, size_t bufferCount);
  525. typedef int (ENET_CALLBACK *ENetInterceptCallback)(struct _ENetHost* host, void* event);
  526. typedef struct _ENetHost {
  527. ENetSocket socket;
  528. ENetAddress address;
  529. uint32_t incomingBandwidth;
  530. uint32_t outgoingBandwidth;
  531. uint32_t bandwidthThrottleEpoch;
  532. uint32_t mtu;
  533. uint32_t randomSeed;
  534. int recalculateBandwidthLimits;
  535. uint8_t preventConnections;
  536. ENetPeer* peers;
  537. size_t peerCount;
  538. size_t channelLimit;
  539. uint32_t serviceTime;
  540. ENetList dispatchQueue;
  541. int continueSending;
  542. size_t packetSize;
  543. uint16_t headerFlags;
  544. uint32_t totalSentData;
  545. uint32_t totalSentPackets;
  546. uint32_t totalReceivedData;
  547. uint32_t totalReceivedPackets;
  548. ENetProtocol commands[ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS];
  549. size_t commandCount;
  550. ENetBuffer buffers[ENET_BUFFER_MAXIMUM];
  551. size_t bufferCount;
  552. ENetChecksumCallback checksumCallback;
  553. uint8_t packetData[2][ENET_PROTOCOL_MAXIMUM_MTU];
  554. ENetAddress receivedAddress;
  555. uint8_t* receivedData;
  556. size_t receivedDataLength;
  557. ENetInterceptCallback interceptCallback;
  558. size_t connectedPeers;
  559. size_t bandwidthLimitedPeers;
  560. size_t duplicatePeers;
  561. size_t maximumPacketSize;
  562. size_t maximumWaitingData;
  563. } ENetHost;
  564. typedef enum _ENetEventType {
  565. ENET_EVENT_TYPE_NONE = 0,
  566. ENET_EVENT_TYPE_CONNECT = 1,
  567. ENET_EVENT_TYPE_DISCONNECT = 2,
  568. ENET_EVENT_TYPE_RECEIVE = 3,
  569. ENET_EVENT_TYPE_DISCONNECT_TIMEOUT = 4
  570. } ENetEventType;
  571. typedef struct _ENetEvent {
  572. ENetEventType type;
  573. ENetPeer* peer;
  574. uint8_t channelID;
  575. uint32_t data;
  576. ENetPacket* packet;
  577. } ENetEvent;
  578. /*
  579. =======================================================================
  580. Public API
  581. =======================================================================
  582. */
  583. ENET_API int enet_initialize(void);
  584. ENET_API int enet_initialize_with_callbacks(ENetVersion, const ENetCallbacks*);
  585. ENET_API void enet_deinitialize(void);
  586. ENET_API ENetVersion enet_linked_version(void);
  587. ENET_API int enet_array_is_zeroed(const uint8_t*, int);
  588. ENET_API uint32_t enet_time_get(void);
  589. ENET_API uint32_t enet_crc32(const ENetBuffer*, size_t);
  590. ENET_API ENetPacket* enet_packet_create(const void*, size_t, uint32_t);
  591. ENET_API ENetPacket* enet_packet_create_offset(const void*, size_t, size_t, uint32_t);
  592. ENET_API void enet_packet_destroy(ENetPacket*);
  593. ENET_API int enet_peer_send(ENetPeer*, uint8_t, ENetPacket*);
  594. ENET_API ENetPacket* enet_peer_receive(ENetPeer*, uint8_t*);
  595. ENET_API void enet_peer_ping(ENetPeer*);
  596. ENET_API void enet_peer_ping_interval(ENetPeer*, uint32_t);
  597. ENET_API void enet_peer_timeout(ENetPeer*, uint32_t, uint32_t, uint32_t);
  598. ENET_API void enet_peer_reset(ENetPeer*);
  599. ENET_API void enet_peer_disconnect(ENetPeer*, uint32_t);
  600. ENET_API void enet_peer_disconnect_now(ENetPeer*, uint32_t);
  601. ENET_API void enet_peer_disconnect_later(ENetPeer*, uint32_t);
  602. ENET_API void enet_peer_throttle_configure(ENetPeer*, uint32_t, uint32_t, uint32_t, uint32_t);
  603. ENET_API ENetHost* enet_host_create(const ENetAddress*, size_t, size_t, uint32_t, uint32_t, int);
  604. ENET_API void enet_host_destroy(ENetHost*);
  605. ENET_API void enet_host_prevent_connections(ENetHost*, uint8_t);
  606. ENET_API ENetPeer* enet_host_connect(ENetHost*, const ENetAddress*, size_t, uint32_t);
  607. ENET_API int enet_host_check_events(ENetHost*, ENetEvent*);
  608. ENET_API int enet_host_service(ENetHost*, ENetEvent*, uint32_t);
  609. ENET_API void enet_host_flush(ENetHost*);
  610. ENET_API void enet_host_broadcast(ENetHost*, uint8_t, ENetPacket*);
  611. ENET_API void enet_host_broadcast_exclude(ENetHost*, uint8_t, ENetPacket*, ENetPeer*);
  612. ENET_API void enet_host_broadcast_selective(ENetHost*, uint8_t, ENetPacket*, ENetPeer**, size_t);
  613. ENET_API void enet_host_channel_limit(ENetHost*, size_t);
  614. ENET_API void enet_host_bandwidth_limit(ENetHost*, uint32_t, uint32_t);
  615. ENET_API int enet_address_set_ip(ENetAddress*, const char*);
  616. ENET_API int enet_address_set_hostname(ENetAddress*, const char*);
  617. ENET_API int enet_address_get_ip(const ENetAddress*, char*, size_t);
  618. ENET_API int enet_address_get_hostname(const ENetAddress*, char*, size_t);
  619. ENET_API ENetSocket enet_socket_create(ENetSocketType);
  620. ENET_API int enet_socket_bind(ENetSocket, const ENetAddress*);
  621. ENET_API int enet_socket_get_address(ENetSocket, ENetAddress*);
  622. ENET_API int enet_socket_listen(ENetSocket, int);
  623. ENET_API ENetSocket enet_socket_accept(ENetSocket, ENetAddress*);
  624. ENET_API int enet_socket_connect(ENetSocket, const ENetAddress*);
  625. ENET_API int enet_socket_send(ENetSocket, const ENetAddress*, const ENetBuffer*, size_t);
  626. ENET_API int enet_socket_receive(ENetSocket, ENetAddress*, ENetBuffer*, size_t);
  627. ENET_API int enet_socket_wait(ENetSocket, uint32_t*, uint64_t);
  628. ENET_API int enet_socket_set_option(ENetSocket, ENetSocketOption, int);
  629. ENET_API int enet_socket_get_option(ENetSocket, ENetSocketOption, int*);
  630. ENET_API int enet_socket_shutdown(ENetSocket, ENetSocketShutdown);
  631. ENET_API void enet_socket_destroy(ENetSocket);
  632. ENET_API int enet_socket_set_select(ENetSocket, ENetSocketSet*, ENetSocketSet*, uint32_t);
  633. /* Extended API for easier binding in other programming languages */
  634. ENET_API void* enet_packet_get_data(const ENetPacket*);
  635. ENET_API void* enet_packet_get_user_data(const ENetPacket*);
  636. ENET_API void enet_packet_set_user_data(ENetPacket*, void* userData);
  637. ENET_API int enet_packet_get_length(const ENetPacket*);
  638. ENET_API void enet_packet_set_free_callback(ENetPacket*, const void*);
  639. ENET_API int enet_packet_check_references(const ENetPacket*);
  640. ENET_API void enet_packet_dispose(ENetPacket*);
  641. ENET_API uint32_t enet_host_get_peers_count(const ENetHost*);
  642. ENET_API uint32_t enet_host_get_packets_sent(const ENetHost*);
  643. ENET_API uint32_t enet_host_get_packets_received(const ENetHost*);
  644. ENET_API uint32_t enet_host_get_bytes_sent(const ENetHost*);
  645. ENET_API uint32_t enet_host_get_bytes_received(const ENetHost*);
  646. ENET_API void enet_host_set_max_duplicate_peers(ENetHost*, uint16_t);
  647. ENET_API uint32_t enet_peer_get_id(const ENetPeer*);
  648. ENET_API int enet_peer_get_ip(const ENetPeer*, char*, size_t);
  649. ENET_API uint16_t enet_peer_get_port(const ENetPeer*);
  650. ENET_API uint32_t enet_peer_get_mtu(const ENetPeer*);
  651. ENET_API ENetPeerState enet_peer_get_state(const ENetPeer*);
  652. ENET_API uint32_t enet_peer_get_rtt(const ENetPeer*);
  653. ENET_API uint32_t enet_peer_get_last_rtt(const ENetPeer* peer);
  654. ENET_API uint32_t enet_peer_get_lastsendtime(const ENetPeer*);
  655. ENET_API uint32_t enet_peer_get_lastreceivetime(const ENetPeer*);
  656. ENET_API uint64_t enet_peer_get_packets_sent(const ENetPeer*);
  657. ENET_API uint64_t enet_peer_get_packets_lost(const ENetPeer*);
  658. ENET_API float enet_peer_get_packets_throttle(const ENetPeer*);
  659. ENET_API uint64_t enet_peer_get_bytes_sent(const ENetPeer*);
  660. ENET_API uint64_t enet_peer_get_bytes_received(const ENetPeer*);
  661. ENET_API void* enet_peer_get_data(const ENetPeer*);
  662. ENET_API void enet_peer_set_data(ENetPeer*, const void*);
  663. /*
  664. =======================================================================
  665. Private API
  666. =======================================================================
  667. */
  668. extern void enet_host_bandwidth_throttle(ENetHost*);
  669. extern uint64_t enet_host_random_seed(void);
  670. extern int enet_peer_throttle(ENetPeer*, uint32_t);
  671. extern void enet_peer_reset_queues(ENetPeer*);
  672. extern void enet_peer_setup_outgoing_command(ENetPeer*, ENetOutgoingCommand*);
  673. extern ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer*, const ENetProtocol*, ENetPacket*, uint32_t, uint16_t);
  674. extern ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer*, const ENetProtocol*, const void*, size_t, uint32_t, uint32_t);
  675. extern ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer*, const ENetProtocol*, uint16_t);
  676. extern void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer*, ENetChannel*, ENetIncomingCommand*);
  677. extern void enet_peer_dispatch_incoming_reliable_commands(ENetPeer*, ENetChannel*, ENetIncomingCommand*);
  678. extern void enet_peer_on_connect(ENetPeer*);
  679. extern void enet_peer_on_disconnect(ENetPeer*);
  680. extern size_t enet_protocol_command_size(uint8_t);
  681. #ifdef __cplusplus
  682. }
  683. #endif
  684. #if defined(ENET_IMPLEMENTATION) && !defined(ENET_IMPLEMENTATION_DONE)
  685. #define ENET_IMPLEMENTATION_DONE 1
  686. #ifdef _MSC_VER
  687. #pragma warning(push)
  688. #pragma warning(disable: 4244) /* 64-bit to 32-bit integer conversion */
  689. #pragma warning(disable: 4267) /* size_t to integer conversion */
  690. #endif
  691. /*
  692. =======================================================================
  693. Atomics
  694. =======================================================================
  695. */
  696. #ifdef _MSC_VER
  697. #define ENET_AT_CASSERT_PRED(predicate) sizeof(char[2 * !!(predicate) - 1])
  698. #define ENET_IS_SUPPORTED_ATOMIC(size) ENET_AT_CASSERT_PRED(size == 1 || size == 2 || size == 4 || size == 8)
  699. #define ENET_ATOMIC_SIZEOF(variable) (ENET_IS_SUPPORTED_ATOMIC(sizeof(*(variable))), sizeof(*(variable)))
  700. __inline int64_t enet_at_atomic_read(char* ptr, size_t size) {
  701. switch (size) {
  702. case 1:
  703. return _InterlockedExchangeAdd8((volatile char*)ptr, 0);
  704. case 2:
  705. return _InterlockedExchangeAdd16((volatile SHORT*)ptr, 0);
  706. case 4:
  707. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  708. return InterlockedExchangeAdd((volatile LONG*)ptr, 0);
  709. #else
  710. return _InterlockedExchangeAdd((volatile LONG*)ptr, 0);
  711. #endif
  712. case 8:
  713. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  714. return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
  715. #else
  716. return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
  717. #endif
  718. default:
  719. return 0x0;
  720. }
  721. }
  722. __inline int64_t enet_at_atomic_write(char* ptr, int64_t value, size_t size) {
  723. switch (size) {
  724. case 1:
  725. return _InterlockedExchange8((volatile char*)ptr, (char)value);
  726. case 2:
  727. return _InterlockedExchange16((volatile SHORT*)ptr, (SHORT)value);
  728. case 4:
  729. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  730. return InterlockedExchange((volatile LONG*)ptr, (LONG)value);
  731. #else
  732. return _InterlockedExchange((volatile LONG*)ptr, (LONG)value);
  733. #endif
  734. case 8:
  735. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  736. return InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
  737. #else
  738. return _InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
  739. #endif
  740. default:
  741. return 0x0;
  742. }
  743. }
  744. __inline int64_t enet_at_atomic_cas(char* ptr, int64_t new_val, int64_t old_val, size_t size) {
  745. switch (size) {
  746. case 1:
  747. return _InterlockedCompareExchange8((volatile char*)ptr, (char)new_val, (char)old_val);
  748. case 2:
  749. return _InterlockedCompareExchange16((volatile SHORT*)ptr, (SHORT)new_val, (SHORT)old_val);
  750. case 4:
  751. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  752. return InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
  753. #else
  754. return _InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
  755. #endif
  756. case 8:
  757. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  758. return InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
  759. #else
  760. return _InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
  761. #endif
  762. default:
  763. return 0x0;
  764. }
  765. }
  766. __inline int64_t enet_at_atomic_inc(char* ptr, int64_t delta, size_t data_size) {
  767. switch (data_size) {
  768. case 1:
  769. return _InterlockedExchangeAdd8((volatile char*)ptr, (char)delta);
  770. case 2:
  771. return _InterlockedExchangeAdd16((volatile SHORT*)ptr, (SHORT)delta);
  772. case 4:
  773. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  774. return InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
  775. #else
  776. return _InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
  777. #endif
  778. case 8:
  779. #ifdef ENET_NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
  780. return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
  781. #else
  782. return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
  783. #endif
  784. default:
  785. return 0x0;
  786. }
  787. }
  788. #define ENET_ATOMIC_READ(variable) enet_at_atomic_read((char*)(variable), ENET_ATOMIC_SIZEOF(variable))
  789. #define ENET_ATOMIC_WRITE(variable, new_val) enet_at_atomic_write((char*)(variable), (int64_t)(new_val), ENET_ATOMIC_SIZEOF(variable))
  790. #define ENET_ATOMIC_CAS(variable, old_value, new_val) enet_at_atomic_cas((char*)(variable), (int64_t)(new_val), (int64_t)(old_value), ENET_ATOMIC_SIZEOF(variable))
  791. #define ENET_ATOMIC_INC(variable) enet_at_atomic_inc((char*)(variable), 1, ENET_ATOMIC_SIZEOF(variable))
  792. #define ENET_ATOMIC_DEC(variable) enet_at_atomic_inc((char*)(variable), -1, ENET_ATOMIC_SIZEOF(variable))
  793. #define ENET_ATOMIC_INC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), (delta), ENET_ATOMIC_SIZEOF(variable))
  794. #define ENET_ATOMIC_DEC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), -(delta), ENET_ATOMIC_SIZEOF(variable))
  795. #elif defined(__GNUC__) || defined(__clang__)
  796. #if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
  797. #define AT_HAVE_ATOMICS
  798. #endif
  799. /* We want to use __atomic built-ins if possible because the __sync primitives are
  800. deprecated, because the __atomic build-ins allow us to use ENET_ATOMIC_WRITE on
  801. uninitialized memory without running into undefined behavior, and because the
  802. __atomic versions generate more efficient code since we don't need to rely on
  803. CAS when we don't actually want it.
  804. Note that we use acquire-release memory order (like mutexes do). We could use
  805. sequentially consistent memory order but that has lower performance and is
  806. almost always unneeded. */
  807. #ifdef AT_HAVE_ATOMICS
  808. #define ENET_ATOMIC_READ(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
  809. #define ENET_ATOMIC_WRITE(ptr, value) __atomic_store_n((ptr), (value), __ATOMIC_RELEASE)
  810. #ifndef typeof
  811. #define typeof __typeof__
  812. #endif
  813. /* clang_analyzer doesn't know that CAS writes to memory so it complains about
  814. potentially lost data. Replace the code with the equivalent non-sync code. */
  815. #ifdef __clang_analyzer__
  816. #define ENET_ATOMIC_CAS(ptr, old_value, new_value)\
  817. ({\
  818. typeof(*(ptr)) ENET_ATOMIC_CAS_old_actual_ = (*(ptr));\
  819. if (ATOMIC_CAS_old_actual_ == (old_value))\
  820. *(ptr) = new_value;\
  821. ENET_ATOMIC_CAS_old_actual_;\
  822. })
  823. #else
  824. /* Could use __auto_type instead of typeof but that shouldn't work in C++.
  825. The ({ }) syntax is a GCC extension called statement expression. It lets
  826. us return a value out of the macro.
  827. TODO We should return bool here instead of the old value to avoid the ABA
  828. problem. */
  829. #define ENET_ATOMIC_CAS(ptr, old_value, new_value)\
  830. ({\
  831. typeof(*(ptr)) ENET_ATOMIC_CAS_expected_ = (old_value);\
  832. __atomic_compare_exchange_n((ptr), &ENET_ATOMIC_CAS_expected_, (new_value), false,\
  833. __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);\
  834. ENET_ATOMIC_CAS_expected_;\
  835. })
  836. #endif
  837. #define ENET_ATOMIC_INC(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_ACQ_REL)
  838. #define ENET_ATOMIC_DEC(ptr) __atomic_fetch_sub((ptr), 1, __ATOMIC_ACQ_REL)
  839. #define ENET_ATOMIC_INC_BY(ptr, delta) __atomic_fetch_add((ptr), (delta), __ATOMIC_ACQ_REL)
  840. #define ENET_ATOMIC_DEC_BY(ptr, delta) __atomic_fetch_sub((ptr), (delta), __ATOMIC_ACQ_REL)
  841. #else
  842. #define ENET_ATOMIC_READ(variable) __sync_fetch_and_add(variable, 0)
  843. #define ENET_ATOMIC_WRITE(variable, new_val) (void)__sync_val_compare_and_swap((variable), *(variable), (new_val))
  844. #define ENET_ATOMIC_CAS(variable, old_value, new_val) __sync_val_compare_and_swap((variable), (old_value), (new_val))
  845. #define ENET_ATOMIC_INC(variable) __sync_fetch_and_add((variable), 1)
  846. #define ENET_ATOMIC_DEC(variable) __sync_fetch_and_sub((variable), 1)
  847. #define ENET_ATOMIC_INC_BY(variable, delta) __sync_fetch_and_add((variable), (delta), 1)
  848. #define ENET_ATOMIC_DEC_BY(variable, delta) __sync_fetch_and_sub((variable), (delta), 1)
  849. #endif
  850. #undef AT_HAVE_ATOMICS
  851. #endif
  852. /*
  853. =======================================================================
  854. Callbacks
  855. =======================================================================
  856. */
  857. static ENetCallbacks callbacks = {
  858. malloc,
  859. free,
  860. abort
  861. };
  862. int enet_initialize_with_callbacks(ENetVersion version, const ENetCallbacks* inits) {
  863. if (version < ENET_VERSION_CREATE(1, 3, 0))
  864. return -1;
  865. if (inits->malloc != NULL || inits->free != NULL) {
  866. if (inits->malloc == NULL || inits->free == NULL)
  867. return -1;
  868. callbacks.malloc = inits->malloc;
  869. callbacks.free = inits->free;
  870. }
  871. if (inits->noMemory != NULL)
  872. callbacks.noMemory = inits->noMemory;
  873. return enet_initialize();
  874. }
  875. void* enet_malloc(size_t size) {
  876. void* memory = callbacks.malloc(size);
  877. if (memory == NULL)
  878. callbacks.noMemory();
  879. return memory;
  880. }
  881. void enet_free(void* memory) {
  882. callbacks.free(memory);
  883. }
  884. /*
  885. =======================================================================
  886. List
  887. =======================================================================
  888. */
  889. void enet_list_clear(ENetList* list) {
  890. list->sentinel.next = &list->sentinel;
  891. list->sentinel.previous = &list->sentinel;
  892. }
  893. ENetListIterator enet_list_insert(ENetListIterator position, void* data) {
  894. ENetListIterator result = (ENetListIterator)data;
  895. result->previous = position->previous;
  896. result->next = position;
  897. result->previous->next = result;
  898. position->previous = result;
  899. return result;
  900. }
  901. void* enet_list_remove(ENetListIterator position) {
  902. position->previous->next = position->next;
  903. position->next->previous = position->previous;
  904. return position;
  905. }
  906. ENetListIterator enet_list_move(ENetListIterator position, void* dataFirst, void* dataLast) {
  907. ENetListIterator first = (ENetListIterator)dataFirst;
  908. ENetListIterator last = (ENetListIterator)dataLast;
  909. first->previous->next = last->next;
  910. last->next->previous = first->previous;
  911. first->previous = position->previous;
  912. last->next = position;
  913. first->previous->next = first;
  914. position->previous = last;
  915. return first;
  916. }
  917. size_t enet_list_size(ENetList* list) {
  918. size_t size = 0;
  919. ENetListIterator position;
  920. for (position = enet_list_begin(list); position != enet_list_end(list); position = enet_list_next(position)) {
  921. ++size;
  922. }
  923. return size;
  924. }
  925. /*
  926. =======================================================================
  927. Utilities
  928. =======================================================================
  929. */
  930. ENetVersion enet_linked_version(void) {
  931. return ENET_VERSION;
  932. }
  933. int enet_array_is_zeroed(const uint8_t* array, int length) {
  934. size_t i;
  935. for (i = 0; i < length; i++) {
  936. if (array[i] != 0)
  937. return -1;
  938. }
  939. return 0;
  940. }
  941. /*
  942. =======================================================================
  943. Time
  944. =======================================================================
  945. */
  946. #ifdef _WIN32
  947. static LARGE_INTEGER gettime_offset(void) {
  948. SYSTEMTIME s;
  949. FILETIME f;
  950. LARGE_INTEGER t;
  951. s.wYear = 1970;
  952. s.wMonth = 1;
  953. s.wDay = 1;
  954. s.wHour = 0;
  955. s.wMinute = 0;
  956. s.wSecond = 0;
  957. s.wMilliseconds = 0;
  958. SystemTimeToFileTime(&s, &f);
  959. t.QuadPart = f.dwHighDateTime;
  960. t.QuadPart <<= 32;
  961. t.QuadPart |= f.dwLowDateTime;
  962. return t;
  963. }
  964. int clock_gettime(int X, struct timespec* tv) {
  965. LARGE_INTEGER t;
  966. FILETIME f;
  967. double microseconds;
  968. static LARGE_INTEGER offset;
  969. static double frequencyToMicroseconds;
  970. static int initialized = 0;
  971. static BOOL usePerformanceCounter = 0;
  972. if (!initialized) {
  973. LARGE_INTEGER performanceFrequency;
  974. initialized = 1;
  975. usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
  976. if (usePerformanceCounter) {
  977. QueryPerformanceCounter(&offset);
  978. frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
  979. } else {
  980. offset = gettime_offset();
  981. frequencyToMicroseconds = 10.;
  982. }
  983. }
  984. if (usePerformanceCounter) {
  985. QueryPerformanceCounter(&t);
  986. } else {
  987. GetSystemTimeAsFileTime(&f);
  988. t.QuadPart = f.dwHighDateTime;
  989. t.QuadPart <<= 32;
  990. t.QuadPart |= f.dwLowDateTime;
  991. }
  992. t.QuadPart -= offset.QuadPart;
  993. microseconds = (double)t.QuadPart / frequencyToMicroseconds;
  994. t.QuadPart = (LONGLONG)microseconds;
  995. tv->tv_sec = (long)(t.QuadPart / 1000000);
  996. tv->tv_nsec = t.QuadPart % 1000000 * 1000;
  997. return 0;
  998. }
  999. #elif __APPLE__ && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200 || __IPHONE_OS_VERSION_MIN_REQUIRED < 100000) && !defined(CLOCK_MONOTONIC)
  1000. #define CLOCK_MONOTONIC 0
  1001. int clock_gettime(int X, struct timespec* ts) {
  1002. clock_serv_t cclock;
  1003. mach_timespec_t mts;
  1004. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1005. clock_get_time(cclock, &mts);
  1006. mach_port_deallocate(mach_task_self(), cclock);
  1007. ts->tv_sec = mts.tv_sec;
  1008. ts->tv_nsec = mts.tv_nsec;
  1009. return 0;
  1010. }
  1011. #endif
  1012. uint32_t enet_time_get(void) {
  1013. static uint64_t start_time_ns = 0;
  1014. struct timespec ts;
  1015. #ifdef CLOCK_MONOTONIC_RAW
  1016. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  1017. #else
  1018. clock_gettime(CLOCK_MONOTONIC, &ts);
  1019. #endif
  1020. static const uint64_t ns_in_s = 1000 * 1000 * 1000;
  1021. static const uint64_t ns_in_ms = 1000 * 1000;
  1022. uint64_t current_time_ns = ts.tv_nsec + (uint64_t)ts.tv_sec * ns_in_s;
  1023. uint64_t offset_ns = ENET_ATOMIC_READ(&start_time_ns);
  1024. if (offset_ns == 0) {
  1025. uint64_t want_value = current_time_ns - 1 * ns_in_ms;
  1026. uint64_t old_value = ENET_ATOMIC_CAS(&start_time_ns, 0, want_value);
  1027. offset_ns = old_value == 0 ? want_value : old_value;
  1028. }
  1029. uint64_t result_in_ns = current_time_ns - offset_ns;
  1030. return (uint32_t)(result_in_ns / ns_in_ms);
  1031. }
  1032. /*
  1033. =======================================================================
  1034. Checksum
  1035. =======================================================================
  1036. */
  1037. static int initializedCRC32 = 0;
  1038. static uint32_t crcTable[256];
  1039. static uint32_t reflect_crc(int val, int bits) {
  1040. int result = 0, bit;
  1041. for (bit = 0; bit < bits; bit++) {
  1042. if (val & 1)
  1043. result |= 1 << (bits - 1 - bit);
  1044. val >>= 1;
  1045. }
  1046. return result;
  1047. }
  1048. static void initialize_crc32(void) {
  1049. int byte;
  1050. for (byte = 0; byte < 256; ++byte) {
  1051. uint32_t crc = reflect_crc(byte, 8) << 24;
  1052. int offset;
  1053. for (offset = 0; offset < 8; ++offset) {
  1054. if (crc & 0x80000000)
  1055. crc = (crc << 1) ^ 0x04c11db7;
  1056. else
  1057. crc <<= 1;
  1058. }
  1059. crcTable[byte] = reflect_crc(crc, 32);
  1060. }
  1061. initializedCRC32 = 1;
  1062. }
  1063. uint32_t enet_crc32(const ENetBuffer* buffers, size_t bufferCount) {
  1064. uint32_t crc = 0xFFFFFFFF;
  1065. if (!initializedCRC32)
  1066. initialize_crc32();
  1067. while (bufferCount-- > 0) {
  1068. const uint8_t* data = (const uint8_t*)buffers->data;
  1069. const uint8_t* dataEnd = &data[buffers->dataLength];
  1070. while (data < dataEnd) {
  1071. crc = (crc >> 8) ^ crcTable[(crc & 0xFF)^* data++];
  1072. }
  1073. ++buffers;
  1074. }
  1075. return ENET_HOST_TO_NET_32(~crc);
  1076. }
  1077. /*
  1078. =======================================================================
  1079. Packet
  1080. =======================================================================
  1081. */
  1082. ENetPacket* enet_packet_create(const void* data, size_t dataLength, uint32_t flags) {
  1083. ENetPacket* packet;
  1084. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1085. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1086. if (packet == NULL)
  1087. return NULL;
  1088. packet->data = (uint8_t*)data;
  1089. } else {
  1090. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength);
  1091. if (packet == NULL)
  1092. return NULL;
  1093. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1094. if (data != NULL)
  1095. memcpy(packet->data, data, dataLength);
  1096. }
  1097. packet->referenceCount = 0;
  1098. packet->flags = flags;
  1099. packet->dataLength = dataLength;
  1100. packet->freeCallback = NULL;
  1101. packet->userData = NULL;
  1102. return packet;
  1103. }
  1104. ENetPacket* enet_packet_create_offset(const void* data, size_t dataLength, size_t dataOffset, uint32_t flags) {
  1105. ENetPacket* packet;
  1106. if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
  1107. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
  1108. if (packet == NULL)
  1109. return NULL;
  1110. packet->data = (uint8_t*)data;
  1111. } else {
  1112. packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength - dataOffset);
  1113. if (packet == NULL)
  1114. return NULL;
  1115. packet->data = (uint8_t*)packet + sizeof(ENetPacket);
  1116. if (data != NULL)
  1117. memcpy(packet->data, (char*)data + dataOffset, dataLength - dataOffset);
  1118. }
  1119. packet->referenceCount = 0;
  1120. packet->flags = flags;
  1121. packet->dataLength = dataLength - dataOffset;
  1122. packet->freeCallback = NULL;
  1123. packet->userData = NULL;
  1124. return packet;
  1125. }
  1126. void enet_packet_destroy(ENetPacket* packet) {
  1127. if (packet == NULL)
  1128. return;
  1129. if (packet->freeCallback != NULL)
  1130. (*packet->freeCallback)((void*)packet);
  1131. enet_free(packet);
  1132. }
  1133. /*
  1134. =======================================================================
  1135. Protocol
  1136. =======================================================================
  1137. */
  1138. static size_t commandSizes[ENET_PROTOCOL_COMMAND_COUNT] = {
  1139. 0,
  1140. sizeof(ENetProtocolAcknowledge),
  1141. sizeof(ENetProtocolConnect),
  1142. sizeof(ENetProtocolVerifyConnect),
  1143. sizeof(ENetProtocolDisconnect),
  1144. sizeof(ENetProtocolPing),
  1145. sizeof(ENetProtocolSendReliable),
  1146. sizeof(ENetProtocolSendUnreliable),
  1147. sizeof(ENetProtocolSendFragment),
  1148. sizeof(ENetProtocolSendUnsequenced),
  1149. sizeof(ENetProtocolBandwidthLimit),
  1150. sizeof(ENetProtocolThrottleConfigure),
  1151. sizeof(ENetProtocolSendFragment)
  1152. };
  1153. size_t enet_protocol_command_size(uint8_t commandNumber) {
  1154. return commandSizes[commandNumber & ENET_PROTOCOL_COMMAND_MASK];
  1155. }
  1156. static void enet_protocol_change_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1157. if (state == ENET_PEER_STATE_CONNECTED || state == ENET_PEER_STATE_DISCONNECT_LATER)
  1158. enet_peer_on_connect(peer);
  1159. else
  1160. enet_peer_on_disconnect(peer);
  1161. peer->state = state;
  1162. }
  1163. static void enet_protocol_dispatch_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
  1164. enet_protocol_change_state(host, peer, state);
  1165. if (!peer->needsDispatch) {
  1166. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1167. peer->needsDispatch = 1;
  1168. }
  1169. }
  1170. static int enet_protocol_dispatch_incoming_commands(ENetHost* host, ENetEvent* event) {
  1171. while (!enet_list_empty(&host->dispatchQueue)) {
  1172. ENetPeer* peer = (ENetPeer*)enet_list_remove(enet_list_begin(&host->dispatchQueue));
  1173. peer->needsDispatch = 0;
  1174. switch (peer->state) {
  1175. case ENET_PEER_STATE_CONNECTION_PENDING:
  1176. case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
  1177. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1178. event->type = ENET_EVENT_TYPE_CONNECT;
  1179. event->peer = peer;
  1180. event->data = peer->eventData;
  1181. return 1;
  1182. case ENET_PEER_STATE_ZOMBIE:
  1183. host->recalculateBandwidthLimits = 1;
  1184. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1185. event->peer = peer;
  1186. event->data = peer->eventData;
  1187. enet_peer_reset(peer);
  1188. return 1;
  1189. case ENET_PEER_STATE_CONNECTED:
  1190. if (enet_list_empty(&peer->dispatchedCommands))
  1191. continue;
  1192. event->packet = enet_peer_receive(peer, &event->channelID);
  1193. if (event->packet == NULL)
  1194. continue;
  1195. event->type = ENET_EVENT_TYPE_RECEIVE;
  1196. event->peer = peer;
  1197. if (!enet_list_empty(&peer->dispatchedCommands)) {
  1198. peer->needsDispatch = 1;
  1199. enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
  1200. }
  1201. return 1;
  1202. default:
  1203. break;
  1204. }
  1205. }
  1206. return 0;
  1207. }
  1208. static void enet_protocol_notify_connect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1209. host->recalculateBandwidthLimits = 1;
  1210. if (event != NULL) {
  1211. enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
  1212. peer->totalDataSent = 0;
  1213. peer->totalDataReceived = 0;
  1214. peer->totalPacketsSent = 0;
  1215. peer->totalPacketsLost = 0;
  1216. event->type = ENET_EVENT_TYPE_CONNECT;
  1217. event->peer = peer;
  1218. event->data = peer->eventData;
  1219. } else {
  1220. enet_protocol_dispatch_state(host, peer, peer->state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING);
  1221. }
  1222. }
  1223. static void enet_protocol_notify_disconnect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1224. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1225. host->recalculateBandwidthLimits = 1;
  1226. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1227. enet_peer_reset(peer);
  1228. } else if (event != NULL) {
  1229. event->type = ENET_EVENT_TYPE_DISCONNECT;
  1230. event->peer = peer;
  1231. event->data = 0;
  1232. enet_peer_reset(peer);
  1233. } else {
  1234. peer->eventData = 0;
  1235. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1236. }
  1237. }
  1238. static void enet_protocol_notify_disconnect_timeout(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1239. if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
  1240. host->recalculateBandwidthLimits = 1;
  1241. if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
  1242. enet_peer_reset(peer);
  1243. } else if (event != NULL) {
  1244. event->type = ENET_EVENT_TYPE_DISCONNECT_TIMEOUT;
  1245. event->peer = peer;
  1246. event->data = 0;
  1247. enet_peer_reset(peer);
  1248. } else {
  1249. peer->eventData = 0;
  1250. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1251. }
  1252. }
  1253. static void enet_protocol_remove_sent_unreliable_commands(ENetPeer* peer) {
  1254. ENetOutgoingCommand* outgoingCommand;
  1255. if (enet_list_empty(&peer->sentUnreliableCommands))
  1256. return;
  1257. do {
  1258. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentUnreliableCommands);
  1259. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1260. if (outgoingCommand->packet != NULL) {
  1261. --outgoingCommand->packet->referenceCount;
  1262. if (outgoingCommand->packet->referenceCount == 0) {
  1263. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1264. enet_packet_destroy(outgoingCommand->packet);
  1265. }
  1266. }
  1267. enet_free(outgoingCommand);
  1268. }
  1269. while (!enet_list_empty(&peer->sentUnreliableCommands));
  1270. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingCommands) && enet_list_empty(&peer->sentReliableCommands))
  1271. enet_peer_disconnect(peer, peer->eventData);
  1272. }
  1273. static ENetProtocolCommand enet_protocol_remove_sent_reliable_command(ENetPeer* peer, uint16_t reliableSequenceNumber, uint8_t channelID) {
  1274. ENetOutgoingCommand* outgoingCommand = NULL;
  1275. ENetListIterator currentCommand;
  1276. ENetProtocolCommand commandNumber;
  1277. int wasSent = 1;
  1278. for (currentCommand = enet_list_begin(&peer->sentReliableCommands); currentCommand != enet_list_end(&peer->sentReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  1279. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1280. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1281. break;
  1282. }
  1283. if (currentCommand == enet_list_end(&peer->sentReliableCommands)) {
  1284. for (currentCommand = enet_list_begin(&peer->outgoingCommands); currentCommand != enet_list_end(&peer->outgoingCommands); currentCommand = enet_list_next(currentCommand)) {
  1285. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1286. if (outgoingCommand->sendAttempts < 1)
  1287. return ENET_PROTOCOL_COMMAND_NONE;
  1288. if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
  1289. break;
  1290. }
  1291. if (currentCommand == enet_list_end(&peer->outgoingCommands))
  1292. return ENET_PROTOCOL_COMMAND_NONE;
  1293. wasSent = 0;
  1294. }
  1295. if (outgoingCommand == NULL)
  1296. return ENET_PROTOCOL_COMMAND_NONE;
  1297. if (channelID < peer->channelCount) {
  1298. ENetChannel* channel = &peer->channels[channelID];
  1299. uint16_t reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1300. if (channel->reliableWindows[reliableWindow] > 0) {
  1301. --channel->reliableWindows[reliableWindow];
  1302. if (!channel->reliableWindows[reliableWindow])
  1303. channel->usedReliableWindows &= ~(1 << reliableWindow);
  1304. }
  1305. }
  1306. commandNumber = (ENetProtocolCommand)(outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK);
  1307. enet_list_remove(&outgoingCommand->outgoingCommandList);
  1308. if (outgoingCommand->packet != NULL) {
  1309. if (wasSent)
  1310. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  1311. --outgoingCommand->packet->referenceCount;
  1312. if (outgoingCommand->packet->referenceCount == 0) {
  1313. outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
  1314. enet_packet_destroy(outgoingCommand->packet);
  1315. }
  1316. }
  1317. enet_free(outgoingCommand);
  1318. if (enet_list_empty(&peer->sentReliableCommands))
  1319. return commandNumber;
  1320. outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentReliableCommands);
  1321. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  1322. return commandNumber;
  1323. }
  1324. static ENetPeer* enet_protocol_handle_connect(ENetHost* host, ENetProtocolHeader* header, ENetProtocol* command) {
  1325. uint8_t incomingSessionID, outgoingSessionID;
  1326. uint32_t mtu, windowSize;
  1327. ENetChannel* channel;
  1328. size_t channelCount, duplicatePeers = 0;
  1329. ENetPeer* currentPeer, *peer = NULL;
  1330. ENetProtocol verifyCommand;
  1331. channelCount = ENET_NET_TO_HOST_32(command->connect.channelCount);
  1332. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  1333. return NULL;
  1334. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  1335. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
  1336. if (peer == NULL)
  1337. peer = currentPeer;
  1338. } else if (currentPeer->state != ENET_PEER_STATE_CONNECTING && enet_in6_equal(currentPeer->address.ipv6, host->receivedAddress.ipv6)) {
  1339. if (currentPeer->address.port == host->receivedAddress.port && currentPeer->connectID == command->connect.connectID)
  1340. return NULL;
  1341. ++duplicatePeers;
  1342. }
  1343. }
  1344. if (peer == NULL || duplicatePeers >= host->duplicatePeers)
  1345. return NULL;
  1346. if (channelCount > host->channelLimit)
  1347. channelCount = host->channelLimit;
  1348. peer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  1349. if (peer->channels == NULL)
  1350. return NULL;
  1351. peer->channelCount = channelCount;
  1352. peer->state = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT;
  1353. peer->connectID = command->connect.connectID;
  1354. peer->address = host->receivedAddress;
  1355. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->connect.outgoingPeerID);
  1356. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->connect.incomingBandwidth);
  1357. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->connect.outgoingBandwidth);
  1358. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->connect.packetThrottleInterval);
  1359. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleAcceleration);
  1360. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleDeceleration);
  1361. peer->eventData = ENET_NET_TO_HOST_32(command->connect.data);
  1362. incomingSessionID = command->connect.incomingSessionID == 0xFF ? peer->outgoingSessionID : command->connect.incomingSessionID;
  1363. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1364. if (incomingSessionID == peer->outgoingSessionID)
  1365. incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1366. peer->outgoingSessionID = incomingSessionID;
  1367. outgoingSessionID = command->connect.outgoingSessionID == 0xFF ? peer->incomingSessionID : command->connect.outgoingSessionID;
  1368. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1369. if (outgoingSessionID == peer->incomingSessionID)
  1370. outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
  1371. peer->incomingSessionID = outgoingSessionID;
  1372. for (channel = peer->channels; channel < &peer->channels[channelCount]; ++channel) {
  1373. channel->outgoingReliableSequenceNumber = 0;
  1374. channel->outgoingUnreliableSequenceNumber = 0;
  1375. channel->incomingReliableSequenceNumber = 0;
  1376. channel->incomingUnreliableSequenceNumber = 0;
  1377. enet_list_clear(&channel->incomingReliableCommands);
  1378. enet_list_clear(&channel->incomingUnreliableCommands);
  1379. channel->usedReliableWindows = 0;
  1380. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  1381. }
  1382. mtu = ENET_NET_TO_HOST_32(command->connect.mtu);
  1383. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1384. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1385. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1386. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1387. peer->mtu = mtu;
  1388. if (host->outgoingBandwidth == 0 && peer->incomingBandwidth == 0)
  1389. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1390. else if (host->outgoingBandwidth == 0 || peer->incomingBandwidth == 0)
  1391. peer->windowSize = (ENET_MAX(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1392. else
  1393. peer->windowSize = (ENET_MIN(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1394. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1395. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1396. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1397. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1398. if (host->incomingBandwidth == 0)
  1399. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1400. else
  1401. windowSize = (host->incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1402. if (windowSize > ENET_NET_TO_HOST_32(command->connect.windowSize))
  1403. windowSize = ENET_NET_TO_HOST_32(command->connect.windowSize);
  1404. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1405. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1406. else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1407. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1408. verifyCommand.header.command = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  1409. verifyCommand.header.channelID = 0xFF;
  1410. verifyCommand.verifyConnect.outgoingPeerID = ENET_HOST_TO_NET_16(peer->incomingPeerID);
  1411. verifyCommand.verifyConnect.incomingSessionID = incomingSessionID;
  1412. verifyCommand.verifyConnect.outgoingSessionID = outgoingSessionID;
  1413. verifyCommand.verifyConnect.mtu = ENET_HOST_TO_NET_32(peer->mtu);
  1414. verifyCommand.verifyConnect.windowSize = ENET_HOST_TO_NET_32(windowSize);
  1415. verifyCommand.verifyConnect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  1416. verifyCommand.verifyConnect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  1417. verifyCommand.verifyConnect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  1418. verifyCommand.verifyConnect.packetThrottleInterval = ENET_HOST_TO_NET_32(peer->packetThrottleInterval);
  1419. verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(peer->packetThrottleAcceleration);
  1420. verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(peer->packetThrottleDeceleration);
  1421. verifyCommand.verifyConnect.connectID = peer->connectID;
  1422. enet_peer_queue_outgoing_command(peer, &verifyCommand, NULL, 0, 0);
  1423. return peer;
  1424. }
  1425. static int enet_protocol_handle_send_reliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1426. size_t dataLength;
  1427. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1428. return -1;
  1429. dataLength = ENET_NET_TO_HOST_16(command->sendReliable.dataLength);
  1430. *currentData += dataLength;
  1431. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
  1432. return -1;
  1433. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) == NULL)
  1434. return -1;
  1435. return 0;
  1436. }
  1437. static int enet_protocol_handle_send_unsequenced(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1438. uint32_t unsequencedGroup, index;
  1439. size_t dataLength;
  1440. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1441. return -1;
  1442. dataLength = ENET_NET_TO_HOST_16(command->sendUnsequenced.dataLength);
  1443. *currentData += dataLength;
  1444. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
  1445. return -1;
  1446. unsequencedGroup = ENET_NET_TO_HOST_16(command->sendUnsequenced.unsequencedGroup);
  1447. index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE;
  1448. if (unsequencedGroup < peer->incomingUnsequencedGroup)
  1449. unsequencedGroup += 0x10000;
  1450. if (unsequencedGroup >= (uint32_t)peer->incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE)
  1451. return 0;
  1452. unsequencedGroup &= 0xFFFF;
  1453. if (unsequencedGroup - index != peer->incomingUnsequencedGroup) {
  1454. peer->incomingUnsequencedGroup = unsequencedGroup - index;
  1455. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  1456. } else if (peer->unsequencedWindow[index / 32] & (1 << (index % 32))) {
  1457. return 0;
  1458. }
  1459. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED, 0) == NULL)
  1460. return -1;
  1461. peer->unsequencedWindow[index / 32] |= 1 << (index % 32);
  1462. return 0;
  1463. }
  1464. static int enet_protocol_handle_send_unreliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1465. size_t dataLength;
  1466. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1467. return -1;
  1468. dataLength = ENET_NET_TO_HOST_16(command->sendUnreliable.dataLength);
  1469. *currentData += dataLength;
  1470. if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
  1471. return -1;
  1472. if (enet_peer_queue_incoming_command(peer, command, (const uint8_t*)command + sizeof(ENetProtocolSendUnreliable), dataLength, 0, 0) == NULL)
  1473. return -1;
  1474. return 0;
  1475. }
  1476. static int enet_protocol_handle_send_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1477. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength;
  1478. ENetChannel* channel;
  1479. uint16_t startWindow, currentWindow;
  1480. ENetListIterator currentCommand;
  1481. ENetIncomingCommand* startCommand = NULL;
  1482. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1483. return -1;
  1484. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1485. *currentData += fragmentLength;
  1486. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
  1487. return -1;
  1488. channel = &peer->channels[command->header.channelID];
  1489. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1490. startWindow = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1491. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1492. if (startSequenceNumber < channel->incomingReliableSequenceNumber)
  1493. startWindow += ENET_PEER_RELIABLE_WINDOWS;
  1494. if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1495. return 0;
  1496. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1497. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1498. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1499. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1500. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
  1501. return -1;
  1502. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1503. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1504. if (startSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1505. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1506. continue;
  1507. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1508. break;
  1509. }
  1510. if (incomingCommand->reliableSequenceNumber <= startSequenceNumber) {
  1511. if (incomingCommand->reliableSequenceNumber < startSequenceNumber)
  1512. break;
  1513. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1514. return -1;
  1515. startCommand = incomingCommand;
  1516. break;
  1517. }
  1518. }
  1519. if (startCommand == NULL) {
  1520. ENetProtocol hostCommand = *command;
  1521. hostCommand.header.reliableSequenceNumber = startSequenceNumber;
  1522. startCommand = enet_peer_queue_incoming_command(peer, &hostCommand, NULL, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount);
  1523. if (startCommand == NULL)
  1524. return -1;
  1525. }
  1526. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1527. --startCommand->fragmentsRemaining;
  1528. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1529. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1530. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1531. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1532. if (startCommand->fragmentsRemaining <= 0)
  1533. enet_peer_dispatch_incoming_reliable_commands(peer, channel, NULL);
  1534. }
  1535. return 0;
  1536. }
  1537. static int enet_protocol_handle_send_unreliable_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, uint8_t** currentData) {
  1538. uint32_t fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength;
  1539. uint16_t reliableWindow, currentWindow;
  1540. ENetChannel* channel;
  1541. ENetListIterator currentCommand;
  1542. ENetIncomingCommand* startCommand = NULL;
  1543. if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
  1544. return -1;
  1545. fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
  1546. *currentData += fragmentLength;
  1547. if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
  1548. return -1;
  1549. channel = &peer->channels[command->header.channelID];
  1550. reliableSequenceNumber = command->header.reliableSequenceNumber;
  1551. startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
  1552. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1553. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  1554. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1555. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  1556. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  1557. return 0;
  1558. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && startSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  1559. return 0;
  1560. fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
  1561. fragmentCount = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
  1562. fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
  1563. totalLength = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
  1564. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
  1565. return -1;
  1566. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  1567. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  1568. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1569. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  1570. continue;
  1571. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  1572. break;
  1573. }
  1574. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  1575. break;
  1576. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  1577. continue;
  1578. if (incomingCommand->unreliableSequenceNumber <= startSequenceNumber) {
  1579. if (incomingCommand->unreliableSequenceNumber < startSequenceNumber)
  1580. break;
  1581. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
  1582. return -1;
  1583. startCommand = incomingCommand;
  1584. break;
  1585. }
  1586. }
  1587. if (startCommand == NULL) {
  1588. startCommand = enet_peer_queue_incoming_command(peer, command, NULL, totalLength, ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED, fragmentCount);
  1589. if (startCommand == NULL)
  1590. return -1;
  1591. }
  1592. if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
  1593. --startCommand->fragmentsRemaining;
  1594. startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
  1595. if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
  1596. fragmentLength = startCommand->packet->dataLength - fragmentOffset;
  1597. memcpy(startCommand->packet->data + fragmentOffset, (uint8_t*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
  1598. if (startCommand->fragmentsRemaining <= 0)
  1599. enet_peer_dispatch_incoming_unreliable_commands(peer, channel, NULL);
  1600. }
  1601. return 0;
  1602. }
  1603. static int enet_protocol_handle_ping(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1604. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1605. return -1;
  1606. return 0;
  1607. }
  1608. static int enet_protocol_handle_bandwidth_limit(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1609. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1610. return -1;
  1611. if (peer->incomingBandwidth != 0)
  1612. --host->bandwidthLimitedPeers;
  1613. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.incomingBandwidth);
  1614. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.outgoingBandwidth);
  1615. if (peer->incomingBandwidth != 0)
  1616. ++host->bandwidthLimitedPeers;
  1617. if (peer->incomingBandwidth == 0 && host->outgoingBandwidth == 0)
  1618. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1619. else if (peer->incomingBandwidth == 0 || host->outgoingBandwidth == 0)
  1620. peer->windowSize = (ENET_MAX(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1621. else
  1622. peer->windowSize = (ENET_MIN(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1623. if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1624. peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1625. else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1626. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1627. return 0;
  1628. }
  1629. static int enet_protocol_handle_throttle_configure(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1630. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  1631. return -1;
  1632. peer->packetThrottleInterval = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleInterval);
  1633. peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleAcceleration);
  1634. peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleDeceleration);
  1635. return 0;
  1636. }
  1637. static int enet_protocol_handle_disconnect(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
  1638. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT)
  1639. return 0;
  1640. enet_peer_reset_queues(peer);
  1641. if (peer->state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_CONNECTING) {
  1642. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1643. } else if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  1644. if (peer->state == ENET_PEER_STATE_CONNECTION_PENDING)
  1645. host->recalculateBandwidthLimits = 1;
  1646. enet_peer_reset(peer);
  1647. } else if (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  1648. enet_protocol_change_state(host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT);
  1649. } else {
  1650. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1651. }
  1652. if (peer->state != ENET_PEER_STATE_DISCONNECTED)
  1653. peer->eventData = ENET_NET_TO_HOST_32(command->disconnect.data);
  1654. return 0;
  1655. }
  1656. static int enet_protocol_handle_acknowledge(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1657. uint32_t roundTripTime, receivedSentTime, receivedReliableSequenceNumber;
  1658. ENetProtocolCommand commandNumber;
  1659. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE)
  1660. return 0;
  1661. receivedSentTime = ENET_NET_TO_HOST_16(command->acknowledge.receivedSentTime);
  1662. receivedSentTime |= host->serviceTime & 0xFFFF0000;
  1663. if ((receivedSentTime & 0x8000) > (host->serviceTime & 0x8000))
  1664. receivedSentTime -= 0x10000;
  1665. if (ENET_TIME_LESS(host->serviceTime, receivedSentTime))
  1666. return 0;
  1667. roundTripTime = ENET_TIME_DIFFERENCE(host->serviceTime, receivedSentTime);
  1668. if (roundTripTime == 0)
  1669. roundTripTime = 1;
  1670. enet_peer_throttle(peer, roundTripTime);
  1671. if (peer->lastReceiveTime > 0) {
  1672. if (roundTripTime >= peer->roundTripTime) {
  1673. uint32_t diff = roundTripTime - peer->roundTripTime;
  1674. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1675. peer->roundTripTimeVariance += diff / 4;
  1676. peer->roundTripTime += diff / 8;
  1677. } else {
  1678. uint32_t diff = peer->roundTripTime - roundTripTime;
  1679. if (diff <= peer->roundTripTimeVariance) {
  1680. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
  1681. peer->roundTripTimeVariance += diff / 4;
  1682. } else {
  1683. peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 32;
  1684. peer->roundTripTimeVariance += diff / 32;
  1685. }
  1686. peer->roundTripTime -= diff / 8;
  1687. }
  1688. } else {
  1689. peer->roundTripTime = roundTripTime;
  1690. peer->roundTripTimeVariance = roundTripTime / 2;
  1691. }
  1692. if (peer->roundTripTime < peer->lowestRoundTripTime)
  1693. peer->lowestRoundTripTime = peer->roundTripTime;
  1694. if (peer->roundTripTimeVariance > peer->highestRoundTripTimeVariance)
  1695. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1696. if (peer->packetThrottleEpoch == 0 || ENET_TIME_DIFFERENCE(host->serviceTime, peer->packetThrottleEpoch) >= peer->packetThrottleInterval) {
  1697. peer->lastRoundTripTime = peer->lowestRoundTripTime;
  1698. peer->lastRoundTripTimeVariance = peer->highestRoundTripTimeVariance;
  1699. peer->lowestRoundTripTime = peer->roundTripTime;
  1700. peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
  1701. peer->packetThrottleEpoch = host->serviceTime;
  1702. }
  1703. peer->lastReceiveTime = ENET_MAX(host->serviceTime, 1);
  1704. peer->earliestTimeout = 0;
  1705. receivedReliableSequenceNumber = ENET_NET_TO_HOST_16(command->acknowledge.receivedReliableSequenceNumber);
  1706. commandNumber = enet_protocol_remove_sent_reliable_command(peer, receivedReliableSequenceNumber, command->header.channelID);
  1707. switch (peer->state) {
  1708. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1709. if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT)
  1710. return -1;
  1711. enet_protocol_notify_connect(host, peer, event);
  1712. break;
  1713. case ENET_PEER_STATE_DISCONNECTING:
  1714. if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT)
  1715. return -1;
  1716. enet_protocol_notify_disconnect(host, peer, event);
  1717. break;
  1718. case ENET_PEER_STATE_DISCONNECT_LATER:
  1719. if (enet_list_empty(&peer->outgoingCommands) && enet_list_empty(&peer->sentReliableCommands))
  1720. enet_peer_disconnect(peer, peer->eventData);
  1721. break;
  1722. default:
  1723. break;
  1724. }
  1725. return 0;
  1726. }
  1727. static int enet_protocol_handle_verify_connect(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
  1728. uint32_t mtu, windowSize;
  1729. size_t channelCount;
  1730. if (peer->state != ENET_PEER_STATE_CONNECTING)
  1731. return 0;
  1732. channelCount = ENET_NET_TO_HOST_32(command->verifyConnect.channelCount);
  1733. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleInterval) != peer->packetThrottleInterval || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleAcceleration) != peer->packetThrottleAcceleration || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleDeceleration) != peer->packetThrottleDeceleration || command->verifyConnect.connectID != peer->connectID) {
  1734. peer->eventData = 0;
  1735. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1736. return -1;
  1737. }
  1738. enet_protocol_remove_sent_reliable_command(peer, 1, 0xFF);
  1739. if (channelCount < peer->channelCount)
  1740. peer->channelCount = channelCount;
  1741. peer->outgoingPeerID = ENET_NET_TO_HOST_16(command->verifyConnect.outgoingPeerID);
  1742. peer->incomingSessionID = command->verifyConnect.incomingSessionID;
  1743. peer->outgoingSessionID = command->verifyConnect.outgoingSessionID;
  1744. mtu = ENET_NET_TO_HOST_32(command->verifyConnect.mtu);
  1745. if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
  1746. mtu = ENET_PROTOCOL_MINIMUM_MTU;
  1747. else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
  1748. mtu = ENET_PROTOCOL_MAXIMUM_MTU;
  1749. if (mtu < peer->mtu)
  1750. peer->mtu = mtu;
  1751. windowSize = ENET_NET_TO_HOST_32(command->verifyConnect.windowSize);
  1752. if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  1753. windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  1754. if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  1755. windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  1756. if (windowSize < peer->windowSize)
  1757. peer->windowSize = windowSize;
  1758. peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.incomingBandwidth);
  1759. peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.outgoingBandwidth);
  1760. enet_protocol_notify_connect(host, peer, event);
  1761. return 0;
  1762. }
  1763. static int enet_protocol_handle_incoming_commands(ENetHost* host, ENetEvent* event) {
  1764. ENetProtocolHeader* header;
  1765. ENetProtocol* command;
  1766. ENetPeer* peer;
  1767. uint8_t* currentData;
  1768. size_t headerSize;
  1769. uint16_t peerID, flags;
  1770. uint8_t sessionID;
  1771. if (host->receivedDataLength < (size_t)&((ENetProtocolHeader*)0)->sentTime)
  1772. return 0;
  1773. header = (ENetProtocolHeader*)host->receivedData;
  1774. peerID = ENET_NET_TO_HOST_16(header->peerID);
  1775. sessionID = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  1776. flags = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK;
  1777. peerID &= ~(ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK);
  1778. headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof(ENetProtocolHeader) : (size_t)&((ENetProtocolHeader*)0)->sentTime);
  1779. if (host->checksumCallback != NULL)
  1780. headerSize += sizeof(uint32_t);
  1781. if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) {
  1782. peer = NULL;
  1783. } else if (peerID >= host->peerCount) {
  1784. return 0;
  1785. } else {
  1786. peer = &host->peers[peerID];
  1787. if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || ((!enet_in6_equal(host->receivedAddress.ipv6, peer->address.ipv6) || host->receivedAddress.port != peer->address.port) && peer->address.ipv4.ip.s_addr != INADDR_BROADCAST) || (peer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID && sessionID != peer->incomingSessionID))
  1788. return 0;
  1789. }
  1790. if (host->checksumCallback != NULL) {
  1791. uint32_t* checksum = (uint32_t*)&host->receivedData[headerSize - sizeof(uint32_t)];
  1792. uint32_t desiredChecksum = *checksum;
  1793. ENetBuffer buffer;
  1794. *checksum = peer != NULL ? peer->connectID : 0;
  1795. buffer.data = host->receivedData;
  1796. buffer.dataLength = host->receivedDataLength;
  1797. if (host->checksumCallback(&buffer, 1) != desiredChecksum)
  1798. return 0;
  1799. }
  1800. if (peer != NULL) {
  1801. peer->address.ipv6 = host->receivedAddress.ipv6;
  1802. peer->address.port = host->receivedAddress.port;
  1803. peer->incomingDataTotal += host->receivedDataLength;
  1804. peer->totalDataReceived += host->receivedDataLength;
  1805. }
  1806. currentData = host->receivedData + headerSize;
  1807. while (currentData < &host->receivedData[host->receivedDataLength]) {
  1808. uint8_t commandNumber;
  1809. size_t commandSize;
  1810. command = (ENetProtocol*)currentData;
  1811. if (currentData + sizeof(ENetProtocolCommandHeader) > &host->receivedData[host->receivedDataLength])
  1812. break;
  1813. commandNumber = command->header.command & ENET_PROTOCOL_COMMAND_MASK;
  1814. if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT)
  1815. break;
  1816. commandSize = commandSizes[commandNumber];
  1817. if (commandSize == 0 || currentData + commandSize > &host->receivedData[host->receivedDataLength])
  1818. break;
  1819. currentData += commandSize;
  1820. if (peer == NULL && (commandNumber != ENET_PROTOCOL_COMMAND_CONNECT || currentData < &host->receivedData[host->receivedDataLength]))
  1821. break;
  1822. command->header.reliableSequenceNumber = ENET_NET_TO_HOST_16(command->header.reliableSequenceNumber);
  1823. switch (commandNumber) {
  1824. case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE:
  1825. if (enet_protocol_handle_acknowledge(host, event, peer, command))
  1826. goto commandError;
  1827. break;
  1828. case ENET_PROTOCOL_COMMAND_CONNECT:
  1829. if (peer != NULL)
  1830. goto commandError;
  1831. if (host->preventConnections == 0) {
  1832. peer = enet_protocol_handle_connect(host, header, command);
  1833. if (peer == NULL)
  1834. goto commandError;
  1835. }
  1836. break;
  1837. case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT:
  1838. if (enet_protocol_handle_verify_connect(host, event, peer, command))
  1839. goto commandError;
  1840. break;
  1841. case ENET_PROTOCOL_COMMAND_DISCONNECT:
  1842. if (enet_protocol_handle_disconnect(host, peer, command))
  1843. goto commandError;
  1844. break;
  1845. case ENET_PROTOCOL_COMMAND_PING:
  1846. if (enet_protocol_handle_ping(host, peer, command))
  1847. goto commandError;
  1848. break;
  1849. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  1850. if (enet_protocol_handle_send_reliable(host, peer, command, &currentData))
  1851. goto commandError;
  1852. break;
  1853. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  1854. if (enet_protocol_handle_send_unreliable(host, peer, command, &currentData))
  1855. goto commandError;
  1856. break;
  1857. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  1858. if (enet_protocol_handle_send_unsequenced(host, peer, command, &currentData))
  1859. goto commandError;
  1860. break;
  1861. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  1862. if (enet_protocol_handle_send_fragment(host, peer, command, &currentData))
  1863. goto commandError;
  1864. break;
  1865. case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT:
  1866. if (enet_protocol_handle_bandwidth_limit(host, peer, command))
  1867. goto commandError;
  1868. break;
  1869. case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE:
  1870. if (enet_protocol_handle_throttle_configure(host, peer, command))
  1871. goto commandError;
  1872. break;
  1873. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  1874. if (enet_protocol_handle_send_unreliable_fragment(host, peer, command, &currentData))
  1875. goto commandError;
  1876. break;
  1877. default:
  1878. goto commandError;
  1879. }
  1880. if (peer != NULL && (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) {
  1881. uint16_t sentTime;
  1882. if (!(flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME))
  1883. break;
  1884. sentTime = ENET_NET_TO_HOST_16(header->sentTime);
  1885. switch (peer->state) {
  1886. case ENET_PEER_STATE_DISCONNECTING:
  1887. case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
  1888. case ENET_PEER_STATE_DISCONNECTED:
  1889. case ENET_PEER_STATE_ZOMBIE:
  1890. break;
  1891. case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
  1892. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  1893. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1894. break;
  1895. default:
  1896. enet_peer_queue_acknowledgement(peer, command, sentTime);
  1897. break;
  1898. }
  1899. }
  1900. }
  1901. commandError:
  1902. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  1903. return 1;
  1904. return 0;
  1905. }
  1906. static int enet_protocol_receive_incoming_commands(ENetHost* host, ENetEvent* event) {
  1907. int packets;
  1908. for (packets = 0; packets < 256; ++packets) {
  1909. int receivedLength;
  1910. ENetBuffer buffer;
  1911. buffer.data = host->packetData[0];
  1912. buffer.dataLength = host->mtu;
  1913. receivedLength = enet_socket_receive(host->socket, &host->receivedAddress, &buffer, 1);
  1914. if (receivedLength == -2)
  1915. continue;
  1916. if (receivedLength < 0)
  1917. return -1;
  1918. if (receivedLength == 0)
  1919. return 0;
  1920. host->receivedData = host->packetData[0];
  1921. host->receivedDataLength = receivedLength;
  1922. host->totalReceivedData += receivedLength;
  1923. host->totalReceivedPackets++;
  1924. if (host->interceptCallback != NULL) {
  1925. switch (host->interceptCallback(host, (void*)event)) {
  1926. case 1:
  1927. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  1928. return 1;
  1929. continue;
  1930. case -1:
  1931. return -1;
  1932. default:
  1933. break;
  1934. }
  1935. }
  1936. switch (enet_protocol_handle_incoming_commands(host, event)) {
  1937. case 1:
  1938. return 1;
  1939. case -1:
  1940. return -1;
  1941. default:
  1942. break;
  1943. }
  1944. }
  1945. return 0;
  1946. }
  1947. static void enet_protocol_send_acknowledgements(ENetHost* host, ENetPeer* peer) {
  1948. ENetProtocol* command = &host->commands[host->commandCount];
  1949. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  1950. ENetAcknowledgement* acknowledgement;
  1951. ENetListIterator currentAcknowledgement;
  1952. uint16_t reliableSequenceNumber;
  1953. currentAcknowledgement = enet_list_begin(&peer->acknowledgements);
  1954. while (currentAcknowledgement != enet_list_end(&peer->acknowledgements)) {
  1955. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < sizeof(ENetProtocolAcknowledge)) {
  1956. host->continueSending = 1;
  1957. break;
  1958. }
  1959. acknowledgement = (ENetAcknowledgement*)currentAcknowledgement;
  1960. currentAcknowledgement = enet_list_next(currentAcknowledgement);
  1961. buffer->data = command;
  1962. buffer->dataLength = sizeof(ENetProtocolAcknowledge);
  1963. host->packetSize += buffer->dataLength;
  1964. reliableSequenceNumber = ENET_HOST_TO_NET_16(acknowledgement->command.header.reliableSequenceNumber);
  1965. command->header.command = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
  1966. command->header.channelID = acknowledgement->command.header.channelID;
  1967. command->header.reliableSequenceNumber = reliableSequenceNumber;
  1968. command->acknowledge.receivedReliableSequenceNumber = reliableSequenceNumber;
  1969. command->acknowledge.receivedSentTime = ENET_HOST_TO_NET_16(acknowledgement->sentTime);
  1970. if ((acknowledgement->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
  1971. enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
  1972. enet_list_remove(&acknowledgement->acknowledgementList);
  1973. enet_free(acknowledgement);
  1974. ++command;
  1975. ++buffer;
  1976. }
  1977. host->commandCount = command - host->commands;
  1978. host->bufferCount = buffer - host->buffers;
  1979. }
  1980. static int enet_protocol_check_timeouts(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
  1981. ENetOutgoingCommand* outgoingCommand;
  1982. ENetListIterator currentCommand, insertPosition;
  1983. currentCommand = enet_list_begin(&peer->sentReliableCommands);
  1984. insertPosition = enet_list_begin(&peer->outgoingCommands);
  1985. while (currentCommand != enet_list_end(&peer->sentReliableCommands)) {
  1986. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  1987. currentCommand = enet_list_next(currentCommand);
  1988. if (ENET_TIME_DIFFERENCE(host->serviceTime, outgoingCommand->sentTime) < outgoingCommand->roundTripTimeout)
  1989. continue;
  1990. if (peer->earliestTimeout == 0 || ENET_TIME_LESS(outgoingCommand->sentTime, peer->earliestTimeout))
  1991. peer->earliestTimeout = outgoingCommand->sentTime;
  1992. if (peer->earliestTimeout != 0 && (ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMaximum || (outgoingCommand->roundTripTimeout >= outgoingCommand->roundTripTimeoutLimit && ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMinimum))) {
  1993. enet_protocol_notify_disconnect_timeout(host, peer, event);
  1994. return 1;
  1995. }
  1996. if (outgoingCommand->packet != NULL)
  1997. peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
  1998. ++peer->totalPacketsLost;
  1999. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2000. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2001. enet_list_insert(insertPosition, enet_list_remove(&outgoingCommand->outgoingCommandList));
  2002. if (currentCommand == enet_list_begin(&peer->sentReliableCommands) && !enet_list_empty(&peer->sentReliableCommands)) {
  2003. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2004. peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
  2005. }
  2006. }
  2007. return 0;
  2008. }
  2009. static int enet_protocol_check_outgoing_commands(ENetHost* host, ENetPeer* peer) {
  2010. ENetProtocol* command = &host->commands[host->commandCount];
  2011. ENetBuffer* buffer = &host->buffers[host->bufferCount];
  2012. ENetOutgoingCommand* outgoingCommand;
  2013. ENetListIterator currentCommand;
  2014. ENetChannel* channel;
  2015. uint16_t reliableWindow;
  2016. size_t commandSize;
  2017. int windowExceeded = 0, windowWrap = 0, canPing = 1;
  2018. currentCommand = enet_list_begin(&peer->outgoingCommands);
  2019. while (currentCommand != enet_list_end(&peer->outgoingCommands)) {
  2020. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2021. if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  2022. channel = outgoingCommand->command.header.channelID < peer->channelCount ? &peer->channels[outgoingCommand->command.header.channelID] : NULL;
  2023. reliableWindow = outgoingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2024. if (channel != NULL) {
  2025. if (!windowWrap && outgoingCommand->sendAttempts < 1 && !(outgoingCommand->reliableSequenceNumber % ENET_PEER_RELIABLE_WINDOW_SIZE) && (channel->reliableWindows[(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1) % ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE || channel->usedReliableWindows & ((((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) << reliableWindow) | (((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) >> (ENET_PEER_RELIABLE_WINDOWS - reliableWindow)))))
  2026. windowWrap = 1;
  2027. if (windowWrap) {
  2028. currentCommand = enet_list_next(currentCommand);
  2029. continue;
  2030. }
  2031. }
  2032. if (outgoingCommand->packet != NULL) {
  2033. if (!windowExceeded) {
  2034. uint32_t windowSize = (peer->packetThrottle * peer->windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE;
  2035. if (peer->reliableDataInTransit + outgoingCommand->fragmentLength > ENET_MAX(windowSize, peer->mtu))
  2036. windowExceeded = 1;
  2037. }
  2038. if (windowExceeded) {
  2039. currentCommand = enet_list_next(currentCommand);
  2040. continue;
  2041. }
  2042. }
  2043. canPing = 0;
  2044. }
  2045. commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
  2046. if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < commandSize || (outgoingCommand->packet != NULL && (uint16_t)(peer->mtu - host->packetSize) < (uint16_t)(commandSize + outgoingCommand->fragmentLength))) {
  2047. host->continueSending = 1;
  2048. break;
  2049. }
  2050. currentCommand = enet_list_next(currentCommand);
  2051. if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  2052. if (channel != NULL && outgoingCommand->sendAttempts < 1) {
  2053. channel->usedReliableWindows |= 1 << reliableWindow;
  2054. ++channel->reliableWindows[reliableWindow];
  2055. }
  2056. ++outgoingCommand->sendAttempts;
  2057. if (outgoingCommand->roundTripTimeout == 0) {
  2058. outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
  2059. outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
  2060. }
  2061. if (enet_list_empty(&peer->sentReliableCommands))
  2062. peer->nextTimeout = host->serviceTime + outgoingCommand->roundTripTimeout;
  2063. enet_list_insert(enet_list_end(&peer->sentReliableCommands),
  2064. enet_list_remove(&outgoingCommand->outgoingCommandList));
  2065. outgoingCommand->sentTime = host->serviceTime;
  2066. host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
  2067. peer->reliableDataInTransit += outgoingCommand->fragmentLength;
  2068. } else {
  2069. if (outgoingCommand->packet != NULL && outgoingCommand->fragmentOffset == 0) {
  2070. peer->packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER;
  2071. peer->packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE;
  2072. if (peer->packetThrottleCounter > peer->packetThrottle) {
  2073. uint16_t reliableSequenceNumber = outgoingCommand->reliableSequenceNumber,
  2074. unreliableSequenceNumber = outgoingCommand->unreliableSequenceNumber;
  2075. for (;;) {
  2076. --outgoingCommand->packet->referenceCount;
  2077. if (outgoingCommand->packet->referenceCount == 0)
  2078. enet_packet_destroy(outgoingCommand->packet);
  2079. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2080. enet_free(outgoingCommand);
  2081. if (currentCommand == enet_list_end(&peer->outgoingCommands))
  2082. break;
  2083. outgoingCommand = (ENetOutgoingCommand*)currentCommand;
  2084. if (outgoingCommand->reliableSequenceNumber != reliableSequenceNumber || outgoingCommand->unreliableSequenceNumber != unreliableSequenceNumber)
  2085. break;
  2086. currentCommand = enet_list_next(currentCommand);
  2087. }
  2088. continue;
  2089. }
  2090. }
  2091. enet_list_remove(&outgoingCommand->outgoingCommandList);
  2092. if (outgoingCommand->packet != NULL)
  2093. enet_list_insert(enet_list_end(&peer->sentUnreliableCommands), outgoingCommand);
  2094. }
  2095. buffer->data = command;
  2096. buffer->dataLength = commandSize;
  2097. host->packetSize += buffer->dataLength;
  2098. *command = outgoingCommand->command;
  2099. if (outgoingCommand->packet != NULL) {
  2100. ++buffer;
  2101. buffer->data = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
  2102. buffer->dataLength = outgoingCommand->fragmentLength;
  2103. host->packetSize += outgoingCommand->fragmentLength;
  2104. } else if (!(outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)) {
  2105. enet_free(outgoingCommand);
  2106. }
  2107. ++peer->totalPacketsSent;
  2108. ++command;
  2109. ++buffer;
  2110. }
  2111. host->commandCount = command - host->commands;
  2112. host->bufferCount = buffer - host->buffers;
  2113. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingCommands) && enet_list_empty(&peer->sentReliableCommands) && enet_list_empty(&peer->sentUnreliableCommands))
  2114. enet_peer_disconnect(peer, peer->eventData);
  2115. return canPing;
  2116. }
  2117. static int enet_protocol_send_outgoing_commands(ENetHost* host, ENetEvent* event, int checkForTimeouts) {
  2118. uint8_t headerData[sizeof(ENetProtocolHeader) + sizeof(uint32_t)];
  2119. ENetProtocolHeader* header = (ENetProtocolHeader*)headerData;
  2120. ENetPeer* currentPeer;
  2121. int sentLength;
  2122. host->continueSending = 1;
  2123. while (host->continueSending) {
  2124. for (host->continueSending = 0, currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2125. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED || currentPeer->state == ENET_PEER_STATE_ZOMBIE)
  2126. continue;
  2127. host->headerFlags = 0;
  2128. host->commandCount = 0;
  2129. host->bufferCount = 1;
  2130. host->packetSize = sizeof(ENetProtocolHeader);
  2131. if (!enet_list_empty(&currentPeer->acknowledgements))
  2132. enet_protocol_send_acknowledgements(host, currentPeer);
  2133. if (checkForTimeouts != 0 && !enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_GREATER_EQUAL(host->serviceTime, currentPeer->nextTimeout) && enet_protocol_check_timeouts(host, currentPeer, event) == 1) {
  2134. if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
  2135. return 1;
  2136. else
  2137. continue;
  2138. }
  2139. if ((enet_list_empty(&currentPeer->outgoingCommands) || enet_protocol_check_outgoing_commands(host, currentPeer)) && enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->lastReceiveTime) >= currentPeer->pingInterval && currentPeer->mtu - host->packetSize >= sizeof(ENetProtocolPing)) {
  2140. enet_peer_ping(currentPeer);
  2141. enet_protocol_check_outgoing_commands(host, currentPeer);
  2142. }
  2143. if (host->commandCount == 0)
  2144. continue;
  2145. host->buffers->data = headerData;
  2146. if (host->headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) {
  2147. header->sentTime = ENET_HOST_TO_NET_16(host->serviceTime & 0xFFFF);
  2148. host->buffers->dataLength = sizeof(ENetProtocolHeader);
  2149. } else {
  2150. host->buffers->dataLength = (size_t)&((ENetProtocolHeader*)0)->sentTime;
  2151. }
  2152. if (currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID)
  2153. host->headerFlags |= currentPeer->outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT;
  2154. header->peerID = ENET_HOST_TO_NET_16(currentPeer->outgoingPeerID | host->headerFlags);
  2155. if (host->checksumCallback != NULL) {
  2156. uint32_t* checksum = (uint32_t*)&headerData[host->buffers->dataLength];
  2157. *checksum = currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer->connectID : 0;
  2158. host->buffers->dataLength += sizeof(uint32_t);
  2159. *checksum = host->checksumCallback(host->buffers, host->bufferCount);
  2160. }
  2161. currentPeer->lastSendTime = host->serviceTime;
  2162. sentLength = enet_socket_send(host->socket, &currentPeer->address, host->buffers, host->bufferCount);
  2163. enet_protocol_remove_sent_unreliable_commands(currentPeer);
  2164. if (sentLength < 0)
  2165. return -1;
  2166. host->totalSentData += sentLength;
  2167. currentPeer->totalDataSent += sentLength;
  2168. host->totalSentPackets++;
  2169. }
  2170. }
  2171. return 0;
  2172. }
  2173. void enet_host_flush(ENetHost* host) {
  2174. host->serviceTime = enet_time_get();
  2175. enet_protocol_send_outgoing_commands(host, NULL, 0);
  2176. }
  2177. int enet_host_check_events(ENetHost* host, ENetEvent* event) {
  2178. if (event == NULL)
  2179. return -1;
  2180. event->type = ENET_EVENT_TYPE_NONE;
  2181. event->peer = NULL;
  2182. event->packet = NULL;
  2183. return enet_protocol_dispatch_incoming_commands(host, event);
  2184. }
  2185. int enet_host_service(ENetHost* host, ENetEvent* event, uint32_t timeout) {
  2186. uint32_t waitCondition;
  2187. if (event != NULL) {
  2188. event->type = ENET_EVENT_TYPE_NONE;
  2189. event->peer = NULL;
  2190. event->packet = NULL;
  2191. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2192. case 1:
  2193. return 1;
  2194. case -1:
  2195. #ifdef ENET_DEBUG
  2196. perror("Error dispatching incoming packets");
  2197. #endif
  2198. return -1;
  2199. default:
  2200. break;
  2201. }
  2202. }
  2203. host->serviceTime = enet_time_get();
  2204. timeout += host->serviceTime;
  2205. do {
  2206. if (ENET_TIME_DIFFERENCE(host->serviceTime, host->bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  2207. enet_host_bandwidth_throttle(host);
  2208. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2209. case 1:
  2210. return 1;
  2211. case -1:
  2212. #ifdef ENET_DEBUG
  2213. perror("Error sending outgoing packets");
  2214. #endif
  2215. return -1;
  2216. default:
  2217. break;
  2218. }
  2219. switch (enet_protocol_receive_incoming_commands(host, event)) {
  2220. case 1:
  2221. return 1;
  2222. case -1:
  2223. #ifdef ENET_DEBUG
  2224. perror("Error receiving incoming packets");
  2225. #endif
  2226. return -1;
  2227. default:
  2228. break;
  2229. }
  2230. switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
  2231. case 1:
  2232. return 1;
  2233. case -1:
  2234. #ifdef ENET_DEBUG
  2235. perror("Error sending outgoing packets");
  2236. #endif
  2237. return -1;
  2238. default:
  2239. break;
  2240. }
  2241. if (event != NULL) {
  2242. switch (enet_protocol_dispatch_incoming_commands(host, event)) {
  2243. case 1:
  2244. return 1;
  2245. case -1:
  2246. #ifdef ENET_DEBUG
  2247. perror("Error dispatching incoming packets");
  2248. #endif
  2249. return -1;
  2250. default:
  2251. break;
  2252. }
  2253. }
  2254. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2255. return 0;
  2256. do {
  2257. host->serviceTime = enet_time_get();
  2258. if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
  2259. return 0;
  2260. waitCondition = ENET_SOCKET_WAIT_RECEIVE | ENET_SOCKET_WAIT_INTERRUPT;
  2261. if (enet_socket_wait(host->socket, &waitCondition, ENET_TIME_DIFFERENCE(timeout, host->serviceTime)) != 0)
  2262. return -1;
  2263. }
  2264. while (waitCondition & ENET_SOCKET_WAIT_INTERRUPT);
  2265. host->serviceTime = enet_time_get();
  2266. }
  2267. while (waitCondition & ENET_SOCKET_WAIT_RECEIVE);
  2268. return 0;
  2269. }
  2270. /*
  2271. =======================================================================
  2272. Peer
  2273. =======================================================================
  2274. */
  2275. void enet_peer_throttle_configure(ENetPeer* peer, uint32_t interval, uint32_t acceleration, uint32_t deceleration, uint32_t threshold) {
  2276. ENetProtocol command;
  2277. peer->packetThrottleThreshold = threshold;
  2278. peer->packetThrottleInterval = interval;
  2279. peer->packetThrottleAcceleration = acceleration;
  2280. peer->packetThrottleDeceleration = deceleration;
  2281. command.header.command = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2282. command.header.channelID = 0xFF;
  2283. command.throttleConfigure.packetThrottleInterval = ENET_HOST_TO_NET_32(interval);
  2284. command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32(acceleration);
  2285. command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32(deceleration);
  2286. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2287. }
  2288. int enet_peer_throttle(ENetPeer* peer, uint32_t rtt) {
  2289. if (peer->lastRoundTripTime <= peer->lastRoundTripTimeVariance) {
  2290. peer->packetThrottle = peer->packetThrottleLimit;
  2291. } else if (rtt < peer->lastRoundTripTime + (peer -> lastRoundTripTimeVariance + 1) / 2) {
  2292. peer->packetThrottle += peer->packetThrottleAcceleration;
  2293. if (peer->packetThrottle > peer->packetThrottleLimit)
  2294. peer->packetThrottle = peer->packetThrottleLimit;
  2295. return 1;
  2296. } else if (rtt > peer->lastRoundTripTime + peer->packetThrottleThreshold + 2 * peer->lastRoundTripTimeVariance) {
  2297. if (peer->packetThrottle > peer->packetThrottleDeceleration)
  2298. peer->packetThrottle -= peer->packetThrottleDeceleration;
  2299. else
  2300. peer->packetThrottle = 0;
  2301. return -1;
  2302. }
  2303. return 0;
  2304. }
  2305. int enet_peer_send(ENetPeer* peer, uint8_t channelID, ENetPacket* packet) {
  2306. ENetChannel* channel = &peer->channels[channelID];
  2307. ENetProtocol command;
  2308. size_t fragmentLength;
  2309. if (peer->state != ENET_PEER_STATE_CONNECTED || channelID >= peer->channelCount || packet->dataLength > peer->host->maximumPacketSize)
  2310. return -1;
  2311. fragmentLength = peer->mtu - sizeof(ENetProtocolHeader) - sizeof(ENetProtocolSendFragment);
  2312. if (peer->host->checksumCallback != NULL)
  2313. fragmentLength -= sizeof(uint32_t);
  2314. if (packet->dataLength > fragmentLength) {
  2315. uint32_t fragmentCount = (packet->dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset;
  2316. uint8_t commandNumber;
  2317. uint16_t startSequenceNumber;
  2318. ENetList fragments;
  2319. ENetOutgoingCommand* fragment;
  2320. if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
  2321. return -1;
  2322. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED)) == ENET_PACKET_FLAG_UNRELIABLE_FRAGMENTED && channel->outgoingUnreliableSequenceNumber < 0xFFFF) {
  2323. commandNumber = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
  2324. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingUnreliableSequenceNumber + 1);
  2325. } else {
  2326. commandNumber = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2327. startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingReliableSequenceNumber + 1);
  2328. }
  2329. enet_list_clear(&fragments);
  2330. for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet->dataLength; ++fragmentNumber, fragmentOffset += fragmentLength) {
  2331. if (packet->dataLength - fragmentOffset < fragmentLength)
  2332. fragmentLength = packet->dataLength - fragmentOffset;
  2333. fragment = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2334. if (fragment == NULL) {
  2335. while (!enet_list_empty(&fragments)) {
  2336. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2337. enet_free(fragment);
  2338. }
  2339. return -1;
  2340. }
  2341. fragment->fragmentOffset = fragmentOffset;
  2342. fragment->fragmentLength = fragmentLength;
  2343. fragment->packet = packet;
  2344. fragment->command.header.command = commandNumber;
  2345. fragment->command.header.channelID = channelID;
  2346. fragment->command.sendFragment.startSequenceNumber = startSequenceNumber;
  2347. fragment->command.sendFragment.dataLength = ENET_HOST_TO_NET_16(fragmentLength);
  2348. fragment->command.sendFragment.fragmentCount = ENET_HOST_TO_NET_32(fragmentCount);
  2349. fragment->command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32(fragmentNumber);
  2350. fragment->command.sendFragment.totalLength = ENET_HOST_TO_NET_32(packet->dataLength);
  2351. fragment->command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32(fragmentOffset);
  2352. enet_list_insert(enet_list_end(&fragments), fragment);
  2353. }
  2354. packet->referenceCount += fragmentNumber;
  2355. while (!enet_list_empty(&fragments)) {
  2356. fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
  2357. enet_peer_setup_outgoing_command(peer, fragment);
  2358. }
  2359. return 0;
  2360. }
  2361. command.header.channelID = channelID;
  2362. if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) {
  2363. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2364. command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2365. } else if (packet->flags & ENET_PACKET_FLAG_RELIABLE || channel->outgoingUnreliableSequenceNumber >= 0xFFFF) {
  2366. command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2367. command.sendReliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2368. } else {
  2369. command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
  2370. command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
  2371. }
  2372. if (enet_peer_queue_outgoing_command(peer, &command, packet, 0, packet->dataLength) == NULL)
  2373. return -1;
  2374. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  2375. enet_host_flush(peer->host);
  2376. return 0;
  2377. }
  2378. ENetPacket* enet_peer_receive(ENetPeer* peer, uint8_t* channelID) {
  2379. ENetIncomingCommand* incomingCommand;
  2380. ENetPacket* packet;
  2381. if (enet_list_empty(&peer->dispatchedCommands))
  2382. return NULL;
  2383. incomingCommand = (ENetIncomingCommand*)enet_list_remove(enet_list_begin(&peer->dispatchedCommands));
  2384. if (channelID != NULL)
  2385. *channelID = incomingCommand->command.header.channelID;
  2386. packet = incomingCommand->packet;
  2387. --packet->referenceCount;
  2388. if (incomingCommand->fragments != NULL)
  2389. enet_free(incomingCommand->fragments);
  2390. enet_free(incomingCommand);
  2391. peer->totalWaitingData -= packet->dataLength;
  2392. return packet;
  2393. }
  2394. static void enet_peer_reset_outgoing_commands(ENetList* queue) {
  2395. ENetOutgoingCommand* outgoingCommand;
  2396. while (!enet_list_empty(queue)) {
  2397. outgoingCommand = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(queue));
  2398. if (outgoingCommand->packet != NULL) {
  2399. --outgoingCommand->packet->referenceCount;
  2400. if (outgoingCommand->packet->referenceCount == 0)
  2401. enet_packet_destroy(outgoingCommand->packet);
  2402. }
  2403. enet_free(outgoingCommand);
  2404. }
  2405. }
  2406. static void enet_peer_remove_incoming_commands(ENetList* queue, ENetListIterator startCommand, ENetListIterator endCommand, ENetIncomingCommand* excludeCommand) {
  2407. ENetListIterator currentCommand;
  2408. for (currentCommand = startCommand; currentCommand != endCommand;) {
  2409. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2410. currentCommand = enet_list_next(currentCommand);
  2411. if (incomingCommand == excludeCommand)
  2412. continue;
  2413. enet_list_remove(&incomingCommand->incomingCommandList);
  2414. if (incomingCommand->packet != NULL) {
  2415. --incomingCommand->packet->referenceCount;
  2416. if (incomingCommand->packet->referenceCount == 0)
  2417. enet_packet_destroy(incomingCommand->packet);
  2418. }
  2419. if (incomingCommand->fragments != NULL)
  2420. enet_free(incomingCommand->fragments);
  2421. enet_free(incomingCommand);
  2422. }
  2423. }
  2424. static void enet_peer_reset_incoming_commands(ENetList* queue) {
  2425. enet_peer_remove_incoming_commands(queue, enet_list_begin(queue), enet_list_end(queue), NULL);
  2426. }
  2427. void enet_peer_reset_queues(ENetPeer* peer) {
  2428. ENetChannel* channel;
  2429. if (peer->needsDispatch) {
  2430. enet_list_remove(&peer->dispatchList);
  2431. peer->needsDispatch = 0;
  2432. }
  2433. while (!enet_list_empty(&peer->acknowledgements)) {
  2434. enet_free(enet_list_remove(enet_list_begin(&peer->acknowledgements)));
  2435. }
  2436. enet_peer_reset_outgoing_commands(&peer->sentReliableCommands);
  2437. enet_peer_reset_outgoing_commands(&peer->sentUnreliableCommands);
  2438. enet_peer_reset_outgoing_commands(&peer->outgoingCommands);
  2439. enet_peer_reset_incoming_commands(&peer->dispatchedCommands);
  2440. if (peer->channels != NULL && peer->channelCount > 0) {
  2441. for (channel = peer->channels; channel < &peer->channels[peer->channelCount]; ++channel) {
  2442. enet_peer_reset_incoming_commands(&channel->incomingReliableCommands);
  2443. enet_peer_reset_incoming_commands(&channel->incomingUnreliableCommands);
  2444. }
  2445. enet_free(peer->channels);
  2446. }
  2447. peer->channels = NULL;
  2448. peer->channelCount = 0;
  2449. }
  2450. void enet_peer_on_connect(ENetPeer* peer) {
  2451. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
  2452. if (peer->incomingBandwidth != 0)
  2453. ++peer->host->bandwidthLimitedPeers;
  2454. ++peer->host->connectedPeers;
  2455. }
  2456. }
  2457. void enet_peer_on_disconnect(ENetPeer* peer) {
  2458. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2459. if (peer->incomingBandwidth != 0)
  2460. --peer->host->bandwidthLimitedPeers;
  2461. --peer->host->connectedPeers;
  2462. }
  2463. }
  2464. void enet_peer_reset(ENetPeer* peer) {
  2465. enet_peer_on_disconnect(peer);
  2466. peer->outgoingPeerID = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  2467. peer->state = ENET_PEER_STATE_DISCONNECTED;
  2468. peer->incomingBandwidth = 0;
  2469. peer->outgoingBandwidth = 0;
  2470. peer->incomingBandwidthThrottleEpoch = 0;
  2471. peer->outgoingBandwidthThrottleEpoch = 0;
  2472. peer->incomingDataTotal = 0;
  2473. peer->totalDataReceived = 0;
  2474. peer->outgoingDataTotal = 0;
  2475. peer->totalDataSent = 0;
  2476. peer->lastSendTime = 0;
  2477. peer->lastReceiveTime = 0;
  2478. peer->nextTimeout = 0;
  2479. peer->earliestTimeout = 0;
  2480. peer->totalPacketsSent = 0;
  2481. peer->totalPacketsLost = 0;
  2482. peer->packetThrottle = ENET_PEER_DEFAULT_PACKET_THROTTLE;
  2483. peer->packetThrottleThreshold = ENET_PEER_PACKET_THROTTLE_THRESHOLD;
  2484. peer->packetThrottleLimit = ENET_PEER_PACKET_THROTTLE_SCALE;
  2485. peer->packetThrottleCounter = 0;
  2486. peer->packetThrottleEpoch = 0;
  2487. peer->packetThrottleAcceleration = ENET_PEER_PACKET_THROTTLE_ACCELERATION;
  2488. peer->packetThrottleDeceleration = ENET_PEER_PACKET_THROTTLE_DECELERATION;
  2489. peer->packetThrottleInterval = ENET_PEER_PACKET_THROTTLE_INTERVAL;
  2490. peer->pingInterval = ENET_PEER_PING_INTERVAL;
  2491. peer->timeoutLimit = ENET_PEER_TIMEOUT_LIMIT;
  2492. peer->timeoutMinimum = ENET_PEER_TIMEOUT_MINIMUM;
  2493. peer->timeoutMaximum = ENET_PEER_TIMEOUT_MAXIMUM;
  2494. peer->lastRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2495. peer->lowestRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
  2496. peer->lastRoundTripTimeVariance = 0;
  2497. peer->highestRoundTripTimeVariance = 0;
  2498. peer->roundTripTime = 1;
  2499. peer->roundTripTimeVariance = 0;
  2500. peer->mtu = peer->host->mtu;
  2501. peer->reliableDataInTransit = 0;
  2502. peer->outgoingReliableSequenceNumber = 0;
  2503. peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2504. peer->incomingUnsequencedGroup = 0;
  2505. peer->outgoingUnsequencedGroup = 0;
  2506. peer->eventData = 0;
  2507. peer->totalWaitingData = 0;
  2508. memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
  2509. enet_peer_reset_queues(peer);
  2510. }
  2511. void enet_peer_ping(ENetPeer* peer) {
  2512. ENetProtocol command;
  2513. if (peer->state != ENET_PEER_STATE_CONNECTED)
  2514. return;
  2515. command.header.command = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2516. command.header.channelID = 0xFF;
  2517. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2518. }
  2519. void enet_peer_ping_interval(ENetPeer* peer, uint32_t pingInterval) {
  2520. peer->pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL;
  2521. }
  2522. void enet_peer_timeout(ENetPeer* peer, uint32_t timeoutLimit, uint32_t timeoutMinimum, uint32_t timeoutMaximum) {
  2523. peer->timeoutLimit = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT;
  2524. peer->timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM;
  2525. peer->timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM;
  2526. }
  2527. void enet_peer_disconnect_now(ENetPeer* peer, uint32_t data) {
  2528. ENetProtocol command;
  2529. if (peer->state == ENET_PEER_STATE_DISCONNECTED)
  2530. return;
  2531. if (peer->state != ENET_PEER_STATE_ZOMBIE && peer->state != ENET_PEER_STATE_DISCONNECTING) {
  2532. enet_peer_reset_queues(peer);
  2533. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2534. command.header.channelID = 0xFF;
  2535. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2536. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2537. enet_host_flush(peer->host);
  2538. }
  2539. enet_peer_reset(peer);
  2540. }
  2541. void enet_peer_disconnect(ENetPeer* peer, uint32_t data) {
  2542. ENetProtocol command;
  2543. if (peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT || peer->state == ENET_PEER_STATE_ZOMBIE)
  2544. return;
  2545. enet_peer_reset_queues(peer);
  2546. command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT;
  2547. command.header.channelID = 0xFF;
  2548. command.disconnect.data = ENET_HOST_TO_NET_32(data);
  2549. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2550. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2551. else
  2552. command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
  2553. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  2554. if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
  2555. enet_peer_on_disconnect(peer);
  2556. peer->state = ENET_PEER_STATE_DISCONNECTING;
  2557. } else {
  2558. enet_host_flush(peer->host);
  2559. enet_peer_reset(peer);
  2560. }
  2561. }
  2562. void enet_peer_disconnect_later(ENetPeer* peer, uint32_t data) {
  2563. if ((peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) && !(enet_list_empty(&peer->outgoingCommands) && enet_list_empty(&peer->sentReliableCommands))) {
  2564. peer->state = ENET_PEER_STATE_DISCONNECT_LATER;
  2565. peer->eventData = data;
  2566. } else {
  2567. enet_peer_disconnect(peer, data);
  2568. }
  2569. }
  2570. ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer* peer, const ENetProtocol* command, uint16_t sentTime) {
  2571. ENetAcknowledgement* acknowledgement;
  2572. if (command->header.channelID < peer->channelCount) {
  2573. ENetChannel* channel = &peer->channels[command->header.channelID];
  2574. uint16_t reliableWindow = command->header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2575. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2576. if (command->header.reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2577. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2578. if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS)
  2579. return NULL;
  2580. }
  2581. acknowledgement = (ENetAcknowledgement*)enet_malloc(sizeof(ENetAcknowledgement));
  2582. if (acknowledgement == NULL)
  2583. return NULL;
  2584. peer->outgoingDataTotal += sizeof(ENetProtocolAcknowledge);
  2585. acknowledgement->sentTime = sentTime;
  2586. acknowledgement->command = *command;
  2587. enet_list_insert(enet_list_end(&peer->acknowledgements), acknowledgement);
  2588. return acknowledgement;
  2589. }
  2590. void enet_peer_setup_outgoing_command(ENetPeer* peer, ENetOutgoingCommand* outgoingCommand) {
  2591. ENetChannel* channel = &peer->channels[outgoingCommand->command.header.channelID];
  2592. peer->outgoingDataTotal += enet_protocol_command_size(outgoingCommand->command.header.command) + outgoingCommand->fragmentLength;
  2593. if (outgoingCommand->command.header.channelID == 0xFF) {
  2594. ++peer->outgoingReliableSequenceNumber;
  2595. outgoingCommand->reliableSequenceNumber = peer->outgoingReliableSequenceNumber;
  2596. outgoingCommand->unreliableSequenceNumber = 0;
  2597. } else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
  2598. ++channel->outgoingReliableSequenceNumber;
  2599. channel->outgoingUnreliableSequenceNumber = 0;
  2600. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2601. outgoingCommand->unreliableSequenceNumber = 0;
  2602. } else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) {
  2603. ++peer->outgoingUnsequencedGroup;
  2604. outgoingCommand->reliableSequenceNumber = 0;
  2605. outgoingCommand->unreliableSequenceNumber = 0;
  2606. } else {
  2607. if (outgoingCommand->fragmentOffset == 0)
  2608. ++channel->outgoingUnreliableSequenceNumber;
  2609. outgoingCommand->reliableSequenceNumber = channel->outgoingReliableSequenceNumber;
  2610. outgoingCommand->unreliableSequenceNumber = channel->outgoingUnreliableSequenceNumber;
  2611. }
  2612. outgoingCommand->sendAttempts = 0;
  2613. outgoingCommand->sentTime = 0;
  2614. outgoingCommand->roundTripTimeout = 0;
  2615. outgoingCommand->roundTripTimeoutLimit = 0;
  2616. outgoingCommand->command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->reliableSequenceNumber);
  2617. switch (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2618. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2619. outgoingCommand->command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->unreliableSequenceNumber);
  2620. break;
  2621. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2622. outgoingCommand->command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16(peer->outgoingUnsequencedGroup);
  2623. break;
  2624. default:
  2625. break;
  2626. }
  2627. enet_list_insert(enet_list_end(&peer->outgoingCommands), outgoingCommand);
  2628. }
  2629. ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer* peer, const ENetProtocol* command, ENetPacket* packet, uint32_t offset, uint16_t length) {
  2630. ENetOutgoingCommand* outgoingCommand = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
  2631. if (outgoingCommand == NULL)
  2632. return NULL;
  2633. outgoingCommand->command = *command;
  2634. outgoingCommand->fragmentOffset = offset;
  2635. outgoingCommand->fragmentLength = length;
  2636. outgoingCommand->packet = packet;
  2637. if (packet != NULL)
  2638. ++packet->referenceCount;
  2639. enet_peer_setup_outgoing_command(peer, outgoingCommand);
  2640. return outgoingCommand;
  2641. }
  2642. void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer* peer, ENetChannel* channel, ENetIncomingCommand* queuedCommand) {
  2643. ENetListIterator droppedCommand, startCommand, currentCommand;
  2644. for (droppedCommand = startCommand = currentCommand = enet_list_begin(&channel->incomingUnreliableCommands); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2645. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2646. if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2647. continue;
  2648. if (incomingCommand->reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
  2649. if (incomingCommand->fragmentsRemaining <= 0) {
  2650. channel->incomingUnreliableSequenceNumber = incomingCommand->unreliableSequenceNumber;
  2651. continue;
  2652. }
  2653. if (startCommand != currentCommand) {
  2654. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2655. if (!peer->needsDispatch) {
  2656. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2657. peer->needsDispatch = 1;
  2658. }
  2659. droppedCommand = currentCommand;
  2660. } else if (droppedCommand != currentCommand) {
  2661. droppedCommand = enet_list_previous(currentCommand);
  2662. }
  2663. } else {
  2664. uint16_t reliableWindow = incomingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2665. uint16_t currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2666. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2667. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2668. if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2669. break;
  2670. droppedCommand = enet_list_next(currentCommand);
  2671. if (startCommand != currentCommand) {
  2672. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2673. if (!peer->needsDispatch) {
  2674. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2675. peer->needsDispatch = 1;
  2676. }
  2677. }
  2678. }
  2679. startCommand = enet_list_next(currentCommand);
  2680. }
  2681. if (startCommand != currentCommand) {
  2682. enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
  2683. if (!peer->needsDispatch) {
  2684. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2685. peer->needsDispatch = 1;
  2686. }
  2687. droppedCommand = currentCommand;
  2688. }
  2689. enet_peer_remove_incoming_commands(&channel->incomingUnreliableCommands, enet_list_begin(&channel->incomingUnreliableCommands), droppedCommand, queuedCommand);
  2690. }
  2691. void enet_peer_dispatch_incoming_reliable_commands(ENetPeer* peer, ENetChannel* channel, ENetIncomingCommand* queuedCommand) {
  2692. ENetListIterator currentCommand;
  2693. for (currentCommand = enet_list_begin(&channel->incomingReliableCommands); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
  2694. ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
  2695. if (incomingCommand->fragmentsRemaining > 0 || incomingCommand->reliableSequenceNumber != (uint16_t)(channel->incomingReliableSequenceNumber + 1))
  2696. break;
  2697. channel->incomingReliableSequenceNumber = incomingCommand->reliableSequenceNumber;
  2698. if (incomingCommand->fragmentCount > 0)
  2699. channel->incomingReliableSequenceNumber += incomingCommand->fragmentCount - 1;
  2700. }
  2701. if (currentCommand == enet_list_begin(&channel->incomingReliableCommands))
  2702. return;
  2703. channel->incomingUnreliableSequenceNumber = 0;
  2704. enet_list_move(enet_list_end(&peer->dispatchedCommands), enet_list_begin(&channel->incomingReliableCommands), enet_list_previous(currentCommand));
  2705. if (!peer->needsDispatch) {
  2706. enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
  2707. peer->needsDispatch = 1;
  2708. }
  2709. if (!enet_list_empty(&channel->incomingUnreliableCommands))
  2710. enet_peer_dispatch_incoming_unreliable_commands(peer, channel, queuedCommand);
  2711. }
  2712. ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer* peer, const ENetProtocol* command, const void* data, size_t dataLength, uint32_t flags, uint32_t fragmentCount) {
  2713. static ENetIncomingCommand dummyCommand;
  2714. ENetChannel* channel = &peer->channels[command->header.channelID];
  2715. uint32_t unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
  2716. uint16_t reliableWindow, currentWindow;
  2717. ENetIncomingCommand* incomingCommand;
  2718. ENetListIterator currentCommand;
  2719. ENetPacket* packet = NULL;
  2720. if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
  2721. goto discardCommand;
  2722. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
  2723. reliableSequenceNumber = command->header.reliableSequenceNumber;
  2724. reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2725. currentWindow = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
  2726. if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2727. reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
  2728. if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
  2729. goto discardCommand;
  2730. }
  2731. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2732. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2733. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2734. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber)
  2735. goto discardCommand;
  2736. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2737. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2738. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2739. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2740. continue;
  2741. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2742. break;
  2743. }
  2744. if (incomingCommand->reliableSequenceNumber <= reliableSequenceNumber) {
  2745. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2746. break;
  2747. goto discardCommand;
  2748. }
  2749. }
  2750. break;
  2751. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
  2752. case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
  2753. unreliableSequenceNumber = ENET_NET_TO_HOST_16(command->sendUnreliable.unreliableSequenceNumber);
  2754. if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && unreliableSequenceNumber <= channel->incomingUnreliableSequenceNumber)
  2755. goto discardCommand;
  2756. for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
  2757. incomingCommand = (ENetIncomingCommand*)currentCommand;
  2758. if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
  2759. continue;
  2760. if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2761. if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
  2762. continue;
  2763. } else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
  2764. break;
  2765. }
  2766. if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
  2767. break;
  2768. if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
  2769. continue;
  2770. if (incomingCommand->unreliableSequenceNumber <= unreliableSequenceNumber) {
  2771. if (incomingCommand->unreliableSequenceNumber < unreliableSequenceNumber)
  2772. break;
  2773. goto discardCommand;
  2774. }
  2775. }
  2776. break;
  2777. case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
  2778. currentCommand = enet_list_end(&channel->incomingUnreliableCommands);
  2779. break;
  2780. default:
  2781. goto discardCommand;
  2782. }
  2783. if (peer->totalWaitingData >= peer->host->maximumWaitingData)
  2784. goto notifyError;
  2785. packet = enet_packet_create(data, dataLength, flags);
  2786. if (packet == NULL)
  2787. goto notifyError;
  2788. incomingCommand = (ENetIncomingCommand*)enet_malloc(sizeof(ENetIncomingCommand));
  2789. if (incomingCommand == NULL)
  2790. goto notifyError;
  2791. incomingCommand->reliableSequenceNumber = command->header.reliableSequenceNumber;
  2792. incomingCommand->unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF;
  2793. incomingCommand->command = *command;
  2794. incomingCommand->fragmentCount = fragmentCount;
  2795. incomingCommand->fragmentsRemaining = fragmentCount;
  2796. incomingCommand->packet = packet;
  2797. incomingCommand->fragments = NULL;
  2798. if (fragmentCount > 0) {
  2799. if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
  2800. incomingCommand->fragments = (uint32_t*)enet_malloc((fragmentCount + 31) / 32 * sizeof(uint32_t));
  2801. if (incomingCommand->fragments == NULL) {
  2802. enet_free(incomingCommand);
  2803. goto notifyError;
  2804. }
  2805. memset(incomingCommand->fragments, 0, (fragmentCount + 31) / 32 * sizeof(uint32_t));
  2806. }
  2807. if (packet != NULL) {
  2808. ++packet->referenceCount;
  2809. peer->totalWaitingData += packet->dataLength;
  2810. }
  2811. enet_list_insert(enet_list_next(currentCommand), incomingCommand);
  2812. switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
  2813. case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
  2814. case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
  2815. enet_peer_dispatch_incoming_reliable_commands(peer, channel, incomingCommand);
  2816. break;
  2817. default:
  2818. enet_peer_dispatch_incoming_unreliable_commands(peer, channel, incomingCommand);
  2819. break;
  2820. }
  2821. return incomingCommand;
  2822. discardCommand:
  2823. if (fragmentCount > 0)
  2824. goto notifyError;
  2825. if (packet != NULL && packet->referenceCount == 0)
  2826. enet_packet_destroy(packet);
  2827. return &dummyCommand;
  2828. notifyError:
  2829. if (packet != NULL && packet->referenceCount == 0)
  2830. enet_packet_destroy(packet);
  2831. return NULL;
  2832. }
  2833. /*
  2834. =======================================================================
  2835. Host
  2836. =======================================================================
  2837. */
  2838. ENetHost* enet_host_create(const ENetAddress* address, size_t peerCount, size_t channelLimit, uint32_t incomingBandwidth, uint32_t outgoingBandwidth, int bufferSize) {
  2839. ENetHost* host;
  2840. ENetPeer* currentPeer;
  2841. if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID)
  2842. return NULL;
  2843. host = (ENetHost*)enet_malloc(sizeof(ENetHost));
  2844. if (host == NULL)
  2845. return NULL;
  2846. memset(host, 0, sizeof(ENetHost));
  2847. host->peers = (ENetPeer*)enet_malloc(peerCount * sizeof(ENetPeer));
  2848. if (host->peers == NULL) {
  2849. enet_free(host);
  2850. return NULL;
  2851. }
  2852. memset(host->peers, 0, peerCount * sizeof(ENetPeer));
  2853. host->socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
  2854. if (host->socket != ENET_SOCKET_NULL)
  2855. enet_socket_set_option(host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
  2856. if (host->socket == ENET_SOCKET_NULL || (address != NULL && enet_socket_bind(host->socket, address) < 0)) {
  2857. if (host->socket != ENET_SOCKET_NULL)
  2858. enet_socket_destroy(host->socket);
  2859. enet_free(host->peers);
  2860. enet_free(host);
  2861. return NULL;
  2862. }
  2863. if (bufferSize > ENET_HOST_BUFFER_SIZE_MAX)
  2864. bufferSize = ENET_HOST_BUFFER_SIZE_MAX;
  2865. else if (bufferSize < ENET_HOST_BUFFER_SIZE_MIN)
  2866. bufferSize = ENET_HOST_BUFFER_SIZE_MIN;
  2867. enet_socket_set_option(host->socket, ENET_SOCKOPT_NONBLOCK, 1);
  2868. enet_socket_set_option(host->socket, ENET_SOCKOPT_BROADCAST, 1);
  2869. enet_socket_set_option(host->socket, ENET_SOCKOPT_RCVBUF, bufferSize);
  2870. enet_socket_set_option(host->socket, ENET_SOCKOPT_SNDBUF, bufferSize);
  2871. if (address != NULL && enet_socket_get_address(host->socket, &host->address) < 0)
  2872. host->address = *address;
  2873. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  2874. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  2875. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  2876. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  2877. host->randomSeed = (uint32_t)(size_t)host;
  2878. host->randomSeed += enet_host_random_seed();
  2879. host->randomSeed = (host->randomSeed << 16) | (host->randomSeed >> 16);
  2880. host->channelLimit = channelLimit;
  2881. host->incomingBandwidth = incomingBandwidth;
  2882. host->outgoingBandwidth = outgoingBandwidth;
  2883. host->bandwidthThrottleEpoch = 0;
  2884. host->recalculateBandwidthLimits = 0;
  2885. host->preventConnections = 0;
  2886. host->mtu = ENET_HOST_DEFAULT_MTU;
  2887. host->peerCount = peerCount;
  2888. host->commandCount = 0;
  2889. host->bufferCount = 0;
  2890. host->checksumCallback = NULL;
  2891. host->receivedAddress.ipv6 = ENET_HOST_ANY;
  2892. host->receivedAddress.port = 0;
  2893. host->receivedData = NULL;
  2894. host->receivedDataLength = 0;
  2895. host->totalSentData = 0;
  2896. host->totalSentPackets = 0;
  2897. host->totalReceivedData = 0;
  2898. host->totalReceivedPackets = 0;
  2899. host->connectedPeers = 0;
  2900. host->bandwidthLimitedPeers = 0;
  2901. host->duplicatePeers = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  2902. host->maximumPacketSize = ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE;
  2903. host->maximumWaitingData = ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA;
  2904. host->interceptCallback = NULL;
  2905. enet_list_clear(&host->dispatchQueue);
  2906. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2907. currentPeer->host = host;
  2908. currentPeer->incomingPeerID = currentPeer - host->peers;
  2909. currentPeer->outgoingSessionID = currentPeer->incomingSessionID = 0xFF;
  2910. currentPeer->data = NULL;
  2911. enet_list_clear(&currentPeer->acknowledgements);
  2912. enet_list_clear(&currentPeer->sentReliableCommands);
  2913. enet_list_clear(&currentPeer->sentUnreliableCommands);
  2914. enet_list_clear(&currentPeer->outgoingCommands);
  2915. enet_list_clear(&currentPeer->dispatchedCommands);
  2916. enet_peer_reset(currentPeer);
  2917. }
  2918. return host;
  2919. }
  2920. void enet_host_destroy(ENetHost* host) {
  2921. ENetPeer* currentPeer;
  2922. if (host == NULL)
  2923. return;
  2924. enet_socket_destroy(host->socket);
  2925. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2926. enet_peer_reset(currentPeer);
  2927. }
  2928. enet_free(host->peers);
  2929. enet_free(host);
  2930. }
  2931. void enet_host_prevent_connections(ENetHost* host, uint8_t state) {
  2932. if (host == NULL)
  2933. return;
  2934. host->preventConnections = state;
  2935. }
  2936. ENetPeer* enet_host_connect(ENetHost* host, const ENetAddress* address, size_t channelCount, uint32_t data) {
  2937. ENetPeer* currentPeer;
  2938. ENetChannel* channel;
  2939. ENetProtocol command;
  2940. if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  2941. channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  2942. else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  2943. channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  2944. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2945. if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED)
  2946. break;
  2947. }
  2948. if (currentPeer >= &host->peers[host->peerCount])
  2949. return NULL;
  2950. currentPeer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
  2951. if (currentPeer->channels == NULL)
  2952. return NULL;
  2953. currentPeer->channelCount = channelCount;
  2954. currentPeer->state = ENET_PEER_STATE_CONNECTING;
  2955. currentPeer->address = *address;
  2956. currentPeer->connectID = ++host->randomSeed;
  2957. if (host->outgoingBandwidth == 0)
  2958. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2959. else
  2960. currentPeer->windowSize = (host->outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  2961. if (currentPeer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
  2962. currentPeer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
  2963. else if (currentPeer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
  2964. currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
  2965. for (channel = currentPeer->channels; channel < &currentPeer->channels[channelCount]; ++channel) {
  2966. channel->outgoingReliableSequenceNumber = 0;
  2967. channel->outgoingUnreliableSequenceNumber = 0;
  2968. channel->incomingReliableSequenceNumber = 0;
  2969. channel->incomingUnreliableSequenceNumber = 0;
  2970. enet_list_clear(&channel->incomingReliableCommands);
  2971. enet_list_clear(&channel->incomingUnreliableCommands);
  2972. channel->usedReliableWindows = 0;
  2973. memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
  2974. }
  2975. command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  2976. command.header.channelID = 0xFF;
  2977. command.connect.outgoingPeerID = ENET_HOST_TO_NET_16(currentPeer->incomingPeerID);
  2978. command.connect.incomingSessionID = currentPeer->incomingSessionID;
  2979. command.connect.outgoingSessionID = currentPeer->outgoingSessionID;
  2980. command.connect.mtu = ENET_HOST_TO_NET_32(currentPeer->mtu);
  2981. command.connect.windowSize = ENET_HOST_TO_NET_32(currentPeer->windowSize);
  2982. command.connect.channelCount = ENET_HOST_TO_NET_32(channelCount);
  2983. command.connect.incomingBandwidth = ENET_HOST_TO_NET_32(host->incomingBandwidth);
  2984. command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  2985. command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32(currentPeer->packetThrottleInterval);
  2986. command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleAcceleration);
  2987. command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleDeceleration);
  2988. command.connect.connectID = currentPeer->connectID;
  2989. command.connect.data = ENET_HOST_TO_NET_32(data);
  2990. enet_peer_queue_outgoing_command(currentPeer, &command, NULL, 0, 0);
  2991. return currentPeer;
  2992. }
  2993. void enet_host_broadcast(ENetHost* host, uint8_t channelID, ENetPacket* packet) {
  2994. ENetPeer* currentPeer;
  2995. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  2996. ++packet->referenceCount;
  2997. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  2998. if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
  2999. continue;
  3000. enet_peer_send(currentPeer, channelID, packet);
  3001. }
  3002. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3003. --packet->referenceCount;
  3004. if (packet->referenceCount == 0)
  3005. enet_packet_destroy(packet);
  3006. }
  3007. void enet_host_broadcast_exclude(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer* excludedPeer) {
  3008. ENetPeer* currentPeer;
  3009. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3010. ++packet->referenceCount;
  3011. for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
  3012. if (currentPeer->state != ENET_PEER_STATE_CONNECTED || currentPeer == excludedPeer)
  3013. continue;
  3014. enet_peer_send(currentPeer, channelID, packet);
  3015. }
  3016. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3017. --packet->referenceCount;
  3018. if (packet->referenceCount == 0)
  3019. enet_packet_destroy(packet);
  3020. }
  3021. void enet_host_broadcast_selective(ENetHost* host, uint8_t channelID, ENetPacket* packet, ENetPeer** peers, size_t length) {
  3022. ENetPeer* currentPeer;
  3023. size_t i;
  3024. if (host == NULL)
  3025. return;
  3026. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3027. ++packet->referenceCount;
  3028. for (i = 0; i < length; i++) {
  3029. currentPeer = peers[i];
  3030. if (currentPeer == NULL || currentPeer->state != ENET_PEER_STATE_CONNECTED)
  3031. continue;
  3032. enet_peer_send(currentPeer, channelID, packet);
  3033. }
  3034. if (packet->flags & ENET_PACKET_FLAG_INSTANT)
  3035. --packet->referenceCount;
  3036. if (packet->referenceCount == 0)
  3037. enet_packet_destroy(packet);
  3038. }
  3039. void enet_host_channel_limit(ENetHost* host, size_t channelLimit) {
  3040. if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  3041. channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
  3042. else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
  3043. channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
  3044. host->channelLimit = channelLimit;
  3045. }
  3046. void enet_host_bandwidth_limit(ENetHost* host, uint32_t incomingBandwidth, uint32_t outgoingBandwidth) {
  3047. host->incomingBandwidth = incomingBandwidth;
  3048. host->outgoingBandwidth = outgoingBandwidth;
  3049. host->recalculateBandwidthLimits = 1;
  3050. }
  3051. void enet_host_bandwidth_throttle(ENetHost* host) {
  3052. uint32_t timeCurrent = enet_time_get();
  3053. uint32_t elapsedTime = timeCurrent - host->bandwidthThrottleEpoch;
  3054. uint32_t peersRemaining = (uint32_t)host->connectedPeers;
  3055. uint32_t dataTotal = ~0;
  3056. uint32_t bandwidth = ~0;
  3057. uint32_t throttle = 0;
  3058. uint32_t bandwidthLimit = 0;
  3059. int needsAdjustment = host->bandwidthLimitedPeers > 0 ? 1 : 0;
  3060. ENetPeer* peer;
  3061. ENetProtocol command;
  3062. if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
  3063. return;
  3064. if (host->outgoingBandwidth == 0 && host->incomingBandwidth == 0)
  3065. return;
  3066. host->bandwidthThrottleEpoch = timeCurrent;
  3067. if (peersRemaining == 0)
  3068. return;
  3069. if (host->outgoingBandwidth != 0) {
  3070. dataTotal = 0;
  3071. bandwidth = (host->outgoingBandwidth * elapsedTime) / 1000;
  3072. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3073. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3074. continue;
  3075. dataTotal += peer->outgoingDataTotal;
  3076. }
  3077. }
  3078. while (peersRemaining > 0 && needsAdjustment != 0) {
  3079. needsAdjustment = 0;
  3080. if (dataTotal <= bandwidth)
  3081. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3082. else
  3083. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3084. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3085. uint32_t peerBandwidth;
  3086. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidth == 0 || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3087. continue;
  3088. peerBandwidth = (peer->incomingBandwidth * elapsedTime) / 1000;
  3089. if ((throttle * peer->outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
  3090. continue;
  3091. peer->packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer->outgoingDataTotal;
  3092. if (peer->packetThrottleLimit == 0)
  3093. peer->packetThrottleLimit = 1;
  3094. if (peer->packetThrottle > peer->packetThrottleLimit)
  3095. peer->packetThrottle = peer->packetThrottleLimit;
  3096. peer->outgoingBandwidthThrottleEpoch = timeCurrent;
  3097. peer->incomingDataTotal = 0;
  3098. peer->outgoingDataTotal = 0;
  3099. needsAdjustment = 1;
  3100. --peersRemaining;
  3101. bandwidth -= peerBandwidth;
  3102. dataTotal -= peerBandwidth;
  3103. }
  3104. }
  3105. if (peersRemaining > 0) {
  3106. if (dataTotal <= bandwidth)
  3107. throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
  3108. else
  3109. throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
  3110. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3111. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
  3112. continue;
  3113. peer->packetThrottleLimit = throttle;
  3114. if (peer->packetThrottle > peer->packetThrottleLimit)
  3115. peer->packetThrottle = peer->packetThrottleLimit;
  3116. peer->incomingDataTotal = 0;
  3117. peer->outgoingDataTotal = 0;
  3118. }
  3119. }
  3120. if (host->recalculateBandwidthLimits) {
  3121. host->recalculateBandwidthLimits = 0;
  3122. peersRemaining = (uint32_t)host->connectedPeers;
  3123. bandwidth = host->incomingBandwidth;
  3124. needsAdjustment = 1;
  3125. if (bandwidth == 0) {
  3126. bandwidthLimit = 0;
  3127. } else {
  3128. while (peersRemaining > 0 && needsAdjustment != 0) {
  3129. needsAdjustment = 0;
  3130. bandwidthLimit = bandwidth / peersRemaining;
  3131. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3132. if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3133. continue;
  3134. if (peer->outgoingBandwidth > 0 && peer->outgoingBandwidth >= bandwidthLimit)
  3135. continue;
  3136. peer->incomingBandwidthThrottleEpoch = timeCurrent;
  3137. needsAdjustment = 1;
  3138. --peersRemaining;
  3139. bandwidth -= peer->outgoingBandwidth;
  3140. }
  3141. }
  3142. }
  3143. for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
  3144. if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
  3145. continue;
  3146. command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
  3147. command.header.channelID = 0xFF;
  3148. command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
  3149. if (peer->incomingBandwidthThrottleEpoch == timeCurrent)
  3150. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(peer->outgoingBandwidth);
  3151. else
  3152. command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(bandwidthLimit);
  3153. enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
  3154. }
  3155. }
  3156. }
  3157. /*
  3158. =======================================================================
  3159. Address
  3160. =======================================================================
  3161. */
  3162. int enet_address_set_ip(ENetAddress* address, const char* ip) {
  3163. int type = AF_INET6;
  3164. void* destination = &address->ipv6;
  3165. if (strchr(ip, ':') == NULL) {
  3166. type = AF_INET;
  3167. memset(address, 0, sizeof(address->ipv4.zeros));
  3168. address->ipv4.ffff = 0xFFFF;
  3169. destination = &address->ipv4.ip;
  3170. }
  3171. if (!inet_pton(type, ip, destination))
  3172. return -1;
  3173. return 0;
  3174. }
  3175. int enet_address_set_hostname(ENetAddress* address, const char* name) {
  3176. struct addrinfo hints, *resultList = NULL, *result = NULL;
  3177. memset(&hints, 0, sizeof(hints));
  3178. hints.ai_family = AF_UNSPEC;
  3179. if (getaddrinfo(name, NULL, &hints, &resultList) != 0)
  3180. return -1;
  3181. for (result = resultList; result != NULL; result = result->ai_next) {
  3182. if (result->ai_addr != NULL && result->ai_addrlen >= sizeof(struct sockaddr_in)) {
  3183. if (result->ai_family == AF_INET) {
  3184. struct sockaddr_in* sin = (struct sockaddr_in*)result->ai_addr;
  3185. memset(address, 0, sizeof(address->ipv4.zeros));
  3186. address->ipv4.ffff = 0xFFFF;
  3187. address->ipv4.ip.s_addr = sin->sin_addr.s_addr;
  3188. freeaddrinfo(resultList);
  3189. return 0;
  3190. } else if (result->ai_family == AF_INET6) {
  3191. struct sockaddr_in6* sin = (struct sockaddr_in6*)result->ai_addr;
  3192. address->ipv6 = sin->sin6_addr;
  3193. freeaddrinfo(resultList);
  3194. return 0;
  3195. }
  3196. }
  3197. }
  3198. if (resultList != NULL)
  3199. freeaddrinfo(resultList);
  3200. return enet_address_set_ip(address, name);
  3201. }
  3202. int enet_address_get_ip(const ENetAddress* address, char* ip, size_t ipLength) {
  3203. if (address->ipv4.ffff == 0xFFFF && enet_array_is_zeroed(address->ipv4.zeros, sizeof(address->ipv4.zeros)) == 0) {
  3204. if (inet_ntop(AF_INET, &address->ipv4.ip, ip, ipLength) == NULL)
  3205. return -1;
  3206. } else if (inet_ntop(AF_INET6, &address->ipv6, ip, ipLength) == NULL) {
  3207. return -1;
  3208. }
  3209. return 0;
  3210. }
  3211. int enet_address_get_hostname(const ENetAddress* address, char* name, size_t nameLength) {
  3212. struct sockaddr_in6 sin;
  3213. int err;
  3214. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3215. sin.sin6_family = AF_INET6;
  3216. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3217. sin.sin6_addr = address->ipv6;
  3218. err = getnameinfo((struct sockaddr*)&sin, sizeof(sin), name, nameLength, NULL, 0, NI_NAMEREQD);
  3219. if (!err) {
  3220. if (name != NULL && nameLength > 0 && !memchr(name, '\0', nameLength))
  3221. return -1;
  3222. return 0;
  3223. }
  3224. if (err != EAI_NONAME)
  3225. return -1;
  3226. return enet_address_get_ip(address, name, nameLength);
  3227. }
  3228. /*
  3229. =======================================================================
  3230. Platform-specific (Unix)
  3231. =======================================================================
  3232. */
  3233. #ifndef _WIN32
  3234. int enet_initialize(void) {
  3235. return 0;
  3236. }
  3237. void enet_deinitialize(void) { }
  3238. uint64_t enet_host_random_seed(void) {
  3239. struct timeval timeVal;
  3240. gettimeofday(&timeVal, NULL);
  3241. return (timeVal.tv_sec * 1000) ^ (timeVal.tv_usec / 1000);
  3242. }
  3243. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3244. struct sockaddr_in6 sin;
  3245. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3246. sin.sin6_family = AF_INET6;
  3247. if (address != NULL) {
  3248. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3249. sin.sin6_addr = address->ipv6;
  3250. } else {
  3251. sin.sin6_port = 0;
  3252. sin.sin6_addr = ENET_HOST_ANY;
  3253. }
  3254. return bind(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
  3255. }
  3256. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3257. struct sockaddr_storage ss;
  3258. socklen_t saLength = sizeof(ss);
  3259. if (getsockname(socket, (struct sockaddr*)&ss, &saLength) == -1)
  3260. return -1;
  3261. if (ss.ss_family == AF_INET) {
  3262. struct sockaddr_in* sin = (struct sockaddr_in*)&ss;
  3263. memset(address, 0, sizeof(address->ipv4.zeros));
  3264. address->ipv4.ffff = 0xFFFF;
  3265. address->ipv4.ip = sin->sin_addr;
  3266. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3267. } else if (ss.ss_family == AF_INET6) {
  3268. struct sockaddr_in6* sin = (struct sockaddr_in6*)&ss;
  3269. address->ipv6 = sin->sin6_addr;
  3270. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3271. }
  3272. return 0;
  3273. }
  3274. int enet_socket_listen(ENetSocket socket, int backlog) {
  3275. return listen(socket, backlog < 0 ? SOMAXCONN : backlog);
  3276. }
  3277. ENetSocket enet_socket_create(ENetSocketType type) {
  3278. int socketType = (type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM);
  3279. #ifdef SOCK_CLOEXEC
  3280. socketType |= SOCK_CLOEXEC;
  3281. #endif
  3282. return socket(PF_INET6, socketType, 0);
  3283. }
  3284. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3285. int result = -1;
  3286. switch (option) {
  3287. case ENET_SOCKOPT_NONBLOCK:
  3288. result = fcntl(socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl(socket, F_GETFL) & ~O_NONBLOCK));
  3289. break;
  3290. case ENET_SOCKOPT_BROADCAST:
  3291. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3292. break;
  3293. case ENET_SOCKOPT_REUSEADDR:
  3294. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3295. break;
  3296. case ENET_SOCKOPT_RCVBUF:
  3297. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3298. break;
  3299. case ENET_SOCKOPT_SNDBUF:
  3300. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3301. break;
  3302. case ENET_SOCKOPT_RCVTIMEO: {
  3303. struct timeval timeVal;
  3304. timeVal.tv_sec = value / 1000;
  3305. timeVal.tv_usec = (value % 1000) * 1000;
  3306. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3307. break;
  3308. }
  3309. case ENET_SOCKOPT_SNDTIMEO: {
  3310. struct timeval timeVal;
  3311. timeVal.tv_sec = value / 1000;
  3312. timeVal.tv_usec = (value % 1000) * 1000;
  3313. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeVal, sizeof(struct timeval));
  3314. break;
  3315. }
  3316. case ENET_SOCKOPT_NODELAY:
  3317. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3318. break;
  3319. case ENET_SOCKOPT_IPV6_V6ONLY:
  3320. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3321. break;
  3322. default:
  3323. break;
  3324. }
  3325. return result == -1 ? -1 : 0;
  3326. }
  3327. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3328. int result = -1;
  3329. socklen_t len;
  3330. switch (option) {
  3331. case ENET_SOCKOPT_ERROR:
  3332. len = sizeof(int);
  3333. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, value, &len);
  3334. break;
  3335. default:
  3336. break;
  3337. }
  3338. return result == -1 ? -1 : 0;
  3339. }
  3340. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3341. int result = -1;
  3342. struct sockaddr_in6 sin;
  3343. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3344. sin.sin6_family = AF_INET6;
  3345. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3346. sin.sin6_addr = address->ipv6;
  3347. result = connect(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
  3348. if (result == -1 && errno == EINPROGRESS)
  3349. return 0;
  3350. return result;
  3351. }
  3352. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3353. int result = -1;
  3354. struct sockaddr_in6 sin;
  3355. socklen_t sinLength = sizeof(struct sockaddr_in6);
  3356. result = accept(socket, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL);
  3357. if (result == -1)
  3358. return ENET_SOCKET_NULL;
  3359. if (address != NULL) {
  3360. address->ipv6 = sin.sin6_addr;
  3361. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3362. }
  3363. return result;
  3364. }
  3365. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3366. return shutdown(socket, (int)how);
  3367. }
  3368. void enet_socket_destroy(ENetSocket socket) {
  3369. if (socket != ENET_SOCKET_NULL)
  3370. close(socket);
  3371. }
  3372. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3373. struct msghdr msgHdr;
  3374. struct sockaddr_in6 sin;
  3375. int sentLength;
  3376. memset(&msgHdr, 0, sizeof(struct msghdr));
  3377. if (address != NULL) {
  3378. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3379. sin.sin6_family = AF_INET6;
  3380. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3381. sin.sin6_addr = address->ipv6;
  3382. msgHdr.msg_name = &sin;
  3383. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3384. }
  3385. msgHdr.msg_iov = (struct iovec*)buffers;
  3386. msgHdr.msg_iovlen = bufferCount;
  3387. sentLength = sendmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3388. if (sentLength == -1) {
  3389. if (errno == EWOULDBLOCK)
  3390. return 0;
  3391. return -1;
  3392. }
  3393. return sentLength;
  3394. }
  3395. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3396. struct msghdr msgHdr;
  3397. struct sockaddr_in6 sin;
  3398. int recvLength;
  3399. memset(&msgHdr, 0, sizeof(struct msghdr));
  3400. if (address != NULL) {
  3401. msgHdr.msg_name = &sin;
  3402. msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
  3403. }
  3404. msgHdr.msg_iov = (struct iovec*)buffers;
  3405. msgHdr.msg_iovlen = bufferCount;
  3406. recvLength = recvmsg(socket, &msgHdr, MSG_NOSIGNAL);
  3407. if (recvLength == -1) {
  3408. if (errno == EWOULDBLOCK)
  3409. return 0;
  3410. return -1;
  3411. }
  3412. if (msgHdr.msg_flags & MSG_TRUNC)
  3413. return -2;
  3414. if (address != NULL) {
  3415. address->ipv6 = sin.sin6_addr;
  3416. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3417. }
  3418. return recvLength;
  3419. }
  3420. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3421. struct timeval timeVal;
  3422. timeVal.tv_sec = timeout / 1000;
  3423. timeVal.tv_usec = (timeout % 1000) * 1000;
  3424. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3425. }
  3426. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3427. struct pollfd pollSocket;
  3428. int pollCount;
  3429. pollSocket.fd = socket;
  3430. pollSocket.events = 0;
  3431. if (*condition & ENET_SOCKET_WAIT_SEND)
  3432. pollSocket.events |= POLLOUT;
  3433. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3434. pollSocket.events |= POLLIN;
  3435. pollCount = poll(&pollSocket, 1, timeout);
  3436. if (pollCount < 0) {
  3437. if (errno == EINTR && *condition & ENET_SOCKET_WAIT_INTERRUPT) {
  3438. *condition = ENET_SOCKET_WAIT_INTERRUPT;
  3439. return 0;
  3440. }
  3441. return -1;
  3442. }
  3443. *condition = ENET_SOCKET_WAIT_NONE;
  3444. if (pollCount == 0)
  3445. return 0;
  3446. if (pollSocket.revents & POLLOUT)
  3447. *condition |= ENET_SOCKET_WAIT_SEND;
  3448. if (pollSocket.revents & POLLIN)
  3449. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3450. return 0;
  3451. }
  3452. #endif
  3453. /*
  3454. =======================================================================
  3455. Platform-specific (Windows)
  3456. =======================================================================
  3457. */
  3458. #ifdef _WIN32
  3459. int enet_initialize(void) {
  3460. WORD versionRequested = MAKEWORD(2, 2);
  3461. WSADATA wsaData;
  3462. if (WSAStartup(versionRequested, &wsaData))
  3463. return -1;
  3464. if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
  3465. WSACleanup();
  3466. return -1;
  3467. }
  3468. timeBeginPeriod(1);
  3469. return 0;
  3470. }
  3471. void enet_deinitialize(void) {
  3472. timeEndPeriod(1);
  3473. WSACleanup();
  3474. }
  3475. uint64_t enet_host_random_seed(void) {
  3476. return (uint64_t)timeGetTime();
  3477. }
  3478. int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
  3479. struct sockaddr_in6 sin;
  3480. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3481. sin.sin6_family = AF_INET6;
  3482. if (address != NULL) {
  3483. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3484. sin.sin6_addr = address->ipv6;
  3485. } else {
  3486. sin.sin6_port = 0;
  3487. sin.sin6_addr = in6addr_any;
  3488. }
  3489. return bind(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6)) == SOCKET_ERROR ? -1 : 0;
  3490. }
  3491. int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
  3492. struct sockaddr_storage ss;
  3493. int saLength = sizeof(ss);
  3494. if (getsockname(socket, (struct sockaddr*)&ss, &saLength) == -1)
  3495. return -1;
  3496. if (ss.ss_family == AF_INET) {
  3497. struct sockaddr_in* sin = (struct sockaddr_in*)&ss;
  3498. memset(address, 0, sizeof(address->ipv4.zeros));
  3499. address->ipv4.ffff = 0xFFFF;
  3500. address->ipv4.ip = sin->sin_addr;
  3501. address->port = ENET_NET_TO_HOST_16(sin->sin_port);
  3502. } else if (ss.ss_family == AF_INET6) {
  3503. struct sockaddr_in6* sin = (struct sockaddr_in6*)&ss;
  3504. address->ipv6 = sin->sin6_addr;
  3505. address->port = ENET_NET_TO_HOST_16(sin->sin6_port);
  3506. }
  3507. return 0;
  3508. }
  3509. int enet_socket_listen(ENetSocket socket, int backlog) {
  3510. return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
  3511. }
  3512. ENetSocket enet_socket_create(ENetSocketType type) {
  3513. return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
  3514. }
  3515. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  3516. int result = SOCKET_ERROR;
  3517. switch (option) {
  3518. case ENET_SOCKOPT_NONBLOCK: {
  3519. u_long nonBlocking = (u_long)value;
  3520. result = ioctlsocket(socket, FIONBIO, &nonBlocking);
  3521. break;
  3522. }
  3523. case ENET_SOCKOPT_BROADCAST:
  3524. result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
  3525. break;
  3526. case ENET_SOCKOPT_REUSEADDR:
  3527. result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
  3528. break;
  3529. case ENET_SOCKOPT_RCVBUF:
  3530. result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
  3531. break;
  3532. case ENET_SOCKOPT_SNDBUF:
  3533. result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
  3534. break;
  3535. case ENET_SOCKOPT_RCVTIMEO:
  3536. result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&value, sizeof(int));
  3537. break;
  3538. case ENET_SOCKOPT_SNDTIMEO:
  3539. result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&value, sizeof(int));
  3540. break;
  3541. case ENET_SOCKOPT_NODELAY:
  3542. result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
  3543. break;
  3544. case ENET_SOCKOPT_IPV6_V6ONLY:
  3545. result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
  3546. break;
  3547. default:
  3548. break;
  3549. }
  3550. return result == SOCKET_ERROR ? -1 : 0;
  3551. }
  3552. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
  3553. int result = SOCKET_ERROR, len;
  3554. switch (option) {
  3555. case ENET_SOCKOPT_ERROR:
  3556. len = sizeof(int);
  3557. result = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)value, &len);
  3558. break;
  3559. default:
  3560. break;
  3561. }
  3562. return result == SOCKET_ERROR ? -1 : 0;
  3563. }
  3564. int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
  3565. int result = -1;
  3566. struct sockaddr_in6 sin;
  3567. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3568. sin.sin6_family = AF_INET6;
  3569. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3570. sin.sin6_addr = address->ipv6;
  3571. result = connect(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
  3572. if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
  3573. return -1;
  3574. return 0;
  3575. }
  3576. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
  3577. SOCKET result;
  3578. struct sockaddr_in6 sin;
  3579. int sinLength = sizeof(struct sockaddr_in6);
  3580. result = accept(socket, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL);
  3581. if (result == INVALID_SOCKET)
  3582. return ENET_SOCKET_NULL;
  3583. if (address != NULL) {
  3584. address->ipv6 = sin.sin6_addr;
  3585. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3586. }
  3587. return result;
  3588. }
  3589. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  3590. return shutdown(socket, (int)how) == SOCKET_ERROR ? -1 : 0;
  3591. }
  3592. void enet_socket_destroy(ENetSocket socket) {
  3593. if (socket != INVALID_SOCKET)
  3594. closesocket(socket);
  3595. }
  3596. int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
  3597. struct sockaddr_in6 sin;
  3598. DWORD sentLength = 0;
  3599. if (address != NULL) {
  3600. memset(&sin, 0, sizeof(struct sockaddr_in6));
  3601. sin.sin6_family = AF_INET6;
  3602. sin.sin6_port = ENET_HOST_TO_NET_16(address->port);
  3603. sin.sin6_addr = address->ipv6;
  3604. }
  3605. if (WSASendTo(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &sentLength, 0, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? sizeof(struct sockaddr_in6) : 0, NULL, NULL) == SOCKET_ERROR)
  3606. return (WSAGetLastError() == WSAEWOULDBLOCK) ? 0 : -1;
  3607. return (int)sentLength;
  3608. }
  3609. int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
  3610. INT sinLength = sizeof(struct sockaddr_in6);
  3611. DWORD flags = 0, recvLength = 0;
  3612. struct sockaddr_in6 sin;
  3613. if (WSARecvFrom(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &recvLength, &flags, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL, NULL, NULL) == SOCKET_ERROR) {
  3614. switch (WSAGetLastError()) {
  3615. case WSAEWOULDBLOCK:
  3616. case WSAECONNRESET:
  3617. return 0;
  3618. }
  3619. return -1;
  3620. }
  3621. if (flags & MSG_PARTIAL)
  3622. return -2;
  3623. if (address != NULL) {
  3624. address->ipv6 = sin.sin6_addr;
  3625. address->port = ENET_NET_TO_HOST_16(sin.sin6_port);
  3626. }
  3627. return (int)recvLength;
  3628. }
  3629. int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, uint32_t timeout) {
  3630. struct timeval timeVal;
  3631. timeVal.tv_sec = timeout / 1000;
  3632. timeVal.tv_usec = (timeout % 1000) * 1000;
  3633. return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
  3634. }
  3635. int enet_socket_wait(ENetSocket socket, uint32_t* condition, uint64_t timeout) {
  3636. fd_set readSet, writeSet;
  3637. struct timeval timeVal;
  3638. int selectCount;
  3639. timeVal.tv_sec = timeout / 1000;
  3640. timeVal.tv_usec = (timeout % 1000) * 1000;
  3641. FD_ZERO(&readSet);
  3642. FD_ZERO(&writeSet);
  3643. if (*condition & ENET_SOCKET_WAIT_SEND)
  3644. FD_SET(socket, &writeSet);
  3645. if (*condition & ENET_SOCKET_WAIT_RECEIVE)
  3646. FD_SET(socket, &readSet);
  3647. selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
  3648. if (selectCount < 0)
  3649. return -1;
  3650. *condition = ENET_SOCKET_WAIT_NONE;
  3651. if (selectCount == 0)
  3652. return 0;
  3653. if (FD_ISSET(socket, &writeSet))
  3654. *condition |= ENET_SOCKET_WAIT_SEND;
  3655. if (FD_ISSET(socket, &readSet))
  3656. *condition |= ENET_SOCKET_WAIT_RECEIVE;
  3657. return 0;
  3658. }
  3659. #endif
  3660. /*
  3661. =======================================================================
  3662. Extended functionality
  3663. =======================================================================
  3664. */
  3665. void* enet_packet_get_data(const ENetPacket* packet) {
  3666. return (void*)packet->data;
  3667. }
  3668. void* enet_packet_get_user_data(const ENetPacket* packet) {
  3669. return packet->userData;
  3670. }
  3671. void enet_packet_set_user_data(ENetPacket* packet, void* userData) {
  3672. packet->userData = userData;
  3673. }
  3674. int enet_packet_get_length(const ENetPacket* packet) {
  3675. return packet->dataLength;
  3676. }
  3677. void enet_packet_set_free_callback(ENetPacket* packet, const void* callback) {
  3678. packet->freeCallback = (ENetPacketFreeCallback)callback;
  3679. }
  3680. int enet_packet_check_references(const ENetPacket* packet) {
  3681. return (int)packet->referenceCount;
  3682. }
  3683. void enet_packet_dispose(ENetPacket* packet) {
  3684. if (packet->referenceCount == 0)
  3685. enet_packet_destroy(packet);
  3686. }
  3687. uint32_t enet_host_get_peers_count(const ENetHost* host) {
  3688. return host->connectedPeers;
  3689. }
  3690. uint32_t enet_host_get_packets_sent(const ENetHost* host) {
  3691. return host->totalSentPackets;
  3692. }
  3693. uint32_t enet_host_get_packets_received(const ENetHost* host) {
  3694. return host->totalReceivedPackets;
  3695. }
  3696. uint32_t enet_host_get_bytes_sent(const ENetHost* host) {
  3697. return host->totalSentData;
  3698. }
  3699. uint32_t enet_host_get_bytes_received(const ENetHost* host) {
  3700. return host->totalReceivedData;
  3701. }
  3702. void enet_host_set_max_duplicate_peers(ENetHost* host, uint16_t number) {
  3703. if (number < 1)
  3704. number = 1;
  3705. if (number > ENET_PROTOCOL_MAXIMUM_PEER_ID)
  3706. number = ENET_PROTOCOL_MAXIMUM_PEER_ID;
  3707. host->duplicatePeers = number;
  3708. }
  3709. uint32_t enet_peer_get_id(const ENetPeer* peer) {
  3710. return peer->incomingPeerID;
  3711. }
  3712. int enet_peer_get_ip(const ENetPeer* peer, char* ip, size_t ipLength) {
  3713. return enet_address_get_ip(&peer->address, ip, ipLength);
  3714. }
  3715. uint16_t enet_peer_get_port(const ENetPeer* peer) {
  3716. return peer->address.port;
  3717. }
  3718. uint32_t enet_peer_get_mtu(const ENetPeer* peer) {
  3719. return peer->mtu;
  3720. }
  3721. ENetPeerState enet_peer_get_state(const ENetPeer* peer) {
  3722. return peer->state;
  3723. }
  3724. uint32_t enet_peer_get_rtt(const ENetPeer* peer) {
  3725. return peer->roundTripTime;
  3726. }
  3727. uint32_t enet_peer_get_last_rtt(const ENetPeer* peer) {
  3728. return peer->lastRoundTripTime;
  3729. }
  3730. uint32_t enet_peer_get_lastsendtime(const ENetPeer* peer) {
  3731. return peer->lastSendTime;
  3732. }
  3733. uint32_t enet_peer_get_lastreceivetime(const ENetPeer* peer) {
  3734. return peer->lastReceiveTime;
  3735. }
  3736. uint64_t enet_peer_get_packets_sent(const ENetPeer* peer) {
  3737. return peer->totalPacketsSent;
  3738. }
  3739. uint64_t enet_peer_get_packets_lost(const ENetPeer* peer) {
  3740. return peer->totalPacketsLost;
  3741. }
  3742. float enet_peer_get_packets_throttle(const ENetPeer* peer) {
  3743. return peer->packetThrottle / (float)ENET_PEER_PACKET_THROTTLE_SCALE * 100.0f;
  3744. }
  3745. uint64_t enet_peer_get_bytes_sent(const ENetPeer* peer) {
  3746. return peer->totalDataSent;
  3747. }
  3748. uint64_t enet_peer_get_bytes_received(const ENetPeer* peer) {
  3749. return peer->totalDataReceived;
  3750. }
  3751. void* enet_peer_get_data(const ENetPeer* peer) {
  3752. return (void*)peer->data;
  3753. }
  3754. void enet_peer_set_data(ENetPeer* peer, const void* data) {
  3755. peer->data = (uint32_t*)data;
  3756. }
  3757. #ifdef _MSC_VER
  3758. #pragma warning(pop)
  3759. #endif
  3760. #endif // ENET_IMPLEMENTATION
  3761. #endif // ENET_H