enet.h 214 KB

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