enet.h 223 KB

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