enet.h 214 KB

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