enet.h 168 KB

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