enet.h 225 KB

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