enet.h 171 KB

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