enet.h 210 KB

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