enet.h 223 KB

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