enet.h 208 KB

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