enet.h 224 KB

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