Network.c 440 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937
  1. // SoftEther VPN Source Code - Stable Edition Repository
  2. // Mayaqua Kernel
  3. //
  4. // SoftEther VPN Server, Client and Bridge are free software under GPLv2.
  5. //
  6. // Copyright (c) Daiyuu Nobori.
  7. // Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan.
  8. // Copyright (c) SoftEther Corporation.
  9. //
  10. // All Rights Reserved.
  11. //
  12. // http://www.softether.org/
  13. //
  14. // Author: Daiyuu Nobori, Ph.D.
  15. // Contributors:
  16. // - nattoheaven (https://github.com/nattoheaven)
  17. // Comments: Tetsuo Sugiyama, Ph.D.
  18. //
  19. // This program is free software; you can redistribute it and/or
  20. // modify it under the terms of the GNU General Public License
  21. // version 2 as published by the Free Software Foundation.
  22. //
  23. // This program is distributed in the hope that it will be useful,
  24. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. // GNU General Public License for more details.
  27. //
  28. // You should have received a copy of the GNU General Public License version 2
  29. // along with this program; if not, write to the Free Software
  30. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  31. //
  32. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  33. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  34. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  35. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  36. // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  37. // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  38. // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  39. //
  40. // THE LICENSE AGREEMENT IS ATTACHED ON THE SOURCE-CODE PACKAGE
  41. // AS "LICENSE.TXT" FILE. READ THE TEXT FILE IN ADVANCE TO USE THE SOFTWARE.
  42. //
  43. //
  44. // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN,
  45. // UNDER JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY,
  46. // MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS
  47. // SOFTWARE, THAT ANY JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS
  48. // SOFTWARE OR ITS CONTENTS, AGAINST US (SOFTETHER PROJECT, SOFTETHER
  49. // CORPORATION, DAIYUU NOBORI OR OTHER SUPPLIERS), OR ANY JURIDICAL
  50. // DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND OF USING, COPYING,
  51. // MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING, AND/OR
  52. // SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
  53. // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO
  54. // EXCLUSIVE JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO,
  55. // JAPAN. YOU MUST WAIVE ALL DEFENSES OF LACK OF PERSONAL JURISDICTION
  56. // AND FORUM NON CONVENIENS. PROCESS MAY BE SERVED ON EITHER PARTY IN
  57. // THE MANNER AUTHORIZED BY APPLICABLE LAW OR COURT RULE.
  58. //
  59. // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS
  60. // YOU HAVE A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY
  61. // CRIMINAL LAWS OR CIVIL RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS
  62. // SOFTWARE IN OTHER COUNTRIES IS COMPLETELY AT YOUR OWN RISK. THE
  63. // SOFTETHER VPN PROJECT HAS DEVELOPED AND DISTRIBUTED THIS SOFTWARE TO
  64. // COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING CIVIL RIGHTS INCLUDING
  65. // PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER COUNTRIES' LAWS OR
  66. // CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES. WE HAVE
  67. // NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
  68. // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+
  69. // COUNTRIES AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE
  70. // WORLD, WITH DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY
  71. // COUNTRIES' LAWS, REGULATIONS AND CIVIL RIGHTS TO MAKE THE SOFTWARE
  72. // COMPLY WITH ALL COUNTRIES' LAWS BY THE PROJECT. EVEN IF YOU WILL BE
  73. // SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A PUBLIC SERVANT IN YOUR
  74. // COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE LIABLE TO
  75. // RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
  76. // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT
  77. // JUST A STATEMENT FOR WARNING AND DISCLAIMER.
  78. //
  79. //
  80. // SOURCE CODE CONTRIBUTION
  81. // ------------------------
  82. //
  83. // Your contribution to SoftEther VPN Project is much appreciated.
  84. // Please send patches to us through GitHub.
  85. // Read the SoftEther VPN Patch Acceptance Policy in advance:
  86. // http://www.softether.org/5-download/src/9.patch
  87. //
  88. //
  89. // DEAR SECURITY EXPERTS
  90. // ---------------------
  91. //
  92. // If you find a bug or a security vulnerability please kindly inform us
  93. // about the problem immediately so that we can fix the security problem
  94. // to protect a lot of users around the world as soon as possible.
  95. //
  96. // Our e-mail address for security reports is:
  97. // softether-vpn-security [at] softether.org
  98. //
  99. // Please note that the above e-mail address is not a technical support
  100. // inquiry address. If you need technical assistance, please visit
  101. // http://www.softether.org/ and ask your question on the users forum.
  102. //
  103. // Thank you for your cooperation.
  104. //
  105. //
  106. // NO MEMORY OR RESOURCE LEAKS
  107. // ---------------------------
  108. //
  109. // The memory-leaks and resource-leaks verification under the stress
  110. // test has been passed before release this source code.
  111. // Network.c
  112. // Network communication module
  113. #include <GlobalConst.h>
  114. #define ENCRYPT_C
  115. #define NETWORK_C
  116. #define __WINCRYPT_H__
  117. #ifdef WIN32
  118. // Include windows.h for Socket API
  119. #define _WIN32_WINNT 0x0502
  120. #define WINVER 0x0502
  121. #include <Ws2tcpip.h>
  122. #include <Wspiapi.h>
  123. #include <winsock2.h>
  124. #include <windows.h>
  125. #include <Iphlpapi.h>
  126. #include <ws2ipdef.h>
  127. #include <netioapi.h>
  128. #include <Icmpapi.h>
  129. #endif // WIN32
  130. #include <stdio.h>
  131. #include <stdlib.h>
  132. #include <string.h>
  133. #include <wchar.h>
  134. #include <stdarg.h>
  135. #include <time.h>
  136. #include <openssl/ssl.h>
  137. #include <openssl/err.h>
  138. #include <openssl/rand.h>
  139. #include <openssl/engine.h>
  140. #include <openssl/bio.h>
  141. #include <openssl/x509.h>
  142. #include <openssl/pkcs7.h>
  143. #include <openssl/pkcs12.h>
  144. #include <openssl/rc4.h>
  145. #include <openssl/md5.h>
  146. #include <openssl/sha.h>
  147. #include <Mayaqua/Mayaqua.h>
  148. #ifdef UNIX_MACOS
  149. #include <sys/event.h>
  150. #endif // UNIX_MACOS
  151. #ifdef OS_WIN32
  152. NETWORK_WIN32_FUNCTIONS *w32net;
  153. struct ROUTE_CHANGE_DATA
  154. {
  155. OVERLAPPED Overlapped;
  156. HANDLE Handle;
  157. UINT NumCalled;
  158. };
  159. #endif // OS_WIN32
  160. // Whether the blocking occurs in SSL
  161. #if defined(UNIX_BSD) || defined(UNIX_MACOS)
  162. #define FIX_SSL_BLOCKING
  163. #endif
  164. // IPV6_V6ONLY constant
  165. #ifdef UNIX_LINUX
  166. #ifndef IPV6_V6ONLY
  167. #define IPV6_V6ONLY 26
  168. #endif // IPV6_V6ONLY
  169. #endif // UNIX_LINUX
  170. #ifdef UNIX_SOLARIS
  171. #ifndef IPV6_V6ONLY
  172. #define IPV6_V6ONLY 0x27
  173. #endif // IPV6_V6ONLY
  174. #endif // UNIX_SOLARIS
  175. // HTTP constant
  176. static char http_404_str[] = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>404 Not Found</TITLE>\r\n</HEAD><BODY>\r\n<H1>Not Found</H1>\r\nThe requested URL $TARGET$ was not found on this server.<P>\r\n<HR>\r\n<ADDRESS>HTTP Server at $HOST$ Port $PORT$</ADDRESS>\r\n</BODY></HTML>\r\n";
  177. static char http_403_str[] = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>403 Forbidden</TITLE>\r\n</HEAD><BODY>\r\n<H1>Forbidden</H1>\r\nYou don't have permission to access $TARGET$\r\non this server.<P>\r\n<HR>\r\n<ADDRESS>HTTP Server at $HOST$ Port $PORT$</ADDRESS>\r\n</BODY></HTML>\r\n";
  178. static char http_500_str[] = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>500 Server Error</TITLE>\r\n</HEAD><BODY>\r\n<H1>Server Error</H1>\r\nServer Error<P>\r\n<HR>\r\n<ADDRESS>HTTP Server at $HOST$ Port $PORT$</ADDRESS>\r\n</BODY></HTML>\r\n";
  179. static char http_501_str[] = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>501 Method Not Implemented</TITLE>\r\n</HEAD><BODY>\r\n<H1>Method Not Implemented</H1>\r\n$METHOD$ to $TARGET$ not supported.<P>\r\nInvalid method in request $METHOD$ $TARGET$ $VERSION$<P>\r\n<HR>\r\n<ADDRESS>HTTP Server at $HOST$ Port $PORT$</ADDRESS>\r\n</BODY></HTML>\r\n";
  180. static char http_detect_server_startwith[] = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n<HTML><HEAD>\r\n<TITLE>403 Forbidden</TITLE>\r\n</HEAD><BODY>\r\n<H1>Forbidden</H1>\r\nYou don't have permission to access ";
  181. static char http_detect_server_tag_future[] = "9C37197CA7C2428388C2E6E59B829B30";
  182. // DNS cache list
  183. static LIST *DnsCache;
  184. // Lock related
  185. static LOCK *machine_name_lock = NULL;
  186. static LOCK *disconnect_function_lock = NULL;
  187. static LOCK *aho = NULL;
  188. static LOCK *socket_library_lock = NULL;
  189. extern LOCK *openssl_lock;
  190. static LOCK *ssl_accept_lock = NULL;
  191. static LOCK *ssl_connect_lock = NULL;
  192. static TOKEN_LIST *cipher_list_token = NULL;
  193. static COUNTER *num_tcp_connections = NULL;
  194. static LOCK *dns_lock = NULL;
  195. static LOCK *unix_dns_server_addr_lock = NULL;
  196. static IP unix_dns_server;
  197. static LIST *HostCacheList = NULL;
  198. static LIST *WaitThreadList = NULL;
  199. static bool disable_cache = false;
  200. static bool NetworkReleaseMode = false; // Network release mode
  201. static UCHAR machine_ip_process_hash[SHA1_SIZE];
  202. static LOCK *machine_ip_process_hash_lock = NULL;
  203. static LOCK *current_global_ip_lock = NULL;
  204. static LOCK *current_fqdn_lock = NULL;
  205. static bool current_global_ip_set = false;
  206. static IP current_glocal_ipv4 = {0};
  207. static IP current_glocal_ipv6 = {0};
  208. static char current_fqdn[MAX_SIZE];
  209. static bool g_no_rudp_server = false;
  210. static bool g_no_rudp_register = false;
  211. static bool g_natt_low_priority = false;
  212. static LOCK *host_ip_address_list_cache_lock = NULL;
  213. static UINT64 host_ip_address_list_cache_last = 0;
  214. static LIST *host_ip_address_cache = NULL;
  215. static bool disable_gethostname_by_accept = false;
  216. static COUNTER *getip_thread_counter = NULL;
  217. static UINT max_getip_thread = 0;
  218. static char *cipher_list = "RC4-MD5 RC4-SHA AES128-SHA AES256-SHA DES-CBC-SHA DES-CBC3-SHA DHE-RSA-AES128-SHA DHE-RSA-AES256-SHA AES128-GCM-SHA256 AES128-SHA256 AES256-GCM-SHA384 AES256-SHA256 DHE-RSA-AES128-GCM-SHA256 DHE-RSA-AES128-SHA256 DHE-RSA-AES256-GCM-SHA384 DHE-RSA-AES256-SHA256 ECDHE-RSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-SHA256 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-SHA384"
  219. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  220. " DHE-RSA-CHACHA20-POLY1305 ECDHE-RSA-CHACHA20-POLY1305";
  221. #endif
  222. ;
  223. static LIST *ip_clients = NULL;
  224. static LIST *local_mac_list = NULL;
  225. static LOCK *local_mac_list_lock = NULL;
  226. static UINT rand_port_numbers[256] = {0};
  227. static bool g_use_privateip_file = false;
  228. static bool g_source_ip_validation_force_disable = false;
  229. static DH_CTX *dh_2048 = NULL;
  230. typedef struct PRIVATE_IP_SUBNET
  231. {
  232. UINT Ip, Mask, Ip2;
  233. } PRIVATE_IP_SUBNET;
  234. static LIST *g_private_ip_list = NULL;
  235. static LIST *g_dyn_value_list = NULL;
  236. //#define RUDP_DETAIL_LOG
  237. // Get a value from a dynamic value list (Returns a default value if the value is not found)
  238. UINT64 GetDynValueOrDefault(char *name, UINT64 default_value, UINT64 min_value, UINT64 max_value)
  239. {
  240. UINT64 ret = GetDynValue(name);
  241. if (ret == 0)
  242. {
  243. return default_value;
  244. }
  245. if (ret < min_value)
  246. {
  247. ret = min_value;
  248. }
  249. if (ret > max_value)
  250. {
  251. ret = max_value;
  252. }
  253. return ret;
  254. }
  255. // Get a value from a dynamic value list (Returns a default value if the value is not found)
  256. // The value is limited to 1/5 to 50 times of the default value for safety
  257. UINT64 GetDynValueOrDefaultSafe(char *name, UINT64 default_value)
  258. {
  259. return GetDynValueOrDefault(name, default_value, default_value / (UINT64)5, default_value * (UINT64)50);
  260. }
  261. // Get a value from a dynamic value list
  262. UINT64 GetDynValue(char *name)
  263. {
  264. UINT64 ret = 0;
  265. // Validate arguments
  266. if (name == NULL)
  267. {
  268. return 0;
  269. }
  270. if (g_dyn_value_list == NULL)
  271. {
  272. return 0;
  273. }
  274. LockList(g_dyn_value_list);
  275. {
  276. UINT i;
  277. for (i = 0; i < LIST_NUM(g_dyn_value_list);i++)
  278. {
  279. DYN_VALUE *vv = LIST_DATA(g_dyn_value_list, i);
  280. if (StrCmpi(vv->Name, name) == 0)
  281. {
  282. ret = vv->Value;
  283. break;
  284. }
  285. }
  286. }
  287. UnlockList(g_dyn_value_list);
  288. return ret;
  289. }
  290. // Set the value to the dynamic value list
  291. void SetDynListValue(char *name, UINT64 value)
  292. {
  293. // Validate arguments
  294. if (name == NULL)
  295. {
  296. return;
  297. }
  298. if (g_dyn_value_list == NULL)
  299. {
  300. return;
  301. }
  302. LockList(g_dyn_value_list);
  303. {
  304. UINT i;
  305. DYN_VALUE *v = NULL;
  306. for (i = 0; i < LIST_NUM(g_dyn_value_list);i++)
  307. {
  308. DYN_VALUE *vv = LIST_DATA(g_dyn_value_list, i);
  309. if (StrCmpi(vv->Name, name) == 0)
  310. {
  311. v = vv;
  312. break;
  313. }
  314. }
  315. if (v == NULL)
  316. {
  317. v = ZeroMalloc(sizeof(DYN_VALUE));
  318. StrCpy(v->Name, sizeof(v->Name), name);
  319. Add(g_dyn_value_list, v);
  320. }
  321. v->Value = value;
  322. }
  323. UnlockList(g_dyn_value_list);
  324. }
  325. // Apply by extracting dynamic value list from the specified PACK
  326. void ExtractAndApplyDynList(PACK *p)
  327. {
  328. BUF *b;
  329. // Validate arguments
  330. if (p == NULL)
  331. {
  332. return;
  333. }
  334. b = PackGetBuf(p, "DynList");
  335. if (b == NULL)
  336. {
  337. return;
  338. }
  339. AddDynList(b);
  340. FreeBuf(b);
  341. }
  342. // Insert the data to the dynamic value list
  343. void AddDynList(BUF *b)
  344. {
  345. PACK *p;
  346. TOKEN_LIST *t;
  347. // Validate arguments
  348. if (b == NULL)
  349. {
  350. return;
  351. }
  352. SeekBufToBegin(b);
  353. p = BufToPack(b);
  354. if (p == NULL)
  355. {
  356. return;
  357. }
  358. t = GetPackElementNames(p);
  359. if (t != NULL)
  360. {
  361. UINT i;
  362. for (i = 0;i < t->NumTokens;i++)
  363. {
  364. char *name = t->Token[i];
  365. UINT64 v = PackGetInt64(p, name);
  366. SetDynListValue(name, v);
  367. }
  368. FreeToken(t);
  369. }
  370. FreePack(p);
  371. }
  372. // Initialization of the dynamic value list
  373. void InitDynList()
  374. {
  375. g_dyn_value_list = NewList(NULL);
  376. }
  377. // Solution of dynamic value list
  378. void FreeDynList()
  379. {
  380. UINT i;
  381. if (g_dyn_value_list == NULL)
  382. {
  383. return;
  384. }
  385. for (i = 0;i < LIST_NUM(g_dyn_value_list);i++)
  386. {
  387. DYN_VALUE *d = LIST_DATA(g_dyn_value_list, i);
  388. Free(d);
  389. }
  390. ReleaseList(g_dyn_value_list);
  391. g_dyn_value_list = NULL;
  392. }
  393. // Check whether the string in the string list appears in the specified string
  394. bool IsInStrByStrList(char *str, char *str_list)
  395. {
  396. TOKEN_LIST *t;
  397. bool ret = false;
  398. // Validate arguments
  399. if (str == NULL || str_list == NULL)
  400. {
  401. return false;
  402. }
  403. t = ParseTokenWithoutNullStr(str_list, ", \t\r\n");
  404. if (t != NULL)
  405. {
  406. UINT i;
  407. for (i = 0;i < t->NumTokens;i++)
  408. {
  409. char *s = t->Token[i];
  410. if (StrLen(s) >= 1)
  411. {
  412. if (InStrEx(str, s, true))
  413. {
  414. ret = true;
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. FreeToken(t);
  421. return ret;
  422. }
  423. // Search whether the IP address exists on the IP address list string
  424. bool IsIpInStrList(IP *ip, char *ip_list)
  425. {
  426. char ip_str[128];
  427. TOKEN_LIST *t;
  428. bool ret = false;
  429. // Validate arguments
  430. if (ip == NULL || ip_list == NULL)
  431. {
  432. return false;
  433. }
  434. Zero(ip_str, sizeof(ip_str));
  435. IPToStr(ip_str, sizeof(ip_str), ip);
  436. t = ParseTokenWithoutNullStr(ip_list, ", \t\r\n");
  437. if (t != NULL)
  438. {
  439. UINT i;
  440. for (i = 0;i < t->NumTokens;i++)
  441. {
  442. char *s = t->Token[i];
  443. if (StrCmpi(s, ip_str) == 0)
  444. {
  445. ret = true;
  446. break;
  447. }
  448. }
  449. }
  450. FreeToken(t);
  451. return ret;
  452. }
  453. // Disable NAT-T function globally
  454. void DisableRDUPServerGlobally()
  455. {
  456. g_no_rudp_server = true;
  457. }
  458. // Disable NAT-T registration globally
  459. void DisableRUDPRegisterGlobally()
  460. {
  461. g_no_rudp_register = true;
  462. }
  463. // Lower the priority of the host at NAT-T
  464. void SetNatTLowPriority()
  465. {
  466. g_natt_low_priority = true;
  467. }
  468. // Extract only the host name part from FQDN
  469. void GetSimpleHostname(char *hostname, UINT hostname_size, char *fqdn)
  470. {
  471. UINT i;
  472. ClearStr(hostname, hostname_size);
  473. // Validate arguments
  474. if (hostname == NULL || fqdn == NULL)
  475. {
  476. return;
  477. }
  478. StrCpy(hostname, hostname_size, fqdn);
  479. Trim(hostname);
  480. i = SearchStrEx(hostname, ".", 0, true);
  481. if (i != INFINITE)
  482. {
  483. hostname[i] = 0;
  484. }
  485. }
  486. // Get the current time zone
  487. int GetCurrentTimezone()
  488. {
  489. int ret = 0;
  490. #ifdef OS_WIN32
  491. ret = GetCurrentTimezoneWin32();
  492. #else // OS_WIN32
  493. {
  494. #if defined(UNIX_MACOS) || defined(UNIX_BSD)
  495. struct timeval tv;
  496. struct timezone tz;
  497. Zero(&tv, sizeof(tv));
  498. Zero(&tz, sizeof(tz));
  499. gettimeofday(&tv, &tz);
  500. ret = tz.tz_minuteswest;
  501. #else // defined(UNIX_MACOS) || defined(UNIX_BSD)
  502. tzset();
  503. ret = timezone / 60;
  504. #endif // defined(UNIX_MACOS) || defined(UNIX_BSD)
  505. }
  506. #endif // OS_WIN32
  507. return ret;
  508. }
  509. // Flag of whether to use the DNS proxy
  510. bool IsUseDnsProxy()
  511. {
  512. return false;
  513. }
  514. // Flag of whether to use an alternate host name
  515. bool IsUseAlternativeHostname()
  516. {
  517. return false;
  518. }
  519. #ifdef OS_WIN32
  520. // Get the current time zone (Win32)
  521. int GetCurrentTimezoneWin32()
  522. {
  523. TIME_ZONE_INFORMATION info;
  524. Zero(&info, sizeof(info));
  525. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_INVALID)
  526. {
  527. return 0;
  528. }
  529. return info.Bias;
  530. }
  531. #endif // OS_WIN32
  532. // Set the current FQDN of the DDNS
  533. void SetCurrentDDnsFqdn(char *name)
  534. {
  535. // Validate arguments
  536. if (name == NULL)
  537. {
  538. return;
  539. }
  540. Lock(current_fqdn_lock);
  541. {
  542. StrCpy(current_fqdn, sizeof(current_fqdn), name);
  543. }
  544. Unlock(current_fqdn_lock);
  545. }
  546. // Get the current DDNS FQDN hash
  547. UINT GetCurrentDDnsFqdnHash()
  548. {
  549. UINT ret;
  550. UCHAR hash[SHA1_SIZE];
  551. char name[MAX_SIZE];
  552. ClearStr(name, sizeof(name));
  553. GetCurrentDDnsFqdn(name, sizeof(name));
  554. Trim(name);
  555. StrUpper(name);
  556. HashSha1(hash, name, StrLen(name));
  557. Copy(&ret, hash, sizeof(UINT));
  558. return ret;
  559. }
  560. // Get the current DDNS FQDN
  561. void GetCurrentDDnsFqdn(char *name, UINT size)
  562. {
  563. ClearStr(name, size);
  564. // Validate arguments
  565. if (name == NULL || size == 0)
  566. {
  567. return;
  568. }
  569. Lock(current_fqdn_lock);
  570. {
  571. StrCpy(name, size, current_fqdn);
  572. }
  573. Unlock(current_fqdn_lock);
  574. Trim(name);
  575. }
  576. // Check whether the specified MAC address exists on the local host (high speed)
  577. bool IsMacAddressLocalFast(void *addr)
  578. {
  579. bool ret = false;
  580. // Validate arguments
  581. if (addr == NULL)
  582. {
  583. return false;
  584. }
  585. Lock(local_mac_list_lock);
  586. {
  587. if (local_mac_list == NULL)
  588. {
  589. // First enumeration
  590. RefreshLocalMacAddressList();
  591. }
  592. ret = IsMacAddressLocalInner(local_mac_list, addr);
  593. }
  594. Unlock(local_mac_list_lock);
  595. return ret;
  596. }
  597. // Update the local MAC address list
  598. void RefreshLocalMacAddressList()
  599. {
  600. Lock(local_mac_list_lock);
  601. {
  602. if (local_mac_list != NULL)
  603. {
  604. FreeNicList(local_mac_list);
  605. }
  606. local_mac_list = GetNicList();
  607. }
  608. Unlock(local_mac_list_lock);
  609. }
  610. // Check whether the specified MAC address exists on the local host
  611. bool IsMacAddressLocal(void *addr)
  612. {
  613. LIST *o;
  614. bool ret;
  615. // Validate arguments
  616. if (addr == NULL)
  617. {
  618. return false;
  619. }
  620. o = GetNicList();
  621. ret = IsMacAddressLocalInner(o, addr);
  622. FreeNicList(o);
  623. return ret;
  624. }
  625. bool IsMacAddressLocalInner(LIST *o, void *addr)
  626. {
  627. bool ret = false;
  628. UINT i;
  629. // Validate arguments
  630. if (o == NULL || addr == NULL)
  631. {
  632. return false;
  633. }
  634. for (i = 0;i < LIST_NUM(o);i++)
  635. {
  636. NIC_ENTRY *e = LIST_DATA(o, i);
  637. if (Cmp(e->MacAddress, addr, 6) == 0)
  638. {
  639. ret = true;
  640. break;
  641. }
  642. }
  643. return ret;
  644. }
  645. // Get a list of the NICs on the computer
  646. LIST *GetNicList()
  647. {
  648. LIST *o = NULL;
  649. #ifdef OS_WIN32
  650. o = Win32GetNicList();
  651. #endif // OS_WIN32
  652. #ifdef UNIX_LINUX
  653. #endif // UNIX_LINUX
  654. if (o == NULL)
  655. {
  656. return NewListFast(NULL);
  657. }
  658. return o;
  659. }
  660. #ifdef OS_WIN32
  661. LIST *Win32GetNicList()
  662. {
  663. UINT i;
  664. LIST *o = NewListFast(NULL);
  665. MS_ADAPTER_LIST *al = MsCreateAdapterList();
  666. if (al == NULL)
  667. {
  668. return NULL;
  669. }
  670. for (i = 0;i < al->Num;i++)
  671. {
  672. MS_ADAPTER *a = al->Adapters[i];
  673. if (a->Type == 6 && a->AddressSize == 6)
  674. {
  675. NIC_ENTRY *e = ZeroMalloc(sizeof(NIC_ENTRY));
  676. StrCpy(e->IfName, sizeof(e->IfName), a->Title);
  677. Copy(e->MacAddress, a->Address, 6);
  678. Add(o, e);
  679. }
  680. }
  681. MsFreeAdapterList(al);
  682. return o;
  683. }
  684. #endif // OS_WIN32
  685. // Release the NIC list
  686. void FreeNicList(LIST *o)
  687. {
  688. UINT i;
  689. // Validate arguments
  690. if (o == NULL)
  691. {
  692. return;
  693. }
  694. for (i = 0;i < LIST_NUM(o);i++)
  695. {
  696. NIC_ENTRY *e = LIST_DATA(o, i);
  697. Free(e);
  698. }
  699. ReleaseList(o);
  700. }
  701. // If the computer is connected to the FLET'S line currently, detect the type of the line (obsolete)
  702. UINT DetectFletsType()
  703. {
  704. UINT ret = 0;
  705. //LIST *o = GetHostIPAddressList();
  706. // UINT i;
  707. /*
  708. for (i = 0;i < LIST_NUM(o);i++)
  709. {
  710. IP *ip = LIST_DATA(o, i);
  711. if (IsIP6(ip))
  712. {
  713. char ip_str[MAX_SIZE];
  714. IPToStr(ip_str, sizeof(ip_str), ip);
  715. if (IsInSameNetwork6ByStr(ip_str, "2001:c90::", "/32"))
  716. {
  717. // NTT East B-FLETs
  718. ret |= FLETS_DETECT_TYPE_EAST_BFLETS_PRIVATE;
  719. }
  720. if (IsInSameNetwork6ByStr(ip_str, "2408:200::", "/23"))
  721. {
  722. // Wrapping in network of NTT East NGN
  723. ret |= FLETS_DETECT_TYPE_EAST_NGN_PRIVATE;
  724. }
  725. if (IsInSameNetwork6ByStr(ip_str, "2001:a200::", "/23"))
  726. {
  727. // Wrapping in network of NTT West NGN
  728. ret |= FLETS_DETECT_TYPE_WEST_NGN_PRIVATE;
  729. }
  730. }
  731. }
  732. FreeHostIPAddressList(o);
  733. */
  734. return ret;
  735. }
  736. // Query for the IP address using the DNS proxy for the B FLETs
  737. bool GetIPViaDnsProxyForJapanFlets(IP *ip_ret, char *hostname, bool ipv6, UINT timeout, bool *cancel, char *dns_proxy_hostname)
  738. {
  739. SOCK *s;
  740. char connect_hostname[MAX_SIZE];
  741. char connect_hostname2[MAX_SIZE];
  742. IP dns_proxy_ip;
  743. bool ret = false;
  744. bool dummy_flag = false;
  745. char request_str[512];
  746. // Validate arguments
  747. if (ip_ret == NULL || hostname == NULL)
  748. {
  749. return false;
  750. }
  751. if (timeout == 0)
  752. {
  753. timeout = BFLETS_DNS_PROXY_TIMEOUT_FOR_QUERY;
  754. }
  755. if (cancel == NULL)
  756. {
  757. cancel = &dummy_flag;
  758. }
  759. // Get the IP address of the DNS proxy server
  760. if (IsEmptyStr(dns_proxy_hostname))
  761. {
  762. // B FLETs
  763. if (GetDnsProxyIPAddressForJapanBFlets(&dns_proxy_ip, BFLETS_DNS_PROXY_TIMEOUT_FOR_GET_F, cancel) == false)
  764. {
  765. return false;
  766. }
  767. }
  768. else
  769. {
  770. // FLET'S NEXT
  771. if (GetIP4Ex6Ex2(&dns_proxy_ip, dns_proxy_hostname, FLETS_NGN_DNS_QUERY_TIMEOUT, true, cancel, true) == false)
  772. {
  773. return false;
  774. }
  775. }
  776. if (*cancel)
  777. {
  778. return false;
  779. }
  780. IPToStr(connect_hostname, sizeof(connect_hostname), &dns_proxy_ip);
  781. /*{
  782. StrCpy(connect_hostname, sizeof(connect_hostname), "2409:250:62c0:100:6a05:caff:fe09:5158");
  783. }*/
  784. StrCpy(connect_hostname2, sizeof(connect_hostname2), connect_hostname);
  785. if (IsIP6(&dns_proxy_ip))
  786. {
  787. Format(connect_hostname2, sizeof(connect_hostname2), "[%s]", connect_hostname);
  788. }
  789. s = ConnectEx3(connect_hostname, BFLETS_DNS_PROXY_PORT, timeout, cancel, NULL, NULL, false, false, false);
  790. if (s == NULL)
  791. {
  792. return false;
  793. }
  794. if (*cancel)
  795. {
  796. Disconnect(s);
  797. ReleaseSock(s);
  798. return false;
  799. }
  800. SetTimeout(s, timeout);
  801. // Start the SSL
  802. if (StartSSLEx(s, NULL, NULL, true, 0, NULL) && (*cancel == false))
  803. {
  804. UCHAR hash[SHA1_SIZE];
  805. BUF *hash2 = StrToBin(BFLETS_DNS_PROXY_CERT_HASH);
  806. Zero(hash, sizeof(hash));
  807. GetXDigest(s->RemoteX, hash, true);
  808. if (Cmp(hash, hash2->Buf, SHA1_SIZE) == 0)
  809. {
  810. // Send the HTTP Request
  811. Format(request_str, sizeof(request_str),
  812. "GET " BFLETS_DNS_PROXY_PATH "?q=%s&ipv6=%u\r\n"
  813. "\r\n",
  814. hostname, ipv6, connect_hostname2);
  815. if (SendAll(s, request_str, StrLen(request_str), true))
  816. {
  817. if (*cancel == false)
  818. {
  819. BUF *recv_buf = NewBuf();
  820. UINT port_ret;
  821. while (true)
  822. {
  823. UCHAR tmp[MAX_SIZE];
  824. UINT r;
  825. r = Recv(s, tmp, sizeof(tmp), true);
  826. if (r == 0 || (recv_buf->Size > 65536))
  827. {
  828. break;
  829. }
  830. else
  831. {
  832. WriteBuf(recv_buf, tmp, r);
  833. }
  834. }
  835. ret = RUDPParseIPAndPortStr(recv_buf->Buf, recv_buf->Size, ip_ret, &port_ret);
  836. FreeBuf(recv_buf);
  837. }
  838. }
  839. }
  840. FreeBuf(hash2);
  841. }
  842. Disconnect(s);
  843. ReleaseSock(s);
  844. if (ret)
  845. {
  846. NewDnsCache(hostname, ip_ret);
  847. }
  848. return ret;
  849. }
  850. // Get the IP address of the available DNS proxy in B-FLET'S service that is provided by NTT East of Japan
  851. bool GetDnsProxyIPAddressForJapanBFlets(IP *ip_ret, UINT timeout, bool *cancel)
  852. {
  853. BUF *b;
  854. LIST *o;
  855. bool ret = false;
  856. // Validate arguments
  857. if (ip_ret == NULL)
  858. {
  859. return false;
  860. }
  861. if (timeout == 0)
  862. {
  863. timeout = BFLETS_DNS_PROXY_TIMEOUT_FOR_GET_F;
  864. }
  865. b = QueryFileByUdpForJapanBFlets(timeout, cancel);
  866. if (b == NULL)
  867. {
  868. return false;
  869. }
  870. o = ReadIni(b);
  871. if (o != NULL)
  872. {
  873. INI_ENTRY *e = GetIniEntry(o, "DDnsServerForBFlets");
  874. if (e != NULL)
  875. {
  876. char *s = e->Value;
  877. if (IsEmptyStr(s) == false)
  878. {
  879. IP ip;
  880. if (StrToIP(&ip, s))
  881. {
  882. if (IsZeroIp(&ip) == false)
  883. {
  884. Copy(ip_ret, &ip, sizeof(IP));
  885. ret = true;
  886. }
  887. }
  888. }
  889. }
  890. }
  891. FreeIni(o);
  892. FreeBuf(b);
  893. return ret;
  894. }
  895. // Get a valid F.txt file in B-FLET'S service that is provided by NTT East of Japan
  896. BUF *QueryFileByUdpForJapanBFlets(UINT timeout, bool *cancel)
  897. {
  898. bool dummy_flag = false;
  899. BUF *txt_buf = NULL;
  900. BUF *ret = NULL;
  901. LIST *ip_list = NULL;
  902. UINT i;
  903. // Validate arguments
  904. if (cancel == NULL)
  905. {
  906. cancel = &dummy_flag;
  907. }
  908. if (timeout == 0)
  909. {
  910. timeout = BFLETS_DNS_PROXY_TIMEOUT_FOR_GET_F;
  911. }
  912. txt_buf = ReadDump(UDP_FILE_QUERY_BFLETS_TXT_FILENAME);
  913. if (txt_buf == NULL)
  914. {
  915. return NULL;
  916. }
  917. ip_list = NewListFast(NULL);
  918. while (true)
  919. {
  920. char *line = CfgReadNextLine(txt_buf);
  921. if (line == NULL)
  922. {
  923. break;
  924. }
  925. Trim(line);
  926. if (IsEmptyStr(line) == false && StartWith(line, "#") == false)
  927. {
  928. IP ip;
  929. if (StrToIP6(&ip, line))
  930. {
  931. if (IsZeroIp(&ip) == false)
  932. {
  933. if (IsIPv6LocalNetworkAddress(&ip) == false)
  934. {
  935. Add(ip_list, Clone(&ip, sizeof(IP)));
  936. }
  937. }
  938. }
  939. }
  940. Free(line);
  941. }
  942. FreeBuf(txt_buf);
  943. ret = QueryFileByIPv6Udp(ip_list, timeout, cancel);
  944. for (i = 0;i < LIST_NUM(ip_list);i++)
  945. {
  946. IP *ip = LIST_DATA(ip_list, i);
  947. Free(ip);
  948. }
  949. ReleaseList(ip_list);
  950. return ret;
  951. }
  952. // Request a file by UDP (send the requests to the multiple IP addresses at the same time)
  953. BUF *QueryFileByIPv6Udp(LIST *ip_list, UINT timeout, bool *cancel)
  954. {
  955. bool dummy_flag = false;
  956. UINT64 start_tick, giveup_tick;
  957. UINT64 next_send_tick;
  958. SOCK *s;
  959. INTERRUPT_MANAGER *interrupt;
  960. BUF *buf = NULL;
  961. SOCK_EVENT *se;
  962. UCHAR *tmp_buf;
  963. UINT tmp_buf_size = 65535;
  964. // Validate arguments
  965. if (cancel == NULL)
  966. {
  967. cancel = &dummy_flag;
  968. }
  969. if (ip_list == NULL)
  970. {
  971. return NULL;
  972. }
  973. s = NewUDP6(0, NULL);
  974. if (s == NULL)
  975. {
  976. return NULL;
  977. }
  978. tmp_buf = Malloc(tmp_buf_size);
  979. start_tick = Tick64();
  980. giveup_tick = start_tick + (UINT64)timeout;
  981. next_send_tick = 0;
  982. interrupt = NewInterruptManager();
  983. AddInterrupt(interrupt, giveup_tick);
  984. se = NewSockEvent();
  985. JoinSockToSockEvent(s, se);
  986. while (true)
  987. {
  988. UINT64 now = Tick64();
  989. if (now >= giveup_tick)
  990. {
  991. // Time-out
  992. break;
  993. }
  994. if (*cancel)
  995. {
  996. // User canceled
  997. break;
  998. }
  999. // Receive
  1000. while (true)
  1001. {
  1002. IP src_ip;
  1003. UINT src_port;
  1004. UINT r;
  1005. r = RecvFrom(s, &src_ip, &src_port, tmp_buf, tmp_buf_size);
  1006. if (r == SOCK_LATER || r == 0)
  1007. {
  1008. break;
  1009. }
  1010. if (src_port == UDP_FILE_QUERY_DST_PORT)
  1011. {
  1012. if (r >= 40)
  1013. {
  1014. if (Cmp(tmp_buf, UDP_FILE_QUERY_MAGIC_NUMBER, StrLen(UDP_FILE_QUERY_MAGIC_NUMBER)) == 0)
  1015. {
  1016. // Successful reception
  1017. buf = NewBuf();
  1018. WriteBuf(buf, tmp_buf, r);
  1019. SeekBuf(buf, 0, 0);
  1020. break;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. if (buf != NULL)
  1026. {
  1027. // Successful reception
  1028. break;
  1029. }
  1030. if (next_send_tick == 0 || (now >= next_send_tick))
  1031. {
  1032. // Transmission
  1033. UINT i;
  1034. for (i = 0;i < LIST_NUM(ip_list);i++)
  1035. {
  1036. IP *ip = LIST_DATA(ip_list, i);
  1037. UCHAR c = 'F';
  1038. SendTo(s, ip, UDP_FILE_QUERY_DST_PORT, &c, 1);
  1039. }
  1040. next_send_tick = now + (UINT64)UDP_FILE_QUERY_RETRY_INTERVAL;
  1041. AddInterrupt(interrupt, next_send_tick);
  1042. }
  1043. WaitSockEvent(se, GetNextIntervalForInterrupt(interrupt));
  1044. }
  1045. FreeInterruptManager(interrupt);
  1046. Disconnect(s);
  1047. ReleaseSock(s);
  1048. ReleaseSockEvent(se);
  1049. Free(tmp_buf);
  1050. return buf;
  1051. }
  1052. // Parse the user name of the NT
  1053. void ParseNtUsername(char *src_username, char *dst_username, UINT dst_username_size, char *dst_domain, UINT dst_domain_size, bool do_not_parse_atmark)
  1054. {
  1055. char tmp_username[MAX_SIZE];
  1056. char tmp_domain[MAX_SIZE];
  1057. TOKEN_LIST *t;
  1058. if (src_username != dst_username)
  1059. {
  1060. ClearStr(dst_username, dst_username_size);
  1061. }
  1062. ClearStr(dst_domain, dst_domain_size);
  1063. // Validate arguments
  1064. if (src_username == NULL || dst_username == NULL || dst_domain == NULL)
  1065. {
  1066. return;
  1067. }
  1068. StrCpy(tmp_username, sizeof(tmp_username), src_username);
  1069. ClearStr(tmp_domain, sizeof(tmp_domain));
  1070. // Analysis of [email protected] format
  1071. if (do_not_parse_atmark == false)
  1072. {
  1073. t = ParseTokenWithNullStr(tmp_username, "@");
  1074. if (t->NumTokens >= 1)
  1075. {
  1076. StrCpy(tmp_username, sizeof(tmp_username), t->Token[0]);
  1077. }
  1078. if (t->NumTokens >= 2)
  1079. {
  1080. StrCpy(tmp_domain, sizeof(tmp_domain), t->Token[1]);
  1081. }
  1082. FreeToken(t);
  1083. }
  1084. // If the username part is in "domain\username" format, split it
  1085. t = ParseTokenWithNullStr(tmp_username, "\\");
  1086. if (t->NumTokens >= 2)
  1087. {
  1088. if (IsEmptyStr(tmp_domain))
  1089. {
  1090. StrCpy(tmp_domain, sizeof(tmp_domain), t->Token[0]);
  1091. }
  1092. StrCpy(tmp_username, sizeof(tmp_username), t->Token[1]);
  1093. }
  1094. FreeToken(t);
  1095. StrCpy(dst_username, dst_username_size, tmp_username);
  1096. StrCpy(dst_domain, dst_domain_size, tmp_domain);
  1097. }
  1098. // The calculation of the optimum MSS value for use in TCP/IP packet in the payload of bulk transfer in R-UDP session
  1099. UINT RUDPCalcBestMssForBulk(RUDP_STACK *r, RUDP_SESSION *se)
  1100. {
  1101. UINT ret;
  1102. // Validate arguments
  1103. if (r == NULL || se == NULL)
  1104. {
  1105. return 0;
  1106. }
  1107. ret = MTU_FOR_PPPOE;
  1108. // IPv4
  1109. if (IsIP6(&se->YourIp) == false)
  1110. {
  1111. ret -= 20;
  1112. }
  1113. else
  1114. {
  1115. ret -= 40;
  1116. }
  1117. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  1118. {
  1119. // ICMP
  1120. ret -= 8;
  1121. ret -= SHA1_SIZE;
  1122. }
  1123. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  1124. {
  1125. // UDP
  1126. ret -= 8;
  1127. // DNS
  1128. ret -= 42;
  1129. }
  1130. // IV
  1131. ret -= SHA1_SIZE;
  1132. // Sign
  1133. ret -= SHA1_SIZE;
  1134. // SEQ_NO
  1135. ret -= sizeof(UINT64);
  1136. // Padding Max
  1137. ret -= 31;
  1138. // Ethernet header (target packets of communication)
  1139. ret -= 14;
  1140. // IPv4 Header (target packet of communication)
  1141. ret -= 20;
  1142. // TCP header (target packet of communication)
  1143. ret -= 20;
  1144. // I don't know well, but subtract 24 bytes
  1145. ret -= 24;
  1146. return ret;
  1147. }
  1148. // Processing of the reply packet from the NAT-T server
  1149. void RUDPProcess_NatT_Recv(RUDP_STACK *r, UDPPACKET *udp)
  1150. {
  1151. BUF *b;
  1152. PACK *p;
  1153. // Validate arguments
  1154. if (r == NULL || udp == NULL)
  1155. {
  1156. return;
  1157. }
  1158. if (udp->Size >= 8)
  1159. {
  1160. char tmp[128];
  1161. Zero(tmp, sizeof(tmp));
  1162. Copy(tmp, udp->Data, MIN(udp->Size, sizeof(tmp) - 1));
  1163. if (StartWith(tmp, "IP="))
  1164. {
  1165. IP my_ip;
  1166. UINT my_port;
  1167. // There was a response to the packet to determine the NAT state
  1168. if (IsEmptyStr(r->NatT_Registered_IPAndPort) == false)
  1169. {
  1170. if (StrCmpi(r->NatT_Registered_IPAndPort, tmp) != 0)
  1171. {
  1172. // Redo getting the token and registration because the NAT state is changed
  1173. ClearStr(r->NatT_Registered_IPAndPort, sizeof(r->NatT_Registered_IPAndPort));
  1174. r->NatT_GetTokenNextTick = 0;
  1175. r->NatT_GetTokenFailNum = 0;
  1176. r->NatT_Token_Ok = false;
  1177. Zero(r->NatT_Token, sizeof(r->NatT_Token));
  1178. r->NatT_RegisterNextTick = 0;
  1179. r->NatT_RegisterFailNum = 0;
  1180. r->NatT_Register_Ok = false;
  1181. }
  1182. }
  1183. if (RUDPParseIPAndPortStr(udp->Data, udp->Size, &my_ip, &my_port))
  1184. {
  1185. if (r->NatTGlobalUdpPort != NULL)
  1186. {
  1187. *r->NatTGlobalUdpPort = my_port;
  1188. }
  1189. }
  1190. return;
  1191. }
  1192. }
  1193. // Interpret the UDP packet
  1194. b = NewBuf();
  1195. WriteBuf(b, udp->Data, udp->Size);
  1196. SeekBuf(b, 0, 0);
  1197. p = BufToPack(b);
  1198. if (p != NULL)
  1199. {
  1200. bool is_ok = PackGetBool(p, "ok");
  1201. UINT64 tran_id = PackGetInt64(p, "tran_id");
  1202. ExtractAndApplyDynList(p);
  1203. if (r->ServerMode)
  1204. {
  1205. if (PackCmpStr(p, "opcode", "get_token"))
  1206. {
  1207. // Get the Token
  1208. if (is_ok && (tran_id == r->NatT_TranId))
  1209. {
  1210. char tmp[MAX_SIZE];
  1211. if (PackGetStr(p, "token", tmp, sizeof(tmp)) && IsEmptyStr(tmp) == false)
  1212. {
  1213. char myip[MAX_SIZE];
  1214. // Acquisition success
  1215. StrCpy(r->NatT_Token, sizeof(r->NatT_Token), tmp);
  1216. r->NatT_Token_Ok = true;
  1217. r->NatT_GetTokenNextTick = r->Now + (UINT64)GenRandInterval(UDP_NAT_T_GET_TOKEN_INTERVAL_2_MIN, UDP_NAT_T_GET_TOKEN_INTERVAL_2_MAX);
  1218. r->NatT_GetTokenFailNum = 0;
  1219. // Since success to obtain the self global IPv4 address,
  1220. // re-obtain the destination NAT-T host from this IPv4 address
  1221. if (PackGetStr(p, "your_ip", myip, sizeof(myip)))
  1222. {
  1223. IP ip;
  1224. char new_hostname[MAX_SIZE];
  1225. StrToIP(&ip, myip);
  1226. SetCurrentGlobalIP(&ip, false);
  1227. RUDPGetRegisterHostNameByIP(new_hostname,
  1228. sizeof(new_hostname), &ip);
  1229. Lock(r->Lock);
  1230. {
  1231. if (StrCmpi(r->CurrentRegisterHostname, new_hostname) != 0)
  1232. {
  1233. r->NumChangedHostname++;
  1234. if (r->NumChangedHostname <= RUDP_NATT_MAX_CONT_CHANGE_HOSTNAME)
  1235. {
  1236. if (r->NumChangedHostnameValueResetTick == 0)
  1237. {
  1238. r->NumChangedHostnameValueResetTick = r->Now + (UINT64)RUDP_NATT_CONT_CHANGE_HOSTNAME_RESET_INTERVAL;
  1239. }
  1240. // Change the host name
  1241. Debug("CurrentRegisterHostname Changed: New=%s\n", new_hostname);
  1242. StrCpy(r->CurrentRegisterHostname, sizeof(r->CurrentRegisterHostname), new_hostname);
  1243. Zero(&r->NatT_IP, sizeof(r->NatT_IP));
  1244. //Zero(&r->NatT_IP_Safe, sizeof(r->NatT_IP_Safe));
  1245. Set(r->HaltEvent);
  1246. }
  1247. else
  1248. {
  1249. if (r->NumChangedHostnameValueResetTick == 0)
  1250. {
  1251. r->NumChangedHostnameValueResetTick = r->Now + (UINT64)RUDP_NATT_CONT_CHANGE_HOSTNAME_RESET_INTERVAL;
  1252. }
  1253. if (r->Now >= r->NumChangedHostnameValueResetTick)
  1254. {
  1255. r->NumChangedHostname = 0;
  1256. r->NumChangedHostnameValueResetTick = 0;
  1257. }
  1258. }
  1259. }
  1260. else
  1261. {
  1262. r->NumChangedHostname = 0;
  1263. r->NumChangedHostnameValueResetTick = 0;
  1264. }
  1265. }
  1266. Unlock(r->Lock);
  1267. }
  1268. AddInterrupt(r->Interrupt, r->NatT_GetTokenNextTick);
  1269. }
  1270. }
  1271. }
  1272. else if (PackCmpStr(p, "opcode", "nat_t_register"))
  1273. {
  1274. // NAT-T server registration result
  1275. if (is_ok && (tran_id == r->NatT_TranId))
  1276. {
  1277. UINT my_global_port;
  1278. // Successful registration
  1279. r->NatT_Register_Ok = true;
  1280. r->NatT_RegisterNextTick = r->Now + (UINT64)GenRandInterval(UDP_NAT_T_REGISTER_INTERVAL_MIN, UDP_NAT_T_REGISTER_INTERVAL_MAX);
  1281. r->NatT_RegisterFailNum = 0;
  1282. Debug("NAT-T Registered.\n");
  1283. // Save the IP address and port number at the time of registration
  1284. PackGetStr(p, "your_ip_and_port", r->NatT_Registered_IPAndPort, sizeof(r->NatT_Registered_IPAndPort));
  1285. if (g_source_ip_validation_force_disable == false)
  1286. {
  1287. // Enable the source IP address validation mechanism
  1288. r->NatT_EnableSourceIpValidation = PackGetBool(p, "enable_source_ip_validation");
  1289. }
  1290. else
  1291. {
  1292. // Force disable the source IP address validation mechanism
  1293. r->NatT_EnableSourceIpValidation = false;
  1294. }
  1295. // Global port of itself
  1296. my_global_port = PackGetInt(p, "your_port");
  1297. if (my_global_port != 0)
  1298. {
  1299. if (r->NatTGlobalUdpPort != NULL)
  1300. {
  1301. *r->NatTGlobalUdpPort = my_global_port;
  1302. }
  1303. }
  1304. AddInterrupt(r->Interrupt, r->NatT_RegisterNextTick);
  1305. }
  1306. }
  1307. else if (PackCmpStr(p, "opcode", "nat_t_connect_relay"))
  1308. {
  1309. // Connection request from the client via the NAT-T server
  1310. if (is_ok && (PackGetInt64(p, "session_key") == r->NatT_SessionKey))
  1311. {
  1312. char client_ip_str[MAX_SIZE];
  1313. UINT client_port;
  1314. IP client_ip;
  1315. PackGetStr(p, "client_ip", client_ip_str, sizeof(client_ip_str));
  1316. client_port = PackGetInt(p, "client_port");
  1317. StrToIP(&client_ip, client_ip_str);
  1318. if (IsZeroIp(&client_ip) == false && client_port != 0)
  1319. {
  1320. UCHAR *rand_data;
  1321. UINT rand_size;
  1322. if (r->NatT_EnableSourceIpValidation)
  1323. {
  1324. RUDPAddIpToValidateList(r, &client_ip);
  1325. }
  1326. rand_size = Rand32() % 19;
  1327. rand_data = Malloc(rand_size);
  1328. Rand(rand_data, rand_size);
  1329. RUDPSendPacket(r, &client_ip, client_port, rand_data, rand_size, 0);
  1330. Free(rand_data);
  1331. }
  1332. }
  1333. }
  1334. }
  1335. FreePack(p);
  1336. }
  1337. FreeBuf(b);
  1338. }
  1339. // Set the flag of the source IP address validation function
  1340. void RUDPSetSourceIpValidationForceDisable(bool b)
  1341. {
  1342. g_source_ip_validation_force_disable = b;
  1343. }
  1344. // Process such as packet transmission for NAT-T server
  1345. void RUDPDo_NatT_Interrupt(RUDP_STACK *r)
  1346. {
  1347. // Validate arguments
  1348. if (r == NULL)
  1349. {
  1350. return;
  1351. }
  1352. if (r->ServerMode)
  1353. {
  1354. if (g_no_rudp_register == false && IsZeroIp(&r->NatT_IP_Safe) == false)
  1355. {
  1356. if (r->NatT_GetTokenNextTick == 0 || r->Now >= r->NatT_GetTokenNextTick)
  1357. {
  1358. // Try to get a token from the NAT-T server periodically
  1359. PACK *p = NewPack();
  1360. BUF *b;
  1361. PackAddStr(p, "opcode", "get_token");
  1362. PackAddInt64(p, "tran_id", r->NatT_TranId);
  1363. PackAddInt(p, "nat_traversal_version", UDP_NAT_TRAVERSAL_VERSION);
  1364. b = PackToBuf(p);
  1365. FreePack(p);
  1366. RUDPSendPacket(r, &r->NatT_IP_Safe, UDP_NAT_T_PORT, b->Buf, b->Size, 0);
  1367. FreeBuf(b);
  1368. // Determine the next acquisition time
  1369. r->NatT_GetTokenFailNum++;
  1370. r->NatT_GetTokenNextTick = r->Now + (UINT64)(UDP_NAT_T_GET_TOKEN_INTERVAL_1 * (UINT64)MIN(r->NatT_GetTokenFailNum, UDP_NAT_T_GET_TOKEN_INTERVAL_FAIL_MAX));
  1371. AddInterrupt(r->Interrupt, r->NatT_GetTokenNextTick);
  1372. r->NatT_Token_Ok = false;
  1373. }
  1374. }
  1375. {
  1376. if (IsZeroIp(&r->NatT_IP_Safe) == false)
  1377. {
  1378. // Normal servers: Send request packets to the NAT-T server
  1379. if (r->NatT_NextNatStatusCheckTick == 0 || r->Now >= r->NatT_NextNatStatusCheckTick)
  1380. {
  1381. UCHAR a = 'A';
  1382. UINT ddns_hash;
  1383. // Check of the NAT state
  1384. RUDPSendPacket(r, &r->NatT_IP_Safe, UDP_NAT_T_PORT, &a, 1, 0);
  1385. // Execution time of the next
  1386. r->NatT_NextNatStatusCheckTick = r->Now + (UINT64)GenRandInterval(UDP_NAT_T_NAT_STATUS_CHECK_INTERVAL_MIN, UDP_NAT_T_NAT_STATUS_CHECK_INTERVAL_MAX);
  1387. AddInterrupt(r->Interrupt, r->NatT_NextNatStatusCheckTick);
  1388. // Check whether the DDNS host name changing have not occurred
  1389. ddns_hash = GetCurrentDDnsFqdnHash();
  1390. if (r->LastDDnsFqdnHash != ddns_hash)
  1391. {
  1392. r->LastDDnsFqdnHash = ddns_hash;
  1393. // Do the Register immediately if there is a change in the DDNS host name
  1394. r->NatT_RegisterNextTick = 0;
  1395. }
  1396. }
  1397. }
  1398. }
  1399. if (r->NatT_Token_Ok && g_no_rudp_register == false && IsZeroIp(&r->NatT_IP_Safe) == false)
  1400. {
  1401. if (r->NatT_RegisterNextTick == 0 || r->Now >= r->NatT_RegisterNextTick)
  1402. {
  1403. // Try to register itself periodically for NAT-T server
  1404. PACK *p = NewPack();
  1405. BUF *b;
  1406. char private_ip_str[MAX_SIZE];
  1407. char machine_key[MAX_SIZE];
  1408. char machine_name[MAX_SIZE];
  1409. UCHAR hash[SHA1_SIZE];
  1410. char ddns_fqdn[MAX_SIZE];
  1411. Debug("NAT-T Registering...\n");
  1412. GetCurrentDDnsFqdn(ddns_fqdn, sizeof(ddns_fqdn));
  1413. PackAddStr(p, "opcode", "nat_t_register");
  1414. PackAddInt64(p, "tran_id", r->NatT_TranId);
  1415. PackAddStr(p, "token", r->NatT_Token);
  1416. PackAddStr(p, "svc_name", r->SvcName);
  1417. PackAddStr(p, "product_str", CEDAR_PRODUCT_STR);
  1418. PackAddInt64(p, "session_key", r->NatT_SessionKey);
  1419. PackAddInt(p, "nat_traversal_version", UDP_NAT_TRAVERSAL_VERSION);
  1420. if (g_natt_low_priority)
  1421. {
  1422. PackAddBool(p, "low_priority", g_natt_low_priority);
  1423. }
  1424. Zero(private_ip_str, sizeof(private_ip_str));
  1425. if (IsZeroIp(&r->My_Private_IP_Safe) == false)
  1426. {
  1427. IPToStr(private_ip_str, sizeof(private_ip_str), &r->My_Private_IP_Safe);
  1428. PackAddStr(p, "private_ip", private_ip_str);
  1429. }
  1430. PackAddInt(p, "private_port", r->UdpSock->LocalPort);
  1431. Zero(hash, sizeof(hash));
  1432. GetCurrentMachineIpProcessHash(hash);
  1433. BinToStr(machine_key, sizeof(machine_key), hash, sizeof(hash));
  1434. PackAddStr(p, "machine_key", machine_key);
  1435. Zero(machine_name, sizeof(machine_name));
  1436. GetMachineName(machine_name, sizeof(machine_name));
  1437. PackAddStr(p, "host_name", machine_name);
  1438. PackAddStr(p, "ddns_fqdn", ddns_fqdn);
  1439. b = PackToBuf(p);
  1440. FreePack(p);
  1441. RUDPSendPacket(r, &r->NatT_IP_Safe, UDP_NAT_T_PORT, b->Buf, b->Size, 0);
  1442. //RUDPSendPacket(r, &r->NatT_IP_Safe, UDP_NAT_T_PORT, "a", 1);
  1443. FreeBuf(b);
  1444. // Determine the next acquisition time
  1445. r->NatT_RegisterFailNum++;
  1446. r->NatT_RegisterNextTick = r->Now + (UINT64)UDP_NAT_T_REGISTER_INTERVAL_INITIAL * (UINT64)MIN(r->NatT_RegisterFailNum, UDP_NAT_T_REGISTER_INTERVAL_FAIL_MAX);
  1447. AddInterrupt(r->Interrupt, r->NatT_RegisterNextTick);
  1448. r->NatT_Register_Ok = false;
  1449. }
  1450. }
  1451. }
  1452. }
  1453. // R-UDP packet reception procedure
  1454. void RUDPRecvProc(RUDP_STACK *r, UDPPACKET *p)
  1455. {
  1456. RUDP_SESSION *se = NULL;
  1457. // Validate arguments
  1458. if (r == NULL || p == NULL)
  1459. {
  1460. return;
  1461. }
  1462. if (r->ServerMode)
  1463. {
  1464. if (g_no_rudp_server)
  1465. {
  1466. return;
  1467. }
  1468. }
  1469. if (r->ServerMode && r->NoNatTRegister == false)
  1470. {
  1471. if (p->SrcPort == UDP_NAT_T_PORT && CmpIpAddr(&p->SrcIP, &r->NatT_IP_Safe) == 0)
  1472. {
  1473. // There was a response from the NAT-T server
  1474. RUDPProcess_NatT_Recv(r, p);
  1475. return;
  1476. }
  1477. }
  1478. if (r->ServerMode)
  1479. {
  1480. if (r->ProcRpcRecv != NULL)
  1481. {
  1482. if (r->ProcRpcRecv(r, p))
  1483. {
  1484. return;
  1485. }
  1486. }
  1487. }
  1488. if (r->ServerMode)
  1489. {
  1490. // Search the session by the end-point information if in the server mode
  1491. se = RUDPSearchSession(r, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort);
  1492. }
  1493. else
  1494. {
  1495. // Session should exist only one in the case of client mode
  1496. if (LIST_NUM(r->SessionList) >= 1)
  1497. {
  1498. se = LIST_DATA(r->SessionList, 0);
  1499. }
  1500. else
  1501. {
  1502. se = NULL;
  1503. }
  1504. }
  1505. if (p->Size < 20)
  1506. {
  1507. // The received packet is too small
  1508. if (r->ServerMode == false)
  1509. {
  1510. if (se != NULL && se->Status == RUDP_SESSION_STATUS_CONNECT_SENT)
  1511. {
  1512. if (CmpIpAddr(&se->YourIp, &p->SrcIP) == 0)
  1513. {
  1514. // If the connection initialization packet which is shorter than 20 bytes
  1515. // has been received from the server side, overwrite the source port number
  1516. // of the packet to the client-side session information (for some NAT)
  1517. se->YourPort = p->SrcPort;
  1518. }
  1519. }
  1520. }
  1521. return;
  1522. }
  1523. if (se == NULL && r->ServerMode && p->Size >= 40)
  1524. {
  1525. // Corresponding to a sudden change of port number on the client side.
  1526. // The target session is a session which matches the client side IP address
  1527. // and the key and the signature is verified
  1528. UINT i;
  1529. for (i = 0; i < LIST_NUM(r->SessionList);i++)
  1530. {
  1531. RUDP_SESSION *s = LIST_DATA(r->SessionList, i);
  1532. if (CmpIpAddr(&s->YourIp, &p->SrcIP) == 0)
  1533. {
  1534. if (RUDPCheckSignOfRecvPacket(r, s, p->Data, p->Size))
  1535. {
  1536. // Signature matched
  1537. se = s;
  1538. break;
  1539. }
  1540. }
  1541. }
  1542. }
  1543. if (se == NULL)
  1544. {
  1545. // There is no session
  1546. if (r->ServerMode)
  1547. {
  1548. if (p->Size < 40)
  1549. {
  1550. bool ok = true;
  1551. UCHAR ctoken_hash[SHA1_SIZE];
  1552. Zero(ctoken_hash, sizeof(ctoken_hash));
  1553. // Examine the quota of new session creation
  1554. if (LIST_NUM(r->SessionList) >= RUDP_QUOTA_MAX_NUM_SESSIONS)
  1555. {
  1556. // Entire number of sessions exceeds the limit
  1557. ok = false;
  1558. }
  1559. else if (r->NatT_EnableSourceIpValidation && RUDPIsIpInValidateList(r, &p->SrcIP) == false)
  1560. {
  1561. // Invalid source IP address, which is not registered on the validated source IP address list
  1562. ok = false;
  1563. }
  1564. else
  1565. {
  1566. UINT i;
  1567. // Check the number of sessions per IP address
  1568. UINT num = 0;
  1569. for (i = 0;i < LIST_NUM(r->SessionList);i++)
  1570. {
  1571. RUDP_SESSION *se = LIST_DATA(r->SessionList, i);
  1572. if (CmpIpAddr(&se->YourIp, &p->SrcIP) == 0)
  1573. {
  1574. num++;
  1575. }
  1576. }
  1577. if (num >= RUDP_QUOTA_MAX_NUM_SESSIONS_PER_IP)
  1578. {
  1579. // Limit exceeded the number of sessions per IP address
  1580. ok = false;
  1581. }
  1582. }
  1583. if (ok)
  1584. {
  1585. char ip_str[64];
  1586. // Create a session since a new session creation request packet was received
  1587. se = RUDPNewSession(true, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, p->Data);
  1588. se->Status = RUDP_SESSION_STATUS_ESTABLISHED;
  1589. Insert(r->SessionList, se);
  1590. IPToStr(ip_str, sizeof(ip_str), &p->SrcIP);
  1591. Debug("RUDPNewSession %X %s:%u\n", se, ip_str, p->SrcPort);
  1592. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  1593. {
  1594. // In case of ICMP, save the ICMP TYPE number to use
  1595. se->Icmp_Type = (p->Type == ICMP_TYPE_INFORMATION_REQUEST ? ICMP_TYPE_INFORMATION_REPLY : p->Type);
  1596. }
  1597. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  1598. {
  1599. // Save the Tran ID to be used if it's a DNS
  1600. se->Dns_TranId = (USHORT)p->Type;
  1601. }
  1602. }
  1603. }
  1604. }
  1605. }
  1606. else
  1607. {
  1608. if (p->Size < 40)
  1609. {
  1610. if (r->ServerMode)
  1611. {
  1612. if (Cmp(se->Key_Init, p->Data, SHA1_SIZE) == 0)
  1613. {
  1614. // New session creation request packet have received more than once. reply an ACK immediately for second and subsequent
  1615. se->LastSentTick = 0;
  1616. // Update the endpoint information
  1617. Copy(&se->YourIp, &p->SrcIP, sizeof(IP));
  1618. se->YourPort = p->SrcPort;
  1619. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  1620. {
  1621. // In case of ICMP, save the ICMP TYPE number to use
  1622. se->Icmp_Type = (p->Type == ICMP_TYPE_INFORMATION_REQUEST ? ICMP_TYPE_INFORMATION_REPLY : p->Type);
  1623. }
  1624. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  1625. {
  1626. // Save the Tran ID to be used if it's a DNS
  1627. se->Dns_TranId = (USHORT)p->Type;
  1628. }
  1629. }
  1630. else
  1631. {
  1632. // Since the different session creation request packet have been received from the same end point, ignore it
  1633. }
  1634. }
  1635. }
  1636. else
  1637. {
  1638. // Process the received packet
  1639. if (RUDPProcessRecvPacket(r, se, p->Data, p->Size) || RUDPProcessBulkRecvPacket(r, se, p->Data, p->Size))
  1640. {
  1641. // Update endpoint information (only the port number)
  1642. //Copy(&se->YourIp, &p->SrcIP, sizeof(IP));
  1643. se->YourPort = p->SrcPort;
  1644. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  1645. {
  1646. // In case of ICMP, save the ICMP TYPE number to use
  1647. if (r->ServerMode)
  1648. {
  1649. se->Icmp_Type = (p->Type == ICMP_TYPE_INFORMATION_REQUEST ? ICMP_TYPE_INFORMATION_REPLY : p->Type);
  1650. }
  1651. else
  1652. {
  1653. se->Icmp_Type = (p->Type == ICMP_TYPE_INFORMATION_REPLY ? ICMP_TYPE_INFORMATION_REQUEST : p->Type);
  1654. }
  1655. }
  1656. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  1657. {
  1658. if (r->ServerMode)
  1659. {
  1660. // Save the Tran ID to be used if it's a DNS
  1661. se->Dns_TranId = (USHORT)p->Type;
  1662. }
  1663. }
  1664. }
  1665. }
  1666. }
  1667. }
  1668. // Check whether the specificed IP address is in the validated source IP address list
  1669. bool RUDPIsIpInValidateList(RUDP_STACK *r, IP *ip)
  1670. {
  1671. UINT i;
  1672. UINT64 now = Tick64();
  1673. LIST *o = NULL;
  1674. bool ret = false;
  1675. // Validate arguments
  1676. if (r == NULL || ip == NULL)
  1677. {
  1678. return false;
  1679. }
  1680. // Always allow private IP addresses
  1681. if (IsIPPrivate(ip))
  1682. {
  1683. return true;
  1684. }
  1685. if (IsIPAddressInSameLocalNetwork(ip))
  1686. {
  1687. return true;
  1688. }
  1689. for (i = 0;i < LIST_NUM(r->NatT_SourceIpList);i++)
  1690. {
  1691. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(r->NatT_SourceIpList, i);
  1692. if (s->ExpiresTick <= now)
  1693. {
  1694. if (o == NULL)
  1695. {
  1696. o = NewListFast(NULL);
  1697. }
  1698. Add(o, s);
  1699. }
  1700. }
  1701. if (o != NULL)
  1702. {
  1703. for (i = 0;i < LIST_NUM(o);i++)
  1704. {
  1705. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(o, i);
  1706. Delete(r->NatT_SourceIpList, s);
  1707. Free(s);
  1708. }
  1709. ReleaseList(o);
  1710. }
  1711. for (i = 0;i < LIST_NUM(r->NatT_SourceIpList);i++)
  1712. {
  1713. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(r->NatT_SourceIpList, i);
  1714. if (CmpIpAddr(&s->ClientIP, ip) == 0)
  1715. {
  1716. ret = true;
  1717. break;
  1718. }
  1719. }
  1720. Debug("RUDP: NAT-T: Validate IP: %r, ret=%u (current list len = %u)\n", ip, ret, LIST_NUM(r->NatT_SourceIpList));
  1721. return ret;
  1722. }
  1723. // Add an IP address to the validated source IP address list
  1724. void RUDPAddIpToValidateList(RUDP_STACK *r, IP *ip)
  1725. {
  1726. UINT i;
  1727. RUDP_SOURCE_IP *sip;
  1728. UINT64 now = Tick64();
  1729. LIST *o = NULL;
  1730. // Validate arguments
  1731. if (r == NULL || ip == NULL)
  1732. {
  1733. return;
  1734. }
  1735. if (LIST_NUM(r->NatT_SourceIpList) >= RUDP_MAX_VALIDATED_SOURCE_IP_ADDRESSES)
  1736. {
  1737. return;
  1738. }
  1739. for (i = 0;i < LIST_NUM(r->NatT_SourceIpList);i++)
  1740. {
  1741. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(r->NatT_SourceIpList, i);
  1742. if (s->ExpiresTick <= now)
  1743. {
  1744. if (o == NULL)
  1745. {
  1746. o = NewListFast(NULL);
  1747. }
  1748. Add(o, s);
  1749. }
  1750. }
  1751. if (o != NULL)
  1752. {
  1753. for (i = 0;i < LIST_NUM(o);i++)
  1754. {
  1755. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(o, i);
  1756. Delete(r->NatT_SourceIpList, s);
  1757. Free(s);
  1758. }
  1759. ReleaseList(o);
  1760. }
  1761. sip = NULL;
  1762. for (i = 0;i < LIST_NUM(r->NatT_SourceIpList);i++)
  1763. {
  1764. RUDP_SOURCE_IP *s = (RUDP_SOURCE_IP *)LIST_DATA(r->NatT_SourceIpList, i);
  1765. if (CmpIpAddr(&s->ClientIP, ip) == 0)
  1766. {
  1767. sip = s;
  1768. break;
  1769. }
  1770. }
  1771. if (sip == NULL)
  1772. {
  1773. sip = ZeroMalloc(sizeof(RUDP_SOURCE_IP));
  1774. Copy(&sip->ClientIP, ip, sizeof(IP));
  1775. Add(r->NatT_SourceIpList, sip);
  1776. }
  1777. sip->ExpiresTick = now + (UINT64)RUDP_VALIDATED_SOURCE_IP_ADDRESS_EXPIRES;
  1778. Debug("RUDP: NAT-T: Src IP added: %r (current list len = %u)\n", ip, LIST_NUM(r->NatT_SourceIpList));
  1779. }
  1780. // R-UDP interrupt processing procedure
  1781. void RUDPInterruptProc(RUDP_STACK *r)
  1782. {
  1783. UINT i;
  1784. LIST *o;
  1785. // Validate arguments
  1786. if (r == NULL)
  1787. {
  1788. return;
  1789. }
  1790. // Packet transmission and other process for NAT-T server
  1791. if (r->NoNatTRegister == false)
  1792. {
  1793. RUDPDo_NatT_Interrupt(r);
  1794. }
  1795. if (r->ServerMode == false)
  1796. {
  1797. if (r->ClientInitiated == false)
  1798. {
  1799. bool client_target_inited = false;
  1800. Lock(r->Lock);
  1801. {
  1802. client_target_inited = r->TargetIpAndPortInited;
  1803. }
  1804. Unlock(r->Lock);
  1805. if (client_target_inited)
  1806. {
  1807. // Start a connection when there is the end point information of the destination server to connect as a client
  1808. RUDP_SESSION *se;
  1809. UCHAR init_key[SHA1_SIZE];
  1810. char ip_str[128];
  1811. UINT64 ui;
  1812. Rand(init_key, SHA1_SIZE);
  1813. se = RUDPNewSession(false, &r->UdpSock->LocalIP, r->UdpSock->LocalPort,
  1814. &r->TargetIp, r->TargetPort, init_key);
  1815. IPToStr(ip_str, sizeof(ip_str), &r->TargetIp);
  1816. Debug("RUDPNewSession %X %s:%u\n", se, ip_str, r->TargetPort);
  1817. Insert(r->SessionList, se);
  1818. ui = Endian64(se->Magic_Disconnect);
  1819. WriteFifo(se->SendFifo, &ui, sizeof(UINT64));
  1820. r->ClientInitiated = true;
  1821. }
  1822. }
  1823. }
  1824. // Process for all the sessions
  1825. for (i = 0;i < LIST_NUM(r->SessionList);i++)
  1826. {
  1827. RUDP_SESSION *se = LIST_DATA(r->SessionList, i);
  1828. if (r->Halt)
  1829. {
  1830. // Disconnect all the sessions if the R-UDP stack stopped
  1831. RUDPDisconnectSession(r, se, false);
  1832. }
  1833. if (se->FlushBulkSendTube)
  1834. {
  1835. if (se->TcpSock != NULL && se->TcpSock->BulkSendTube != NULL)
  1836. {
  1837. TubeFlush(se->TcpSock->BulkSendTube);
  1838. }
  1839. se->FlushBulkSendTube = false;
  1840. }
  1841. if (se->Status == RUDP_SESSION_STATUS_ESTABLISHED)
  1842. {
  1843. // Process for all of the sessions which is established a connection
  1844. UINT j;
  1845. if (r->Now >= (se->LatestRecvMyTick + (UINT64)RUDP_TIMEOUT))
  1846. {
  1847. // Disconnect the session because the fully communication failure is detected for a while
  1848. Debug("R-UDP Session %X Timed Out.\n", se);
  1849. RUDPDisconnectSession(r, se, false);
  1850. }
  1851. // If there are received segments, read to the part that has arrived in succession
  1852. if (FifoSize(se->RecvFifo) <= RUDP_MAX_FIFO_SIZE)
  1853. {
  1854. LIST *o;
  1855. UINT64 current_seq_no;
  1856. o = NULL;
  1857. current_seq_no = se->LastRecvCompleteSeqNo;
  1858. for (j = 0;j < LIST_NUM(se->RecvSegmentList);j++)
  1859. {
  1860. RUDP_SEGMENT *s;
  1861. current_seq_no++;
  1862. s = LIST_DATA(se->RecvSegmentList, j);
  1863. if (s->SeqNo == current_seq_no)
  1864. {
  1865. #ifdef RUDP_DETAIL_LOG
  1866. Debug("%X s->SeqNo = %I64u, current_seq_no = %I64u\n", se, s->SeqNo, current_seq_no);
  1867. #endif // RUDP_DETAIL_LOG
  1868. if (s->Size == sizeof(se->Magic_KeepAliveRequest) && Cmp(s->Data, se->Magic_KeepAliveRequest, sizeof(se->Magic_KeepAliveRequest)) == 0)
  1869. {
  1870. // Receive the KeepAlive Request
  1871. #ifdef RUDP_DETAIL_LOG
  1872. Debug("Recv KeepAlive Request\n");
  1873. #endif // RUDP_DETAIL_LOG
  1874. // Send a KeepAlive Response if the transmisson queue is empty
  1875. if (LIST_NUM(se->SendSegmentList) == 0)
  1876. {
  1877. #ifdef RUDP_DETAIL_LOG
  1878. Debug("Send KeepAlive Response\n");
  1879. #endif // RUDP_DETAIL_LOG
  1880. RUDPSendSegment(r, se, se->Magic_KeepAliveResponse, sizeof(se->Magic_KeepAliveResponse));
  1881. }
  1882. }
  1883. else if (s->Size == sizeof(se->Magic_KeepAliveResponse) && Cmp(s->Data, se->Magic_KeepAliveResponse, sizeof(se->Magic_KeepAliveResponse)) == 0)
  1884. {
  1885. // Receive the KeepAlive Response
  1886. #ifdef RUDP_DETAIL_LOG
  1887. Debug("Recv KeepAlive Response\n");
  1888. #endif // RUDP_DETAIL_LOG
  1889. }
  1890. else
  1891. {
  1892. // Write to the receive FIFO
  1893. WriteFifo(se->RecvFifo, s->Data, s->Size);
  1894. }
  1895. r->TotalLogicalReceived += s->Size;
  1896. // Advance the SEQ NO which has been received completely
  1897. se->LastRecvCompleteSeqNo = s->SeqNo;
  1898. // Add to the Delete list
  1899. if (o == NULL)
  1900. {
  1901. o = NewListFast(NULL);
  1902. }
  1903. Add(o, s);
  1904. }
  1905. else
  1906. {
  1907. // Continuous reading is interrupted
  1908. #ifdef RUDP_DETAIL_LOG
  1909. Debug("%X s->SeqNo = %I64u, current_seq_no = %I64u\n", se, s->SeqNo, current_seq_no);
  1910. WHERE;
  1911. #endif // RUDP_DETAIL_LOG
  1912. break;
  1913. }
  1914. }
  1915. // Delete the segment which has been received completely
  1916. if (o != NULL)
  1917. {
  1918. for (j = 0;j < LIST_NUM(o);j++)
  1919. {
  1920. RUDP_SEGMENT *s = LIST_DATA(o, j);
  1921. Delete(se->RecvSegmentList, s);
  1922. Free(s);
  1923. }
  1924. ReleaseList(o);
  1925. }
  1926. }
  1927. if (r->ServerMode && se->Magic_Disconnect == 0)
  1928. {
  1929. if (FifoSize(se->RecvFifo) >= sizeof(UINT64))
  1930. {
  1931. UINT64 ui;
  1932. if (ReadFifo(se->RecvFifo, &ui, sizeof(UINT64)) == sizeof(UINT64))
  1933. {
  1934. ui = Endian64(ui);
  1935. if ((ui & 0xffffffff00000000ULL) != 0ULL)
  1936. {
  1937. se->Magic_Disconnect = ui;
  1938. }
  1939. }
  1940. }
  1941. }
  1942. // If the data remains in FIFO, write it to the TCP socket as possible
  1943. if (r->ServerMode == false || se->Magic_Disconnect != 0)
  1944. {
  1945. while (FifoSize(se->RecvFifo) >= 1)
  1946. {
  1947. UINT ret;
  1948. RUDPInitSock(r, se);
  1949. ret = Send(se->TcpSock, FifoPtr(se->RecvFifo), FifoSize(se->RecvFifo), false);
  1950. if (ret == SOCK_LATER)
  1951. {
  1952. // Can not write any more
  1953. break;
  1954. }
  1955. else if (ret == 0)
  1956. {
  1957. // Disconnected
  1958. Disconnect(se->TcpSock);
  1959. RUDPDisconnectSession(r, se, false);
  1960. break;
  1961. }
  1962. else
  1963. {
  1964. // Writing success
  1965. ReadFifo(se->RecvFifo, NULL, ret);
  1966. }
  1967. }
  1968. }
  1969. // Read the data as much as possible from the TCP socket and store it to FIFO
  1970. if (se->TcpSock != NULL)
  1971. {
  1972. SetNoNeedToRead(se->TcpSock);
  1973. while (FifoSize(se->SendFifo) <= RUDP_MAX_FIFO_SIZE)
  1974. {
  1975. UINT ret = Recv(se->TcpSock, r->TmpBuf, sizeof(r->TmpBuf), false);
  1976. if (ret == SOCK_LATER)
  1977. {
  1978. // Can not read any more
  1979. break;
  1980. }
  1981. else if (ret == 0)
  1982. {
  1983. // Disconnected
  1984. Disconnect(se->TcpSock);
  1985. RUDPDisconnectSession(r, se, false);
  1986. break;
  1987. }
  1988. else
  1989. {
  1990. // Reading success
  1991. WriteFifo(se->SendFifo, r->TmpBuf, ret);
  1992. }
  1993. }
  1994. }
  1995. // Attempt to send a divided segment
  1996. while (true)
  1997. {
  1998. UINT64 seq_no_min, seq_no_max;
  1999. seq_no_min = RUDPGetCurrentSendingMinSeqNo(se);
  2000. seq_no_max = RUDPGetCurrentSendingMaxSeqNo(se);
  2001. #ifdef RUDP_DETAIL_LOG
  2002. Debug("min=%I64u max=%I64u\n", seq_no_min, seq_no_max);
  2003. #endif // RUDP_DETAIL_LOG
  2004. if (seq_no_min == 0 || ((seq_no_min + RUDP_MAX_NUM_ACK - 1) >= se->NextSendSeqNo))
  2005. {
  2006. // Because there is a room to send a new segment, send a segment
  2007. UINT size = MIN(FifoSize(se->SendFifo), RUDP_MAX_SEGMENT_SIZE);
  2008. if (size == 0)
  2009. {
  2010. // There is no more data to send in FIFO
  2011. break;
  2012. }
  2013. // Transmission
  2014. RUDPSendSegment(r, se, FifoPtr(se->SendFifo), size);
  2015. r->TotalLogicalSent += size;
  2016. // Advance the FIFO
  2017. ReadFifo(se->SendFifo, NULL, size);
  2018. }
  2019. else
  2020. {
  2021. // There is no room to send a new segment further
  2022. break;
  2023. }
  2024. }
  2025. if (se->DisconnectFlag == false)
  2026. {
  2027. UINT64 seq_no_min;
  2028. if (se->LastSentTick == 0 || (r->Now >= (se->LastSentTick + (UINT64)se->NextKeepAliveInterval)))
  2029. {
  2030. if (LIST_NUM(se->SendSegmentList) == 0)
  2031. {
  2032. // Send a Keep-Alive if no data was sent for a while and the transmission queue is empty
  2033. RUDPSendSegment(r, se, se->Magic_KeepAliveRequest, sizeof(se->Magic_KeepAliveRequest));
  2034. #ifdef RUDP_DETAIL_LOG
  2035. Debug("Sent KeepAlive Request\n");
  2036. #endif // RUDP_DETAIL_LOG
  2037. }
  2038. se->NextKeepAliveInterval = RUDP_KEEPALIVE_INTERVAL_MIN + (Rand32() % (RUDP_KEEPALIVE_INTERVAL_MAX - RUDP_KEEPALIVE_INTERVAL_MIN));
  2039. AddInterrupt(r->Interrupt, r->Now + se->NextKeepAliveInterval);
  2040. }
  2041. seq_no_min = RUDPGetCurrentSendingMinSeqNo(se);
  2042. for (j = 0;j < LIST_NUM(se->SendSegmentList);j++)
  2043. {
  2044. RUDP_SEGMENT *s = LIST_DATA(se->SendSegmentList, j);
  2045. if (s->SeqNo <= (seq_no_min + RUDP_MAX_NUM_ACK - 1))
  2046. {
  2047. if (s->NextSendTick == 0 || r->Now >= s->NextSendTick)
  2048. {
  2049. UINT next_interval;
  2050. // Transmits a segment which has not been sent even once yet, or whose retransmission time has arrived
  2051. RUDPSendSegmentNow(r, se, s->SeqNo, s->Data, s->Size);
  2052. if (se->CurrentRtt != 0)
  2053. {
  2054. next_interval = (se->CurrentRtt * 120 / 100) * Power(2, MIN(s->NumSent, 10));
  2055. }
  2056. else
  2057. {
  2058. next_interval = RUDP_RESEND_TIMER * Power(2, MIN(s->NumSent, 10));
  2059. }
  2060. next_interval = MIN(next_interval, RUDP_RESEND_TIMER_MAX);
  2061. s->NumSent++;
  2062. s->NextSendTick = r->Now + next_interval;
  2063. AddInterrupt(r->Interrupt, s->NextSendTick);
  2064. }
  2065. }
  2066. }
  2067. while (LIST_NUM(se->ReplyAckList) >= 1)
  2068. {
  2069. // If there are ACKs which is not responded yet in the list, send all of them
  2070. RUDPSendSegmentNow(r, se, se->NextSendSeqNo, NULL, 0);
  2071. }
  2072. // Send all if there are bulk transfer data
  2073. if (se->TcpSock != NULL)
  2074. {
  2075. SOCK *s = se->TcpSock;
  2076. if (s->BulkRecvTube != NULL)
  2077. {
  2078. TUBE *t = s->BulkRecvTube;
  2079. while (true)
  2080. {
  2081. TUBEDATA *d = TubeRecvAsync(t);
  2082. if (d == NULL)
  2083. {
  2084. break;
  2085. }
  2086. if (d->Header != NULL && d->HeaderSize == sizeof(TCP_PAIR_HEADER))
  2087. {
  2088. TCP_PAIR_HEADER *h = d->Header;
  2089. if (h->EnableHMac)
  2090. {
  2091. se->UseHMac = true;
  2092. }
  2093. }
  2094. RUDPBulkSend(r, se, d->Data, d->DataSize);
  2095. FreeTubeData(d);
  2096. }
  2097. }
  2098. }
  2099. }
  2100. }
  2101. if (r->ServerMode == false)
  2102. {
  2103. if (se->Status == RUDP_SESSION_STATUS_CONNECT_SENT)
  2104. {
  2105. // Send a connection request periodically from the client side
  2106. if (se->LastSentTick == 0 || ((se->LastSentTick + (UINT64)RUDP_RESEND_TIMER) <= r->Now))
  2107. {
  2108. UCHAR tmp[40];
  2109. UINT size_of_padding = 19;
  2110. UINT size = size_of_padding + SHA1_SIZE;
  2111. se->LastSentTick = r->Now;
  2112. Copy(tmp, se->Key_Init, SHA1_SIZE);
  2113. Rand(tmp + SHA1_SIZE, size_of_padding);
  2114. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  2115. {
  2116. // ICMP packet
  2117. UCHAR *rand_data;
  2118. UINT rand_size;
  2119. rand_size = Rand32() % 64 + 64;
  2120. rand_data = Malloc(rand_size);
  2121. Rand(rand_data, rand_size);
  2122. RUDPSendPacket(r, &se->YourIp, se->YourPort, rand_data, rand_size, ICMP_TYPE_ECHO_REQUEST);
  2123. Free(rand_data);
  2124. se->Client_Icmp_NextSendEchoRequest = r->Now + GenRandInterval(RUDP_CLIENT_ECHO_REQUEST_SEND_INTERVAL_MIN, RUDP_CLIENT_ECHO_REQUEST_SEND_INTERVAL_MAX);
  2125. AddInterrupt(r->Interrupt, se->Client_Icmp_NextSendEchoRequest);
  2126. // Try in both INFORMATION_REQUEST and ECHO_RESPONSE from the client side first
  2127. RUDPSendPacket(r, &se->YourIp, se->YourPort, tmp, size, ICMP_TYPE_ECHO_RESPONSE);
  2128. RUDPSendPacket(r, &se->YourIp, se->YourPort, tmp, size, ICMP_TYPE_INFORMATION_REQUEST);
  2129. }
  2130. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  2131. {
  2132. // DNS
  2133. RUDPSendPacket(r, &se->YourIp, se->YourPort, tmp, size, se->Dns_TranId);
  2134. }
  2135. else
  2136. {
  2137. // Normal UDP
  2138. RUDPSendPacket(r, &se->YourIp, se->YourPort, tmp, size, 0);
  2139. }
  2140. AddInterrupt(r->Interrupt, r->Now + (UINT64)RUDP_RESEND_TIMER);
  2141. }
  2142. }
  2143. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  2144. {
  2145. if (se->Client_Icmp_NextSendEchoRequest == 0 || (r->Now >= se->Client_Icmp_NextSendEchoRequest))
  2146. {
  2147. // Periodic ICMP Echo transmission from the client side when R-UDP used in ICMP mode
  2148. // (To maintain the mapping table of the NAT)
  2149. UCHAR *rand_data;
  2150. UINT rand_size;
  2151. rand_size = Rand32() % 64 + 64;
  2152. rand_data = Malloc(rand_size);
  2153. Rand(rand_data, rand_size);
  2154. RUDPSendPacket(r, &se->YourIp, se->YourPort, rand_data, rand_size, ICMP_TYPE_ECHO_REQUEST);
  2155. Free(rand_data);
  2156. se->Client_Icmp_NextSendEchoRequest = r->Now + GenRandInterval(RUDP_CLIENT_ECHO_REQUEST_SEND_INTERVAL_MIN, RUDP_CLIENT_ECHO_REQUEST_SEND_INTERVAL_MAX);
  2157. AddInterrupt(r->Interrupt, se->Client_Icmp_NextSendEchoRequest);
  2158. }
  2159. }
  2160. }
  2161. }
  2162. // Release the disconnected sessions
  2163. o = NULL;
  2164. for (i = 0;i < LIST_NUM(r->SessionList);i++)
  2165. {
  2166. RUDP_SESSION *se = LIST_DATA(r->SessionList, i);
  2167. if (se->DisconnectFlag)
  2168. {
  2169. if (o == NULL)
  2170. {
  2171. o = NewListFast(NULL);
  2172. }
  2173. Add(o, se);
  2174. }
  2175. }
  2176. if (o != NULL)
  2177. {
  2178. for (i = 0;i < LIST_NUM(o);i++)
  2179. {
  2180. RUDP_SESSION *se = LIST_DATA(o, i);
  2181. Delete(r->SessionList, se);
  2182. RUDPFreeSession(se);
  2183. }
  2184. ReleaseList(o);
  2185. }
  2186. }
  2187. // Do the bulk send
  2188. void RUDPBulkSend(RUDP_STACK *r, RUDP_SESSION *se, void *data, UINT data_size)
  2189. {
  2190. UCHAR *buf;
  2191. UINT buf_size;
  2192. UINT padding_size;
  2193. UINT i;
  2194. CRYPT *c;
  2195. UCHAR crypt_key_src[SHA1_SIZE * 2];
  2196. UCHAR crypt_key[SHA1_SIZE];
  2197. UINT icmp_type;
  2198. UCHAR sign[SHA1_SIZE];
  2199. UCHAR iv[SHA1_SIZE + 1];
  2200. // Validate arguments
  2201. if (r == NULL || se == NULL || (data == NULL && data_size != 0))
  2202. {
  2203. return;
  2204. }
  2205. padding_size = Rand32() % 31 + 1;
  2206. buf_size = SHA1_SIZE + SHA1_SIZE + sizeof(UINT64) + data_size + padding_size;
  2207. buf = Malloc(buf_size);
  2208. // SEQ NO
  2209. WRITE_UINT64(buf + SHA1_SIZE + SHA1_SIZE, se->BulkNextSeqNo);
  2210. se->BulkNextSeqNo++;
  2211. // Data
  2212. Copy(buf + SHA1_SIZE + SHA1_SIZE + sizeof(UINT64), data, data_size);
  2213. // Padding
  2214. for (i = 0;i < padding_size;i++)
  2215. {
  2216. buf[SHA1_SIZE + SHA1_SIZE + sizeof(UINT64) + data_size + i] = (UCHAR)padding_size;
  2217. }
  2218. // Encryption
  2219. Copy(iv, se->BulkNextIv, SHA1_SIZE);
  2220. Copy(crypt_key_src + 0, se->BulkSendKey->Data, SHA1_SIZE);
  2221. Copy(crypt_key_src + SHA1_SIZE, iv, SHA1_SIZE);
  2222. HashSha1(crypt_key, crypt_key_src, SHA1_SIZE * 2);
  2223. c = NewCrypt(crypt_key, sizeof(crypt_key));
  2224. Encrypt(c, buf + SHA1_SIZE + SHA1_SIZE, buf + SHA1_SIZE + SHA1_SIZE, sizeof(UINT64) + data_size + padding_size);
  2225. FreeCrypt(c);
  2226. // IV
  2227. Copy(buf + SHA1_SIZE, iv, SHA1_SIZE);
  2228. // Sign
  2229. if (se->UseHMac == false)
  2230. {
  2231. Copy(buf + 0, se->BulkSendKey->Data, SHA1_SIZE);
  2232. HashSha1(sign, buf, SHA1_SIZE + SHA1_SIZE + sizeof(UINT64) + data_size + padding_size);
  2233. Copy(buf + 0, sign, SHA1_SIZE);
  2234. }
  2235. else
  2236. {
  2237. HMacSha1(buf + 0, se->BulkSendKey->Data, SHA1_SIZE, buf + SHA1_SIZE, SHA1_SIZE + sizeof(UINT64) + data_size + padding_size);
  2238. }
  2239. // Next IV
  2240. Copy(se->BulkNextIv, buf + buf_size - SHA1_SIZE, SHA1_SIZE);
  2241. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  2242. {
  2243. icmp_type = se->Icmp_Type;
  2244. }
  2245. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  2246. {
  2247. icmp_type = se->Dns_TranId;
  2248. }
  2249. RUDPSendPacket(r, &se->YourIp, se->YourPort, buf, buf_size, icmp_type);
  2250. Free(buf);
  2251. }
  2252. // Start a socket for R-UDP Listening
  2253. SOCK *ListenRUDP(char *svc_name, RUDP_STACK_INTERRUPTS_PROC *proc_interrupts, RUDP_STACK_RPC_RECV_PROC *proc_rpc_recv, void *param, UINT port, bool no_natt_register, bool over_dns_mode)
  2254. {
  2255. return ListenRUDPEx(svc_name, proc_interrupts, proc_rpc_recv, param, port, no_natt_register, over_dns_mode, NULL, 0);
  2256. }
  2257. SOCK *ListenRUDPEx(char *svc_name, RUDP_STACK_INTERRUPTS_PROC *proc_interrupts, RUDP_STACK_RPC_RECV_PROC *proc_rpc_recv, void *param, UINT port, bool no_natt_register, bool over_dns_mode,
  2258. volatile UINT *natt_global_udp_port, UCHAR rand_port_id)
  2259. {
  2260. SOCK *s;
  2261. RUDP_STACK *r;
  2262. // Creating a R-UDP stack
  2263. r = NewRUDPServer(svc_name, proc_interrupts, proc_rpc_recv, param, port, no_natt_register, over_dns_mode, natt_global_udp_port, rand_port_id);
  2264. if (r == NULL)
  2265. {
  2266. return NULL;
  2267. }
  2268. s = NewSock();
  2269. s->Type = SOCK_RUDP_LISTEN;
  2270. s->ListenMode = true;
  2271. s->Connected = true;
  2272. s->LocalPort = r->UdpSock->LocalPort;
  2273. s->R_UDP_Stack = r;
  2274. return s;
  2275. }
  2276. // Accept on the R-UDP socket
  2277. SOCK *AcceptRUDP(SOCK *s)
  2278. {
  2279. // Validate arguments
  2280. if (s == NULL || s->Type != SOCK_RUDP_LISTEN || s->ListenMode == false)
  2281. {
  2282. return NULL;
  2283. }
  2284. while (true)
  2285. {
  2286. RUDP_STACK *r = s->R_UDP_Stack;
  2287. SOCK *ret;
  2288. if (s->Disconnecting || s->CancelAccept)
  2289. {
  2290. return NULL;
  2291. }
  2292. ret = GetNextWithLock(r->NewSockQueue);
  2293. if (ret != NULL)
  2294. {
  2295. switch (r->Protocol)
  2296. {
  2297. case RUDP_PROTOCOL_UDP:
  2298. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_NAT_T);
  2299. break;
  2300. case RUDP_PROTOCOL_DNS:
  2301. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_DNS);
  2302. break;
  2303. case RUDP_PROTOCOL_ICMP:
  2304. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_ICMP);
  2305. break;
  2306. }
  2307. return ret;
  2308. }
  2309. Wait(r->NewSockConnectEvent, INFINITE);
  2310. }
  2311. }
  2312. // Verify the signature of the received packet
  2313. bool RUDPCheckSignOfRecvPacket(RUDP_STACK *r, RUDP_SESSION *se, void *recv_data, UINT recv_size)
  2314. {
  2315. UCHAR sign[SHA1_SIZE];
  2316. UCHAR sign2[SHA1_SIZE];
  2317. UCHAR *p;
  2318. UINT size;
  2319. // Validate arguments
  2320. if (r == NULL || se == NULL || recv_data == NULL || recv_size == 0)
  2321. {
  2322. return false;
  2323. }
  2324. p = (UCHAR *)recv_data;
  2325. size = recv_size;
  2326. if (size < SHA1_SIZE)
  2327. {
  2328. return false;
  2329. }
  2330. // Verification the signature (segment packet)
  2331. Copy(sign, p, SHA1_SIZE);
  2332. Copy(p, se->Key_Recv, SHA1_SIZE);
  2333. HashSha1(sign2, p, recv_size);
  2334. if (r->Protocol == RUDP_PROTOCOL_DNS || r->Protocol == RUDP_PROTOCOL_ICMP)
  2335. {
  2336. XorData(sign2, sign2, r->SvcNameHash, SHA1_SIZE);
  2337. }
  2338. Copy(p, sign, SHA1_SIZE);
  2339. if (Cmp(sign, sign2, SHA1_SIZE) == 0)
  2340. {
  2341. return true;
  2342. }
  2343. if (se->BulkRecvKey == NULL)
  2344. {
  2345. return false;
  2346. }
  2347. // Verification signature (bulk packet)
  2348. if (se->UseHMac == false)
  2349. {
  2350. Copy(sign, p, SHA1_SIZE);
  2351. Copy(p, se->BulkRecvKey->Data, SHA1_SIZE);
  2352. HashSha1(sign2, p, recv_size);
  2353. Copy(p, sign, SHA1_SIZE);
  2354. if (Cmp(sign, sign2, SHA1_SIZE) == 0)
  2355. {
  2356. return true;
  2357. }
  2358. }
  2359. HMacSha1(sign2, se->BulkRecvKey->Data, SHA1_SIZE, p + SHA1_SIZE, size - SHA1_SIZE);
  2360. if (Cmp(p, sign2, SHA1_SIZE) == 0)
  2361. {
  2362. se->UseHMac = true;
  2363. return true;
  2364. }
  2365. return false;
  2366. }
  2367. // Process the received packet (bulk)
  2368. bool RUDPProcessBulkRecvPacket(RUDP_STACK *r, RUDP_SESSION *se, void *recv_data, UINT recv_size)
  2369. {
  2370. UCHAR sign[SHA1_SIZE];
  2371. UCHAR sign2[SHA1_SIZE];
  2372. UCHAR *p;
  2373. UCHAR *iv;
  2374. UINT size;
  2375. UCHAR keygen[SHA1_SIZE * 2];
  2376. UCHAR key[SHA1_SIZE];
  2377. CRYPT *c;
  2378. UCHAR padlen;
  2379. UINT64 seq_no;
  2380. UCHAR *payload;
  2381. UINT payload_size;
  2382. // Validate arguments
  2383. if (r == NULL || se == NULL || recv_data == NULL || recv_size == 0 || se->BulkRecvKey == NULL)
  2384. {
  2385. return false;
  2386. }
  2387. p = (UCHAR *)recv_data;
  2388. size = recv_size;
  2389. if (size < SHA1_SIZE)
  2390. {
  2391. return false;
  2392. }
  2393. // Validate the signature
  2394. if (se->UseHMac == false)
  2395. {
  2396. Copy(sign, p, SHA1_SIZE);
  2397. Copy(p, se->BulkRecvKey->Data, SHA1_SIZE);
  2398. HashSha1(sign2, p, recv_size);
  2399. Copy(p, sign, SHA1_SIZE);
  2400. if (Cmp(sign, sign2, SHA1_SIZE) != 0)
  2401. {
  2402. HMacSha1(sign2, se->BulkRecvKey->Data, SHA1_SIZE, p + SHA1_SIZE, recv_size - SHA1_SIZE);
  2403. if (Cmp(p, sign2, SHA1_SIZE) != 0)
  2404. {
  2405. return false;
  2406. }
  2407. else
  2408. {
  2409. se->UseHMac = true;
  2410. }
  2411. }
  2412. else
  2413. {
  2414. }
  2415. }
  2416. else
  2417. {
  2418. HMacSha1(sign2, se->BulkRecvKey->Data, SHA1_SIZE, p + SHA1_SIZE, recv_size - SHA1_SIZE);
  2419. if (Cmp(p, sign2, SHA1_SIZE) != 0)
  2420. {
  2421. return false;
  2422. }
  2423. }
  2424. p += SHA1_SIZE;
  2425. size -= SHA1_SIZE;
  2426. // IV
  2427. if (size < SHA1_SIZE)
  2428. {
  2429. return false;
  2430. }
  2431. iv = p;
  2432. p += SHA1_SIZE;
  2433. size -= SHA1_SIZE;
  2434. // Decrypt
  2435. if (size < 1)
  2436. {
  2437. return false;
  2438. }
  2439. Copy(keygen + 0, se->BulkRecvKey->Data, SHA1_SIZE);
  2440. Copy(keygen + SHA1_SIZE, iv, SHA1_SIZE);
  2441. HashSha1(key, keygen, sizeof(keygen));
  2442. c = NewCrypt(key, sizeof(key));
  2443. Encrypt(c, p, p, size);
  2444. FreeCrypt(c);
  2445. // padlen
  2446. padlen = p[size - 1];
  2447. if (padlen == 0)
  2448. {
  2449. return false;
  2450. }
  2451. if (size < padlen)
  2452. {
  2453. return false;
  2454. }
  2455. size -= padlen;
  2456. // SEQ NO
  2457. seq_no = READ_UINT64(p);
  2458. p += sizeof(UINT64);
  2459. size -= sizeof(UINT64);
  2460. if (seq_no == 0 || seq_no >= (0xF000000000000000ULL))
  2461. {
  2462. // Sequence number is invalid
  2463. return false;
  2464. }
  2465. if ((seq_no + RUDP_BULK_SEQ_NO_RANGE) < se->BulkRecvSeqNoMax)
  2466. {
  2467. // Sequence number is too small
  2468. return false;
  2469. }
  2470. se->LastRecvTick = r->Now;
  2471. payload = p;
  2472. payload_size = size;
  2473. se->BulkRecvSeqNoMax = MAX(seq_no, se->BulkRecvSeqNoMax);
  2474. // Send the received bulk packet to the Tube of the socket
  2475. RUDPInitSock(r, se);
  2476. if (se->TcpSock != NULL)
  2477. {
  2478. SOCK *s = se->TcpSock;
  2479. TUBE *t = s->BulkSendTube;
  2480. if (t != NULL)
  2481. {
  2482. TubeSendEx2(t, payload, payload_size, NULL, true, RUDP_BULK_MAX_RECV_PKTS_IN_QUEUE);
  2483. se->FlushBulkSendTube = true;
  2484. }
  2485. }
  2486. return true;
  2487. }
  2488. // Process the received packet (segment)
  2489. bool RUDPProcessRecvPacket(RUDP_STACK *r, RUDP_SESSION *se, void *recv_data, UINT recv_size)
  2490. {
  2491. UCHAR sign[SHA1_SIZE];
  2492. UCHAR sign2[SHA1_SIZE];
  2493. UCHAR *p;
  2494. UCHAR *iv;
  2495. UINT size;
  2496. UCHAR keygen[SHA1_SIZE * 2];
  2497. UCHAR key[SHA1_SIZE];
  2498. CRYPT *c;
  2499. UCHAR padlen;
  2500. UINT num_ack;
  2501. UINT i;
  2502. UINT64 seq_no;
  2503. UCHAR *payload;
  2504. UINT payload_size;
  2505. UINT64 max_ack;
  2506. UINT64 my_tick, your_tick;
  2507. // Validate arguments
  2508. if (r == NULL || se == NULL || recv_data == NULL || recv_size == 0)
  2509. {
  2510. return false;
  2511. }
  2512. p = (UCHAR *)recv_data;
  2513. size = recv_size;
  2514. if (size < SHA1_SIZE)
  2515. {
  2516. return false;
  2517. }
  2518. // Validate the signature
  2519. Copy(sign, p, SHA1_SIZE);
  2520. Copy(p, se->Key_Recv, SHA1_SIZE);
  2521. HashSha1(sign2, p, recv_size);
  2522. Copy(p, sign, SHA1_SIZE);
  2523. if (r->Protocol == RUDP_PROTOCOL_DNS || r->Protocol == RUDP_PROTOCOL_ICMP)
  2524. {
  2525. XorData(sign2, sign2, r->SvcNameHash, SHA1_SIZE);
  2526. }
  2527. if (Cmp(sign, sign2, SHA1_SIZE) != 0)
  2528. {
  2529. //WHERE;
  2530. return false;
  2531. }
  2532. p += SHA1_SIZE;
  2533. size -= SHA1_SIZE;
  2534. // IV
  2535. if (size < SHA1_SIZE)
  2536. {
  2537. return false;
  2538. }
  2539. iv = p;
  2540. p += SHA1_SIZE;
  2541. size -= SHA1_SIZE;
  2542. // Decrypt
  2543. if (size < 1)
  2544. {
  2545. return false;
  2546. }
  2547. Copy(keygen + 0, iv, SHA1_SIZE);
  2548. Copy(keygen + SHA1_SIZE, se->Key_Recv, SHA1_SIZE);
  2549. HashSha1(key, keygen, sizeof(keygen));
  2550. c = NewCrypt(key, sizeof(key));
  2551. Encrypt(c, p, p, size);
  2552. FreeCrypt(c);
  2553. // padlen
  2554. padlen = p[size - 1];
  2555. if (padlen == 0)
  2556. {
  2557. return false;
  2558. }
  2559. if (size < padlen)
  2560. {
  2561. return false;
  2562. }
  2563. size -= padlen;
  2564. // MyTick
  2565. if (size < sizeof(UINT64))
  2566. {
  2567. return false;
  2568. }
  2569. my_tick = READ_UINT64(p);
  2570. p += sizeof(UINT64);
  2571. size -= sizeof(UINT64);
  2572. // YourTick
  2573. if (size < sizeof(UINT64))
  2574. {
  2575. return false;
  2576. }
  2577. your_tick = READ_UINT64(p);
  2578. p += sizeof(UINT64);
  2579. size -= sizeof(UINT64);
  2580. if (your_tick > r->Now)
  2581. {
  2582. return false;
  2583. }
  2584. // MAX_ACK
  2585. if (size < sizeof(UINT64))
  2586. {
  2587. return false;
  2588. }
  2589. max_ack = READ_UINT64(p);
  2590. p += sizeof(UINT64);
  2591. size -= sizeof(UINT64);
  2592. // num_ack
  2593. if (size < sizeof(UINT))
  2594. {
  2595. return false;
  2596. }
  2597. num_ack = READ_UINT(p);
  2598. if (num_ack > RUDP_MAX_NUM_ACK)
  2599. {
  2600. return false;
  2601. }
  2602. p += sizeof(UINT);
  2603. size -= sizeof(UINT);
  2604. // ACKs
  2605. if (size < (sizeof(UINT64) * num_ack + sizeof(UINT64)))
  2606. {
  2607. return false;
  2608. }
  2609. if (max_ack >= 1)
  2610. {
  2611. RUDPProcessAck2(r, se, max_ack);
  2612. }
  2613. for (i = 0;i < num_ack;i++)
  2614. {
  2615. UINT64 seq = READ_UINT64(p);
  2616. RUDPProcessAck(r, se, seq);
  2617. p += sizeof(UINT64);
  2618. size -= sizeof(UINT64);
  2619. }
  2620. // Processing of the Tick (Calculation of RTT)
  2621. if (my_tick >= 2)
  2622. {
  2623. my_tick--;
  2624. }
  2625. se->YourTick = MAX(se->YourTick, my_tick);
  2626. se->LatestRecvMyTick = MAX(se->LatestRecvMyTick, your_tick);
  2627. if (se->LatestRecvMyTick2 != se->LatestRecvMyTick)
  2628. {
  2629. se->LatestRecvMyTick2 = se->LatestRecvMyTick;
  2630. se->CurrentRtt = (UINT)(r->Now - se->LatestRecvMyTick);
  2631. #ifdef RUDP_DETAIL_LOG
  2632. Debug("CurrentRTT = %u\n", se->CurrentRtt);
  2633. #endif // RUDP_DETAIL_LOG
  2634. }
  2635. // SEQ NO
  2636. seq_no = READ_UINT64(p);
  2637. p += sizeof(UINT64);
  2638. size -= sizeof(UINT64);
  2639. if (seq_no == 0)
  2640. {
  2641. // Sequence number of 0 is a invalid packet
  2642. return true;
  2643. }
  2644. if (seq_no == se->Magic_Disconnect)
  2645. {
  2646. // Disconnected from opponent
  2647. RUDPDisconnectSession(r, se, true);
  2648. return true;
  2649. }
  2650. // Update the last reception date and time
  2651. se->LastRecvTick = r->Now;
  2652. payload = p;
  2653. payload_size = size;
  2654. #ifdef RUDP_DETAIL_LOG
  2655. Debug("RUDP %X Segment Recv: %I64u (num_ack=%u, size=%u)\n", se, seq_no, num_ack, size);
  2656. #endif // RUDP_DETAIL_LOG
  2657. if (payload_size >= 1 && payload_size <= RUDP_MAX_SEGMENT_SIZE)
  2658. {
  2659. // Received one or more bytes of data
  2660. #ifdef RUDP_DETAIL_LOG
  2661. Debug("Recv Size: %X %I64u %u %u\n", se, seq_no, payload_size, recv_size);
  2662. #endif // RUDP_DETAIL_LOG
  2663. RUDPProcessRecvPayload(r, se, seq_no, payload, payload_size);
  2664. }
  2665. if (r->ServerMode == false)
  2666. {
  2667. if (se->Status == RUDP_SESSION_STATUS_CONNECT_SENT)
  2668. {
  2669. // Shift to the established state if the connection is not yet in established state
  2670. se->Status = RUDP_SESSION_STATUS_ESTABLISHED;
  2671. RUDPInitSock(r, se);
  2672. }
  2673. }
  2674. return true;
  2675. }
  2676. // Disconnect the session
  2677. void RUDPDisconnectSession(RUDP_STACK *r, RUDP_SESSION *se, bool disconnected_by_you)
  2678. {
  2679. // Validate arguments
  2680. if (r == NULL || se == NULL)
  2681. {
  2682. return;
  2683. }
  2684. if (se->DisconnectFlag == false)
  2685. {
  2686. UINT i;
  2687. se->DisconnectFlag = true;
  2688. se->DisconnectedByYou = disconnected_by_you;
  2689. Debug("R-UDP Session %X Disconnected. by you flag: %u\n", se, disconnected_by_you);
  2690. if (se->TcpSock != NULL)
  2691. {
  2692. // Disconnect a TCP socket
  2693. Disconnect(se->TcpSock);
  2694. ReleaseSock(se->TcpSock);
  2695. se->TcpSock = NULL;
  2696. }
  2697. // Send 5 disconnect signals serially if to disconnect from here
  2698. if (disconnected_by_you == false)
  2699. {
  2700. for (i = 0;i < 5;i++)
  2701. {
  2702. RUDPSendSegmentNow(r, se, se->Magic_Disconnect, NULL, 0);
  2703. }
  2704. }
  2705. }
  2706. }
  2707. // Initialize the TCP socket for the session
  2708. void RUDPInitSock(RUDP_STACK *r, RUDP_SESSION *se)
  2709. {
  2710. SOCK *s1, *s2;
  2711. UINT mss;
  2712. // Validate arguments
  2713. if (r == NULL || se == NULL || se->DisconnectFlag)
  2714. {
  2715. return;
  2716. }
  2717. if (se->TcpSock != NULL)
  2718. {
  2719. // It has already been created
  2720. return;
  2721. }
  2722. // Creating a TCP socket pair
  2723. if (NewTcpPair(&s1, &s2) == false)
  2724. {
  2725. // Failed to create. Disconnect the session
  2726. RUDPDisconnectSession(r, se, false);
  2727. return;
  2728. }
  2729. // Calculate the optimal MSS
  2730. mss = RUDPCalcBestMssForBulk(r, se);
  2731. if (r->ServerMode)
  2732. {
  2733. // Server mode
  2734. se->TcpSock = s2;
  2735. JoinSockToSockEvent(s2, r->SockEvent);
  2736. // Update the end point information of the socket s1
  2737. ZeroIP4(&s1->LocalIP);
  2738. s1->LocalPort = se->MyPort;
  2739. Copy(&s1->RemoteIP, &se->YourIp, sizeof(IP));
  2740. s1->RemotePort = se->YourPort;
  2741. if (IsLocalHostIP(&s1->RemoteIP) == false)
  2742. {
  2743. AddIpClient(&s1->RemoteIP);
  2744. s1->IpClientAdded = true;
  2745. }
  2746. s1->IsRUDPSocket = true;
  2747. s1->BulkSendKey = se->BulkSendKey;
  2748. s1->BulkRecvKey = se->BulkRecvKey;
  2749. AddRef(s1->BulkSendKey->Ref);
  2750. AddRef(s1->BulkRecvKey->Ref);
  2751. s1->RUDP_OptimizedMss = mss;
  2752. // Enqueue the newly created socket, and set the event
  2753. InsertQueueWithLock(r->NewSockQueue, s1);
  2754. Set(r->NewSockConnectEvent);
  2755. }
  2756. else
  2757. {
  2758. // Client mode
  2759. Lock(r->Lock);
  2760. {
  2761. if (r->TargetConnectedSock == NULL && r->DoNotSetTargetConnectedSock == false)
  2762. {
  2763. // Update the end point information of the socket s2
  2764. Copy(&s2->LocalIP, &r->UdpSock->LocalIP, sizeof(IP));
  2765. s2->LocalPort = se->MyPort;
  2766. Copy(&s2->RemoteIP, &se->YourIp, sizeof(IP));
  2767. s2->RemotePort = se->YourPort;
  2768. if (IsLocalHostIP(&s2->RemoteIP) == false)
  2769. {
  2770. AddIpClient(&s2->RemoteIP);
  2771. s2->IpClientAdded = true;
  2772. }
  2773. s2->IsRUDPSocket = true;
  2774. s2->BulkSendKey = se->BulkSendKey;
  2775. s2->BulkRecvKey = se->BulkRecvKey;
  2776. AddRef(s2->BulkSendKey->Ref);
  2777. AddRef(s2->BulkRecvKey->Ref);
  2778. s2->RUDP_OptimizedMss = mss;
  2779. // Register the socket to the RUDP stack
  2780. r->TargetConnectedSock = s2;
  2781. s2->R_UDP_Stack = r;
  2782. se->TcpSock = s1;
  2783. JoinSockToSockEvent(s1, r->SockEvent);
  2784. // Set the event to be set when the connection is successful
  2785. Set(r->TargetConnectedEvent);
  2786. }
  2787. else
  2788. {
  2789. Disconnect(s1);
  2790. Disconnect(s2);
  2791. ReleaseSock(s1);
  2792. ReleaseSock(s2);
  2793. }
  2794. }
  2795. Unlock(r->Lock);
  2796. }
  2797. }
  2798. // Process the received payload
  2799. void RUDPProcessRecvPayload(RUDP_STACK *r, RUDP_SESSION *se, UINT64 seq, void *payload_data, UINT payload_size)
  2800. {
  2801. RUDP_SEGMENT t;
  2802. RUDP_SEGMENT *s;
  2803. // Validate arguments
  2804. if (r == NULL || se == NULL || seq == 0 || payload_data == NULL || payload_size == 0 || payload_size > RUDP_MAX_SEGMENT_SIZE)
  2805. {
  2806. return;
  2807. }
  2808. if (seq > (se->LastRecvCompleteSeqNo + RUDP_MAX_NUM_ACK))
  2809. {
  2810. // Ignore the segment which have sequence number beyond the window size, and also not to reply an ACK
  2811. return;
  2812. }
  2813. if (seq <= se->LastRecvCompleteSeqNo)
  2814. {
  2815. // Do not receive the segment which have the sequence number that has been already received. However, reply an ACK for it
  2816. AddInt64Distinct(se->ReplyAckList, seq);
  2817. return;
  2818. }
  2819. Zero(&t, sizeof(t));
  2820. t.SeqNo = seq;
  2821. s = Search(se->RecvSegmentList, &t);
  2822. if (s != NULL)
  2823. {
  2824. // Do not receive the segment which have the sequence number that has been already received. However, reply an ACK for it
  2825. AddInt64Distinct(se->ReplyAckList, seq);
  2826. return;
  2827. }
  2828. // Received a segment of the new sequence number
  2829. s = ZeroMalloc(sizeof(RUDP_SEGMENT));
  2830. s->SeqNo = seq;
  2831. Copy(s->Data, payload_data, payload_size);
  2832. s->Size = payload_size;
  2833. Insert(se->RecvSegmentList, s);
  2834. // Reply an ACK
  2835. AddInt64Distinct(se->ReplyAckList, seq);
  2836. // Create a socket for session if it have not been created yet
  2837. //RUDPInitSock(r, se);
  2838. }
  2839. // Process the incoming ACK
  2840. void RUDPProcessAck(RUDP_STACK *r, RUDP_SESSION *se, UINT64 seq)
  2841. {
  2842. RUDP_SEGMENT t;
  2843. RUDP_SEGMENT *s;
  2844. // Validate arguments
  2845. if (r == NULL || se == NULL || seq == 0)
  2846. {
  2847. return;
  2848. }
  2849. Zero(&t, sizeof(t));
  2850. t.SeqNo = seq;
  2851. s = Search(se->SendSegmentList, &t);
  2852. if (s == NULL)
  2853. {
  2854. return;
  2855. }
  2856. Delete(se->SendSegmentList, s);
  2857. Free(s);
  2858. }
  2859. // Remove all segments which are preceding max_seq as already delivered
  2860. void RUDPProcessAck2(RUDP_STACK *r, RUDP_SESSION *se, UINT64 max_seq)
  2861. {
  2862. LIST *o;
  2863. UINT i;
  2864. // Validate arguments
  2865. if (r == NULL || se == NULL || max_seq == 0)
  2866. {
  2867. return;
  2868. }
  2869. o = NULL;
  2870. for (i = 0;i < LIST_NUM(se->SendSegmentList);i++)
  2871. {
  2872. RUDP_SEGMENT *s = LIST_DATA(se->SendSegmentList, i);
  2873. if (s->SeqNo <= max_seq)
  2874. {
  2875. if (o == NULL)
  2876. {
  2877. o = NewListFast(NULL);
  2878. }
  2879. Add(o, s);
  2880. }
  2881. }
  2882. if (o != NULL)
  2883. {
  2884. for (i = 0;i < LIST_NUM(o);i++)
  2885. {
  2886. RUDP_SEGMENT *s = LIST_DATA(o, i);
  2887. Delete(se->SendSegmentList, s);
  2888. Free(s);
  2889. }
  2890. ReleaseList(o);
  2891. }
  2892. }
  2893. // Get the minimum sequence number which is trying to send
  2894. UINT64 RUDPGetCurrentSendingMinSeqNo(RUDP_SESSION *se)
  2895. {
  2896. RUDP_SEGMENT *s;
  2897. // Validate arguments
  2898. if (se == NULL)
  2899. {
  2900. return 0;
  2901. }
  2902. if (LIST_NUM(se->SendSegmentList) == 0)
  2903. {
  2904. return 0;
  2905. }
  2906. s = LIST_DATA(se->SendSegmentList, 0);
  2907. return s->SeqNo;
  2908. }
  2909. // Get the maximum sequence number which is trying to send
  2910. UINT64 RUDPGetCurrentSendingMaxSeqNo(RUDP_SESSION *se)
  2911. {
  2912. RUDP_SEGMENT *s;
  2913. // Validate arguments
  2914. if (se == NULL)
  2915. {
  2916. return 0;
  2917. }
  2918. if (LIST_NUM(se->SendSegmentList) == 0)
  2919. {
  2920. return 0;
  2921. }
  2922. s = LIST_DATA(se->SendSegmentList, (LIST_NUM(se->SendSegmentList) - 1));
  2923. return s->SeqNo;
  2924. }
  2925. // R-UDP segment transmission
  2926. void RUDPSendSegmentNow(RUDP_STACK *r, RUDP_SESSION *se, UINT64 seq_no, void *data, UINT size)
  2927. {
  2928. UCHAR dst[RUDP_MAX_PACKET_SIZE];
  2929. UCHAR *p;
  2930. UCHAR *iv;
  2931. LIST *o = NULL;
  2932. UINT i;
  2933. UCHAR padlen;
  2934. UINT current_size;
  2935. UCHAR sign[SHA1_SIZE];
  2936. UCHAR key[SHA1_SIZE];
  2937. UCHAR keygen[SHA1_SIZE * 2];
  2938. CRYPT *c;
  2939. UINT next_iv_pos;
  2940. UINT num_ack;
  2941. UINT icmp_type = 0;
  2942. // Validate arguments
  2943. if (r == NULL || se == NULL || (size != 0 && data == NULL) || (size > RUDP_MAX_SEGMENT_SIZE))
  2944. {
  2945. return;
  2946. }
  2947. Zero(dst, sizeof(dst));
  2948. p = dst;
  2949. // SIGN
  2950. Copy(p, se->Key_Send, SHA1_SIZE);
  2951. p += SHA1_SIZE;
  2952. // IV
  2953. iv = p;
  2954. Copy(iv, se->NextIv, SHA1_SIZE);
  2955. p += SHA1_SIZE;
  2956. for (i = 0;i < MIN(LIST_NUM(se->ReplyAckList), RUDP_MAX_NUM_ACK);i++)
  2957. {
  2958. UINT64 *seq = LIST_DATA(se->ReplyAckList, i);
  2959. if (o == NULL)
  2960. {
  2961. o = NewListFast(NULL);
  2962. }
  2963. Add(o, seq);
  2964. }
  2965. // MyTick
  2966. WRITE_UINT64(p, r->Now);
  2967. p += sizeof(UINT64);
  2968. // YourTick
  2969. WRITE_UINT64(p, se->YourTick);
  2970. p += sizeof(UINT64);
  2971. // MAX_ACK
  2972. WRITE_UINT64(p, se->LastRecvCompleteSeqNo);
  2973. p += sizeof(UINT64);
  2974. // NUM_ACK
  2975. num_ack = LIST_NUM(o);
  2976. WRITE_UINT(p, num_ack);
  2977. p += sizeof(UINT);
  2978. if (o != NULL)
  2979. {
  2980. // ACK body
  2981. for (i = 0;i < LIST_NUM(o);i++)
  2982. {
  2983. UINT64 *seq = LIST_DATA(o, i);
  2984. WRITE_UINT64(p, *seq);
  2985. p += sizeof(UINT64);
  2986. Delete(se->ReplyAckList, seq);
  2987. Free(seq);
  2988. }
  2989. ReleaseList(o);
  2990. }
  2991. // SEQ
  2992. WRITE_UINT64(p, seq_no);
  2993. p += sizeof(UINT64);
  2994. // data
  2995. Copy(p, data, size);
  2996. p += size;
  2997. // padding
  2998. padlen = Rand8();
  2999. padlen = MAX(padlen, 1);
  3000. for (i = 0;i < padlen;i++)
  3001. {
  3002. *p = padlen;
  3003. p++;
  3004. }
  3005. current_size = (UINT)(p - dst);
  3006. // Encrypt
  3007. Copy(keygen + 0, iv, SHA1_SIZE);
  3008. Copy(keygen + SHA1_SIZE, se->Key_Send, SHA1_SIZE);
  3009. HashSha1(key, keygen, sizeof(keygen));
  3010. c = NewCrypt(key, sizeof(key));
  3011. Encrypt(c, dst + SHA1_SIZE * 2, dst + SHA1_SIZE * 2, current_size - (SHA1_SIZE * 2));
  3012. FreeCrypt(c);
  3013. // Sign
  3014. HashSha1(sign, dst, current_size);
  3015. if (r->Protocol == RUDP_PROTOCOL_DNS || r->Protocol == RUDP_PROTOCOL_ICMP)
  3016. {
  3017. XorData(sign, sign, r->SvcNameHash, SHA1_SIZE);
  3018. }
  3019. Copy(dst, sign, SHA1_SIZE);
  3020. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  3021. {
  3022. icmp_type = se->Icmp_Type;
  3023. }
  3024. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  3025. {
  3026. icmp_type = se->Dns_TranId;
  3027. }
  3028. RUDPSendPacket(r, &se->YourIp, se->YourPort, dst, current_size, icmp_type);
  3029. if (size >= 1)
  3030. {
  3031. se->LastSentTick = r->Now;
  3032. }
  3033. // Next IV
  3034. next_iv_pos = Rand32() % (current_size - SHA1_SIZE);
  3035. Copy(se->NextIv, dst + next_iv_pos, SHA1_SIZE);
  3036. #ifdef RUDP_DETAIL_LOG
  3037. Debug("RUDP %X Segment Sent: %I64u (num_ack=%u, size=%u)\n", se, seq_no, num_ack, size);
  3038. #endif // RUDP_DETAIL_LOG
  3039. if (size >= 1)
  3040. {
  3041. #ifdef RUDP_DETAIL_LOG
  3042. Debug("Send Size: %X %I64u %u %u\n", se, seq_no, size, current_size);
  3043. #endif // RUDP_DETAIL_LOG
  3044. }
  3045. }
  3046. // R-UDP segment transmission (only put into the queue)
  3047. void RUDPSendSegment(RUDP_STACK *r, RUDP_SESSION *se, void *data, UINT size)
  3048. {
  3049. RUDP_SEGMENT *s;
  3050. // Validate arguments
  3051. if (r == NULL || se == NULL || (size != 0 && data == NULL) || (size > RUDP_MAX_SEGMENT_SIZE))
  3052. {
  3053. return;
  3054. }
  3055. s = ZeroMalloc(sizeof(RUDP_SEGMENT));
  3056. Copy(s->Data, data, size);
  3057. s->Size = size;
  3058. s->SeqNo = se->NextSendSeqNo++;
  3059. Insert(se->SendSegmentList, s);
  3060. }
  3061. // Search for a session
  3062. RUDP_SESSION *RUDPSearchSession(RUDP_STACK *r, IP *my_ip, UINT my_port, IP *your_ip, UINT your_port)
  3063. {
  3064. RUDP_SESSION t;
  3065. RUDP_SESSION *se;
  3066. // Validate arguments
  3067. if (r == NULL || my_ip == NULL || your_ip == NULL)
  3068. {
  3069. return NULL;
  3070. }
  3071. Copy(&t.MyIp, my_ip, sizeof(IP));
  3072. t.MyPort = my_port;
  3073. Copy(&t.YourIp, your_ip, sizeof(IP));
  3074. t.YourPort = your_port;
  3075. se = Search(r->SessionList, &t);
  3076. return se;
  3077. }
  3078. // Release of the session
  3079. void RUDPFreeSession(RUDP_SESSION *se)
  3080. {
  3081. UINT i;
  3082. // Validate arguments
  3083. if (se == NULL)
  3084. {
  3085. return;
  3086. }
  3087. Debug("RUDPFreeSession %X\n", se);
  3088. for (i = 0;i < LIST_NUM(se->SendSegmentList);i++)
  3089. {
  3090. RUDP_SEGMENT *s = LIST_DATA(se->SendSegmentList, i);
  3091. Free(s);
  3092. }
  3093. ReleaseList(se->SendSegmentList);
  3094. for (i = 0;i < LIST_NUM(se->RecvSegmentList);i++)
  3095. {
  3096. RUDP_SEGMENT *s = LIST_DATA(se->RecvSegmentList, i);
  3097. Free(s);
  3098. }
  3099. ReleaseList(se->RecvSegmentList);
  3100. if (se->TcpSock != NULL)
  3101. {
  3102. Disconnect(se->TcpSock);
  3103. ReleaseSock(se->TcpSock);
  3104. }
  3105. ReleaseInt64List(se->ReplyAckList);
  3106. ReleaseFifo(se->RecvFifo);
  3107. ReleaseFifo(se->SendFifo);
  3108. ReleaseSharedBuffer(se->BulkSendKey);
  3109. ReleaseSharedBuffer(se->BulkRecvKey);
  3110. Free(se);
  3111. }
  3112. // Create a new session
  3113. RUDP_SESSION *RUDPNewSession(bool server_mode, IP *my_ip, UINT my_port, IP *your_ip, UINT your_port, UCHAR *init_key)
  3114. {
  3115. RUDP_SESSION *se;
  3116. UCHAR key1[SHA1_SIZE];
  3117. UCHAR key2[SHA1_SIZE];
  3118. UCHAR bulk_send_key[SHA1_SIZE];
  3119. UCHAR bulk_recv_key[SHA1_SIZE];
  3120. BUF *b;
  3121. se = ZeroMalloc(sizeof(RUDP_SESSION));
  3122. Copy(&se->MyIp, my_ip, sizeof(IP));
  3123. se->MyPort = my_port;
  3124. Copy(&se->YourIp, your_ip, sizeof(IP));
  3125. se->YourPort = your_port;
  3126. Copy(se->Key_Init, init_key, SHA1_SIZE);
  3127. se->LastSentTick = 0;
  3128. se->LastRecvTick = Tick64();
  3129. se->LatestRecvMyTick = Tick64();
  3130. se->NextSendSeqNo = 1;
  3131. se->ServerMode = server_mode;
  3132. se->SendSegmentList = NewList(RUDPCompareSegmentList);
  3133. se->RecvSegmentList = NewList(RUDPCompareSegmentList);
  3134. // Generate the two keys
  3135. b = NewBuf();
  3136. WriteBuf(b, init_key, SHA1_SIZE);
  3137. WriteBufStr(b, "zurukko");
  3138. HashSha1(key1, b->Buf, b->Size);
  3139. FreeBuf(b);
  3140. b = NewBuf();
  3141. WriteBuf(b, init_key, SHA1_SIZE);
  3142. WriteBuf(b, key1, SHA1_SIZE);
  3143. WriteBufStr(b, "yasushineko");
  3144. HashSha1(key2, b->Buf, b->Size);
  3145. FreeBuf(b);
  3146. // Generate the magic number for the KeepAlive
  3147. b = NewBuf();
  3148. WriteBuf(b, init_key, SHA1_SIZE);
  3149. WriteBufStr(b, "Magic_KeepAliveRequest");
  3150. HashSha1(se->Magic_KeepAliveRequest, b->Buf, b->Size);
  3151. FreeBuf(b);
  3152. b = NewBuf();
  3153. WriteBuf(b, init_key, SHA1_SIZE);
  3154. WriteBufStr(b, "Magic_KeepAliveResponse");
  3155. HashSha1(se->Magic_KeepAliveResponse, b->Buf, b->Size);
  3156. FreeBuf(b);
  3157. if (server_mode == false)
  3158. {
  3159. se->Magic_Disconnect = 0xffffffff00000000ULL | (UINT64)(Rand32());
  3160. }
  3161. Copy(se->Key_Init, init_key, SHA1_SIZE);
  3162. if (se->ServerMode)
  3163. {
  3164. Copy(se->Key_Send, key1, SHA1_SIZE);
  3165. Copy(se->Key_Recv, key2, SHA1_SIZE);
  3166. }
  3167. else
  3168. {
  3169. Copy(se->Key_Send, key2, SHA1_SIZE);
  3170. Copy(se->Key_Recv, key1, SHA1_SIZE);
  3171. }
  3172. Rand(se->NextIv, sizeof(se->NextIv));
  3173. se->ReplyAckList = NewInt64List(true);
  3174. se->NextKeepAliveInterval = RUDP_KEEPALIVE_INTERVAL_MIN + (Rand32() % (RUDP_KEEPALIVE_INTERVAL_MAX - RUDP_KEEPALIVE_INTERVAL_MIN));
  3175. se->RecvFifo = NewFifo();
  3176. se->SendFifo = NewFifo();
  3177. se->Dns_TranId = Rand16() % 65535 + 1;
  3178. // Generate the bulk transfer key
  3179. Rand(bulk_send_key, sizeof(bulk_send_key));
  3180. Rand(bulk_recv_key, sizeof(bulk_recv_key));
  3181. se->BulkSendKey = NewSharedBuffer(bulk_send_key, sizeof(bulk_send_key));
  3182. se->BulkRecvKey = NewSharedBuffer(bulk_recv_key, sizeof(bulk_recv_key));
  3183. Rand(se->BulkNextIv, sizeof(se->BulkNextIv));
  3184. se->BulkNextSeqNo = 1;
  3185. return se;
  3186. }
  3187. // Comparison function of the segment list items
  3188. int RUDPCompareSegmentList(void *p1, void *p2)
  3189. {
  3190. RUDP_SEGMENT *s1, *s2;
  3191. UINT r;
  3192. // Validate arguments
  3193. if (p1 == NULL || p2 == NULL)
  3194. {
  3195. return 0;
  3196. }
  3197. s1 = *((RUDP_SEGMENT **)p1);
  3198. s2 = *((RUDP_SEGMENT **)p2);
  3199. if (s1 == NULL || s2 == NULL)
  3200. {
  3201. return 0;
  3202. }
  3203. r = COMPARE_RET(s1->SeqNo, s2->SeqNo);
  3204. return r;
  3205. }
  3206. // Send a UDP packet
  3207. void RUDPSendPacket(RUDP_STACK *r, IP *dest_ip, UINT dest_port, void *data, UINT size, UINT icmp_type)
  3208. {
  3209. UDPPACKET *p;
  3210. // Validate arguments
  3211. if (r == NULL || dest_ip == NULL || dest_port == 0 || data == NULL || size == 0)
  3212. {
  3213. return;
  3214. }
  3215. p = NewUdpPacket(&r->UdpSock->LocalIP, r->UdpSock->LocalPort,
  3216. dest_ip, dest_port,
  3217. Clone(data, size), size);
  3218. if (r->Protocol == RUDP_PROTOCOL_ICMP || r->Protocol == RUDP_PROTOCOL_DNS)
  3219. {
  3220. // ICMP Type / DNS Tran ID
  3221. p->Type = icmp_type;
  3222. }
  3223. Add(r->SendPacketList, p);
  3224. }
  3225. // R-UDP main thread
  3226. void RUDPMainThread(THREAD *thread, void *param)
  3227. {
  3228. RUDP_STACK *r;
  3229. bool halt_flag = false;
  3230. // Validate arguments
  3231. if (thread == NULL || param == NULL)
  3232. {
  3233. return;
  3234. }
  3235. r = (RUDP_STACK *)param;
  3236. AddWaitThread(thread);
  3237. NoticeThreadInit(thread);
  3238. while (true)
  3239. {
  3240. UINT wait_interval;
  3241. UINT i;
  3242. UINT min_wait_interval;
  3243. UINT num_ignore_errors = 0;
  3244. r->Now = Tick64();
  3245. Lock(r->Lock);
  3246. {
  3247. Copy(&r->NatT_IP_Safe, &r->NatT_IP, sizeof(IP));
  3248. Copy(&r->My_Private_IP_Safe, &r->My_Private_IP, sizeof(IP));
  3249. }
  3250. Unlock(r->Lock);
  3251. // Receive the data from the UDP socket
  3252. while (true)
  3253. {
  3254. UINT ret;
  3255. IP ip_src;
  3256. UINT port_src;
  3257. ret = RecvFrom(r->UdpSock, &ip_src, &port_src, r->TmpBuf, sizeof(r->TmpBuf));
  3258. if (ret == SOCK_LATER)
  3259. {
  3260. // There is no packet more
  3261. break;
  3262. }
  3263. else if (ret != 0)
  3264. {
  3265. // Receive a Packet
  3266. bool ok = false;
  3267. UDPPACKET *p = NewUdpPacket(&ip_src, port_src,
  3268. &r->UdpSock->LocalIP, r->UdpSock->LocalPort,
  3269. Clone(r->TmpBuf, ret), ret);
  3270. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  3271. {
  3272. // Analyse the incoming ICMP packet
  3273. UINT ip_header_size = GetIpHeaderSize(p->Data, p->Size);
  3274. if (ip_header_size >= sizeof(IPV4_HEADER))
  3275. {
  3276. if (p->Size >= (ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE))
  3277. {
  3278. IPV4_HEADER *ip_header = (IPV4_HEADER *)(((UCHAR *)p->Data) + 0);
  3279. ICMP_HEADER *icmp_header = (ICMP_HEADER *)(((UCHAR *)p->Data) + ip_header_size);
  3280. ICMP_ECHO *echo_header = (ICMP_ECHO *)(((UCHAR *)p->Data) + ip_header_size + sizeof(ICMP_HEADER));
  3281. if (icmp_header->Type == ICMP_TYPE_ECHO_RESPONSE ||
  3282. icmp_header->Type == (r->ServerMode ? ICMP_TYPE_INFORMATION_REQUEST : ICMP_TYPE_INFORMATION_REPLY))
  3283. {
  3284. UCHAR hash[SHA1_SIZE];
  3285. HashSha1(hash, ((UCHAR *)p->Data) + ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE,
  3286. p->Size - (ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE));
  3287. if (Cmp(hash, ((UCHAR *)p->Data) + ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO), SHA1_SIZE) == 0)
  3288. {
  3289. UCHAR *new_data;
  3290. UINT new_data_size;
  3291. if (r->ServerMode)
  3292. {
  3293. // On the server side, the ICMP ID and the SEQ NO of received messages are treated as a source port number
  3294. Copy(&p->SrcPort, echo_header, sizeof(UINT));
  3295. }
  3296. // Record the Type
  3297. p->Type = icmp_header->Type;
  3298. // Erase the header part
  3299. new_data_size = p->Size - (ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE);
  3300. new_data = Clone(((UCHAR *)p->Data) + ip_header_size + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE, new_data_size);
  3301. Free(p->Data);
  3302. p->Data = new_data;
  3303. p->Size = new_data_size;
  3304. ok = true;
  3305. }
  3306. }
  3307. }
  3308. }
  3309. }
  3310. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  3311. {
  3312. // Analyse the incoming DNS packet
  3313. UINT offset;
  3314. if (r->ServerMode == false)
  3315. {
  3316. offset = 42;
  3317. }
  3318. else
  3319. {
  3320. offset = 37;
  3321. }
  3322. if (p->Size > offset)
  3323. {
  3324. UCHAR *new_data;
  3325. UINT new_size = p->Size - offset;
  3326. p->Type = *((USHORT *)p->Data);
  3327. new_data = Clone(((UCHAR *)p->Data) + offset, new_size);
  3328. Free(p->Data);
  3329. p->Data = new_data;
  3330. p->Size = new_size;
  3331. ok = true;
  3332. }
  3333. }
  3334. else
  3335. {
  3336. // Don't do anything for ordinary UDP packet
  3337. ok = true;
  3338. }
  3339. if (ok)
  3340. {
  3341. // Process the received packet
  3342. RUDPRecvProc(r, p);
  3343. r->TotalPhysicalReceived += ret;
  3344. }
  3345. FreeUdpPacket(p);
  3346. }
  3347. else
  3348. {
  3349. if (r->UdpSock->IgnoreRecvErr)
  3350. {
  3351. // An ignorable reception error occurs
  3352. if ((num_ignore_errors++) >= MAX_NUM_IGNORE_ERRORS)
  3353. {
  3354. break;
  3355. }
  3356. }
  3357. else
  3358. {
  3359. // A non-ignorable reception error occurs
  3360. break;
  3361. }
  3362. }
  3363. }
  3364. // Call the interrupt notification callback function
  3365. if (r->ProcInterrupts != NULL)
  3366. {
  3367. r->ProcInterrupts(r);
  3368. }
  3369. RUDPInterruptProc(r);
  3370. // Send all packets in the transmission packet list
  3371. for (i = 0;i < LIST_NUM(r->SendPacketList);i++)
  3372. {
  3373. UDPPACKET *p = LIST_DATA(r->SendPacketList, i);
  3374. if (r->Protocol == RUDP_PROTOCOL_ICMP)
  3375. {
  3376. // In case of the ICMP protocol, assemble an ICMP header
  3377. UINT dst_size = sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE + p->Size;
  3378. UCHAR *dst_data = ZeroMalloc(dst_size);
  3379. ICMP_HEADER *icmp_header = (ICMP_HEADER *)dst_data;
  3380. ICMP_ECHO *icmp_echo = (ICMP_ECHO *)(dst_data + sizeof(ICMP_HEADER));
  3381. UCHAR *hash = dst_data + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO);
  3382. UCHAR *icmp_data = dst_data + sizeof(ICMP_HEADER) + sizeof(ICMP_ECHO) + SHA1_SIZE;
  3383. // Header
  3384. icmp_header->Type = (UCHAR)p->Type;
  3385. icmp_header->Code = 0;
  3386. icmp_header->Checksum = 0;
  3387. if (r->ServerMode)
  3388. {
  3389. // On the server side, use the port number in the opponent internal data as ICMP ID and SEQ NO
  3390. Copy(icmp_echo, &p->DestPort, 4);
  3391. }
  3392. else
  3393. {
  3394. // Use the fixed ICMP ID and SEQ NO on the client side
  3395. icmp_echo->Identifier = Endian16(r->Client_IcmpId);
  3396. icmp_echo->SeqNo = Endian16(r->Client_IcmpSeqNo);
  3397. }
  3398. // Data body
  3399. Copy(icmp_data, p->Data, p->Size);
  3400. // Hash
  3401. HashSha1(hash, icmp_data, p->Size);
  3402. // Checksum calculation
  3403. icmp_header->Checksum = IpChecksum(dst_data, dst_size);
  3404. // Replacement
  3405. Free(p->Data);
  3406. p->Data = dst_data;
  3407. p->Size = dst_size;
  3408. }
  3409. else if (r->Protocol == RUDP_PROTOCOL_DNS)
  3410. {
  3411. BUF *b = NewBuf();
  3412. // In case of over DNS protocol, assemble a header that conforms to the DNS protocol
  3413. if (r->ServerMode == false)
  3414. {
  3415. // DNS query header
  3416. USHORT us = Rand16() % 65535 + 1;
  3417. static UCHAR dns_query_header_1[] =
  3418. {
  3419. 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08,
  3420. };
  3421. static UCHAR dns_query_header_2[] =
  3422. {
  3423. 0x00, 0x00, 0x30, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10,
  3424. 0x00, 0x00, 0x00, 0x80, 0x00,
  3425. };
  3426. UCHAR rand_data[4];
  3427. char rand_str[MAX_SIZE];
  3428. Rand(rand_data, sizeof(rand_data));
  3429. BinToStr(rand_str, sizeof(rand_str), rand_data, sizeof(rand_data));
  3430. StrLower(rand_str);
  3431. WriteBuf(b, &us, sizeof(USHORT));
  3432. WriteBuf(b, dns_query_header_1, sizeof(dns_query_header_1));
  3433. WriteBuf(b, rand_str, 8);
  3434. WriteBuf(b, dns_query_header_2, sizeof(dns_query_header_2));
  3435. us = Endian16((USHORT)p->Size);
  3436. WriteBuf(b, &us, sizeof(USHORT));
  3437. WriteBuf(b, p->Data, p->Size);
  3438. }
  3439. else
  3440. {
  3441. // DNS response header
  3442. USHORT us = p->Type;
  3443. UINT ui;
  3444. static UCHAR dns_response_header_1[] =
  3445. {
  3446. 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
  3447. 0x00, 0x00, 0x08,
  3448. };
  3449. static UCHAR dns_response_header_2[] =
  3450. {
  3451. 0x00, 0x00, 0x30, 0x00, 0x01,
  3452. 0xc0, 0x0c, 0x00, 0x30, 0x00, 0x01, 0x00, 0x00, 0xa4, 0x5b,
  3453. };
  3454. static UCHAR dns_response_header_3[] =
  3455. {
  3456. 0x01, 0x00, 0x03, 0x08,
  3457. };
  3458. UCHAR rand_data[4];
  3459. char rand_str[MAX_SIZE];
  3460. Rand(rand_data, sizeof(rand_data));
  3461. BinToStr(rand_str, sizeof(rand_str), rand_data, sizeof(rand_data));
  3462. StrLower(rand_str);
  3463. WriteBuf(b, &us, sizeof(USHORT));
  3464. WriteBuf(b, dns_response_header_1, sizeof(dns_response_header_1));
  3465. WriteBuf(b, rand_str, 8);
  3466. WriteBuf(b, dns_response_header_2, sizeof(dns_response_header_2));
  3467. us = Endian16((USHORT)(p->Size + 4));
  3468. WriteBuf(b, &us, sizeof(USHORT));
  3469. WriteBuf(b, dns_response_header_3, sizeof(dns_response_header_3));
  3470. WriteBuf(b, p->Data, p->Size);
  3471. ui = Rand16() % (60 * 60 * 12) + (60 * 60 * 12);
  3472. WRITE_UINT(((UCHAR *)b->Buf) + 0x20, ui);
  3473. }
  3474. Free(p->Data);
  3475. p->Data = b->Buf;
  3476. p->Size = b->Size;
  3477. Free(b);
  3478. }
  3479. SendTo(r->UdpSock, &p->DstIP, p->DestPort, p->Data, p->Size);
  3480. r->TotalPhysicalSent += p->Size;
  3481. FreeUdpPacket(p);
  3482. }
  3483. DeleteAll(r->SendPacketList);
  3484. if (r->Halt)
  3485. {
  3486. // If it is necessary to stop, stop it after cycling through a loop
  3487. if (halt_flag == false)
  3488. {
  3489. halt_flag = true;
  3490. continue;
  3491. }
  3492. else
  3493. {
  3494. break;
  3495. }
  3496. }
  3497. // Rest the CPU until the next event
  3498. wait_interval = GetNextIntervalForInterrupt(r->Interrupt);
  3499. if (r->ServerMode)
  3500. {
  3501. min_wait_interval = RUDP_LOOP_WAIT_INTERVAL_S;
  3502. }
  3503. else
  3504. {
  3505. min_wait_interval = RUDP_LOOP_WAIT_INTERVAL_C;
  3506. }
  3507. if (wait_interval == INFINITE)
  3508. {
  3509. wait_interval = min_wait_interval;
  3510. }
  3511. else
  3512. {
  3513. wait_interval = MIN(min_wait_interval, wait_interval);
  3514. }
  3515. #ifdef RUDP_DETAIL_LOG
  3516. Debug("wait_interval = %u\n", wait_interval);
  3517. #endif // RUDP_DETAIL_LOG
  3518. if (wait_interval >= 1)
  3519. {
  3520. WaitSockEvent(r->SockEvent, wait_interval);
  3521. }
  3522. #ifdef RUDP_DETAIL_LOG
  3523. if (r->ServerMode)
  3524. {
  3525. char str1[MAX_SIZE];
  3526. char str2[MAX_SIZE];
  3527. double rate = 0.0;
  3528. ToStr64(str1, r->TotalPhysicalReceived);
  3529. ToStr64(str2, r->TotalLogicalReceived);
  3530. if (r->TotalPhysicalReceived >= 1)
  3531. {
  3532. rate = (double)r->TotalLogicalReceived / (double)r->TotalPhysicalReceived;
  3533. }
  3534. Debug("%s / %s %.4f\n", str1, str2, rate);
  3535. }
  3536. #endif // RUDP_DETAIL_LOG
  3537. }
  3538. Disconnect(r->UdpSock);
  3539. DelWaitThread(thread);
  3540. }
  3541. // Generate a appropriate register host name from the IP address
  3542. void RUDPGetRegisterHostNameByIP(char *dst, UINT size, IP *ip)
  3543. {
  3544. char tmp[16];
  3545. // Validate arguments
  3546. if (dst == NULL)
  3547. {
  3548. return;
  3549. }
  3550. if (ip != NULL && IsIP4(ip))
  3551. {
  3552. UCHAR hash[SHA1_SIZE];
  3553. HashSha1(hash, ip->addr, 4);
  3554. BinToStr(tmp, sizeof(tmp), hash, 2);
  3555. }
  3556. else
  3557. {
  3558. UCHAR rand[2];
  3559. Rand(rand, 2);
  3560. BinToStr(tmp, sizeof(tmp), rand, 2);
  3561. }
  3562. StrLower(tmp);
  3563. Format(dst, size,
  3564. (IsUseAlternativeHostname() ? UDP_NAT_T_SERVER_TAG_ALT : UDP_NAT_T_SERVER_TAG),
  3565. tmp[2], tmp[3]);
  3566. if (false)
  3567. {
  3568. Debug("Hash Src IP: %r\n"
  3569. "Hash Dst HN: %s\n",
  3570. ip,
  3571. dst);
  3572. }
  3573. }
  3574. // Analyze the IP address and port number from the string
  3575. bool RUDPParseIPAndPortStr(void *data, UINT data_size, IP *ip, UINT *port)
  3576. {
  3577. char tmp[MAX_SIZE];
  3578. UINT i;
  3579. char ipstr[MAX_SIZE];
  3580. char *portstr;
  3581. // Validate arguments
  3582. if (data == NULL || ip == NULL || port == NULL)
  3583. {
  3584. return false;
  3585. }
  3586. Zero(tmp, sizeof(tmp));
  3587. Copy(tmp, data, MIN(data_size, sizeof(tmp) - 1));
  3588. if (StartWith(tmp, "IP=") == false)
  3589. {
  3590. return false;
  3591. }
  3592. i = SearchStrEx(tmp, "#", 0, true);
  3593. if (i != INFINITE)
  3594. {
  3595. tmp[i] = 0;
  3596. }
  3597. StrCpy(ipstr, sizeof(ipstr), tmp + 3);
  3598. i = SearchStrEx(ipstr, ",PORT=", 0, true);
  3599. if (i == INFINITE)
  3600. {
  3601. return false;
  3602. }
  3603. ipstr[i] = 0;
  3604. portstr = ipstr + i + 6;
  3605. StrToIP(ip, ipstr);
  3606. *port = ToInt(portstr);
  3607. return true;
  3608. }
  3609. // R-UDP NAT-T IP address acquisition thread
  3610. void RUDPIpQueryThread(THREAD *thread, void *param)
  3611. {
  3612. RUDP_STACK *r;
  3613. UINT64 next_getip_tick = 0;
  3614. UINT64 next_getprivate_ip_tick = 0;
  3615. UINT last_ip_hash = 0;
  3616. void *route_change_poller = NULL;
  3617. char current_hostname[MAX_SIZE];
  3618. bool last_time_ip_changed = false;
  3619. UINT num_retry = 0;
  3620. // Validate arguments
  3621. if (thread == NULL || param == NULL)
  3622. {
  3623. return;
  3624. }
  3625. r = (RUDP_STACK *)param;
  3626. last_ip_hash = GetHostIPAddressHash32();
  3627. route_change_poller = NewRouteChange();
  3628. IsRouteChanged(route_change_poller);
  3629. Zero(current_hostname, sizeof(current_hostname));
  3630. while (r->Halt == false)
  3631. {
  3632. UINT ip_hash = GetHostIPAddressHash32();
  3633. UINT64 now = Tick64();
  3634. bool ip_changed = false;
  3635. if (ip_hash != last_ip_hash)
  3636. {
  3637. last_time_ip_changed = false;
  3638. }
  3639. if ((ip_hash != last_ip_hash) || (IsRouteChanged(route_change_poller)))
  3640. {
  3641. if (last_time_ip_changed == false)
  3642. {
  3643. // Call all getting functions from the beginning
  3644. // if the routing table or the IP address of this host has changed
  3645. next_getip_tick = 0;
  3646. next_getprivate_ip_tick = 0;
  3647. ip_changed = true;
  3648. last_ip_hash = ip_hash;
  3649. last_time_ip_changed = true;
  3650. }
  3651. }
  3652. else
  3653. {
  3654. last_time_ip_changed = false;
  3655. }
  3656. Lock(r->Lock);
  3657. {
  3658. if (StrCmpi(current_hostname, r->CurrentRegisterHostname) != 0)
  3659. {
  3660. // The target host name has changed
  3661. next_getip_tick = 0;
  3662. StrCpy(current_hostname, sizeof(current_hostname), r->CurrentRegisterHostname);
  3663. }
  3664. }
  3665. Unlock(r->Lock);
  3666. // Get the IP address of the NAT-T server with DNS
  3667. if (next_getip_tick == 0 || now >= next_getip_tick)
  3668. {
  3669. IP ip;
  3670. if (GetIP4(&ip, current_hostname) && IsZeroIp(&ip) == false)
  3671. {
  3672. Lock(r->Lock);
  3673. {
  3674. // Debug("%r %r\n",&r->NatT_IP, &ip);
  3675. if (CmpIpAddr(&r->NatT_IP, &ip) != 0)
  3676. {
  3677. // WHERE;
  3678. ip_changed = true;
  3679. Copy(&r->NatT_IP, &ip, sizeof(IP));
  3680. }
  3681. }
  3682. Unlock(r->Lock);
  3683. }
  3684. if (IsZeroIp(&r->NatT_IP))
  3685. {
  3686. num_retry++;
  3687. next_getip_tick = now + MIN((UINT64)UDP_NAT_T_GET_IP_INTERVAL * (UINT64)num_retry, (UINT64)UDP_NAT_T_GET_IP_INTERVAL_MAX);
  3688. }
  3689. else
  3690. {
  3691. next_getip_tick = now + (UINT64)UDP_NAT_T_GET_IP_INTERVAL_AFTER;
  3692. }
  3693. if (ip_changed)
  3694. {
  3695. Debug("NAT-T: NAT-T Server IP (%s): %r\n", current_hostname, &r->NatT_IP);
  3696. r->NatT_GetTokenNextTick = 0;
  3697. r->NatT_RegisterNextTick = 0;
  3698. r->NatT_GetTokenFailNum = 0;
  3699. r->NatT_RegisterFailNum = 0;
  3700. r->NatT_TranId = Rand64();
  3701. SetSockEvent(r->SockEvent);
  3702. }
  3703. }
  3704. // Get a private IP address of this host using TCP
  3705. if (next_getprivate_ip_tick == 0 || now >= next_getprivate_ip_tick)
  3706. {
  3707. IP ip;
  3708. if (GetMyPrivateIP(&ip, false))
  3709. {
  3710. Lock(r->Lock);
  3711. {
  3712. Copy(&r->My_Private_IP, &ip, sizeof(IP));
  3713. }
  3714. Unlock(r->Lock);
  3715. }
  3716. if (IsZeroIp(&r->My_Private_IP))
  3717. {
  3718. next_getprivate_ip_tick = now + (UINT64)UDP_NAT_T_GET_PRIVATE_IP_INTERVAL;
  3719. }
  3720. else
  3721. {
  3722. next_getprivate_ip_tick = now + (UINT64)GenRandInterval(UDP_NAT_T_GET_PRIVATE_IP_INTERVAL_AFTER_MIN, UDP_NAT_T_GET_PRIVATE_IP_INTERVAL_AFTER_MAX);
  3723. }
  3724. Debug("NAT-T: My Private IP: %r\n", &r->My_Private_IP);
  3725. }
  3726. if (r->Halt)
  3727. {
  3728. break;
  3729. }
  3730. Wait(r->HaltEvent, RUDP_LOOP_WAIT_INTERVAL_S);
  3731. }
  3732. FreeRouteChange(route_change_poller);
  3733. }
  3734. // Generate a random intervals
  3735. UINT GenRandInterval(UINT min, UINT max)
  3736. {
  3737. UINT a, b;
  3738. a = MIN(min, max);
  3739. b = MAX(min, max);
  3740. if (a == b)
  3741. {
  3742. return a;
  3743. }
  3744. return (Rand32() % (b - a)) + a;
  3745. }
  3746. // Identify the private IP of the interface which is used to connect to the Internet currently
  3747. bool GetMyPrivateIP(IP *ip, bool from_vg)
  3748. {
  3749. SOCK *s;
  3750. IP t;
  3751. char *hostname = UDP_NAT_T_GET_PRIVATE_IP_TCP_SERVER;
  3752. // Validate arguments
  3753. if (ip == NULL)
  3754. {
  3755. return false;
  3756. }
  3757. s = ConnectEx(hostname, UDP_NAT_T_PORT_FOR_TCP_1, UDP_NAT_T_GET_PRIVATE_IP_CONNECT_TIMEOUT);
  3758. if (s == NULL)
  3759. {
  3760. s = ConnectEx(hostname, UDP_NAT_T_PORT_FOR_TCP_2, UDP_NAT_T_GET_PRIVATE_IP_CONNECT_TIMEOUT);
  3761. if (s == NULL)
  3762. {
  3763. s = ConnectEx(GetRandHostNameForGetMyPrivateIP(), UDP_NAT_T_PORT_FOR_TCP_1, UDP_NAT_T_GET_PRIVATE_IP_CONNECT_TIMEOUT);
  3764. if (s == NULL)
  3765. {
  3766. return false;
  3767. }
  3768. }
  3769. }
  3770. Copy(&t, &s->LocalIP, sizeof(IP));
  3771. Disconnect(s);
  3772. ReleaseSock(s);
  3773. if (IsZeroIp(&t))
  3774. {
  3775. return false;
  3776. }
  3777. Copy(ip, &t, sizeof(IP));
  3778. return true;
  3779. }
  3780. char *GetRandHostNameForGetMyPrivateIP()
  3781. {
  3782. char *hosts[] =
  3783. {
  3784. "www.microsoft.com",
  3785. "www.yahoo.com",
  3786. "www.bing.com",
  3787. };
  3788. UINT num_hosts = 3;
  3789. return hosts[Rand32() % num_hosts];
  3790. }
  3791. // Function to wait until changing any IP address of the host or expiring the specified time or waking the event
  3792. void WaitUntilHostIPAddressChanged(void *p, EVENT *event, UINT timeout, UINT ip_check_interval)
  3793. {
  3794. UINT64 start, end;
  3795. UINT last_hash;
  3796. // Validate arguments
  3797. if (timeout == 0x7FFFFFFF)
  3798. {
  3799. timeout = 0xFFFFFFFF;
  3800. }
  3801. if (ip_check_interval == 0)
  3802. {
  3803. ip_check_interval = 0xFFFFFFFF;
  3804. }
  3805. if (event == NULL || timeout == 0)
  3806. {
  3807. return;
  3808. }
  3809. start = Tick64();
  3810. end = start + (UINT64)timeout;
  3811. last_hash = GetHostIPAddressHash32();
  3812. while (true)
  3813. {
  3814. UINT64 now = Tick64();
  3815. UINT next_interval;
  3816. if (now >= end)
  3817. {
  3818. break;
  3819. }
  3820. if (p != NULL)
  3821. {
  3822. if (IsRouteChanged(p))
  3823. {
  3824. break;
  3825. }
  3826. }
  3827. if (last_hash != GetHostIPAddressHash32())
  3828. {
  3829. break;
  3830. }
  3831. next_interval = (UINT)(end - now);
  3832. next_interval = MIN(next_interval, ip_check_interval);
  3833. if (Wait(event, next_interval))
  3834. {
  3835. break;
  3836. }
  3837. }
  3838. }
  3839. void *InitWaitUntilHostIPAddressChanged()
  3840. {
  3841. void *p = NewRouteChange();
  3842. if (p != NULL)
  3843. {
  3844. IsRouteChanged(p);
  3845. }
  3846. return p;
  3847. }
  3848. void FreeWaitUntilHostIPAddressChanged(void *p)
  3849. {
  3850. FreeRouteChange(p);
  3851. }
  3852. // Get whether the specified IPv6 address is on the local network
  3853. bool IsIPv6LocalNetworkAddress(IP *ip)
  3854. {
  3855. UINT type;
  3856. LIST *o;
  3857. UINT i;
  3858. bool ret = false;
  3859. IP mask64;
  3860. // Validate arguments
  3861. if (ip == NULL)
  3862. {
  3863. return false;
  3864. }
  3865. if (IsIP6(ip) == false)
  3866. {
  3867. return false;
  3868. }
  3869. if (IsZeroIp(ip))
  3870. {
  3871. return false;
  3872. }
  3873. type = GetIPAddrType6(ip);
  3874. if (type & IPV6_ADDR_LOCAL_UNICAST)
  3875. {
  3876. return true;
  3877. }
  3878. if ((type & IPV6_ADDR_GLOBAL_UNICAST) == 0)
  3879. {
  3880. return false;
  3881. }
  3882. IntToSubnetMask6(&mask64, 64);
  3883. o = GetHostIPAddressList();
  3884. ret = false;
  3885. for (i = 0;i < LIST_NUM(o);i++)
  3886. {
  3887. IP *p = LIST_DATA(o, i);
  3888. if (IsIP6(p))
  3889. {
  3890. if (IsZeroIp(p) == false)
  3891. {
  3892. if (IsLocalHostIP6(p) == false)
  3893. {
  3894. if (IsInSameNetwork6(p, ip, &mask64))
  3895. {
  3896. ret = true;
  3897. }
  3898. }
  3899. }
  3900. }
  3901. }
  3902. FreeHostIPAddressList(o);
  3903. return ret;
  3904. }
  3905. // Check whether the specified IP address is localhost or the IP address of the local interface of itself
  3906. bool IsIPLocalHostOrMySelf(IP *ip)
  3907. {
  3908. LIST *o;
  3909. bool ret = false;
  3910. UINT i;
  3911. // Validate arguments
  3912. if (ip == NULL)
  3913. {
  3914. return false;
  3915. }
  3916. o = GetHostIPAddressList();
  3917. if (o == NULL)
  3918. {
  3919. return false;
  3920. }
  3921. for (i = 0;i < LIST_NUM(o);i++)
  3922. {
  3923. IP *p = LIST_DATA(o, i);
  3924. if (CmpIpAddr(p, ip) == 0)
  3925. {
  3926. ret = true;
  3927. break;
  3928. }
  3929. }
  3930. FreeHostIPAddressList(o);
  3931. if (IsLocalHostIP4(ip) || IsLocalHostIP6(ip))
  3932. {
  3933. ret = true;
  3934. }
  3935. return ret;
  3936. }
  3937. // Get the results of the port number that is determined at random
  3938. UINT RUDPGetRandPortNumber(UCHAR rand_port_id)
  3939. {
  3940. UINT ret;
  3941. // Validate arguments
  3942. if (rand_port_id == 0)
  3943. {
  3944. return 0;
  3945. }
  3946. ret = rand_port_numbers[rand_port_id];
  3947. Debug("rand_port_id[%u] = %u\n", rand_port_id, ret);
  3948. return ret;
  3949. }
  3950. // Obtain the hash value of combining all of the IP address assigned to the host
  3951. UINT GetHostIPAddressHash32()
  3952. {
  3953. BUF *b;
  3954. UINT i;
  3955. UCHAR hash[SHA1_SIZE];
  3956. UINT ret;
  3957. LIST *o = GetHostIPAddressList();
  3958. if (o == NULL)
  3959. {
  3960. return 0;
  3961. }
  3962. b = NewBuf();
  3963. for (i = 0;i < LIST_NUM(o);i++)
  3964. {
  3965. IP *ip = LIST_DATA(o, i);
  3966. WriteBuf(b, ip, sizeof(IP));
  3967. WriteBufStr(b, ":-) yas (-:");
  3968. }
  3969. FreeHostIPAddressList(o);
  3970. WriteBuf(b, rand_port_numbers, sizeof(rand_port_numbers));
  3971. HashSha1(hash, b->Buf, b->Size);
  3972. FreeBuf(b);
  3973. Copy(&ret, hash, sizeof(UINT));
  3974. return ret;
  3975. }
  3976. // Create an IPv4 UDP socket destined for a particular target
  3977. SOCK *NewUDP4ForSpecificIp(IP *target_ip, UINT port)
  3978. {
  3979. SOCK *s;
  3980. IP local_ip;
  3981. // Validate arguments
  3982. if (target_ip == NULL || IsZeroIP(target_ip) || IsIP4(target_ip) == false)
  3983. {
  3984. target_ip = NULL;
  3985. }
  3986. Zero(&local_ip, sizeof(local_ip));
  3987. GetBestLocalIpForTarget(&local_ip, target_ip);
  3988. s = NewUDP4(port, &local_ip);
  3989. if (s == NULL)
  3990. {
  3991. s = NewUDP4(port, NULL);
  3992. }
  3993. return s;
  3994. }
  3995. // Get the best self IPv4 address to connect to the target IPv4 address
  3996. bool GetBestLocalIpForTarget(IP *local_ip, IP *target_ip)
  3997. {
  3998. bool ret = false;
  3999. ROUTE_ENTRY *e;
  4000. IP ip2;
  4001. UINT n = 0;
  4002. IP zero_ip;
  4003. // Validate arguments
  4004. Zero(local_ip, sizeof(IP));
  4005. ZeroIP4(&zero_ip);
  4006. if (target_ip == NULL)
  4007. {
  4008. target_ip = &zero_ip;
  4009. }
  4010. if (local_ip == NULL || IsIP4(target_ip) == false)
  4011. {
  4012. return false;
  4013. }
  4014. Copy(&ip2, target_ip, sizeof(IP));
  4015. while (true)
  4016. {
  4017. n++;
  4018. if (n >= 64)
  4019. {
  4020. break;
  4021. }
  4022. e = GetBestRouteEntry(&ip2);
  4023. if (e != NULL)
  4024. {
  4025. if (IsZeroIp(&e->GatewayIP))
  4026. {
  4027. Free(e);
  4028. break;
  4029. }
  4030. if (e->LocalRouting)
  4031. {
  4032. ret = true;
  4033. Copy(local_ip, &e->GatewayIP, sizeof(IP));
  4034. Free(e);
  4035. break;
  4036. }
  4037. else
  4038. {
  4039. Copy(&ip2, &e->GatewayIP, sizeof(IP));
  4040. }
  4041. Free(e);
  4042. }
  4043. }
  4044. if (ret == false)
  4045. {
  4046. if (IsLocalHostIP4(target_ip))
  4047. {
  4048. GetLocalHostIP4(local_ip);
  4049. ret = true;
  4050. }
  4051. }
  4052. return ret;
  4053. }
  4054. // Create a R-UDP client (Connection via NAT-T gateway)
  4055. SOCK *NewRUDPClientNatT(char *svc_name, IP *ip, UINT *error_code, UINT timeout, bool *cancel, char *hint_str, char *target_hostname)
  4056. {
  4057. IP nat_t_ip;
  4058. UINT dummy_int = 0;
  4059. UINT64 giveup_tick;
  4060. bool dummy_bool = false;
  4061. SOCK_EVENT *sock_event;
  4062. SOCK *sock;
  4063. bool same_lan = false;
  4064. char hostname[MAX_SIZE];
  4065. if (timeout == 0)
  4066. {
  4067. timeout = RUDP_TIMEOUT;
  4068. }
  4069. if (error_code == NULL)
  4070. {
  4071. error_code = &dummy_int;
  4072. }
  4073. if (cancel == NULL)
  4074. {
  4075. cancel = &dummy_bool;
  4076. }
  4077. *error_code = RUDP_ERROR_UNKNOWN;
  4078. if (svc_name == NULL || ip == NULL)
  4079. {
  4080. return NULL;
  4081. }
  4082. ListenTcpForPopupFirewallDialog();
  4083. giveup_tick = Tick64() + (UINT64)timeout;
  4084. // Get the IP address of the NAT-T server
  4085. RUDPGetRegisterHostNameByIP(hostname, sizeof(hostname), ip);
  4086. if (GetIP4Ex(&nat_t_ip, hostname, 0, cancel) == false)
  4087. {
  4088. *error_code = RUDP_ERROR_NAT_T_NO_RESPONSE;
  4089. return NULL;
  4090. }
  4091. if (Tick64() >= giveup_tick)
  4092. {
  4093. *error_code = RUDP_ERROR_TIMEOUT;
  4094. return NULL;
  4095. }
  4096. if (*cancel)
  4097. {
  4098. *error_code = RUDP_ERROR_USER_CANCELED;
  4099. return NULL;
  4100. }
  4101. sock = NewUDP4ForSpecificIp(&nat_t_ip, 0);
  4102. if (sock == NULL)
  4103. {
  4104. *error_code = RUDP_ERROR_UNKNOWN;
  4105. return NULL;
  4106. }
  4107. else
  4108. {
  4109. UINT64 next_send_request_tick = 0;
  4110. INTERRUPT_MANAGER *interrupt = NewInterruptManager();
  4111. UINT64 tran_id = Rand64();
  4112. UINT tmp_size = 65536;
  4113. UCHAR *tmp = Malloc(tmp_size);
  4114. char result_ip_str[MAX_SIZE];
  4115. IP result_ip;
  4116. UINT result_port;
  4117. SOCK *ret = NULL;
  4118. UINT num_tries = 0;
  4119. UINT64 current_cookie = 0;
  4120. AddInterrupt(interrupt, giveup_tick);
  4121. sock_event = NewSockEvent();
  4122. JoinSockToSockEvent(sock, sock_event);
  4123. // Communication with the NAT-T server
  4124. while (true)
  4125. {
  4126. UINT64 now = Tick64();
  4127. UINT interval;
  4128. UINT r;
  4129. IP src_ip;
  4130. UINT src_port;
  4131. UINT err;
  4132. UINT num_ignore_errors = 0;
  4133. if (now >= giveup_tick)
  4134. {
  4135. // Time-out
  4136. LABEL_TIMEOUT:
  4137. *error_code = RUDP_ERROR_NAT_T_NO_RESPONSE;
  4138. break;
  4139. }
  4140. if (*cancel)
  4141. {
  4142. // User canceled
  4143. *error_code = RUDP_ERROR_USER_CANCELED;
  4144. break;
  4145. }
  4146. err = INFINITE;
  4147. // Receive a response packet from the NAT-T server
  4148. while (err == INFINITE)
  4149. {
  4150. r = RecvFrom(sock, &src_ip, &src_port, tmp, tmp_size);
  4151. if (r == SOCK_LATER)
  4152. {
  4153. // No packet
  4154. break;
  4155. }
  4156. else if (r == 0)
  4157. {
  4158. if (sock->IgnoreRecvErr == false)
  4159. {
  4160. // Communication error
  4161. goto LABEL_TIMEOUT;
  4162. }
  4163. else
  4164. {
  4165. if ((num_ignore_errors++) >= MAX_NUM_IGNORE_ERRORS)
  4166. {
  4167. goto LABEL_TIMEOUT;
  4168. }
  4169. }
  4170. }
  4171. else
  4172. {
  4173. // Check the source IP address and the port number
  4174. if (CmpIpAddr(&src_ip, &nat_t_ip) == 0 && src_port == UDP_NAT_T_PORT)
  4175. {
  4176. BUF *b = NewBuf();
  4177. PACK *p;
  4178. WriteBuf(b, tmp, r);
  4179. SeekBuf(b, 0, 0);
  4180. p = BufToPack(b);
  4181. if (p != NULL)
  4182. {
  4183. UINT64 cookie = PackGetInt64(p, "cookie");
  4184. if (cookie != 0)
  4185. {
  4186. current_cookie = cookie;
  4187. }
  4188. // Compare tran_id
  4189. if (PackGetInt64(p, "tran_id") == tran_id)
  4190. {
  4191. // Compare opcode
  4192. if (PackCmpStr(p, "opcode", "nat_t_connect_request"))
  4193. {
  4194. bool ok = PackGetBool(p, "ok");
  4195. bool multi_candidate = PackGetBool(p, "multi_candidates");
  4196. if (ok)
  4197. {
  4198. // Success
  4199. PackGetStr(p, "result_ip", result_ip_str, sizeof(result_ip_str));
  4200. StrToIP(&result_ip, result_ip_str);
  4201. result_port = PackGetInt(p, "result_port");
  4202. same_lan = PackGetBool(p, "same_lan");
  4203. if (result_port != 0)
  4204. {
  4205. if (IsZeroIp(&result_ip) == false)
  4206. {
  4207. if ((sock->IPv6 == false && IsIP4(&result_ip)) ||
  4208. (sock->IPv6 && IsIP6(&result_ip)))
  4209. {
  4210. err = RUDP_ERROR_OK;
  4211. }
  4212. }
  4213. }
  4214. }
  4215. else if (multi_candidate)
  4216. {
  4217. // There are two or more computers behind the specified IP address
  4218. err = RUDP_ERROR_NAT_T_TWO_OR_MORE;
  4219. }
  4220. else
  4221. {
  4222. // Failure
  4223. err = RUDP_ERROR_NAT_T_NOT_FOUND;
  4224. }
  4225. }
  4226. }
  4227. FreePack(p);
  4228. }
  4229. FreeBuf(b);
  4230. }
  4231. }
  4232. }
  4233. if (err != INFINITE)
  4234. {
  4235. *error_code = err;
  4236. break;
  4237. }
  4238. if (next_send_request_tick == 0 || now >= next_send_request_tick)
  4239. {
  4240. // Send a connection request to the NAT-T server
  4241. BUF *b;
  4242. char ip_str[MAX_SIZE];
  4243. PACK *p = NewPack();
  4244. PackAddStr(p, "opcode", "nat_t_connect_request");
  4245. PackAddInt64(p, "tran_id", tran_id);
  4246. IPToStr(ip_str, sizeof(ip_str), ip);
  4247. PackAddStr(p, "dest_ip", ip_str);
  4248. PackAddInt64(p, "cookie", current_cookie);
  4249. if (IsEmptyStr(hint_str) == false)
  4250. {
  4251. PackAddStr(p, "hint", hint_str);
  4252. }
  4253. if (IsEmptyStr(target_hostname) == false)
  4254. {
  4255. PackAddStr(p, "target_hostname", target_hostname);
  4256. }
  4257. PackAddStr(p, "svc_name", svc_name);
  4258. PackAddInt(p, "nat_traversal_version", UDP_NAT_TRAVERSAL_VERSION);
  4259. b = PackToBuf(p);
  4260. FreePack(p);
  4261. SendTo(sock, &nat_t_ip, UDP_NAT_T_PORT, b->Buf, b->Size);
  4262. FreeBuf(b);
  4263. // Determine the next transmission time
  4264. next_send_request_tick = now + (UINT64)UDP_NAT_T_CONNECT_INTERVAL * (UINT64)(Power(2, MAX(num_tries, 6)));
  4265. num_tries++;
  4266. AddInterrupt(interrupt, next_send_request_tick);
  4267. }
  4268. interval = GetNextIntervalForInterrupt(interrupt);
  4269. interval = MIN(interval, 50);
  4270. WaitSockEvent(sock_event, interval);
  4271. }
  4272. Free(tmp);
  4273. FreeInterruptManager(interrupt);
  4274. if (*error_code == RUDP_ERROR_OK)
  4275. {
  4276. UINT remain_timeout;
  4277. UINT64 now = Tick64();
  4278. // Success to get the IP address and the port number of the target
  4279. // Get the rest timeout tolerance
  4280. if (now <= giveup_tick)
  4281. {
  4282. remain_timeout = (UINT)(giveup_tick - now);
  4283. }
  4284. else
  4285. {
  4286. remain_timeout = 0;
  4287. }
  4288. remain_timeout = MAX(remain_timeout, 2000);
  4289. if (same_lan)
  4290. {
  4291. // Discard current UDP socket and create a new UDP socket in NewRUDPClientDirect().
  4292. // Because using a UDP socket which used for communication with the NAT-T server
  4293. // can cause trouble when the client and the server exists in the same LAN.
  4294. ReleaseSockEvent(sock_event);
  4295. ReleaseSock(sock);
  4296. sock = NULL;
  4297. sock_event = NULL;
  4298. }
  4299. ret = NewRUDPClientDirect(svc_name, &result_ip, result_port, error_code, remain_timeout, cancel,
  4300. sock, sock_event, 0, false);
  4301. }
  4302. if (sock_event != NULL)
  4303. {
  4304. ReleaseSockEvent(sock_event);
  4305. }
  4306. if (sock != NULL)
  4307. {
  4308. if (ret == NULL)
  4309. {
  4310. Disconnect(sock);
  4311. }
  4312. ReleaseSock(sock);
  4313. }
  4314. return ret;
  4315. }
  4316. }
  4317. // Listen to the TCP for a moment to show the firewall dialog
  4318. void ListenTcpForPopupFirewallDialog()
  4319. {
  4320. #ifdef OS_WIN32
  4321. static bool tried = false;
  4322. if (tried == false)
  4323. {
  4324. SOCK *s;
  4325. tried = true;
  4326. s = ListenAnyPortEx2(false, true);
  4327. if (s != NULL)
  4328. {
  4329. Disconnect(s);
  4330. ReleaseSock(s);
  4331. }
  4332. }
  4333. #endif // OS_WIN32
  4334. }
  4335. // Create a R-UDP client (direct connection)
  4336. SOCK *NewRUDPClientDirect(char *svc_name, IP *ip, UINT port, UINT *error_code, UINT timeout, bool *cancel, SOCK *sock, SOCK_EVENT *sock_event, UINT local_port, bool over_dns_mode)
  4337. {
  4338. RUDP_STACK *r;
  4339. UINT dummy_int = 0;
  4340. SOCK *ret = NULL;
  4341. // Validate arguments
  4342. if (error_code == NULL)
  4343. {
  4344. error_code = &dummy_int;
  4345. }
  4346. if (timeout == 0)
  4347. {
  4348. timeout = RUDP_TIMEOUT;
  4349. }
  4350. *error_code = RUDP_ERROR_UNKNOWN;
  4351. if (svc_name == NULL || ip == NULL || port == 0)
  4352. {
  4353. return NULL;
  4354. }
  4355. r = NewRUDP(false, svc_name, NULL, NULL, NULL, local_port, sock, sock_event, false, over_dns_mode, ip, NULL, 0);
  4356. if (r == NULL)
  4357. {
  4358. *error_code = RUDP_ERROR_UNKNOWN;
  4359. return NULL;
  4360. }
  4361. // Set the port number and the target IP address
  4362. Lock(r->Lock);
  4363. {
  4364. Copy(&r->TargetIp, ip, sizeof(IP));
  4365. r->TargetPort = port;
  4366. r->TargetIpAndPortInited = true;
  4367. }
  4368. Unlock(r->Lock);
  4369. SetSockEvent(r->SockEvent);
  4370. // Wait for a connection success/failure to the target IP address
  4371. WaitEx(r->TargetConnectedEvent, timeout, cancel);
  4372. Lock(r->Lock);
  4373. {
  4374. if (r->TargetConnectedSock != NULL)
  4375. {
  4376. // The connection succeeded
  4377. ret = r->TargetConnectedSock;
  4378. r->TargetConnectedSock = NULL;
  4379. }
  4380. else
  4381. {
  4382. r->DoNotSetTargetConnectedSock = true;
  4383. }
  4384. }
  4385. Unlock(r->Lock);
  4386. if (ret == NULL)
  4387. {
  4388. // Stop the R-UDP stack if the connection has failed
  4389. *error_code = RUDP_ERROR_TIMEOUT;
  4390. FreeRUDP(r);
  4391. }
  4392. else if (cancel != NULL && (*cancel))
  4393. {
  4394. // User canceled
  4395. *error_code = RUDP_ERROR_USER_CANCELED;
  4396. Disconnect(ret);
  4397. ReleaseSock(ret);
  4398. ret = NULL;
  4399. }
  4400. else
  4401. {
  4402. *error_code = RUDP_ERROR_OK;
  4403. }
  4404. return ret;
  4405. }
  4406. // Creating a R-UDP server
  4407. RUDP_STACK *NewRUDPServer(char *svc_name, RUDP_STACK_INTERRUPTS_PROC *proc_interrupts, RUDP_STACK_RPC_RECV_PROC *proc_rpc_recv, void *param, UINT port, bool no_natt_register, bool over_dns_mode, volatile UINT *natt_global_udp_port, UCHAR rand_port_id)
  4408. {
  4409. RUDP_STACK *r;
  4410. // Validate arguments
  4411. if (IsEmptyStr(svc_name))
  4412. {
  4413. return NULL;
  4414. }
  4415. if (g_no_rudp_server)
  4416. {
  4417. return NULL;
  4418. }
  4419. ListenTcpForPopupFirewallDialog();
  4420. r = NewRUDP(true, svc_name, proc_interrupts, proc_rpc_recv, param, port, NULL, NULL, no_natt_register, over_dns_mode, NULL, natt_global_udp_port, rand_port_id);
  4421. if (r == NULL)
  4422. {
  4423. return NULL;
  4424. }
  4425. return r;
  4426. }
  4427. // Creating a R-UDP
  4428. RUDP_STACK *NewRUDP(bool server_mode, char *svc_name, RUDP_STACK_INTERRUPTS_PROC *proc_interrupts, RUDP_STACK_RPC_RECV_PROC *proc_rpc_recv, void *param, UINT port, SOCK *sock, SOCK_EVENT *sock_event, bool server_no_natt_register, bool over_dns_mode, IP *client_target_ip, volatile UINT *natt_global_udp_port, UCHAR rand_port_id)
  4429. {
  4430. RUDP_STACK *r;
  4431. char tmp[MAX_SIZE];
  4432. UCHAR pid_hash[SHA1_SIZE];
  4433. UINT pid;
  4434. USHORT pid_us;
  4435. // Validate arguments
  4436. if (IsEmptyStr(svc_name))
  4437. {
  4438. return NULL;
  4439. }
  4440. ListenTcpForPopupFirewallDialog();
  4441. if (sock == NULL)
  4442. {
  4443. if (server_mode == false && client_target_ip != NULL)
  4444. {
  4445. sock = NewUDP4ForSpecificIp(client_target_ip, port);
  4446. }
  4447. else
  4448. {
  4449. if (rand_port_id == 0)
  4450. {
  4451. sock = NewUDP(port);
  4452. }
  4453. else
  4454. {
  4455. sock = NewUDPEx2RandMachineAndExePath(false, NULL, 0, rand_port_id);
  4456. }
  4457. }
  4458. if (sock == NULL)
  4459. {
  4460. return NULL;
  4461. }
  4462. }
  4463. else
  4464. {
  4465. AddRef(sock->ref);
  4466. }
  4467. if (port == 0)
  4468. {
  4469. port = sock->LocalPort;
  4470. }
  4471. if (rand_port_id != 0)
  4472. {
  4473. rand_port_numbers[rand_port_id] = port;
  4474. }
  4475. if (sock_event == NULL)
  4476. {
  4477. sock_event = NewSockEvent();
  4478. }
  4479. else
  4480. {
  4481. AddRef(sock_event->ref);
  4482. }
  4483. r = ZeroMalloc(sizeof(RUDP_STACK));
  4484. r->NatT_SessionKey = Rand64();
  4485. StrCpy(r->SvcName, sizeof(r->SvcName), svc_name);
  4486. r->RandPortId = rand_port_id;
  4487. r->NatTGlobalUdpPort = natt_global_udp_port;
  4488. r->ServerMode = server_mode;
  4489. r->Interrupt = NewInterruptManager();
  4490. r->SessionList = NewList(RUDPCompareSessionList);
  4491. r->UdpSock = sock;
  4492. r->Port = port;
  4493. r->SockEvent = sock_event;
  4494. r->HaltEvent = NewEvent();
  4495. r->Now = Tick64();
  4496. r->Lock = NewLock();
  4497. r->Param = param;
  4498. r->TargetConnectedEvent = NewEvent();
  4499. r->SendPacketList = NewList(NULL);
  4500. r->NewSockConnectEvent = NewEvent();
  4501. r->NewSockQueue = NewQueue();
  4502. r->NatT_TranId = Rand64();
  4503. r->NatT_SourceIpList = NewListFast(NULL);
  4504. StrCpy(tmp, sizeof(tmp), r->SvcName);
  4505. Trim(tmp);
  4506. StrLower(tmp);
  4507. HashSha1(r->SvcNameHash, tmp, StrLen(tmp));
  4508. r->Client_IcmpId = (USHORT)(Rand32() % 65534 + 1);
  4509. r->Client_IcmpSeqNo = (USHORT)(Rand32() % 65534 + 1);
  4510. // Determination of the type of the protocol
  4511. r->Protocol = RUDP_PROTOCOL_UDP;
  4512. if (r->Port == MAKE_SPECIAL_PORT(IP_PROTO_ICMPV4))
  4513. {
  4514. r->Protocol = RUDP_PROTOCOL_ICMP;
  4515. // Generate the ICMP ID based on the process ID
  4516. #ifdef OS_WIN32
  4517. pid = (UINT)MsGetProcessId();
  4518. #else // OS_WIN32
  4519. pid = (UINT)getpid();
  4520. #endif // OS_WIN32
  4521. pid = Endian32(pid);
  4522. HashSha1(pid_hash, &pid, sizeof(UINT));
  4523. pid_us = READ_USHORT(pid_hash);
  4524. if (pid_us == 0 || pid_us == 0xFFFF)
  4525. {
  4526. pid_us = 1;
  4527. }
  4528. r->Client_IcmpId = pid_us;
  4529. }
  4530. else if (over_dns_mode)
  4531. {
  4532. r->Protocol = RUDP_PROTOCOL_DNS;
  4533. }
  4534. if (r->ServerMode)
  4535. {
  4536. r->NoNatTRegister = server_no_natt_register;
  4537. if (r->Protocol == RUDP_PROTOCOL_ICMP || r->Protocol == RUDP_PROTOCOL_DNS)
  4538. {
  4539. // Never register to the NAT-T server in case of using the DNS or the ICMP
  4540. r->NoNatTRegister = true;
  4541. }
  4542. }
  4543. if (true
  4544. )
  4545. {
  4546. RUDPGetRegisterHostNameByIP(r->CurrentRegisterHostname, sizeof(r->CurrentRegisterHostname), NULL);
  4547. }
  4548. if (r->ServerMode)
  4549. {
  4550. r->ProcInterrupts = proc_interrupts;
  4551. r->ProcRpcRecv = proc_rpc_recv;
  4552. }
  4553. if (r->ServerMode && r->NoNatTRegister == false
  4554. )
  4555. {
  4556. r->IpQueryThread = NewThread(RUDPIpQueryThread, r);
  4557. }
  4558. JoinSockToSockEvent(r->UdpSock, r->SockEvent);
  4559. r->Thread = NewThread(RUDPMainThread, r);
  4560. WaitThreadInit(r->Thread);
  4561. return r;
  4562. }
  4563. // R-UDP session comparison function
  4564. int RUDPCompareSessionList(void *p1, void *p2)
  4565. {
  4566. RUDP_SESSION *s1, *s2;
  4567. UINT r;
  4568. // Validate arguments
  4569. if (p1 == NULL || p2 == NULL)
  4570. {
  4571. return 0;
  4572. }
  4573. s1 = *((RUDP_SESSION **)p1);
  4574. s2 = *((RUDP_SESSION **)p2);
  4575. if (s1 == NULL || s2 == NULL)
  4576. {
  4577. return 0;
  4578. }
  4579. r = CmpIpAddr(&s1->YourIp, &s2->YourIp);
  4580. if (r != 0)
  4581. {
  4582. return r;
  4583. }
  4584. r = COMPARE_RET(s1->YourPort, s2->YourPort);
  4585. if (r != 0)
  4586. {
  4587. return r;
  4588. }
  4589. r = CmpIpAddr(&s1->MyIp, &s2->MyIp);
  4590. if (r != 0)
  4591. {
  4592. return r;
  4593. }
  4594. r = COMPARE_RET(s1->MyPort, s2->MyPort);
  4595. if (r != 0)
  4596. {
  4597. return r;
  4598. }
  4599. return 0;
  4600. }
  4601. // Release of the R-UDP
  4602. void FreeRUDP(RUDP_STACK *r)
  4603. {
  4604. UINT i;
  4605. // Validate arguments
  4606. if (r == NULL)
  4607. {
  4608. return;
  4609. }
  4610. r->Halt = true;
  4611. Set(r->HaltEvent);
  4612. SetSockEvent(r->SockEvent);
  4613. if (r->ServerMode && r->NoNatTRegister == false)
  4614. {
  4615. if (r->IpQueryThread != NULL)
  4616. {
  4617. WaitThread(r->IpQueryThread, INFINITE);
  4618. ReleaseThread(r->IpQueryThread);
  4619. }
  4620. }
  4621. WaitThread(r->Thread, INFINITE);
  4622. ReleaseThread(r->Thread);
  4623. for (i = 0;i < LIST_NUM(r->SessionList);i++)
  4624. {
  4625. RUDP_SESSION *se = LIST_DATA(r->SessionList, i);
  4626. RUDPFreeSession(se);
  4627. }
  4628. ReleaseList(r->SessionList);
  4629. for (i = 0;i < LIST_NUM(r->SendPacketList);i++)
  4630. {
  4631. UDPPACKET *p = LIST_DATA(r->SendPacketList, i);
  4632. FreeUdpPacket(p);
  4633. }
  4634. while (true)
  4635. {
  4636. SOCK *s = GetNext(r->NewSockQueue);
  4637. if (s == NULL)
  4638. {
  4639. break;
  4640. }
  4641. Disconnect(s);
  4642. ReleaseSock(s);
  4643. }
  4644. for (i = 0;i < LIST_NUM(r->NatT_SourceIpList);i++)
  4645. {
  4646. RUDP_SOURCE_IP *sip = (RUDP_SOURCE_IP *)LIST_DATA(r->NatT_SourceIpList, i);
  4647. Free(sip);
  4648. }
  4649. ReleaseList(r->NatT_SourceIpList);
  4650. ReleaseQueue(r->NewSockQueue);
  4651. ReleaseList(r->SendPacketList);
  4652. FreeInterruptManager(r->Interrupt);
  4653. Disconnect(r->UdpSock);
  4654. ReleaseSock(r->UdpSock);
  4655. ReleaseSockEvent(r->SockEvent);
  4656. ReleaseEvent(r->HaltEvent);
  4657. ReleaseEvent(r->TargetConnectedEvent);
  4658. ReleaseEvent(r->NewSockConnectEvent);
  4659. Disconnect(r->TargetConnectedSock);
  4660. ReleaseSock(r->TargetConnectedSock);
  4661. DeleteLock(r->Lock);
  4662. if (r->RandPortId != 0)
  4663. {
  4664. rand_port_numbers[r->RandPortId] = 0;
  4665. }
  4666. Free(r);
  4667. }
  4668. // Generate a hash from the current computer name and the process name
  4669. void GetCurrentMachineIpProcessHash(void *hash)
  4670. {
  4671. // Validate arguments
  4672. if (hash == NULL)
  4673. {
  4674. return;
  4675. }
  4676. Lock(machine_ip_process_hash_lock);
  4677. {
  4678. if (IsZero(machine_ip_process_hash, SHA1_SIZE))
  4679. {
  4680. GetCurrentMachineIpProcessHashInternal(machine_ip_process_hash);
  4681. }
  4682. Copy(hash, machine_ip_process_hash, SHA1_SIZE);
  4683. }
  4684. Unlock(machine_ip_process_hash_lock);
  4685. }
  4686. void GetCurrentMachineIpProcessHashInternal(void *hash)
  4687. {
  4688. BUF *b;
  4689. LIST *ip_list;
  4690. char machine_name[MAX_SIZE];
  4691. wchar_t exe_path[MAX_PATH];
  4692. char *product_id = NULL;
  4693. // Validate arguments
  4694. if (hash == NULL)
  4695. {
  4696. return;
  4697. }
  4698. #ifdef OS_WIN32
  4699. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductId");
  4700. if (product_id == NULL)
  4701. {
  4702. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProductId");
  4703. }
  4704. #endif // OS_WIN32
  4705. b = NewBuf();
  4706. GetMachineHostName(machine_name, sizeof(machine_name));
  4707. Trim(machine_name);
  4708. StrUpper(machine_name);
  4709. GetExeNameW(exe_path, sizeof(exe_path));
  4710. UniTrim(exe_path);
  4711. UniStrUpper(exe_path);
  4712. WriteBuf(b, machine_name, StrSize(machine_name));
  4713. WriteBuf(b, exe_path, UniStrSize(exe_path));
  4714. WriteBuf(b, product_id, StrSize(product_id));
  4715. ip_list = GetHostIPAddressList();
  4716. if (ip_list != NULL)
  4717. {
  4718. UINT i;
  4719. for (i = 0;i < LIST_NUM(ip_list);i++)
  4720. {
  4721. IP *ip = LIST_DATA(ip_list, i);
  4722. WriteBuf(b, ip, sizeof(IP));
  4723. }
  4724. }
  4725. FreeHostIPAddressList(ip_list);
  4726. HashSha1(hash, b->Buf, b->Size);
  4727. FreeBuf(b);
  4728. Free(product_id);
  4729. }
  4730. // Create a pair of pre-bound TCP sockets
  4731. bool NewTcpPair(SOCK **s1, SOCK **s2)
  4732. {
  4733. SOCK *a;
  4734. SOCK *s, *c;
  4735. TUBE *t1, *t2;
  4736. SOCK_EVENT *e1, *e2;
  4737. // Validate arguments
  4738. if (s1 == NULL || s2 == NULL)
  4739. {
  4740. return false;
  4741. }
  4742. a = ListenAnyPortEx2(true, true);
  4743. if (a == NULL)
  4744. {
  4745. return false;
  4746. }
  4747. c = Connect("127.0.0.1", a->LocalPort);
  4748. if (c == NULL)
  4749. {
  4750. ReleaseSock(a);
  4751. return false;
  4752. }
  4753. s = Accept(a);
  4754. if (s == NULL)
  4755. {
  4756. ReleaseSock(c);
  4757. ReleaseSock(a);
  4758. return false;
  4759. }
  4760. ReleaseSock(a);
  4761. if ((s->LocalPort != c->RemotePort) || (s->RemotePort != c->LocalPort))
  4762. {
  4763. ReleaseSock(s);
  4764. ReleaseSock(c);
  4765. return false;
  4766. }
  4767. NewTubePair(&t1, &t2, sizeof(TCP_PAIR_HEADER));
  4768. // Creating a socket event
  4769. e1 = NewSockEvent();
  4770. e2 = NewSockEvent();
  4771. SetTubeSockEvent(t1, e1);
  4772. SetTubeSockEvent(t2, e2);
  4773. AddRef(t1->Ref);
  4774. AddRef(t2->Ref);
  4775. s->BulkRecvTube = c->BulkSendTube = t1;
  4776. s->BulkSendTube = c->BulkRecvTube = t2;
  4777. ReleaseSockEvent(e1);
  4778. ReleaseSockEvent(e2);
  4779. *s1 = s;
  4780. *s2 = c;
  4781. return true;
  4782. }
  4783. // Listen in any available port
  4784. SOCK *ListenAnyPortEx(bool local_only)
  4785. {
  4786. return ListenAnyPortEx2(local_only, false);
  4787. }
  4788. SOCK *ListenAnyPortEx2(bool local_only, bool disable_ca)
  4789. {
  4790. UINT i;
  4791. SOCK *s;
  4792. for (i = 40000;i < 65536;i++)
  4793. {
  4794. s = ListenEx(i, local_only);
  4795. if (s != NULL)
  4796. {
  4797. return s;
  4798. }
  4799. }
  4800. return NULL;
  4801. }
  4802. int cb_test(int a, X509_STORE_CTX *ctx)
  4803. {
  4804. WHERE;
  4805. return 1;
  4806. }
  4807. // Create a new SSL pipe
  4808. SSL_PIPE *NewSslPipe(bool server_mode, X *x, K *k, DH_CTX *dh)
  4809. {
  4810. SSL_PIPE *s;
  4811. SSL *ssl;
  4812. SSL_CTX *ssl_ctx = NewSSLCtx(server_mode);
  4813. Lock(openssl_lock);
  4814. {
  4815. if (server_mode)
  4816. {
  4817. SSL_CTX_set_ssl_version(ssl_ctx, SSLv23_method());
  4818. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
  4819. AddChainSslCertOnDirectory(ssl_ctx);
  4820. if (dh != NULL)
  4821. {
  4822. SSL_CTX_set_tmp_dh(ssl_ctx, dh->dh);
  4823. }
  4824. }
  4825. else
  4826. {
  4827. SSL_CTX_set_ssl_version(ssl_ctx, SSLv23_client_method());
  4828. }
  4829. //SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, cb_test);
  4830. if (dh != NULL)
  4831. {
  4832. SSL_CTX_set_options(ssl_ctx, SSL_OP_SINGLE_DH_USE);
  4833. }
  4834. if (server_mode == false)
  4835. {
  4836. SSL_CTX_set_options(ssl_ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
  4837. }
  4838. ssl = SSL_new(ssl_ctx);
  4839. }
  4840. Unlock(openssl_lock);
  4841. s = ZeroMalloc(sizeof(SSL_PIPE));
  4842. s->ssl = ssl;
  4843. s->ssl_ctx = ssl_ctx;
  4844. s->ServerMode = server_mode;
  4845. s->SslInOut = NewSslBioSsl();
  4846. s->RawIn = NewSslBioMem();
  4847. s->RawOut = NewSslBioMem();
  4848. if (x != NULL && k != NULL)
  4849. {
  4850. Lock(openssl_lock);
  4851. {
  4852. SSL_use_certificate(s->ssl, x->x509);
  4853. SSL_use_PrivateKey(s->ssl, k->pkey);
  4854. }
  4855. Unlock(openssl_lock);
  4856. }
  4857. if (s->ServerMode == false)
  4858. {
  4859. SSL_set_connect_state(s->ssl);
  4860. }
  4861. else
  4862. {
  4863. SSL_set_accept_state(s->ssl);
  4864. }
  4865. SSL_set_bio(s->ssl, s->RawIn->bio, s->RawOut->bio);
  4866. BIO_set_ssl(s->SslInOut->bio, s->ssl, BIO_NOCLOSE);
  4867. //s->RawIn->NoFree = true;
  4868. s->RawOut->NoFree = true;
  4869. return s;
  4870. }
  4871. // Synchronization of the SSL pipe
  4872. bool SyncSslPipe(SSL_PIPE *s)
  4873. {
  4874. UINT i;
  4875. // Validate arguments
  4876. if (s == NULL || s->IsDisconnected)
  4877. {
  4878. return false;
  4879. }
  4880. for (i = 0;i < 2;i++)
  4881. {
  4882. if (SslBioSync(s->RawIn, true, false) == false)
  4883. {
  4884. s->IsDisconnected = true;
  4885. Debug("SyncSslPipe: s->RawIn error.\n");
  4886. return false;
  4887. }
  4888. if (SslBioSync(s->RawOut, false, true) == false)
  4889. {
  4890. s->IsDisconnected = true;
  4891. Debug("SyncSslPipe: s->RawOut error.\n");
  4892. return false;
  4893. }
  4894. if (SslBioSync(s->SslInOut, true, true) == false)
  4895. {
  4896. s->IsDisconnected = true;
  4897. Debug("SyncSslPipe: s->SslInOut error.\n");
  4898. return false;
  4899. }
  4900. }
  4901. return true;
  4902. }
  4903. // Release of the SSL pipe
  4904. void FreeSslPipe(SSL_PIPE *s)
  4905. {
  4906. // Validate arguments
  4907. if (s == NULL)
  4908. {
  4909. return;
  4910. }
  4911. FreeSslBio(s->SslInOut);
  4912. FreeSslBio(s->RawIn);
  4913. FreeSslBio(s->RawOut);
  4914. SSL_free(s->ssl);
  4915. SSL_CTX_free(s->ssl_ctx);
  4916. Free(s);
  4917. }
  4918. // Release of the SSL BIO
  4919. void FreeSslBio(SSL_BIO *b)
  4920. {
  4921. // Validate arguments
  4922. if (b == NULL)
  4923. {
  4924. return;
  4925. }
  4926. if (b->NoFree == false)
  4927. {
  4928. BIO_free(b->bio);
  4929. }
  4930. ReleaseFifo(b->RecvFifo);
  4931. ReleaseFifo(b->SendFifo);
  4932. Free(b);
  4933. }
  4934. // Create a new SSL BIO (SSL)
  4935. SSL_BIO *NewSslBioSsl()
  4936. {
  4937. SSL_BIO *b = ZeroMalloc(sizeof(SSL_BIO));
  4938. b->bio = BIO_new(BIO_f_ssl());
  4939. b->RecvFifo = NewFifo();
  4940. b->SendFifo = NewFifo();
  4941. return b;
  4942. }
  4943. // Create a new SSL BIO (memory)
  4944. SSL_BIO *NewSslBioMem()
  4945. {
  4946. SSL_BIO *b = ZeroMalloc(sizeof(SSL_BIO));
  4947. b->bio = BIO_new(BIO_s_mem());
  4948. b->RecvFifo = NewFifo();
  4949. b->SendFifo = NewFifo();
  4950. return b;
  4951. }
  4952. // Synchronize memory contents of the SSL BIO with the FIFO
  4953. bool SslBioSync(SSL_BIO *b, bool sync_send, bool sync_recv)
  4954. {
  4955. // Validate arguments
  4956. if (b == NULL)
  4957. {
  4958. return false;
  4959. }
  4960. if (b->IsDisconnected)
  4961. {
  4962. return false;
  4963. }
  4964. // Write the contents of the SendFifo to the BIO
  4965. if (sync_send)
  4966. {
  4967. while (b->SendFifo->size >= 1)
  4968. {
  4969. int r = BIO_write(b->bio, GetFifoPointer(b->SendFifo), FifoSize(b->SendFifo));
  4970. if (r == 0)
  4971. {
  4972. b->IsDisconnected = true;
  4973. WHERE;
  4974. return false;
  4975. }
  4976. else
  4977. {
  4978. if (r < 0)
  4979. {
  4980. if (BIO_should_retry(b->bio))
  4981. {
  4982. break;
  4983. }
  4984. else
  4985. {
  4986. b->IsDisconnected = true;
  4987. WHERE;
  4988. return false;
  4989. }
  4990. }
  4991. else
  4992. {
  4993. ReadFifo(b->SendFifo, NULL, (UINT)r);
  4994. }
  4995. }
  4996. }
  4997. }
  4998. // Save to the RecvFifo by reading from the BIO
  4999. if (sync_recv)
  5000. {
  5001. while (true)
  5002. {
  5003. UCHAR tmp[4096];
  5004. int r;
  5005. r = BIO_read(b->bio, tmp, sizeof(tmp));
  5006. if (r == 0)
  5007. {
  5008. b->IsDisconnected = true;
  5009. WHERE;
  5010. return false;
  5011. }
  5012. else
  5013. {
  5014. if (r < 0)
  5015. {
  5016. if (BIO_should_retry(b->bio))
  5017. {
  5018. break;
  5019. }
  5020. else
  5021. {
  5022. b->IsDisconnected = true;
  5023. WHERE;
  5024. Debug("OpenSSL Error: %s\n", ERR_error_string(ERR_peek_last_error(), NULL));
  5025. return false;
  5026. }
  5027. }
  5028. else
  5029. {
  5030. WriteFifo(b->RecvFifo, tmp, (UINT)r);
  5031. }
  5032. }
  5033. }
  5034. }
  5035. return true;
  5036. }
  5037. // Release the memory for the return value of the ICMP API
  5038. void IcmpApiFreeResult(ICMP_RESULT *ret)
  5039. {
  5040. // Validate arguments
  5041. if (ret == NULL)
  5042. {
  5043. return;
  5044. }
  5045. if (ret->Data != NULL)
  5046. {
  5047. Free(ret->Data);
  5048. }
  5049. Free(ret);
  5050. }
  5051. // Send an ICMP Echo using ICMP API
  5052. ICMP_RESULT *IcmpApiEchoSend(IP *dest_ip, UCHAR ttl, UCHAR *data, UINT size, UINT timeout)
  5053. {
  5054. #ifdef OS_WIN32
  5055. // Validate arguments
  5056. if (dest_ip == NULL || IsIP4(dest_ip) == false || (size != 0 && data == NULL))
  5057. {
  5058. return NULL;
  5059. }
  5060. if (ttl == 0)
  5061. {
  5062. ttl = 127;
  5063. }
  5064. if (IsIcmpApiSupported())
  5065. {
  5066. HANDLE h;
  5067. DWORD dw;
  5068. IPAddr dest_addr;
  5069. UINT reply_size;
  5070. ICMP_ECHO_REPLY *reply;
  5071. ICMP_RESULT *ret = NULL;
  5072. IP_OPTION_INFORMATION opt;
  5073. h = w32net->IcmpCreateFile();
  5074. if (h == INVALID_HANDLE_VALUE)
  5075. {
  5076. return NULL;
  5077. }
  5078. Zero(&opt, sizeof(opt));
  5079. opt.Ttl = ttl;
  5080. IPToInAddr((struct in_addr *)&dest_addr, dest_ip);
  5081. reply_size = sizeof(*reply) + size + 64;
  5082. reply = ZeroMalloc(reply_size);
  5083. dw = w32net->IcmpSendEcho(h, dest_addr, data, size, &opt, reply, reply_size, timeout);
  5084. ret = ZeroMalloc(sizeof(ICMP_RESULT));
  5085. if (dw >= 1 && reply->Status == IP_SUCCESS)
  5086. {
  5087. ret->Ok = true;
  5088. }
  5089. else
  5090. {
  5091. switch (reply->Status)
  5092. {
  5093. case IP_DEST_NET_UNREACHABLE:
  5094. ret->Type = ICMP_TYPE_DESTINATION_UNREACHABLE;
  5095. ret->Code = ICMP_CODE_NET_UNREACHABLE;
  5096. break;
  5097. case IP_DEST_HOST_UNREACHABLE:
  5098. ret->Type = ICMP_TYPE_DESTINATION_UNREACHABLE;
  5099. ret->Code = ICMP_CODE_HOST_UNREACHABLE;
  5100. break;
  5101. case IP_DEST_PROT_UNREACHABLE:
  5102. ret->Type = ICMP_TYPE_DESTINATION_UNREACHABLE;
  5103. ret->Code = ICMP_CODE_PROTOCOL_UNREACHABLE;
  5104. break;
  5105. case IP_DEST_PORT_UNREACHABLE:
  5106. ret->Type = ICMP_TYPE_DESTINATION_UNREACHABLE;
  5107. ret->Code = ICMP_CODE_PORT_UNREACHABLE;
  5108. break;
  5109. case IP_TTL_EXPIRED_TRANSIT:
  5110. ret->Type = ICMP_TYPE_TIME_EXCEEDED;
  5111. ret->Code = ICMP_CODE_TTL_EXCEEDED_IN_TRANSIT;
  5112. break;
  5113. case IP_TTL_EXPIRED_REASSEM:
  5114. ret->Type = ICMP_TYPE_TIME_EXCEEDED;
  5115. ret->Code = ICMP_CODE_FRAGMENT_REASSEMBLY_TIME_EXCEEDED;
  5116. break;
  5117. default:
  5118. ret->Timeout = true;
  5119. break;
  5120. }
  5121. }
  5122. if (ret->Timeout == false)
  5123. {
  5124. ret->Ttl = reply->Options.Ttl;
  5125. ret->Rtt = reply->RoundTripTime;
  5126. InAddrToIP(&ret->IpAddress, (struct in_addr *)&reply->Address);
  5127. if (reply->DataSize >= 1 && reply->Data != NULL)
  5128. {
  5129. ret->DataSize = reply->DataSize;
  5130. ret->Data = Clone(reply->Data, reply->DataSize);
  5131. }
  5132. }
  5133. Free(reply);
  5134. w32net->IcmpCloseHandle(h);
  5135. return ret;
  5136. }
  5137. else
  5138. {
  5139. return NULL;
  5140. }
  5141. #else // OS_WIN32
  5142. return NULL;
  5143. #endif // OS_WIN32
  5144. }
  5145. // Detect whether the ICMP API is supported
  5146. bool IsIcmpApiSupported()
  5147. {
  5148. #ifdef OS_WIN32
  5149. if (w32net->IcmpCloseHandle != NULL &&
  5150. w32net->IcmpCreateFile != NULL &&
  5151. w32net->IcmpSendEcho != NULL)
  5152. {
  5153. return true;
  5154. }
  5155. #endif // OS_WIN32
  5156. return false;
  5157. }
  5158. // Initialize the routing table change detector
  5159. ROUTE_CHANGE *NewRouteChange()
  5160. {
  5161. #ifdef OS_WIN32
  5162. return Win32NewRouteChange();
  5163. #else // OS_WIN32
  5164. return NULL;
  5165. #endif // OS_WIN32
  5166. }
  5167. // Release the routing table change detector
  5168. void FreeRouteChange(ROUTE_CHANGE *r)
  5169. {
  5170. #ifdef OS_WIN32
  5171. Win32FreeRouteChange(r);
  5172. #endif // OS_WIN32
  5173. }
  5174. // Get whether the routing table has been changed
  5175. bool IsRouteChanged(ROUTE_CHANGE *r)
  5176. {
  5177. #ifdef OS_WIN32
  5178. return Win32IsRouteChanged(r);
  5179. #else // OS_WIN32
  5180. return false;
  5181. #endif // OS_WIN32
  5182. }
  5183. // Routing table change detector function (Win32)
  5184. #ifdef OS_WIN32
  5185. ROUTE_CHANGE *Win32NewRouteChange()
  5186. {
  5187. ROUTE_CHANGE *r;
  5188. bool ret;
  5189. if (MsIsNt() == false)
  5190. {
  5191. return NULL;
  5192. }
  5193. if (w32net->CancelIPChangeNotify == NULL ||
  5194. w32net->NotifyRouteChange == NULL)
  5195. {
  5196. return NULL;
  5197. }
  5198. r = ZeroMalloc(sizeof(ROUTE_CHANGE));
  5199. r->Data = ZeroMalloc(sizeof(ROUTE_CHANGE_DATA));
  5200. r->Data->Overlapped.hEvent = CreateEventA(NULL, false, true, NULL);
  5201. ret = w32net->NotifyRouteChange(&r->Data->Handle, &r->Data->Overlapped);
  5202. if (!(ret == NO_ERROR || ret == WSA_IO_PENDING || WSAGetLastError() == WSA_IO_PENDING))
  5203. {
  5204. Free(r->Data);
  5205. Free(r);
  5206. return NULL;
  5207. }
  5208. return r;
  5209. }
  5210. void Win32FreeRouteChange(ROUTE_CHANGE *r)
  5211. {
  5212. // Validate arguments
  5213. if (r == NULL)
  5214. {
  5215. return;
  5216. }
  5217. w32net->CancelIPChangeNotify(&r->Data->Overlapped);
  5218. CloseHandle(r->Data->Overlapped.hEvent);
  5219. Free(r->Data);
  5220. Free(r);
  5221. }
  5222. bool Win32IsRouteChanged(ROUTE_CHANGE *r)
  5223. {
  5224. // Validate arguments
  5225. if (r == NULL)
  5226. {
  5227. return false;
  5228. }
  5229. if ((r->Data->NumCalled++) == 0)
  5230. {
  5231. return true;
  5232. }
  5233. if (WaitForSingleObject(r->Data->Overlapped.hEvent, 0) == WAIT_OBJECT_0)
  5234. {
  5235. w32net->NotifyRouteChange(&r->Data->Handle, &r->Data->Overlapped);
  5236. return true;
  5237. }
  5238. return false;
  5239. }
  5240. typedef struct WIN32_ACCEPT_CHECK_DATA
  5241. {
  5242. bool IsIPv6;
  5243. bool Rejected;
  5244. } WIN32_ACCEPT_CHECK_DATA;
  5245. // Function for determining whether accept or not in Win32
  5246. int CALLBACK Win32AcceptCheckCallback_Delay(LPWSABUF lpCallerId, LPWSABUF lpCallerData, LPQOS pQos,
  5247. LPQOS lpGQOS, LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,
  5248. GROUP FAR * g, DWORD_PTR dwCallbackData)
  5249. {
  5250. return CF_DEFER;
  5251. }
  5252. int CALLBACK Win32AcceptCheckCallback(LPWSABUF lpCallerId, LPWSABUF lpCallerData, LPQOS pQos,
  5253. LPQOS lpGQOS, LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,
  5254. GROUP FAR * g, DWORD_PTR dwCallbackData)
  5255. {
  5256. return CF_ACCEPT;
  5257. }
  5258. // Accept function for Win32
  5259. SOCKET Win32Accept_XP(SOCK *sock, SOCKET s, struct sockaddr *addr, int *addrlen, bool ipv6)
  5260. {
  5261. SOCKET ret;
  5262. WIN32_ACCEPT_CHECK_DATA d;
  5263. UINT err;
  5264. int initial_addrlen = *addrlen;
  5265. UINT num_error = 0;
  5266. // Validate arguments
  5267. if (s == INVALID_SOCKET)
  5268. {
  5269. return INVALID_SOCKET;
  5270. }
  5271. L_LOOP:
  5272. Zero(&d, sizeof(d));
  5273. d.IsIPv6 = ipv6;
  5274. *addrlen = initial_addrlen;
  5275. Zero(addr, initial_addrlen);
  5276. ret = WSAAccept(s, addr, addrlen, Win32AcceptCheckCallback, (DWORD_PTR)&d);
  5277. if (ret == INVALID_SOCKET)
  5278. {
  5279. err = WSAGetLastError();
  5280. num_error++;
  5281. Debug("!!! WSAAccept Error: %u rej=%u num=%u tick=%I64u\n", WSAGetLastError(), d.Rejected, num_error, Tick64());
  5282. if (d.Rejected && err == WSAECONNREFUSED)
  5283. {
  5284. goto L_LOOP;
  5285. }
  5286. if (err == WSAETIMEDOUT)
  5287. {
  5288. goto L_LOOP;
  5289. }
  5290. }
  5291. return ret;
  5292. }
  5293. // Accept function for Win32
  5294. SOCKET Win32Accept(SOCK *sock, SOCKET s, struct sockaddr *addr, int *addrlen, bool ipv6)
  5295. {
  5296. SOCKET ret;
  5297. WIN32_ACCEPT_CHECK_DATA d;
  5298. UINT err;
  5299. int initial_addrlen = *addrlen;
  5300. UINT num_error = 0;
  5301. UINT zero = 0;
  5302. UINT tmp = 0;
  5303. UINT ret_size = 0;
  5304. // Validate arguments
  5305. if (sock == NULL || s == INVALID_SOCKET)
  5306. {
  5307. return INVALID_SOCKET;
  5308. }
  5309. if (sock->hAcceptEvent == NULL)
  5310. {
  5311. sock->hAcceptEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  5312. WSAEventSelect(s, sock->hAcceptEvent, FD_ACCEPT | FD_CLOSE);
  5313. }
  5314. L_LOOP:
  5315. if (sock->CancelAccept)
  5316. {
  5317. return INVALID_SOCKET;
  5318. }
  5319. Zero(&d, sizeof(d));
  5320. d.IsIPv6 = ipv6;
  5321. *addrlen = initial_addrlen;
  5322. Zero(addr, initial_addrlen);
  5323. ret = WSAAccept(s, addr, addrlen, Win32AcceptCheckCallback, (DWORD_PTR)&d);
  5324. if (ret == INVALID_SOCKET)
  5325. {
  5326. err = WSAGetLastError();
  5327. if (err == WSAEWOULDBLOCK)
  5328. {
  5329. //Debug("!!! WSAAccept: WSAEWOULDBLOCK\n");
  5330. UINT wait_ret = WaitForSingleObject(sock->hAcceptEvent, 1234);
  5331. if (wait_ret == WAIT_OBJECT_0 || wait_ret == WAIT_TIMEOUT)
  5332. {
  5333. goto L_LOOP;
  5334. }
  5335. Debug("!!! WaitForSingleObject Error. ret=%u GetLastError=%u\n", wait_ret, GetLastError());
  5336. }
  5337. num_error++;
  5338. Debug("!!! WSAAccept Error: %u rej=%u num=%u tick=%I64u\n", err, d.Rejected, num_error, Tick64());
  5339. if (d.Rejected && err == WSAECONNREFUSED)
  5340. {
  5341. goto L_LOOP;
  5342. }
  5343. if (err == WSAETIMEDOUT)
  5344. {
  5345. goto L_LOOP;
  5346. }
  5347. }
  5348. else
  5349. {
  5350. // Remove a new socket from the event
  5351. WSAEventSelect(ret, sock->hAcceptEvent, 0);
  5352. // Restore the new socket to synchronized
  5353. WSAIoctl(ret, FIONBIO, &zero, sizeof(zero), &tmp, sizeof(tmp), &ret_size, NULL, NULL);
  5354. }
  5355. return ret;
  5356. }
  5357. #endif // OS_WIN32
  5358. // Get whether the aquirement of the Process ID of the TCP connection succeed
  5359. bool CanGetTcpProcessId()
  5360. {
  5361. UINT i;
  5362. bool ret = false;
  5363. LIST *o = GetTcpTableList();
  5364. if (o == NULL)
  5365. {
  5366. return false;
  5367. }
  5368. for (i = 0;i < LIST_NUM(o);i++)
  5369. {
  5370. TCPTABLE *t = LIST_DATA(o, i);
  5371. if (t->ProcessId != 0)
  5372. {
  5373. ret = true;
  5374. break;
  5375. }
  5376. }
  5377. FreeTcpTableList(o);
  5378. return ret;
  5379. }
  5380. #define USE_OLD_GETIP
  5381. // Set the arp_filter in Linux
  5382. void SetLinuxArpFilter()
  5383. {
  5384. char *filename = "/proc/sys/net/ipv4/conf/all/arp_filter";
  5385. char *data = "1\n";
  5386. IO *o;
  5387. o = FileCreate(filename);
  5388. if (o == NULL)
  5389. {
  5390. return;
  5391. }
  5392. FileWrite(o, data, StrLen(data));
  5393. FileFlush(o);
  5394. FileClose(o);
  5395. }
  5396. // Determine whether the string is a IPv6 mask
  5397. bool IsIpMask6(char *str)
  5398. {
  5399. IP mask;
  5400. // Validate arguments
  5401. if (str == NULL)
  5402. {
  5403. return false;
  5404. }
  5405. return StrToMask6(&mask, str);
  5406. }
  5407. // Determine whether the string is a IPv6 address
  5408. bool IsStrIPv6Address(char *str)
  5409. {
  5410. IP ip;
  5411. // Validate arguments
  5412. if (str == NULL)
  5413. {
  5414. return false;
  5415. }
  5416. if (StrToIP6(&ip, str) == false)
  5417. {
  5418. return false;
  5419. }
  5420. return true;
  5421. }
  5422. // Convert the subnet mask to an integer
  5423. UINT SubnetMaskToInt6(IP *a)
  5424. {
  5425. UINT i;
  5426. // Validate arguments
  5427. if (IsIP6(a) == false)
  5428. {
  5429. return 0;
  5430. }
  5431. for (i = 0;i <= 128;i++)
  5432. {
  5433. IP tmp;
  5434. IntToSubnetMask6(&tmp, i);
  5435. if (CmpIpAddr(a, &tmp) == 0)
  5436. {
  5437. return i;
  5438. }
  5439. }
  5440. return 0;
  5441. }
  5442. UINT SubnetMaskToInt4(IP *a)
  5443. {
  5444. UINT i;
  5445. // Validate arguments
  5446. if (IsIP4(a) == false)
  5447. {
  5448. return 0;
  5449. }
  5450. for (i = 0;i <= 32;i++)
  5451. {
  5452. IP tmp;
  5453. IntToSubnetMask4(&tmp, i);
  5454. if (CmpIpAddr(a, &tmp) == 0)
  5455. {
  5456. return i;
  5457. }
  5458. }
  5459. return 0;
  5460. }
  5461. UINT SubnetMaskToInt(IP *a)
  5462. {
  5463. if (IsIP6(a))
  5464. {
  5465. return SubnetMaskToInt6(a);
  5466. }
  5467. else
  5468. {
  5469. return SubnetMaskToInt4(a);
  5470. }
  5471. }
  5472. // Determine whether the specified IP address is a subnet mask
  5473. bool IsSubnetMask6(IP *a)
  5474. {
  5475. UINT i;
  5476. // Validate arguments
  5477. if (IsIP6(a) == false)
  5478. {
  5479. return false;
  5480. }
  5481. for (i = 0;i <= 128;i++)
  5482. {
  5483. IP tmp;
  5484. IntToSubnetMask6(&tmp, i);
  5485. if (CmpIpAddr(a, &tmp) == 0)
  5486. {
  5487. return true;
  5488. }
  5489. }
  5490. return false;
  5491. }
  5492. // Generate a global address from the MAC address
  5493. void GenerateEui64GlobalAddress(IP *ip, IP *prefix, IP *subnet, UCHAR *mac)
  5494. {
  5495. UCHAR tmp[8];
  5496. IP a;
  5497. IP subnet_not;
  5498. IP or1, or2;
  5499. // Validate arguments
  5500. if (ip == NULL || prefix == NULL || subnet == NULL || mac == NULL)
  5501. {
  5502. return;
  5503. }
  5504. GenerateEui64Address6(tmp, mac);
  5505. ZeroIP6(&a);
  5506. Copy(&a.ipv6_addr[8], tmp, 8);
  5507. IPNot6(&subnet_not, subnet);
  5508. IPAnd6(&or1, &a, &subnet_not);
  5509. IPAnd6(&or2, prefix, subnet);
  5510. IPOr6(ip, &or1, &or2);
  5511. }
  5512. // Generate a local address from the MAC address
  5513. void GenerateEui64LocalAddress(IP *a, UCHAR *mac)
  5514. {
  5515. UCHAR tmp[8];
  5516. // Validate arguments
  5517. if (a == NULL || mac == NULL)
  5518. {
  5519. return;
  5520. }
  5521. GenerateEui64Address6(tmp, mac);
  5522. ZeroIP6(a);
  5523. a->ipv6_addr[0] = 0xfe;
  5524. a->ipv6_addr[1] = 0x80;
  5525. Copy(&a->ipv6_addr[8], tmp, 8);
  5526. }
  5527. // Generate the EUI-64 address from the MAC address
  5528. void GenerateEui64Address6(UCHAR *dst, UCHAR *mac)
  5529. {
  5530. // Validate arguments
  5531. if (dst == NULL || mac == NULL)
  5532. {
  5533. return;
  5534. }
  5535. Copy(dst, mac, 3);
  5536. Copy(dst + 5, mac, 3);
  5537. dst[3] = 0xff;
  5538. dst[4] = 0xfe;
  5539. dst[0] = ((~(dst[0] & 0x02)) & 0x02) | (dst[0] & 0xfd);
  5540. }
  5541. // Examine whether two IP addresses are in the same network
  5542. bool IsInSameNetwork6ByStr(char *ip1, char *ip2, char *subnet)
  5543. {
  5544. IP p1, p2, s;
  5545. if (StrToIP6(&p1, ip1) == false)
  5546. {
  5547. return false;
  5548. }
  5549. if (StrToIP6(&p2, ip2) == false)
  5550. {
  5551. return false;
  5552. }
  5553. if (StrToMask6(&s, subnet) == false)
  5554. {
  5555. return false;
  5556. }
  5557. return IsInSameNetwork6(&p1, &p2, &s);
  5558. }
  5559. bool IsInSameNetwork6(IP *a1, IP *a2, IP *subnet)
  5560. {
  5561. IP prefix1, prefix2;
  5562. // Validate arguments
  5563. if (IsIP6(a1) == false || IsIP6(a2) == false || IsIP6(subnet) == false)
  5564. {
  5565. return false;
  5566. }
  5567. if (a1->ipv6_scope_id != a2->ipv6_scope_id)
  5568. {
  5569. return false;
  5570. }
  5571. GetPrefixAddress6(&prefix1, a1, subnet);
  5572. GetPrefixAddress6(&prefix2, a2, subnet);
  5573. if (CmpIpAddr(&prefix1, &prefix2) == 0)
  5574. {
  5575. return true;
  5576. }
  5577. return false;
  5578. }
  5579. bool IsInSameNetwork4(IP *a1, IP *a2, IP *subnet)
  5580. {
  5581. IP net1, net2;
  5582. // Validate arguments
  5583. if (IsIP4(a1) == false || IsIP4(a2) == false || IsIP4(subnet) == false)
  5584. {
  5585. return false;
  5586. }
  5587. IPAnd4(&net1, a1, subnet);
  5588. IPAnd4(&net2, a2, subnet);
  5589. if (CmpIpAddr(&net1, &net2) == 0)
  5590. {
  5591. return true;
  5592. }
  5593. return false;
  5594. }
  5595. bool IsInSameNetwork4Standard(IP *a1, IP *a2)
  5596. {
  5597. IP subnet;
  5598. SetIP(&subnet, 255, 255, 0, 0);
  5599. return IsInSameNetwork4(a1, a2, &subnet);
  5600. }
  5601. bool IsInSameLocalNetworkToMe4(IP *a)
  5602. {
  5603. IP g1, g2;
  5604. Zero(&g1, sizeof(g1));
  5605. Zero(&g2, sizeof(g2));
  5606. GetCurrentGlobalIPGuess(&g1, false);
  5607. if (IsZeroIp(&g1) == false)
  5608. {
  5609. if (IsInSameNetwork4Standard(&g1, a))
  5610. {
  5611. return true;
  5612. }
  5613. }
  5614. if (GetCurrentGlobalIP(&g2, false))
  5615. {
  5616. if (IsInSameNetwork4Standard(&g2, a))
  5617. {
  5618. return true;
  5619. }
  5620. }
  5621. if (IsIPAddressInSameLocalNetwork(a))
  5622. {
  5623. return true;
  5624. }
  5625. return false;
  5626. }
  5627. // Check whether it is a network address prefix
  5628. bool IsNetworkAddress6(IP *ip, IP *subnet)
  5629. {
  5630. return IsNetworkPrefixAddress6(ip, subnet);
  5631. }
  5632. bool IsNetworkPrefixAddress6(IP *ip, IP *subnet)
  5633. {
  5634. IP host;
  5635. // Validate arguments
  5636. if (ip == NULL || subnet == NULL)
  5637. {
  5638. return false;
  5639. }
  5640. if (IsIP6(ip) == false || IsIP6(subnet) == false)
  5641. {
  5642. return false;
  5643. }
  5644. GetHostAddress6(&host, ip, subnet);
  5645. if (IsZeroIp(&host))
  5646. {
  5647. return true;
  5648. }
  5649. return false;
  5650. }
  5651. // Check whether the unicast address is available
  5652. bool CheckUnicastAddress(IP *ip)
  5653. {
  5654. // Validate arguments
  5655. if (ip == NULL)
  5656. {
  5657. return false;
  5658. }
  5659. if ((GetIPAddrType6(ip) & IPV6_ADDR_UNICAST) == 0)
  5660. {
  5661. return false;
  5662. }
  5663. return true;
  5664. }
  5665. // Get the host address
  5666. void GetHostAddress6(IP *dst, IP *ip, IP *subnet)
  5667. {
  5668. IP not;
  5669. // Validate arguments
  5670. if (dst == NULL || ip == NULL || subnet == NULL)
  5671. {
  5672. return;
  5673. }
  5674. IPNot6(&not, subnet);
  5675. IPAnd6(dst, ip, &not);
  5676. dst->ipv6_scope_id = ip->ipv6_scope_id;
  5677. }
  5678. // Get the prefix address
  5679. void GetPrefixAddress6(IP *dst, IP *ip, IP *subnet)
  5680. {
  5681. // Validate arguments
  5682. if (dst == NULL || ip == NULL || subnet == NULL)
  5683. {
  5684. return;
  5685. }
  5686. IPAnd6(dst, ip, subnet);
  5687. dst->ipv6_scope_id = ip->ipv6_scope_id;
  5688. }
  5689. // Get the solicited-node multicast address
  5690. void GetSoliciationMulticastAddr6(IP *dst, IP *src)
  5691. {
  5692. IP prefix;
  5693. IP mask104;
  5694. IP or1, or2;
  5695. // Validate arguments
  5696. if (dst == NULL || src == NULL)
  5697. {
  5698. return;
  5699. }
  5700. ZeroIP6(&prefix);
  5701. prefix.ipv6_addr[0] = 0xff;
  5702. prefix.ipv6_addr[1] = 0x02;
  5703. prefix.ipv6_addr[11] = 0x01;
  5704. prefix.ipv6_addr[12] = 0xff;
  5705. IntToSubnetMask6(&mask104, 104);
  5706. IPAnd6(&or1, &prefix, &mask104);
  5707. IPAnd6(&or2, src, &mask104);
  5708. IPOr6(dst, &or1, &or2);
  5709. dst->ipv6_scope_id = src->ipv6_scope_id;
  5710. }
  5711. // Generate a MAC address corresponding to the multicast address
  5712. void GenerateMulticastMacAddress6(UCHAR *mac, IP *ip)
  5713. {
  5714. // Validate arguments
  5715. if (mac == NULL)
  5716. {
  5717. return;
  5718. }
  5719. mac[0] = 0x33;
  5720. mac[1] = 0x33;
  5721. mac[2] = ip->ipv6_addr[12];
  5722. mac[3] = ip->ipv6_addr[13];
  5723. mac[4] = ip->ipv6_addr[14];
  5724. mac[5] = ip->ipv6_addr[15];
  5725. }
  5726. // Get the type of the IPv6 address
  5727. UINT GetIPv6AddrType(IPV6_ADDR *addr)
  5728. {
  5729. IP ip;
  5730. // Validate arguments
  5731. if (addr == NULL)
  5732. {
  5733. return 0;
  5734. }
  5735. IPv6AddrToIP(&ip, addr);
  5736. return GetIPAddrType6(&ip);
  5737. }
  5738. UINT GetIPAddrType6(IP *ip)
  5739. {
  5740. UINT ret = 0;
  5741. // Validate arguments
  5742. if (IsIP6(ip) == false)
  5743. {
  5744. return 0;
  5745. }
  5746. if (ip->ipv6_addr[0] == 0xff)
  5747. {
  5748. IP all_node, all_router;
  5749. GetAllNodeMulticaseAddress6(&all_node);
  5750. GetAllRouterMulticastAddress6(&all_router);
  5751. ret |= IPV6_ADDR_MULTICAST;
  5752. if (Cmp(ip->ipv6_addr, all_node.ipv6_addr, 16) == 0)
  5753. {
  5754. ret |= IPV6_ADDR_ALL_NODE_MULTICAST;
  5755. }
  5756. else if (Cmp(ip->ipv6_addr, all_router.ipv6_addr, 16) == 0)
  5757. {
  5758. ret |= IPV6_ADDR_ALL_ROUTER_MULTICAST;
  5759. }
  5760. else
  5761. {
  5762. if (ip->ipv6_addr[1] == 0x02 && ip->ipv6_addr[2] == 0 && ip->ipv6_addr[3] == 0 &&
  5763. ip->ipv6_addr[4] == 0 && ip->ipv6_addr[5] == 0 && ip->ipv6_addr[6] == 0 &&
  5764. ip->ipv6_addr[7] == 0 && ip->ipv6_addr[8] == 0 && ip->ipv6_addr[9] == 0 &&
  5765. ip->ipv6_addr[10] == 0 && ip->ipv6_addr[11] == 0x01 && ip->ipv6_addr[12] == 0xff)
  5766. {
  5767. ret |= IPV6_ADDR_SOLICIATION_MULTICAST;
  5768. }
  5769. }
  5770. }
  5771. else
  5772. {
  5773. ret |= IPV6_ADDR_UNICAST;
  5774. if (ip->ipv6_addr[0] == 0xfe && (ip->ipv6_addr[1] & 0xc0) == 0x80)
  5775. {
  5776. ret |= IPV6_ADDR_LOCAL_UNICAST;
  5777. }
  5778. else
  5779. {
  5780. ret |= IPV6_ADDR_GLOBAL_UNICAST;
  5781. if (IsZero(&ip->ipv6_addr, 16))
  5782. {
  5783. ret |= IPV6_ADDR_ZERO;
  5784. }
  5785. else
  5786. {
  5787. IP loopback;
  5788. GetLoopbackAddress6(&loopback);
  5789. if (Cmp(ip->ipv6_addr, loopback.ipv6_addr, 16) == 0)
  5790. {
  5791. ret |= IPV6_ADDR_LOOPBACK;
  5792. }
  5793. }
  5794. }
  5795. }
  5796. return ret;
  5797. }
  5798. // Address that all of the bits are set
  5799. void GetAllFilledAddress6(IP *ip)
  5800. {
  5801. UINT i;
  5802. // Validate arguments
  5803. if (ip == NULL)
  5804. {
  5805. return;
  5806. }
  5807. ZeroIP6(ip);
  5808. for (i = 0;i < 15;i++)
  5809. {
  5810. ip->ipv6_addr[i] = 0xff;
  5811. }
  5812. }
  5813. // Loopback address
  5814. void GetLoopbackAddress6(IP *ip)
  5815. {
  5816. // Validate arguments
  5817. if (ip == NULL)
  5818. {
  5819. return;
  5820. }
  5821. ZeroIP6(ip);
  5822. ip->ipv6_addr[15] = 0x01;
  5823. }
  5824. // All-nodes multicast address
  5825. void GetAllNodeMulticaseAddress6(IP *ip)
  5826. {
  5827. // Validate arguments
  5828. if (ip == NULL)
  5829. {
  5830. return;
  5831. }
  5832. ZeroIP6(ip);
  5833. ip->ipv6_addr[0] = 0xff;
  5834. ip->ipv6_addr[1] = 0x02;
  5835. ip->ipv6_addr[15] = 0x01;
  5836. }
  5837. // All-routers multicast address
  5838. void GetAllRouterMulticastAddress6(IP *ip)
  5839. {
  5840. // Validate arguments
  5841. if (ip == NULL)
  5842. {
  5843. return;
  5844. }
  5845. ZeroIP6(ip);
  5846. ip->ipv6_addr[0] = 0xff;
  5847. ip->ipv6_addr[1] = 0x02;
  5848. ip->ipv6_addr[15] = 0x02;
  5849. }
  5850. // Logical operation of the IPv4 address
  5851. void IPNot4(IP *dst, IP *a)
  5852. {
  5853. UINT i;
  5854. // Validate arguments
  5855. if (dst == NULL || a == NULL || IsIP4(a) == false)
  5856. {
  5857. Zero(dst, sizeof(IP));
  5858. return;
  5859. }
  5860. i = IPToUINT(a);
  5861. i = ~i;
  5862. UINTToIP(dst, i);
  5863. }
  5864. void IPOr4(IP *dst, IP *a, IP *b)
  5865. {
  5866. UINT i;
  5867. // Validate arguments
  5868. if (dst == NULL || a == NULL || b == NULL || IsIP4(a) == false || IsIP4(b) == false)
  5869. {
  5870. Zero(dst, sizeof(IP));
  5871. return;
  5872. }
  5873. i = IPToUINT(a) | IPToUINT(b);
  5874. UINTToIP(dst, i);
  5875. }
  5876. void IPAnd4(IP *dst, IP *a, IP *b)
  5877. {
  5878. UINT i;
  5879. // Validate arguments
  5880. if (dst == NULL || a == NULL || b == NULL || IsIP4(a) == false || IsIP4(b) == false)
  5881. {
  5882. Zero(dst, sizeof(IP));
  5883. return;
  5884. }
  5885. i = IPToUINT(a) & IPToUINT(b);
  5886. UINTToIP(dst, i);
  5887. }
  5888. // Logical operation of the IPv6 address
  5889. void IPAnd6(IP *dst, IP *a, IP *b)
  5890. {
  5891. UINT i;
  5892. // Validate arguments
  5893. if (dst == NULL || IsIP6(a) == false || IsIP6(b) == false)
  5894. {
  5895. ZeroIP6(dst);
  5896. return;
  5897. }
  5898. ZeroIP6(dst);
  5899. for (i = 0;i < 16;i++)
  5900. {
  5901. dst->ipv6_addr[i] = a->ipv6_addr[i] & b->ipv6_addr[i];
  5902. }
  5903. }
  5904. void IPOr6(IP *dst, IP *a, IP *b)
  5905. {
  5906. UINT i;
  5907. // Validate arguments
  5908. if (dst == NULL || IsIP6(a) == false || IsIP6(b) == false)
  5909. {
  5910. ZeroIP6(dst);
  5911. return;
  5912. }
  5913. ZeroIP6(dst);
  5914. for (i = 0;i < 16;i++)
  5915. {
  5916. dst->ipv6_addr[i] = a->ipv6_addr[i] | b->ipv6_addr[i];
  5917. }
  5918. }
  5919. void IPNot6(IP *dst, IP *a)
  5920. {
  5921. UINT i;
  5922. // Validate arguments
  5923. if (dst == NULL || IsIP6(a) == false)
  5924. {
  5925. ZeroIP6(dst);
  5926. return;
  5927. }
  5928. ZeroIP6(dst);
  5929. for (i = 0;i < 16;i++)
  5930. {
  5931. dst->ipv6_addr[i] = ~(a->ipv6_addr[i]);
  5932. }
  5933. }
  5934. // Creating a subnet mask
  5935. void IntToSubnetMask6(IP *ip, UINT i)
  5936. {
  5937. UINT j = i / 8;
  5938. UINT k = i % 8;
  5939. UINT z;
  5940. IP a;
  5941. ZeroIP6(&a);
  5942. for (z = 0;z < 16;z++)
  5943. {
  5944. if (z < j)
  5945. {
  5946. a.ipv6_addr[z] = 0xff;
  5947. }
  5948. else if (z == j)
  5949. {
  5950. a.ipv6_addr[z] = ~(0xff >> k);
  5951. }
  5952. }
  5953. Copy(ip, &a, sizeof(IP));
  5954. }
  5955. // Convert the IP address to a string
  5956. void IP6AddrToStr(char *str, UINT size, IPV6_ADDR *addr)
  5957. {
  5958. // Validate arguments
  5959. if (str == NULL || addr == NULL)
  5960. {
  5961. return;
  5962. }
  5963. IPToStr6Array(str, size, addr->Value);
  5964. }
  5965. void IPToStr6Array(char *str, UINT size, UCHAR *bytes)
  5966. {
  5967. IP ip;
  5968. // Validate arguments
  5969. if (str == NULL || bytes == NULL)
  5970. {
  5971. return;
  5972. }
  5973. SetIP6(&ip, bytes);
  5974. IPToStr6(str, size, &ip);
  5975. }
  5976. void IPToStr6(char *str, UINT size, IP *ip)
  5977. {
  5978. char tmp[MAX_SIZE];
  5979. IPToStr6Inner(tmp, ip);
  5980. StrCpy(str, size, tmp);
  5981. }
  5982. void IPToStr6Inner(char *str, IP *ip)
  5983. {
  5984. UINT i;
  5985. USHORT values[8];
  5986. UINT zero_started_index;
  5987. UINT max_zero_len;
  5988. UINT max_zero_start;
  5989. IP a;
  5990. // Validate arguments
  5991. if (str == NULL || ip == NULL)
  5992. {
  5993. return;
  5994. }
  5995. Copy(&a, ip, sizeof(IP));
  5996. for (i = 0;i < 8;i++)
  5997. {
  5998. Copy(&values[i], &a.ipv6_addr[i * 2], sizeof(USHORT));
  5999. values[i] = Endian16(values[i]);
  6000. }
  6001. // Search for omitable part
  6002. zero_started_index = INFINITE;
  6003. max_zero_len = 0;
  6004. max_zero_start = INFINITE;
  6005. for (i = 0;i < 9;i++)
  6006. {
  6007. USHORT v = (i != 8 ? values[i] : 1);
  6008. if (v == 0)
  6009. {
  6010. if (zero_started_index == INFINITE)
  6011. {
  6012. zero_started_index = i;
  6013. }
  6014. }
  6015. else
  6016. {
  6017. UINT zero_len;
  6018. if (zero_started_index != INFINITE)
  6019. {
  6020. zero_len = i - zero_started_index;
  6021. if (zero_len >= 2)
  6022. {
  6023. if (max_zero_len < zero_len)
  6024. {
  6025. max_zero_start = zero_started_index;
  6026. max_zero_len = zero_len;
  6027. }
  6028. }
  6029. zero_started_index = INFINITE;
  6030. }
  6031. }
  6032. }
  6033. // Format a string
  6034. StrCpy(str, 0, "");
  6035. for (i = 0;i < 8;i++)
  6036. {
  6037. char tmp[16];
  6038. ToHex(tmp, values[i]);
  6039. StrLower(tmp);
  6040. if (i == max_zero_start)
  6041. {
  6042. if (i == 0)
  6043. {
  6044. StrCat(str, 0, "::");
  6045. }
  6046. else
  6047. {
  6048. StrCat(str, 0, ":");
  6049. }
  6050. i += max_zero_len - 1;
  6051. }
  6052. else
  6053. {
  6054. StrCat(str, 0, tmp);
  6055. if (i != 7)
  6056. {
  6057. StrCat(str, 0, ":");
  6058. }
  6059. }
  6060. }
  6061. // Scope ID
  6062. if (ip->ipv6_scope_id != 0)
  6063. {
  6064. char tmp[64];
  6065. StrCat(str, 0, "%");
  6066. ToStr(tmp, ip->ipv6_scope_id);
  6067. StrCat(str, 0, tmp);
  6068. }
  6069. }
  6070. // Convert the string to an IP address
  6071. bool StrToIP6(IP *ip, char *str)
  6072. {
  6073. TOKEN_LIST *t;
  6074. char tmp[MAX_PATH];
  6075. IP a;
  6076. UINT i;
  6077. UINT scope_id = 0;
  6078. // Validate arguments
  6079. if (str == NULL || ip == NULL)
  6080. {
  6081. return false;
  6082. }
  6083. ZeroIP6(&a);
  6084. StrCpy(tmp, sizeof(tmp), str);
  6085. Trim(tmp);
  6086. if (StartWith(tmp, "[") && EndWith(tmp, "]"))
  6087. {
  6088. // If the string is enclosed in square brackets, remove brackets
  6089. StrCpyAllowOverlap(tmp, sizeof(tmp), &tmp[1]);
  6090. if (StrLen(tmp) >= 1)
  6091. {
  6092. tmp[StrLen(tmp) - 1] = 0;
  6093. }
  6094. }
  6095. // Remove the scope ID by analyzing if there is it
  6096. i = SearchStrEx(tmp, "%", 0, false);
  6097. if (i != INFINITE)
  6098. {
  6099. char ss[MAX_PATH];
  6100. StrCpy(ss, sizeof(ss), &tmp[i + 1]);
  6101. tmp[i] = 0;
  6102. Trim(tmp);
  6103. Trim(ss);
  6104. scope_id = ToInt(ss);
  6105. }
  6106. // Tokenize
  6107. t = ParseTokenWithNullStr(tmp, ":");
  6108. if (t->NumTokens >= 3 && t->NumTokens <= 8)
  6109. {
  6110. UINT i, n;
  6111. bool b = true;
  6112. UINT k = 0;
  6113. n = 0;
  6114. for (i = 0;i < t->NumTokens;i++)
  6115. {
  6116. char *str = t->Token[i];
  6117. if (i != 0 && i != (t->NumTokens - 1) && StrLen(str) == 0)
  6118. {
  6119. n++;
  6120. if (n == 1)
  6121. {
  6122. k += 2 * (8 - t->NumTokens + 1);
  6123. }
  6124. else
  6125. {
  6126. b = false;
  6127. break;
  6128. }
  6129. }
  6130. else
  6131. {
  6132. UCHAR chars[2];
  6133. if (CheckIPItemStr6(str) == false)
  6134. {
  6135. b = false;
  6136. break;
  6137. }
  6138. IPItemStrToChars6(chars, str);
  6139. a.ipv6_addr[k++] = chars[0];
  6140. a.ipv6_addr[k++] = chars[1];
  6141. }
  6142. }
  6143. if (n != 0 && n != 1)
  6144. {
  6145. b = false;
  6146. }
  6147. else if (n == 0 && t->NumTokens != 8)
  6148. {
  6149. b = false;
  6150. }
  6151. if (b == false)
  6152. {
  6153. FreeToken(t);
  6154. return false;
  6155. }
  6156. }
  6157. else
  6158. {
  6159. FreeToken(t);
  6160. return false;
  6161. }
  6162. FreeToken(t);
  6163. Copy(ip, &a, sizeof(IP));
  6164. ip->ipv6_scope_id = scope_id;
  6165. return true;
  6166. }
  6167. bool StrToIP6Addr(IPV6_ADDR *ip, char *str)
  6168. {
  6169. IP ip2;
  6170. // Validate arguments
  6171. if (ip == NULL || str == NULL)
  6172. {
  6173. Zero(ip, sizeof(IPV6_ADDR));
  6174. return false;
  6175. }
  6176. if (StrToIP6(&ip2, str) == false)
  6177. {
  6178. return false;
  6179. }
  6180. if (IPToIPv6Addr(ip, &ip2) == false)
  6181. {
  6182. return false;
  6183. }
  6184. return true;
  6185. }
  6186. // Convert an IP address character to the UCHAR type
  6187. void IPItemStrToChars6(UCHAR *chars, char *str)
  6188. {
  6189. char tmp[5];
  6190. BUF *b;
  6191. UINT len;
  6192. // Validate arguments
  6193. if (chars == NULL)
  6194. {
  6195. return;
  6196. }
  6197. Zero(tmp, sizeof(tmp));
  6198. len = StrLen(str);
  6199. switch (len)
  6200. {
  6201. case 0:
  6202. tmp[0] = tmp[1] = tmp[2] = tmp[3] = '0';
  6203. break;
  6204. case 1:
  6205. tmp[0] = tmp[1] = tmp[2] = '0';
  6206. tmp[3] = str[0];
  6207. break;
  6208. case 2:
  6209. tmp[0] = tmp[1] = '0';
  6210. tmp[2] = str[0];
  6211. tmp[3] = str[1];
  6212. break;
  6213. case 3:
  6214. tmp[0] = '0';
  6215. tmp[1] = str[0];
  6216. tmp[2] = str[1];
  6217. tmp[3] = str[2];
  6218. break;
  6219. case 4:
  6220. tmp[0] = str[0];
  6221. tmp[1] = str[1];
  6222. tmp[2] = str[2];
  6223. tmp[3] = str[3];
  6224. break;
  6225. }
  6226. b = StrToBin(tmp);
  6227. chars[0] = ((UCHAR *)b->Buf)[0];
  6228. chars[1] = ((UCHAR *)b->Buf)[1];
  6229. FreeBuf(b);
  6230. }
  6231. // Check whether invalid characters are included in the element string of the IP address
  6232. bool CheckIPItemStr6(char *str)
  6233. {
  6234. UINT i, len;
  6235. // Validate arguments
  6236. if (str == NULL)
  6237. {
  6238. return false;
  6239. }
  6240. len = StrLen(str);
  6241. if (len >= 5)
  6242. {
  6243. // Invalid length
  6244. return false;
  6245. }
  6246. for (i = 0;i < len;i++)
  6247. {
  6248. char c = str[i];
  6249. if ((c >= 'a' && c <= 'f') ||
  6250. (c >= 'A' && c <= 'F') ||
  6251. (c >= '0' && c <= '9'))
  6252. {
  6253. }
  6254. else
  6255. {
  6256. return false;
  6257. }
  6258. }
  6259. return true;
  6260. }
  6261. // Create an IPv4 address of all zero
  6262. void ZeroIP4(IP *ip)
  6263. {
  6264. // Validate arguments
  6265. if (ip == NULL)
  6266. {
  6267. return;
  6268. }
  6269. Zero(ip, sizeof(IP));
  6270. }
  6271. // Create an IPv6 address of all zero
  6272. void ZeroIP6(IP *ip)
  6273. {
  6274. // Validate arguments
  6275. if (ip == NULL)
  6276. {
  6277. return;
  6278. }
  6279. SetIP6(ip, NULL);
  6280. }
  6281. // Get the IP address of the localhost
  6282. void GetLocalHostIP6(IP *ip)
  6283. {
  6284. // Validate arguments
  6285. if (ip == NULL)
  6286. {
  6287. return;
  6288. }
  6289. ZeroIP6(ip);
  6290. ip->ipv6_addr[15] = 1;
  6291. }
  6292. void GetLocalHostIP4(IP *ip)
  6293. {
  6294. // Validate arguments
  6295. if (ip == NULL)
  6296. {
  6297. return;
  6298. }
  6299. SetIP(ip, 127, 0, 0, 1);
  6300. }
  6301. // Check whether the specified address is a localhost
  6302. bool IsLocalHostIP6(IP *ip)
  6303. {
  6304. IP local;
  6305. // Validate arguments
  6306. if (ip == NULL)
  6307. {
  6308. return false;
  6309. }
  6310. if (IsIP6(ip) == false)
  6311. {
  6312. return false;
  6313. }
  6314. GetLocalHostIP6(&local);
  6315. if (CmpIpAddr(&local, ip) == 0)
  6316. {
  6317. return true;
  6318. }
  6319. return false;
  6320. }
  6321. bool IsLocalHostIP4(IP *ip)
  6322. {
  6323. // Validate arguments
  6324. if (ip == NULL)
  6325. {
  6326. return false;
  6327. }
  6328. if (IsIP4(ip) == false)
  6329. {
  6330. return false;
  6331. }
  6332. if (ip->addr[0] == 127)
  6333. {
  6334. return true;
  6335. }
  6336. return false;
  6337. }
  6338. bool IsLocalHostIP(IP *ip)
  6339. {
  6340. // Validate arguments
  6341. if (ip == NULL)
  6342. {
  6343. return false;
  6344. }
  6345. if (IsIP4(ip))
  6346. {
  6347. return IsLocalHostIP4(ip);
  6348. }
  6349. else
  6350. {
  6351. return IsLocalHostIP6(ip);
  6352. }
  6353. }
  6354. // Convert the IPV6_ADDR to an IP
  6355. void IPv6AddrToIP(IP *ip, IPV6_ADDR *addr)
  6356. {
  6357. // Validate arguments
  6358. if (ip == NULL || addr == NULL)
  6359. {
  6360. return;
  6361. }
  6362. SetIP6(ip, addr->Value);
  6363. }
  6364. // Convert the IP to an IPV6_ADDR
  6365. bool IPToIPv6Addr(IPV6_ADDR *addr, IP *ip)
  6366. {
  6367. UINT i;
  6368. // Validate arguments
  6369. if (addr == NULL || ip == NULL)
  6370. {
  6371. Zero(addr, sizeof(IPV6_ADDR));
  6372. return false;
  6373. }
  6374. if (IsIP6(ip) == false)
  6375. {
  6376. Zero(addr, sizeof(IPV6_ADDR));
  6377. return false;
  6378. }
  6379. for (i = 0;i < 16;i++)
  6380. {
  6381. addr->Value[i] = ip->ipv6_addr[i];
  6382. }
  6383. return true;
  6384. }
  6385. // Set an IPv6 address
  6386. void SetIP6(IP *ip, UCHAR *value)
  6387. {
  6388. // Validate arguments
  6389. if (ip == NULL)
  6390. {
  6391. return;
  6392. }
  6393. Zero(ip, sizeof(IP));
  6394. ip->addr[0] = 223;
  6395. ip->addr[1] = 255;
  6396. ip->addr[2] = 255;
  6397. ip->addr[3] = 254;
  6398. if (value != NULL)
  6399. {
  6400. UINT i;
  6401. for (i = 0;i < 16;i++)
  6402. {
  6403. ip->ipv6_addr[i] = value[i];
  6404. }
  6405. }
  6406. }
  6407. // Check whether the specified address is a IPv6 address
  6408. bool IsIP6(IP *ip)
  6409. {
  6410. // Validate arguments
  6411. if (ip == NULL)
  6412. {
  6413. return false;
  6414. }
  6415. if (ip->addr[0] == 223 && ip->addr[1] == 255 && ip->addr[2] == 255 && ip->addr[3] == 254)
  6416. {
  6417. return true;
  6418. }
  6419. return false;
  6420. }
  6421. bool IsIP4(IP *ip)
  6422. {
  6423. // Validate arguments
  6424. if (ip == NULL)
  6425. {
  6426. return false;
  6427. }
  6428. return (IsIP6(ip) ? false : true);
  6429. }
  6430. // Examine whether the version of the two IP addresses are same
  6431. bool IsSameIPVer(IP *ip1, IP *ip2)
  6432. {
  6433. // Validate arguments
  6434. if (ip1 == NULL || ip2 == NULL)
  6435. {
  6436. return false;
  6437. }
  6438. if (IsIP4(ip1) && IsIP4(ip2))
  6439. {
  6440. return true;
  6441. }
  6442. if (IsIP6(ip1) && IsIP6(ip2))
  6443. {
  6444. return true;
  6445. }
  6446. return false;
  6447. }
  6448. // Copy the IP address
  6449. void CopyIP(IP *dst, IP *src)
  6450. {
  6451. Copy(dst, src, sizeof(IP));
  6452. }
  6453. // Check the length of the IPv6 subnet
  6454. bool CheckSubnetLength6(UINT i)
  6455. {
  6456. if (i >= 1 && i <= 127)
  6457. {
  6458. return true;
  6459. }
  6460. return false;
  6461. }
  6462. // Get the process ID of the corresponding TCP connection by the socket
  6463. UINT GetTcpProcessIdFromSocket(SOCK *s)
  6464. {
  6465. LIST *o;
  6466. TCPTABLE *t;
  6467. UINT pid = 0;
  6468. // Validate arguments
  6469. if (s == NULL)
  6470. {
  6471. return 0;
  6472. }
  6473. o = GetTcpTableList();
  6474. if (o == NULL)
  6475. {
  6476. return 0;
  6477. }
  6478. t = GetTcpTableFromEndPoint(o, &s->LocalIP, s->LocalPort,
  6479. &s->RemoteIP, s->RemotePort);
  6480. if (t != NULL)
  6481. {
  6482. pid = t->ProcessId;
  6483. }
  6484. FreeTcpTableList(o);
  6485. return pid;
  6486. }
  6487. UINT GetTcpProcessIdFromSocketReverse(SOCK *s)
  6488. {
  6489. LIST *o;
  6490. TCPTABLE *t;
  6491. UINT pid = 0;
  6492. // Validate arguments
  6493. if (s == NULL)
  6494. {
  6495. return 0;
  6496. }
  6497. o = GetTcpTableList();
  6498. if (o == NULL)
  6499. {
  6500. return 0;
  6501. }
  6502. t = GetTcpTableFromEndPoint(o, &s->RemoteIP, s->RemotePort,
  6503. &s->LocalIP, s->LocalPort);
  6504. if (t != NULL)
  6505. {
  6506. pid = t->ProcessId;
  6507. }
  6508. FreeTcpTableList(o);
  6509. return pid;
  6510. }
  6511. // Search in the TCP table by the end point
  6512. TCPTABLE *GetTcpTableFromEndPoint(LIST *o, IP *local_ip, UINT local_port, IP *remote_ip, UINT remote_port)
  6513. {
  6514. IP local;
  6515. UINT i;
  6516. // Validate arguments
  6517. if (o == NULL)
  6518. {
  6519. return NULL;
  6520. }
  6521. SetIP(&local, 127, 0, 0, 1);
  6522. if (local_ip == NULL)
  6523. {
  6524. local_ip = &local;
  6525. }
  6526. if (remote_ip == NULL)
  6527. {
  6528. remote_ip = &local;
  6529. }
  6530. for (i = 0;i < LIST_NUM(o);i++)
  6531. {
  6532. TCPTABLE *t = LIST_DATA(o, i);
  6533. if (t->Status == TCP_STATE_SYN_SENT || t->Status == TCP_STATE_SYN_RCVD ||
  6534. t->Status == TCP_STATE_ESTAB)
  6535. {
  6536. if (CmpIpAddr(&t->LocalIP, local_ip) == 0)
  6537. {
  6538. if (CmpIpAddr(&t->RemoteIP, remote_ip) == 0)
  6539. {
  6540. if (t->LocalPort == local_port)
  6541. {
  6542. if (t->RemotePort == remote_port)
  6543. {
  6544. return t;
  6545. }
  6546. }
  6547. }
  6548. }
  6549. }
  6550. }
  6551. return NULL;
  6552. }
  6553. // Get the TCP table list (Win32)
  6554. #ifdef OS_WIN32
  6555. LIST *Win32GetTcpTableList()
  6556. {
  6557. LIST *o;
  6558. // Windows XP SP2 or later
  6559. o = Win32GetTcpTableListByGetExtendedTcpTable();
  6560. if (o != NULL)
  6561. {
  6562. return o;
  6563. }
  6564. // Windows XP or later
  6565. o = Win32GetTcpTableListByAllocateAndGetTcpExTableFromStack();
  6566. if (o != NULL)
  6567. {
  6568. return o;
  6569. }
  6570. // For legacy Windows
  6571. return Win32GetTcpTableListByGetTcpTable();
  6572. }
  6573. // Get the TCP table list (for Windows XP SP2 or later)
  6574. LIST *Win32GetTcpTableListByGetExtendedTcpTable()
  6575. {
  6576. UINT need_size;
  6577. UINT i;
  6578. MIB_TCPTABLE_OWNER_PID *table;
  6579. bool ok = false;
  6580. LIST *o;
  6581. if (w32net->GetExtendedTcpTable == NULL)
  6582. {
  6583. return NULL;
  6584. }
  6585. for (i = 0;i < 128;i++)
  6586. {
  6587. UINT ret;
  6588. table = MallocFast(sizeof(MIB_TCPTABLE_OWNER_PID));
  6589. need_size = sizeof(MIB_TCPTABLE_OWNER_PID);
  6590. ret = w32net->GetExtendedTcpTable(table, &need_size, true, AF_INET, _TCP_TABLE_OWNER_PID_ALL, 0);
  6591. if (ret == NO_ERROR)
  6592. {
  6593. ok = true;
  6594. break;
  6595. }
  6596. else
  6597. {
  6598. Free(table);
  6599. if (ret != ERROR_INSUFFICIENT_BUFFER)
  6600. {
  6601. return NULL;
  6602. }
  6603. }
  6604. table = MallocFast(need_size);
  6605. ret = w32net->GetExtendedTcpTable(table, &need_size, true, AF_INET, _TCP_TABLE_OWNER_PID_ALL, 0);
  6606. if (ret == NO_ERROR)
  6607. {
  6608. ok = true;
  6609. break;
  6610. }
  6611. else
  6612. {
  6613. Free(table);
  6614. if (ret != ERROR_INSUFFICIENT_BUFFER)
  6615. {
  6616. return NULL;
  6617. }
  6618. }
  6619. }
  6620. if (ok == false)
  6621. {
  6622. return NULL;
  6623. }
  6624. o = NewListEx(NULL, true);
  6625. for (i = 0;i < table->dwNumEntries;i++)
  6626. {
  6627. MIB_TCPROW_OWNER_PID *r = &table->table[i];
  6628. TCPTABLE *t = ZeroMallocFast(sizeof(TCPTABLE));
  6629. UINTToIP(&t->LocalIP, r->dwLocalAddr);
  6630. t->LocalPort = Endian16((USHORT)r->dwLocalPort);
  6631. if (r->dwState != TCP_STATE_LISTEN)
  6632. {
  6633. UINTToIP(&t->RemoteIP, r->dwRemoteAddr);
  6634. t->RemotePort = Endian16((USHORT)r->dwRemotePort);
  6635. }
  6636. t->Status = r->dwState;
  6637. t->ProcessId = r->dwOwningPid;
  6638. Add(o, t);
  6639. }
  6640. Free(table);
  6641. return o;
  6642. }
  6643. // Get the TCP table list (Windows XP or later)
  6644. LIST *Win32GetTcpTableListByAllocateAndGetTcpExTableFromStack()
  6645. {
  6646. HANDLE heap;
  6647. UINT i;
  6648. MIB_TCPTABLE_OWNER_PID *table;
  6649. bool ok = false;
  6650. LIST *o;
  6651. if (w32net->AllocateAndGetTcpExTableFromStack == NULL)
  6652. {
  6653. return NULL;
  6654. }
  6655. heap = GetProcessHeap();
  6656. if (w32net->AllocateAndGetTcpExTableFromStack(&table, true, heap, HEAP_GROWABLE, AF_INET) != ERROR_SUCCESS)
  6657. {
  6658. return NULL;
  6659. }
  6660. o = NewListEx(NULL, true);
  6661. for (i = 0;i < table->dwNumEntries;i++)
  6662. {
  6663. MIB_TCPROW_OWNER_PID *r = &table->table[i];
  6664. TCPTABLE *t = ZeroMallocFast(sizeof(TCPTABLE));
  6665. UINTToIP(&t->LocalIP, r->dwLocalAddr);
  6666. t->LocalPort = Endian16((USHORT)r->dwLocalPort);
  6667. if (r->dwState != TCP_STATE_LISTEN)
  6668. {
  6669. UINTToIP(&t->RemoteIP, r->dwRemoteAddr);
  6670. t->RemotePort = Endian16((USHORT)r->dwRemotePort);
  6671. }
  6672. t->ProcessId = r->dwOwningPid;
  6673. t->Status = r->dwState;
  6674. Add(o, t);
  6675. }
  6676. HeapFree(heap, 0, table);
  6677. return o;
  6678. }
  6679. // Get the TCP table list (For legacy Windows)
  6680. LIST *Win32GetTcpTableListByGetTcpTable()
  6681. {
  6682. UINT need_size;
  6683. UINT i;
  6684. MIB_TCPTABLE *table;
  6685. bool ok = false;
  6686. LIST *o;
  6687. if (w32net->GetTcpTable == NULL)
  6688. {
  6689. return NULL;
  6690. }
  6691. for (i = 0;i < 128;i++)
  6692. {
  6693. UINT ret;
  6694. table = MallocFast(sizeof(MIB_TCPTABLE));
  6695. need_size = sizeof(MIB_TCPTABLE);
  6696. ret = w32net->GetTcpTable(table, &need_size, true);
  6697. if (ret == NO_ERROR)
  6698. {
  6699. ok = true;
  6700. break;
  6701. }
  6702. else
  6703. {
  6704. Free(table);
  6705. if (ret != ERROR_INSUFFICIENT_BUFFER)
  6706. {
  6707. return NULL;
  6708. }
  6709. }
  6710. table = MallocFast(need_size);
  6711. ret = w32net->GetTcpTable(table, &need_size, true);
  6712. if (ret == NO_ERROR)
  6713. {
  6714. ok = true;
  6715. break;
  6716. }
  6717. else
  6718. {
  6719. Free(table);
  6720. if (ret != ERROR_INSUFFICIENT_BUFFER)
  6721. {
  6722. return NULL;
  6723. }
  6724. }
  6725. }
  6726. if (ok == false)
  6727. {
  6728. return NULL;
  6729. }
  6730. o = NewListEx(NULL, true);
  6731. for (i = 0;i < table->dwNumEntries;i++)
  6732. {
  6733. MIB_TCPROW *r = &table->table[i];
  6734. TCPTABLE *t = ZeroMallocFast(sizeof(TCPTABLE));
  6735. UINTToIP(&t->LocalIP, r->dwLocalAddr);
  6736. t->LocalPort = Endian16((USHORT)r->dwLocalPort);
  6737. if (r->dwState != TCP_STATE_LISTEN)
  6738. {
  6739. UINTToIP(&t->RemoteIP, r->dwRemoteAddr);
  6740. t->RemotePort = Endian16((USHORT)r->dwRemotePort);
  6741. }
  6742. t->Status = r->dwState;
  6743. Add(o, t);
  6744. }
  6745. Free(table);
  6746. return o;
  6747. }
  6748. #endif // OS_WIN32
  6749. // Display the TCP table
  6750. void PrintTcpTableList(LIST *o)
  6751. {
  6752. UINT i;
  6753. // Validate arguments
  6754. if (o == NULL)
  6755. {
  6756. Print("o == NULL\n\n");
  6757. return;
  6758. }
  6759. Print("--- TCPTABLE: %u Entries ---\n", LIST_NUM(o));
  6760. for (i = 0;i < LIST_NUM(o);i++)
  6761. {
  6762. char tmp1[MAX_PATH], tmp2[MAX_PATH];
  6763. TCPTABLE *t = LIST_DATA(o, i);
  6764. IPToStr(tmp1, sizeof(tmp1), &t->LocalIP);
  6765. IPToStr(tmp2, sizeof(tmp2), &t->RemoteIP);
  6766. Print("%s:%u <--> %s:%u state=%u pid=%u\n",
  6767. tmp1, t->LocalPort,
  6768. tmp2, t->RemotePort,
  6769. t->Status,
  6770. t->ProcessId);
  6771. }
  6772. Print("------\n\n");
  6773. }
  6774. // Comparison of TCP table items
  6775. int CompareTcpTable(void *p1, void *p2)
  6776. {
  6777. TCPTABLE *t1, *t2;
  6778. if (p1 == NULL || p2 == NULL)
  6779. {
  6780. return 0;
  6781. }
  6782. t1 = *(TCPTABLE **)p1;
  6783. t2 = *(TCPTABLE **)p2;
  6784. if (t1 == NULL || t2 == NULL)
  6785. {
  6786. return 0;
  6787. }
  6788. return Cmp(t1, t2, sizeof(TCPTABLE));
  6789. }
  6790. // Get the TCP table list
  6791. LIST *GetTcpTableList()
  6792. {
  6793. #ifdef OS_WIN32
  6794. return Win32GetTcpTableList();
  6795. #else // OS_WIN32
  6796. return NULL;
  6797. #endif // OS_WIN32
  6798. }
  6799. // Release the TCP table list
  6800. void FreeTcpTableList(LIST *o)
  6801. {
  6802. UINT i;
  6803. // Validate arguments
  6804. if (o == NULL)
  6805. {
  6806. return;
  6807. }
  6808. for (i = 0;i < LIST_NUM(o);i++)
  6809. {
  6810. TCPTABLE *t = LIST_DATA(o, i);
  6811. Free(t);
  6812. }
  6813. ReleaseList(o);
  6814. }
  6815. // Get the number of clients connected from the specified IP address
  6816. UINT GetNumIpClient(IP *ip)
  6817. {
  6818. IP_CLIENT *c;
  6819. UINT ret = 0;
  6820. // Validate arguments
  6821. if (ip == NULL)
  6822. {
  6823. return 0;
  6824. }
  6825. LockList(ip_clients);
  6826. {
  6827. c = SearchIpClient(ip);
  6828. if (c != NULL)
  6829. {
  6830. ret = c->NumConnections;
  6831. }
  6832. }
  6833. UnlockList(ip_clients);
  6834. return ret;
  6835. }
  6836. // Add to the IP client entry
  6837. void AddIpClient(IP *ip)
  6838. {
  6839. IP_CLIENT *c;
  6840. // Validate arguments
  6841. if (ip == NULL)
  6842. {
  6843. return;
  6844. }
  6845. LockList(ip_clients);
  6846. {
  6847. c = SearchIpClient(ip);
  6848. if (c == NULL)
  6849. {
  6850. c = ZeroMallocFast(sizeof(IP_CLIENT));
  6851. Copy(&c->IpAddress, ip, sizeof(IP));
  6852. c->NumConnections = 0;
  6853. Add(ip_clients, c);
  6854. }
  6855. c->NumConnections++;
  6856. }
  6857. UnlockList(ip_clients);
  6858. //Debug("AddIpClient: %r\n", ip);
  6859. }
  6860. // Remove from the IP client list
  6861. void DelIpClient(IP *ip)
  6862. {
  6863. IP_CLIENT *c;
  6864. // Validate arguments
  6865. if (ip == NULL)
  6866. {
  6867. return;
  6868. }
  6869. LockList(ip_clients);
  6870. {
  6871. c = SearchIpClient(ip);
  6872. if (c != NULL)
  6873. {
  6874. c->NumConnections--;
  6875. if (c->NumConnections == 0)
  6876. {
  6877. Delete(ip_clients, c);
  6878. Free(c);
  6879. }
  6880. }
  6881. }
  6882. UnlockList(ip_clients);
  6883. //Debug("DelIpClient: %r\n", ip);
  6884. }
  6885. // Search for the IP client entry
  6886. IP_CLIENT *SearchIpClient(IP *ip)
  6887. {
  6888. IP_CLIENT t;
  6889. // Validate arguments
  6890. if (ip == NULL)
  6891. {
  6892. return NULL;
  6893. }
  6894. Zero(&t, sizeof(t));
  6895. Copy(&t.IpAddress, ip, sizeof(IP));
  6896. return Search(ip_clients, &t);
  6897. }
  6898. // Initialization of the client list
  6899. void InitIpClientList()
  6900. {
  6901. ip_clients = NewList(CompareIpClientList);
  6902. }
  6903. // Release of the client list
  6904. void FreeIpClientList()
  6905. {
  6906. UINT i;
  6907. for (i = 0;i < LIST_NUM(ip_clients);i++)
  6908. {
  6909. IP_CLIENT *c = LIST_DATA(ip_clients, i);
  6910. Free(c);
  6911. }
  6912. ReleaseList(ip_clients);
  6913. ip_clients = NULL;
  6914. }
  6915. // Comparison of the client list entries
  6916. int CompareIpClientList(void *p1, void *p2)
  6917. {
  6918. IP_CLIENT *c1, *c2;
  6919. if (p1 == NULL || p2 == NULL)
  6920. {
  6921. return 0;
  6922. }
  6923. c1 = *(IP_CLIENT **)p1;
  6924. c2 = *(IP_CLIENT **)p2;
  6925. if (c1 == NULL || c2 == NULL)
  6926. {
  6927. return 0;
  6928. }
  6929. return CmpIpAddr(&c1->IpAddress, &c2->IpAddress);
  6930. }
  6931. // Normalization of the MAC address
  6932. bool NormalizeMacAddress(char *dst, UINT size, char *src)
  6933. {
  6934. BUF *b;
  6935. bool ret = false;
  6936. // Validate arguments
  6937. if (dst == NULL || src == NULL)
  6938. {
  6939. return false;
  6940. }
  6941. b = StrToBin(src);
  6942. if (b != NULL && b->Size == 6)
  6943. {
  6944. ret = true;
  6945. BinToStr(dst, size, b->Buf, b->Size);
  6946. }
  6947. FreeBuf(b);
  6948. return ret;
  6949. }
  6950. // Identify whether the IP address is empty
  6951. bool IsZeroIP(IP *ip)
  6952. {
  6953. return IsZeroIp(ip);
  6954. }
  6955. bool IsZeroIp(IP *ip)
  6956. {
  6957. // Validate arguments
  6958. if (ip == NULL)
  6959. {
  6960. return true;
  6961. }
  6962. if (IsIP6(ip) == false)
  6963. {
  6964. return IsZero(ip->addr, sizeof(ip->addr));
  6965. }
  6966. else
  6967. {
  6968. return IsZero(ip->ipv6_addr, sizeof(ip->ipv6_addr));
  6969. }
  6970. }
  6971. bool IsZeroIP6Addr(IPV6_ADDR *addr)
  6972. {
  6973. // Validate arguments
  6974. if (addr == NULL)
  6975. {
  6976. return true;
  6977. }
  6978. return IsZero(addr, sizeof(IPV6_ADDR));
  6979. }
  6980. // Examine whether the specified IP address is meaningful as a host
  6981. bool IsHostIPAddress4(IP *ip)
  6982. {
  6983. UINT a;
  6984. // Validate arguments
  6985. if (ip == NULL)
  6986. {
  6987. return false;
  6988. }
  6989. a = IPToUINT(ip);
  6990. if (a == 0 || a == 0xffffffff)
  6991. {
  6992. return false;
  6993. }
  6994. return true;
  6995. }
  6996. bool IsHostIPAddress32(UINT ip)
  6997. {
  6998. IP p;
  6999. UINTToIP(&p, ip);
  7000. return IsHostIPAddress4(&p);
  7001. }
  7002. // Check whether the specified IP address and subnet mask indicates a network correctly
  7003. bool IsNetworkAddress(IP *ip, IP *mask)
  7004. {
  7005. if (IsIP4(ip))
  7006. {
  7007. return IsNetworkAddress4(ip, mask);
  7008. }
  7009. else
  7010. {
  7011. return IsNetworkAddress6(ip, mask);
  7012. }
  7013. }
  7014. bool IsNetworkAddress4(IP *ip, IP *mask)
  7015. {
  7016. UINT a, b;
  7017. // Validate arguments
  7018. if (ip == NULL || mask == NULL)
  7019. {
  7020. return false;
  7021. }
  7022. if (IsIP4(ip) == false || IsIP4(mask) == false)
  7023. {
  7024. return false;
  7025. }
  7026. if (IsSubnetMask4(mask) == false)
  7027. {
  7028. return false;
  7029. }
  7030. a = IPToUINT(ip);
  7031. b = IPToUINT(mask);
  7032. if ((a & b) == a)
  7033. {
  7034. return true;
  7035. }
  7036. return false;
  7037. }
  7038. bool IsNetworkAddress32(UINT ip, UINT mask)
  7039. {
  7040. IP a, b;
  7041. UINTToIP(&a, ip);
  7042. UINTToIP(&b, mask);
  7043. return IsNetworkAddress4(&a, &b);
  7044. }
  7045. // Convert the integer to a subnet mask
  7046. UINT IntToSubnetMask32(UINT i)
  7047. {
  7048. UINT ret = 0xFFFFFFFF;
  7049. switch (i)
  7050. {
  7051. case 0: ret = 0x00000000; break;
  7052. case 1: ret = 0x80000000; break;
  7053. case 2: ret = 0xC0000000; break;
  7054. case 3: ret = 0xE0000000; break;
  7055. case 4: ret = 0xF0000000; break;
  7056. case 5: ret = 0xF8000000; break;
  7057. case 6: ret = 0xFC000000; break;
  7058. case 7: ret = 0xFE000000; break;
  7059. case 8: ret = 0xFF000000; break;
  7060. case 9: ret = 0xFF800000; break;
  7061. case 10: ret = 0xFFC00000; break;
  7062. case 11: ret = 0xFFE00000; break;
  7063. case 12: ret = 0xFFF00000; break;
  7064. case 13: ret = 0xFFF80000; break;
  7065. case 14: ret = 0xFFFC0000; break;
  7066. case 15: ret = 0xFFFE0000; break;
  7067. case 16: ret = 0xFFFF0000; break;
  7068. case 17: ret = 0xFFFF8000; break;
  7069. case 18: ret = 0xFFFFC000; break;
  7070. case 19: ret = 0xFFFFE000; break;
  7071. case 20: ret = 0xFFFFF000; break;
  7072. case 21: ret = 0xFFFFF800; break;
  7073. case 22: ret = 0xFFFFFC00; break;
  7074. case 23: ret = 0xFFFFFE00; break;
  7075. case 24: ret = 0xFFFFFF00; break;
  7076. case 25: ret = 0xFFFFFF80; break;
  7077. case 26: ret = 0xFFFFFFC0; break;
  7078. case 27: ret = 0xFFFFFFE0; break;
  7079. case 28: ret = 0xFFFFFFF0; break;
  7080. case 29: ret = 0xFFFFFFF8; break;
  7081. case 30: ret = 0xFFFFFFFC; break;
  7082. case 31: ret = 0xFFFFFFFE; break;
  7083. case 32: ret = 0xFFFFFFFF; break;
  7084. }
  7085. if (IsLittleEndian())
  7086. {
  7087. ret = Swap32(ret);
  7088. }
  7089. return ret;
  7090. }
  7091. void IntToSubnetMask4(IP *ip, UINT i)
  7092. {
  7093. UINT m;
  7094. // Validate arguments
  7095. if (ip == NULL)
  7096. {
  7097. return;
  7098. }
  7099. m = IntToSubnetMask32(i);
  7100. UINTToIP(ip, m);
  7101. }
  7102. // Examine whether the specified IP address is a subnet mask
  7103. bool IsSubnetMask(IP *ip)
  7104. {
  7105. if (IsIP6(ip))
  7106. {
  7107. return IsSubnetMask6(ip);
  7108. }
  7109. else
  7110. {
  7111. return IsSubnetMask4(ip);
  7112. }
  7113. }
  7114. bool IsSubnetMask4(IP *ip)
  7115. {
  7116. UINT i;
  7117. // Validate arguments
  7118. if (ip == NULL)
  7119. {
  7120. return false;
  7121. }
  7122. if (IsIP6(ip))
  7123. {
  7124. return false;
  7125. }
  7126. i = IPToUINT(ip);
  7127. if (IsLittleEndian())
  7128. {
  7129. i = Swap32(i);
  7130. }
  7131. switch (i)
  7132. {
  7133. case 0x00000000:
  7134. case 0x80000000:
  7135. case 0xC0000000:
  7136. case 0xE0000000:
  7137. case 0xF0000000:
  7138. case 0xF8000000:
  7139. case 0xFC000000:
  7140. case 0xFE000000:
  7141. case 0xFF000000:
  7142. case 0xFF800000:
  7143. case 0xFFC00000:
  7144. case 0xFFE00000:
  7145. case 0xFFF00000:
  7146. case 0xFFF80000:
  7147. case 0xFFFC0000:
  7148. case 0xFFFE0000:
  7149. case 0xFFFF0000:
  7150. case 0xFFFF8000:
  7151. case 0xFFFFC000:
  7152. case 0xFFFFE000:
  7153. case 0xFFFFF000:
  7154. case 0xFFFFF800:
  7155. case 0xFFFFFC00:
  7156. case 0xFFFFFE00:
  7157. case 0xFFFFFF00:
  7158. case 0xFFFFFF80:
  7159. case 0xFFFFFFC0:
  7160. case 0xFFFFFFE0:
  7161. case 0xFFFFFFF0:
  7162. case 0xFFFFFFF8:
  7163. case 0xFFFFFFFC:
  7164. case 0xFFFFFFFE:
  7165. case 0xFFFFFFFF:
  7166. return true;
  7167. }
  7168. return false;
  7169. }
  7170. bool IsSubnetMask32(UINT ip)
  7171. {
  7172. IP p;
  7173. UINTToIP(&p, ip);
  7174. return IsSubnetMask4(&p);
  7175. }
  7176. // Network release mode
  7177. void SetNetworkReleaseMode()
  7178. {
  7179. NetworkReleaseMode = true;
  7180. }
  7181. #ifdef OS_UNIX // Code for UNIX
  7182. // Turn on and off the non-blocking mode of the socket
  7183. void UnixSetSocketNonBlockingMode(int fd, bool nonblock)
  7184. {
  7185. UINT flag = 0;
  7186. // Validate arguments
  7187. if (fd == INVALID_SOCKET)
  7188. {
  7189. return;
  7190. }
  7191. if (nonblock)
  7192. {
  7193. flag = 1;
  7194. }
  7195. #ifdef FIONBIO
  7196. ioctl(fd, FIONBIO, &flag);
  7197. #else // FIONBIO
  7198. {
  7199. int flag = fcntl(fd, F_GETFL, 0);
  7200. if (flag != -1)
  7201. {
  7202. if (nonblock)
  7203. {
  7204. flag |= O_NONBLOCK;
  7205. }
  7206. else
  7207. {
  7208. flag = flag & ~O_NONBLOCK;
  7209. fcntl(fd, F_SETFL, flag);
  7210. }
  7211. }
  7212. }
  7213. #endif // FIONBIO
  7214. }
  7215. // Do Nothing
  7216. void UnixIpForwardRowToRouteEntry(ROUTE_ENTRY *entry, void *ip_forward_row)
  7217. {
  7218. }
  7219. // Do Nothing
  7220. void UnixRouteEntryToIpForwardRow(void *ip_forward_row, ROUTE_ENTRY *entry)
  7221. {
  7222. }
  7223. // Do Nothing
  7224. int UnixCompareRouteEntryByMetric(void *p1, void *p2)
  7225. {
  7226. return 1;
  7227. }
  7228. // Do Nothing
  7229. ROUTE_TABLE *UnixGetRouteTable()
  7230. {
  7231. ROUTE_TABLE *ret = ZeroMalloc(sizeof(ROUTE_TABLE));
  7232. ret->NumEntry = 0;
  7233. ret->Entry = ZeroMalloc(0);
  7234. return ret;
  7235. }
  7236. // Do Nothing
  7237. bool UnixAddRouteEntry(ROUTE_ENTRY *e, bool *already_exists)
  7238. {
  7239. return true;
  7240. }
  7241. // Do Nothing
  7242. void UnixDeleteRouteEntry(ROUTE_ENTRY *e)
  7243. {
  7244. return;
  7245. }
  7246. // Do Nothing
  7247. UINT UnixGetVLanInterfaceID(char *instance_name)
  7248. {
  7249. return 1;
  7250. }
  7251. // Do Nothing
  7252. char **UnixEnumVLan(char *tag_name)
  7253. {
  7254. char **list;
  7255. list = ZeroMalloc(sizeof(char *));
  7256. return list;
  7257. }
  7258. // Do Nothing
  7259. void UnixRenewDhcp()
  7260. {
  7261. }
  7262. // Get the IP address of the default DNS server
  7263. bool UnixGetDefaultDns(IP *ip)
  7264. {
  7265. BUF *b;
  7266. // Validate arguments
  7267. if (ip == NULL)
  7268. {
  7269. return false;
  7270. }
  7271. Lock(unix_dns_server_addr_lock);
  7272. {
  7273. if (IsZero(&unix_dns_server, sizeof(IP)) == false)
  7274. {
  7275. Copy(ip, &unix_dns_server, sizeof(IP));
  7276. Unlock(unix_dns_server_addr_lock);
  7277. return true;
  7278. }
  7279. ip->addr[0] = 127;
  7280. ip->addr[1] = 0;
  7281. ip->addr[2] = 0;
  7282. ip->addr[3] = 1;
  7283. b = ReadDump("/etc/resolv.conf");
  7284. if (b != NULL)
  7285. {
  7286. char *s;
  7287. bool f = false;
  7288. while ((s = CfgReadNextLine(b)) != NULL)
  7289. {
  7290. TOKEN_LIST *t = ParseToken(s, "\" \t,");
  7291. if (t->NumTokens == 2)
  7292. {
  7293. if (StrCmpi(t->Token[0], "nameserver") == 0)
  7294. {
  7295. StrToIP(ip, t->Token[1]);
  7296. f = true;
  7297. }
  7298. }
  7299. FreeToken(t);
  7300. Free(s);
  7301. if (f)
  7302. {
  7303. break;
  7304. }
  7305. }
  7306. FreeBuf(b);
  7307. }
  7308. Copy(&unix_dns_server, ip, sizeof(IP));
  7309. }
  7310. Unlock(unix_dns_server_addr_lock);
  7311. return true;
  7312. }
  7313. // Select procedure
  7314. void UnixSelect(SOCKSET *set, UINT timeout, CANCEL *c1, CANCEL *c2)
  7315. {
  7316. UINT reads[MAXIMUM_WAIT_OBJECTS];
  7317. UINT writes[MAXIMUM_WAIT_OBJECTS];
  7318. UINT num_read, num_write, i;
  7319. UINT p1, p2;
  7320. SOCK_EVENT *sock_events[MAXIMUM_WAIT_OBJECTS];
  7321. UINT num_sock_events;
  7322. SOCK *s;
  7323. UCHAR tmp[MAX_SIZE];
  7324. int ret;
  7325. bool any_of_tubes_are_readable = false;
  7326. // Initialization of array
  7327. Zero(reads, sizeof(reads));
  7328. Zero(writes, sizeof(writes));
  7329. Zero(sock_events, sizeof(sock_events));
  7330. num_read = num_write = num_sock_events = 0;
  7331. // Setting the event array
  7332. if (set != NULL)
  7333. {
  7334. for (i = 0;i < set->NumSocket;i++)
  7335. {
  7336. s = set->Sock[i];
  7337. if (s != NULL)
  7338. {
  7339. UnixInitAsyncSocket(s);
  7340. if (s->Type == SOCK_INPROC)
  7341. {
  7342. TUBE *t = s->RecvTube;
  7343. if (t != NULL)
  7344. {
  7345. reads[num_read++] = t->SockEvent->pipe_read;
  7346. sock_events[num_sock_events++] = t->SockEvent;
  7347. if (t->SockEvent->current_pipe_data != 0)
  7348. {
  7349. any_of_tubes_are_readable = true;
  7350. }
  7351. }
  7352. }
  7353. else
  7354. {
  7355. if (s->NoNeedToRead == false)
  7356. {
  7357. reads[num_read++] = s->socket;
  7358. }
  7359. }
  7360. if (s->BulkRecvTube != NULL)
  7361. {
  7362. TUBE *t = s->BulkRecvTube;
  7363. if (t != NULL)
  7364. {
  7365. reads[num_read++] = t->SockEvent->pipe_read;
  7366. sock_events[num_sock_events++] = t->SockEvent;
  7367. if (t->SockEvent->current_pipe_data != 0)
  7368. {
  7369. any_of_tubes_are_readable = true;
  7370. }
  7371. }
  7372. }
  7373. if (s->WriteBlocked)
  7374. {
  7375. writes[num_write++] = s->socket;
  7376. }
  7377. }
  7378. }
  7379. }
  7380. if (timeout == 0)
  7381. {
  7382. return;
  7383. }
  7384. p1 = p2 = -1;
  7385. if (c1 != NULL)
  7386. {
  7387. reads[num_read++] = p1 = c1->pipe_read;
  7388. if (c1->SpecialFlag)
  7389. {
  7390. if (c1->pipe_special_read2 != -1 && c1->pipe_special_read2 != 0)
  7391. {
  7392. reads[num_read++] = c1->pipe_special_read2;
  7393. }
  7394. if (c1->pipe_special_read3 != -1 && c1->pipe_special_read3 != 0)
  7395. {
  7396. reads[num_read++] = c1->pipe_special_read3;
  7397. }
  7398. }
  7399. }
  7400. if (c2 != NULL)
  7401. {
  7402. reads[num_read++] = p2 = c2->pipe_read;
  7403. if (c2->SpecialFlag)
  7404. {
  7405. if (c2->pipe_special_read2 != -1 && c2->pipe_special_read2 != 0)
  7406. {
  7407. reads[num_read++] = c2->pipe_special_read2;
  7408. }
  7409. if (c2->pipe_special_read3 != -1 && c2->pipe_special_read3 != 0)
  7410. {
  7411. reads[num_read++] = c2->pipe_special_read3;
  7412. }
  7413. }
  7414. }
  7415. // Call the select
  7416. if (any_of_tubes_are_readable == false)
  7417. {
  7418. UnixSelectInner(num_read, reads, num_write, writes, timeout);
  7419. }
  7420. // Read from the pipe
  7421. if (c1 != NULL && c1->SpecialFlag == false && p1 != -1)
  7422. {
  7423. do
  7424. {
  7425. ret = read(p1, tmp, sizeof(tmp));
  7426. }
  7427. while (ret >= 1);
  7428. }
  7429. if (c2 != NULL && c2->SpecialFlag == false && p2 != -1)
  7430. {
  7431. do
  7432. {
  7433. ret = read(p2, tmp, sizeof(tmp));
  7434. }
  7435. while (ret >= 1);
  7436. }
  7437. // Read from the pipe of sockevent
  7438. for (i = 0;i < num_sock_events;i++)
  7439. {
  7440. SOCK_EVENT *e = sock_events[i];
  7441. e->current_pipe_data = 0;
  7442. do
  7443. {
  7444. ret = read(e->pipe_read, tmp, sizeof(tmp));
  7445. }
  7446. while (ret >= 1);
  7447. }
  7448. }
  7449. // Cancel
  7450. void UnixCancel(CANCEL *c)
  7451. {
  7452. // Validate arguments
  7453. if (c == NULL)
  7454. {
  7455. return;
  7456. }
  7457. UnixWritePipe(c->pipe_write);
  7458. }
  7459. // Release of the cancel object
  7460. void UnixCleanupCancel(CANCEL *c)
  7461. {
  7462. // Validate arguments
  7463. if (c == NULL)
  7464. {
  7465. return;
  7466. }
  7467. if (c->SpecialFlag == false)
  7468. {
  7469. UnixDeletePipe(c->pipe_read, c->pipe_write);
  7470. }
  7471. Free(c);
  7472. }
  7473. // Creating a new cancel object
  7474. CANCEL *UnixNewCancel()
  7475. {
  7476. CANCEL *c = ZeroMallocFast(sizeof(CANCEL));
  7477. c->ref = NewRef();
  7478. c->SpecialFlag = false;
  7479. UnixNewPipe(&c->pipe_read, &c->pipe_write);
  7480. c->pipe_special_read2 = c->pipe_special_read3 = -1;
  7481. return c;
  7482. }
  7483. // Add the socket to the socket event
  7484. void UnixJoinSockToSockEvent(SOCK *sock, SOCK_EVENT *event)
  7485. {
  7486. // Validate arguments
  7487. if (sock == NULL || event == NULL || sock->AsyncMode)
  7488. {
  7489. return;
  7490. }
  7491. if (sock->ListenMode != false || (sock->Type == SOCK_TCP && sock->Connected == false))
  7492. {
  7493. return;
  7494. }
  7495. sock->AsyncMode = true;
  7496. LockList(event->SockList);
  7497. {
  7498. Add(event->SockList, sock);
  7499. AddRef(sock->ref);
  7500. }
  7501. UnlockList(event->SockList);
  7502. // Make the socket asynchronous mode
  7503. if (sock->Type != SOCK_INPROC)
  7504. {
  7505. UnixSetSocketNonBlockingMode(sock->socket, true);
  7506. }
  7507. // Increase the reference count of the SOCK_EVENT
  7508. AddRef(event->ref);
  7509. sock->SockEvent = event;
  7510. // Set the socket event
  7511. SetSockEvent(event);
  7512. }
  7513. // Wait for a socket event
  7514. bool UnixWaitSockEvent(SOCK_EVENT *event, UINT timeout)
  7515. {
  7516. UINT num_read, num_write;
  7517. UINT *reads, *writes;
  7518. UINT n;
  7519. char tmp[MAX_SIZE];
  7520. int readret = 0;
  7521. bool event_pipe_is_readable = false;
  7522. // Validate arguments
  7523. if (event == NULL)
  7524. {
  7525. return false;
  7526. }
  7527. LockList(event->SockList);
  7528. {
  7529. UINT i;
  7530. reads = ZeroMallocFast(sizeof(SOCK *) * (LIST_NUM(event->SockList) + 1));
  7531. num_write = 0;
  7532. num_read = 0;
  7533. for (i = 0;i < LIST_NUM(event->SockList);i++)
  7534. {
  7535. SOCK *s = LIST_DATA(event->SockList, i);
  7536. if (s->NoNeedToRead == false)
  7537. {
  7538. reads[num_read++] = s->socket;
  7539. }
  7540. if (s->WriteBlocked)
  7541. {
  7542. num_write++;
  7543. }
  7544. }
  7545. reads[num_read++] = event->pipe_read;
  7546. if (event->current_pipe_data != 0)
  7547. {
  7548. event_pipe_is_readable = true;
  7549. }
  7550. writes = ZeroMallocFast(sizeof(SOCK *) * num_write);
  7551. n = 0;
  7552. for (i = 0;i < (num_read - 1);i++)
  7553. {
  7554. SOCK *s = LIST_DATA(event->SockList, i);
  7555. if (s->WriteBlocked)
  7556. {
  7557. writes[n++] = s->socket;
  7558. }
  7559. }
  7560. }
  7561. UnlockList(event->SockList);
  7562. if (event_pipe_is_readable == false)
  7563. {
  7564. UnixSelectInner(num_read, reads, num_write, writes, timeout);
  7565. }
  7566. event->current_pipe_data = 0;
  7567. do
  7568. {
  7569. readret = read(event->pipe_read, tmp, sizeof(tmp));
  7570. }
  7571. while (readret >= 1);
  7572. Free(reads);
  7573. Free(writes);
  7574. return true;
  7575. }
  7576. // Set the socket event
  7577. void UnixSetSockEvent(SOCK_EVENT *event)
  7578. {
  7579. // Validate arguments
  7580. if (event == NULL)
  7581. {
  7582. return;
  7583. }
  7584. if (event->current_pipe_data <= 100)
  7585. {
  7586. UnixWritePipe(event->pipe_write);
  7587. event->current_pipe_data++;
  7588. }
  7589. }
  7590. // This is a helper function for select()
  7591. int safe_fd_set(int fd, fd_set* fds, int* max_fd) {
  7592. FD_SET(fd, fds);
  7593. if (fd > *max_fd) {
  7594. *max_fd = fd;
  7595. }
  7596. return 0;
  7597. }
  7598. // Execute 'select' for the socket
  7599. void UnixSelectInner(UINT num_read, UINT *reads, UINT num_write, UINT *writes, UINT timeout)
  7600. {
  7601. #ifdef UNIX_MACOS
  7602. fd_set rfds; //read descriptors
  7603. fd_set wfds; //write descriptors
  7604. int max_fd = 0; //maximum descriptor id
  7605. struct timeval tv; //timeval for timeout
  7606. #else // UNIX_MACOS
  7607. struct pollfd *p;
  7608. #endif // UNIX_MACOS
  7609. UINT num;
  7610. UINT i;
  7611. UINT n;
  7612. UINT num_read_total, num_write_total;
  7613. if (num_read != 0 && reads == NULL)
  7614. {
  7615. num_read = 0;
  7616. }
  7617. if (num_write != 0 && writes == NULL)
  7618. {
  7619. num_write = 0;
  7620. }
  7621. if (timeout == 0)
  7622. {
  7623. return;
  7624. }
  7625. num_read_total = num_write_total = 0;
  7626. for (i = 0;i < num_read;i++)
  7627. {
  7628. if (reads[i] != INVALID_SOCKET)
  7629. {
  7630. num_read_total++;
  7631. }
  7632. }
  7633. for (i = 0;i < num_write;i++)
  7634. {
  7635. if (writes[i] != INVALID_SOCKET)
  7636. {
  7637. num_write_total++;
  7638. }
  7639. }
  7640. num = num_read_total + num_write_total;
  7641. #ifdef UNIX_MACOS
  7642. FD_ZERO(&rfds); //zero out descriptor set for read descriptors
  7643. FD_ZERO(&wfds); //same for write
  7644. #else // UNIX_MACOS
  7645. p = ZeroMallocFast(sizeof(struct pollfd) * num);
  7646. #endif // UNIX_MACOS
  7647. n = 0;
  7648. for (i = 0;i < num_read;i++)
  7649. {
  7650. if (reads[i] != INVALID_SOCKET)
  7651. {
  7652. #ifdef UNIX_MACOS
  7653. safe_fd_set(reads[i], &rfds, &max_fd);
  7654. #else // UNIX_MACOS
  7655. struct pollfd *pfd = &p[n++];
  7656. pfd->fd = reads[i];
  7657. pfd->events = POLLIN | POLLPRI | POLLERR | POLLHUP;
  7658. #endif // UNIX_MACOS
  7659. }
  7660. }
  7661. for (i = 0;i < num_write;i++)
  7662. {
  7663. if (writes[i] != INVALID_SOCKET)
  7664. {
  7665. #ifdef UNIX_MACOS
  7666. safe_fd_set(writes[i], &wfds, &max_fd);
  7667. #else // UNIX_MACOS
  7668. struct pollfd *pfd = &p[n++];
  7669. pfd->fd = writes[i];
  7670. pfd->events = POLLIN | POLLPRI | POLLERR | POLLHUP | POLLOUT;
  7671. #endif // UNIX_MACOS
  7672. }
  7673. }
  7674. if (num != 0)
  7675. {
  7676. #ifdef UNIX_MACOS
  7677. tv.tv_sec = timeout / 1000;
  7678. tv.tv_usec = (timeout % 1000) * 1000l;
  7679. select(max_fd + 1, &rfds, &wfds, NULL, timeout == INFINITE ? NULL : &tv);
  7680. #else // UNIX_MACOS
  7681. poll(p, num, timeout == INFINITE ? -1 : (int)timeout);
  7682. #endif // UNIX_MACOS
  7683. }
  7684. else
  7685. {
  7686. SleepThread(timeout);
  7687. }
  7688. #ifndef UNIX_MACOS
  7689. Free(p);
  7690. #endif // not UNIX_MACOS
  7691. }
  7692. // Clean-up of the socket event
  7693. void UnixCleanupSockEvent(SOCK_EVENT *event)
  7694. {
  7695. UINT i;
  7696. // Validate arguments
  7697. if (event == NULL)
  7698. {
  7699. return;
  7700. }
  7701. for (i = 0;i < LIST_NUM(event->SockList);i++)
  7702. {
  7703. SOCK *s = LIST_DATA(event->SockList, i);
  7704. ReleaseSock(s);
  7705. }
  7706. ReleaseList(event->SockList);
  7707. UnixDeletePipe(event->pipe_read, event->pipe_write);
  7708. Free(event);
  7709. }
  7710. // Create a socket event
  7711. SOCK_EVENT *UnixNewSockEvent()
  7712. {
  7713. SOCK_EVENT *e = ZeroMallocFast(sizeof(SOCK_EVENT));
  7714. e->SockList = NewList(NULL);
  7715. e->ref = NewRef();
  7716. UnixNewPipe(&e->pipe_read, &e->pipe_write);
  7717. return e;
  7718. }
  7719. // Close the pipe
  7720. void UnixDeletePipe(int p1, int p2)
  7721. {
  7722. if (p1 != -1)
  7723. {
  7724. close(p1);
  7725. }
  7726. if (p2 != -1)
  7727. {
  7728. close(p2);
  7729. }
  7730. }
  7731. // Write to the pipe
  7732. void UnixWritePipe(int pipe_write)
  7733. {
  7734. char c = 1;
  7735. write(pipe_write, &c, 1);
  7736. }
  7737. // Create a new pipe
  7738. void UnixNewPipe(int *pipe_read, int *pipe_write)
  7739. {
  7740. int fd[2];
  7741. // Validate arguments
  7742. if (pipe_read == NULL || pipe_write == NULL)
  7743. {
  7744. return;
  7745. }
  7746. fd[0] = fd[1] = 0;
  7747. pipe(fd);
  7748. *pipe_read = fd[0];
  7749. *pipe_write = fd[1];
  7750. UnixSetSocketNonBlockingMode(*pipe_write, true);
  7751. UnixSetSocketNonBlockingMode(*pipe_read, true);
  7752. }
  7753. // Release the asynchronous socket
  7754. void UnixFreeAsyncSocket(SOCK *sock)
  7755. {
  7756. UINT p;
  7757. // Validate arguments
  7758. if (sock == NULL)
  7759. {
  7760. return;
  7761. }
  7762. Lock(sock->lock);
  7763. {
  7764. if (sock->AsyncMode == false)
  7765. {
  7766. Unlock(sock->lock);
  7767. return;
  7768. }
  7769. sock->AsyncMode = false;
  7770. // Examine whether this socket are associated to SockEvent
  7771. if (sock->SockEvent != NULL)
  7772. {
  7773. SOCK_EVENT *e = sock->SockEvent;
  7774. AddRef(e->ref);
  7775. p = e->pipe_write;
  7776. LockList(e->SockList);
  7777. {
  7778. if (Delete(e->SockList, sock))
  7779. {
  7780. ReleaseSock(sock);
  7781. }
  7782. }
  7783. UnlockList(e->SockList);
  7784. // Release the socket event
  7785. ReleaseSockEvent(sock->SockEvent);
  7786. sock->SockEvent = NULL;
  7787. SetSockEvent(e);
  7788. ReleaseSockEvent(e);
  7789. }
  7790. }
  7791. Unlock(sock->lock);
  7792. }
  7793. // Set the socket to asynchronous mode
  7794. void UnixInitAsyncSocket(SOCK *sock)
  7795. {
  7796. // Validate arguments
  7797. if (sock == NULL)
  7798. {
  7799. return;
  7800. }
  7801. if (sock->AsyncMode)
  7802. {
  7803. // The socket has been set in asynchronous mode already
  7804. return;
  7805. }
  7806. if (sock->ListenMode != false || ((sock->Type == SOCK_TCP || sock->Type == SOCK_INPROC) && sock->Connected == false))
  7807. {
  7808. return;
  7809. }
  7810. sock->AsyncMode = true;
  7811. if (sock->Type != SOCK_INPROC)
  7812. {
  7813. UnixSetSocketNonBlockingMode(sock->socket, true);
  7814. }
  7815. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  7816. if (sock->ssl != NULL && sock->ssl->s3 != NULL)
  7817. {
  7818. sock->Ssl_Init_Async_SendAlert[0] = sock->ssl->s3->send_alert[0];
  7819. sock->Ssl_Init_Async_SendAlert[1] = sock->ssl->s3->send_alert[1];
  7820. }
  7821. #endif
  7822. }
  7823. // Initializing the socket library
  7824. void UnixInitSocketLibrary()
  7825. {
  7826. // Do not do anything special
  7827. }
  7828. // Release of the socket library
  7829. void UnixFreeSocketLibrary()
  7830. {
  7831. // Do not do anything special
  7832. }
  7833. #endif // OS_UNIX
  7834. #ifdef OS_WIN32 // Code for Windows
  7835. NETWORK_WIN32_FUNCTIONS *w32net;
  7836. // Comparison of IP_ADAPTER_INDEX_MAP
  7837. int CompareIpAdapterIndexMap(void *p1, void *p2)
  7838. {
  7839. IP_ADAPTER_INDEX_MAP *a1, *a2;
  7840. if (p1 == NULL || p2 == NULL)
  7841. {
  7842. return 0;
  7843. }
  7844. a1 = *(IP_ADAPTER_INDEX_MAP **)p1;
  7845. a2 = *(IP_ADAPTER_INDEX_MAP **)p2;
  7846. if (a1 == NULL || a2 == NULL)
  7847. {
  7848. return 0;
  7849. }
  7850. if (a1->Index > a2->Index)
  7851. {
  7852. return 1;
  7853. }
  7854. else if (a1->Index < a2->Index)
  7855. {
  7856. return -1;
  7857. }
  7858. else
  7859. {
  7860. return 0;
  7861. }
  7862. }
  7863. // Update the IP address of the adapter
  7864. bool Win32RenewAddressByGuid(char *guid)
  7865. {
  7866. IP_ADAPTER_INDEX_MAP a;
  7867. // Validate arguments
  7868. if (guid == NULL)
  7869. {
  7870. return false;
  7871. }
  7872. Zero(&a, sizeof(a));
  7873. if (Win32GetAdapterFromGuid(&a, guid) == false)
  7874. {
  7875. return false;
  7876. }
  7877. return Win32RenewAddress(&a);
  7878. }
  7879. bool Win32RenewAddress(void *a)
  7880. {
  7881. DWORD ret;
  7882. // Validate arguments
  7883. if (a == NULL)
  7884. {
  7885. return false;
  7886. }
  7887. if (w32net->IpRenewAddress == NULL)
  7888. {
  7889. return false;
  7890. }
  7891. ret = w32net->IpRenewAddress(a);
  7892. if (ret == NO_ERROR)
  7893. {
  7894. return true;
  7895. }
  7896. else
  7897. {
  7898. Debug("IpRenewAddress: Error: %u\n", ret);
  7899. return false;
  7900. }
  7901. }
  7902. // Release the IP address of the adapter
  7903. bool Win32ReleaseAddress(void *a)
  7904. {
  7905. DWORD ret;
  7906. // Validate arguments
  7907. if (a == NULL)
  7908. {
  7909. return false;
  7910. }
  7911. if (w32net->IpReleaseAddress == NULL)
  7912. {
  7913. return false;
  7914. }
  7915. ret = w32net->IpReleaseAddress(a);
  7916. if (ret == NO_ERROR)
  7917. {
  7918. return true;
  7919. }
  7920. else
  7921. {
  7922. Debug("IpReleaseAddress: Error: %u\n", ret);
  7923. return false;
  7924. }
  7925. }
  7926. bool Win32ReleaseAddressByGuid(char *guid)
  7927. {
  7928. IP_ADAPTER_INDEX_MAP a;
  7929. // Validate arguments
  7930. if (guid == NULL)
  7931. {
  7932. return false;
  7933. }
  7934. Zero(&a, sizeof(a));
  7935. if (Win32GetAdapterFromGuid(&a, guid) == false)
  7936. {
  7937. return false;
  7938. }
  7939. return Win32ReleaseAddress(&a);
  7940. }
  7941. void Win32ReleaseAddressByGuidExThread(THREAD *t, void *param)
  7942. {
  7943. WIN32_RELEASEADDRESS_THREAD_PARAM *p;
  7944. // Validate arguments
  7945. if (t == NULL || param == NULL)
  7946. {
  7947. return;
  7948. }
  7949. p = (WIN32_RELEASEADDRESS_THREAD_PARAM *)param;
  7950. AddRef(p->Ref);
  7951. NoticeThreadInit(t);
  7952. AddWaitThread(t);
  7953. if (p->Renew == false)
  7954. {
  7955. p->Ok = Win32ReleaseAddressByGuid(p->Guid);
  7956. }
  7957. else
  7958. {
  7959. p->Ok = Win32RenewAddressByGuid(p->Guid);
  7960. }
  7961. ReleaseWin32ReleaseAddressByGuidThreadParam(p);
  7962. DelWaitThread(t);
  7963. }
  7964. bool Win32RenewAddressByGuidEx(char *guid, UINT timeout)
  7965. {
  7966. return Win32ReleaseOrRenewAddressByGuidEx(guid, timeout, true);
  7967. }
  7968. bool Win32ReleaseAddressByGuidEx(char *guid, UINT timeout)
  7969. {
  7970. return Win32ReleaseOrRenewAddressByGuidEx(guid, timeout, false);
  7971. }
  7972. bool Win32ReleaseOrRenewAddressByGuidEx(char *guid, UINT timeout, bool renew)
  7973. {
  7974. THREAD *t;
  7975. WIN32_RELEASEADDRESS_THREAD_PARAM *p;
  7976. bool ret = false;
  7977. UINT64 start_tick = 0;
  7978. UINT64 end_tick = 0;
  7979. // Validate arguments
  7980. if (guid == NULL)
  7981. {
  7982. return false;
  7983. }
  7984. if (timeout == 0)
  7985. {
  7986. timeout = INFINITE;
  7987. }
  7988. p = ZeroMalloc(sizeof(WIN32_RELEASEADDRESS_THREAD_PARAM));
  7989. p->Ref = NewRef();
  7990. StrCpy(p->Guid, sizeof(p->Guid), guid);
  7991. p->Timeout = timeout;
  7992. p->Renew = renew;
  7993. t = NewThread(Win32ReleaseAddressByGuidExThread, p);
  7994. WaitThreadInit(t);
  7995. start_tick = Tick64();
  7996. end_tick = start_tick + (UINT64)timeout;
  7997. while (true)
  7998. {
  7999. UINT64 now = Tick64();
  8000. UINT64 remain;
  8001. UINT remain32;
  8002. if (now >= end_tick)
  8003. {
  8004. break;
  8005. }
  8006. remain = end_tick - now;
  8007. remain32 = MIN((UINT)remain, 100);
  8008. if (WaitThread(t, remain32))
  8009. {
  8010. break;
  8011. }
  8012. }
  8013. ReleaseThread(t);
  8014. if (p->Ok)
  8015. {
  8016. ret = true;
  8017. }
  8018. ReleaseWin32ReleaseAddressByGuidThreadParam(p);
  8019. return ret;
  8020. }
  8021. void ReleaseWin32ReleaseAddressByGuidThreadParam(WIN32_RELEASEADDRESS_THREAD_PARAM *p)
  8022. {
  8023. // Validate arguments
  8024. if (p == NULL)
  8025. {
  8026. return;
  8027. }
  8028. if (Release(p->Ref) == 0)
  8029. {
  8030. Free(p);
  8031. }
  8032. }
  8033. // Get the adapter by the GUID
  8034. bool Win32GetAdapterFromGuid(void *a, char *guid)
  8035. {
  8036. bool ret = false;
  8037. IP_INTERFACE_INFO *info;
  8038. UINT size;
  8039. int i;
  8040. LIST *o;
  8041. wchar_t tmp[MAX_SIZE];
  8042. // Validate arguments
  8043. if (a == NULL || guid == NULL)
  8044. {
  8045. return false;
  8046. }
  8047. if (w32net->GetInterfaceInfo == NULL)
  8048. {
  8049. return false;
  8050. }
  8051. UniFormat(tmp, sizeof(tmp), L"\\DEVICE\\TCPIP_%S", guid);
  8052. size = sizeof(IP_INTERFACE_INFO);
  8053. info = ZeroMallocFast(size);
  8054. if (w32net->GetInterfaceInfo(info, &size) == ERROR_INSUFFICIENT_BUFFER)
  8055. {
  8056. Free(info);
  8057. info = ZeroMallocFast(size);
  8058. }
  8059. if (w32net->GetInterfaceInfo(info, &size) != NO_ERROR)
  8060. {
  8061. Free(info);
  8062. return false;
  8063. }
  8064. o = NewListFast(CompareIpAdapterIndexMap);
  8065. for (i = 0;i < info->NumAdapters;i++)
  8066. {
  8067. IP_ADAPTER_INDEX_MAP *a = &info->Adapter[i];
  8068. Add(o, a);
  8069. }
  8070. Sort(o);
  8071. for (i = 0;i < (int)(LIST_NUM(o));i++)
  8072. {
  8073. IP_ADAPTER_INDEX_MAP *e = LIST_DATA(o, i);
  8074. if (UniStrCmpi(e->Name, tmp) == 0)
  8075. {
  8076. Copy(a, e, sizeof(IP_ADAPTER_INDEX_MAP));
  8077. ret = true;
  8078. break;
  8079. }
  8080. }
  8081. ReleaseList(o);
  8082. Free(info);
  8083. return ret;
  8084. }
  8085. // Test
  8086. void Win32NetworkTest()
  8087. {
  8088. IP_INTERFACE_INFO *info;
  8089. UINT size;
  8090. int i;
  8091. LIST *o;
  8092. size = sizeof(IP_INTERFACE_INFO);
  8093. info = ZeroMallocFast(size);
  8094. if (w32net->GetInterfaceInfo(info, &size) == ERROR_INSUFFICIENT_BUFFER)
  8095. {
  8096. Free(info);
  8097. info = ZeroMallocFast(size);
  8098. }
  8099. if (w32net->GetInterfaceInfo(info, &size) != NO_ERROR)
  8100. {
  8101. Free(info);
  8102. return;
  8103. }
  8104. o = NewListFast(CompareIpAdapterIndexMap);
  8105. for (i = 0;i < info->NumAdapters;i++)
  8106. {
  8107. IP_ADAPTER_INDEX_MAP *a = &info->Adapter[i];
  8108. Add(o, a);
  8109. }
  8110. Sort(o);
  8111. for (i = 0;i < (int)(LIST_NUM(o));i++)
  8112. {
  8113. IP_ADAPTER_INDEX_MAP *a = LIST_DATA(o, i);
  8114. DoNothing();
  8115. }
  8116. ReleaseList(o);
  8117. Free(info);
  8118. }
  8119. // Clear the DNS cache on Win32
  8120. void Win32FlushDnsCache()
  8121. {
  8122. Run("ipconfig.exe", "/flushdns", true, false);
  8123. }
  8124. // Update the DHCP address of the specified LAN card
  8125. void Win32RenewDhcp9x(UINT if_id)
  8126. {
  8127. IP_INTERFACE_INFO *info;
  8128. UINT size;
  8129. int i;
  8130. LIST *o;
  8131. // Validate arguments
  8132. if (if_id == 0)
  8133. {
  8134. return;
  8135. }
  8136. size = sizeof(IP_INTERFACE_INFO);
  8137. info = ZeroMallocFast(size);
  8138. if (w32net->GetInterfaceInfo(info, &size) == ERROR_INSUFFICIENT_BUFFER)
  8139. {
  8140. Free(info);
  8141. info = ZeroMallocFast(size);
  8142. }
  8143. if (w32net->GetInterfaceInfo(info, &size) != NO_ERROR)
  8144. {
  8145. Free(info);
  8146. return;
  8147. }
  8148. o = NewListFast(CompareIpAdapterIndexMap);
  8149. for (i = 0;i < info->NumAdapters;i++)
  8150. {
  8151. IP_ADAPTER_INDEX_MAP *a = &info->Adapter[i];
  8152. Add(o, a);
  8153. }
  8154. Sort(o);
  8155. for (i = 0;i < (int)(LIST_NUM(o));i++)
  8156. {
  8157. IP_ADAPTER_INDEX_MAP *a = LIST_DATA(o, i);
  8158. if (a->Index == if_id)
  8159. {
  8160. char arg[MAX_PATH];
  8161. Format(arg, sizeof(arg), "/renew %u", i);
  8162. Run("ipconfig.exe", arg, true, false);
  8163. }
  8164. }
  8165. ReleaseList(o);
  8166. Free(info);
  8167. }
  8168. // Release the DHCP address of the specified LAN card
  8169. void Win32ReleaseDhcp9x(UINT if_id, bool wait)
  8170. {
  8171. IP_INTERFACE_INFO *info;
  8172. UINT size;
  8173. int i;
  8174. LIST *o;
  8175. // Validate arguments
  8176. if (if_id == 0)
  8177. {
  8178. return;
  8179. }
  8180. size = sizeof(IP_INTERFACE_INFO);
  8181. info = ZeroMallocFast(size);
  8182. if (w32net->GetInterfaceInfo(info, &size) == ERROR_INSUFFICIENT_BUFFER)
  8183. {
  8184. Free(info);
  8185. info = ZeroMallocFast(size);
  8186. }
  8187. if (w32net->GetInterfaceInfo(info, &size) != NO_ERROR)
  8188. {
  8189. Free(info);
  8190. return;
  8191. }
  8192. o = NewListFast(CompareIpAdapterIndexMap);
  8193. for (i = 0;i < info->NumAdapters;i++)
  8194. {
  8195. IP_ADAPTER_INDEX_MAP *a = &info->Adapter[i];
  8196. Add(o, a);
  8197. }
  8198. Sort(o);
  8199. for (i = 0;i < (int)(LIST_NUM(o));i++)
  8200. {
  8201. IP_ADAPTER_INDEX_MAP *a = LIST_DATA(o, i);
  8202. if (a->Index == if_id)
  8203. {
  8204. char arg[MAX_PATH];
  8205. Format(arg, sizeof(arg), "/release %u", i);
  8206. Run("ipconfig.exe", arg, true, wait);
  8207. }
  8208. }
  8209. ReleaseList(o);
  8210. Free(info);
  8211. }
  8212. // Re-obtain an IP address from a DHCP server
  8213. void Win32RenewDhcp()
  8214. {
  8215. if (OS_IS_WINDOWS_NT(GetOsInfo()->OsType))
  8216. {
  8217. Run("ipconfig.exe", "/renew", true, false);
  8218. if (MsIsVista())
  8219. {
  8220. Run("ipconfig.exe", "/renew6", true, false);
  8221. }
  8222. else
  8223. {
  8224. Run("netsh.exe", "int ipv6 renew", true, false);
  8225. }
  8226. }
  8227. else
  8228. {
  8229. Run("ipconfig.exe", "/renew_all", true, false);
  8230. }
  8231. }
  8232. // Enumerate a list of virtual LAN cards that contains the specified string
  8233. char **Win32EnumVLan(char *tag_name)
  8234. {
  8235. MIB_IFTABLE *p;
  8236. UINT ret;
  8237. UINT size_needed;
  8238. UINT num_retry = 0;
  8239. UINT i;
  8240. LIST *o;
  8241. char **ss;
  8242. // Validate arguments
  8243. if (tag_name == 0)
  8244. {
  8245. return NULL;
  8246. }
  8247. RETRY:
  8248. p = ZeroMallocFast(sizeof(MIB_IFTABLE));
  8249. size_needed = 0;
  8250. // Examine the needed size
  8251. ret = w32net->GetIfTable(p, &size_needed, 0);
  8252. if (ret == ERROR_INSUFFICIENT_BUFFER)
  8253. {
  8254. // Re-allocate the memory block of the needed size
  8255. Free(p);
  8256. p = ZeroMallocFast(size_needed);
  8257. }
  8258. else if (ret != NO_ERROR)
  8259. {
  8260. // Acquisition failure
  8261. FAILED:
  8262. Free(p);
  8263. return NULL;
  8264. }
  8265. // Actually get
  8266. ret = w32net->GetIfTable(p, &size_needed, FALSE);
  8267. if (ret != NO_ERROR)
  8268. {
  8269. // Acquisition failure
  8270. if ((++num_retry) >= 5)
  8271. {
  8272. goto FAILED;
  8273. }
  8274. Free(p);
  8275. goto RETRY;
  8276. }
  8277. // Search
  8278. ret = 0;
  8279. o = NewListFast(CompareStr);
  8280. for (i = 0;i < p->dwNumEntries;i++)
  8281. {
  8282. MIB_IFROW *r = &p->table[i];
  8283. if (SearchStrEx(r->bDescr, tag_name, 0, false) != INFINITE)
  8284. {
  8285. char *s = CopyStr(r->bDescr);
  8286. Add(o, s);
  8287. }
  8288. }
  8289. Free(p);
  8290. // Sort
  8291. Sort(o);
  8292. // Convert to string
  8293. ss = ZeroMallocFast(sizeof(char *) * (LIST_NUM(o) + 1));
  8294. for (i = 0;i < LIST_NUM(o);i++)
  8295. {
  8296. ss[i] = LIST_DATA(o, i);
  8297. }
  8298. ss[LIST_NUM(o)] = NULL;
  8299. ReleaseList(o);
  8300. return ss;
  8301. }
  8302. // Get the ID of the virtual LAN card from the instance name of the virtual LAN card
  8303. UINT Win32GetVLanInterfaceID(char *instance_name)
  8304. {
  8305. MIB_IFTABLE *p;
  8306. UINT ret;
  8307. UINT size_needed;
  8308. UINT num_retry = 0;
  8309. UINT i;
  8310. char ps_miniport_str[MAX_SIZE];
  8311. char ps_miniport_str2[MAX_SIZE];
  8312. UINT min_len = 0x7FFFFFFF;
  8313. // Validate arguments
  8314. if (instance_name == 0)
  8315. {
  8316. return 0;
  8317. }
  8318. RETRY:
  8319. p = ZeroMallocFast(sizeof(MIB_IFTABLE));
  8320. size_needed = 0;
  8321. // Examine the needed size
  8322. ret = w32net->GetIfTable(p, &size_needed, 0);
  8323. if (ret == ERROR_INSUFFICIENT_BUFFER)
  8324. {
  8325. // Re-allocate the memory block of the needed size
  8326. Free(p);
  8327. p = ZeroMallocFast(size_needed);
  8328. }
  8329. else if (ret != NO_ERROR)
  8330. {
  8331. // Acquisition failure
  8332. FAILED:
  8333. Free(p);
  8334. Debug("******** GetIfTable Failed 1. Err = %u\n", ret);
  8335. return 0;
  8336. }
  8337. // Actually get
  8338. ret = w32net->GetIfTable(p, &size_needed, FALSE);
  8339. if (ret != NO_ERROR)
  8340. {
  8341. // Acquisition failure
  8342. if ((++num_retry) >= 5)
  8343. {
  8344. goto FAILED;
  8345. }
  8346. Free(p);
  8347. Debug("******** GetIfTable Failed 2. Err = %u\n", ret);
  8348. goto RETRY;
  8349. }
  8350. // "%s - Packet scheduler miniport"
  8351. Format(ps_miniport_str, sizeof(ps_miniport_str), "%s - ", instance_name);
  8352. Format(ps_miniport_str2, sizeof(ps_miniport_str2), "%s (Microsoft", instance_name);
  8353. // Search
  8354. ret = 0;
  8355. for (i = 0;i < p->dwNumEntries;i++)
  8356. {
  8357. MIB_IFROW *r = &p->table[i];
  8358. if (instance_name[0] != '@')
  8359. {
  8360. if (StrCmpi(r->bDescr, instance_name) == 0 || StartWith(r->bDescr, ps_miniport_str) || StartWith(r->bDescr, ps_miniport_str2))
  8361. {
  8362. UINT len = StrLen(r->bDescr);
  8363. if (len < min_len)
  8364. {
  8365. ret = r->dwIndex;
  8366. min_len = len;
  8367. }
  8368. }
  8369. }
  8370. else
  8371. {
  8372. if (SearchStrEx(r->bDescr, &instance_name[1], 0, false) != INFINITE)
  8373. {
  8374. ret = r->dwIndex;
  8375. }
  8376. }
  8377. //Debug("if[%u] (dwIndex=%u): %u, %s\n", i, r->dwIndex, r->dwType, r->bDescr);
  8378. }
  8379. Free(p);
  8380. return ret;
  8381. }
  8382. // Get the DNS suffix in another way
  8383. bool Win32GetDnsSuffix(char *domain, UINT size)
  8384. {
  8385. IP_ADAPTER_ADDRESSES_XP *info;
  8386. IP_ADAPTER_ADDRESSES_XP *cur;
  8387. UINT info_size;
  8388. bool ret = false;
  8389. // Validate arguments
  8390. ClearStr(domain, size);
  8391. if (domain == NULL)
  8392. {
  8393. return false;
  8394. }
  8395. if (w32net->GetAdaptersAddresses == NULL)
  8396. {
  8397. return false;
  8398. }
  8399. info_size = 0;
  8400. info = ZeroMalloc(sizeof(IP_ADAPTER_ADDRESSES_XP));
  8401. if (w32net->GetAdaptersAddresses(AF_INET, 0, NULL, info, &info_size) == ERROR_BUFFER_OVERFLOW)
  8402. {
  8403. Free(info);
  8404. info = ZeroMalloc(info_size);
  8405. }
  8406. if (w32net->GetAdaptersAddresses(AF_INET, 0, NULL, info, &info_size) != NO_ERROR)
  8407. {
  8408. Free(info);
  8409. return false;
  8410. }
  8411. cur = info;
  8412. while (cur != NULL)
  8413. {
  8414. if (UniIsEmptyStr(cur->DnsSuffix) == false)
  8415. {
  8416. UniToStr(domain, size, cur->DnsSuffix);
  8417. ret = true;
  8418. break;
  8419. }
  8420. cur = cur->Next;
  8421. }
  8422. Free(info);
  8423. return ret;
  8424. }
  8425. // Get the DNS server address of the default
  8426. bool Win32GetDefaultDns(IP *ip, char *domain, UINT size)
  8427. {
  8428. FIXED_INFO *info;
  8429. UINT info_size;
  8430. char *dns_name;
  8431. // Validate arguments
  8432. ClearStr(domain, size);
  8433. if (ip == NULL)
  8434. {
  8435. return false;
  8436. }
  8437. Zero(ip, sizeof(IP));
  8438. if (w32net->GetNetworkParams == NULL)
  8439. {
  8440. return false;
  8441. }
  8442. info_size = 0;
  8443. info = ZeroMallocFast(sizeof(FIXED_INFO));
  8444. if (w32net->GetNetworkParams(info, &info_size) == ERROR_BUFFER_OVERFLOW)
  8445. {
  8446. Free(info);
  8447. info = ZeroMallocFast(info_size);
  8448. }
  8449. if (w32net->GetNetworkParams(info, &info_size) != NO_ERROR)
  8450. {
  8451. Free(info);
  8452. return false;
  8453. }
  8454. if (info->DnsServerList.IpAddress.String == NULL)
  8455. {
  8456. Free(info);
  8457. return false;
  8458. }
  8459. dns_name = info->DnsServerList.IpAddress.String;
  8460. StrToIP(ip, dns_name);
  8461. if (domain != NULL)
  8462. {
  8463. StrCpy(domain, size, info->DomainName);
  8464. Trim(domain);
  8465. }
  8466. Free(info);
  8467. return true;
  8468. }
  8469. // IP conversion function for Win32
  8470. void Win32UINTToIP(IP *ip, UINT i)
  8471. {
  8472. UINTToIP(ip, i);
  8473. }
  8474. // IP conversion function for Win32
  8475. UINT Win32IPToUINT(IP *ip)
  8476. {
  8477. return IPToUINT(ip);
  8478. }
  8479. // Remove a routing entry from the routing table
  8480. void Win32DeleteRouteEntry(ROUTE_ENTRY *e)
  8481. {
  8482. MIB_IPFORWARDROW *p;
  8483. // Validate arguments
  8484. if (e == NULL)
  8485. {
  8486. return;
  8487. }
  8488. p = ZeroMallocFast(sizeof(MIB_IPFORWARDROW));
  8489. Win32RouteEntryToIpForwardRow(p, e);
  8490. // Delete
  8491. w32net->DeleteIpForwardEntry(p);
  8492. Free(p);
  8493. }
  8494. // Add a routing entry to the routing table
  8495. bool Win32AddRouteEntry(ROUTE_ENTRY *e, bool *already_exists)
  8496. {
  8497. bool ret = false;
  8498. bool dummy = false;
  8499. MIB_IPFORWARDROW *p;
  8500. UINT err = 0;
  8501. // Validate arguments
  8502. if (e == NULL)
  8503. {
  8504. return false;
  8505. }
  8506. if (already_exists == NULL)
  8507. {
  8508. already_exists = &dummy;
  8509. }
  8510. *already_exists = false;
  8511. p = ZeroMallocFast(sizeof(MIB_IPFORWARDROW));
  8512. Win32RouteEntryToIpForwardRow(p, e);
  8513. // Adding
  8514. err = w32net->CreateIpForwardEntry(p);
  8515. if (err != 0)
  8516. {
  8517. if (err == ERROR_OBJECT_ALREADY_EXISTS)
  8518. {
  8519. Debug("CreateIpForwardEntry: Already Exists\n");
  8520. *already_exists = true;
  8521. ret = true;
  8522. }
  8523. else
  8524. {
  8525. Debug("CreateIpForwardEntry Error: %u\n", err);
  8526. ret = false;
  8527. }
  8528. }
  8529. else
  8530. {
  8531. ret = true;
  8532. }
  8533. Free(p);
  8534. return ret;
  8535. }
  8536. // Get the routing table
  8537. ROUTE_TABLE *Win32GetRouteTable()
  8538. {
  8539. ROUTE_TABLE *t = ZeroMallocFast(sizeof(ROUTE_TABLE));
  8540. MIB_IPFORWARDTABLE *p;
  8541. UINT ret;
  8542. UINT size_needed;
  8543. UINT num_retry = 0;
  8544. LIST *o;
  8545. UINT i;
  8546. ROUTE_ENTRY *e;
  8547. RETRY:
  8548. p = ZeroMallocFast(sizeof(MIB_IFTABLE));
  8549. size_needed = 0;
  8550. // Examine the needed size
  8551. ret = w32net->GetIpForwardTable(p, &size_needed, 0);
  8552. if (ret == ERROR_INSUFFICIENT_BUFFER)
  8553. {
  8554. // Re-allocate the memory block of the needed size
  8555. Free(p);
  8556. p = ZeroMallocFast(size_needed);
  8557. }
  8558. else if (ret != NO_ERROR)
  8559. {
  8560. // Acquisition failure
  8561. FAILED:
  8562. Free(p);
  8563. t->Entry = MallocFast(0);
  8564. return t;
  8565. }
  8566. // Actually get
  8567. ret = w32net->GetIpForwardTable(p, &size_needed, FALSE);
  8568. if (ret != NO_ERROR)
  8569. {
  8570. // Acquisition failure
  8571. if ((++num_retry) >= 5)
  8572. {
  8573. goto FAILED;
  8574. }
  8575. Free(p);
  8576. goto RETRY;
  8577. }
  8578. // Add to the list along
  8579. o = NewListFast(Win32CompareRouteEntryByMetric);
  8580. for (i = 0;i < p->dwNumEntries;i++)
  8581. {
  8582. e = ZeroMallocFast(sizeof(ROUTE_ENTRY));
  8583. Win32IpForwardRowToRouteEntry(e, &p->table[i]);
  8584. Add(o, e);
  8585. }
  8586. Free(p);
  8587. // Sort by metric
  8588. Sort(o);
  8589. // Combine the results
  8590. t->NumEntry = LIST_NUM(o);
  8591. t->Entry = ToArrayEx(o, true);
  8592. ReleaseList(o);
  8593. return t;
  8594. }
  8595. // Sort the routing entries by metric
  8596. int Win32CompareRouteEntryByMetric(void *p1, void *p2)
  8597. {
  8598. ROUTE_ENTRY *e1, *e2;
  8599. // Validate arguments
  8600. if (p1 == NULL || p2 == NULL)
  8601. {
  8602. return 0;
  8603. }
  8604. e1 = *(ROUTE_ENTRY **)p1;
  8605. e2 = *(ROUTE_ENTRY **)p2;
  8606. if (e1 == NULL || e2 == NULL)
  8607. {
  8608. return 0;
  8609. }
  8610. if (e1->Metric > e2->Metric)
  8611. {
  8612. return 1;
  8613. }
  8614. else if (e1->Metric == e2->Metric)
  8615. {
  8616. return 0;
  8617. }
  8618. else
  8619. {
  8620. return -1;
  8621. }
  8622. }
  8623. // Convert the ROUTE_ENTRY to a MIB_IPFORWARDROW
  8624. void Win32RouteEntryToIpForwardRow(void *ip_forward_row, ROUTE_ENTRY *entry)
  8625. {
  8626. MIB_IPFORWARDROW *r;
  8627. // Validate arguments
  8628. if (entry == NULL || ip_forward_row == NULL)
  8629. {
  8630. return;
  8631. }
  8632. r = (MIB_IPFORWARDROW *)ip_forward_row;
  8633. Zero(r, sizeof(MIB_IPFORWARDROW));
  8634. // IP address
  8635. r->dwForwardDest = Win32IPToUINT(&entry->DestIP);
  8636. // Subnet mask
  8637. r->dwForwardMask = Win32IPToUINT(&entry->DestMask);
  8638. // Gateway IP address
  8639. r->dwForwardNextHop = Win32IPToUINT(&entry->GatewayIP);
  8640. // Local routing flag
  8641. if (entry->LocalRouting)
  8642. {
  8643. // Local
  8644. r->dwForwardType = 3;
  8645. }
  8646. else
  8647. {
  8648. // Remote router
  8649. r->dwForwardType = 4;
  8650. }
  8651. // Protocol
  8652. r->dwForwardProto = r->dwForwardType - 1; // Subtract by 1 in most cases
  8653. if (entry->PPPConnection)
  8654. {
  8655. // Isn't this a PPP? Danger!
  8656. r->dwForwardProto++;
  8657. }
  8658. // Metric
  8659. r->dwForwardMetric1 = entry->Metric;
  8660. if (MsIsVista() == false)
  8661. {
  8662. r->dwForwardMetric2 = r->dwForwardMetric3 = r->dwForwardMetric4 = r->dwForwardMetric5 = INFINITE;
  8663. }
  8664. else
  8665. {
  8666. r->dwForwardMetric2 = r->dwForwardMetric3 = r->dwForwardMetric4 = r->dwForwardMetric5 = 0;
  8667. r->dwForwardAge = 163240;
  8668. }
  8669. // Interface ID
  8670. r->dwForwardIfIndex = entry->InterfaceID;
  8671. Debug("Win32RouteEntryToIpForwardRow()\n");
  8672. Debug(" r->dwForwardDest=%X\n", r->dwForwardDest);
  8673. Debug(" r->dwForwardMask=%X\n", r->dwForwardMask);
  8674. Debug(" r->dwForwardNextHop=%X\n", r->dwForwardNextHop);
  8675. Debug(" r->dwForwardType=%u\n", r->dwForwardType);
  8676. Debug(" r->dwForwardProto=%u\n", r->dwForwardProto);
  8677. Debug(" r->dwForwardMetric1=%u\n", r->dwForwardMetric1);
  8678. Debug(" r->dwForwardMetric2=%u\n", r->dwForwardMetric2);
  8679. Debug(" r->dwForwardIfIndex=%u\n", r->dwForwardIfIndex);
  8680. }
  8681. // Convert the MIB_IPFORWARDROW to a ROUTE_ENTRY
  8682. void Win32IpForwardRowToRouteEntry(ROUTE_ENTRY *entry, void *ip_forward_row)
  8683. {
  8684. MIB_IPFORWARDROW *r;
  8685. // Validate arguments
  8686. if (entry == NULL || ip_forward_row == NULL)
  8687. {
  8688. return;
  8689. }
  8690. r = (MIB_IPFORWARDROW *)ip_forward_row;
  8691. Zero(entry, sizeof(ROUTE_ENTRY));
  8692. // IP address
  8693. Win32UINTToIP(&entry->DestIP, r->dwForwardDest);
  8694. // Subnet mask
  8695. Win32UINTToIP(&entry->DestMask, r->dwForwardMask);
  8696. // Gateway IP address
  8697. Win32UINTToIP(&entry->GatewayIP, r->dwForwardNextHop);
  8698. // Local routing flag
  8699. if (r->dwForwardType == 3)
  8700. {
  8701. entry->LocalRouting = true;
  8702. }
  8703. else
  8704. {
  8705. entry->LocalRouting = false;
  8706. }
  8707. if (entry->LocalRouting && r->dwForwardProto == 3)
  8708. {
  8709. // PPP. Danger!
  8710. entry->PPPConnection = true;
  8711. }
  8712. // Metric
  8713. entry->Metric = r->dwForwardMetric1;
  8714. // Interface ID
  8715. entry->InterfaceID = r->dwForwardIfIndex;
  8716. }
  8717. // Initializing the socket library
  8718. void Win32InitSocketLibrary()
  8719. {
  8720. WSADATA data;
  8721. Zero(&data, sizeof(data));
  8722. WSAStartup(MAKEWORD(2, 2), &data);
  8723. // Load the DLL functions
  8724. w32net = ZeroMalloc(sizeof(NETWORK_WIN32_FUNCTIONS));
  8725. w32net->hIpHlpApi32 = LoadLibrary("iphlpapi.dll");
  8726. w32net->hIcmp = LoadLibrary("icmp.dll");
  8727. if (w32net->hIpHlpApi32 != NULL)
  8728. {
  8729. w32net->CreateIpForwardEntry =
  8730. (DWORD (__stdcall *)(PMIB_IPFORWARDROW))
  8731. GetProcAddress(w32net->hIpHlpApi32, "CreateIpForwardEntry");
  8732. w32net->DeleteIpForwardEntry =
  8733. (DWORD (__stdcall *)(PMIB_IPFORWARDROW))
  8734. GetProcAddress(w32net->hIpHlpApi32, "DeleteIpForwardEntry");
  8735. w32net->GetIfTable =
  8736. (DWORD (__stdcall *)(PMIB_IFTABLE, PULONG, BOOL))
  8737. GetProcAddress(w32net->hIpHlpApi32, "GetIfTable");
  8738. w32net->GetIfTable2 =
  8739. (DWORD (__stdcall *)(void **))
  8740. GetProcAddress(w32net->hIpHlpApi32, "GetIfTable2");
  8741. w32net->FreeMibTable =
  8742. (void (__stdcall *)(PVOID))
  8743. GetProcAddress(w32net->hIpHlpApi32, "FreeMibTable");
  8744. w32net->GetIpForwardTable =
  8745. (DWORD (__stdcall *)(PMIB_IPFORWARDTABLE, PULONG, BOOL))
  8746. GetProcAddress(w32net->hIpHlpApi32, "GetIpForwardTable");
  8747. w32net->GetNetworkParams =
  8748. (DWORD (__stdcall *)(PFIXED_INFO,PULONG))
  8749. GetProcAddress(w32net->hIpHlpApi32, "GetNetworkParams");
  8750. w32net->GetAdaptersAddresses =
  8751. (ULONG (__stdcall *)(ULONG,ULONG,PVOID,PIP_ADAPTER_ADDRESSES,PULONG))
  8752. GetProcAddress(w32net->hIpHlpApi32, "GetAdaptersAddresses");
  8753. w32net->IpRenewAddress =
  8754. (DWORD (__stdcall *)(PIP_ADAPTER_INDEX_MAP))
  8755. GetProcAddress(w32net->hIpHlpApi32, "IpRenewAddress");
  8756. w32net->IpReleaseAddress =
  8757. (DWORD (__stdcall *)(PIP_ADAPTER_INDEX_MAP))
  8758. GetProcAddress(w32net->hIpHlpApi32, "IpReleaseAddress");
  8759. w32net->GetInterfaceInfo =
  8760. (DWORD (__stdcall *)(PIP_INTERFACE_INFO, PULONG))
  8761. GetProcAddress(w32net->hIpHlpApi32, "GetInterfaceInfo");
  8762. w32net->GetAdaptersInfo =
  8763. (DWORD (__stdcall *)(PIP_ADAPTER_INFO, PULONG))
  8764. GetProcAddress(w32net->hIpHlpApi32, "GetAdaptersInfo");
  8765. w32net->GetExtendedTcpTable =
  8766. (DWORD (__stdcall *)(PVOID,PDWORD,BOOL,ULONG,_TCP_TABLE_CLASS,ULONG))
  8767. GetProcAddress(w32net->hIpHlpApi32, "GetExtendedTcpTable");
  8768. w32net->AllocateAndGetTcpExTableFromStack =
  8769. (DWORD (__stdcall *)(PVOID *,BOOL,HANDLE,DWORD,DWORD))
  8770. GetProcAddress(w32net->hIpHlpApi32, "AllocateAndGetTcpExTableFromStack");
  8771. w32net->GetTcpTable =
  8772. (DWORD (__stdcall *)(PMIB_TCPTABLE,PDWORD,BOOL))
  8773. GetProcAddress(w32net->hIpHlpApi32, "GetTcpTable");
  8774. w32net->NotifyRouteChange =
  8775. (DWORD (__stdcall *)(PHANDLE,LPOVERLAPPED))
  8776. GetProcAddress(w32net->hIpHlpApi32, "NotifyRouteChange");
  8777. w32net->CancelIPChangeNotify =
  8778. (BOOL (__stdcall *)(LPOVERLAPPED))
  8779. GetProcAddress(w32net->hIpHlpApi32, "CancelIPChangeNotify");
  8780. w32net->NhpAllocateAndGetInterfaceInfoFromStack =
  8781. (DWORD (__stdcall *)(IP_INTERFACE_NAME_INFO **,PDWORD,BOOL,HANDLE,DWORD))
  8782. GetProcAddress(w32net->hIpHlpApi32, "NhpAllocateAndGetInterfaceInfoFromStack");
  8783. w32net->IcmpCreateFile =
  8784. (HANDLE (__stdcall *)())
  8785. GetProcAddress(w32net->hIpHlpApi32, "IcmpCreateFile");
  8786. w32net->IcmpCloseHandle =
  8787. (BOOL (__stdcall *)(HANDLE))
  8788. GetProcAddress(w32net->hIpHlpApi32, "IcmpCloseHandle");
  8789. w32net->IcmpSendEcho =
  8790. (DWORD (__stdcall *)(HANDLE,IPAddr,LPVOID,WORD,PIP_OPTION_INFORMATION,LPVOID,DWORD,DWORD))
  8791. GetProcAddress(w32net->hIpHlpApi32, "IcmpSendEcho");
  8792. }
  8793. if (w32net->hIcmp != NULL)
  8794. {
  8795. if (w32net->IcmpCreateFile == NULL || w32net->IcmpCloseHandle == NULL || w32net->IcmpSendEcho == NULL)
  8796. {
  8797. w32net->IcmpCreateFile =
  8798. (HANDLE (__stdcall *)())
  8799. GetProcAddress(w32net->hIcmp, "IcmpCreateFile");
  8800. w32net->IcmpCloseHandle =
  8801. (BOOL (__stdcall *)(HANDLE))
  8802. GetProcAddress(w32net->hIcmp, "IcmpCloseHandle");
  8803. w32net->IcmpSendEcho =
  8804. (DWORD (__stdcall *)(HANDLE,IPAddr,LPVOID,WORD,PIP_OPTION_INFORMATION,LPVOID,DWORD,DWORD))
  8805. GetProcAddress(w32net->hIcmp, "IcmpSendEcho");
  8806. }
  8807. }
  8808. if (w32net->IcmpCreateFile == NULL || w32net->IcmpCloseHandle == NULL || w32net->IcmpSendEcho == NULL)
  8809. {
  8810. w32net->IcmpCreateFile = NULL;
  8811. w32net->IcmpCloseHandle = NULL;
  8812. w32net->IcmpSendEcho = NULL;
  8813. }
  8814. }
  8815. // Release of the socket library
  8816. void Win32FreeSocketLibrary()
  8817. {
  8818. if (w32net != NULL)
  8819. {
  8820. if (w32net->hIpHlpApi32 != NULL)
  8821. {
  8822. FreeLibrary(w32net->hIpHlpApi32);
  8823. }
  8824. if (w32net->hIcmp != NULL)
  8825. {
  8826. FreeLibrary(w32net->hIcmp);
  8827. }
  8828. Free(w32net);
  8829. w32net = NULL;
  8830. }
  8831. WSACleanup();
  8832. }
  8833. // Cancel
  8834. void Win32Cancel(CANCEL *c)
  8835. {
  8836. // Validate arguments
  8837. if (c == NULL)
  8838. {
  8839. return;
  8840. }
  8841. SetEvent((HANDLE)c->hEvent);
  8842. }
  8843. // Cleanup of the cancel object
  8844. void Win32CleanupCancel(CANCEL *c)
  8845. {
  8846. // Validate arguments
  8847. if (c == NULL)
  8848. {
  8849. return;
  8850. }
  8851. if (c->SpecialFlag == false)
  8852. {
  8853. CloseHandle(c->hEvent);
  8854. }
  8855. Free(c);
  8856. }
  8857. // New cancel object
  8858. CANCEL *Win32NewCancel()
  8859. {
  8860. CANCEL *c = ZeroMallocFast(sizeof(CANCEL));
  8861. c->ref = NewRef();
  8862. c->SpecialFlag = false;
  8863. c->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  8864. return c;
  8865. }
  8866. // Waiting for a socket event
  8867. bool Win32WaitSockEvent(SOCK_EVENT *event, UINT timeout)
  8868. {
  8869. // Validate arguments
  8870. if (event == NULL || timeout == 0)
  8871. {
  8872. return false;
  8873. }
  8874. if (WaitForSingleObject((HANDLE)event->hEvent, timeout) == WAIT_OBJECT_0)
  8875. {
  8876. return true;
  8877. }
  8878. else
  8879. {
  8880. return false;
  8881. }
  8882. }
  8883. // Clean-up of the socket event
  8884. void Win32CleanupSockEvent(SOCK_EVENT *event)
  8885. {
  8886. // Validate arguments
  8887. if (event == NULL)
  8888. {
  8889. return;
  8890. }
  8891. CloseHandle((HANDLE)event->hEvent);
  8892. Free(event);
  8893. }
  8894. // Set of the socket event
  8895. void Win32SetSockEvent(SOCK_EVENT *event)
  8896. {
  8897. // Validate arguments
  8898. if (event == NULL)
  8899. {
  8900. return;
  8901. }
  8902. SetEvent((HANDLE)event->hEvent);
  8903. }
  8904. // Creating a socket event
  8905. SOCK_EVENT *Win32NewSockEvent()
  8906. {
  8907. SOCK_EVENT *e = ZeroMallocFast(sizeof(SOCK_EVENT));
  8908. e->ref = NewRef();
  8909. e->hEvent = (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  8910. return e;
  8911. }
  8912. // Associate the socket with socket event and set it to asynchronous mode
  8913. void Win32JoinSockToSockEvent(SOCK *sock, SOCK_EVENT *event)
  8914. {
  8915. HANDLE hEvent;
  8916. // Validate arguments
  8917. if (sock == NULL || event == NULL || sock->AsyncMode)
  8918. {
  8919. return;
  8920. }
  8921. if (sock->ListenMode != false || (sock->Type != SOCK_UDP && sock->Connected == false))
  8922. {
  8923. return;
  8924. }
  8925. sock->AsyncMode = true;
  8926. hEvent = event->hEvent;
  8927. // Association
  8928. WSAEventSelect(sock->socket, hEvent, FD_READ | FD_WRITE | FD_CLOSE);
  8929. // Increase the reference count of the SOCK_EVENT
  8930. AddRef(event->ref);
  8931. sock->SockEvent = event;
  8932. }
  8933. // Set the socket to asynchronous mode
  8934. void Win32InitAsyncSocket(SOCK *sock)
  8935. {
  8936. // Validate arguments
  8937. if (sock == NULL)
  8938. {
  8939. return;
  8940. }
  8941. if (sock->AsyncMode)
  8942. {
  8943. // This socket is already in asynchronous mode
  8944. return;
  8945. }
  8946. if (sock->ListenMode || ((sock->Type == SOCK_TCP || sock->Type == SOCK_INPROC) && sock->Connected == false))
  8947. {
  8948. return;
  8949. }
  8950. sock->AsyncMode = true;
  8951. if (sock->Type == SOCK_INPROC)
  8952. {
  8953. // Fetch the event of the TUBE
  8954. TUBE *t = sock->RecvTube;
  8955. if (t != NULL)
  8956. {
  8957. if (t->SockEvent != NULL)
  8958. {
  8959. sock->hEvent = t->SockEvent->hEvent;
  8960. }
  8961. }
  8962. }
  8963. else
  8964. {
  8965. // Creating an Event
  8966. sock->hEvent = (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  8967. // Association
  8968. WSAEventSelect(sock->socket, sock->hEvent, FD_READ | FD_WRITE | FD_CLOSE);
  8969. }
  8970. }
  8971. // Release the asynchronous socket
  8972. void Win32FreeAsyncSocket(SOCK *sock)
  8973. {
  8974. // Validate arguments
  8975. if (sock == NULL)
  8976. {
  8977. return;
  8978. }
  8979. // Asynchronous socket
  8980. if (sock->hEvent != NULL)
  8981. {
  8982. if (sock->Type != SOCK_INPROC)
  8983. {
  8984. CloseHandle((HANDLE)sock->hEvent);
  8985. }
  8986. }
  8987. sock->hEvent = NULL;
  8988. sock->AsyncMode = false;
  8989. // Socket event
  8990. if (sock->SockEvent != NULL)
  8991. {
  8992. ReleaseSockEvent(sock->SockEvent);
  8993. sock->SockEvent = NULL;
  8994. }
  8995. }
  8996. // Select function for Win32
  8997. void Win32Select(SOCKSET *set, UINT timeout, CANCEL *c1, CANCEL *c2)
  8998. {
  8999. HANDLE array[MAXIMUM_WAIT_OBJECTS];
  9000. UINT n, i;
  9001. SOCK *s;
  9002. // Initialization of array
  9003. Zero(array, sizeof(array));
  9004. n = 0;
  9005. // Setting the event array
  9006. if (set != NULL)
  9007. {
  9008. for (i = 0;i < set->NumSocket;i++)
  9009. {
  9010. s = set->Sock[i];
  9011. if (s != NULL)
  9012. {
  9013. Win32InitAsyncSocket(s);
  9014. if (s->hEvent != NULL)
  9015. {
  9016. array[n++] = (HANDLE)s->hEvent;
  9017. }
  9018. if (s->BulkRecvTube != NULL)
  9019. {
  9020. array[n++] = (HANDLE)s->BulkRecvTube->SockEvent->hEvent;
  9021. }
  9022. }
  9023. }
  9024. }
  9025. if (c1 != NULL && c1->hEvent != NULL)
  9026. {
  9027. array[n++] = c1->hEvent;
  9028. }
  9029. if (c2 != NULL && c2->hEvent != NULL)
  9030. {
  9031. array[n++] = c2->hEvent;
  9032. }
  9033. if (timeout == 0)
  9034. {
  9035. return;
  9036. }
  9037. if (n == 0)
  9038. {
  9039. // Call normal waiting function if no events to wait are registered
  9040. SleepThread(timeout);
  9041. }
  9042. else
  9043. {
  9044. // Wait for the event if events are registered at least one
  9045. if (n == 1)
  9046. {
  9047. // Calling a lightweight version If the event is only one
  9048. WaitForSingleObject(array[0], timeout);
  9049. }
  9050. else
  9051. {
  9052. // In case of multiple events
  9053. WaitForMultipleObjects(n, array, false, timeout);
  9054. }
  9055. }
  9056. }
  9057. #endif // OS_WIN32
  9058. // Check whether the IPv6 is supported
  9059. bool IsIPv6Supported()
  9060. {
  9061. #ifdef NO_IPV6
  9062. return false;
  9063. #else // NO_IPV6
  9064. SOCKET s;
  9065. s = socket(AF_INET6, SOCK_STREAM, 0);
  9066. if (s == INVALID_SOCKET)
  9067. {
  9068. return false;
  9069. }
  9070. closesocket(s);
  9071. return true;
  9072. #endif // NO_IPV6
  9073. }
  9074. // Get the host name from the host cache
  9075. bool GetHostCache(char *hostname, UINT size, IP *ip)
  9076. {
  9077. bool ret;
  9078. // Validate arguments
  9079. if (hostname == NULL || ip == NULL)
  9080. {
  9081. return false;
  9082. }
  9083. ret = false;
  9084. LockList(HostCacheList);
  9085. {
  9086. HOSTCACHE t, *c;
  9087. Zero(&t, sizeof(t));
  9088. Copy(&t.IpAddress, ip, sizeof(IP));
  9089. c = Search(HostCacheList, &t);
  9090. if (c != NULL)
  9091. {
  9092. if (IsEmptyStr(c->HostName) == false)
  9093. {
  9094. ret = true;
  9095. StrCpy(hostname, size, c->HostName);
  9096. }
  9097. else
  9098. {
  9099. ret = true;
  9100. StrCpy(hostname, size, "");
  9101. }
  9102. }
  9103. }
  9104. UnlockList(HostCacheList);
  9105. return ret;
  9106. }
  9107. // Add to the host name cache
  9108. void AddHostCache(IP *ip, char *hostname)
  9109. {
  9110. // Validate arguments
  9111. if (ip == NULL || hostname == NULL)
  9112. {
  9113. return;
  9114. }
  9115. if (IsNetworkNameCacheEnabled() == false)
  9116. {
  9117. return;
  9118. }
  9119. LockList(HostCacheList);
  9120. {
  9121. HOSTCACHE t, *c;
  9122. UINT i;
  9123. LIST *o;
  9124. Zero(&t, sizeof(t));
  9125. Copy(&t.IpAddress, ip, sizeof(IP));
  9126. c = Search(HostCacheList, &t);
  9127. if (c == NULL)
  9128. {
  9129. c = ZeroMalloc(sizeof(HOSTCACHE));
  9130. Copy(&c->IpAddress, ip, sizeof(IP));
  9131. Add(HostCacheList, c);
  9132. }
  9133. StrCpy(c->HostName, sizeof(c->HostName), hostname);
  9134. c->Expires = Tick64() + (UINT64)EXPIRES_HOSTNAME;
  9135. o = NewListFast(NULL);
  9136. for (i = 0;i < LIST_NUM(HostCacheList);i++)
  9137. {
  9138. HOSTCACHE *c = LIST_DATA(HostCacheList, i);
  9139. if (c->Expires <= Tick64())
  9140. {
  9141. Add(o, c);
  9142. }
  9143. }
  9144. for (i = 0;i < LIST_NUM(o);i++)
  9145. {
  9146. HOSTCACHE *c = LIST_DATA(o, i);
  9147. if (Delete(HostCacheList, c))
  9148. {
  9149. Free(c);
  9150. }
  9151. }
  9152. ReleaseList(o);
  9153. }
  9154. UnlockList(HostCacheList);
  9155. }
  9156. // Comparison of host name cache entries
  9157. int CompareHostCache(void *p1, void *p2)
  9158. {
  9159. HOSTCACHE *c1, *c2;
  9160. if (p1 == NULL || p2 == NULL)
  9161. {
  9162. return 0;
  9163. }
  9164. c1 = *(HOSTCACHE **)p1;
  9165. c2 = *(HOSTCACHE **)p2;
  9166. if (c1 == NULL || c2 == NULL)
  9167. {
  9168. return 0;
  9169. }
  9170. return CmpIpAddr(&c1->IpAddress, &c2->IpAddress);
  9171. }
  9172. // Release of the host name cache
  9173. void FreeHostCache()
  9174. {
  9175. UINT i;
  9176. for (i = 0;i < LIST_NUM(HostCacheList);i++)
  9177. {
  9178. HOSTCACHE *c = LIST_DATA(HostCacheList, i);
  9179. Free(c);
  9180. }
  9181. ReleaseList(HostCacheList);
  9182. HostCacheList = NULL;
  9183. }
  9184. // Initialization of the host name cache
  9185. void InitHostCache()
  9186. {
  9187. HostCacheList = NewList(CompareHostCache);
  9188. }
  9189. // Get the number of wait threads
  9190. UINT GetNumWaitThread()
  9191. {
  9192. UINT ret = 0;
  9193. LockList(WaitThreadList);
  9194. {
  9195. ret = LIST_NUM(WaitThreadList);
  9196. }
  9197. UnlockList(WaitThreadList);
  9198. return ret;
  9199. }
  9200. // Add the thread to the thread waiting list
  9201. void AddWaitThread(THREAD *t)
  9202. {
  9203. // Validate arguments
  9204. if (t == NULL)
  9205. {
  9206. return;
  9207. }
  9208. AddRef(t->ref);
  9209. LockList(WaitThreadList);
  9210. {
  9211. Add(WaitThreadList, t);
  9212. }
  9213. UnlockList(WaitThreadList);
  9214. }
  9215. // Remove the thread from the waiting list
  9216. void DelWaitThread(THREAD *t)
  9217. {
  9218. // Validate arguments
  9219. if (t == NULL)
  9220. {
  9221. return;
  9222. }
  9223. LockList(WaitThreadList);
  9224. {
  9225. if (Delete(WaitThreadList, t))
  9226. {
  9227. ReleaseThread(t);
  9228. }
  9229. }
  9230. UnlockList(WaitThreadList);
  9231. }
  9232. // Creating a thread waiting list
  9233. void InitWaitThread()
  9234. {
  9235. WaitThreadList = NewList(NULL);
  9236. }
  9237. // Release of the thread waiting list
  9238. void FreeWaitThread()
  9239. {
  9240. UINT i, num;
  9241. THREAD **threads;
  9242. LockList(WaitThreadList);
  9243. {
  9244. num = LIST_NUM(WaitThreadList);
  9245. threads = ToArray(WaitThreadList);
  9246. DeleteAll(WaitThreadList);
  9247. }
  9248. UnlockList(WaitThreadList);
  9249. for (i = 0;i < num;i++)
  9250. {
  9251. THREAD *t = threads[i];
  9252. WaitThread(t, INFINITE);
  9253. ReleaseThread(t);
  9254. }
  9255. Free(threads);
  9256. ReleaseList(WaitThreadList);
  9257. WaitThreadList = NULL;
  9258. }
  9259. // Check the cipher list name
  9260. bool CheckCipherListName(char *name)
  9261. {
  9262. UINT i;
  9263. // Validate arguments
  9264. if (name == NULL)
  9265. {
  9266. return false;
  9267. }
  9268. for (i = 0;i < cipher_list_token->NumTokens;i++)
  9269. {
  9270. if (StrCmpi(cipher_list_token->Token[i], name) == 0)
  9271. {
  9272. return true;
  9273. }
  9274. }
  9275. return false;
  9276. }
  9277. // Renewing the IP address of the DHCP server
  9278. void RenewDhcp()
  9279. {
  9280. #ifdef OS_WIN32
  9281. Win32RenewDhcp();
  9282. #else
  9283. UnixRenewDhcp();
  9284. #endif
  9285. }
  9286. // Get a domain name for UNIX
  9287. bool UnixGetDomainName(char *name, UINT size)
  9288. {
  9289. bool ret = false;
  9290. BUF *b = ReadDump("/etc/resolv.conf");
  9291. if (b == NULL)
  9292. {
  9293. return false;
  9294. }
  9295. while (true)
  9296. {
  9297. char *s = CfgReadNextLine(b);
  9298. TOKEN_LIST *t;
  9299. if (s == NULL)
  9300. {
  9301. break;
  9302. }
  9303. Trim(s);
  9304. t = ParseToken(s, " \t");
  9305. if (t != NULL)
  9306. {
  9307. if (t->NumTokens == 2)
  9308. {
  9309. if (StrCmpi(t->Token[0], "domain") == 0)
  9310. {
  9311. StrCpy(name, size, t->Token[1]);
  9312. ret = true;
  9313. }
  9314. }
  9315. FreeToken(t);
  9316. }
  9317. Free(s);
  9318. }
  9319. FreeBuf(b);
  9320. return ret;
  9321. }
  9322. // Get the domain name
  9323. bool GetDomainName(char *name, UINT size)
  9324. {
  9325. bool ret = false;
  9326. IP ip;
  9327. // Validate arguments
  9328. ClearStr(name, size);
  9329. if (name == NULL)
  9330. {
  9331. return false;
  9332. }
  9333. #ifdef OS_WIN32
  9334. ClearStr(name, size);
  9335. ret = Win32GetDefaultDns(&ip, name, size);
  9336. if (ret == false || IsEmptyStr(name))
  9337. {
  9338. ret = Win32GetDnsSuffix(name, size);
  9339. }
  9340. #else // OS_WIN32
  9341. ret = UnixGetDomainName(name, size);
  9342. #endif // OS_WIN32
  9343. if (ret == false)
  9344. {
  9345. return false;
  9346. }
  9347. return (IsEmptyStr(name) ? false : true);
  9348. }
  9349. // Get the default DNS server
  9350. bool GetDefaultDns(IP *ip)
  9351. {
  9352. bool ret = false;
  9353. #ifdef OS_WIN32
  9354. ret = Win32GetDefaultDns(ip, NULL, 0);
  9355. #else
  9356. ret = UnixGetDefaultDns(ip);
  9357. #endif // OS_WIN32
  9358. return ret;
  9359. }
  9360. // Creating a socket event
  9361. SOCK_EVENT *NewSockEvent()
  9362. {
  9363. SOCK_EVENT *e = NULL;
  9364. #ifdef OS_WIN32
  9365. e = Win32NewSockEvent();
  9366. #else
  9367. e = UnixNewSockEvent();
  9368. #endif // OS_WIN32
  9369. return e;
  9370. }
  9371. // Set of the socket event
  9372. void SetSockEvent(SOCK_EVENT *event)
  9373. {
  9374. #ifdef OS_WIN32
  9375. Win32SetSockEvent(event);
  9376. #else
  9377. UnixSetSockEvent(event);
  9378. #endif // OS_WIN32
  9379. }
  9380. // Clean-up of the socket event
  9381. void CleanupSockEvent(SOCK_EVENT *event)
  9382. {
  9383. #ifdef OS_WIN32
  9384. Win32CleanupSockEvent(event);
  9385. #else
  9386. UnixCleanupSockEvent(event);
  9387. #endif // OS_WIN32
  9388. }
  9389. // Waiting for the socket event
  9390. bool WaitSockEvent(SOCK_EVENT *event, UINT timeout)
  9391. {
  9392. bool ret = false;
  9393. #ifdef OS_WIN32
  9394. ret = Win32WaitSockEvent(event, timeout);
  9395. #else
  9396. ret = UnixWaitSockEvent(event, timeout);
  9397. #endif // OS_WIN32
  9398. return ret;
  9399. }
  9400. // Release of the socket event
  9401. void ReleaseSockEvent(SOCK_EVENT *event)
  9402. {
  9403. // Validate arguments
  9404. if (event == NULL)
  9405. {
  9406. return;
  9407. }
  9408. if (Release(event->ref) == 0)
  9409. {
  9410. CleanupSockEvent(event);
  9411. }
  9412. }
  9413. // Let belonging the socket to the socket event
  9414. void JoinSockToSockEvent(SOCK *sock, SOCK_EVENT *event)
  9415. {
  9416. // Validate arguments
  9417. if (sock == NULL || event == NULL)
  9418. {
  9419. return;
  9420. }
  9421. if (sock->Type == SOCK_INPROC)
  9422. {
  9423. // Set the SockEvent on the receiver TUBE for in-process type socket
  9424. SetTubeSockEvent(sock->RecvTube, event);
  9425. return;
  9426. }
  9427. if (sock->BulkRecvTube != NULL)
  9428. {
  9429. // Set the SockEvent on the receiver TUBE in case of R-UDP socket
  9430. SetTubeSockEvent(sock->BulkRecvTube, event);
  9431. }
  9432. #ifdef OS_WIN32
  9433. Win32JoinSockToSockEvent(sock, event);
  9434. #else
  9435. UnixJoinSockToSockEvent(sock, event);
  9436. #endif // OS_WIN32
  9437. }
  9438. // New special cancel object
  9439. CANCEL *NewCancelSpecial(void *hEvent)
  9440. {
  9441. CANCEL *c;
  9442. // Validate arguments
  9443. if (hEvent == NULL)
  9444. {
  9445. return NULL;
  9446. }
  9447. c = ZeroMalloc(sizeof(CANCEL));
  9448. c->ref = NewRef();
  9449. c->SpecialFlag = true;
  9450. #ifdef OS_WIN32
  9451. c->hEvent = (HANDLE)hEvent;
  9452. #else // OS_WIN32
  9453. c->pipe_read = (int)hEvent;
  9454. c->pipe_write = -1;
  9455. #endif // OS_WIN32
  9456. return c;
  9457. }
  9458. // Creating a cancel object
  9459. CANCEL *NewCancel()
  9460. {
  9461. CANCEL *c = NULL;
  9462. #ifdef OS_WIN32
  9463. c = Win32NewCancel();
  9464. #else
  9465. c = UnixNewCancel();
  9466. #endif // OS_WIN32
  9467. return c;
  9468. }
  9469. // Release of the cancel object
  9470. void ReleaseCancel(CANCEL *c)
  9471. {
  9472. // Validate arguments
  9473. if (c == NULL)
  9474. {
  9475. return;
  9476. }
  9477. if (Release(c->ref) == 0)
  9478. {
  9479. CleanupCancel(c);
  9480. }
  9481. }
  9482. // Clean up of the cancel object
  9483. void CleanupCancel(CANCEL *c)
  9484. {
  9485. #ifdef OS_WIN32
  9486. Win32CleanupCancel(c);
  9487. #else
  9488. UnixCleanupCancel(c);
  9489. #endif
  9490. }
  9491. // Cancellation triggered
  9492. void Cancel(CANCEL *c)
  9493. {
  9494. #ifdef OS_WIN32
  9495. Win32Cancel(c);
  9496. #else
  9497. UnixCancel(c);
  9498. #endif
  9499. }
  9500. // Calculate the optimal route from the specified routing table
  9501. ROUTE_ENTRY *GetBestRouteEntryFromRouteTable(ROUTE_TABLE *table, IP *ip)
  9502. {
  9503. return GetBestRouteEntryFromRouteTableEx(table, ip, 0);
  9504. }
  9505. ROUTE_ENTRY *GetBestRouteEntryFromRouteTableEx(ROUTE_TABLE *table, IP *ip, UINT exclude_if_id)
  9506. {
  9507. UINT i;
  9508. ROUTE_ENTRY *ret = NULL;
  9509. ROUTE_ENTRY *tmp = NULL;
  9510. UINT64 min_score = 0;
  9511. // Validate arguments
  9512. if (ip == NULL || table == NULL)
  9513. {
  9514. return NULL;
  9515. }
  9516. if (IsIP6(ip))
  9517. {
  9518. // IPv6 is not supported
  9519. return NULL;
  9520. }
  9521. // Select routing table entry by following rule
  9522. // 1. Largest subnet mask
  9523. // 2. Smallest metric value
  9524. for (i = 0;i < table->NumEntry;i++)
  9525. {
  9526. ROUTE_ENTRY *e = table->Entry[i];
  9527. UINT dest, net, mask;
  9528. dest = IPToUINT(ip);
  9529. net = IPToUINT(&e->DestIP);
  9530. mask = IPToUINT(&e->DestMask);
  9531. if (exclude_if_id != 0)
  9532. {
  9533. if (e->InterfaceID == exclude_if_id)
  9534. {
  9535. continue;
  9536. }
  9537. }
  9538. // Mask test
  9539. if ((dest & mask) == (net & mask))
  9540. {
  9541. // Calculate the score
  9542. UINT score_high32 = mask;
  9543. UINT score_low32 = 0xFFFFFFFF - e->Metric;
  9544. UINT64 score64 = (UINT64)score_high32 * (UINT64)0x80000000 * (UINT64)2 + (UINT64)score_low32;
  9545. if (score64 == 0)
  9546. {
  9547. score64 = 1;
  9548. }
  9549. e->InnerScore = score64;
  9550. }
  9551. }
  9552. tmp = NULL;
  9553. // Search for the item with maximum score
  9554. for (i = 0;i < table->NumEntry;i++)
  9555. {
  9556. ROUTE_ENTRY *e = table->Entry[i];
  9557. if (e->InnerScore != 0)
  9558. {
  9559. if (e->InnerScore >= min_score)
  9560. {
  9561. tmp = e;
  9562. min_score = e->InnerScore;
  9563. }
  9564. }
  9565. }
  9566. if (tmp != NULL)
  9567. {
  9568. UINT dest, gateway, mask;
  9569. // Generate an entry
  9570. ret = ZeroMallocFast(sizeof(ROUTE_ENTRY));
  9571. Copy(&ret->DestIP, ip, sizeof(IP));
  9572. ret->DestMask.addr[0] = 255;
  9573. ret->DestMask.addr[1] = 255;
  9574. ret->DestMask.addr[2] = 255;
  9575. ret->DestMask.addr[3] = 255;
  9576. Copy(&ret->GatewayIP, &tmp->GatewayIP, sizeof(IP));
  9577. ret->InterfaceID = tmp->InterfaceID;
  9578. ret->LocalRouting = tmp->LocalRouting;
  9579. ret->OldIfMetric = tmp->Metric;
  9580. ret->Metric = 1;
  9581. ret->PPPConnection = tmp->PPPConnection;
  9582. // Calculation related to routing control
  9583. dest = IPToUINT(&tmp->DestIP);
  9584. gateway = IPToUINT(&tmp->GatewayIP);
  9585. mask = IPToUINT(&tmp->DestMask);
  9586. if ((dest & mask) == (gateway & mask))
  9587. {
  9588. #ifdef OS_WIN32
  9589. if (MsIsVista() == false)
  9590. {
  9591. // Adjust for Windows
  9592. ret->PPPConnection = true;
  9593. }
  9594. #endif // OS_WIN32
  9595. }
  9596. }
  9597. return ret;
  9598. }
  9599. // Release the routing entry
  9600. void FreeRouteEntry(ROUTE_ENTRY *e)
  9601. {
  9602. // Validate arguments
  9603. if (e == NULL)
  9604. {
  9605. return;
  9606. }
  9607. Free(e);
  9608. }
  9609. // Get the best route entry by analyzing the current routing table
  9610. ROUTE_ENTRY *GetBestRouteEntry(IP *ip)
  9611. {
  9612. return GetBestRouteEntryEx(ip, 0);
  9613. }
  9614. ROUTE_ENTRY *GetBestRouteEntryEx(IP *ip, UINT exclude_if_id)
  9615. {
  9616. ROUTE_TABLE *table;
  9617. ROUTE_ENTRY *e = NULL;
  9618. // Validate arguments
  9619. if (ip == NULL)
  9620. {
  9621. return NULL;
  9622. }
  9623. table = GetRouteTable();
  9624. if (table == NULL)
  9625. {
  9626. return NULL;
  9627. }
  9628. e = GetBestRouteEntryFromRouteTableEx(table, ip, exclude_if_id);
  9629. FreeRouteTable(table);
  9630. return e;
  9631. }
  9632. // Get the interface ID of the virtual LAN card
  9633. UINT GetVLanInterfaceID(char *tag_name)
  9634. {
  9635. UINT ret = 0;
  9636. #ifdef OS_WIN32
  9637. ret = Win32GetVLanInterfaceID(tag_name);
  9638. #else // OS_WIN32
  9639. ret = UnixGetVLanInterfaceID(tag_name);
  9640. #endif // OS_WIN32
  9641. return ret;
  9642. }
  9643. // Release of enumeration variable of virtual LAN card
  9644. void FreeEnumVLan(char **s)
  9645. {
  9646. char *a;
  9647. UINT i;
  9648. // Validate arguments
  9649. if (s == NULL)
  9650. {
  9651. return;
  9652. }
  9653. i = 0;
  9654. while (true)
  9655. {
  9656. a = s[i++];
  9657. if (a == NULL)
  9658. {
  9659. break;
  9660. }
  9661. Free(a);
  9662. }
  9663. Free(s);
  9664. }
  9665. // Enumeration of virtual LAN cards
  9666. char **EnumVLan(char *tag_name)
  9667. {
  9668. char **ret = NULL;
  9669. #ifdef OS_WIN32
  9670. ret = Win32EnumVLan(tag_name);
  9671. #else // OS_WIN32
  9672. ret = UnixEnumVLan(tag_name);
  9673. #endif // OS_WIN32
  9674. return ret;
  9675. }
  9676. // Display the routing table
  9677. void DebugPrintRouteTable(ROUTE_TABLE *r)
  9678. {
  9679. UINT i;
  9680. // Validate arguments
  9681. if (r == NULL)
  9682. {
  9683. return;
  9684. }
  9685. if (IsDebug() == false)
  9686. {
  9687. return;
  9688. }
  9689. Debug("---- Routing Table (%u Entries) ----\n", r->NumEntry);
  9690. for (i = 0;i < r->NumEntry;i++)
  9691. {
  9692. Debug(" ");
  9693. DebugPrintRoute(r->Entry[i]);
  9694. }
  9695. Debug("------------------------------------\n");
  9696. }
  9697. // Display the routing table entry
  9698. void DebugPrintRoute(ROUTE_ENTRY *e)
  9699. {
  9700. char tmp[MAX_SIZE];
  9701. // Validate arguments
  9702. if (e == NULL)
  9703. {
  9704. return;
  9705. }
  9706. if (IsDebug() == false)
  9707. {
  9708. return;
  9709. }
  9710. RouteToStr(tmp, sizeof(tmp), e);
  9711. Debug("%s\n", tmp);
  9712. }
  9713. // Convert the routing table entry to string
  9714. void RouteToStr(char *str, UINT str_size, ROUTE_ENTRY *e)
  9715. {
  9716. char dest_ip[MAX_PATH];
  9717. char dest_mask[MAX_PATH];
  9718. char gateway_ip[MAX_PATH];
  9719. // Validate arguments
  9720. if (str == NULL || e == NULL)
  9721. {
  9722. return;
  9723. }
  9724. IPToStr(dest_ip, sizeof(dest_ip), &e->DestIP);
  9725. IPToStr(dest_mask, sizeof(dest_mask), &e->DestMask);
  9726. IPToStr(gateway_ip, sizeof(gateway_ip), &e->GatewayIP);
  9727. Format(str, str_size, "%s/%s %s m=%u oif=%u if=%u lo=%u p=%u",
  9728. dest_ip, dest_mask, gateway_ip,
  9729. e->Metric, e->OldIfMetric, e->InterfaceID,
  9730. e->LocalRouting, e->PPPConnection);
  9731. }
  9732. // Delete the routing table
  9733. void DeleteRouteEntry(ROUTE_ENTRY *e)
  9734. {
  9735. Debug("DeleteRouteEntry();\n");
  9736. #ifdef OS_WIN32
  9737. Win32DeleteRouteEntry(e);
  9738. #else // OS_WIN32
  9739. UnixDeleteRouteEntry(e);
  9740. #endif
  9741. }
  9742. // Add to the routing table
  9743. bool AddRouteEntry(ROUTE_ENTRY *e)
  9744. {
  9745. bool dummy = false;
  9746. return AddRouteEntryEx(e, &dummy);
  9747. }
  9748. bool AddRouteEntryEx(ROUTE_ENTRY *e, bool *already_exists)
  9749. {
  9750. bool ret = false;
  9751. Debug("AddRouteEntryEx();\n");
  9752. #ifdef OS_WIN32
  9753. ret = Win32AddRouteEntry(e, already_exists);
  9754. #else // OS_WIN32
  9755. ret = UnixAddRouteEntry(e, already_exists);
  9756. #endif
  9757. return ret;
  9758. }
  9759. // Get the routing table
  9760. ROUTE_TABLE *GetRouteTable()
  9761. {
  9762. ROUTE_TABLE *t = NULL;
  9763. UINT i;
  9764. BUF *buf = NewBuf();
  9765. UCHAR hash[MD5_SIZE];
  9766. #ifdef OS_WIN32
  9767. t = Win32GetRouteTable();
  9768. #else //OS_WIN32
  9769. t = UnixGetRouteTable();
  9770. #endif // OS_WIN32
  9771. WriteBuf(buf, &t->NumEntry, sizeof(t->NumEntry));
  9772. for (i = 0;i < t->NumEntry;i++)
  9773. {
  9774. ROUTE_ENTRY *e = t->Entry[i];
  9775. WriteBuf(buf, e, sizeof(ROUTE_ENTRY));
  9776. }
  9777. Hash(hash, buf->Buf, buf->Size, false);
  9778. FreeBuf(buf);
  9779. Copy(&t->HashedValue, hash, sizeof(t->HashedValue));
  9780. return t;
  9781. }
  9782. // Release of the routing table
  9783. void FreeRouteTable(ROUTE_TABLE *t)
  9784. {
  9785. UINT i;
  9786. // Validate arguments
  9787. if (t == NULL)
  9788. {
  9789. return;
  9790. }
  9791. for (i = 0;i < t->NumEntry;i++)
  9792. {
  9793. Free(t->Entry[i]);
  9794. }
  9795. Free(t->Entry);
  9796. Free(t);
  9797. }
  9798. // UDP receiving
  9799. UINT RecvFrom(SOCK *sock, IP *src_addr, UINT *src_port, void *data, UINT size)
  9800. {
  9801. SOCKET s;
  9802. int ret, sz;
  9803. struct sockaddr_in addr;
  9804. // Validate arguments
  9805. if (sock != NULL)
  9806. {
  9807. sock->IgnoreRecvErr = false;
  9808. }
  9809. if (sock == NULL || src_addr == NULL || src_port == NULL || data == NULL)
  9810. {
  9811. return false;
  9812. }
  9813. if (sock->Type != SOCK_UDP || sock->socket == INVALID_SOCKET)
  9814. {
  9815. return false;
  9816. }
  9817. if (size == 0)
  9818. {
  9819. return false;
  9820. }
  9821. if (sock->IPv6)
  9822. {
  9823. return RecvFrom6(sock, src_addr, src_port, data, size);
  9824. }
  9825. s = sock->socket;
  9826. sz = sizeof(addr);
  9827. ret = recvfrom(s, data, size, 0, (struct sockaddr *)&addr, (int *)&sz);
  9828. if (ret > 0)
  9829. {
  9830. InAddrToIP(src_addr, &addr.sin_addr);
  9831. *src_port = (UINT)ntohs(addr.sin_port);
  9832. if (sock->IsRawSocket)
  9833. {
  9834. *src_port = sock->LocalPort;
  9835. /*
  9836. {
  9837. char tmp[MAX_SIZE];
  9838. IPToStr(tmp, sizeof(tmp), &sock->LocalIP);
  9839. Debug("Raw: %u from %s\n", sock->LocalPort, tmp);
  9840. }*/
  9841. }
  9842. Lock(sock->lock);
  9843. {
  9844. sock->RecvNum++;
  9845. sock->RecvSize += (UINT64)ret;
  9846. }
  9847. Unlock(sock->lock);
  9848. // Debug("UDP RecvFrom: %u\n", ret);
  9849. return (UINT)ret;
  9850. }
  9851. else
  9852. {
  9853. sock->IgnoreRecvErr = false;
  9854. #ifdef OS_WIN32
  9855. if (WSAGetLastError() == WSAECONNRESET || WSAGetLastError() == WSAENETRESET || WSAGetLastError() == WSAEMSGSIZE || WSAGetLastError() == WSAENETUNREACH ||
  9856. WSAGetLastError() == WSAENOBUFS || WSAGetLastError() == WSAEHOSTUNREACH || WSAGetLastError() == WSAEUSERS || WSAGetLastError() == WSAEADDRNOTAVAIL || WSAGetLastError() == WSAEADDRNOTAVAIL)
  9857. {
  9858. sock->IgnoreRecvErr = true;
  9859. }
  9860. else if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINPROGRESS)
  9861. {
  9862. return SOCK_LATER;
  9863. }
  9864. else
  9865. {
  9866. UINT e = WSAGetLastError();
  9867. // Debug("RecvFrom Error: %u\n", e);
  9868. }
  9869. #else // OS_WIN32
  9870. if (errno == ECONNREFUSED || errno == ECONNRESET || errno == EMSGSIZE || errno == ENOBUFS || errno == ENOMEM || errno == EINTR)
  9871. {
  9872. sock->IgnoreRecvErr = true;
  9873. }
  9874. else if (errno == EAGAIN)
  9875. {
  9876. return SOCK_LATER;
  9877. }
  9878. #endif // OS_WIN32
  9879. return 0;
  9880. }
  9881. }
  9882. UINT RecvFrom6(SOCK *sock, IP *src_addr, UINT *src_port, void *data, UINT size)
  9883. {
  9884. SOCKET s;
  9885. int ret, sz;
  9886. struct sockaddr_in6 addr;
  9887. // Validate arguments
  9888. if (sock != NULL)
  9889. {
  9890. sock->IgnoreRecvErr = false;
  9891. }
  9892. if (sock == NULL || src_addr == NULL || src_port == NULL || data == NULL)
  9893. {
  9894. return false;
  9895. }
  9896. if (sock->Type != SOCK_UDP || sock->socket == INVALID_SOCKET)
  9897. {
  9898. return false;
  9899. }
  9900. if (size == 0)
  9901. {
  9902. return false;
  9903. }
  9904. s = sock->socket;
  9905. sz = sizeof(addr);
  9906. ret = recvfrom(s, data, size, 0, (struct sockaddr *)&addr, (int *)&sz);
  9907. if (ret > 0)
  9908. {
  9909. InAddrToIP6(src_addr, &addr.sin6_addr);
  9910. src_addr->ipv6_scope_id = addr.sin6_scope_id;
  9911. *src_port = (UINT)ntohs(addr.sin6_port);
  9912. if (sock->IsRawSocket)
  9913. {
  9914. *src_port = sock->LocalPort;
  9915. }
  9916. Lock(sock->lock);
  9917. {
  9918. sock->RecvNum++;
  9919. sock->RecvSize += (UINT64)ret;
  9920. }
  9921. Unlock(sock->lock);
  9922. // Debug("UDP RecvFrom: %u\n", ret);
  9923. return (UINT)ret;
  9924. }
  9925. else
  9926. {
  9927. sock->IgnoreRecvErr = false;
  9928. #ifdef OS_WIN32
  9929. if (WSAGetLastError() == WSAECONNRESET || WSAGetLastError() == WSAENETRESET || WSAGetLastError() == WSAEMSGSIZE || WSAGetLastError() == WSAENETUNREACH ||
  9930. WSAGetLastError() == WSAENOBUFS || WSAGetLastError() == WSAEHOSTUNREACH || WSAGetLastError() == WSAEUSERS || WSAGetLastError() == WSAEADDRNOTAVAIL || WSAGetLastError() == WSAEADDRNOTAVAIL)
  9931. {
  9932. sock->IgnoreRecvErr = true;
  9933. }
  9934. else if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINPROGRESS)
  9935. {
  9936. return SOCK_LATER;
  9937. }
  9938. else
  9939. {
  9940. UINT e = WSAGetLastError();
  9941. // Debug("RecvFrom Error: %u\n", e);
  9942. }
  9943. #else // OS_WIN32
  9944. if (errno == ECONNREFUSED || errno == ECONNRESET || errno == EMSGSIZE || errno == ENOBUFS || errno == ENOMEM || errno == EINTR)
  9945. {
  9946. sock->IgnoreRecvErr = true;
  9947. }
  9948. else if (errno == EAGAIN)
  9949. {
  9950. return SOCK_LATER;
  9951. }
  9952. #endif // OS_WIN32
  9953. return 0;
  9954. }
  9955. }
  9956. // Lock the OpenSSL
  9957. void LockOpenSSL()
  9958. {
  9959. Lock(openssl_lock);
  9960. }
  9961. // Unlock the OpenSSL
  9962. void UnlockOpenSSL()
  9963. {
  9964. Unlock(openssl_lock);
  9965. }
  9966. // UDP transmission
  9967. UINT SendTo(SOCK *sock, IP *dest_addr, UINT dest_port, void *data, UINT size)
  9968. {
  9969. return SendToEx(sock, dest_addr, dest_port, data, size, false);
  9970. }
  9971. UINT SendToEx(SOCK *sock, IP *dest_addr, UINT dest_port, void *data, UINT size, bool broadcast)
  9972. {
  9973. SOCKET s;
  9974. int ret;
  9975. struct sockaddr_in addr;
  9976. // Validate arguments
  9977. if (sock != NULL)
  9978. {
  9979. sock->IgnoreSendErr = false;
  9980. }
  9981. if (sock == NULL || dest_addr == NULL || (sock->IsRawSocket == false && dest_port == 0) || data == NULL)
  9982. {
  9983. return 0;
  9984. }
  9985. if (dest_port >= 65536 && sock->IsRawSocket == false)
  9986. {
  9987. return 0;
  9988. }
  9989. if (sock->Type != SOCK_UDP || sock->socket == INVALID_SOCKET)
  9990. {
  9991. return 0;
  9992. }
  9993. if (size == 0)
  9994. {
  9995. return 0;
  9996. }
  9997. if (sock->IPv6)
  9998. {
  9999. return SendTo6Ex(sock, dest_addr, dest_port, data, size, broadcast);
  10000. }
  10001. if (IsIP4(dest_addr) == false)
  10002. {
  10003. return 0;
  10004. }
  10005. s = sock->socket;
  10006. Zero(&addr, sizeof(addr));
  10007. addr.sin_family = AF_INET;
  10008. if (sock->IsRawSocket == false)
  10009. {
  10010. addr.sin_port = htons((USHORT)dest_port);
  10011. }
  10012. IPToInAddr(&addr.sin_addr, dest_addr);
  10013. if ((dest_addr->addr[0] == 255 && dest_addr->addr[1] == 255 &&
  10014. dest_addr->addr[2] == 255 && dest_addr->addr[3] == 255) ||
  10015. (dest_addr->addr[0] >= 224 && dest_addr->addr[0] <= 239)
  10016. || broadcast)
  10017. {
  10018. if (sock->UdpBroadcast == false)
  10019. {
  10020. bool yes = true;
  10021. sock->UdpBroadcast = true;
  10022. setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&yes, sizeof(yes));
  10023. }
  10024. }
  10025. ret = sendto(s, data, size, 0, (struct sockaddr *)&addr, sizeof(addr));
  10026. if (ret != (int)size)
  10027. {
  10028. sock->IgnoreSendErr = false;
  10029. #ifdef OS_WIN32
  10030. if (WSAGetLastError() == WSAECONNRESET || WSAGetLastError() == WSAENETRESET || WSAGetLastError() == WSAEMSGSIZE || WSAGetLastError() == WSAENETUNREACH ||
  10031. WSAGetLastError() == WSAENOBUFS || WSAGetLastError() == WSAEHOSTUNREACH || WSAGetLastError() == WSAEUSERS || WSAGetLastError() == WSAEINVAL || WSAGetLastError() == WSAEADDRNOTAVAIL)
  10032. {
  10033. sock->IgnoreSendErr = true;
  10034. }
  10035. else if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINPROGRESS)
  10036. {
  10037. return SOCK_LATER;
  10038. }
  10039. else
  10040. {
  10041. UINT e = WSAGetLastError();
  10042. Debug("SendTo Error; %u\n", e);
  10043. }
  10044. #else // OS_WIN32
  10045. if (errno == ECONNREFUSED || errno == ECONNRESET || errno == EMSGSIZE || errno == ENOBUFS || errno == ENOMEM || errno == EINTR)
  10046. {
  10047. sock->IgnoreSendErr = true;
  10048. }
  10049. else if (errno == EAGAIN)
  10050. {
  10051. return SOCK_LATER;
  10052. }
  10053. #endif // OS_WIN32
  10054. return 0;
  10055. }
  10056. Lock(sock->lock);
  10057. {
  10058. sock->SendSize += (UINT64)size;
  10059. sock->SendNum++;
  10060. }
  10061. Unlock(sock->lock);
  10062. return ret;
  10063. }
  10064. UINT SendTo6(SOCK *sock, IP *dest_addr, UINT dest_port, void *data, UINT size)
  10065. {
  10066. return SendTo6Ex(sock, dest_addr, dest_port, data, size, false);
  10067. }
  10068. UINT SendTo6Ex(SOCK *sock, IP *dest_addr, UINT dest_port, void *data, UINT size, bool broadcast)
  10069. {
  10070. SOCKET s;
  10071. int ret;
  10072. struct sockaddr_in6 addr;
  10073. UINT type;
  10074. // Validate arguments
  10075. if (sock != NULL)
  10076. {
  10077. sock->IgnoreSendErr = false;
  10078. }
  10079. if (sock == NULL || dest_addr == NULL || (sock->IsRawSocket == false && dest_port == 0) || data == NULL)
  10080. {
  10081. return 0;
  10082. }
  10083. if (dest_port >= 65536 && sock->IsRawSocket == false)
  10084. {
  10085. return 0;
  10086. }
  10087. if (sock->Type != SOCK_UDP || sock->socket == INVALID_SOCKET)
  10088. {
  10089. return 0;
  10090. }
  10091. if (size == 0)
  10092. {
  10093. return 0;
  10094. }
  10095. if (IsIP6(dest_addr) == false)
  10096. {
  10097. return 0;
  10098. }
  10099. s = sock->socket;
  10100. Zero(&addr, sizeof(addr));
  10101. addr.sin6_family = AF_INET6;
  10102. if (sock->IsRawSocket == false)
  10103. {
  10104. addr.sin6_port = htons((USHORT)dest_port);
  10105. }
  10106. IPToInAddr6(&addr.sin6_addr, dest_addr);
  10107. addr.sin6_scope_id = dest_addr->ipv6_scope_id;
  10108. type = GetIPAddrType6(dest_addr);
  10109. if ((type & IPV6_ADDR_MULTICAST) || broadcast)
  10110. {
  10111. if (sock->UdpBroadcast == false)
  10112. {
  10113. bool yes = true;
  10114. sock->UdpBroadcast = true;
  10115. setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&yes, sizeof(yes));
  10116. }
  10117. }
  10118. ret = sendto(s, data, size, 0, (struct sockaddr *)&addr, sizeof(addr));
  10119. if (ret != (int)size)
  10120. {
  10121. sock->IgnoreSendErr = false;
  10122. #ifdef OS_WIN32
  10123. if (WSAGetLastError() == WSAECONNRESET || WSAGetLastError() == WSAENETRESET || WSAGetLastError() == WSAEMSGSIZE || WSAGetLastError() == WSAENETUNREACH ||
  10124. WSAGetLastError() == WSAENOBUFS || WSAGetLastError() == WSAEHOSTUNREACH || WSAGetLastError() == WSAEUSERS || WSAGetLastError() == WSAEINVAL || WSAGetLastError() == WSAEADDRNOTAVAIL)
  10125. {
  10126. sock->IgnoreSendErr = true;
  10127. }
  10128. else if (WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINPROGRESS)
  10129. {
  10130. return SOCK_LATER;
  10131. }
  10132. else
  10133. {
  10134. UINT e = WSAGetLastError();
  10135. }
  10136. #else // OS_WIN32
  10137. if (errno == ECONNREFUSED || errno == ECONNRESET || errno == EMSGSIZE || errno == ENOBUFS || errno == ENOMEM || errno == EINTR)
  10138. {
  10139. sock->IgnoreSendErr = true;
  10140. }
  10141. else if (errno == EAGAIN)
  10142. {
  10143. return SOCK_LATER;
  10144. }
  10145. #endif // OS_WIN32
  10146. return 0;
  10147. }
  10148. Lock(sock->lock);
  10149. {
  10150. sock->SendSize += (UINT64)size;
  10151. sock->SendNum++;
  10152. }
  10153. Unlock(sock->lock);
  10154. return ret;
  10155. }
  10156. // Disable the UDP checksum
  10157. void DisableUDPChecksum(SOCK *s)
  10158. {
  10159. bool true_flag = true;
  10160. // Validate arguments
  10161. if (s == NULL || s->Type != SOCK_UDP)
  10162. {
  10163. return;
  10164. }
  10165. if (s->socket != INVALID_SOCKET)
  10166. {
  10167. if (s->IPv6 == false)
  10168. {
  10169. #ifdef UDP_NOCHECKSUM
  10170. setsockopt(s->socket, IPPROTO_UDP, UDP_NOCHECKSUM, (char *)&true_flag, sizeof(bool));
  10171. #endif // UDP_NOCHECKSUM
  10172. }
  10173. }
  10174. }
  10175. // Set the socket to asynchronous mode
  10176. void InitAsyncSocket(SOCK *sock)
  10177. {
  10178. #ifdef OS_WIN32
  10179. Win32InitAsyncSocket(sock);
  10180. #else // OS_WIN32
  10181. UnixInitAsyncSocket(sock);
  10182. #endif // OS_WIN32
  10183. }
  10184. // Get a new available UDP port number
  10185. UINT GetNewAvailableUdpPortRand()
  10186. {
  10187. UINT num_retry = 8;
  10188. UINT i;
  10189. UINT ret = 0;
  10190. UCHAR seed[SHA1_SIZE];
  10191. Rand(seed, sizeof(seed));
  10192. for (i = 0;i < num_retry;i++)
  10193. {
  10194. SOCK *s = NewUDPEx2Rand(false, NULL, seed, sizeof(seed), RAND_UDP_PORT_DEFAULT_NUM_RETRY);
  10195. if (s != NULL)
  10196. {
  10197. ret = s->LocalPort;
  10198. Disconnect(s);
  10199. ReleaseSock(s);
  10200. }
  10201. if (ret != 0)
  10202. {
  10203. break;
  10204. }
  10205. }
  10206. return ret;
  10207. }
  10208. // Open a UDP port (port number is random, but determine the randomness in the seed)
  10209. SOCK *NewUDPEx2Rand(bool ipv6, IP *ip, void *rand_seed, UINT rand_seed_size, UINT num_retry)
  10210. {
  10211. UINT i;
  10212. // Validate arguments
  10213. if (rand_seed == NULL || rand_seed_size == 0)
  10214. {
  10215. return NULL;
  10216. }
  10217. if (num_retry == 0)
  10218. {
  10219. num_retry = RAND_UDP_PORT_DEFAULT_NUM_RETRY;
  10220. }
  10221. for (i = 0; i < (num_retry + 1);i++)
  10222. {
  10223. BUF *buf = NewBuf();
  10224. UCHAR hash[SHA1_SIZE];
  10225. UINT port = 0;
  10226. SOCK *s;
  10227. WriteBuf(buf, rand_seed, rand_seed_size);
  10228. WriteBufInt(buf, i);
  10229. HashSha1(hash, buf->Buf, buf->Size);
  10230. FreeBuf(buf);
  10231. port = READ_UINT(hash);
  10232. port = RAND_UDP_PORT_START + (port % (RAND_UDP_PORT_END - RAND_UDP_PORT_START));
  10233. s = NewUDPEx2(port, ipv6, ip);
  10234. if (s != NULL)
  10235. {
  10236. return s;
  10237. }
  10238. }
  10239. return NewUDPEx2(0, ipv6, ip);
  10240. }
  10241. // Generate a random port number (based on the EXE path and machine key)
  10242. UINT NewRandPortByMachineAndExePath(UINT start_port, UINT end_port, UINT additional_int)
  10243. {
  10244. BUF *b;
  10245. char machine_name[MAX_SIZE];
  10246. wchar_t exe_path[MAX_PATH];
  10247. char *product_id = NULL;
  10248. UCHAR hash[SHA1_SIZE];
  10249. #ifdef OS_WIN32
  10250. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductId");
  10251. if (product_id == NULL)
  10252. {
  10253. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProductId");
  10254. }
  10255. #endif // OS_WIN32
  10256. b = NewBuf();
  10257. GetMachineHostName(machine_name, sizeof(machine_name));
  10258. Trim(machine_name);
  10259. StrUpper(machine_name);
  10260. GetExeNameW(exe_path, sizeof(exe_path));
  10261. UniTrim(exe_path);
  10262. UniStrUpper(exe_path);
  10263. WriteBuf(b, machine_name, StrSize(machine_name));
  10264. WriteBuf(b, exe_path, UniStrSize(exe_path));
  10265. WriteBuf(b, product_id, StrSize(product_id));
  10266. WriteBufInt(b, additional_int);
  10267. HashSha1(hash, b->Buf, b->Size);
  10268. FreeBuf(b);
  10269. Free(product_id);
  10270. return (READ_UINT(hash) % (end_port - start_port)) + start_port;
  10271. }
  10272. // Open the UDP port (based on the EXE path and machine key)
  10273. SOCK *NewUDPEx2RandMachineAndExePath(bool ipv6, IP *ip, UINT num_retry, UCHAR rand_port_id)
  10274. {
  10275. BUF *b;
  10276. char machine_name[MAX_SIZE];
  10277. wchar_t exe_path[MAX_PATH];
  10278. char *product_id = NULL;
  10279. UCHAR hash[SHA1_SIZE];
  10280. #ifdef OS_WIN32
  10281. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductId");
  10282. if (product_id == NULL)
  10283. {
  10284. product_id = MsRegReadStr(REG_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProductId");
  10285. }
  10286. #endif // OS_WIN32
  10287. b = NewBuf();
  10288. GetMachineHostName(machine_name, sizeof(machine_name));
  10289. Trim(machine_name);
  10290. StrUpper(machine_name);
  10291. GetExeNameW(exe_path, sizeof(exe_path));
  10292. UniTrim(exe_path);
  10293. UniStrUpper(exe_path);
  10294. WriteBuf(b, machine_name, StrSize(machine_name));
  10295. WriteBuf(b, exe_path, UniStrSize(exe_path));
  10296. WriteBuf(b, product_id, StrSize(product_id));
  10297. WriteBufChar(b, rand_port_id);
  10298. //WriteBufInt(b, GetHostIPAddressHash32());
  10299. HashSha1(hash, b->Buf, b->Size);
  10300. FreeBuf(b);
  10301. Free(product_id);
  10302. return NewUDPEx2Rand(ipv6, ip, hash, sizeof(hash), num_retry);
  10303. }
  10304. // Set the DF bit of the socket
  10305. void ClearSockDfBit(SOCK *s)
  10306. {
  10307. #ifdef IP_PMTUDISC_DONT
  10308. #ifdef IP_MTU_DISCOVER
  10309. UINT value = IP_PMTUDISC_DONT;
  10310. if (s == NULL)
  10311. {
  10312. return;
  10313. }
  10314. setsockopt(s->socket, IPPROTO_IP, IP_MTU_DISCOVER, (char *)&value, sizeof(value));
  10315. #endif // IP_MTU_DISCOVER
  10316. #endif // IP_PMTUDISC_DONT
  10317. }
  10318. // Set the header-include option
  10319. void SetRawSockHeaderIncludeOption(SOCK *s, bool enable)
  10320. {
  10321. UINT value = BOOL_TO_INT(enable);
  10322. if (s == NULL || s->IsRawSocket == false)
  10323. {
  10324. return;
  10325. }
  10326. setsockopt(s->socket, IPPROTO_IP, IP_HDRINCL, (char *)&value, sizeof(value));
  10327. s->RawIP_HeaderIncludeFlag = enable;
  10328. }
  10329. // Create and initialize the UDP socket
  10330. // If port is specified as 0, system assigns a certain port.
  10331. SOCK *NewUDP(UINT port)
  10332. {
  10333. return NewUDPEx(port, false);
  10334. }
  10335. SOCK *NewUDPEx(UINT port, bool ipv6)
  10336. {
  10337. return NewUDPEx2(port, ipv6, NULL);
  10338. }
  10339. SOCK *NewUDPEx2(UINT port, bool ipv6, IP *ip)
  10340. {
  10341. if (ipv6 == false)
  10342. {
  10343. return NewUDP4(port, ip);
  10344. }
  10345. else
  10346. {
  10347. return NewUDP6(port, ip);
  10348. }
  10349. }
  10350. SOCK *NewUDPEx3(UINT port, IP *ip)
  10351. {
  10352. // Validate arguments
  10353. if (ip == NULL)
  10354. {
  10355. return NewUDPEx2(port, false, NULL);
  10356. }
  10357. if (IsIP4(ip))
  10358. {
  10359. return NewUDPEx2(port, false, ip);
  10360. }
  10361. else
  10362. {
  10363. return NewUDPEx2(port, true, ip);
  10364. }
  10365. }
  10366. SOCK *NewUDP4(UINT port, IP *ip)
  10367. {
  10368. SOCK *sock;
  10369. SOCKET s;
  10370. struct sockaddr_in addr;
  10371. // Validate arguments
  10372. if (ip != NULL && IsIP4(ip) == false)
  10373. {
  10374. return NULL;
  10375. }
  10376. if (IS_SPECIAL_PORT(port) == false)
  10377. {
  10378. s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  10379. }
  10380. else
  10381. {
  10382. s = socket(AF_INET, SOCK_RAW, GET_SPECIAL_PORT(port));
  10383. }
  10384. if (s == INVALID_SOCKET)
  10385. {
  10386. return NULL;
  10387. }
  10388. Zero(&addr, sizeof(addr));
  10389. addr.sin_family = AF_INET;
  10390. if (ip == NULL || IsZeroIP(ip))
  10391. {
  10392. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  10393. }
  10394. else
  10395. {
  10396. IPToInAddr(&addr.sin_addr, ip);
  10397. }
  10398. if (port == 0 || IS_SPECIAL_PORT(port))
  10399. {
  10400. addr.sin_port = 0;
  10401. }
  10402. else
  10403. {
  10404. addr.sin_port = htons((USHORT)port);
  10405. }
  10406. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10407. {
  10408. // Failure
  10409. if (port != 0)
  10410. {
  10411. bool true_flag = true;
  10412. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  10413. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10414. {
  10415. bool false_flag = false;
  10416. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&false_flag, sizeof(bool));
  10417. #ifdef SO_EXCLUSIVEADDRUSE
  10418. setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&true_flag, sizeof(bool));
  10419. #endif // SO_EXCLUSIVEADDRUSE
  10420. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10421. {
  10422. closesocket(s);
  10423. return NULL;
  10424. }
  10425. }
  10426. }
  10427. else
  10428. {
  10429. closesocket(s);
  10430. return NULL;
  10431. }
  10432. }
  10433. sock = NewSock();
  10434. sock->Type = SOCK_UDP;
  10435. sock->Connected = false;
  10436. sock->AsyncMode = false;
  10437. sock->ServerMode = false;
  10438. if (port != 0)
  10439. {
  10440. sock->ServerMode = true;
  10441. }
  10442. sock->socket = s;
  10443. InitUdpSocketBufferSize((int)s);
  10444. if (IS_SPECIAL_PORT(port))
  10445. {
  10446. bool no = false;
  10447. setsockopt(sock->socket, IPPROTO_IP, IP_HDRINCL, (char *)&no, sizeof(no));
  10448. sock->IsRawSocket = true;
  10449. sock->RawSocketIPProtocol = GET_SPECIAL_PORT(port);
  10450. }
  10451. QuerySocketInformation(sock);
  10452. return sock;
  10453. }
  10454. SOCK *NewUDP6(UINT port, IP *ip)
  10455. {
  10456. SOCK *sock;
  10457. SOCKET s;
  10458. struct sockaddr_in6 addr;
  10459. // Validate arguments
  10460. if (ip != NULL && IsIP6(ip) == false)
  10461. {
  10462. return NULL;
  10463. }
  10464. if (IS_SPECIAL_PORT(port) == false)
  10465. {
  10466. s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
  10467. }
  10468. else
  10469. {
  10470. s = socket(AF_INET6, SOCK_RAW, GET_SPECIAL_PORT(port));
  10471. }
  10472. if (s == INVALID_SOCKET)
  10473. {
  10474. return NULL;
  10475. }
  10476. Zero(&addr, sizeof(addr));
  10477. addr.sin6_family = AF_INET6;
  10478. if (port == 0)
  10479. {
  10480. addr.sin6_port = 0;
  10481. }
  10482. else
  10483. {
  10484. addr.sin6_port = htons((USHORT)port);
  10485. }
  10486. if (ip != NULL && IsZeroIP(ip) == false)
  10487. {
  10488. IPToInAddr6(&addr.sin6_addr, ip);
  10489. addr.sin6_scope_id = ip->ipv6_scope_id;
  10490. }
  10491. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10492. {
  10493. // Failure
  10494. if (port != 0)
  10495. {
  10496. bool true_flag = true;
  10497. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  10498. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10499. {
  10500. bool false_flag = false;
  10501. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&false_flag, sizeof(bool));
  10502. #ifdef SO_EXCLUSIVEADDRUSE
  10503. setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&true_flag, sizeof(bool));
  10504. #endif // SO_EXCLUSIVEADDRUSE
  10505. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  10506. {
  10507. closesocket(s);
  10508. return NULL;
  10509. }
  10510. }
  10511. }
  10512. else
  10513. {
  10514. closesocket(s);
  10515. return NULL;
  10516. }
  10517. }
  10518. sock = NewSock();
  10519. sock->Type = SOCK_UDP;
  10520. sock->Connected = false;
  10521. sock->AsyncMode = false;
  10522. sock->ServerMode = false;
  10523. sock->IPv6 = true;
  10524. if (port != 0)
  10525. {
  10526. sock->ServerMode = true;
  10527. }
  10528. sock->socket = s;
  10529. InitUdpSocketBufferSize(s);
  10530. if (IS_SPECIAL_PORT(port))
  10531. {
  10532. bool no = false;
  10533. #ifdef IPV6_HDRINCL
  10534. setsockopt(sock->socket, IPPROTO_IP, IPV6_HDRINCL, (char *)&no, sizeof(no));
  10535. #endif // IPV6_HDRINCL
  10536. setsockopt(sock->socket, IPPROTO_IP, IP_HDRINCL, (char *)&no, sizeof(no));
  10537. sock->IsRawSocket = true;
  10538. sock->RawSocketIPProtocol = GET_SPECIAL_PORT(port);
  10539. }
  10540. QuerySocketInformation(sock);
  10541. return sock;
  10542. }
  10543. // Select function
  10544. void Select(SOCKSET *set, UINT timeout, CANCEL *c1, CANCEL *c2)
  10545. {
  10546. #ifdef OS_WIN32
  10547. Win32Select(set, timeout, c1, c2);
  10548. #else
  10549. UnixSelect(set, timeout, c1, c2);
  10550. #endif // OS_WIN32
  10551. }
  10552. // Add a socket to the socket set
  10553. void AddSockSet(SOCKSET *set, SOCK *sock)
  10554. {
  10555. // Validate arguments
  10556. if (set == NULL || sock == NULL)
  10557. {
  10558. return;
  10559. }
  10560. if (sock->Type == SOCK_TCP && sock->Connected == false)
  10561. {
  10562. return;
  10563. }
  10564. if (set->NumSocket >= MAX_SOCKSET_NUM)
  10565. {
  10566. // Upper limit
  10567. return;
  10568. }
  10569. set->Sock[set->NumSocket++] = sock;
  10570. }
  10571. // Initializing the socket set
  10572. void InitSockSet(SOCKSET *set)
  10573. {
  10574. // Validate arguments
  10575. if (set == NULL)
  10576. {
  10577. return;
  10578. }
  10579. Zero(set, sizeof(SOCKSET));
  10580. }
  10581. // Receive all by TCP
  10582. bool RecvAll(SOCK *sock, void *data, UINT size, bool secure)
  10583. {
  10584. UINT recv_size, sz, ret;
  10585. // Validate arguments
  10586. if (sock == NULL || data == NULL)
  10587. {
  10588. return false;
  10589. }
  10590. if (size == 0)
  10591. {
  10592. return true;
  10593. }
  10594. if (sock->AsyncMode)
  10595. {
  10596. return false;
  10597. }
  10598. recv_size = 0;
  10599. while (true)
  10600. {
  10601. sz = size - recv_size;
  10602. ret = Recv(sock, (UCHAR *)data + recv_size, sz, secure);
  10603. if (ret == 0)
  10604. {
  10605. return false;
  10606. }
  10607. if (ret == SOCK_LATER)
  10608. {
  10609. // I suppose that this is safe because the RecvAll() function is used only
  10610. // if the sock->AsyncMode == true. And the Recv() function may return
  10611. // SOCK_LATER only if the sock->AsyncMode == false. Therefore the call of
  10612. // Recv() function in the RecvAll() function never returns SOCK_LATER.
  10613. return false;
  10614. }
  10615. recv_size += ret;
  10616. if (recv_size >= size)
  10617. {
  10618. return true;
  10619. }
  10620. }
  10621. }
  10622. // Send the TCP send buffer
  10623. bool SendNow(SOCK *sock, int secure)
  10624. {
  10625. bool ret;
  10626. // Validate arguments
  10627. if (sock == NULL || sock->AsyncMode != false)
  10628. {
  10629. return false;
  10630. }
  10631. if (sock->SendBuf->Size == 0)
  10632. {
  10633. return true;
  10634. }
  10635. ret = SendAll(sock, sock->SendBuf->Buf, sock->SendBuf->Size, secure);
  10636. ClearBuf(sock->SendBuf);
  10637. return ret;
  10638. }
  10639. // Append to the TCP send buffer
  10640. void SendAdd(SOCK *sock, void *data, UINT size)
  10641. {
  10642. // Validate arguments
  10643. if (sock == NULL || data == NULL || size == 0 || sock->AsyncMode != false)
  10644. {
  10645. return;
  10646. }
  10647. WriteBuf(sock->SendBuf, data, size);
  10648. }
  10649. // Send all by TCP
  10650. bool SendAll(SOCK *sock, void *data, UINT size, bool secure)
  10651. {
  10652. UCHAR *buf;
  10653. UINT sent_size;
  10654. UINT ret;
  10655. // Validate arguments
  10656. if (sock == NULL || data == NULL)
  10657. {
  10658. return false;
  10659. }
  10660. if (sock->AsyncMode)
  10661. {
  10662. return false;
  10663. }
  10664. if (size == 0)
  10665. {
  10666. return true;
  10667. }
  10668. buf = (UCHAR *)data;
  10669. sent_size = 0;
  10670. while (true)
  10671. {
  10672. ret = Send(sock, buf, size - sent_size, secure);
  10673. if (ret == 0)
  10674. {
  10675. return false;
  10676. }
  10677. sent_size += ret;
  10678. buf += ret;
  10679. if (sent_size >= size)
  10680. {
  10681. return true;
  10682. }
  10683. }
  10684. }
  10685. // Set the cipher algorithm name to want to use
  10686. void SetWantToUseCipher(SOCK *sock, char *name)
  10687. {
  10688. char tmp[1024];
  10689. // Validate arguments
  10690. if (sock == NULL || name == NULL)
  10691. {
  10692. return;
  10693. }
  10694. if (sock->WaitToUseCipher)
  10695. {
  10696. Free(sock->WaitToUseCipher);
  10697. }
  10698. Zero(tmp, sizeof(tmp));
  10699. StrCpy(tmp, sizeof(tmp), name);
  10700. StrCat(tmp, sizeof(tmp), " ");
  10701. StrCat(tmp, sizeof(tmp), cipher_list);
  10702. sock->WaitToUseCipher = CopyStr(tmp);
  10703. }
  10704. // Add all the chain certificates in the chain_certs directory
  10705. void AddChainSslCertOnDirectory(struct ssl_ctx_st *ctx)
  10706. {
  10707. wchar_t dirname[MAX_SIZE];
  10708. wchar_t exedir[MAX_SIZE];
  10709. wchar_t txtname[MAX_SIZE];
  10710. DIRLIST *dir;
  10711. LIST *o;
  10712. UINT i;
  10713. // Validate arguments
  10714. if (ctx == NULL)
  10715. {
  10716. return;
  10717. }
  10718. o = NewListFast(NULL);
  10719. GetExeDirW(exedir, sizeof(exedir));
  10720. CombinePathW(dirname, sizeof(dirname), exedir, L"chain_certs");
  10721. MakeDirExW(dirname);
  10722. CombinePathW(txtname, sizeof(txtname), dirname, L"Readme_Chain_Certs.txt");
  10723. if (IsFileExistsW(txtname) == false)
  10724. {
  10725. FileCopyW(L"|chain_certs.txt", txtname);
  10726. }
  10727. dir = EnumDirW(dirname);
  10728. if (dir != NULL)
  10729. {
  10730. for (i = 0;i < dir->NumFiles;i++)
  10731. {
  10732. DIRENT *e = dir->File[i];
  10733. if (e->Folder == false)
  10734. {
  10735. wchar_t tmp[MAX_SIZE];
  10736. X *x;
  10737. CombinePathW(tmp, sizeof(tmp), dirname, e->FileNameW);
  10738. x = FileToXW(tmp);
  10739. if (x != NULL)
  10740. {
  10741. UINT j;
  10742. bool exists = false;
  10743. UCHAR hash[SHA1_SIZE];
  10744. GetXDigest(x, hash, true);
  10745. for (j = 0;j < LIST_NUM(o);j++)
  10746. {
  10747. UCHAR *hash2 = LIST_DATA(o, j);
  10748. if (Cmp(hash, hash2, SHA1_SIZE) == 0)
  10749. {
  10750. exists = true;
  10751. }
  10752. }
  10753. if (exists == false)
  10754. {
  10755. AddChainSslCert(ctx, x);
  10756. Add(o, Clone(hash, SHA1_SIZE));
  10757. }
  10758. FreeX(x);
  10759. }
  10760. }
  10761. }
  10762. FreeDir(dir);
  10763. }
  10764. for (i = 0;i < LIST_NUM(o);i++)
  10765. {
  10766. UCHAR *hash = LIST_DATA(o, i);
  10767. Free(hash);
  10768. }
  10769. ReleaseList(o);
  10770. }
  10771. // Add the chain certificate
  10772. bool AddChainSslCert(struct ssl_ctx_st *ctx, X *x)
  10773. {
  10774. bool ret = false;
  10775. X *x_copy;
  10776. // Validate arguments
  10777. if (ctx == NULL || x == NULL)
  10778. {
  10779. return ret;
  10780. }
  10781. x_copy = CloneX(x);
  10782. if (x_copy != NULL)
  10783. {
  10784. SSL_CTX_add_extra_chain_cert(ctx, x_copy->x509);
  10785. x_copy->do_not_free = true;
  10786. ret = true;
  10787. FreeX(x_copy);
  10788. }
  10789. return ret;
  10790. }
  10791. // Start a TCP-SSL communication
  10792. bool StartSSL(SOCK *sock, X *x, K *priv)
  10793. {
  10794. return StartSSLEx(sock, x, priv, true, 0, NULL);
  10795. }
  10796. bool StartSSLEx(SOCK *sock, X *x, K *priv, bool client_tls, UINT ssl_timeout, char *sni_hostname)
  10797. {
  10798. X509 *x509;
  10799. EVP_PKEY *key;
  10800. UINT prev_timeout = 1024;
  10801. SSL_CTX *ssl_ctx;
  10802. #ifdef UNIX_SOLARIS
  10803. SOCKET_TIMEOUT_PARAM *ttparam;
  10804. #endif //UNIX_SOLARIS
  10805. // Validate arguments
  10806. if (sock == NULL)
  10807. {
  10808. Debug("StartSSL Error: #0\n");
  10809. return false;
  10810. }
  10811. if (sock->Connected && sock->Type == SOCK_INPROC && sock->ListenMode == false)
  10812. {
  10813. sock->SecureMode = true;
  10814. return true;
  10815. }
  10816. if (sock->Connected == false || sock->socket == INVALID_SOCKET ||
  10817. sock->ListenMode != false)
  10818. {
  10819. Debug("StartSSL Error: #1\n");
  10820. return false;
  10821. }
  10822. if (x != NULL && priv == NULL)
  10823. {
  10824. Debug("StartSSL Error: #2\n");
  10825. return false;
  10826. }
  10827. if (ssl_timeout == 0)
  10828. {
  10829. ssl_timeout = TIMEOUT_SSL_CONNECT;
  10830. }
  10831. if (sock->SecureMode)
  10832. {
  10833. //Debug("StartSSL Error: #3\n");
  10834. // SSL communication has already started
  10835. return true;
  10836. }
  10837. Lock(sock->ssl_lock);
  10838. if (sock->SecureMode)
  10839. {
  10840. //Debug("StartSSL Error: #4\n");
  10841. // SSL communication has already started
  10842. Unlock(sock->ssl_lock);
  10843. return true;
  10844. }
  10845. ssl_ctx = NewSSLCtx(sock->ServerMode);
  10846. Lock(openssl_lock);
  10847. {
  10848. if (sock->ServerMode)
  10849. {
  10850. SSL_CTX_set_ssl_version(ssl_ctx, SSLv23_method());
  10851. #ifdef SSL_OP_NO_SSLv2
  10852. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
  10853. #endif // SSL_OP_NO_SSLv2
  10854. if (sock->SslAcceptSettings.AcceptOnlyTls)
  10855. {
  10856. #ifdef SSL_OP_NO_SSLv3
  10857. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
  10858. #endif // SSL_OP_NO_SSLv3
  10859. }
  10860. if (sock->SslAcceptSettings.Tls_Disable1_0)
  10861. {
  10862. #ifdef SSL_OP_NO_TLSv1
  10863. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
  10864. #endif // SSL_OP_NO_TLSv1
  10865. }
  10866. if (sock->SslAcceptSettings.Tls_Disable1_1)
  10867. {
  10868. #ifdef SSL_OP_NO_TLSv1_1
  10869. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
  10870. #endif // SSL_OP_NO_TLSv1_1
  10871. }
  10872. if (sock->SslAcceptSettings.Tls_Disable1_2)
  10873. {
  10874. #ifdef SSL_OP_NO_TLSv1_2
  10875. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
  10876. #endif // SSL_OP_NO_TLSv1_2
  10877. }
  10878. Unlock(openssl_lock);
  10879. AddChainSslCertOnDirectory(ssl_ctx);
  10880. Lock(openssl_lock);
  10881. }
  10882. else
  10883. {
  10884. if (client_tls == false)
  10885. {
  10886. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  10887. SSL_CTX_set_ssl_version(ssl_ctx, SSLv3_method());
  10888. #else
  10889. SSL_CTX_set_ssl_version(ssl_ctx, SSLv23_method());
  10890. #endif
  10891. }
  10892. else
  10893. {
  10894. SSL_CTX_set_ssl_version(ssl_ctx, SSLv23_client_method());
  10895. }
  10896. }
  10897. sock->ssl = SSL_new(ssl_ctx);
  10898. SSL_set_fd(sock->ssl, (int)sock->socket);
  10899. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  10900. if (sock->ServerMode == false && client_tls)
  10901. {
  10902. if (IsEmptyStr(sni_hostname) == false)
  10903. {
  10904. // Set the SNI host name
  10905. SSL_set_tlsext_host_name(sock->ssl, sni_hostname);
  10906. }
  10907. }
  10908. #endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
  10909. }
  10910. Unlock(openssl_lock);
  10911. if (x != NULL)
  10912. {
  10913. // Check the certificate and the private key
  10914. if (CheckXandK(x, priv))
  10915. {
  10916. // Use the certificate
  10917. x509 = x->x509;
  10918. key = priv->pkey;
  10919. Lock(openssl_lock);
  10920. {
  10921. SSL_use_certificate(sock->ssl, x509);
  10922. SSL_use_PrivateKey(sock->ssl, key);
  10923. }
  10924. Unlock(openssl_lock);
  10925. }
  10926. }
  10927. if (sock->WaitToUseCipher != NULL)
  10928. {
  10929. // Set the cipher algorithm name to want to use
  10930. Lock(openssl_lock);
  10931. {
  10932. SSL_set_cipher_list(sock->ssl, sock->WaitToUseCipher);
  10933. }
  10934. Unlock(openssl_lock);
  10935. }
  10936. if (sock->ServerMode)
  10937. {
  10938. // Lock(ssl_connect_lock);
  10939. // Run the time-out thread for SOLARIS
  10940. #ifdef UNIX_SOLARIS
  10941. ttparam = NewSocketTimeout(sock);
  10942. #endif // UNIX_SOLARIS
  10943. // Server mode
  10944. if (SSL_accept(sock->ssl) <= 0)
  10945. {
  10946. // Stop the timeout thread
  10947. #ifdef UNIX_SOLARIS
  10948. FreeSocketTimeout(ttparam);
  10949. #endif // UNIX_SOLARIS
  10950. // Unlock(ssl_connect_lock);
  10951. // SSL-Accept failure
  10952. Lock(openssl_lock);
  10953. {
  10954. SSL_free(sock->ssl);
  10955. sock->ssl = NULL;
  10956. }
  10957. Unlock(openssl_lock);
  10958. Unlock(sock->ssl_lock);
  10959. Debug("StartSSL Error: #5\n");
  10960. FreeSSLCtx(ssl_ctx);
  10961. return false;
  10962. }
  10963. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  10964. #ifdef TLSEXT_NAMETYPE_host_name
  10965. if (true)
  10966. {
  10967. // Get the SNI host name
  10968. const char *sni_recv_hostname = SSL_get_servername(sock->ssl, TLSEXT_NAMETYPE_host_name);
  10969. if (IsEmptyStr((char *)sni_recv_hostname) == false)
  10970. {
  10971. StrCpy(sock->SniHostname, sizeof(sock->SniHostname), (char *)sni_recv_hostname);
  10972. }
  10973. }
  10974. #endif // TLSEXT_NAMETYPE_host_name
  10975. #endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
  10976. // Stop the timeout thread
  10977. #ifdef UNIX_SOLARIS
  10978. FreeSocketTimeout(ttparam);
  10979. #endif // UNIX_SOLARIS
  10980. // Unlock(ssl_connect_lock);
  10981. }
  10982. else
  10983. {
  10984. prev_timeout = GetTimeout(sock);
  10985. SetTimeout(sock, ssl_timeout);
  10986. Lock(ssl_connect_lock);
  10987. // Client mode
  10988. if (SSL_connect(sock->ssl) <= 0)
  10989. {
  10990. Unlock(ssl_connect_lock);
  10991. // SSL-connect failure
  10992. Lock(openssl_lock);
  10993. {
  10994. SSL_free(sock->ssl);
  10995. sock->ssl = NULL;
  10996. }
  10997. Unlock(openssl_lock);
  10998. Unlock(sock->ssl_lock);
  10999. Debug("StartSSL Error: #5\n");
  11000. SetTimeout(sock, prev_timeout);
  11001. FreeSSLCtx(ssl_ctx);
  11002. return false;
  11003. }
  11004. Unlock(ssl_connect_lock);
  11005. SetTimeout(sock, prev_timeout);
  11006. }
  11007. // SSL communication is initiated
  11008. sock->SecureMode = true;
  11009. // Get the certificate of the remote host
  11010. Lock(openssl_lock);
  11011. {
  11012. x509 = SSL_get_peer_certificate(sock->ssl);
  11013. sock->SslVersion = SSL_get_version(sock->ssl);
  11014. }
  11015. Unlock(openssl_lock);
  11016. if (x509 == NULL)
  11017. {
  11018. // The certificate does not exist on the remote host
  11019. sock->RemoteX = NULL;
  11020. }
  11021. else
  11022. {
  11023. // Got a certificate
  11024. sock->RemoteX = X509ToX(x509);
  11025. }
  11026. // Get the certificate of local host
  11027. Lock(openssl_lock);
  11028. {
  11029. x509 = SSL_get_certificate(sock->ssl);
  11030. }
  11031. Unlock(openssl_lock);
  11032. if (x509 == NULL)
  11033. {
  11034. // The certificate does not exist on the remote host
  11035. sock->LocalX = NULL;
  11036. }
  11037. else
  11038. {
  11039. X *local_x;
  11040. // Got a certificate
  11041. local_x = X509ToX(x509);
  11042. local_x->do_not_free = true;
  11043. sock->LocalX = CloneX(local_x);
  11044. FreeX(local_x);
  11045. }
  11046. // Automatic retry mode
  11047. SSL_set_mode(sock->ssl, SSL_MODE_AUTO_RETRY);
  11048. // Strange flag
  11049. SSL_set_mode(sock->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  11050. sock->ssl_ctx = ssl_ctx;
  11051. // Get the algorithm name used to encrypt
  11052. Lock(openssl_lock);
  11053. {
  11054. sock->CipherName = CopyStr((char *)SSL_get_cipher(sock->ssl));
  11055. }
  11056. Unlock(openssl_lock);
  11057. Debug("SSL connected with %s\n", SSL_get_version(sock->ssl));
  11058. Unlock(sock->ssl_lock);
  11059. #ifdef ENABLE_SSL_LOGGING
  11060. if (sock->ServerMode)
  11061. {
  11062. SockEnableSslLogging(sock);
  11063. }
  11064. #endif // ENABLE_SSL_LOGGING
  11065. return true;
  11066. }
  11067. #ifdef ENABLE_SSL_LOGGING
  11068. // Enable SSL logging
  11069. void SockEnableSslLogging(SOCK *s)
  11070. {
  11071. char dirname[MAX_PATH];
  11072. char tmp[MAX_PATH];
  11073. char dtstr[MAX_PATH];
  11074. char fn1[MAX_PATH], fn2[MAX_PATH];
  11075. // Validate arguments
  11076. if (s == NULL)
  11077. {
  11078. return;
  11079. }
  11080. if (s->IsSslLoggingEnabled)
  11081. {
  11082. return;
  11083. }
  11084. s->IsSslLoggingEnabled = true;
  11085. GetDateTimeStrMilli64ForFileName(dtstr, sizeof(dtstr), LocalTime64());
  11086. Format(tmp, sizeof(tmp), "%s__%r_%u__%r_%u", dtstr,
  11087. &s->LocalIP, s->LocalPort, &s->RemoteIP, s->RemotePort);
  11088. CombinePath(dirname, sizeof(dirname), SSL_LOGGING_DIRNAME, tmp);
  11089. MakeDirEx(dirname);
  11090. CombinePath(fn1, sizeof(fn1), dirname, "send.c");
  11091. CombinePath(fn2, sizeof(fn2), dirname, "recv.c");
  11092. s->SslLogging_Send = FileCreate(fn1);
  11093. s->SslLogging_Recv = FileCreate(fn2);
  11094. s->SslLogging_Lock = NewLock();
  11095. }
  11096. // Close SSL logging
  11097. void SockCloseSslLogging(SOCK *s)
  11098. {
  11099. // Validate arguments
  11100. if (s == NULL)
  11101. {
  11102. return;
  11103. }
  11104. if (s->IsSslLoggingEnabled == false)
  11105. {
  11106. return;
  11107. }
  11108. s->IsSslLoggingEnabled = false;
  11109. FileClose(s->SslLogging_Recv);
  11110. s->SslLogging_Recv = NULL;
  11111. FileClose(s->SslLogging_Send);
  11112. s->SslLogging_Send = NULL;
  11113. DeleteLock(s->SslLogging_Lock);
  11114. s->SslLogging_Lock = NULL;
  11115. }
  11116. // Write SSL log
  11117. void SockWriteSslLog(SOCK *s, void *send_data, UINT send_size, void *recv_data, UINT recv_size)
  11118. {
  11119. // Validate arguments
  11120. if (s == NULL)
  11121. {
  11122. return;
  11123. }
  11124. if (s->IsSslLoggingEnabled == false)
  11125. {
  11126. return;
  11127. }
  11128. Lock(s->SslLogging_Lock);
  11129. {
  11130. if (s->SslLogging_Send != NULL)
  11131. {
  11132. if (send_size >= 1 && send_data != NULL)
  11133. {
  11134. FileWrite(s->SslLogging_Send, send_data, send_size);
  11135. }
  11136. }
  11137. if (s->SslLogging_Recv != NULL)
  11138. {
  11139. if (recv_size >= 1 && recv_data != NULL)
  11140. {
  11141. FileWrite(s->SslLogging_Recv, recv_data, recv_size);
  11142. }
  11143. }
  11144. }
  11145. Unlock(s->SslLogging_Lock);
  11146. }
  11147. #endif // ENABLE_SSL_LOGGING
  11148. // Set the flag to indicate that the socket doesn't require reading
  11149. void SetNoNeedToRead(SOCK *sock)
  11150. {
  11151. // Validate arguments
  11152. if (sock == NULL)
  11153. {
  11154. return;
  11155. }
  11156. sock->NoNeedToRead = true;
  11157. }
  11158. // TCP-SSL receive
  11159. UINT SecureRecv(SOCK *sock, void *data, UINT size)
  11160. {
  11161. SOCKET s;
  11162. int ret, e = 0;
  11163. SSL *ssl;
  11164. #ifdef UNIX_SOLARIS
  11165. SOCKET_TIMEOUT_PARAM *ttparam;
  11166. #endif //UNIX_SOLARIS
  11167. s = sock->socket;
  11168. ssl = sock->ssl;
  11169. if (sock->AsyncMode)
  11170. {
  11171. // Confirm whether the data is readable even 1 byte in the case of asynchronous mode.
  11172. // To read data results blocking, if there is no readable data.
  11173. // We must avoid blocking.
  11174. char c;
  11175. Lock(sock->ssl_lock);
  11176. {
  11177. if (sock->Connected == false)
  11178. {
  11179. Unlock(sock->ssl_lock);
  11180. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11181. return 0;
  11182. }
  11183. ret = SSL_peek(ssl, &c, sizeof(c));
  11184. }
  11185. Unlock(sock->ssl_lock);
  11186. if (ret == 0)
  11187. {
  11188. // The communication have been disconnected
  11189. Disconnect(sock);
  11190. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11191. return 0;
  11192. }
  11193. if (ret < 0)
  11194. {
  11195. // An error has occurred
  11196. e = SSL_get_error(ssl, ret);
  11197. if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE || e == SSL_ERROR_SSL)
  11198. {
  11199. if (e == SSL_ERROR_SSL
  11200. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  11201. &&
  11202. sock->ssl->s3->send_alert[0] == SSL3_AL_FATAL &&
  11203. sock->ssl->s3->send_alert[0] != sock->Ssl_Init_Async_SendAlert[0] &&
  11204. sock->ssl->s3->send_alert[1] != sock->Ssl_Init_Async_SendAlert[1]
  11205. #endif
  11206. )
  11207. {
  11208. Debug("%s %u SSL Fatal Error on ASYNC socket !!!\n", __FILE__, __LINE__);
  11209. Disconnect(sock);
  11210. return 0;
  11211. }
  11212. // Packet has not arrived yet, that is not to be read
  11213. return SOCK_LATER;
  11214. }
  11215. }
  11216. }
  11217. // Receive
  11218. Lock(sock->ssl_lock);
  11219. {
  11220. if (sock->Connected == false)
  11221. {
  11222. Unlock(sock->ssl_lock);
  11223. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11224. return 0;
  11225. }
  11226. #ifdef OS_UNIX
  11227. if (sock->AsyncMode == false)
  11228. {
  11229. sock->CallingThread = pthread_self();
  11230. }
  11231. #endif // OS_UNIX
  11232. // Run the time-out thread for SOLARIS
  11233. #ifdef UNIX_SOLARIS
  11234. ttparam = NewSocketTimeout(sock);
  11235. #endif // UNIX_SOLARIS
  11236. ret = SSL_read(ssl, data, size);
  11237. // Stop the timeout thread
  11238. #ifdef UNIX_SOLARIS
  11239. FreeSocketTimeout(ttparam);
  11240. #endif // UNIX_SOLARIS
  11241. #ifdef OS_UNIX
  11242. if (sock->AsyncMode == false)
  11243. {
  11244. sock->CallingThread = 0;
  11245. }
  11246. #endif // OS_UNIX
  11247. if (ret < 0)
  11248. {
  11249. e = SSL_get_error(ssl, ret);
  11250. }
  11251. }
  11252. Unlock(sock->ssl_lock);
  11253. #ifdef ENABLE_SSL_LOGGING
  11254. if (ret > 0)
  11255. {
  11256. SockWriteSslLog(sock, NULL, 0, data, ret);
  11257. }
  11258. #endif // ENABLE_SSL_LOGGING
  11259. if (ret > 0)
  11260. {
  11261. // Successful reception
  11262. sock->RecvSize += (UINT64)ret;
  11263. sock->RecvNum++;
  11264. return (UINT)ret;
  11265. }
  11266. if (ret == 0)
  11267. {
  11268. // Disconnect the communication
  11269. Disconnect(sock);
  11270. //Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11271. return 0;
  11272. }
  11273. if (sock->AsyncMode)
  11274. {
  11275. if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE || e == SSL_ERROR_SSL)
  11276. {
  11277. if (e == SSL_ERROR_SSL
  11278. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  11279. &&
  11280. sock->ssl->s3->send_alert[0] == SSL3_AL_FATAL &&
  11281. sock->ssl->s3->send_alert[0] != sock->Ssl_Init_Async_SendAlert[0] &&
  11282. sock->ssl->s3->send_alert[1] != sock->Ssl_Init_Async_SendAlert[1]
  11283. #endif
  11284. )
  11285. {
  11286. Debug("%s %u SSL Fatal Error on ASYNC socket !!!\n", __FILE__, __LINE__);
  11287. Disconnect(sock);
  11288. return 0;
  11289. }
  11290. // Packet has not yet arrived
  11291. return SOCK_LATER;
  11292. }
  11293. }
  11294. Disconnect(sock);
  11295. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11296. return 0;
  11297. }
  11298. // TCP-SSL transmission
  11299. UINT SecureSend(SOCK *sock, void *data, UINT size)
  11300. {
  11301. SOCKET s;
  11302. int ret, e;
  11303. SSL *ssl;
  11304. s = sock->socket;
  11305. ssl = sock->ssl;
  11306. if (sock->AsyncMode)
  11307. {
  11308. // Asynchronous mode
  11309. SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
  11310. }
  11311. // Transmission
  11312. Lock(sock->ssl_lock);
  11313. {
  11314. if (sock->Connected == false)
  11315. {
  11316. Unlock(sock->ssl_lock);
  11317. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11318. return 0;
  11319. }
  11320. ret = SSL_write(ssl, data, size);
  11321. if (ret < 0)
  11322. {
  11323. e = SSL_get_error(ssl, ret);
  11324. }
  11325. }
  11326. Unlock(sock->ssl_lock);
  11327. #ifdef ENABLE_SSL_LOGGING
  11328. if (ret > 0)
  11329. {
  11330. SockWriteSslLog(sock, data, ret, NULL, 0);
  11331. }
  11332. #endif // ENABLE_SSL_LOGGING
  11333. if (ret > 0)
  11334. {
  11335. // Successful transmission
  11336. sock->SendSize += (UINT64)ret;
  11337. sock->SendNum++;
  11338. sock->WriteBlocked = false;
  11339. return (UINT)ret;
  11340. }
  11341. if (ret == 0)
  11342. {
  11343. // Disconnect
  11344. Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11345. Disconnect(sock);
  11346. return 0;
  11347. }
  11348. if (sock->AsyncMode)
  11349. {
  11350. // Confirmation of the error value
  11351. if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE || e == SSL_ERROR_SSL)
  11352. {
  11353. sock->WriteBlocked = true;
  11354. return SOCK_LATER;
  11355. }
  11356. Debug("%s %u e=%u\n", __FILE__, __LINE__, e);
  11357. }
  11358. //Debug("%s %u SecureRecv() Disconnect\n", __FILE__, __LINE__);
  11359. Disconnect(sock);
  11360. return 0;
  11361. }
  11362. // Peep the TCP
  11363. UINT Peek(SOCK *sock, void *data, UINT size)
  11364. {
  11365. SOCKET s;
  11366. int ret;
  11367. // Validate arguments
  11368. if (sock == NULL || data == NULL || size == 0)
  11369. {
  11370. return 0;
  11371. }
  11372. if (sock->Type == SOCK_INPROC)
  11373. {
  11374. return 0;
  11375. }
  11376. if (sock->Type != SOCK_TCP || sock->Connected == false || sock->ListenMode != false ||
  11377. sock->socket == INVALID_SOCKET)
  11378. {
  11379. return 0;
  11380. }
  11381. if (sock->AsyncMode)
  11382. {
  11383. return 0;
  11384. }
  11385. // Receive
  11386. s = sock->socket;
  11387. ret = recv(s, data, size, MSG_PEEK);
  11388. //Debug("Peek: %u\n", ret);
  11389. if (ret > 0)
  11390. {
  11391. return ret;
  11392. }
  11393. return 0;
  11394. }
  11395. // TCP receive
  11396. UINT Recv(SOCK *sock, void *data, UINT size, bool secure)
  11397. {
  11398. SOCKET s;
  11399. int ret;
  11400. #ifdef UNIX_SOLARIS
  11401. SOCKET_TIMEOUT_PARAM *ttparam;
  11402. #endif //UNIX_SOLARIS
  11403. // Validate arguments
  11404. if (sock == NULL || data == NULL || size == 0)
  11405. {
  11406. return 0;
  11407. }
  11408. sock->NoNeedToRead = false;
  11409. if (sock->Type == SOCK_INPROC)
  11410. {
  11411. return RecvInProc(sock, data, size);
  11412. }
  11413. if (sock->Type != SOCK_TCP || sock->Connected == false || sock->ListenMode != false ||
  11414. sock->socket == INVALID_SOCKET)
  11415. {
  11416. return 0;
  11417. }
  11418. if (secure != false && sock->SecureMode == false)
  11419. {
  11420. return 0;
  11421. }
  11422. if (secure)
  11423. {
  11424. return SecureRecv(sock, data, size);
  11425. }
  11426. // Receive
  11427. s = sock->socket;
  11428. #ifdef OS_UNIX
  11429. if (sock->AsyncMode == false)
  11430. {
  11431. sock->CallingThread = pthread_self();
  11432. }
  11433. #endif // OS_UNIX
  11434. // Start of the timeout thread for SOLARIS
  11435. #ifdef UNIX_SOLARIS
  11436. ttparam = NewSocketTimeout(sock);
  11437. #endif // UNIX_SOLARIS
  11438. ret = recv(s, data, size, 0);
  11439. // Stop the timeout thread
  11440. #ifdef UNIX_SOLARIS
  11441. FreeSocketTimeout(ttparam);
  11442. #endif // UNIX_SOLARIS
  11443. #ifdef OS_UNIX
  11444. if (sock->AsyncMode == false)
  11445. {
  11446. sock->CallingThread = 0;
  11447. }
  11448. #endif // OS_UNIX
  11449. if (ret > 0)
  11450. {
  11451. // Successful reception
  11452. Lock(sock->lock);
  11453. {
  11454. sock->RecvSize += (UINT64)ret;
  11455. sock->SendNum++;
  11456. }
  11457. Unlock(sock->lock);
  11458. return (UINT)ret;
  11459. }
  11460. // Transmission failure
  11461. if (sock->AsyncMode)
  11462. {
  11463. // In asynchronous mode, examine the error
  11464. if (ret == SOCKET_ERROR)
  11465. {
  11466. #ifdef OS_WIN32
  11467. if (WSAGetLastError() == WSAEWOULDBLOCK)
  11468. {
  11469. // In blocking
  11470. return SOCK_LATER;
  11471. }
  11472. else
  11473. {
  11474. //Debug("Socket Error: %u\n", WSAGetLastError());
  11475. }
  11476. #else // OS_WIN32
  11477. if (errno == EAGAIN)
  11478. {
  11479. // In blocking
  11480. return SOCK_LATER;
  11481. }
  11482. #endif // OS_WIN32
  11483. }
  11484. }
  11485. // Disconnected
  11486. Disconnect(sock);
  11487. return 0;
  11488. }
  11489. // TCP transmission
  11490. UINT Send(SOCK *sock, void *data, UINT size, bool secure)
  11491. {
  11492. SOCKET s;
  11493. int ret;
  11494. // Validate arguments
  11495. if (sock == NULL || data == NULL || size == 0)
  11496. {
  11497. return 0;
  11498. }
  11499. if (sock->Type == SOCK_INPROC)
  11500. {
  11501. return SendInProc(sock, data, size);
  11502. }
  11503. size = MIN(size, MAX_SEND_BUF_MEM_SIZE);
  11504. if (sock->Type != SOCK_TCP || sock->Connected == false || sock->ListenMode != false ||
  11505. sock->socket == INVALID_SOCKET)
  11506. {
  11507. return 0;
  11508. }
  11509. if (secure != false && sock->SecureMode == false)
  11510. {
  11511. return 0;
  11512. }
  11513. if (secure)
  11514. {
  11515. return SecureSend(sock, data, size);
  11516. }
  11517. // Transmission
  11518. s = sock->socket;
  11519. ret = send(s, data, size, 0);
  11520. if (ret > 0)
  11521. {
  11522. // Successful transmission
  11523. Lock(sock->lock);
  11524. {
  11525. sock->SendSize += (UINT64)ret;
  11526. sock->SendNum++;
  11527. }
  11528. Unlock(sock->lock);
  11529. sock->WriteBlocked = false;
  11530. return (UINT)ret;
  11531. }
  11532. // Transmission failure
  11533. if (sock->AsyncMode)
  11534. {
  11535. // In asynchronous mode, examine the error
  11536. if (ret == SOCKET_ERROR)
  11537. {
  11538. #ifdef OS_WIN32
  11539. if (WSAGetLastError() == WSAEWOULDBLOCK)
  11540. {
  11541. // In blocking
  11542. sock->WriteBlocked = true;
  11543. return SOCK_LATER;
  11544. }
  11545. else
  11546. {
  11547. //Debug("Socket Error: %u\n", WSAGetLastError());
  11548. }
  11549. #else // OS_WIN32
  11550. if (errno == EAGAIN)
  11551. {
  11552. // In blocking
  11553. sock->WriteBlocked = true;
  11554. return SOCK_LATER;
  11555. }
  11556. #endif // OS_WIN32
  11557. }
  11558. }
  11559. // Disconnected
  11560. Disconnect(sock);
  11561. return 0;
  11562. }
  11563. // Get the time-out value (in milliseconds)
  11564. UINT GetTimeout(SOCK *sock)
  11565. {
  11566. // Validate arguments
  11567. if (sock == NULL)
  11568. {
  11569. return INFINITE;
  11570. }
  11571. if (sock->Type != SOCK_TCP && sock->Type != SOCK_INPROC)
  11572. {
  11573. return INFINITE;
  11574. }
  11575. return sock->TimeOut;
  11576. }
  11577. // Setting the time-out value (in milliseconds)
  11578. void SetTimeout(SOCK *sock, UINT timeout)
  11579. {
  11580. // Validate arguments
  11581. if (sock == NULL)
  11582. {
  11583. return;
  11584. }
  11585. if (sock->Type == SOCK_UDP)
  11586. {
  11587. return;
  11588. }
  11589. if (timeout == INFINITE)
  11590. {
  11591. timeout = TIMEOUT_INFINITE;
  11592. }
  11593. sock->TimeOut = timeout;
  11594. // Debug("SetTimeout(%u)\n",timeout);
  11595. if (sock->Type != SOCK_INPROC)
  11596. {
  11597. #ifdef OS_WIN32
  11598. setsockopt(sock->socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(UINT));
  11599. setsockopt(sock->socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(UINT));
  11600. #endif
  11601. #ifdef OS_UNIX
  11602. #ifndef UNIX_SOLARIS
  11603. {
  11604. struct timeval tv_timeout;
  11605. tv_timeout.tv_sec = timeout / 1000; // miliseconds to seconds
  11606. tv_timeout.tv_usec = (timeout % 1000) * 1000; // miliseconds to microseconds
  11607. setsockopt(sock->socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv_timeout, sizeof(tv_timeout));
  11608. setsockopt(sock->socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv_timeout, sizeof(tv_timeout));
  11609. }
  11610. #endif // UNIX_SOLARIS
  11611. #endif // OS_UNIX
  11612. }
  11613. }
  11614. // Disable GetHostName call by accepting new TCP connection
  11615. void DisableGetHostNameWhenAcceptInit()
  11616. {
  11617. disable_gethostname_by_accept = true;
  11618. }
  11619. // Initialize the connection acceptance
  11620. void AcceptInit(SOCK *s)
  11621. {
  11622. AcceptInitEx(s, false);
  11623. }
  11624. void AcceptInitEx(SOCK *s, bool no_lookup_hostname)
  11625. {
  11626. char tmp[MAX_SIZE];
  11627. // Validate arguments
  11628. if (s == NULL)
  11629. {
  11630. return;
  11631. }
  11632. Zero(tmp, sizeof(tmp));
  11633. if (disable_gethostname_by_accept == false && no_lookup_hostname == false)
  11634. {
  11635. if (GetHostName(tmp, sizeof(tmp), &s->RemoteIP) == false ||
  11636. IsEmptyStr(tmp))
  11637. {
  11638. IPToStr(tmp, sizeof(tmp), &s->RemoteIP);
  11639. }
  11640. }
  11641. else
  11642. {
  11643. IPToStr(tmp, sizeof(tmp), &s->RemoteIP);
  11644. }
  11645. if (s->RemoteHostname != NULL)
  11646. {
  11647. Free(s->RemoteHostname);
  11648. }
  11649. s->RemoteHostname = CopyStr(tmp);
  11650. }
  11651. // TCP connection acceptance (IPv4)
  11652. SOCK *Accept(SOCK *sock)
  11653. {
  11654. SOCK *ret;
  11655. SOCKET s, new_socket;
  11656. int size;
  11657. struct sockaddr_in addr;
  11658. bool true_flag = true;
  11659. // Validate arguments
  11660. if (sock == NULL)
  11661. {
  11662. return NULL;
  11663. }
  11664. if (sock->Type == SOCK_INPROC)
  11665. {
  11666. return AcceptInProc(sock);
  11667. }
  11668. if (sock->Type == SOCK_REVERSE_LISTEN)
  11669. {
  11670. return AcceptReverse(sock);
  11671. }
  11672. if (sock->Type == SOCK_RUDP_LISTEN)
  11673. {
  11674. return AcceptRUDP(sock);
  11675. }
  11676. if (sock->ListenMode == false || sock->Type != SOCK_TCP || sock->ServerMode == false)
  11677. {
  11678. return NULL;
  11679. }
  11680. if (sock->CancelAccept)
  11681. {
  11682. return NULL;
  11683. }
  11684. if (sock->IPv6)
  11685. {
  11686. return Accept6(sock);
  11687. }
  11688. s = sock->socket;
  11689. if (s == INVALID_SOCKET)
  11690. {
  11691. return NULL;
  11692. }
  11693. Zero(&addr, sizeof(addr));
  11694. size = sizeof(addr);
  11695. #ifdef OS_UNIX
  11696. #if defined(UNIX_LINUX) || defined(UNIX_MACOS)
  11697. UnixIgnoreSignalForThread(SIGUSR1);
  11698. #endif // defined(UNIX_LINUX) || defined(UNIX_MACOS)
  11699. sock->CallingThread = pthread_self();
  11700. #endif // OS_UNIX
  11701. #ifdef OS_WIN32
  11702. if (sock->EnableConditionalAccept)
  11703. {
  11704. new_socket = Win32Accept(sock, s, (struct sockaddr *)&addr,(int *)&size, false);
  11705. }
  11706. else
  11707. {
  11708. new_socket = accept(s, (struct sockaddr *)&addr,(int *)&size);
  11709. }
  11710. #else // OS_WIN32
  11711. new_socket = accept(s, (struct sockaddr *)&addr,(int *)&size);
  11712. #endif // OS_WIN32
  11713. #ifdef OS_UNIX
  11714. sock->CallingThread = 0;
  11715. #endif // OS_UNIX
  11716. if (new_socket == INVALID_SOCKET)
  11717. {
  11718. if (sock->CancelAccept)
  11719. {
  11720. sock->AcceptCanceled = true;
  11721. }
  11722. return NULL;
  11723. }
  11724. if (sock->CancelAccept)
  11725. {
  11726. sock->AcceptCanceled = true;
  11727. closesocket(new_socket);
  11728. return NULL;
  11729. }
  11730. ret = NewSock();
  11731. ret->socket = new_socket;
  11732. ret->Connected = true;
  11733. ret->AsyncMode = false;
  11734. ret->Type = SOCK_TCP;
  11735. ret->ServerMode = true;
  11736. ret->SecureMode = false;
  11737. // Configuring the TCP options
  11738. setsockopt(ret->socket, IPPROTO_TCP, TCP_NODELAY, (char *)&true_flag, sizeof(bool));
  11739. // Initialization of the time-out value
  11740. SetTimeout(ret, TIMEOUT_INFINITE);
  11741. // Socket information
  11742. QuerySocketInformation(ret);
  11743. if (IsLocalHostIP(&ret->RemoteIP) == false)
  11744. {
  11745. ret->IpClientAdded = true;
  11746. AddIpClient(&ret->RemoteIP);
  11747. }
  11748. if (IsZeroIp(&sock->LocalIP) == false && IsLocalHostIP(&sock->LocalIP) == false)
  11749. {
  11750. IP current_ip;
  11751. if (GetCurrentGlobalIP(&current_ip, false) == false)
  11752. {
  11753. SetCurrentGlobalIP(&sock->LocalIP, false);
  11754. }
  11755. }
  11756. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_NATIVE_V4);
  11757. return ret;
  11758. }
  11759. // TCP connection acceptance (IPv6)
  11760. SOCK *Accept6(SOCK *sock)
  11761. {
  11762. SOCK *ret;
  11763. SOCKET s, new_socket;
  11764. int size;
  11765. struct sockaddr_in6 addr;
  11766. bool true_flag = true;
  11767. // Validate arguments
  11768. if (sock == NULL)
  11769. {
  11770. return NULL;
  11771. }
  11772. if (sock->ListenMode == false || sock->Type != SOCK_TCP || sock->ServerMode == false)
  11773. {
  11774. return NULL;
  11775. }
  11776. if (sock->CancelAccept)
  11777. {
  11778. return NULL;
  11779. }
  11780. if (sock->IPv6 == false)
  11781. {
  11782. return NULL;
  11783. }
  11784. s = sock->socket;
  11785. if (s == INVALID_SOCKET)
  11786. {
  11787. return NULL;
  11788. }
  11789. Zero(&addr, sizeof(addr));
  11790. size = sizeof(addr);
  11791. #ifdef OS_UNIX
  11792. #if defined(UNIX_LINUX) || defined(UNIX_MACOS)
  11793. UnixIgnoreSignalForThread(SIGUSR1);
  11794. #endif // defined(UNIX_LINUX) || defined(UNIX_MACOS)
  11795. sock->CallingThread = pthread_self();
  11796. #endif // OS_UNIX
  11797. #ifdef OS_WIN32
  11798. if (sock->EnableConditionalAccept)
  11799. {
  11800. new_socket = Win32Accept(sock, s, (struct sockaddr *)&addr,(int *)&size, true);
  11801. }
  11802. else
  11803. {
  11804. new_socket = accept(s, (struct sockaddr *)&addr,(int *)&size);
  11805. }
  11806. #else // OS_WIN32
  11807. new_socket = accept(s, (struct sockaddr *)&addr,(int *)&size);
  11808. #endif // OS_WIN32
  11809. #ifdef OS_UNIX
  11810. sock->CallingThread = 0;
  11811. #endif // OS_UNIX
  11812. if (new_socket == INVALID_SOCKET)
  11813. {
  11814. if (sock->CancelAccept)
  11815. {
  11816. sock->AcceptCanceled = true;
  11817. }
  11818. return NULL;
  11819. }
  11820. if (sock->CancelAccept)
  11821. {
  11822. sock->AcceptCanceled = true;
  11823. closesocket(new_socket);
  11824. return NULL;
  11825. }
  11826. ret = NewSock();
  11827. ret->socket = new_socket;
  11828. ret->Connected = true;
  11829. ret->AsyncMode = false;
  11830. ret->Type = SOCK_TCP;
  11831. ret->ServerMode = true;
  11832. ret->SecureMode = false;
  11833. // Configuring the TCP options
  11834. setsockopt(ret->socket, IPPROTO_TCP, TCP_NODELAY, (char *)&true_flag, sizeof(bool));
  11835. // Initialize the time-out value
  11836. SetTimeout(ret, TIMEOUT_INFINITE);
  11837. // Socket information
  11838. QuerySocketInformation(ret);
  11839. if (IsLocalHostIP(&ret->RemoteIP) == false)
  11840. {
  11841. ret->IpClientAdded = true;
  11842. AddIpClient(&ret->RemoteIP);
  11843. }
  11844. if (IsZeroIp(&sock->LocalIP) == false && IsLocalHostIP(&sock->LocalIP) == false)
  11845. {
  11846. IP current_ip;
  11847. if (GetCurrentGlobalIP(&current_ip, true) == false)
  11848. {
  11849. SetCurrentGlobalIP(&sock->LocalIP, true);
  11850. }
  11851. }
  11852. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_NATIVE_V6);
  11853. return ret;
  11854. }
  11855. // Standby for TCP (IPv6)
  11856. SOCK *Listen6(UINT port)
  11857. {
  11858. return ListenEx6(port, false);
  11859. }
  11860. SOCK *ListenEx6(UINT port, bool local_only)
  11861. {
  11862. return ListenEx62(port, local_only, false);
  11863. }
  11864. SOCK *ListenEx62(UINT port, bool local_only, bool enable_ca)
  11865. {
  11866. SOCKET s;
  11867. SOCK *sock;
  11868. struct sockaddr_in6 addr;
  11869. struct in6_addr in;
  11870. bool true_flag = true;
  11871. bool disable_conditional_accept = false;
  11872. IP localhost;
  11873. UINT backlog = SOMAXCONN;
  11874. // Validate arguments
  11875. if (port == 0 || port >= 65536)
  11876. {
  11877. return NULL;
  11878. }
  11879. #ifdef OS_WIN32
  11880. if (MsIsVista() == false)
  11881. {
  11882. // Disable the Conditional Accept due to a bug in Windows
  11883. enable_ca = false;
  11884. }
  11885. #endif // OS_WIN32
  11886. // Initialization
  11887. Zero(&addr, sizeof(addr));
  11888. Zero(&in, sizeof(in));
  11889. GetLocalHostIP6(&localhost);
  11890. addr.sin6_port = htons((UINT)port);
  11891. addr.sin6_family = AF_INET6;
  11892. if (local_only)
  11893. {
  11894. IPToInAddr6(&addr.sin6_addr, &localhost);
  11895. enable_ca = false;
  11896. }
  11897. // Creating a socket
  11898. s = socket(AF_INET6, SOCK_STREAM, 0);
  11899. if (s == INVALID_SOCKET)
  11900. {
  11901. return NULL;
  11902. }
  11903. #ifdef OS_UNIX
  11904. // It is necessary to set the IPv6 Only flag on a UNIX system
  11905. setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &true_flag, sizeof(true_flag));
  11906. #endif // OS_UNIX
  11907. //SetSocketSendRecvBufferSize(s, SOCKET_BUFFER_SIZE);
  11908. #ifdef OS_UNIX
  11909. // This only have enabled for UNIX system since there is a bug
  11910. // in the implementation of REUSEADDR in Windows OS
  11911. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  11912. #endif // OS_UNIX
  11913. if (bind(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_in6)) != 0)
  11914. {
  11915. // Bind failure
  11916. closesocket(s);
  11917. return NULL;
  11918. }
  11919. #ifdef OS_WIN32
  11920. if (enable_ca)
  11921. {
  11922. if (MsIsWinXPOrGreater())
  11923. {
  11924. setsockopt(s, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char *)&true_flag, sizeof(bool));
  11925. backlog = 1;
  11926. }
  11927. }
  11928. #endif // OS_WIN32
  11929. if (listen(s, backlog))
  11930. {
  11931. // Listen failure
  11932. closesocket(s);
  11933. return NULL;
  11934. }
  11935. // Success
  11936. sock = NewSock();
  11937. sock->Connected = false;
  11938. sock->AsyncMode = false;
  11939. sock->ServerMode = true;
  11940. sock->Type = SOCK_TCP;
  11941. sock->socket = s;
  11942. sock->ListenMode = true;
  11943. sock->SecureMode = false;
  11944. sock->LocalPort = port;
  11945. sock->IPv6 = true;
  11946. sock->LocalOnly = local_only;
  11947. sock->EnableConditionalAccept = enable_ca;
  11948. return sock;
  11949. }
  11950. // Standby for the TCP
  11951. SOCK *Listen(UINT port)
  11952. {
  11953. return ListenEx(port, false);
  11954. }
  11955. SOCK *ListenEx(UINT port, bool local_only)
  11956. {
  11957. return ListenEx2(port, local_only, false);
  11958. }
  11959. SOCK *ListenEx2(UINT port, bool local_only, bool enable_ca)
  11960. {
  11961. SOCKET s;
  11962. SOCK *sock;
  11963. struct sockaddr_in addr;
  11964. struct in_addr in;
  11965. bool true_flag = true;
  11966. IP localhost;
  11967. UINT backlog = SOMAXCONN;
  11968. // Validate arguments
  11969. if (port == 0 || port >= 65536)
  11970. {
  11971. return NULL;
  11972. }
  11973. #ifdef OS_WIN32
  11974. if (MsIsVista() == false)
  11975. {
  11976. // Disable the Conditional Accept due to a bug in Windows
  11977. enable_ca = false;
  11978. }
  11979. #endif // OS_WIN32
  11980. // Initialization
  11981. Zero(&addr, sizeof(addr));
  11982. Zero(&in, sizeof(in));
  11983. SetIP(&localhost, 127, 0, 0, 1);
  11984. addr.sin_port = htons((UINT)port);
  11985. *((UINT *)&addr.sin_addr) = htonl(INADDR_ANY);
  11986. addr.sin_family = AF_INET;
  11987. if (local_only)
  11988. {
  11989. IPToInAddr(&addr.sin_addr, &localhost);
  11990. enable_ca = false;
  11991. }
  11992. // Creating a socket
  11993. s = socket(AF_INET, SOCK_STREAM, 0);
  11994. if (s == INVALID_SOCKET)
  11995. {
  11996. return NULL;
  11997. }
  11998. //SetSocketSendRecvBufferSize(s, SOCKET_BUFFER_SIZE);
  11999. #ifdef OS_UNIX
  12000. // This only have enabled for UNIX system since there is a bug
  12001. // in the implementation of REUSEADDR in Windows OS
  12002. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  12003. #endif // OS_UNIX
  12004. if (bind(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) != 0)
  12005. {
  12006. // Bind failure
  12007. closesocket(s);
  12008. return NULL;
  12009. }
  12010. #ifdef OS_WIN32
  12011. if (enable_ca)
  12012. {
  12013. if (MsIsWinXPOrGreater())
  12014. {
  12015. setsockopt(s, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char *)&true_flag, sizeof(bool));
  12016. backlog = 1;
  12017. }
  12018. }
  12019. #endif // OS_WIN32
  12020. if (listen(s, backlog))
  12021. {
  12022. // Listen failure
  12023. closesocket(s);
  12024. return NULL;
  12025. }
  12026. // Success
  12027. sock = NewSock();
  12028. sock->Connected = false;
  12029. sock->AsyncMode = false;
  12030. sock->ServerMode = true;
  12031. sock->Type = SOCK_TCP;
  12032. sock->socket = s;
  12033. sock->ListenMode = true;
  12034. sock->SecureMode = false;
  12035. sock->LocalPort = port;
  12036. sock->LocalOnly = local_only;
  12037. sock->EnableConditionalAccept = enable_ca;
  12038. return sock;
  12039. }
  12040. // TCP disconnect
  12041. void Disconnect(SOCK *sock)
  12042. {
  12043. SOCKET s;
  12044. bool true_flag = true;
  12045. bool false_flag = false;
  12046. // Validate arguments
  12047. if (sock == NULL)
  12048. {
  12049. return;
  12050. }
  12051. sock->Disconnecting = true;
  12052. #ifdef ENABLE_SSL_LOGGING
  12053. SockCloseSslLogging(sock);
  12054. #endif // ENABLE_SSL_LOGGING
  12055. #ifdef OS_UNIX
  12056. UnixFreeAsyncSocket(sock);
  12057. #endif // UnixFreeAsyncSocket
  12058. if (sock->Type == SOCK_TCP && sock->ListenMode)
  12059. {
  12060. bool no_tcp_check_port = false;
  12061. // Connect to localhost if the socket is in listening
  12062. sock->CancelAccept = true;
  12063. #if defined(UNIX_LINUX) || defined(UNIX_MACOS)
  12064. {
  12065. pthread_t t = sock->CallingThread;
  12066. // Send a signal to the socket to abort accept() forcibly on Linux
  12067. if (t != 0)
  12068. {
  12069. pthread_kill(t, SIGUSR1);
  12070. SleepThread(200);
  12071. }
  12072. }
  12073. #endif // defined(UNIX_LINUX) || defined(UNIX_MACOS)
  12074. #ifdef OS_WIN32
  12075. if (sock->hAcceptEvent != NULL)
  12076. {
  12077. SetEvent(sock->hAcceptEvent);
  12078. no_tcp_check_port = true;
  12079. }
  12080. #endif // OS_WIN32
  12081. if (sock->AcceptCanceled == false)
  12082. {
  12083. if (no_tcp_check_port == false)
  12084. {
  12085. if (sock->IPv6 == false)
  12086. {
  12087. CheckTCPPort("127.0.0.1", sock->LocalPort);
  12088. }
  12089. else
  12090. {
  12091. CheckTCPPort("::1", sock->LocalPort);
  12092. }
  12093. }
  12094. }
  12095. }
  12096. Lock(disconnect_function_lock);
  12097. Lock(sock->disconnect_lock);
  12098. if (sock->Type == SOCK_TCP)
  12099. {
  12100. if (sock->socket != INVALID_SOCKET)
  12101. {
  12102. // Forced disconnection flag
  12103. #ifdef SO_DONTLINGER
  12104. setsockopt(sock->socket, SOL_SOCKET, SO_DONTLINGER, (char *)&true_flag, sizeof(bool));
  12105. #else // SO_DONTLINGER
  12106. setsockopt(sock->socket, SOL_SOCKET, SO_LINGER, (char *)&false_flag, sizeof(bool));
  12107. #endif // SO_DONTLINGER
  12108. // setsockopt(sock->socket, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  12109. }
  12110. // TCP socket
  12111. Lock(sock->lock);
  12112. {
  12113. if (sock->socket == INVALID_SOCKET)
  12114. {
  12115. Unlock(sock->lock);
  12116. Unlock(sock->disconnect_lock);
  12117. Unlock(disconnect_function_lock);
  12118. return;
  12119. }
  12120. s = sock->socket;
  12121. if (sock->Connected)
  12122. {
  12123. struct linger ling;
  12124. Zero(&ling, sizeof(ling));
  12125. #if 0
  12126. // SSL disconnect
  12127. Lock(sock->ssl_lock);
  12128. {
  12129. if (sock->SecureMode)
  12130. {
  12131. SSL_shutdown(sock->ssl);
  12132. }
  12133. }
  12134. Unlock(sock->ssl_lock);
  12135. #endif
  12136. // Disconnect
  12137. shutdown(s, 2);
  12138. }
  12139. // Close the socket
  12140. closesocket(s);
  12141. #ifdef OS_UNIX
  12142. #ifdef FIX_SSL_BLOCKING
  12143. if (sock->CallingThread != NULL)
  12144. {
  12145. pthread_kill(sock->CallingThread, 64);
  12146. }
  12147. #endif // FIX_SSL_BLOCKING
  12148. #endif // OS_UNIX
  12149. // Release the SSL
  12150. Lock(sock->ssl_lock);
  12151. {
  12152. if (sock->SecureMode)
  12153. {
  12154. if (sock->ssl != NULL)
  12155. {
  12156. Lock(openssl_lock);
  12157. {
  12158. SSL_free(sock->ssl);
  12159. FreeSSLCtx(sock->ssl_ctx);
  12160. }
  12161. Unlock(openssl_lock);
  12162. sock->ssl = NULL;
  12163. sock->ssl_ctx = NULL;
  12164. }
  12165. sock->Connected = false;
  12166. sock->SecureMode = false;
  12167. }
  12168. }
  12169. Unlock(sock->ssl_lock);
  12170. // Initialization
  12171. sock->socket = INVALID_SOCKET;
  12172. sock->Type = 0;
  12173. sock->AsyncMode = false;
  12174. sock->Connected = false;
  12175. sock->ListenMode = false;
  12176. sock->SecureMode = false;
  12177. if (sock->IpClientAdded)
  12178. {
  12179. DelIpClient(&sock->RemoteIP);
  12180. sock->IpClientAdded = false;
  12181. }
  12182. }
  12183. Unlock(sock->lock);
  12184. if (sock->BulkSendTube != NULL)
  12185. {
  12186. TubeDisconnect(sock->BulkSendTube);
  12187. }
  12188. if (sock->BulkRecvTube != NULL)
  12189. {
  12190. TubeDisconnect(sock->BulkRecvTube);
  12191. }
  12192. }
  12193. else if (sock->Type == SOCK_UDP)
  12194. {
  12195. // UDP socket
  12196. Lock(sock->lock);
  12197. {
  12198. if (sock->socket == INVALID_SOCKET)
  12199. {
  12200. Unlock(sock->lock);
  12201. Unlock(sock->disconnect_lock);
  12202. Unlock(disconnect_function_lock);
  12203. return;
  12204. }
  12205. s = sock->socket;
  12206. // Close the socket
  12207. closesocket(s);
  12208. // Initialization
  12209. sock->socket = INVALID_SOCKET;
  12210. sock->Type = 0;
  12211. sock->AsyncMode = false;
  12212. sock->Connected = false;
  12213. sock->ListenMode = false;
  12214. sock->SecureMode = false;
  12215. }
  12216. Unlock(sock->lock);
  12217. }
  12218. else if (sock->Type == SOCK_INPROC)
  12219. {
  12220. // In-process socket
  12221. if (sock->ListenMode)
  12222. {
  12223. // Stop the Accept process
  12224. sock->CancelAccept = true;
  12225. Set(sock->InProcAcceptEvent);
  12226. LockQueue(sock->InProcAcceptQueue);
  12227. {
  12228. while (true)
  12229. {
  12230. SOCK *ss = GetNext(sock->InProcAcceptQueue);
  12231. if (ss == NULL)
  12232. {
  12233. break;
  12234. }
  12235. Disconnect(ss);
  12236. ReleaseSock(ss);
  12237. }
  12238. }
  12239. UnlockQueue(sock->InProcAcceptQueue);
  12240. }
  12241. else
  12242. {
  12243. // Disconnect the Tube
  12244. TubeDisconnect(sock->SendTube);
  12245. TubeDisconnect(sock->RecvTube);
  12246. sock->socket = INVALID_SOCKET;
  12247. sock->AsyncMode = false;
  12248. sock->Connected = false;
  12249. sock->ListenMode = false;
  12250. sock->SecureMode = false;
  12251. }
  12252. }
  12253. else if (sock->Type == SOCK_RUDP_LISTEN)
  12254. {
  12255. // RUDP Listen socket
  12256. if (sock->ListenMode)
  12257. {
  12258. // Stop the Accept process
  12259. sock->CancelAccept = true;
  12260. Set(sock->R_UDP_Stack->NewSockConnectEvent);
  12261. sock->R_UDP_Stack->Halt = true;
  12262. Set(sock->R_UDP_Stack->HaltEvent);
  12263. SetSockEvent(sock->R_UDP_Stack->SockEvent);
  12264. }
  12265. }
  12266. else if (sock->Type == SOCK_REVERSE_LISTEN)
  12267. {
  12268. // Reverse Listen socket
  12269. if (sock->ListenMode)
  12270. {
  12271. // Stop the Accept process
  12272. sock->CancelAccept = true;
  12273. Set(sock->ReverseAcceptEvent);
  12274. LockQueue(sock->ReverseAcceptQueue);
  12275. {
  12276. while (true)
  12277. {
  12278. SOCK *ss = GetNext(sock->ReverseAcceptQueue);
  12279. if (ss == NULL)
  12280. {
  12281. break;
  12282. }
  12283. Disconnect(ss);
  12284. ReleaseSock(ss);
  12285. }
  12286. }
  12287. UnlockQueue(sock->ReverseAcceptQueue);
  12288. }
  12289. }
  12290. Unlock(sock->disconnect_lock);
  12291. Unlock(disconnect_function_lock);
  12292. }
  12293. typedef struct TCP_PORT_CHECK
  12294. {
  12295. REF *ref;
  12296. char hostname[MAX_SIZE];
  12297. UINT port;
  12298. bool ok;
  12299. } TCP_PORT_CHECK;
  12300. // The thread to check the TCP port
  12301. void CheckTCPPortThread(THREAD *thread, void *param)
  12302. {
  12303. TCP_PORT_CHECK *c;
  12304. SOCK *s;
  12305. // Validate arguments
  12306. if (thread == NULL || param == NULL)
  12307. {
  12308. return;
  12309. }
  12310. c = (TCP_PORT_CHECK *)param;
  12311. AddRef(c->ref);
  12312. NoticeThreadInit(thread);
  12313. AddWaitThread(thread);
  12314. s = Connect(c->hostname, c->port);
  12315. if (s != NULL)
  12316. {
  12317. c->ok = true;
  12318. Disconnect(s);
  12319. ReleaseSock(s);
  12320. }
  12321. if (Release(c->ref) == 0)
  12322. {
  12323. Free(c);
  12324. }
  12325. DelWaitThread(thread);
  12326. }
  12327. // Check whether the TCP port can be connected
  12328. bool CheckTCPPortEx(char *hostname, UINT port, UINT timeout)
  12329. {
  12330. SOCK *s;
  12331. // Validate arguments
  12332. if (hostname == NULL || port == 0 || port >= 65536)
  12333. {
  12334. return false;
  12335. }
  12336. if (timeout == 0)
  12337. {
  12338. timeout = TIMEOUT_TCP_PORT_CHECK;
  12339. }
  12340. s = ConnectEx(hostname, port, timeout);
  12341. if (s == NULL)
  12342. {
  12343. return false;
  12344. }
  12345. else
  12346. {
  12347. Disconnect(s);
  12348. ReleaseSock(s);
  12349. return true;
  12350. }
  12351. }
  12352. bool CheckTCPPort(char *hostname, UINT port)
  12353. {
  12354. return CheckTCPPortEx(hostname, port, TIMEOUT_TCP_PORT_CHECK);
  12355. }
  12356. #ifdef OS_UNIX
  12357. // Connection with timeout (UNIX version)
  12358. int connect_timeout(SOCKET s, struct sockaddr *addr, int size, int timeout, bool *cancel_flag)
  12359. {
  12360. SOCKSET set;
  12361. bool ok = false;
  12362. UINT64 start_time;
  12363. // Validate arguments
  12364. if (s == INVALID_SOCKET || addr == NULL)
  12365. {
  12366. return -1;
  12367. }
  12368. if (timeout == 0)
  12369. {
  12370. timeout = TIMEOUT_TCP_PORT_CHECK;
  12371. }
  12372. UnixSetSocketNonBlockingMode(s, true);
  12373. start_time = Tick64();
  12374. while (true)
  12375. {
  12376. int ret;
  12377. ret = connect(s, addr, size);
  12378. if (ret == 0 || errno == EISCONN)
  12379. {
  12380. ok = true;
  12381. break;
  12382. }
  12383. else
  12384. {
  12385. if (((start_time + (UINT64)timeout) <= Tick64()) || (errno != EAGAIN && errno != EINPROGRESS && errno != EALREADY))
  12386. {
  12387. // Failure
  12388. break;
  12389. }
  12390. else if (*cancel_flag)
  12391. {
  12392. // Cancel
  12393. break;
  12394. }
  12395. else
  12396. {
  12397. // Connecting
  12398. SleepThread(50);
  12399. UnixSelectInner(1, (UINT *)&s, 1, (UINT *)&s, 100);
  12400. }
  12401. }
  12402. }
  12403. UnixSetSocketNonBlockingMode(s, false);
  12404. if (ok)
  12405. {
  12406. return 0;
  12407. }
  12408. else
  12409. {
  12410. return -1;
  12411. }
  12412. }
  12413. #else
  12414. // Connection with timeout (Win32 version)
  12415. int connect_timeout(SOCKET s, struct sockaddr *addr, int size, int timeout, bool *cancel_flag)
  12416. {
  12417. UINT64 start_time;
  12418. bool ok = false;
  12419. bool timeouted = false;
  12420. WSAEVENT hEvent;
  12421. UINT zero = 0;
  12422. UINT tmp = 0;
  12423. UINT ret_size = 0;
  12424. bool is_nt = false;
  12425. // Validate arguments
  12426. if (s == INVALID_SOCKET || addr == NULL)
  12427. {
  12428. return -1;
  12429. }
  12430. if (timeout == 0)
  12431. {
  12432. timeout = TIMEOUT_TCP_PORT_CHECK;
  12433. }
  12434. is_nt = OS_IS_WINDOWS_NT(GetOsInfo()->OsType);
  12435. // Create an event
  12436. hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  12437. // Associate the socket with the event
  12438. WSAEventSelect(s, hEvent, FD_CONNECT);
  12439. start_time = Tick64();
  12440. while (true)
  12441. {
  12442. int ret;
  12443. ret = connect(s, addr, size);
  12444. if (ret == 0)
  12445. {
  12446. ok = true;
  12447. break;
  12448. }
  12449. else
  12450. {
  12451. int err = WSAGetLastError();
  12452. //Debug("err=%u\n", err);
  12453. //Debug("cancel_flag=%u\n", *cancel_flag);
  12454. if (timeouted && ((err == WSAEALREADY) || (err == WSAEWOULDBLOCK && !is_nt)))
  12455. {
  12456. // Time-out
  12457. ok = false;
  12458. break;
  12459. }
  12460. if (*cancel_flag)
  12461. {
  12462. // Cancel
  12463. ok = false;
  12464. break;
  12465. }
  12466. if (err == WSAEISCONN || (err == WSAEINVAL && is_nt))
  12467. {
  12468. ok = true;
  12469. break;
  12470. }
  12471. if (((start_time + (UINT64)timeout) <= Tick64()) || (err != WSAEWOULDBLOCK && err != WSAEALREADY && (is_nt || err != WSAEINVAL)))
  12472. {
  12473. // Failure (timeout)
  12474. break;
  12475. }
  12476. else
  12477. {
  12478. SleepThread(10);
  12479. // Connecting
  12480. if (WaitForSingleObject(hEvent, 100) == WAIT_OBJECT_0)
  12481. {
  12482. timeouted = true;
  12483. }
  12484. }
  12485. }
  12486. }
  12487. // Remove the socket from the event
  12488. WSAEventSelect(s, hEvent, 0);
  12489. // Restore to synchronized socket
  12490. WSAIoctl(s, FIONBIO, &zero, sizeof(zero), &tmp, sizeof(tmp), &ret_size, NULL, NULL);
  12491. // Close the event
  12492. CloseHandle(hEvent);
  12493. if (ok)
  12494. {
  12495. return 0;
  12496. }
  12497. else
  12498. {
  12499. return -1;
  12500. }
  12501. }
  12502. #endif // OS_UNIX
  12503. // Set the TOS value of the socket
  12504. void SetSockTos(SOCK *s, int tos)
  12505. {
  12506. // Validate arguments
  12507. if (s == NULL)
  12508. {
  12509. return;
  12510. }
  12511. if (s->CurrentTos == tos)
  12512. {
  12513. return;
  12514. }
  12515. #ifdef IP_TOS
  12516. setsockopt(s->socket, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int));
  12517. #endif // IP_TOS
  12518. s->CurrentTos = tos;
  12519. }
  12520. // Set the priority of the socket
  12521. void SetSockHighPriority(SOCK *s, bool flag)
  12522. {
  12523. // Validate arguments
  12524. if (s == NULL)
  12525. {
  12526. return;
  12527. }
  12528. SetSockTos(s, (flag ? 16 : 0));
  12529. }
  12530. // Connect to the IPv4 host using a socket
  12531. SOCKET ConnectTimeoutIPv4(IP *ip, UINT port, UINT timeout, bool *cancel_flag)
  12532. {
  12533. SOCKET s;
  12534. struct sockaddr_in sockaddr4;
  12535. struct in_addr addr4;
  12536. Zero(&sockaddr4, sizeof(sockaddr4));
  12537. Zero(&addr4, sizeof(addr4));
  12538. // Generate a sockaddr_in
  12539. IPToInAddr(&addr4, ip);
  12540. sockaddr4.sin_port = htons((USHORT)port);
  12541. sockaddr4.sin_family = AF_INET;
  12542. sockaddr4.sin_addr.s_addr = addr4.s_addr;
  12543. // Socket creation
  12544. s = socket(AF_INET, SOCK_STREAM, 0);
  12545. if (s != INVALID_SOCKET)
  12546. {
  12547. // Connection
  12548. if (connect_timeout(s, (struct sockaddr *)&sockaddr4, sizeof(struct sockaddr_in), timeout, cancel_flag) != 0)
  12549. {
  12550. // Connection failure
  12551. closesocket(s);
  12552. s = INVALID_SOCKET;
  12553. }
  12554. }
  12555. return s;
  12556. }
  12557. // Identify whether the HTTPS server to be connected is a SoftEther VPN
  12558. bool DetectIsServerSoftEtherVPN(SOCK *s)
  12559. {
  12560. HTTP_HEADER *h;
  12561. char ip_str[MAX_SIZE];
  12562. char *send_str;
  12563. UINT content_len;
  12564. BUF *recv_buf;
  12565. void *socket_buffer;
  12566. UINT socket_buffer_size = 32768;
  12567. bool ok = false;
  12568. // Validate arguments
  12569. if (s == NULL)
  12570. {
  12571. return false;
  12572. }
  12573. IPToStr(ip_str, sizeof(ip_str), &s->RemoteIP);
  12574. // Request generation
  12575. h = NewHttpHeaderEx("GET", "/", "HTTP/1.1", true);
  12576. AddHttpValue(h, NewHttpValue("X-VPN", "1"));
  12577. AddHttpValue(h, NewHttpValue("Host", ip_str));
  12578. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  12579. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  12580. AddHttpValue(h, NewHttpValue("Accept-Language", "ja"));
  12581. AddHttpValue(h, NewHttpValue("User-Agent", DEFAULT_USER_AGENT));
  12582. AddHttpValue(h, NewHttpValue("Pragma", "no-cache"));
  12583. AddHttpValue(h, NewHttpValue("Cache-Control", "no-cache"));
  12584. send_str = HttpHeaderToStr(h);
  12585. FreeHttpHeader(h);
  12586. // Transmission
  12587. if (SendAll(s, send_str, StrLen(send_str), true) == false)
  12588. {
  12589. Free(send_str);
  12590. return false;
  12591. }
  12592. Free(send_str);
  12593. // Receive
  12594. h = RecvHttpHeader(s);
  12595. if (h == NULL)
  12596. {
  12597. return false;
  12598. }
  12599. // Get the length of the content
  12600. content_len = GetContentLength(h);
  12601. FreeHttpHeader(h);
  12602. if (content_len == 0 || content_len >= (1024 * 1024))
  12603. {
  12604. return false;
  12605. }
  12606. // Receive contents
  12607. recv_buf = NewBuf();
  12608. socket_buffer = Malloc(socket_buffer_size);
  12609. while (true)
  12610. {
  12611. UINT recvsize = MIN(socket_buffer_size, content_len - recv_buf->Size);
  12612. UINT size;
  12613. if (recvsize == 0)
  12614. {
  12615. ok = true;
  12616. break;
  12617. }
  12618. size = Recv(s, socket_buffer, recvsize, true);
  12619. if (size == 0)
  12620. {
  12621. // Disconnected
  12622. break;
  12623. }
  12624. WriteBuf(recv_buf, socket_buffer, size);
  12625. }
  12626. SeekBuf(recv_buf, 0, 0);
  12627. Free(socket_buffer);
  12628. if (ok)
  12629. {
  12630. // Examine to confirm whether the incoming data is a SoftEther VPN protocol
  12631. char tmp[1024];
  12632. Zero(tmp, sizeof(tmp));
  12633. Copy(tmp, recv_buf->Buf, MIN(recv_buf->Size, (sizeof(tmp) - 1)));
  12634. ok = false;
  12635. if (StartWith(tmp, http_detect_server_startwith))
  12636. {
  12637. ok = true;
  12638. }
  12639. else if (InStr(tmp, http_detect_server_tag_future))
  12640. {
  12641. ok = true;
  12642. }
  12643. }
  12644. FreeBuf(recv_buf);
  12645. return ok;
  12646. }
  12647. // TCP connection thread
  12648. void ConnectThreadForTcp(THREAD *thread, void *param)
  12649. {
  12650. SOCK *sock;
  12651. char hostname[MAX_SIZE];
  12652. CONNECT_TCP_RUDP_PARAM *p = (CONNECT_TCP_RUDP_PARAM *)param;
  12653. if (thread == NULL || p == NULL)
  12654. {
  12655. return;
  12656. }
  12657. // Delay
  12658. if (p->Delay >= 1)
  12659. {
  12660. WaitEx(NULL, p->Delay, p->CancelFlag);
  12661. }
  12662. // Connecting process
  12663. IPToStr(hostname, sizeof(hostname), &p->Ip);
  12664. sock = ConnectEx3(hostname, p->Port, p->Timeout, p->CancelFlag, NULL, NULL, false, false, true);
  12665. if (sock != NULL && p->Tcp_TryStartSsl)
  12666. {
  12667. bool ssl_ret = false;
  12668. p->Tcp_InNegotiation = true;
  12669. // Attempt the SSL negotiation to take this opportunity
  12670. Lock(p->CancelLock);
  12671. {
  12672. if ((*p->CancelFlag) == false)
  12673. {
  12674. p->CancelDisconnectSock = sock;
  12675. AddRef(sock->ref);
  12676. }
  12677. else
  12678. {
  12679. Debug("User Cancel to StartSSL.\n");
  12680. goto LABEL_CANCEL;
  12681. }
  12682. }
  12683. Unlock(p->CancelLock);
  12684. // Start the SSL communication
  12685. ssl_ret = StartSSLEx(sock, NULL, NULL, p->Tcp_SslNoTls, 0, p->Hostname);
  12686. if (ssl_ret)
  12687. {
  12688. // Identify whether the HTTPS server to be connected is a SoftEther VPN
  12689. SetTimeout(sock, (10 * 1000));
  12690. ssl_ret = DetectIsServerSoftEtherVPN(sock);
  12691. SetTimeout(sock, INFINITE);
  12692. if (ssl_ret == false)
  12693. {
  12694. Debug("DetectIsServerSoftEtherVPN Error.\n");
  12695. }
  12696. }
  12697. Lock(p->CancelLock);
  12698. {
  12699. ReleaseSock(p->CancelDisconnectSock);
  12700. p->CancelDisconnectSock = NULL;
  12701. LABEL_CANCEL:
  12702. DoNothing();
  12703. }
  12704. Unlock(p->CancelLock);
  12705. if (ssl_ret == false)
  12706. {
  12707. // SSL negotiation failure
  12708. Disconnect(sock);
  12709. ReleaseSock(sock);
  12710. Debug("Fail to StartSSL.\n");
  12711. sock = NULL;
  12712. }
  12713. }
  12714. p->Result_Tcp_Sock = sock;
  12715. p->Ok = (p->Result_Tcp_Sock == NULL ? false : true);
  12716. p->FinishedTick = Tick64();
  12717. p->Finished = true;
  12718. p->Tcp_InNegotiation = false;
  12719. Set(p->FinishEvent);
  12720. }
  12721. // R-UDP over ICMP / over DNS connection thread
  12722. void ConnectThreadForOverDnsOrIcmp(THREAD *thread, void *param)
  12723. {
  12724. SOCK *sock;
  12725. CONNECT_TCP_RUDP_PARAM *p = (CONNECT_TCP_RUDP_PARAM *)param;
  12726. if (thread == NULL || p == NULL)
  12727. {
  12728. return;
  12729. }
  12730. // Delay
  12731. if (p->Delay >= 1)
  12732. {
  12733. WaitEx(NULL, p->Delay, p->CancelFlag);
  12734. }
  12735. // Connecting process
  12736. sock = NewRUDPClientDirect(p->SvcName, &p->Ip,
  12737. (p->RUdpProtocol == RUDP_PROTOCOL_DNS ? 53 : MAKE_SPECIAL_PORT(IP_PROTO_ICMPV4)),
  12738. &p->NatT_ErrorCode, p->Timeout, p->CancelFlag, NULL, NULL,
  12739. (p->RUdpProtocol == RUDP_PROTOCOL_DNS ? 0 : MAKE_SPECIAL_PORT(IP_PROTO_ICMPV4)),
  12740. (p->RUdpProtocol == RUDP_PROTOCOL_DNS ? true : false));
  12741. p->Result_Nat_T_Sock = sock;
  12742. p->Ok = (p->Result_Nat_T_Sock == NULL ? false : true);
  12743. p->FinishedTick = Tick64();
  12744. p->Finished = true;
  12745. Set(p->FinishEvent);
  12746. }
  12747. // R-UDP (via NAT-T) connection thread
  12748. void ConnectThreadForRUDP(THREAD *thread, void *param)
  12749. {
  12750. SOCK *sock;
  12751. CONNECT_TCP_RUDP_PARAM *p = (CONNECT_TCP_RUDP_PARAM *)param;
  12752. if (thread == NULL || p == NULL)
  12753. {
  12754. return;
  12755. }
  12756. // Delay
  12757. if (p->Delay >= 1)
  12758. {
  12759. WaitEx(NULL, p->Delay, p->CancelFlag);
  12760. }
  12761. // Connecting process
  12762. sock = NewRUDPClientNatT(p->SvcName, &p->Ip, &p->NatT_ErrorCode, p->Timeout, p->CancelFlag, p->HintStr, p->TargetHostname);
  12763. p->Result_Nat_T_Sock = sock;
  12764. p->Ok = (p->Result_Nat_T_Sock == NULL ? false : true);
  12765. p->FinishedTick = Tick64();
  12766. p->Finished = true;
  12767. Set(p->FinishEvent);
  12768. }
  12769. // TCP connection
  12770. SOCK *Connect(char *hostname, UINT port)
  12771. {
  12772. return ConnectEx(hostname, port, 0);
  12773. }
  12774. SOCK *ConnectEx(char *hostname, UINT port, UINT timeout)
  12775. {
  12776. return ConnectEx2(hostname, port, timeout, NULL);
  12777. }
  12778. SOCK *ConnectEx2(char *hostname, UINT port, UINT timeout, bool *cancel_flag)
  12779. {
  12780. return ConnectEx3(hostname, port, timeout, cancel_flag, NULL, NULL, false, false, true);
  12781. }
  12782. SOCK *ConnectEx3(char *hostname, UINT port, UINT timeout, bool *cancel_flag, char *nat_t_svc_name, UINT *nat_t_error_code, bool try_start_ssl, bool ssl_no_tls, bool no_get_hostname)
  12783. {
  12784. return ConnectEx4(hostname, port, timeout, cancel_flag, nat_t_svc_name, nat_t_error_code, try_start_ssl, ssl_no_tls,
  12785. no_get_hostname, NULL);
  12786. }
  12787. SOCK *ConnectEx4(char *hostname, UINT port, UINT timeout, bool *cancel_flag, char *nat_t_svc_name, UINT *nat_t_error_code, bool try_start_ssl, bool ssl_no_tls, bool no_get_hostname, IP *ret_ip)
  12788. {
  12789. SOCK *sock;
  12790. SOCKET s;
  12791. struct linger ling;
  12792. IP ip4;
  12793. IP ip6;
  12794. bool true_flag = true;
  12795. bool false_flag = false;
  12796. char tmp[MAX_SIZE];
  12797. IP current_ip;
  12798. bool is_ipv6 = false;
  12799. bool dummy = false;
  12800. bool use_natt = false;
  12801. char hostname_original[MAX_SIZE];
  12802. char hint_str[MAX_SIZE];
  12803. bool force_use_natt = false;
  12804. UINT dummy_int = 0;
  12805. IP dummy_ret_ip;
  12806. // Validate arguments
  12807. if (hostname == NULL || port == 0 || port >= 65536 || IsEmptyStr(hostname))
  12808. {
  12809. return NULL;
  12810. }
  12811. if (timeout == 0)
  12812. {
  12813. timeout = TIMEOUT_TCP_PORT_CHECK;
  12814. }
  12815. if (cancel_flag == NULL)
  12816. {
  12817. cancel_flag = &dummy;
  12818. }
  12819. if (nat_t_error_code == NULL)
  12820. {
  12821. nat_t_error_code = &dummy_int;
  12822. }
  12823. Zero(&dummy_ret_ip, sizeof(IP));
  12824. if (ret_ip == NULL)
  12825. {
  12826. ret_ip = &dummy_ret_ip;
  12827. }
  12828. Zero(hint_str, sizeof(hint_str));
  12829. StrCpy(hostname_original, sizeof(hostname_original), hostname);
  12830. use_natt = (IsEmptyStr(nat_t_svc_name) ? false : true);
  12831. if (use_natt)
  12832. {
  12833. // In case of using NAT-T, split host name if the '/' is included in the host name
  12834. UINT i = SearchStrEx(hostname, "/", 0, false);
  12835. if (i == INFINITE)
  12836. {
  12837. // Not included
  12838. StrCpy(hostname_original, sizeof(hostname_original), hostname);
  12839. }
  12840. else
  12841. {
  12842. // Included
  12843. StrCpy(hostname_original, sizeof(hostname_original), hostname);
  12844. hostname_original[i] = 0;
  12845. // Force to use the NAT-T
  12846. force_use_natt = true;
  12847. // Copy the hint string
  12848. StrCpy(hint_str, sizeof(hint_str), hostname + i + 1);
  12849. if (StrCmpi(hint_str, "tcp") == 0 || StrCmpi(hint_str, "disable") == 0
  12850. || StrCmpi(hint_str, "disabled") == 0
  12851. || StrCmpi(hint_str, "no") == 0 || StrCmpi(hint_str, "none") == 0)
  12852. {
  12853. // Force not to use the NAT-T
  12854. force_use_natt = false;
  12855. use_natt = false;
  12856. }
  12857. }
  12858. }
  12859. else
  12860. {
  12861. StrCpy(hostname_original, sizeof(hostname_original), hostname);
  12862. }
  12863. Zero(&current_ip, sizeof(current_ip));
  12864. Zero(&ip4, sizeof(ip4));
  12865. Zero(&ip6, sizeof(ip6));
  12866. if (IsZeroIp(ret_ip) == false)
  12867. {
  12868. // Skip name resolution
  12869. if (IsIP6(ret_ip))
  12870. {
  12871. Copy(&ip6, ret_ip, sizeof(IP));
  12872. }
  12873. else
  12874. {
  12875. Copy(&ip4, ret_ip, sizeof(IP));
  12876. }
  12877. //Debug("Using cached IP address: %s = %r\n", hostname_original, ret_ip);
  12878. }
  12879. else
  12880. {
  12881. // Forward resolution
  12882. if (GetIP46Ex(&ip4, &ip6, hostname_original, 0, cancel_flag) == false)
  12883. {
  12884. return NULL;
  12885. }
  12886. }
  12887. if (IsZeroIp(&ip4) == false && IsIPLocalHostOrMySelf(&ip4))
  12888. {
  12889. // NAT-T isn't used in the case of connection to localhost
  12890. force_use_natt = false;
  12891. use_natt = false;
  12892. }
  12893. s = INVALID_SOCKET;
  12894. // Attempt to connect with IPv4
  12895. if (IsZeroIp(&ip4) == false)
  12896. {
  12897. if (use_natt == false)
  12898. {
  12899. // Normal connection without using NAT-T
  12900. s = ConnectTimeoutIPv4(&ip4, port, timeout, cancel_flag);
  12901. if (s != INVALID_SOCKET)
  12902. {
  12903. Copy(&current_ip, &ip4, sizeof(IP));
  12904. Copy(ret_ip, &ip4, sizeof(IP));
  12905. }
  12906. }
  12907. else if (force_use_natt)
  12908. {
  12909. // The connection by forcing the use of NAT-T (not to connection with normal TCP)
  12910. SOCK *nat_t_sock = NewRUDPClientNatT(nat_t_svc_name, &ip4, nat_t_error_code, timeout, cancel_flag,
  12911. hint_str, hostname);
  12912. if (nat_t_sock != NULL)
  12913. {
  12914. StrCpy(nat_t_sock->UnderlayProtocol, sizeof(nat_t_sock->UnderlayProtocol), SOCK_UNDERLAY_NAT_T);
  12915. }
  12916. Copy(ret_ip, &ip4, sizeof(IP));
  12917. return nat_t_sock;
  12918. }
  12919. else
  12920. {
  12921. // Use the connections using NAT-T with normal TCP connection together
  12922. // (Use multiple threads to try to connect in four connection methods concurrently)
  12923. CONNECT_TCP_RUDP_PARAM p1, p2, p3, p4;
  12924. EVENT *finish_event;
  12925. THREAD *t1, *t2, *t3, *t4;
  12926. UINT64 start_tick = Tick64();
  12927. UINT64 giveup_for_all_tick = start_tick + (UINT64)SOCK_CONNECT_WAIT_FOR_ICMP_AND_DNS_AT_LEAST;
  12928. bool cancel_flag2 = false;
  12929. SOCK *cancel_sock = NULL;
  12930. finish_event = NewEvent();
  12931. Zero(&p1, sizeof(p1));
  12932. Zero(&p2, sizeof(p2));
  12933. Zero(&p3, sizeof(p3));
  12934. Zero(&p4, sizeof(p4));
  12935. // p1: TCP
  12936. StrCpy(p1.Hostname, sizeof(p1.Hostname), hostname_original);
  12937. Copy(&p1.Ip, &ip4, sizeof(IP));
  12938. p1.Port = port;
  12939. p1.Timeout = timeout;
  12940. p1.CancelFlag = &cancel_flag2;
  12941. p1.FinishEvent = finish_event;
  12942. p1.Tcp_TryStartSsl = try_start_ssl;
  12943. p1.Tcp_SslNoTls = ssl_no_tls;
  12944. p1.CancelLock = NewLock();
  12945. // p2: NAT-T
  12946. StrCpy(p2.Hostname, sizeof(p2.Hostname), hostname_original);
  12947. Copy(&p2.Ip, &ip4, sizeof(IP));
  12948. p2.Port = port;
  12949. p2.Timeout = timeout;
  12950. p2.CancelFlag = &cancel_flag2;
  12951. p2.FinishEvent = finish_event;
  12952. StrCpy(p2.HintStr, sizeof(p2.HintStr), hint_str);
  12953. StrCpy(p2.TargetHostname, sizeof(p2.TargetHostname), hostname);
  12954. StrCpy(p2.SvcName, sizeof(p2.SvcName), nat_t_svc_name);
  12955. p2.Delay = 30; // Delay by 30ms
  12956. // p3: over ICMP
  12957. StrCpy(p3.Hostname, sizeof(p3.Hostname), hostname_original);
  12958. Copy(&p3.Ip, &ip4, sizeof(IP));
  12959. p3.Port = port;
  12960. p3.Timeout = timeout;
  12961. p3.CancelFlag = &cancel_flag2;
  12962. p3.FinishEvent = finish_event;
  12963. StrCpy(p3.SvcName, sizeof(p3.SvcName), nat_t_svc_name);
  12964. p3.RUdpProtocol = RUDP_PROTOCOL_ICMP;
  12965. p3.Delay = 200; // Delay by 200ms
  12966. // p4: over DNS
  12967. StrCpy(p4.Hostname, sizeof(p4.Hostname), hostname_original);
  12968. Copy(&p4.Ip, &ip4, sizeof(IP));
  12969. p4.Port = port;
  12970. p4.Timeout = timeout;
  12971. p4.CancelFlag = &cancel_flag2;
  12972. p4.FinishEvent = finish_event;
  12973. StrCpy(p4.SvcName, sizeof(p4.SvcName), nat_t_svc_name);
  12974. p4.RUdpProtocol = RUDP_PROTOCOL_DNS;
  12975. p4.Delay = 100; // Delay by 100ms
  12976. t1 = NewThread(ConnectThreadForTcp, &p1);
  12977. t2 = NewThread(ConnectThreadForRUDP, &p2);
  12978. t4 = NewThread(ConnectThreadForOverDnsOrIcmp, &p4);
  12979. t3 = NewThread(ConnectThreadForOverDnsOrIcmp, &p3);
  12980. while (true)
  12981. {
  12982. UINT64 now = Tick64();
  12983. if (*cancel_flag)
  12984. {
  12985. // Cancel by the user
  12986. break;
  12987. }
  12988. if (p1.Finished && p2.Finished)
  12989. {
  12990. // Results for both the TCP and the NAT-T were confirmed
  12991. if (now >= giveup_for_all_tick)
  12992. {
  12993. // Wait at least minimum time until successful of the ICMP or the DNS
  12994. break;
  12995. }
  12996. if (p3.Ok || p4.Ok)
  12997. {
  12998. // Exit the loop immediately if any of the ICMP or the DNS is successful
  12999. break;
  13000. }
  13001. }
  13002. if (p1.Finished && p1.Ok)
  13003. {
  13004. // Have successfully connected by TCP
  13005. break;
  13006. }
  13007. if (p2.Finished && p2.Ok)
  13008. {
  13009. UINT p1_wait_time;
  13010. UINT64 tcp_giveup_tick;
  13011. UINT p2_spent_time;
  13012. // Have successfully connected by R-UDP
  13013. if (p1.Finished)
  13014. {
  13015. // Result of TCP is confirmed
  13016. break;
  13017. }
  13018. // Calculate the time takes to complete connection of R-UDP
  13019. p2_spent_time = (UINT)(p2.FinishedTick - start_tick);
  13020. // Decide the grace time for results of TCP until settled.
  13021. // The grace time is four times the duration of the R-UDP, and at least 400 milliseconds from the start,
  13022. // and up to 2500 milliseconds after the R-UDP results settled
  13023. p1_wait_time = p2_spent_time * 4;
  13024. p1_wait_time = MAX(p1_wait_time, 400);
  13025. //Debug("p2_spent_time = %u, p1_wait_time = %u\n", p2_spent_time, p1_wait_time);
  13026. tcp_giveup_tick = start_tick + (UINT64)p1_wait_time;
  13027. tcp_giveup_tick = MIN(tcp_giveup_tick, (p2.FinishedTick + 2500ULL));
  13028. if (now >= tcp_giveup_tick)
  13029. {
  13030. // Result of the TCP is uncertain, but give up
  13031. if (p1.Finished || p1.Tcp_InNegotiation == false)
  13032. {
  13033. // Break only when TCP SSL negotiation is not being processed
  13034. break;
  13035. }
  13036. }
  13037. }
  13038. Wait(finish_event, 25);
  13039. }
  13040. cancel_flag2 = true;
  13041. Lock(p1.CancelLock);
  13042. {
  13043. if (p1.CancelDisconnectSock != NULL)
  13044. {
  13045. cancel_sock = p1.CancelDisconnectSock;
  13046. AddRef(cancel_sock->ref);
  13047. }
  13048. }
  13049. Unlock(p1.CancelLock);
  13050. if (cancel_sock != NULL)
  13051. {
  13052. Disconnect(cancel_sock);
  13053. ReleaseSock(cancel_sock);
  13054. }
  13055. WaitThread(t1, INFINITE);
  13056. WaitThread(t2, INFINITE);
  13057. WaitThread(t3, INFINITE);
  13058. WaitThread(t4, INFINITE);
  13059. ReleaseThread(t1);
  13060. ReleaseThread(t2);
  13061. ReleaseThread(t3);
  13062. ReleaseThread(t4);
  13063. ReleaseEvent(finish_event);
  13064. DeleteLock(p1.CancelLock);
  13065. if (*cancel_flag)
  13066. {
  13067. // Abandon all the results because the user canceled
  13068. Disconnect(p1.Result_Nat_T_Sock);
  13069. ReleaseSock(p1.Result_Nat_T_Sock);
  13070. Disconnect(p2.Result_Nat_T_Sock);
  13071. ReleaseSock(p2.Result_Nat_T_Sock);
  13072. Disconnect(p3.Result_Nat_T_Sock);
  13073. ReleaseSock(p3.Result_Nat_T_Sock);
  13074. Disconnect(p4.Result_Nat_T_Sock);
  13075. ReleaseSock(p4.Result_Nat_T_Sock);
  13076. return NULL;
  13077. }
  13078. if (p1.Ok)
  13079. {
  13080. char hostname[MAX_SIZE];
  13081. // Use the results of the TCP
  13082. // Dispose other results
  13083. Disconnect(p2.Result_Nat_T_Sock);
  13084. ReleaseSock(p2.Result_Nat_T_Sock);
  13085. Disconnect(p3.Result_Nat_T_Sock);
  13086. ReleaseSock(p3.Result_Nat_T_Sock);
  13087. Disconnect(p4.Result_Nat_T_Sock);
  13088. ReleaseSock(p4.Result_Nat_T_Sock);
  13089. if (GetHostName(hostname, sizeof(hostname), &ip4))
  13090. {
  13091. Free(p1.Result_Tcp_Sock->RemoteHostname);
  13092. p1.Result_Tcp_Sock->RemoteHostname = CopyStr(hostname);
  13093. }
  13094. Copy(ret_ip, &ip4, sizeof(IP));
  13095. return p1.Result_Tcp_Sock;
  13096. }
  13097. else if (p2.Ok)
  13098. {
  13099. // Use the results of the R-UDP
  13100. // Dispose other results
  13101. Disconnect(p3.Result_Nat_T_Sock);
  13102. ReleaseSock(p3.Result_Nat_T_Sock);
  13103. Disconnect(p4.Result_Nat_T_Sock);
  13104. ReleaseSock(p4.Result_Nat_T_Sock);
  13105. StrCpy(p2.Result_Nat_T_Sock->UnderlayProtocol, sizeof(p2.Result_Nat_T_Sock->UnderlayProtocol),
  13106. SOCK_UNDERLAY_NAT_T);
  13107. Copy(ret_ip, &ip4, sizeof(IP));
  13108. return p2.Result_Nat_T_Sock;
  13109. }
  13110. else if (p4.Ok)
  13111. {
  13112. // Use this if over-DNS success
  13113. // Dispose other results
  13114. Disconnect(p3.Result_Nat_T_Sock);
  13115. ReleaseSock(p3.Result_Nat_T_Sock);
  13116. StrCpy(p4.Result_Nat_T_Sock->UnderlayProtocol, sizeof(p4.Result_Nat_T_Sock->UnderlayProtocol),
  13117. SOCK_UNDERLAY_DNS);
  13118. Copy(ret_ip, &ip4, sizeof(IP));
  13119. return p4.Result_Nat_T_Sock;
  13120. }
  13121. else if (p3.Ok)
  13122. {
  13123. // Use this if over ICMP success
  13124. StrCpy(p3.Result_Nat_T_Sock->UnderlayProtocol, sizeof(p3.Result_Nat_T_Sock->UnderlayProtocol),
  13125. SOCK_UNDERLAY_ICMP);
  13126. Copy(ret_ip, &ip4, sizeof(IP));
  13127. return p3.Result_Nat_T_Sock;
  13128. }
  13129. else
  13130. {
  13131. // Continue the process if all trials failed
  13132. *nat_t_error_code = p2.NatT_ErrorCode;
  13133. }
  13134. }
  13135. }
  13136. // Attempt to connect with IPv6
  13137. if (s == INVALID_SOCKET && IsZeroIp(&ip6) == false)
  13138. {
  13139. struct sockaddr_in6 sockaddr6;
  13140. struct in6_addr addr6;
  13141. Zero(&sockaddr6, sizeof(sockaddr6));
  13142. Zero(&addr6, sizeof(addr6));
  13143. // Generation of the sockaddr_in6
  13144. IPToInAddr6(&addr6, &ip6);
  13145. sockaddr6.sin6_port = htons((USHORT)port);
  13146. sockaddr6.sin6_family = AF_INET6;
  13147. sockaddr6.sin6_scope_id = ip6.ipv6_scope_id;
  13148. Copy(&sockaddr6.sin6_addr, &addr6, sizeof(addr6));
  13149. // Socket creation
  13150. s = socket(AF_INET6, SOCK_STREAM, 0);
  13151. if (s != INVALID_SOCKET)
  13152. {
  13153. // Connection
  13154. if (connect_timeout(s, (struct sockaddr *)&sockaddr6, sizeof(struct sockaddr_in6), timeout, cancel_flag) != 0)
  13155. {
  13156. // Connection failure
  13157. closesocket(s);
  13158. s = INVALID_SOCKET;
  13159. }
  13160. else
  13161. {
  13162. Copy(&current_ip, &ip6, sizeof(IP));
  13163. is_ipv6 = true;
  13164. Copy(ret_ip, &ip6, sizeof(IP));
  13165. }
  13166. }
  13167. }
  13168. if (s == INVALID_SOCKET)
  13169. {
  13170. // Connection fails on both of IPv4, IPv6
  13171. return NULL;
  13172. }
  13173. // Creating a SOCK
  13174. sock = NewSock();
  13175. sock->socket = s;
  13176. sock->Type = SOCK_TCP;
  13177. sock->ServerMode = false;
  13178. StrCpy(sock->UnderlayProtocol, sizeof(sock->UnderlayProtocol),
  13179. (is_ipv6 ? SOCK_UNDERLAY_NATIVE_V6 : SOCK_UNDERLAY_NATIVE_V4));
  13180. // Host name resolution
  13181. if (no_get_hostname || (GetHostName(tmp, sizeof(tmp), &current_ip) == false))
  13182. {
  13183. StrCpy(tmp, sizeof(tmp), hostname_original);
  13184. }
  13185. //Debug("PTR: %s\n", tmp);
  13186. sock->RemoteHostname = CopyStr(tmp);
  13187. // Debug("new socket: %u\n", s);
  13188. Zero(&ling, sizeof(ling));
  13189. // Forced disconnection flag
  13190. #ifdef SO_DONTLINGER
  13191. setsockopt(sock->socket, SOL_SOCKET, SO_DONTLINGER, (char *)&true_flag, sizeof(bool));
  13192. #else // SO_DONTLINGER
  13193. setsockopt(sock->socket, SOL_SOCKET, SO_LINGER, (char *)&false_flag, sizeof(bool));
  13194. #endif // SO_DONTLINGER
  13195. // setsockopt(sock->socket, SOL_SOCKET, SO_REUSEADDR, (char *)&true_flag, sizeof(bool));
  13196. // Configuring TCP options
  13197. setsockopt(sock->socket, IPPROTO_TCP, TCP_NODELAY, (char *)&true_flag, sizeof(bool));
  13198. // Initialization of the time-out value
  13199. SetTimeout(sock, TIMEOUT_INFINITE);
  13200. // Get the socket information
  13201. QuerySocketInformation(sock);
  13202. if (IsZeroIp(&sock->LocalIP) == false && IsLocalHostIP(&sock->LocalIP) == false)
  13203. {
  13204. IP current_ip;
  13205. if (GetCurrentGlobalIP(&current_ip, is_ipv6) == false)
  13206. {
  13207. SetCurrentGlobalIP(&sock->LocalIP, is_ipv6);
  13208. }
  13209. }
  13210. sock->Connected = true;
  13211. sock->AsyncMode = false;
  13212. sock->SecureMode = false;
  13213. sock->IPv6 = is_ipv6;
  13214. return sock;
  13215. }
  13216. // Maximize the I/O buffer size of the socket
  13217. void SetSocketSendRecvBufferSize(SOCKET s, UINT size)
  13218. {
  13219. int value = (int)size;
  13220. // Validate arguments
  13221. if (s == INVALID_SOCKET)
  13222. {
  13223. return;
  13224. }
  13225. setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&value, sizeof(int));
  13226. setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&value, sizeof(int));
  13227. }
  13228. // Get the buffer size of the socket
  13229. UINT GetSocketBufferSize(SOCKET s, bool send)
  13230. {
  13231. int value = 0;
  13232. int len = sizeof(int);
  13233. // Validate arguments
  13234. if (s == INVALID_SOCKET)
  13235. {
  13236. return 0;
  13237. }
  13238. if (getsockopt(s, SOL_SOCKET, (send ? SO_SNDBUF : SO_RCVBUF), (char *)&value, &len) != 0)
  13239. {
  13240. return 0;
  13241. }
  13242. return value;
  13243. }
  13244. // Setting the buffer size of the socket
  13245. bool SetSocketBufferSize(SOCKET s, bool send, UINT size)
  13246. {
  13247. int value = (int)size;
  13248. // Validate arguments
  13249. if (s == INVALID_SOCKET)
  13250. {
  13251. return false;
  13252. }
  13253. if (setsockopt(s, SOL_SOCKET, (send ? SO_SNDBUF : SO_RCVBUF), (char *)&value, sizeof(int)) != 0)
  13254. {
  13255. return false;
  13256. }
  13257. return true;
  13258. }
  13259. UINT SetSocketBufferSizeWithBestEffort(SOCKET s, bool send, UINT size)
  13260. {
  13261. // Validate arguments
  13262. if (s == INVALID_SOCKET)
  13263. {
  13264. return 0;
  13265. }
  13266. while (true)
  13267. {
  13268. if (SetSocketBufferSize(s, send, size))
  13269. {
  13270. return size;
  13271. }
  13272. size = (UINT)((double)size / 1.5);
  13273. if (size <= 32767)
  13274. {
  13275. return 0;
  13276. }
  13277. }
  13278. }
  13279. // Initialize the buffer size of the UDP socket
  13280. void InitUdpSocketBufferSize(SOCKET s)
  13281. {
  13282. SetSocketBufferSizeWithBestEffort(s, true, UDP_MAX_BUFFER_SIZE);
  13283. SetSocketBufferSizeWithBestEffort(s, false, UDP_MAX_BUFFER_SIZE);
  13284. }
  13285. // Get the socket information
  13286. void QuerySocketInformation(SOCK *sock)
  13287. {
  13288. // Validate arguments
  13289. if (sock == NULL)
  13290. {
  13291. return;
  13292. }
  13293. Lock(sock->lock);
  13294. {
  13295. struct sockaddr_in6 sockaddr6;
  13296. struct in6_addr *addr6;
  13297. int size;
  13298. DWORD dw;
  13299. UINT opt_value = 0;
  13300. if (sock->Type == SOCK_TCP)
  13301. {
  13302. // Get the information of the remote host
  13303. size = sizeof(sockaddr6);
  13304. if (getpeername(sock->socket, (struct sockaddr *)&sockaddr6, (int *)&size) == 0)
  13305. {
  13306. if (size >= sizeof(struct sockaddr_in6))
  13307. {
  13308. sock->RemotePort = (UINT)ntohs(sockaddr6.sin6_port);
  13309. addr6 = &sockaddr6.sin6_addr;
  13310. InAddrToIP6(&sock->RemoteIP, addr6);
  13311. sock->RemoteIP.ipv6_scope_id = sockaddr6.sin6_scope_id;
  13312. }
  13313. else
  13314. {
  13315. struct sockaddr_in *sockaddr;
  13316. struct in_addr *addr;
  13317. sockaddr = (struct sockaddr_in *)&sockaddr6;
  13318. sock->RemotePort = (UINT)ntohs(sockaddr->sin_port);
  13319. addr = &sockaddr->sin_addr;
  13320. InAddrToIP(&sock->RemoteIP, addr);
  13321. }
  13322. }
  13323. }
  13324. // Get the local host information
  13325. size = sizeof(sockaddr6);
  13326. if (getsockname(sock->socket, (struct sockaddr *)&sockaddr6, (int *)&size) == 0)
  13327. {
  13328. if (size >= sizeof(struct sockaddr_in6))
  13329. {
  13330. sock->LocalPort = (UINT)ntohs(sockaddr6.sin6_port);
  13331. addr6 = &sockaddr6.sin6_addr;
  13332. InAddrToIP6(&sock->LocalIP, addr6);
  13333. sock->LocalIP.ipv6_scope_id = sockaddr6.sin6_scope_id;
  13334. }
  13335. else
  13336. {
  13337. struct sockaddr_in *sockaddr;
  13338. struct in_addr *addr;
  13339. sockaddr = (struct sockaddr_in *)&sockaddr6;
  13340. sock->LocalPort = (UINT)ntohs(sockaddr->sin_port);
  13341. addr = &sockaddr->sin_addr;
  13342. InAddrToIP(&sock->LocalIP, addr);
  13343. }
  13344. }
  13345. if (sock->IsRawSocket)
  13346. {
  13347. sock->LocalPort = sock->RemotePort = MAKE_SPECIAL_PORT(sock->RawSocketIPProtocol);
  13348. }
  13349. if (sock->Type == SOCK_UDP)
  13350. {
  13351. sock->UdpMaxMsgSize = UDP_MAX_MSG_SIZE_DEFAULT;
  13352. #ifdef OS_WIN32
  13353. if (true)
  13354. {
  13355. // Get the buffer size that can be transmitted and received at once
  13356. UINT max_value = 0;
  13357. int len = sizeof(UINT);
  13358. if (getsockopt(sock->socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&max_value, &len) == 0)
  13359. {
  13360. sock->UdpMaxMsgSize = max_value;
  13361. }
  13362. }
  13363. #endif // OS_WIN32
  13364. }
  13365. if (sock->IPv6)
  13366. {
  13367. #ifdef IPV6_UNICAST_HOPS
  13368. opt_value = IPV6_UNICAST_HOPS;
  13369. #endif // IPV6_UNICAST_HOPS
  13370. }
  13371. else
  13372. {
  13373. #ifdef IP_TTL
  13374. opt_value = IP_TTL;
  13375. #endif // IP_TTL
  13376. }
  13377. // Support of the TTL value
  13378. size = sizeof(DWORD);
  13379. if (opt_value == 0 ||
  13380. getsockopt(sock->socket, (sock->IPv6 ? IPPROTO_IPV6 : IPPROTO_IP), opt_value, (char *)&dw, &size) != 0)
  13381. {
  13382. sock->IsTtlSupported = false;
  13383. }
  13384. else
  13385. {
  13386. sock->IsTtlSupported = true;
  13387. sock->CurrentTtl = dw;
  13388. }
  13389. }
  13390. Unlock(sock->lock);
  13391. }
  13392. // Setting the TTL value
  13393. bool SetTtl(SOCK *sock, UINT ttl)
  13394. {
  13395. DWORD dw;
  13396. int size;
  13397. UINT opt_value = 0;
  13398. // Validate arguments
  13399. if (sock == NULL)
  13400. {
  13401. return false;
  13402. }
  13403. if (sock->IsTtlSupported == false)
  13404. {
  13405. return false;
  13406. }
  13407. if (sock->CurrentTtl == ttl)
  13408. {
  13409. return true;
  13410. }
  13411. dw = ttl;
  13412. size = sizeof(DWORD);
  13413. if (sock->IPv6)
  13414. {
  13415. #ifdef IPV6_UNICAST_HOPS
  13416. opt_value = IPV6_UNICAST_HOPS;
  13417. #endif // IPV6_UNICAST_HOPS
  13418. }
  13419. else
  13420. {
  13421. #ifdef IP_TTL
  13422. opt_value = IP_TTL;
  13423. #endif // IP_TTL
  13424. }
  13425. if (opt_value == 0 ||
  13426. setsockopt(sock->socket, (sock->IPv6 ? IPPROTO_IPV6 : IPPROTO_IP), opt_value, (char *)&dw, size) == false)
  13427. {
  13428. return false;
  13429. }
  13430. sock->CurrentTtl = ttl;
  13431. return true;
  13432. }
  13433. // Release of the socket
  13434. void ReleaseSock(SOCK *s)
  13435. {
  13436. // Validate arguments
  13437. if (s == NULL)
  13438. {
  13439. return;
  13440. }
  13441. if (Release(s->ref) == 0)
  13442. {
  13443. if (s->ListenMode == false && s->ServerMode)
  13444. {
  13445. Print("");
  13446. }
  13447. CleanupSock(s);
  13448. }
  13449. }
  13450. // Clean-up of the socket
  13451. void CleanupSock(SOCK *s)
  13452. {
  13453. // Validate arguments
  13454. if (s == NULL)
  13455. {
  13456. return;
  13457. }
  13458. // {Debug("CleanupSock: Disconnect() Called: %s %u\n", __FILE__, __LINE__);Disconnect(s);}
  13459. Disconnect(s);
  13460. if (s->InProcAcceptQueue != NULL)
  13461. {
  13462. while (true)
  13463. {
  13464. SOCK *ss = GetNext(s->InProcAcceptQueue);
  13465. if (ss == NULL)
  13466. {
  13467. break;
  13468. }
  13469. Disconnect(ss);
  13470. ReleaseSock(ss);
  13471. }
  13472. ReleaseQueue(s->InProcAcceptQueue);
  13473. }
  13474. if (s->InProcAcceptEvent != NULL)
  13475. {
  13476. ReleaseEvent(s->InProcAcceptEvent);
  13477. }
  13478. if (s->ReverseAcceptQueue != NULL)
  13479. {
  13480. while (true)
  13481. {
  13482. SOCK *ss = GetNext(s->ReverseAcceptQueue);
  13483. if (ss == NULL)
  13484. {
  13485. break;
  13486. }
  13487. Disconnect(ss);
  13488. ReleaseSock(ss);
  13489. }
  13490. ReleaseQueue(s->ReverseAcceptQueue);
  13491. }
  13492. if (s->ReverseAcceptEvent != NULL)
  13493. {
  13494. ReleaseEvent(s->ReverseAcceptEvent);
  13495. }
  13496. if (s->SendTube != NULL)
  13497. {
  13498. TubeDisconnect(s->SendTube);
  13499. ReleaseTube(s->SendTube);
  13500. }
  13501. if (s->RecvTube != NULL)
  13502. {
  13503. TubeDisconnect(s->RecvTube);
  13504. ReleaseTube(s->RecvTube);
  13505. }
  13506. if (s->BulkRecvTube != NULL)
  13507. {
  13508. TubeDisconnect(s->BulkRecvTube);
  13509. ReleaseTube(s->BulkRecvTube);
  13510. }
  13511. if (s->BulkSendTube != NULL)
  13512. {
  13513. TubeDisconnect(s->BulkSendTube);
  13514. ReleaseTube(s->BulkSendTube);
  13515. }
  13516. if (s->BulkSendKey != NULL)
  13517. {
  13518. ReleaseSharedBuffer(s->BulkSendKey);
  13519. }
  13520. if (s->BulkRecvKey != NULL)
  13521. {
  13522. ReleaseSharedBuffer(s->BulkRecvKey);
  13523. }
  13524. if (s->InProcRecvFifo != NULL)
  13525. {
  13526. ReleaseFifo(s->InProcRecvFifo);
  13527. }
  13528. if (s->R_UDP_Stack != NULL)
  13529. {
  13530. FreeRUDP(s->R_UDP_Stack);
  13531. }
  13532. #ifdef OS_WIN32
  13533. Win32FreeAsyncSocket(s);
  13534. #else // OS_WIN32
  13535. UnixFreeAsyncSocket(s);
  13536. #endif // OS_WIN32
  13537. FreeBuf(s->SendBuf);
  13538. if (s->socket != INVALID_SOCKET)
  13539. {
  13540. #ifdef OS_WIN32
  13541. closesocket(s->socket);
  13542. #else // OS_WIN32
  13543. close(s->socket);
  13544. #endif // OS_WIN32
  13545. }
  13546. Free(s->RemoteHostname);
  13547. #ifdef OS_WIN32
  13548. if (s->hAcceptEvent != NULL)
  13549. {
  13550. CloseHandle(s->hAcceptEvent);
  13551. }
  13552. #endif // OS_WIN32
  13553. // Release the certificate
  13554. if (s->RemoteX != NULL)
  13555. {
  13556. FreeX(s->RemoteX);
  13557. s->RemoteX = NULL;
  13558. }
  13559. if (s->LocalX != NULL)
  13560. {
  13561. FreeX(s->LocalX);
  13562. s->LocalX = NULL;
  13563. }
  13564. // Cipher algorithm name
  13565. if (s->CipherName != NULL)
  13566. {
  13567. Free(s->CipherName);
  13568. s->CipherName = NULL;
  13569. }
  13570. Free(s->WaitToUseCipher);
  13571. DeleteLock(s->lock);
  13572. DeleteLock(s->ssl_lock);
  13573. DeleteLock(s->disconnect_lock);
  13574. Dec(num_tcp_connections);
  13575. Free(s);
  13576. }
  13577. // Creating a new socket
  13578. SOCK *NewSock()
  13579. {
  13580. SOCK *s = ZeroMallocFast(sizeof(SOCK));
  13581. s->ref = NewRef();
  13582. s->lock = NewLock();
  13583. s->SendBuf = NewBuf();
  13584. s->socket = INVALID_SOCKET;
  13585. s->ssl_lock = NewLock();
  13586. s->disconnect_lock = NewLock();
  13587. Inc(num_tcp_connections);
  13588. return s;
  13589. }
  13590. // Convert the IP to UINT
  13591. UINT IPToUINT(IP *ip)
  13592. {
  13593. UCHAR *b;
  13594. UINT i, value = 0;
  13595. // Validate arguments
  13596. if (ip == NULL)
  13597. {
  13598. return 0;
  13599. }
  13600. b = (UCHAR *)&value;
  13601. for (i = 0;i < 4;i++)
  13602. {
  13603. b[i] = ip->addr[i];
  13604. }
  13605. return value;
  13606. }
  13607. // Convert UINT to IP
  13608. void UINTToIP(IP *ip, UINT value)
  13609. {
  13610. UCHAR *b;
  13611. UINT i;
  13612. // Validate arguments
  13613. if (ip == NULL)
  13614. {
  13615. return;
  13616. }
  13617. ZeroIP4(ip);
  13618. b = (UCHAR *)&value;
  13619. for (i = 0;i < 4;i++)
  13620. {
  13621. ip->addr[i] = b[i];
  13622. }
  13623. }
  13624. // Get the host name of the computer
  13625. void GetMachineHostName(char *name, UINT size)
  13626. {
  13627. char tmp[MAX_SIZE];
  13628. UINT i, len;
  13629. // Validate arguments
  13630. if (name == NULL)
  13631. {
  13632. return;
  13633. }
  13634. GetMachineName(tmp, sizeof(tmp));
  13635. len = StrLen(tmp);
  13636. for (i = 0;i < len;i++)
  13637. {
  13638. if (tmp[i] == '.')
  13639. {
  13640. tmp[i] = 0;
  13641. }
  13642. }
  13643. ConvertSafeFileName(name, size, tmp);
  13644. }
  13645. // Get the IP address of this computer
  13646. void GetMachineIp(IP *ip)
  13647. {
  13648. char tmp[MAX_SIZE];
  13649. // Validate arguments
  13650. if (ip == NULL)
  13651. {
  13652. return;
  13653. }
  13654. Zero(ip, sizeof(IP));
  13655. SetIP(ip, 127, 0, 0, 1);
  13656. GetMachineName(tmp, sizeof(tmp));
  13657. GetIP(ip, tmp);
  13658. }
  13659. // Get the computer name from 'hosts'
  13660. bool GetMachineNameFromHosts(char *name, UINT size)
  13661. {
  13662. bool ret = false;
  13663. char *s;
  13664. BUF *b;
  13665. // Validate arguments
  13666. if (name == NULL)
  13667. {
  13668. return false;
  13669. }
  13670. b = ReadDump("/etc/hosts");
  13671. if (b == NULL)
  13672. {
  13673. return false;
  13674. }
  13675. while (true)
  13676. {
  13677. s = CfgReadNextLine(b);
  13678. if (s == NULL)
  13679. {
  13680. break;
  13681. }
  13682. else
  13683. {
  13684. TOKEN_LIST *t = ParseToken(s, " \t");
  13685. if (t != NULL)
  13686. {
  13687. if (t->NumTokens >= 2)
  13688. {
  13689. if (StrCmpi(t->Token[0], "127.0.0.1") == 0)
  13690. {
  13691. UINT i;
  13692. for (i = 1;i < t->NumTokens;i++)
  13693. {
  13694. if (StartWith(t->Token[i], "localhost") == false)
  13695. {
  13696. StrCpy(name, size, t->Token[i]);
  13697. ret = true;
  13698. }
  13699. }
  13700. }
  13701. }
  13702. }
  13703. FreeToken(t);
  13704. }
  13705. Free(s);
  13706. }
  13707. FreeBuf(b);
  13708. return ret;
  13709. }
  13710. // Get the computer name of this computer
  13711. void GetMachineName(char *name, UINT size)
  13712. {
  13713. GetMachineNameEx(name, size, false);
  13714. }
  13715. void GetMachineNameEx(char *name, UINT size, bool no_load_hosts)
  13716. {
  13717. static char name_cache[MAX_SIZE];
  13718. static bool name_cached = false;
  13719. char tmp[MAX_SIZE];
  13720. char tmp2[MAX_SIZE];
  13721. // Validate arguments
  13722. if (name == NULL)
  13723. {
  13724. return;
  13725. }
  13726. Lock(machine_name_lock);
  13727. {
  13728. if (name_cached != false)
  13729. {
  13730. StrCpy(name, size, name_cache);
  13731. Unlock(machine_name_lock);
  13732. return;
  13733. }
  13734. ClearStr(tmp, sizeof(tmp));
  13735. if (gethostname(tmp, MAX_SIZE) != 0)
  13736. {
  13737. StrCpy(name, size, "Unknown");
  13738. Unlock(machine_name_lock);
  13739. return;
  13740. }
  13741. ClearStr(name, size);
  13742. StrCpy(name, size, tmp);
  13743. if (IsEmptyStr(name) || StartWith(name, "localhost"))
  13744. {
  13745. #ifdef OS_WIN32
  13746. ClearStr(name, size);
  13747. MsGetComputerName(name, size);
  13748. #endif // OS_WIN32
  13749. }
  13750. if (IsEmptyStr(name) || StartWith(name, "localhost"))
  13751. {
  13752. if (no_load_hosts == false && OS_IS_UNIX(GetOsInfo()->OsType))
  13753. {
  13754. if (GetMachineNameFromHosts(tmp2, sizeof(tmp2)))
  13755. {
  13756. StrCpy(name, sizeof(name), tmp2);
  13757. }
  13758. }
  13759. }
  13760. StrCpy(name_cache, sizeof(name_cache), name);
  13761. name_cached = true;
  13762. }
  13763. Unlock(machine_name_lock);
  13764. }
  13765. // Host name acquisition thread
  13766. void GetHostNameThread(THREAD *t, void *p)
  13767. {
  13768. IP *ip;
  13769. char hostname[256];
  13770. // Validate arguments
  13771. if (t == NULL || p == NULL)
  13772. {
  13773. return;
  13774. }
  13775. ip = (IP *)p;
  13776. AddWaitThread(t);
  13777. NoticeThreadInit(t);
  13778. if (GetHostNameInner(hostname, sizeof(hostname), ip))
  13779. {
  13780. AddHostCache(ip, hostname);
  13781. }
  13782. Free(ip);
  13783. DelWaitThread(t);
  13784. }
  13785. // Get the host name
  13786. bool GetHostName(char *hostname, UINT size, IP *ip)
  13787. {
  13788. THREAD *t;
  13789. IP *p_ip;
  13790. bool ret;
  13791. // Validate arguments
  13792. if (hostname == NULL || ip == NULL)
  13793. {
  13794. return false;
  13795. }
  13796. if (GetHostCache(hostname, size, ip))
  13797. {
  13798. if (IsEmptyStr(hostname) == false)
  13799. {
  13800. return true;
  13801. }
  13802. else
  13803. {
  13804. return false;
  13805. }
  13806. }
  13807. p_ip = ZeroMalloc(sizeof(IP));
  13808. Copy(p_ip, ip, sizeof(IP));
  13809. t = NewThread(GetHostNameThread, p_ip);
  13810. WaitThreadInit(t);
  13811. WaitThread(t, TIMEOUT_HOSTNAME);
  13812. ReleaseThread(t);
  13813. ret = GetHostCache(hostname, size, ip);
  13814. if (ret == false)
  13815. {
  13816. if (IsIP4(ip))
  13817. {
  13818. ret = GetNetBiosName(hostname, size, ip);
  13819. if (ret)
  13820. {
  13821. AddHostCache(ip, hostname);
  13822. }
  13823. }
  13824. }
  13825. else
  13826. {
  13827. if (IsEmptyStr(hostname))
  13828. {
  13829. ret = false;
  13830. }
  13831. }
  13832. if (ret == false)
  13833. {
  13834. AddHostCache(ip, "");
  13835. StrCpy(hostname, size, "");
  13836. }
  13837. return ret;
  13838. }
  13839. // Perform a DNS reverse query
  13840. bool GetHostNameInner(char *hostname, UINT size, IP *ip)
  13841. {
  13842. struct in_addr addr;
  13843. struct sockaddr_in sa;
  13844. char tmp[MAX_SIZE];
  13845. char ip_str[64];
  13846. // Validate arguments
  13847. if (hostname == NULL || ip == NULL)
  13848. {
  13849. return false;
  13850. }
  13851. if (IsIP6(ip))
  13852. {
  13853. return GetHostNameInner6(hostname, size, ip);
  13854. }
  13855. // Reverse resolution
  13856. IPToInAddr(&addr, ip);
  13857. Zero(&sa, sizeof(sa));
  13858. sa.sin_family = AF_INET;
  13859. #if defined(UNIX_BSD) || defined(UNIX_MACOS)
  13860. sa.sin_len = INET_ADDRSTRLEN;
  13861. #endif // UNIX_BSD || UNIX_MACOS
  13862. Copy(&sa.sin_addr, &addr, sizeof(struct in_addr));
  13863. sa.sin_port = 0;
  13864. if (getnameinfo((struct sockaddr *)&sa, sizeof(sa), tmp, sizeof(tmp), NULL, 0, 0) != 0)
  13865. {
  13866. return false;
  13867. }
  13868. IPToStr(ip_str, sizeof(ip_str), ip);
  13869. if (StrCmpi(tmp, ip_str) == 0)
  13870. {
  13871. return false;
  13872. }
  13873. if (IsEmptyStr(tmp))
  13874. {
  13875. return false;
  13876. }
  13877. StrCpy(hostname, size, tmp);
  13878. return true;
  13879. }
  13880. bool GetHostNameInner6(char *hostname, UINT size, IP *ip)
  13881. {
  13882. struct in6_addr addr;
  13883. struct sockaddr_in6 sa;
  13884. char tmp[MAX_SIZE];
  13885. char ip_str[256];
  13886. // Validate arguments
  13887. if (hostname == NULL || ip == NULL)
  13888. {
  13889. return false;
  13890. }
  13891. // Reverse resolution
  13892. IPToInAddr6(&addr, ip);
  13893. Zero(&sa, sizeof(sa));
  13894. sa.sin6_family = AF_INET6;
  13895. #if defined(UNIX_BSD) || defined(UNIX_MACOS)
  13896. sa.sin6_len = INET6_ADDRSTRLEN;
  13897. #endif // UNIX_BSD || UNIX_MACOS
  13898. Copy(&sa.sin6_addr, &addr, sizeof(struct in6_addr));
  13899. sa.sin6_port = 0;
  13900. if (getnameinfo((struct sockaddr *)&sa, sizeof(sa), tmp, sizeof(tmp), NULL, 0, 0) != 0)
  13901. {
  13902. return false;
  13903. }
  13904. IPToStr(ip_str, sizeof(ip_str), ip);
  13905. if (StrCmpi(tmp, ip_str) == 0)
  13906. {
  13907. return false;
  13908. }
  13909. if (IsEmptyStr(tmp))
  13910. {
  13911. return false;
  13912. }
  13913. StrCpy(hostname, size, tmp);
  13914. return true;
  13915. }
  13916. #define NUM_NBT_QUERYS_SEND 3
  13917. // Get the NetBIOS name of the machine from the IP address
  13918. bool GetNetBiosName(char *name, UINT size, IP *ip)
  13919. {
  13920. SOCK *s;
  13921. UINT i, j;
  13922. bool flag = false;
  13923. bool ok = false;
  13924. NBTREQUEST req;
  13925. UCHAR buf[1024];
  13926. USHORT tran_id[NUM_NBT_QUERYS_SEND];
  13927. UINT64 timeout_tick;
  13928. // Validate arguments
  13929. if (name == NULL || ip == NULL)
  13930. {
  13931. return false;
  13932. }
  13933. IPToStr(name, size, ip);
  13934. for (i = 0;i < NUM_NBT_QUERYS_SEND;i++)
  13935. {
  13936. tran_id[i] = Rand16();
  13937. }
  13938. s = NewUDP(0);
  13939. if (s == NULL)
  13940. {
  13941. return false;
  13942. }
  13943. for (j = 0;j < NUM_NBT_QUERYS_SEND;j++)
  13944. {
  13945. Zero(&req, sizeof(req));
  13946. req.TransactionId = Endian16(tran_id[j]);
  13947. req.NumQuestions = Endian16(1);
  13948. req.Query[0] = 0x20;
  13949. req.Query[1] = 0x43;
  13950. req.Query[2] = 0x4b;
  13951. for (i = 3;i <= 32;i++)
  13952. {
  13953. req.Query[i] = 0x41;
  13954. }
  13955. req.Query[35] = 0x21;
  13956. req.Query[37] = 0x01;
  13957. if (SendTo(s, ip, 137, &req, sizeof(req)) == 0)
  13958. {
  13959. ReleaseSock(s);
  13960. return false;
  13961. }
  13962. }
  13963. timeout_tick = Tick64() + (UINT64)TIMEOUT_NETBIOS_HOSTNAME;
  13964. while (1)
  13965. {
  13966. UINT ret;
  13967. IP src_ip;
  13968. UINT src_port;
  13969. SOCKSET set;
  13970. if (Tick64() >= timeout_tick)
  13971. {
  13972. break;
  13973. }
  13974. InitSockSet(&set);
  13975. AddSockSet(&set, s);
  13976. Select(&set, 100, NULL, NULL);
  13977. if (flag == false)
  13978. {
  13979. flag = true;
  13980. }
  13981. else
  13982. {
  13983. SleepThread(10);
  13984. }
  13985. ret = RecvFrom(s, &src_ip, &src_port, buf, sizeof(buf));
  13986. if (ret == SOCK_LATER)
  13987. {
  13988. continue;
  13989. }
  13990. else if (ret == 0)
  13991. {
  13992. break;
  13993. }
  13994. else
  13995. {
  13996. if (ret >= sizeof(NBTRESPONSE))
  13997. {
  13998. NBTRESPONSE *r = (NBTRESPONSE *)buf;
  13999. bool b = false;
  14000. UINT i;
  14001. USHORT id = Endian16(r->TransactionId);
  14002. for (i = 0;i < NUM_NBT_QUERYS_SEND;i++)
  14003. {
  14004. if (id == tran_id[i])
  14005. {
  14006. b = true;
  14007. break;
  14008. }
  14009. }
  14010. if (b)
  14011. {
  14012. if (r->Flags != 0 && r->NumQuestions == 0 && r->AnswerRRs >= 1)
  14013. {
  14014. if (r->Response[0] == 0x20 && r->Response[1] == 0x43 &&
  14015. r->Response[2] == 0x4b)
  14016. {
  14017. if (r->Response[34] == 0x00 && r->Response[35] == 0x21 &&
  14018. r->Response[36] == 0x00 && r->Response[37] == 0x01)
  14019. {
  14020. char *a = (char *)(&r->Response[45]);
  14021. if (StrCheckLen(a, 15))
  14022. {
  14023. if (IsEmptyStr(a) == false)
  14024. {
  14025. StrCpy(name, size, a);
  14026. Trim(name);
  14027. ok = true;
  14028. }
  14029. else
  14030. {
  14031. ok = false;
  14032. break;
  14033. }
  14034. }
  14035. }
  14036. }
  14037. }
  14038. }
  14039. }
  14040. }
  14041. }
  14042. ReleaseSock(s);
  14043. return ok;
  14044. }
  14045. // Set the IP address
  14046. void SetIP(IP *ip, UCHAR a1, UCHAR a2, UCHAR a3, UCHAR a4)
  14047. {
  14048. // Validate arguments
  14049. if (ip == NULL)
  14050. {
  14051. return;
  14052. }
  14053. Zero(ip, sizeof(IP));
  14054. ip->addr[0] = a1;
  14055. ip->addr[1] = a2;
  14056. ip->addr[2] = a3;
  14057. ip->addr[3] = a4;
  14058. }
  14059. UINT SetIP32(UCHAR a1, UCHAR a2, UCHAR a3, UCHAR a4)
  14060. {
  14061. IP ip;
  14062. Zero(&ip, sizeof(ip));
  14063. SetIP(&ip, a1, a2, a3, a4);
  14064. return IPToUINT(&ip);
  14065. }
  14066. // Get either of v4 and v6 results with a DNS forward lookup (The IPv4 precedes in the case of both results)
  14067. bool GetIP46Any4(IP *ip, char *hostname)
  14068. {
  14069. IP ip4, ip6;
  14070. bool b = false;
  14071. // Validate arguments
  14072. if (ip == NULL || hostname == NULL)
  14073. {
  14074. return false;
  14075. }
  14076. if (GetIP46(&ip4, &ip6, hostname) == false)
  14077. {
  14078. return false;
  14079. }
  14080. if (IsZeroIp(&ip6) == false)
  14081. {
  14082. Copy(ip, &ip6, sizeof(IP));
  14083. b = true;
  14084. }
  14085. if (IsZeroIp(&ip4) == false)
  14086. {
  14087. Copy(ip, &ip4, sizeof(IP));
  14088. b = true;
  14089. }
  14090. return b;
  14091. }
  14092. // Get either of v4 and v6 results with a DNS forward lookup (The IPv6 precedes in the case of both)
  14093. bool GetIP46Any6(IP *ip, char *hostname)
  14094. {
  14095. IP ip4, ip6;
  14096. bool b = false;
  14097. // Validate arguments
  14098. if (ip == NULL || hostname == NULL)
  14099. {
  14100. return false;
  14101. }
  14102. if (GetIP46(&ip4, &ip6, hostname) == false)
  14103. {
  14104. return false;
  14105. }
  14106. if (IsZeroIp(&ip4) == false)
  14107. {
  14108. Copy(ip, &ip4, sizeof(IP));
  14109. b = true;
  14110. }
  14111. if (IsZeroIp(&ip6) == false)
  14112. {
  14113. Copy(ip, &ip6, sizeof(IP));
  14114. b = true;
  14115. }
  14116. return b;
  14117. }
  14118. // Obtain in both v4 and v6 results with a DNS forward lookup
  14119. bool GetIP46(IP *ip4, IP *ip6, char *hostname)
  14120. {
  14121. return GetIP46Ex(ip4, ip6, hostname, 0, NULL);
  14122. }
  14123. bool GetIP46Ex(IP *ip4, IP *ip6, char *hostname, UINT timeout, bool *cancel)
  14124. {
  14125. IP a, b;
  14126. bool ok_a, ok_b;
  14127. // Validate arguments
  14128. if (ip4 == NULL || ip6 == NULL || hostname == NULL)
  14129. {
  14130. return false;
  14131. }
  14132. ZeroIP4(ip4);
  14133. ZeroIP6(ip6);
  14134. ok_a = ok_b = false;
  14135. if (GetIP6Ex(&a, hostname, timeout, cancel))
  14136. {
  14137. ok_a = true;
  14138. }
  14139. if (GetIP4Ex(&b, hostname, timeout, cancel))
  14140. {
  14141. ok_b = true;
  14142. }
  14143. if (ok_a)
  14144. {
  14145. if (IsIP4(&a))
  14146. {
  14147. Copy(ip4, &a, sizeof(IP));
  14148. }
  14149. }
  14150. if (ok_b)
  14151. {
  14152. if (IsIP4(&b))
  14153. {
  14154. Copy(ip4, &b, sizeof(IP));
  14155. }
  14156. if (IsIP6(&b))
  14157. {
  14158. Copy(ip6, &b, sizeof(IP));
  14159. }
  14160. }
  14161. if (ok_a)
  14162. {
  14163. if (IsIP6(&a))
  14164. {
  14165. Copy(ip6, &a, sizeof(IP));
  14166. }
  14167. }
  14168. if (IsZeroIp(ip4) && IsZeroIp(ip6))
  14169. {
  14170. return false;
  14171. }
  14172. return true;
  14173. }
  14174. // Clean-up of the parameters for GetIP thread
  14175. void CleanupGetIPThreadParam(GETIP_THREAD_PARAM *p)
  14176. {
  14177. // Validate arguments
  14178. if (p == NULL)
  14179. {
  14180. return;
  14181. }
  14182. Free(p);
  14183. }
  14184. // Release of the parameters of the GetIP for thread
  14185. void ReleaseGetIPThreadParam(GETIP_THREAD_PARAM *p)
  14186. {
  14187. // Validate arguments
  14188. if (p == NULL)
  14189. {
  14190. return;
  14191. }
  14192. if (Release(p->Ref) == 0)
  14193. {
  14194. CleanupGetIPThreadParam(p);
  14195. }
  14196. }
  14197. // Thread to perform to query the DNS forward lookup (with timeout)
  14198. void GetIP4Ex6ExThread(THREAD *t, void *param)
  14199. {
  14200. GETIP_THREAD_PARAM *p;
  14201. // Validate arguments
  14202. if (t == NULL || param == NULL)
  14203. {
  14204. return;
  14205. }
  14206. p = (GETIP_THREAD_PARAM *)param;
  14207. AddRef(p->Ref);
  14208. NoticeThreadInit(t);
  14209. AddWaitThread(t);
  14210. // Execution of resolution
  14211. if (p->IPv6 == false)
  14212. {
  14213. // IPv4
  14214. p->Ok = GetIP4Inner(&p->Ip, p->HostName);
  14215. }
  14216. else
  14217. {
  14218. // IPv6
  14219. p->Ok = GetIP6Inner(&p->Ip, p->HostName);
  14220. }
  14221. ReleaseGetIPThreadParam(p);
  14222. DelWaitThread(t);
  14223. Dec(getip_thread_counter);
  14224. }
  14225. // Perform a forward DNS query (with timeout)
  14226. bool GetIP4Ex6Ex(IP *ip, char *hostname_arg, UINT timeout, bool ipv6, bool *cancel)
  14227. {
  14228. return GetIP4Ex6Ex2(ip, hostname_arg, timeout, ipv6, cancel, false);
  14229. }
  14230. bool GetIP4Ex6Ex2(IP *ip, char *hostname_arg, UINT timeout, bool ipv6, bool *cancel, bool only_direct_dns)
  14231. {
  14232. GETIP_THREAD_PARAM *p;
  14233. THREAD *t;
  14234. bool ret = false;
  14235. UINT64 start_tick = 0;
  14236. UINT64 end_tick = 0;
  14237. UINT64 spent_time = 0;
  14238. UINT64 now;
  14239. UINT n;
  14240. bool use_dns_proxy = false;
  14241. char hostname[260];
  14242. UINT i;
  14243. bool timed_out;
  14244. // Validate arguments
  14245. if (ip == NULL || hostname_arg == NULL)
  14246. {
  14247. return false;
  14248. }
  14249. if (timeout == 0)
  14250. {
  14251. timeout = TIMEOUT_GETIP;
  14252. }
  14253. Zero(hostname, sizeof(hostname));
  14254. StrCpy(hostname, sizeof(hostname), hostname_arg);
  14255. i = SearchStrEx(hostname, "/", 0, true);
  14256. if (i != INFINITE)
  14257. {
  14258. hostname[i] = 0;
  14259. }
  14260. if (ipv6 == false)
  14261. {
  14262. IP ip2;
  14263. if (StrToIP(&ip2, hostname) && IsZeroIp(&ip2) == false)
  14264. {
  14265. if (IsIP4(&ip2))
  14266. {
  14267. // IPv4 address direct specification
  14268. Copy(ip, &ip2, sizeof(IP));
  14269. return true;
  14270. }
  14271. else
  14272. {
  14273. // IPv6 address direct specification
  14274. return false;
  14275. }
  14276. }
  14277. }
  14278. else
  14279. {
  14280. IP ip2;
  14281. if (StrToIP(&ip2, hostname) && IsZeroIp(&ip2) == false)
  14282. {
  14283. if (IsIP6(&ip2))
  14284. {
  14285. // IPv6 address direct specification
  14286. Copy(ip, &ip2, sizeof(IP));
  14287. return true;
  14288. }
  14289. else
  14290. {
  14291. // IPv4 address direct specification
  14292. return false;
  14293. }
  14294. }
  14295. }
  14296. if (only_direct_dns == false)
  14297. {
  14298. if (ipv6 == false)
  14299. {
  14300. if (IsUseDnsProxy())
  14301. {
  14302. use_dns_proxy = true;
  14303. }
  14304. }
  14305. }
  14306. // check the quota
  14307. start_tick = Tick64();
  14308. end_tick = start_tick + (UINT64)timeout;
  14309. n = 0;
  14310. timed_out = false;
  14311. while (true)
  14312. {
  14313. UINT64 now = Tick64();
  14314. UINT64 remain;
  14315. UINT remain32;
  14316. if (GetGetIpThreadMaxNum() > GetCurrentGetIpThreadNum())
  14317. {
  14318. // below the quota
  14319. break;
  14320. }
  14321. if (now >= end_tick)
  14322. {
  14323. // timeouted
  14324. timed_out = true;
  14325. break;
  14326. }
  14327. if (cancel != NULL && (*cancel))
  14328. {
  14329. // cancelled
  14330. timed_out = true;
  14331. break;
  14332. }
  14333. remain = end_tick - now;
  14334. remain32 = MIN((UINT)remain, 100);
  14335. SleepThread(remain32);
  14336. n++;
  14337. }
  14338. now = Tick64();
  14339. spent_time = now - start_tick;
  14340. if (n == 0)
  14341. {
  14342. spent_time = 0;
  14343. }
  14344. if ((UINT)spent_time >= timeout)
  14345. {
  14346. timed_out = true;
  14347. }
  14348. if (timed_out)
  14349. {
  14350. IP ip2;
  14351. // timed out, cancelled
  14352. if (QueryDnsCache(&ip2, hostname))
  14353. {
  14354. ret = true;
  14355. Copy(ip, &ip2, sizeof(IP));
  14356. }
  14357. Debug("GetIP4Ex6Ex2: Worker thread quota exceeded: max=%u current=%u\n",
  14358. GetGetIpThreadMaxNum(), GetCurrentGetIpThreadNum());
  14359. return ret;
  14360. }
  14361. // Increment the counter
  14362. Inc(getip_thread_counter);
  14363. if (spent_time != 0)
  14364. {
  14365. Debug("GetIP4Ex6Ex2: Waited for %u msecs to create a worker thread.\n",
  14366. spent_time);
  14367. }
  14368. timeout -= (UINT)spent_time;
  14369. p = ZeroMalloc(sizeof(GETIP_THREAD_PARAM));
  14370. p->Ref = NewRef();
  14371. StrCpy(p->HostName, sizeof(p->HostName), hostname);
  14372. p->IPv6 = ipv6;
  14373. p->Timeout = timeout;
  14374. p->Ok = false;
  14375. t = NewThread(GetIP4Ex6ExThread, p);
  14376. WaitThreadInit(t);
  14377. if (cancel == NULL)
  14378. {
  14379. WaitThread(t, timeout);
  14380. }
  14381. else
  14382. {
  14383. start_tick = Tick64();
  14384. end_tick = start_tick + (UINT64)timeout;
  14385. while (true)
  14386. {
  14387. UINT64 now = Tick64();
  14388. UINT64 remain;
  14389. UINT remain32;
  14390. if (*cancel)
  14391. {
  14392. break;
  14393. }
  14394. if (now >= end_tick)
  14395. {
  14396. break;
  14397. }
  14398. remain = end_tick - now;
  14399. remain32 = MIN((UINT)remain, 100);
  14400. if (WaitThread(t, remain32))
  14401. {
  14402. break;
  14403. }
  14404. }
  14405. }
  14406. ReleaseThread(t);
  14407. if (p->Ok)
  14408. {
  14409. ret = true;
  14410. Copy(ip, &p->Ip, sizeof(IP));
  14411. }
  14412. else
  14413. {
  14414. IP ip2;
  14415. #if 0
  14416. if (only_direct_dns == false)
  14417. {
  14418. if (ipv6)
  14419. {
  14420. UINT flets_type = DetectFletsType();
  14421. // if I'm in the FLETs of NTT East,
  14422. // try to get an IP address using the DNS proxy server
  14423. if ((flets_type & FLETS_DETECT_TYPE_EAST_BFLETS_PRIVATE) &&
  14424. GetIPViaDnsProxyForJapanFlets(ip, hostname, true, 0, cancel, NULL))
  14425. {
  14426. // B FLETs
  14427. ret = true;
  14428. }
  14429. else if ((flets_type & FLETS_DETECT_TYPE_EAST_NGN_PRIVATE) &&
  14430. GetIPViaDnsProxyForJapanFlets(ip, hostname, true, 0, cancel, FLETS_NGN_EAST_DNS_PROXY_HOSTNAME))
  14431. {
  14432. // FLET'S Hikar-Next (NTT East)
  14433. ret = true;
  14434. }
  14435. else if ((flets_type & FLETS_DETECT_TYPE_WEST_NGN_PRIVATE) &&
  14436. GetIPViaDnsProxyForJapanFlets(ip, hostname, true, 0, cancel, FLETS_NGN_WEST_DNS_PROXY_HOSTNAME))
  14437. {
  14438. // FLET'S Hikar-Next (NTT West)
  14439. ret = true;
  14440. }
  14441. }
  14442. }
  14443. #endif
  14444. if (QueryDnsCache(&ip2, hostname))
  14445. {
  14446. ret = true;
  14447. Copy(ip, &ip2, sizeof(IP));
  14448. }
  14449. }
  14450. ReleaseGetIPThreadParam(p);
  14451. return ret;
  14452. }
  14453. bool GetIP4Ex(IP *ip, char *hostname, UINT timeout, bool *cancel)
  14454. {
  14455. return GetIP4Ex6Ex(ip, hostname, timeout, false, cancel);
  14456. }
  14457. bool GetIP6Ex(IP *ip, char *hostname, UINT timeout, bool *cancel)
  14458. {
  14459. return GetIP4Ex6Ex(ip, hostname, timeout, true, cancel);
  14460. }
  14461. bool GetIP4(IP *ip, char *hostname)
  14462. {
  14463. return GetIP4Ex(ip, hostname, 0, NULL);
  14464. }
  14465. bool GetIP6(IP *ip, char *hostname)
  14466. {
  14467. return GetIP6Ex(ip, hostname, 0, NULL);
  14468. }
  14469. // Perform a DNS forward lookup query
  14470. bool GetIP(IP *ip, char *hostname)
  14471. {
  14472. return GetIPEx(ip, hostname, false);
  14473. }
  14474. bool GetIPEx(IP *ip, char *hostname, bool ipv6)
  14475. {
  14476. if (ipv6 == false)
  14477. {
  14478. return GetIP4(ip, hostname);
  14479. }
  14480. else
  14481. {
  14482. return GetIP6(ip, hostname);
  14483. }
  14484. }
  14485. bool GetIP6Inner(IP *ip, char *hostname)
  14486. {
  14487. struct sockaddr_in6 in;
  14488. struct in6_addr addr;
  14489. struct addrinfo hint;
  14490. struct addrinfo *info;
  14491. // Validate arguments
  14492. if (ip == NULL || hostname == NULL)
  14493. {
  14494. return false;
  14495. }
  14496. if (IsEmptyStr(hostname))
  14497. {
  14498. return false;
  14499. }
  14500. if (StrCmpi(hostname, "localhost") == 0)
  14501. {
  14502. GetLocalHostIP6(ip);
  14503. return true;
  14504. }
  14505. if (StrToIP6(ip, hostname) == false && StrToIP(ip, hostname) == false)
  14506. {
  14507. // Forward resolution
  14508. Zero(&hint, sizeof(hint));
  14509. hint.ai_family = AF_INET6;
  14510. hint.ai_socktype = SOCK_STREAM;
  14511. hint.ai_protocol = IPPROTO_TCP;
  14512. info = NULL;
  14513. if (getaddrinfo(hostname, NULL, &hint, &info) != 0 ||
  14514. info->ai_family != AF_INET6)
  14515. {
  14516. if (info)
  14517. {
  14518. freeaddrinfo(info);
  14519. }
  14520. return QueryDnsCacheEx(ip, hostname, true);
  14521. }
  14522. // Forward resolution success
  14523. Copy(&in, info->ai_addr, sizeof(struct sockaddr_in6));
  14524. freeaddrinfo(info);
  14525. Copy(&addr, &in.sin6_addr, sizeof(addr));
  14526. InAddrToIP6(ip, &addr);
  14527. }
  14528. // Save Cache
  14529. NewDnsCache(hostname, ip);
  14530. return true;
  14531. }
  14532. bool GetIP4Inner(IP *ip, char *hostname)
  14533. {
  14534. struct sockaddr_in in;
  14535. struct in_addr addr;
  14536. struct addrinfo hint;
  14537. struct addrinfo *info;
  14538. // Validate arguments
  14539. if (ip == NULL || hostname == NULL)
  14540. {
  14541. return false;
  14542. }
  14543. if (IsEmptyStr(hostname))
  14544. {
  14545. return false;
  14546. }
  14547. if (StrCmpi(hostname, "localhost") == 0)
  14548. {
  14549. SetIP(ip, 127, 0, 0, 1);
  14550. return true;
  14551. }
  14552. if (StrToIP6(ip, hostname) == false && StrToIP(ip, hostname) == false)
  14553. {
  14554. // Forward resolution
  14555. Zero(&hint, sizeof(hint));
  14556. hint.ai_family = AF_INET;
  14557. hint.ai_socktype = SOCK_STREAM;
  14558. hint.ai_protocol = IPPROTO_TCP;
  14559. info = NULL;
  14560. if (getaddrinfo(hostname, NULL, &hint, &info) != 0 ||
  14561. info->ai_family != AF_INET)
  14562. {
  14563. if (info)
  14564. {
  14565. freeaddrinfo(info);
  14566. }
  14567. return QueryDnsCache(ip, hostname);
  14568. }
  14569. // Forward resolution success
  14570. Copy(&in, info->ai_addr, sizeof(struct sockaddr_in));
  14571. freeaddrinfo(info);
  14572. Copy(&addr, &in.sin_addr, sizeof(addr));
  14573. InAddrToIP(ip, &addr);
  14574. }
  14575. // Save Cache
  14576. NewDnsCache(hostname, ip);
  14577. return true;
  14578. }
  14579. // Search in the DNS cache
  14580. bool QueryDnsCache(IP *ip, char *hostname)
  14581. {
  14582. return QueryDnsCacheEx(ip, hostname, false);
  14583. }
  14584. bool QueryDnsCacheEx(IP *ip, char *hostname, bool ipv6)
  14585. {
  14586. DNSCACHE *c;
  14587. char tmp[MAX_SIZE];
  14588. // Validate arguments
  14589. if (ip == NULL || hostname == NULL)
  14590. {
  14591. return false;
  14592. }
  14593. GenDnsCacheKeyName(tmp, sizeof(tmp), hostname, ipv6);
  14594. c = FindDnsCache(tmp);
  14595. if (c == NULL)
  14596. {
  14597. return false;
  14598. }
  14599. Copy(ip, &c->IpAddress, sizeof(IP));
  14600. return true;
  14601. }
  14602. // Convert the IP to a string
  14603. void IPToUniStr(wchar_t *str, UINT size, IP *ip)
  14604. {
  14605. char tmp[128];
  14606. IPToStr(tmp, sizeof(tmp), ip);
  14607. StrToUni(str, size, tmp);
  14608. }
  14609. // Convert the IP to a string (32bit UINT)
  14610. void IPToUniStr32(wchar_t *str, UINT size, UINT ip)
  14611. {
  14612. char tmp[128];
  14613. IPToStr32(tmp, sizeof(tmp), ip);
  14614. StrToUni(str, size, tmp);
  14615. }
  14616. // Convert the IP to a string (128bit byte array)
  14617. void IPToStr128(char *str, UINT size, UCHAR *ip_bytes)
  14618. {
  14619. IP ip_st;
  14620. // Validate arguments
  14621. if (str == NULL)
  14622. {
  14623. return;
  14624. }
  14625. SetIP6(&ip_st, ip_bytes);
  14626. IPToStr(str, size, &ip_st);
  14627. }
  14628. // Convert the IP to a string (32bit UINT)
  14629. void IPToStr32(char *str, UINT size, UINT ip)
  14630. {
  14631. IP ip_st;
  14632. // Validate arguments
  14633. if (str == NULL)
  14634. {
  14635. return;
  14636. }
  14637. UINTToIP(&ip_st, ip);
  14638. IPToStr(str, size, &ip_st);
  14639. }
  14640. // Convert IPv4 or IPv6 to a string
  14641. void IPToStr4or6(char *str, UINT size, UINT ip_4_uint, UCHAR *ip_6_bytes)
  14642. {
  14643. IP ip4;
  14644. IP ip6;
  14645. IP ip;
  14646. // Validate arguments
  14647. if (str == NULL)
  14648. {
  14649. return;
  14650. }
  14651. Zero(&ip, sizeof(ip));
  14652. UINTToIP(&ip4, ip_4_uint);
  14653. SetIP6(&ip6, ip_6_bytes);
  14654. if (IsIP6(&ip4) || (IsZeroIp(&ip4) && (IsZeroIp(&ip6) == false)))
  14655. {
  14656. Copy(&ip, &ip6, sizeof(IP));
  14657. }
  14658. else
  14659. {
  14660. Copy(&ip, &ip4, sizeof(IP));
  14661. }
  14662. IPToStr(str, size, &ip);
  14663. }
  14664. // Convert the IP to a string
  14665. void IPToStr(char *str, UINT size, IP *ip)
  14666. {
  14667. // Validate arguments
  14668. if (str == NULL || ip == NULL)
  14669. {
  14670. return;
  14671. }
  14672. if (IsIP6(ip))
  14673. {
  14674. IPToStr6(str, size, ip);
  14675. }
  14676. else
  14677. {
  14678. IPToStr4(str, size, ip);
  14679. }
  14680. }
  14681. // Convert the IPv4 to a string
  14682. void IPToStr4(char *str, UINT size, IP *ip)
  14683. {
  14684. // Validate arguments
  14685. if (str == NULL || ip == NULL)
  14686. {
  14687. return;
  14688. }
  14689. // Conversion
  14690. snprintf(str, size != 0 ? size : 64, "%u.%u.%u.%u", ip->addr[0], ip->addr[1], ip->addr[2], ip->addr[3]);
  14691. }
  14692. // Convert the string to an IP
  14693. bool StrToIP(IP *ip, char *str)
  14694. {
  14695. TOKEN_LIST *token;
  14696. char *tmp;
  14697. UINT i;
  14698. // Validate arguments
  14699. if (ip == NULL || str == NULL)
  14700. {
  14701. return false;
  14702. }
  14703. if (StrToIP6(ip, str))
  14704. {
  14705. return true;
  14706. }
  14707. Zero(ip, sizeof(IP));
  14708. tmp = CopyStr(str);
  14709. Trim(tmp);
  14710. token = ParseToken(tmp, ".");
  14711. Free(tmp);
  14712. if (token->NumTokens != 4)
  14713. {
  14714. FreeToken(token);
  14715. return false;
  14716. }
  14717. for (i = 0;i < 4;i++)
  14718. {
  14719. char *s = token->Token[i];
  14720. if (s[0] < '0' || s[0] > '9' ||
  14721. (ToInt(s) >= 256))
  14722. {
  14723. FreeToken(token);
  14724. return false;
  14725. }
  14726. }
  14727. Zero(ip, sizeof(IP));
  14728. for (i = 0;i < 4;i++)
  14729. {
  14730. ip->addr[i] = (UCHAR)ToInt(token->Token[i]);
  14731. }
  14732. FreeToken(token);
  14733. return true;
  14734. }
  14735. UINT StrToIP32(char *str)
  14736. {
  14737. IP ip;
  14738. // Validate arguments
  14739. if (str == NULL)
  14740. {
  14741. return 0;
  14742. }
  14743. if (StrToIP(&ip, str) == false)
  14744. {
  14745. return 0;
  14746. }
  14747. return IPToUINT(&ip);
  14748. }
  14749. bool UniStrToIP(IP *ip, wchar_t *str)
  14750. {
  14751. char *tmp;
  14752. bool ret;
  14753. tmp = CopyUniToStr(str);
  14754. ret = StrToIP(ip, tmp);
  14755. Free(tmp);
  14756. return ret;
  14757. }
  14758. UINT UniStrToIP32(wchar_t *str)
  14759. {
  14760. UINT ret;
  14761. char *tmp;
  14762. tmp = CopyUniToStr(str);
  14763. ret = StrToIP32(tmp);
  14764. Free(tmp);
  14765. return ret;
  14766. }
  14767. // Convert the IP to the in_addr
  14768. void IPToInAddr(struct in_addr *addr, IP *ip)
  14769. {
  14770. UINT i;
  14771. // Validate arguments
  14772. if (addr == NULL || ip == NULL)
  14773. {
  14774. return;
  14775. }
  14776. Zero(addr, sizeof(struct in_addr));
  14777. if (IsIP6(ip) == false)
  14778. {
  14779. for (i = 0;i < 4;i++)
  14780. {
  14781. ((UCHAR *)addr)[i] = ip->addr[i];
  14782. }
  14783. }
  14784. }
  14785. // Convert the IP to the in6_addr
  14786. void IPToInAddr6(struct in6_addr *addr, IP *ip)
  14787. {
  14788. UINT i;
  14789. // Validate arguments
  14790. if (addr == NULL || ip == NULL)
  14791. {
  14792. return;
  14793. }
  14794. Zero(addr, sizeof(struct in6_addr));
  14795. if (IsIP6(ip))
  14796. {
  14797. for (i = 0;i < 16;i++)
  14798. {
  14799. ((UCHAR *)addr)[i] = ip->ipv6_addr[i];
  14800. }
  14801. }
  14802. }
  14803. // Convert the in_addr to the IP
  14804. void InAddrToIP(IP *ip, struct in_addr *addr)
  14805. {
  14806. UINT i;
  14807. // Validate arguments
  14808. if (ip == NULL || addr == NULL)
  14809. {
  14810. return;
  14811. }
  14812. Zero(ip, sizeof(IP));
  14813. for (i = 0;i < 4;i++)
  14814. {
  14815. ip->addr[i] = ((UCHAR *)addr)[i];
  14816. }
  14817. }
  14818. // Convert the in6_addr to the IP
  14819. void InAddrToIP6(IP *ip, struct in6_addr *addr)
  14820. {
  14821. UINT i;
  14822. // Validate arguments
  14823. if (ip == NULL || addr == NULL)
  14824. {
  14825. return;
  14826. }
  14827. ZeroIP6(ip);
  14828. for (i = 0;i < 16;i++)
  14829. {
  14830. ip->ipv6_addr[i] = ((UCHAR *)addr)[i];
  14831. }
  14832. }
  14833. // Search in the DNS cache
  14834. DNSCACHE *FindDnsCache(char *hostname)
  14835. {
  14836. return FindDnsCacheEx(hostname, false);
  14837. }
  14838. DNSCACHE *FindDnsCacheEx(char *hostname, bool ipv6)
  14839. {
  14840. DNSCACHE *c;
  14841. char tmp[MAX_SIZE];
  14842. if (hostname == NULL)
  14843. {
  14844. return NULL;
  14845. }
  14846. GenDnsCacheKeyName(tmp, sizeof(tmp), hostname, ipv6);
  14847. LockDnsCache();
  14848. {
  14849. DNSCACHE t;
  14850. t.HostName = tmp;
  14851. c = Search(DnsCache, &t);
  14852. }
  14853. UnlockDnsCache();
  14854. return c;
  14855. }
  14856. // Generate the IPv4 / IPv6 key name for the DNS cache
  14857. void GenDnsCacheKeyName(char *dst, UINT size, char *src, bool ipv6)
  14858. {
  14859. // Validate arguments
  14860. if (dst == NULL || src == NULL)
  14861. {
  14862. return;
  14863. }
  14864. if (ipv6 == false)
  14865. {
  14866. StrCpy(dst, size, src);
  14867. }
  14868. else
  14869. {
  14870. Format(dst, size, "%s@ipv6", src);
  14871. }
  14872. }
  14873. // Registration of the new DNS cache
  14874. void NewDnsCache(char *hostname, IP *ip)
  14875. {
  14876. NewDnsCacheEx(hostname, ip, IsIP6(ip));
  14877. }
  14878. void NewDnsCacheEx(char *hostname, IP *ip, bool ipv6)
  14879. {
  14880. DNSCACHE *c;
  14881. char tmp[MAX_PATH];
  14882. // Validate arguments
  14883. if (hostname == NULL || ip == NULL)
  14884. {
  14885. return;
  14886. }
  14887. if (IsNetworkNameCacheEnabled() == false)
  14888. {
  14889. return;
  14890. }
  14891. GenDnsCacheKeyName(tmp, sizeof(tmp), hostname, ipv6);
  14892. LockDnsCache();
  14893. {
  14894. DNSCACHE t;
  14895. // Search for anything matches to the hostname first
  14896. t.HostName = tmp;
  14897. c = Search(DnsCache, &t);
  14898. if (c == NULL)
  14899. {
  14900. // Newly register
  14901. c = ZeroMalloc(sizeof(DNSCACHE));
  14902. c->HostName = CopyStr(tmp);
  14903. Copy(&c->IpAddress, ip, sizeof(IP));
  14904. Add(DnsCache, c);
  14905. }
  14906. else
  14907. {
  14908. // Update
  14909. Copy(&c->IpAddress, ip, sizeof(IP));
  14910. }
  14911. }
  14912. UnlockDnsCache();
  14913. }
  14914. // Name comparison of the DNS cache entries
  14915. int CompareDnsCache(void *p1, void *p2)
  14916. {
  14917. DNSCACHE *c1, *c2;
  14918. if (p1 == NULL || p2 == NULL)
  14919. {
  14920. return 0;
  14921. }
  14922. c1 = *(DNSCACHE **)p1;
  14923. c2 = *(DNSCACHE **)p2;
  14924. if (c1 == NULL || c2 == NULL)
  14925. {
  14926. return 0;
  14927. }
  14928. return StrCmpi(c1->HostName, c2->HostName);
  14929. }
  14930. // Initialization of the DNS cache
  14931. void InitDnsCache()
  14932. {
  14933. // Creating a List
  14934. DnsCache = NewList(CompareDnsCache);
  14935. }
  14936. // Release of the DNS cache
  14937. void FreeDnsCache()
  14938. {
  14939. LockDnsCache();
  14940. {
  14941. DNSCACHE *c;
  14942. UINT i;
  14943. for (i = 0;i < LIST_NUM(DnsCache);i++)
  14944. {
  14945. // Release the memory for the entry
  14946. c = LIST_DATA(DnsCache, i);
  14947. Free(c->HostName);
  14948. Free(c);
  14949. }
  14950. }
  14951. UnlockDnsCache();
  14952. // Release the list
  14953. ReleaseList(DnsCache);
  14954. DnsCache = NULL;
  14955. }
  14956. // Lock the DNS cache
  14957. void LockDnsCache()
  14958. {
  14959. LockList(DnsCache);
  14960. }
  14961. // Unlock the DNS cache
  14962. void UnlockDnsCache()
  14963. {
  14964. UnlockList(DnsCache);
  14965. }
  14966. // DH temp key callback
  14967. DH *TmpDhCallback(SSL *ssl, int is_export, int keylength)
  14968. {
  14969. DH *ret = NULL;
  14970. if (dh_2048 != NULL)
  14971. {
  14972. ret = dh_2048->dh;
  14973. }
  14974. return ret;
  14975. }
  14976. // Create the SSL_CTX
  14977. struct ssl_ctx_st *NewSSLCtx(bool server_mode)
  14978. {
  14979. struct ssl_ctx_st *ctx = SSL_CTX_new(SSLv23_method());
  14980. #ifdef SSL_OP_NO_TICKET
  14981. SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
  14982. #endif // SSL_OP_NO_TICKET
  14983. #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
  14984. if (server_mode)
  14985. {
  14986. SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14987. }
  14988. #endif // SSL_OP_CIPHER_SERVER_PREFERENCE
  14989. SSL_CTX_set_tmp_dh_callback(ctx, TmpDhCallback);
  14990. #ifdef SSL_CTX_set_ecdh_auto
  14991. SSL_CTX_set_ecdh_auto(ctx, 1);
  14992. #endif // SSL_CTX_set_ecdh_auto
  14993. return ctx;
  14994. }
  14995. // Release of the SSL_CTX
  14996. void FreeSSLCtx(struct ssl_ctx_st *ctx)
  14997. {
  14998. // Validate arguments
  14999. if (ctx == NULL)
  15000. {
  15001. return;
  15002. }
  15003. SSL_CTX_free(ctx);
  15004. }
  15005. // The number of get ip threads
  15006. void SetGetIpThreadMaxNum(UINT num)
  15007. {
  15008. max_getip_thread = num;
  15009. }
  15010. UINT GetGetIpThreadMaxNum()
  15011. {
  15012. UINT ret = max_getip_thread;
  15013. if (ret == 0)
  15014. {
  15015. ret = 0x7FFFFFFF;
  15016. }
  15017. return ret;
  15018. }
  15019. UINT GetCurrentGetIpThreadNum()
  15020. {
  15021. return Count(getip_thread_counter);
  15022. }
  15023. // Initialize the network communication module
  15024. void InitNetwork()
  15025. {
  15026. disable_gethostname_by_accept = false;
  15027. InitDynList();
  15028. host_ip_address_list_cache_lock = NewLock();
  15029. host_ip_address_list_cache_last = 0;
  15030. num_tcp_connections = NewCounter();
  15031. getip_thread_counter = NewCounter();
  15032. // Initialization of client list
  15033. InitIpClientList();
  15034. // Thread related initialization
  15035. InitWaitThread();
  15036. // Initialization of the host name cache
  15037. InitHostCache();
  15038. #ifdef OS_WIN32
  15039. // Initializing the socket library
  15040. Win32InitSocketLibrary();
  15041. #else
  15042. UnixInitSocketLibrary();
  15043. #endif // OS_WIN32
  15044. // Initialization of the DNS cache
  15045. InitDnsCache();
  15046. // Locking initialization
  15047. machine_name_lock = NewLock();
  15048. disconnect_function_lock = NewLock();
  15049. aho = NewLock();
  15050. machine_ip_process_hash_lock = NewLock();
  15051. socket_library_lock = NewLock();
  15052. //ssl_connect_lock = NewLock(); //2012.9.28 Not required for recent OpenSSL
  15053. // ssl_accept_lock = NewLock();
  15054. dns_lock = NewLock();
  15055. unix_dns_server_addr_lock = NewLock();
  15056. Zero(&unix_dns_server, sizeof(unix_dns_server));
  15057. local_mac_list_lock = NewLock();
  15058. cipher_list_token = ParseToken(cipher_list, " ");
  15059. current_global_ip_lock = NewLock();
  15060. current_fqdn_lock = NewLock();
  15061. current_global_ip_set = false;
  15062. disable_cache = false;
  15063. dh_2048 = DhNew2048();
  15064. Zero(rand_port_numbers, sizeof(rand_port_numbers));
  15065. SetGetIpThreadMaxNum(DEFAULT_GETIP_THREAD_MAX_NUM);
  15066. }
  15067. // Enable the network name cache
  15068. void EnableNetworkNameCache()
  15069. {
  15070. disable_cache = false;
  15071. }
  15072. // Disable the network name cache
  15073. void DisableNetworkNameCache()
  15074. {
  15075. disable_cache = true;
  15076. }
  15077. // Get whether the network name cache is enabled
  15078. bool IsNetworkNameCacheEnabled()
  15079. {
  15080. return !disable_cache;
  15081. }
  15082. // Get the cipher algorithm list
  15083. TOKEN_LIST *GetCipherList()
  15084. {
  15085. return cipher_list_token;
  15086. }
  15087. // Get the TCP connections counter
  15088. COUNTER *GetNumTcpConnectionsCounter()
  15089. {
  15090. return num_tcp_connections;
  15091. }
  15092. // Get the current global IP address
  15093. bool GetCurrentGlobalIP(IP *ip, bool ipv6)
  15094. {
  15095. bool ret = false;
  15096. // Validate arguments
  15097. if (ip == NULL)
  15098. {
  15099. return false;
  15100. }
  15101. Zero(ip, sizeof(IP));
  15102. Lock(current_global_ip_lock);
  15103. {
  15104. if (ipv6 == false)
  15105. {
  15106. Copy(ip, &current_glocal_ipv4, sizeof(IP));
  15107. }
  15108. else
  15109. {
  15110. Copy(ip, &current_glocal_ipv6, sizeof(IP));
  15111. }
  15112. ret = current_global_ip_set;
  15113. }
  15114. Unlock(current_global_ip_lock);
  15115. return ret;
  15116. }
  15117. // Check whether the specified IP address is assigned to the local host
  15118. bool IsIPMyHost(IP *ip)
  15119. {
  15120. LIST *o;
  15121. UINT i;
  15122. bool ret = false;
  15123. // Validate arguments
  15124. if (ip == NULL)
  15125. {
  15126. return false;
  15127. }
  15128. if (IsZeroIp(ip))
  15129. {
  15130. return false;
  15131. }
  15132. // Search to check whether it matches to any of the IP of the local host
  15133. o = GetHostIPAddressList();
  15134. for (i = 0;i < LIST_NUM(o);i++)
  15135. {
  15136. IP *p = LIST_DATA(o, i);
  15137. if (CmpIpAddr(p, ip) == 0)
  15138. {
  15139. // Matched
  15140. ret = true;
  15141. break;
  15142. }
  15143. }
  15144. FreeHostIPAddressList(o);
  15145. if (ret == false)
  15146. {
  15147. if (IsLocalHostIP(ip))
  15148. {
  15149. // localhost IP addresses
  15150. ret = true;
  15151. }
  15152. }
  15153. return ret;
  15154. }
  15155. // Check whether the specified IP address is a private IP address
  15156. bool IsIPPrivate(IP *ip)
  15157. {
  15158. // Validate arguments
  15159. if (ip == NULL)
  15160. {
  15161. return false;
  15162. }
  15163. if (ip->addr[0] == 10)
  15164. {
  15165. return true;
  15166. }
  15167. if (ip->addr[0] == 172)
  15168. {
  15169. if (ip->addr[1] >= 16 && ip->addr[1] <= 31)
  15170. {
  15171. return true;
  15172. }
  15173. }
  15174. if (ip->addr[0] == 192 && ip->addr[1] == 168)
  15175. {
  15176. return true;
  15177. }
  15178. if (ip->addr[0] == 169 && ip->addr[1] == 254)
  15179. {
  15180. return true;
  15181. }
  15182. if (ip->addr[0] == 100)
  15183. {
  15184. if (ip->addr[1] >= 64 && ip->addr[1] <= 127)
  15185. {
  15186. return true;
  15187. }
  15188. }
  15189. if (g_private_ip_list != NULL)
  15190. {
  15191. if (IsIP4(ip))
  15192. {
  15193. UINT ip4 = IPToUINT(ip);
  15194. return IsOnPrivateIPFile(ip4);
  15195. }
  15196. }
  15197. return false;
  15198. }
  15199. // Is the IP address either local or private?
  15200. bool IsIPLocalOrPrivate(IP *ip)
  15201. {
  15202. // Validate arguments
  15203. if (ip == NULL)
  15204. {
  15205. return false;
  15206. }
  15207. if (IsIPPrivate(ip))
  15208. {
  15209. return true;
  15210. }
  15211. if (IsLocalHostIP(ip))
  15212. {
  15213. return true;
  15214. }
  15215. if (IsIPMyHost(ip))
  15216. {
  15217. return true;
  15218. }
  15219. return false;
  15220. }
  15221. // Read a private IP list file
  15222. void LoadPrivateIPFile()
  15223. {
  15224. BUF *b = ReadDump(PRIVATE_IP_TXT_FILENAME);
  15225. LIST *o;
  15226. if (b == NULL)
  15227. {
  15228. return;
  15229. }
  15230. o = NewList(NULL);
  15231. while (true)
  15232. {
  15233. char *line = CfgReadNextLine(b);
  15234. if (line == NULL)
  15235. {
  15236. break;
  15237. }
  15238. Trim(line);
  15239. if (IsEmptyStr(line) == false)
  15240. {
  15241. UINT ip = 0, mask = 0;
  15242. if (ParseIpAndSubnetMask4(line, &ip, &mask))
  15243. {
  15244. PRIVATE_IP_SUBNET *p = ZeroMalloc(sizeof(PRIVATE_IP_SUBNET));
  15245. p->Ip = ip;
  15246. p->Mask = mask;
  15247. p->Ip2 = ip & mask;
  15248. Add(o, p);
  15249. }
  15250. }
  15251. Free(line);
  15252. }
  15253. g_private_ip_list = o;
  15254. g_use_privateip_file = true;
  15255. FreeBuf(b);
  15256. }
  15257. // Examine whether the specified IP address is in the private IP file
  15258. bool IsOnPrivateIPFile(UINT ip)
  15259. {
  15260. bool ret = false;
  15261. if (g_private_ip_list != NULL)
  15262. {
  15263. LIST *o = g_private_ip_list;
  15264. UINT i;
  15265. for (i = 0;i < LIST_NUM(o);i++)
  15266. {
  15267. PRIVATE_IP_SUBNET *p = LIST_DATA(o, i);
  15268. if ((ip & p->Mask) == p->Ip2)
  15269. {
  15270. ret = true;
  15271. }
  15272. }
  15273. }
  15274. return ret;
  15275. }
  15276. // Free the private IP file
  15277. void FreePrivateIPFile()
  15278. {
  15279. if (g_private_ip_list != NULL)
  15280. {
  15281. LIST *o = g_private_ip_list;
  15282. UINT i;
  15283. g_private_ip_list = NULL;
  15284. for (i = 0;i < LIST_NUM(o);i++)
  15285. {
  15286. PRIVATE_IP_SUBNET *p = LIST_DATA(o, i);
  15287. Free(p);
  15288. }
  15289. ReleaseList(o);
  15290. }
  15291. g_use_privateip_file = false;
  15292. }
  15293. // Check whether the specified IP address is in the same network to this computer
  15294. bool IsIPAddressInSameLocalNetwork(IP *a)
  15295. {
  15296. bool ret = false;
  15297. LIST *o;
  15298. UINT i;
  15299. // Validate arguments
  15300. if (a == NULL)
  15301. {
  15302. return false;
  15303. }
  15304. o = GetHostIPAddressList();
  15305. if (o != NULL)
  15306. {
  15307. for (i = 0;i < LIST_NUM(o);i++)
  15308. {
  15309. IP *p = LIST_DATA(o, i);
  15310. if (IsIP4(p))
  15311. {
  15312. if (IsZeroIp(p) == false && p->addr[0] != 127)
  15313. {
  15314. if (IsInSameNetwork4Standard(p, a))
  15315. {
  15316. ret = true;
  15317. break;
  15318. }
  15319. }
  15320. }
  15321. }
  15322. FreeHostIPAddressList(o);
  15323. }
  15324. return ret;
  15325. }
  15326. // Guess the IPv4, IPv6 global address from the IP address list of the current interface
  15327. void GetCurrentGlobalIPGuess(IP *ip, bool ipv6)
  15328. {
  15329. LIST *o;
  15330. UINT i;
  15331. // Validate arguments
  15332. if (ip == NULL)
  15333. {
  15334. return;
  15335. }
  15336. Zero(ip, sizeof(IP));
  15337. o = GetHostIPAddressList();
  15338. if (ipv6 == false)
  15339. {
  15340. // IPv4
  15341. for (i = 0;i < LIST_NUM(o);i++)
  15342. {
  15343. IP *p = LIST_DATA(o, i);
  15344. if (IsIP4(p))
  15345. {
  15346. if (IsZeroIp(p) == false && IsIPPrivate(p) == false && p->addr[0] != 127)
  15347. {
  15348. Copy(ip, p, sizeof(IP));
  15349. }
  15350. }
  15351. }
  15352. if (IsZeroIp(ip))
  15353. {
  15354. for (i = 0;i < LIST_NUM(o);i++)
  15355. {
  15356. IP *p = LIST_DATA(o, i);
  15357. if (IsIP4(p))
  15358. {
  15359. if (IsZeroIp(p) == false && IsIPPrivate(p) && p->addr[0] != 127)
  15360. {
  15361. Copy(ip, p, sizeof(IP));
  15362. }
  15363. }
  15364. }
  15365. }
  15366. if (IsZeroIp(ip))
  15367. {
  15368. SetIP(ip, 127, 0, 0, 1);
  15369. }
  15370. }
  15371. else
  15372. {
  15373. // IPv6
  15374. for (i = 0;i < LIST_NUM(o);i++)
  15375. {
  15376. IP *p = LIST_DATA(o, i);
  15377. if (IsIP6(p))
  15378. {
  15379. UINT type = GetIPAddrType6(p);
  15380. if ((type & IPV6_ADDR_GLOBAL_UNICAST) && ((type & IPV6_ADDR_ZERO) == 0) && ((type & IPV6_ADDR_LOOPBACK) == 0))
  15381. {
  15382. Copy(ip, p, sizeof(IP));
  15383. }
  15384. }
  15385. }
  15386. }
  15387. FreeHostIPAddressList(o);
  15388. }
  15389. // Record the current global IP address
  15390. void SetCurrentGlobalIP(IP *ip, bool ipv6)
  15391. {
  15392. // Validate arguments
  15393. if (ip == NULL)
  15394. {
  15395. return;
  15396. }
  15397. if (IsZeroIp(ip))
  15398. {
  15399. return;
  15400. }
  15401. Lock(current_global_ip_lock);
  15402. {
  15403. if (ipv6 == false)
  15404. {
  15405. Copy(&current_glocal_ipv4, ip, sizeof(IP));
  15406. }
  15407. else
  15408. {
  15409. Copy(&current_glocal_ipv6, ip, sizeof(IP));
  15410. }
  15411. current_global_ip_set = true;
  15412. }
  15413. Unlock(current_global_ip_lock);
  15414. }
  15415. // Release of the network communication module
  15416. void FreeNetwork()
  15417. {
  15418. if (dh_2048 != NULL)
  15419. {
  15420. DhFree(dh_2048);
  15421. dh_2048 = NULL;
  15422. }
  15423. // Release of thread-related
  15424. FreeWaitThread();
  15425. FreeToken(cipher_list_token);
  15426. cipher_list_token = NULL;
  15427. Zero(&unix_dns_server, sizeof(unix_dns_server));
  15428. // Release the locks
  15429. DeleteLock(unix_dns_server_addr_lock);
  15430. DeleteLock(dns_lock);
  15431. DeleteLock(ssl_accept_lock);
  15432. DeleteLock(machine_name_lock);
  15433. DeleteLock(disconnect_function_lock);
  15434. DeleteLock(aho);
  15435. DeleteLock(socket_library_lock);
  15436. DeleteLock(ssl_connect_lock);
  15437. DeleteLock(machine_ip_process_hash_lock);
  15438. machine_name_lock = NULL;
  15439. ssl_accept_lock = machine_name_lock = disconnect_function_lock =
  15440. aho = socket_library_lock = ssl_connect_lock = machine_ip_process_hash_lock = NULL;
  15441. // Release of the DNS cache
  15442. FreeDnsCache();
  15443. // Release of the host name cache
  15444. FreeHostCache();
  15445. #ifdef OS_WIN32
  15446. // Release of the socket library
  15447. Win32FreeSocketLibrary();
  15448. #else
  15449. UnixFreeSocketLibrary();
  15450. #endif // OS_WIN32
  15451. DeleteCounter(num_tcp_connections);
  15452. num_tcp_connections = NULL;
  15453. // Release of client list
  15454. FreeIpClientList();
  15455. DeleteLock(current_global_ip_lock);
  15456. current_global_ip_lock = NULL;
  15457. DeleteLock(current_fqdn_lock);
  15458. current_fqdn_lock = NULL;
  15459. // Release of the local MAC list
  15460. if (local_mac_list != NULL)
  15461. {
  15462. FreeNicList(local_mac_list);
  15463. local_mac_list = NULL;
  15464. }
  15465. DeleteLock(local_mac_list_lock);
  15466. local_mac_list_lock = NULL;
  15467. DeleteLock(host_ip_address_list_cache_lock);
  15468. host_ip_address_list_cache_lock = NULL;
  15469. FreeHostIPAddressList(host_ip_address_cache);
  15470. host_ip_address_cache = NULL;
  15471. FreeDynList();
  15472. DeleteCounter(getip_thread_counter);
  15473. getip_thread_counter = NULL;
  15474. }
  15475. // Add a socket to socket list
  15476. void AddSockList(SOCKLIST *sl, SOCK *s)
  15477. {
  15478. // Validate arguments
  15479. if (sl == NULL || s == NULL)
  15480. {
  15481. return;
  15482. }
  15483. LockList(sl->SockList);
  15484. {
  15485. if (IsInList(sl->SockList, s) == false)
  15486. {
  15487. AddRef(s->ref);
  15488. Insert(sl->SockList, s);
  15489. }
  15490. }
  15491. UnlockList(sl->SockList);
  15492. }
  15493. // Remove the socket from socket list
  15494. void DelSockList(SOCKLIST *sl, SOCK *s)
  15495. {
  15496. // Validate arguments
  15497. if (sl == NULL || s == NULL)
  15498. {
  15499. return;
  15500. }
  15501. LockList(sl->SockList);
  15502. {
  15503. if (Delete(sl->SockList, s))
  15504. {
  15505. ReleaseSock(s);
  15506. }
  15507. }
  15508. UnlockList(sl->SockList);
  15509. }
  15510. // Stop all the sockets in the list and delete it
  15511. void StopSockList(SOCKLIST *sl)
  15512. {
  15513. SOCK **ss;
  15514. UINT num, i;
  15515. // Validate arguments
  15516. if (sl == NULL)
  15517. {
  15518. return;
  15519. }
  15520. LockList(sl->SockList);
  15521. {
  15522. num = LIST_NUM(sl->SockList);
  15523. ss = ToArray(sl->SockList);
  15524. DeleteAll(sl->SockList);
  15525. }
  15526. UnlockList(sl->SockList);
  15527. for (i = 0;i < num;i++)
  15528. {
  15529. SOCK *s = ss[i];
  15530. Disconnect(s);
  15531. ReleaseSock(s);
  15532. }
  15533. Free(ss);
  15534. }
  15535. // Delete the socket list
  15536. void FreeSockList(SOCKLIST *sl)
  15537. {
  15538. // Validate arguments
  15539. if (sl == NULL)
  15540. {
  15541. return;
  15542. }
  15543. StopSockList(sl);
  15544. ReleaseList(sl->SockList);
  15545. Free(sl);
  15546. }
  15547. // Creating a socket list
  15548. SOCKLIST *NewSockList()
  15549. {
  15550. SOCKLIST *sl = ZeroMallocFast(sizeof(SOCKLIST));
  15551. sl->SockList = NewList(NULL);
  15552. return sl;
  15553. }
  15554. // Time-out thread of the socket on Solaris
  15555. void SocketTimeoutThread(THREAD *t, void *param)
  15556. {
  15557. SOCKET_TIMEOUT_PARAM *ttparam;
  15558. ttparam = (SOCKET_TIMEOUT_PARAM *)param;
  15559. // Wait for time-out period
  15560. Select(NULL, ttparam->sock->TimeOut, ttparam->cancel, NULL);
  15561. // Disconnect if it is blocked
  15562. if(! ttparam->unblocked)
  15563. {
  15564. // Debug("Socket timeouted\n");
  15565. closesocket(ttparam->sock->socket);
  15566. }
  15567. else
  15568. {
  15569. // Debug("Socket timeout cancelled\n");
  15570. }
  15571. }
  15572. // Initialize and start the thread for time-out
  15573. SOCKET_TIMEOUT_PARAM *NewSocketTimeout(SOCK *sock)
  15574. {
  15575. SOCKET_TIMEOUT_PARAM *ttp;
  15576. if(! sock->AsyncMode && sock->TimeOut != TIMEOUT_INFINITE)
  15577. {
  15578. // Debug("NewSockTimeout(%u)\n",sock->TimeOut);
  15579. ttp = (SOCKET_TIMEOUT_PARAM*)Malloc(sizeof(SOCKET_TIMEOUT_PARAM));
  15580. // Set the parameters of the time-out thread
  15581. ttp->cancel = NewCancel();
  15582. ttp->sock = sock;
  15583. ttp->unblocked = false;
  15584. ttp->thread = NewThread(SocketTimeoutThread, ttp);
  15585. return ttp;
  15586. }
  15587. return NULL;
  15588. }
  15589. // Stop and free the thread for timeout
  15590. void FreeSocketTimeout(SOCKET_TIMEOUT_PARAM *ttp)
  15591. {
  15592. if(ttp == NULL)
  15593. {
  15594. return;
  15595. }
  15596. ttp->unblocked = true;
  15597. Cancel(ttp->cancel);
  15598. WaitThread(ttp->thread, INFINITE);
  15599. ReleaseCancel(ttp->cancel);
  15600. ReleaseThread(ttp->thread);
  15601. Free(ttp);
  15602. // Debug("FreeSocketTimeout succeed\n");
  15603. return;
  15604. }
  15605. // Parse the IP address and subnet mask
  15606. bool ParseIpAndSubnetMask46(char *src, IP *ip, IP *mask)
  15607. {
  15608. // Validate arguments
  15609. if (src == NULL || ip == NULL || mask == NULL)
  15610. {
  15611. return false;
  15612. }
  15613. if (ParseIpAndMask46(src, ip, mask) == false)
  15614. {
  15615. return false;
  15616. }
  15617. if (IsIP4(ip))
  15618. {
  15619. return IsSubnetMask4(mask);
  15620. }
  15621. else
  15622. {
  15623. return IsSubnetMask6(mask);
  15624. }
  15625. }
  15626. bool ParseIpAndSubnetMask6(char *src, IP *ip, IP *mask)
  15627. {
  15628. if (ParseIpAndSubnetMask46(src, ip, mask) == false)
  15629. {
  15630. return false;
  15631. }
  15632. if (IsIP6(ip) == false)
  15633. {
  15634. return false;
  15635. }
  15636. return true;
  15637. }
  15638. bool ParseIpAndSubnetMask4(char *src, UINT *ip, UINT *mask)
  15639. {
  15640. IP ip2, mask2;
  15641. // Validate arguments
  15642. if (src == NULL)
  15643. {
  15644. return false;
  15645. }
  15646. if (ParseIpAndSubnetMask46(src, &ip2, &mask2) == false)
  15647. {
  15648. return false;
  15649. }
  15650. if (IsIP4(&ip2) == false)
  15651. {
  15652. return false;
  15653. }
  15654. if (ip != NULL)
  15655. {
  15656. *ip = IPToUINT(&ip2);
  15657. }
  15658. if (mask != NULL)
  15659. {
  15660. *mask = IPToUINT(&mask2);
  15661. }
  15662. return true;
  15663. }
  15664. // Parse the IP address and the mask
  15665. bool ParseIpAndMask46(char *src, IP *ip, IP *mask)
  15666. {
  15667. TOKEN_LIST *t;
  15668. char *ipstr;
  15669. char *subnetstr;
  15670. bool ret = false;
  15671. IP ip2;
  15672. IP mask2;
  15673. // Validate arguments
  15674. if (src == NULL || ip == NULL || mask == NULL)
  15675. {
  15676. return false;
  15677. }
  15678. Zero(&ip2, sizeof(IP));
  15679. Zero(&mask2, sizeof(IP));
  15680. t = ParseToken(src, "/");
  15681. if (t->NumTokens != 2)
  15682. {
  15683. FreeToken(t);
  15684. return false;
  15685. }
  15686. ipstr = t->Token[0];
  15687. subnetstr = t->Token[1];
  15688. Trim(ipstr);
  15689. Trim(subnetstr);
  15690. if (StrToIP(&ip2, ipstr))
  15691. {
  15692. if (StrToIP(&mask2, subnetstr))
  15693. {
  15694. // Compare the kind of the mask part and the IP address part to confirm same
  15695. if (IsIP6(&ip2) && IsIP6(&mask2))
  15696. {
  15697. // Both are IPv6
  15698. ret = true;
  15699. Copy(ip, &ip2, sizeof(IP));
  15700. Copy(mask, &mask2, sizeof(IP));
  15701. }
  15702. else if (IsIP4(&ip2) && IsIP4(&mask2))
  15703. {
  15704. // Both are IPv4
  15705. ret = true;
  15706. Copy(ip, &ip2, sizeof(IP));
  15707. Copy(mask, &mask2, sizeof(IP));
  15708. }
  15709. }
  15710. else
  15711. {
  15712. if (IsNum(subnetstr))
  15713. {
  15714. UINT i = ToInt(subnetstr);
  15715. // Mask part is a number
  15716. if (IsIP6(&ip2) && i <= 128)
  15717. {
  15718. ret = true;
  15719. Copy(ip, &ip2, sizeof(IP));
  15720. IntToSubnetMask6(mask, i);
  15721. }
  15722. else if (i <= 32)
  15723. {
  15724. ret = true;
  15725. Copy(ip, &ip2, sizeof(IP));
  15726. IntToSubnetMask4(mask, i);
  15727. }
  15728. }
  15729. }
  15730. }
  15731. FreeToken(t);
  15732. return ret;
  15733. }
  15734. bool ParseIpAndMask4(char *src, UINT *ip, UINT *mask)
  15735. {
  15736. IP ip_ip, ip_mask;
  15737. if (ParseIpAndMask46(src, &ip_ip, &ip_mask) == false)
  15738. {
  15739. return false;
  15740. }
  15741. if (IsIP4(&ip_ip) == false)
  15742. {
  15743. return false;
  15744. }
  15745. if (ip != NULL)
  15746. {
  15747. *ip = IPToUINT(&ip_ip);
  15748. }
  15749. if (mask != NULL)
  15750. {
  15751. *mask = IPToUINT(&ip_mask);
  15752. }
  15753. return true;
  15754. }
  15755. bool ParseIpAndMask6(char *src, IP *ip, IP *mask)
  15756. {
  15757. if (ParseIpAndMask46(src, ip, mask) == false)
  15758. {
  15759. return false;
  15760. }
  15761. if (IsIP6(ip) == false)
  15762. {
  15763. return false;
  15764. }
  15765. return true;
  15766. }
  15767. // Check whether the specification of the IPv4 address is correct
  15768. bool IsIpStr4(char *str)
  15769. {
  15770. // Validate arguments
  15771. if (str == NULL)
  15772. {
  15773. return false;
  15774. }
  15775. if (StrToIP32(str) == 0 && StrCmpi(str, "0.0.0.0") != 0)
  15776. {
  15777. return false;
  15778. }
  15779. return true;
  15780. }
  15781. // Check whether the specification of the IPv6 address is correct
  15782. bool IsIpStr6(char *str)
  15783. {
  15784. IP ip;
  15785. // Validate arguments
  15786. if (str == NULL)
  15787. {
  15788. return false;
  15789. }
  15790. if (StrToIP6(&ip, str) == false)
  15791. {
  15792. return false;
  15793. }
  15794. return true;
  15795. }
  15796. // Check whether the IP address specification is correct
  15797. bool IsIpStr46(char *str)
  15798. {
  15799. if (IsIpStr4(str) || IsIpStr6(str))
  15800. {
  15801. return true;
  15802. }
  15803. return false;
  15804. }
  15805. // Convert the string to an IPv4 mask
  15806. bool StrToMask4(IP *mask, char *str)
  15807. {
  15808. // Validate arguments
  15809. if (mask == NULL || str == NULL)
  15810. {
  15811. return false;
  15812. }
  15813. if (str[0] == '/')
  15814. {
  15815. str++;
  15816. }
  15817. if (IsNum(str))
  15818. {
  15819. UINT n = ToInt(str);
  15820. if (n <= 32)
  15821. {
  15822. IntToSubnetMask4(mask, n);
  15823. return true;
  15824. }
  15825. else
  15826. {
  15827. return false;
  15828. }
  15829. }
  15830. else
  15831. {
  15832. if (StrToIP(mask, str) == false)
  15833. {
  15834. return false;
  15835. }
  15836. else
  15837. {
  15838. return IsIP4(mask);
  15839. }
  15840. }
  15841. }
  15842. // Convert the string to an IPv6 mask
  15843. bool StrToMask6(IP *mask, char *str)
  15844. {
  15845. // Validate arguments
  15846. if (mask == NULL || str == NULL)
  15847. {
  15848. return false;
  15849. }
  15850. if (str[0] == '/')
  15851. {
  15852. str++;
  15853. }
  15854. if (IsNum(str))
  15855. {
  15856. UINT n = ToInt(str);
  15857. if (n <= 128)
  15858. {
  15859. IntToSubnetMask6(mask, n);
  15860. return true;
  15861. }
  15862. else
  15863. {
  15864. return false;
  15865. }
  15866. }
  15867. else
  15868. {
  15869. if (StrToIP(mask, str) == false)
  15870. {
  15871. return false;
  15872. }
  15873. else
  15874. {
  15875. return IsIP6(mask);
  15876. }
  15877. }
  15878. }
  15879. bool StrToMask6Addr(IPV6_ADDR *mask, char *str)
  15880. {
  15881. IP ip;
  15882. if (StrToMask6(&ip, str) == false)
  15883. {
  15884. return false;
  15885. }
  15886. if (IPToIPv6Addr(mask, &ip) == false)
  15887. {
  15888. return false;
  15889. }
  15890. return true;
  15891. }
  15892. // Convert the string to an IPv4 / IPv6 mask
  15893. bool StrToMask46(IP *mask, char *str, bool ipv6)
  15894. {
  15895. if (ipv6)
  15896. {
  15897. return StrToMask6(mask, str);
  15898. }
  15899. else
  15900. {
  15901. return StrToMask4(mask, str);
  15902. }
  15903. }
  15904. // Convert the IPv4 / IPv6 mask to a string
  15905. void MaskToStr(char *str, UINT size, IP *mask)
  15906. {
  15907. MaskToStrEx(str, size, mask, false);
  15908. }
  15909. void MaskToStrEx(char *str, UINT size, IP *mask, bool always_full_address)
  15910. {
  15911. // Validate arguments
  15912. if (str == NULL || mask == NULL)
  15913. {
  15914. return;
  15915. }
  15916. if (always_full_address == false && IsSubnetMask(mask))
  15917. {
  15918. ToStr(str, SubnetMaskToInt(mask));
  15919. }
  15920. else
  15921. {
  15922. IPToStr(str, size, mask);
  15923. }
  15924. }
  15925. void MaskToStr32(char *str, UINT size, UINT mask)
  15926. {
  15927. MaskToStr32Ex(str, size, mask, false);
  15928. }
  15929. void MaskToStr32Ex(char *str, UINT size, UINT mask, bool always_full_address)
  15930. {
  15931. IP ip;
  15932. UINTToIP(&ip, mask);
  15933. MaskToStrEx(str, size, &ip, always_full_address);
  15934. }
  15935. void Mask6AddrToStrEx(char *str, UINT size, IPV6_ADDR *mask, bool always_full_address)
  15936. {
  15937. IP ip;
  15938. // Validate arguments
  15939. if (str == NULL || mask == NULL)
  15940. {
  15941. StrCpy(str, size, "");
  15942. return;
  15943. }
  15944. IPv6AddrToIP(&ip, mask);
  15945. MaskToStrEx(str, size, &ip, always_full_address);
  15946. }
  15947. void Mask6AddrToStr(char *str, UINT size, IPV6_ADDR *mask)
  15948. {
  15949. Mask6AddrToStrEx(str, size, mask, false);
  15950. }
  15951. // Disconnecting of the tube
  15952. void TubeDisconnect(TUBE *t)
  15953. {
  15954. // Validate arguments
  15955. if (t == NULL)
  15956. {
  15957. return;
  15958. }
  15959. if (t->TubePairData == NULL)
  15960. {
  15961. return;
  15962. }
  15963. Lock(t->TubePairData->Lock);
  15964. {
  15965. t->TubePairData->IsDisconnected = true;
  15966. Set(t->TubePairData->Event1);
  15967. Set(t->TubePairData->Event2);
  15968. SetSockEvent(t->TubePairData->SockEvent1);
  15969. SetSockEvent(t->TubePairData->SockEvent2);
  15970. }
  15971. Unlock(t->TubePairData->Lock);
  15972. }
  15973. // Creating a tube pair
  15974. void NewTubePair(TUBE **t1, TUBE **t2, UINT size_of_header)
  15975. {
  15976. TUBEPAIR_DATA *d;
  15977. // Validate arguments
  15978. if (t1 == NULL || t2 == NULL)
  15979. {
  15980. return;
  15981. }
  15982. *t1 = NewTube(size_of_header);
  15983. *t2 = NewTube(size_of_header);
  15984. (*t1)->IndexInTubePair = 0;
  15985. (*t2)->IndexInTubePair = 1;
  15986. d = NewTubePairData();
  15987. AddRef(d->Ref);
  15988. (*t1)->TubePairData = d;
  15989. (*t2)->TubePairData = d;
  15990. d->Event1 = (*t1)->Event;
  15991. d->Event2 = (*t2)->Event;
  15992. AddRef(d->Event1->ref);
  15993. AddRef(d->Event2->ref);
  15994. }
  15995. // Creating a tube pair data
  15996. TUBEPAIR_DATA *NewTubePairData()
  15997. {
  15998. TUBEPAIR_DATA *d = ZeroMalloc(sizeof(TUBEPAIR_DATA));
  15999. d->Ref = NewRef();
  16000. d->Lock = NewLock();
  16001. return d;
  16002. }
  16003. // Set the SockEvent to the tube
  16004. void SetTubeSockEvent(TUBE *t, SOCK_EVENT *e)
  16005. {
  16006. // Validate arguments
  16007. if (t == NULL)
  16008. {
  16009. return;
  16010. }
  16011. Lock(t->Lock);
  16012. {
  16013. TUBEPAIR_DATA *d;
  16014. if (t->SockEvent != e)
  16015. {
  16016. if (t->SockEvent != NULL)
  16017. {
  16018. ReleaseSockEvent(t->SockEvent);
  16019. }
  16020. if (e != NULL)
  16021. {
  16022. AddRef(e->ref);
  16023. }
  16024. t->SockEvent = e;
  16025. }
  16026. d = t->TubePairData;
  16027. if (d != NULL)
  16028. {
  16029. Lock(d->Lock);
  16030. {
  16031. SOCK_EVENT **sep = (t->IndexInTubePair == 0 ? &d->SockEvent1 : &d->SockEvent2);
  16032. if (*sep != e)
  16033. {
  16034. if (*sep != NULL)
  16035. {
  16036. ReleaseSockEvent(*sep);
  16037. }
  16038. if (e != NULL)
  16039. {
  16040. AddRef(e->ref);
  16041. }
  16042. *sep = e;
  16043. }
  16044. }
  16045. Unlock(d->Lock);
  16046. }
  16047. }
  16048. Unlock(t->Lock);
  16049. }
  16050. // Release of the tube pair data
  16051. void ReleaseTubePairData(TUBEPAIR_DATA *d)
  16052. {
  16053. // Validate arguments
  16054. if (d == NULL)
  16055. {
  16056. return;
  16057. }
  16058. if (Release(d->Ref) == 0)
  16059. {
  16060. CleanupTubePairData(d);
  16061. }
  16062. }
  16063. void CleanupTubePairData(TUBEPAIR_DATA *d)
  16064. {
  16065. // Validate arguments
  16066. if (d == NULL)
  16067. {
  16068. return;
  16069. }
  16070. ReleaseEvent(d->Event1);
  16071. ReleaseEvent(d->Event2);
  16072. ReleaseSockEvent(d->SockEvent1);
  16073. ReleaseSockEvent(d->SockEvent2);
  16074. DeleteLock(d->Lock);
  16075. Free(d);
  16076. }
  16077. // Check whether the tube is connected to the opponent still
  16078. bool IsTubeConnected(TUBE *t)
  16079. {
  16080. // Validate arguments
  16081. if (t == NULL)
  16082. {
  16083. return false;
  16084. }
  16085. if (t->TubePairData == NULL)
  16086. {
  16087. return true;
  16088. }
  16089. if (t->TubePairData->IsDisconnected)
  16090. {
  16091. return false;
  16092. }
  16093. return true;
  16094. }
  16095. // Send the data to the tube
  16096. bool TubeSend(TUBE *t, void *data, UINT size, void *header)
  16097. {
  16098. return TubeSendEx(t, data, size, header, false);
  16099. }
  16100. bool TubeSendEx(TUBE *t, void *data, UINT size, void *header, bool no_flush)
  16101. {
  16102. return TubeSendEx2(t, data, size, header, no_flush, 0);
  16103. }
  16104. bool TubeSendEx2(TUBE *t, void *data, UINT size, void *header, bool no_flush, UINT max_num_in_queue)
  16105. {
  16106. // Validate arguments
  16107. if (t == NULL || data == NULL || size == 0)
  16108. {
  16109. return false;
  16110. }
  16111. if (IsTubeConnected(t) == false)
  16112. {
  16113. return false;
  16114. }
  16115. LockQueue(t->Queue);
  16116. {
  16117. if (max_num_in_queue == 0 || (t->Queue->num_item <= max_num_in_queue))
  16118. {
  16119. InsertQueue(t->Queue, NewTubeData(data, size, header, t->SizeOfHeader));
  16120. }
  16121. else
  16122. {
  16123. no_flush = true;
  16124. }
  16125. }
  16126. UnlockQueue(t->Queue);
  16127. if (no_flush == false)
  16128. {
  16129. Set(t->Event);
  16130. SetSockEvent(t->SockEvent);
  16131. }
  16132. return true;
  16133. }
  16134. // Flush the tube
  16135. void TubeFlush(TUBE *t)
  16136. {
  16137. TubeFlushEx(t, false);
  16138. }
  16139. void TubeFlushEx(TUBE *t, bool force)
  16140. {
  16141. // Validate arguments
  16142. if (t == NULL)
  16143. {
  16144. return;
  16145. }
  16146. if (IsTubeConnected(t) == false)
  16147. {
  16148. return;
  16149. }
  16150. if (force == false)
  16151. {
  16152. if (t->Queue->num_item == 0)
  16153. {
  16154. return;
  16155. }
  16156. }
  16157. Set(t->Event);
  16158. SetSockEvent(t->SockEvent);
  16159. }
  16160. // Receive the data from the tube (asynchronous)
  16161. TUBEDATA *TubeRecvAsync(TUBE *t)
  16162. {
  16163. TUBEDATA *d;
  16164. // Validate arguments
  16165. if (t == NULL)
  16166. {
  16167. return NULL;
  16168. }
  16169. if (IsTubeConnected(t) == false)
  16170. {
  16171. return NULL;
  16172. }
  16173. LockQueue(t->Queue);
  16174. {
  16175. d = GetNext(t->Queue);
  16176. }
  16177. UnlockQueue(t->Queue);
  16178. return d;
  16179. }
  16180. // Get the SockEvent associated with the tube
  16181. SOCK_EVENT *GetTubeSockEvent(TUBE *t)
  16182. {
  16183. SOCK_EVENT *e = NULL;
  16184. // Validate arguments
  16185. if (t == NULL)
  16186. {
  16187. return NULL;
  16188. }
  16189. Lock(t->Lock);
  16190. {
  16191. if (t->SockEvent != NULL)
  16192. {
  16193. AddRef(t->SockEvent->ref);
  16194. e = t->SockEvent;
  16195. }
  16196. }
  16197. Unlock(t->Lock);
  16198. return e;
  16199. }
  16200. // Receive the data from the tube (synchronous)
  16201. TUBEDATA *TubeRecvSync(TUBE *t, UINT timeout)
  16202. {
  16203. UINT64 start_tick, timeout_tick;
  16204. TUBEDATA *d = NULL;
  16205. // Validate arguments
  16206. if (t == NULL)
  16207. {
  16208. return NULL;
  16209. }
  16210. if (IsTubeConnected(t) == false)
  16211. {
  16212. return NULL;
  16213. }
  16214. start_tick = Tick64();
  16215. timeout_tick = start_tick + (UINT64)timeout;
  16216. while (true)
  16217. {
  16218. UINT64 now = Tick64();
  16219. UINT remain_time;
  16220. SOCK_EVENT *e;
  16221. UINT interval;
  16222. d = NULL;
  16223. if (IsTubeConnected(t) == false)
  16224. {
  16225. break;
  16226. }
  16227. LockQueue(t->Queue);
  16228. {
  16229. d = GetNext(t->Queue);
  16230. }
  16231. UnlockQueue(t->Queue);
  16232. if (d != NULL)
  16233. {
  16234. break;
  16235. }
  16236. if (timeout != INFINITE && now >= timeout_tick)
  16237. {
  16238. return NULL;
  16239. }
  16240. remain_time = (UINT)(timeout_tick - now);
  16241. e = GetTubeSockEvent(t);
  16242. interval = (timeout == INFINITE ? INFINITE : remain_time);
  16243. if (e == NULL)
  16244. {
  16245. Wait(t->Event, interval);
  16246. }
  16247. else
  16248. {
  16249. WaitSockEvent(e, interval);
  16250. ReleaseSockEvent(e);
  16251. }
  16252. }
  16253. return d;
  16254. }
  16255. // Creating a tube
  16256. TUBE *NewTube(UINT size_of_header)
  16257. {
  16258. TUBE *t = ZeroMalloc(sizeof(TUBE));
  16259. t->Event = NewEvent();
  16260. t->Queue = NewQueue();
  16261. t->Ref = NewRef();
  16262. t->Lock = NewLock();
  16263. t->SockEvent = NewSockEvent();
  16264. t->SizeOfHeader = size_of_header;
  16265. return t;
  16266. }
  16267. // Release of the tube
  16268. void ReleaseTube(TUBE *t)
  16269. {
  16270. // Validate arguments
  16271. if (t == NULL)
  16272. {
  16273. return;
  16274. }
  16275. if (Release(t->Ref) == 0)
  16276. {
  16277. CleanupTube(t);
  16278. }
  16279. }
  16280. void CleanupTube(TUBE *t)
  16281. {
  16282. // Validate arguments
  16283. if (t == NULL)
  16284. {
  16285. return;
  16286. }
  16287. while (true)
  16288. {
  16289. TUBEDATA *d = GetNext(t->Queue);
  16290. if (d == NULL)
  16291. {
  16292. break;
  16293. }
  16294. FreeTubeData(d);
  16295. }
  16296. ReleaseQueue(t->Queue);
  16297. ReleaseEvent(t->Event);
  16298. ReleaseSockEvent(t->SockEvent);
  16299. ReleaseTubePairData(t->TubePairData);
  16300. DeleteLock(t->Lock);
  16301. Free(t);
  16302. }
  16303. // Creating a tube data
  16304. TUBEDATA *NewTubeData(void *data, UINT size, void *header, UINT header_size)
  16305. {
  16306. TUBEDATA *d;
  16307. // Validate arguments
  16308. if (size == 0 || data == NULL)
  16309. {
  16310. return NULL;
  16311. }
  16312. d = ZeroMalloc(sizeof(TUBEDATA));
  16313. d->Data = Clone(data, size);
  16314. d->DataSize = size;
  16315. if (header != NULL)
  16316. {
  16317. d->Header = Clone(header, header_size);
  16318. d->HeaderSize = header_size;
  16319. }
  16320. else
  16321. {
  16322. d->Header = ZeroMalloc(header_size);
  16323. }
  16324. return d;
  16325. }
  16326. // Release of the tube data
  16327. void FreeTubeData(TUBEDATA *d)
  16328. {
  16329. // Validate arguments
  16330. if (d == NULL)
  16331. {
  16332. return;
  16333. }
  16334. Free(d->Data);
  16335. Free(d->Header);
  16336. Free(d);
  16337. }
  16338. // Release of the IP address list of the host
  16339. void FreeHostIPAddressList(LIST *o)
  16340. {
  16341. UINT i;
  16342. // Validate arguments
  16343. if (o == NULL)
  16344. {
  16345. return;
  16346. }
  16347. for (i = 0;i < LIST_NUM(o);i++)
  16348. {
  16349. IP *ip = LIST_DATA(o, i);
  16350. Free(ip);
  16351. }
  16352. ReleaseList(o);
  16353. }
  16354. // Get whether the specified IP address is held by this host
  16355. bool IsMyIPAddress(IP *ip)
  16356. {
  16357. LIST *o;
  16358. UINT i;
  16359. bool ret = false;
  16360. // Validate arguments
  16361. if (ip == NULL)
  16362. {
  16363. return false;
  16364. }
  16365. o = GetHostIPAddressList();
  16366. for (i = 0;i < LIST_NUM(o);i++)
  16367. {
  16368. IP *a = LIST_DATA(o, i);
  16369. if (CmpIpAddr(ip, a) == 0)
  16370. {
  16371. ret = true;
  16372. break;
  16373. }
  16374. }
  16375. FreeHostIPAddressList(o);
  16376. return ret;
  16377. }
  16378. // Add the IP address to the list
  16379. void AddHostIPAddressToList(LIST *o, IP *ip)
  16380. {
  16381. IP *r;
  16382. // Validate arguments
  16383. if (o == NULL || ip == NULL)
  16384. {
  16385. return;
  16386. }
  16387. r = Search(o, ip);
  16388. if (r != NULL)
  16389. {
  16390. return;
  16391. }
  16392. Insert(o, Clone(ip, sizeof(IP)));
  16393. }
  16394. // Comparison of the IP address list items
  16395. int CmpIpAddressList(void *p1, void *p2)
  16396. {
  16397. IP *ip1, *ip2;
  16398. UINT r;
  16399. // Validate arguments
  16400. if (p1 == NULL || p2 == NULL)
  16401. {
  16402. return 0;
  16403. }
  16404. ip1 = *(IP **)p1;
  16405. ip2 = *(IP **)p2;
  16406. if (ip1 == NULL || ip2 == NULL)
  16407. {
  16408. return 0;
  16409. }
  16410. // IPv4 < IPv6
  16411. r = COMPARE_RET(IsIP6(ip1), IsIP6(ip2));
  16412. if (r != 0)
  16413. {
  16414. return r;
  16415. }
  16416. // any > specified IP
  16417. if (IsZeroIP(ip1) && IsZeroIP(ip2) == false)
  16418. {
  16419. return 1;
  16420. }
  16421. if (IsZeroIP(ip1) == false && IsZeroIP(ip2))
  16422. {
  16423. return -1;
  16424. }
  16425. // local > others
  16426. if (IsLocalHostIP(ip1) && IsLocalHostIP(ip2) == false)
  16427. {
  16428. return 1;
  16429. }
  16430. if (IsLocalHostIP(ip1) == false && IsLocalHostIP(ip2))
  16431. {
  16432. return -1;
  16433. }
  16434. // ip address
  16435. r = CmpIpAddr(ip1, ip2);
  16436. if (r != 0)
  16437. {
  16438. return r;
  16439. }
  16440. // interface index
  16441. if (IsIP6(ip1))
  16442. {
  16443. r = COMPARE_RET(ip1->ipv6_scope_id, ip2->ipv6_scope_id);
  16444. }
  16445. else
  16446. {
  16447. r = 0;
  16448. }
  16449. return r;
  16450. }
  16451. // Get the IP address list hash of the host
  16452. UINT64 GetHostIPAddressListHash()
  16453. {
  16454. UINT i;
  16455. LIST *o;
  16456. BUF *buf = NewBuf();
  16457. UCHAR hash[SHA1_SIZE];
  16458. UINT64 ret = 0;
  16459. o = GetHostIPAddressList();
  16460. if (o != NULL)
  16461. {
  16462. for (i = 0;i < LIST_NUM(o);i++)
  16463. {
  16464. IP *ip = LIST_DATA(o, i);
  16465. char tmp[128];
  16466. Zero(tmp, sizeof(tmp));
  16467. IPToStr(tmp, sizeof(tmp), ip);
  16468. WriteBufStr(buf, tmp);
  16469. }
  16470. FreeHostIPAddressList(o);
  16471. }
  16472. WriteBufStr(buf, "test");
  16473. HashSha1(hash, buf->Buf, buf->Size);
  16474. FreeBuf(buf);
  16475. Copy(&ret, hash, sizeof(UINT64));
  16476. ret = Endian64(ret);
  16477. return ret;
  16478. }
  16479. // Get the IP address list of the host (using cache)
  16480. LIST *GetHostIPAddressList()
  16481. {
  16482. LIST *o = NULL;
  16483. if (host_ip_address_list_cache_lock == NULL)
  16484. {
  16485. return GetHostIPAddressListInternal();
  16486. }
  16487. Lock(host_ip_address_list_cache_lock);
  16488. {
  16489. UINT64 now = Tick64();
  16490. if (host_ip_address_list_cache_last == 0 ||
  16491. ((host_ip_address_list_cache_last + (UINT64)HOST_IP_ADDRESS_LIST_CACHE) < now) ||
  16492. host_ip_address_cache == NULL)
  16493. {
  16494. if (host_ip_address_cache != NULL)
  16495. {
  16496. FreeHostIPAddressList(host_ip_address_cache);
  16497. }
  16498. host_ip_address_cache = GetHostIPAddressListInternal();
  16499. host_ip_address_list_cache_last = now;
  16500. }
  16501. o = CloneIPAddressList(host_ip_address_cache);
  16502. }
  16503. Unlock(host_ip_address_list_cache_lock);
  16504. if (o == NULL)
  16505. {
  16506. o = GetHostIPAddressListInternal();
  16507. }
  16508. return o;
  16509. }
  16510. // Copy of the IP address list
  16511. LIST *CloneIPAddressList(LIST *o)
  16512. {
  16513. LIST *ret;
  16514. UINT i;
  16515. // Validate arguments
  16516. if (o == NULL)
  16517. {
  16518. return NULL;
  16519. }
  16520. ret = NewListFast(CmpIpAddressList);
  16521. for (i = 0;i < LIST_NUM(o);i++)
  16522. {
  16523. IP *ip = LIST_DATA(o, i);
  16524. if (ip != NULL)
  16525. {
  16526. ip = Clone(ip, sizeof(IP));
  16527. Add(ret, ip);
  16528. }
  16529. }
  16530. return ret;
  16531. }
  16532. // Get an IP address list of the host
  16533. LIST *GetHostIPAddressListInternal()
  16534. {
  16535. char hostname[MAX_SIZE];
  16536. LIST *o;
  16537. IP any6, any4;
  16538. IP local6, local4;
  16539. bool is_v6_supported = IsIPv6Supported();
  16540. GetLocalHostIP4(&local4);
  16541. GetLocalHostIP6(&local6);
  16542. ZeroIP4(&any4);
  16543. ZeroIP6(&any6);
  16544. Zero(hostname, sizeof(hostname));
  16545. gethostname(hostname, sizeof(hostname));
  16546. o = NewListFast(CmpIpAddressList);
  16547. // any
  16548. AddHostIPAddressToList(o, &any4);
  16549. if (is_v6_supported)
  16550. {
  16551. AddHostIPAddressToList(o, &any6);
  16552. }
  16553. // localhost
  16554. AddHostIPAddressToList(o, &local4);
  16555. if (is_v6_supported)
  16556. {
  16557. AddHostIPAddressToList(o, &local6);
  16558. }
  16559. #ifndef MAYAQUA_SUPPORTS_GETIFADDRS
  16560. // IPv4
  16561. if (true)
  16562. {
  16563. struct sockaddr_in in;
  16564. struct in_addr addr;
  16565. struct addrinfo hint;
  16566. struct addrinfo *info;
  16567. // Debug("***** GetHostIPAddressListInternal IPv4 Begin *****\n");
  16568. Zero(&hint, sizeof(hint));
  16569. hint.ai_family = AF_INET;
  16570. hint.ai_socktype = SOCK_DGRAM;
  16571. hint.ai_protocol = IPPROTO_UDP;
  16572. info = NULL;
  16573. if (getaddrinfo(hostname, NULL, &hint, &info) == 0)
  16574. {
  16575. if (info->ai_family == AF_INET)
  16576. {
  16577. struct addrinfo *current = info;
  16578. while (current != NULL)
  16579. {
  16580. IP ip;
  16581. Copy(&in, current->ai_addr, sizeof(in));
  16582. Copy(&addr, &in.sin_addr, sizeof(addr));
  16583. InAddrToIP(&ip, &addr);
  16584. AddHostIPAddressToList(o, &ip);
  16585. // Debug("%r\n", &ip);
  16586. current = current->ai_next;
  16587. }
  16588. }
  16589. freeaddrinfo(info);
  16590. }
  16591. // Debug("***** GetHostIPAddressListInternal IPv4 End *****\n");
  16592. }
  16593. #ifndef UNIX_LINUX
  16594. // IPv6
  16595. if (is_v6_supported)
  16596. {
  16597. struct sockaddr_in6 in;
  16598. struct in6_addr addr;
  16599. struct addrinfo hint;
  16600. struct addrinfo *info;
  16601. Zero(&hint, sizeof(hint));
  16602. hint.ai_family = AF_INET6;
  16603. hint.ai_socktype = SOCK_DGRAM;
  16604. hint.ai_protocol = IPPROTO_UDP;
  16605. info = NULL;
  16606. // Debug("***** GetHostIPAddressListInternal IPv6 Begin *****\n");
  16607. if (getaddrinfo(hostname, NULL, &hint, &info) == 0)
  16608. {
  16609. if (info->ai_family == AF_INET6)
  16610. {
  16611. struct addrinfo *current = info;
  16612. while (current != NULL)
  16613. {
  16614. IP ip;
  16615. Copy(&in, current->ai_addr, sizeof(in));
  16616. Copy(&addr, &in.sin6_addr, sizeof(addr));
  16617. InAddrToIP6(&ip, &addr);
  16618. ip.ipv6_scope_id = in.sin6_scope_id;
  16619. AddHostIPAddressToList(o, &ip);
  16620. // Debug("%r\n", &ip);
  16621. current = current->ai_next;
  16622. }
  16623. }
  16624. freeaddrinfo(info);
  16625. }
  16626. // Debug("***** GetHostIPAddressListInternal IPv6 End *****\n");
  16627. }
  16628. #endif // UNIX_LINUX
  16629. #endif // MAYAQUA_SUPPORTS_GETIFADDRS
  16630. #ifdef MAYAQUA_SUPPORTS_GETIFADDRS
  16631. // If the getifaddrs is available, use this
  16632. if (true)
  16633. {
  16634. struct ifaddrs *aa = NULL;
  16635. if (getifaddrs(&aa) == 0)
  16636. {
  16637. struct ifaddrs *a = aa;
  16638. while (a != NULL)
  16639. {
  16640. if (a->ifa_addr != NULL)
  16641. {
  16642. struct sockaddr *addr = a->ifa_addr;
  16643. if (addr->sa_family == AF_INET)
  16644. {
  16645. IP ip;
  16646. struct sockaddr_in *d = (struct sockaddr_in *)addr;
  16647. struct in_addr *addr = &d->sin_addr;
  16648. InAddrToIP(&ip, addr);
  16649. AddHostIPAddressToList(o, &ip);
  16650. }
  16651. else if (addr->sa_family == AF_INET6)
  16652. {
  16653. IP ip;
  16654. struct sockaddr_in6 *d = (struct sockaddr_in6 *)addr;
  16655. UINT scope_id = d->sin6_scope_id;
  16656. struct in6_addr *addr = &d->sin6_addr;
  16657. InAddrToIP6(&ip, addr);
  16658. ip.ipv6_scope_id = scope_id;
  16659. AddHostIPAddressToList(o, &ip);
  16660. }
  16661. }
  16662. a = a->ifa_next;
  16663. }
  16664. freeifaddrs(aa);
  16665. }
  16666. }
  16667. #endif // MAYAQUA_SUPPORTS_GETIFADDRS
  16668. return o;
  16669. }
  16670. // Get whether the UDP listener opens the specified port
  16671. bool IsUdpPortOpened(UDPLISTENER *u, IP *server_ip, UINT port)
  16672. {
  16673. UINT i;
  16674. // Validate arguments
  16675. if (u == NULL || port == 0)
  16676. {
  16677. return false;
  16678. }
  16679. if (server_ip != NULL)
  16680. {
  16681. for (i = 0;i < LIST_NUM(u->SockList);i++)
  16682. {
  16683. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, i);
  16684. if (us->Sock != NULL && us->HasError == false)
  16685. {
  16686. if (us->Port == port)
  16687. {
  16688. if (CmpIpAddr(server_ip, &us->IpAddress) == 0)
  16689. {
  16690. return true;
  16691. }
  16692. }
  16693. }
  16694. }
  16695. }
  16696. for (i = 0;i < LIST_NUM(u->SockList);i++)
  16697. {
  16698. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, i);
  16699. if (us->Sock != NULL && us->HasError == false)
  16700. {
  16701. if (us->Port == port)
  16702. {
  16703. if (IsZeroIP(&us->IpAddress))
  16704. {
  16705. return true;
  16706. }
  16707. }
  16708. }
  16709. }
  16710. return false;
  16711. }
  16712. // IP address acquisition thread
  16713. void QueryIpThreadMain(THREAD *thread, void *param)
  16714. {
  16715. QUERYIPTHREAD *t = (QUERYIPTHREAD *)param;
  16716. // Validate arguments
  16717. if (thread == NULL || param == NULL)
  16718. {
  16719. return;
  16720. }
  16721. while (t->Halt == false)
  16722. {
  16723. UINT next_wait_time = 0;
  16724. IP ip;
  16725. bool ok = false;
  16726. if (GetIP4Ex(&ip, t->Hostname, 5000, &t->Halt))
  16727. {
  16728. if (IsZeroIP(&ip) == false)
  16729. {
  16730. Lock(t->Lock);
  16731. {
  16732. Copy(&t->Ip, &ip, sizeof(IP));
  16733. }
  16734. Unlock(t->Lock);
  16735. ok = true;
  16736. }
  16737. }
  16738. if (ok == false)
  16739. {
  16740. next_wait_time = t->IntervalLastNg;
  16741. }
  16742. else
  16743. {
  16744. next_wait_time = t->IntervalLastOk;
  16745. }
  16746. if (t->Halt)
  16747. {
  16748. break;
  16749. }
  16750. Wait(t->HaltEvent, next_wait_time);
  16751. }
  16752. }
  16753. // Creating an IP address acquisition thread
  16754. QUERYIPTHREAD *NewQueryIpThread(char *hostname, UINT interval_last_ok, UINT interval_last_ng)
  16755. {
  16756. QUERYIPTHREAD *t;
  16757. t = ZeroMalloc(sizeof(QUERYIPTHREAD));
  16758. t->HaltEvent = NewEvent();
  16759. t->Lock = NewLock();
  16760. StrCpy(t->Hostname, sizeof(t->Hostname), hostname);
  16761. t->IntervalLastOk = interval_last_ok;
  16762. t->IntervalLastNg = interval_last_ng;
  16763. t->Thread = NewThread(QueryIpThreadMain, t);
  16764. return t;
  16765. }
  16766. // Get the results of the IP address acquisition thread
  16767. bool GetQueryIpThreadResult(QUERYIPTHREAD *t, IP *ip)
  16768. {
  16769. bool ret = false;
  16770. Zero(ip, sizeof(IP));
  16771. // Validate arguments
  16772. if (t == NULL || ip == NULL)
  16773. {
  16774. return false;
  16775. }
  16776. Lock(t->Lock);
  16777. if (IsZero(&t->Ip, sizeof(IP)))
  16778. {
  16779. ret = false;
  16780. }
  16781. else
  16782. {
  16783. Copy(ip, &t->Ip, sizeof(IP));
  16784. }
  16785. Unlock(t->Lock);
  16786. return ret;
  16787. }
  16788. // Release of the IP address acquisition thread
  16789. void FreeQueryIpThread(QUERYIPTHREAD *t)
  16790. {
  16791. // Validate arguments
  16792. if (t == NULL)
  16793. {
  16794. return;
  16795. }
  16796. t->Halt = true;
  16797. Set(t->HaltEvent);
  16798. WaitThread(t->Thread, INFINITE);
  16799. ReleaseThread(t->Thread);
  16800. ReleaseEvent(t->HaltEvent);
  16801. DeleteLock(t->Lock);
  16802. Free(t);
  16803. }
  16804. // Get a public port list which is known by UDP listener
  16805. void UdpListenerGetPublicPortList(UDPLISTENER *u, char *dst, UINT size)
  16806. {
  16807. UINT k;
  16808. // Validate arguments
  16809. ClearStr(dst, size);
  16810. if (u == NULL || dst == NULL)
  16811. {
  16812. return;
  16813. }
  16814. LockList(u->PortList);
  16815. {
  16816. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16817. {
  16818. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  16819. if (us->PublicPort != 0)
  16820. {
  16821. char tmp[64];
  16822. ToStr(tmp, us->PublicPort);
  16823. StrCat(dst, size, tmp);
  16824. StrCat(dst, size, " ");
  16825. }
  16826. }
  16827. }
  16828. UnlockList(u->PortList);
  16829. Trim(dst);
  16830. }
  16831. // UDP listener thread
  16832. void UdpListenerThread(THREAD *thread, void *param)
  16833. {
  16834. UDPLISTENER *u = (UDPLISTENER *)param;
  16835. UINT i, j, k;
  16836. UINT buf_size = 65536;
  16837. void *buf;
  16838. bool cont_flag;
  16839. BUF *ip_list_buf = NewBuf();
  16840. // Validate arguments
  16841. if (thread == NULL || param == NULL)
  16842. {
  16843. return;
  16844. }
  16845. buf = Malloc(buf_size);
  16846. // Initializing the socket list
  16847. u->SockList = NewList(NULL);
  16848. u->LastCheckTick = 0;
  16849. // u->PollMyIpAndPort = true;
  16850. // Main loop
  16851. while (u->Halt == false)
  16852. {
  16853. LIST *recv_list;
  16854. UINT64 now = Tick64();
  16855. UINT interval;
  16856. bool stage_changed = false;
  16857. IP nat_t_ip;
  16858. Zero(&nat_t_ip, sizeof(nat_t_ip));
  16859. if (u->LastCheckTick == 0 || (now >= (u->LastCheckTick + UDPLISTENER_CHECK_INTERVAL)))
  16860. {
  16861. LIST *iplist;
  16862. LIST *del_us_list = NewListFast(NULL);
  16863. BUF *ip_list_buf_new = NewBuf();
  16864. u->LastCheckTick = now;
  16865. // Obtain an IP address list
  16866. iplist = GetHostIPAddressList();
  16867. LockList(u->PortList);
  16868. {
  16869. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16870. {
  16871. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  16872. us->Mark = false;
  16873. }
  16874. // If the combination of the IP address and the port number doesn't exist in the list, add it to the list
  16875. for (i = 0;i < LIST_NUM(iplist);i++)
  16876. {
  16877. IP *ip = LIST_DATA(iplist, i);
  16878. WriteBuf(ip_list_buf_new, ip, sizeof(IP));
  16879. for (j = 0;j < LIST_NUM(u->PortList);j++)
  16880. {
  16881. UINT k;
  16882. UINT *port = LIST_DATA(u->PortList, j);
  16883. bool existing = false;
  16884. if (IsZeroIP(ip) && (IS_SPECIAL_PORT(*port)))
  16885. {
  16886. continue;
  16887. }
  16888. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16889. {
  16890. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  16891. if (CmpIpAddr(&us->IpAddress, ip) == 0 && us->Port == *port)
  16892. {
  16893. existing = true;
  16894. us->Mark = true;
  16895. break;
  16896. }
  16897. }
  16898. if (existing == false)
  16899. {
  16900. UDPLISTENER_SOCK *us = ZeroMalloc(sizeof(UDPLISTENER_SOCK));
  16901. Copy(&us->IpAddress, ip, sizeof(IP));
  16902. us->Port = *port;
  16903. us->Mark = true;
  16904. Add(u->SockList, us);
  16905. }
  16906. }
  16907. }
  16908. // If any errors suspected or the combination of IP address and port number
  16909. // has been regarded to delete already, delete it
  16910. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16911. {
  16912. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  16913. if (us->Mark == false || us->HasError)
  16914. {
  16915. Debug("mark=%u error=%u\n", us->Mark, us->HasError);
  16916. Add(del_us_list, us);
  16917. }
  16918. }
  16919. for (i = 0;i < LIST_NUM(del_us_list);i++)
  16920. {
  16921. UDPLISTENER_SOCK *us = LIST_DATA(del_us_list, i);
  16922. char ipstr[MAX_SIZE];
  16923. IPToStr(ipstr, sizeof(ipstr), &us->IpAddress);
  16924. Debug("Closed UDP Port %u at %s.\n", us->Port, ipstr);
  16925. Delete(u->SockList, us);
  16926. if (us->Sock != NULL)
  16927. {
  16928. Disconnect(us->Sock);
  16929. ReleaseSock(us->Sock);
  16930. }
  16931. Free(us);
  16932. }
  16933. }
  16934. UnlockList(u->PortList);
  16935. // Open the UDP sockets which is not opend yet
  16936. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16937. {
  16938. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  16939. if (us->Sock == NULL)
  16940. {
  16941. char ipstr[MAX_SIZE];
  16942. IPToStr(ipstr, sizeof(ipstr), &us->IpAddress);
  16943. if (us->ErrorDebugDisplayed == false)
  16944. {
  16945. Debug("Opening UDP Port %u at %s ...", us->Port, ipstr);
  16946. }
  16947. us->Sock = NewUDPEx2(us->Port, IsIP6(&us->IpAddress), &us->IpAddress);
  16948. if (us->Sock != NULL)
  16949. {
  16950. if (us->ErrorDebugDisplayed == false)
  16951. {
  16952. Debug("Ok.\n");
  16953. }
  16954. else
  16955. {
  16956. Debug("Opening UDP Port %u at %s ...", us->Port, ipstr);
  16957. Debug("Ok.\n");
  16958. }
  16959. JoinSockToSockEvent(us->Sock, u->Event);
  16960. us->ErrorDebugDisplayed = false;
  16961. }
  16962. else
  16963. {
  16964. if (us->ErrorDebugDisplayed == false)
  16965. {
  16966. Debug("Error.\n");
  16967. }
  16968. us->ErrorDebugDisplayed = true;
  16969. }
  16970. }
  16971. }
  16972. FreeHostIPAddressList(iplist);
  16973. ReleaseList(del_us_list);
  16974. if (CompareBuf(ip_list_buf, ip_list_buf_new) == false)
  16975. {
  16976. u->HostIPAddressListChanged = true;
  16977. }
  16978. FreeBuf(ip_list_buf);
  16979. ip_list_buf = ip_list_buf_new;
  16980. }
  16981. LABEL_RESTART:
  16982. stage_changed = false;
  16983. recv_list = NewListFast(NULL);
  16984. if (u->PollMyIpAndPort)
  16985. {
  16986. {
  16987. // Create a thread to get a NAT-T IP address if necessary
  16988. if (u->GetNatTIpThread == NULL)
  16989. {
  16990. char natt_hostname[MAX_SIZE];
  16991. RUDPGetRegisterHostNameByIP(natt_hostname, sizeof(natt_hostname), NULL);
  16992. u->GetNatTIpThread = NewQueryIpThread(natt_hostname, QUERYIPTHREAD_INTERVAL_LAST_OK, QUERYIPTHREAD_INTERVAL_LAST_NG);
  16993. }
  16994. GetQueryIpThreadResult(u->GetNatTIpThread, &nat_t_ip);
  16995. }
  16996. }
  16997. // Receive the data that is arriving at the socket
  16998. for (k = 0;k < LIST_NUM(u->SockList);k++)
  16999. {
  17000. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, k);
  17001. if (us->Sock != NULL)
  17002. {
  17003. UINT num_ignore_errors = 0;
  17004. if (u->PollMyIpAndPort && IsIP4(&us->IpAddress))
  17005. {
  17006. if (us->NextMyIpAndPortPollTick == 0 || us->NextMyIpAndPortPollTick <= now)
  17007. {
  17008. // Examine the self IP address and the self port number by using NAT-T server
  17009. us->NextMyIpAndPortPollTick = now + (UINT64)GenRandInterval(UDP_NAT_T_NAT_STATUS_CHECK_INTERVAL_MIN, UDP_NAT_T_NAT_STATUS_CHECK_INTERVAL_MAX);
  17010. if (IsZeroIP(&nat_t_ip) == false
  17011. )
  17012. {
  17013. UCHAR c = 'A';
  17014. SendTo(us->Sock, &nat_t_ip, UDP_NAT_T_PORT, &c, 1);
  17015. }
  17016. }
  17017. }
  17018. while (true)
  17019. {
  17020. IP src_addr;
  17021. UINT src_port;
  17022. UDPPACKET *p;
  17023. UINT size = RecvFrom(us->Sock, &src_addr, &src_port, buf, buf_size);
  17024. if (size == 0)
  17025. {
  17026. // Socket failure
  17027. if (us->Sock->IgnoreRecvErr == false)
  17028. {
  17029. LABEL_FATAL_ERROR:
  17030. Debug("RecvFrom has Error.\n");
  17031. us->HasError = true;
  17032. }
  17033. else
  17034. {
  17035. if ((num_ignore_errors++) >= MAX_NUM_IGNORE_ERRORS)
  17036. {
  17037. goto LABEL_FATAL_ERROR;
  17038. }
  17039. }
  17040. break;
  17041. }
  17042. else if (size == SOCK_LATER)
  17043. {
  17044. // No packet
  17045. break;
  17046. }
  17047. //Debug("UDP %u\n", size);
  17048. if (src_port == UDP_NAT_T_PORT && CmpIpAddr(&src_addr, &nat_t_ip) == 0)
  17049. {
  17050. // Receive a packet in which the IP address and the port number are written from the NAT-T server
  17051. if (size >= 8)
  17052. {
  17053. IP my_ip;
  17054. UINT my_port;
  17055. if (RUDPParseIPAndPortStr(buf, size, &my_ip, &my_port))
  17056. {
  17057. Copy(&us->PublicIpAddress, &my_ip, sizeof(IP));
  17058. us->PublicPort = my_port;
  17059. }
  17060. }
  17061. }
  17062. else
  17063. {
  17064. // Receive a regular packet
  17065. p = NewUdpPacket(&src_addr, src_port, &us->Sock->LocalIP, us->Sock->LocalPort,
  17066. Clone(buf, size), size);
  17067. if (p->SrcPort == MAKE_SPECIAL_PORT(52))
  17068. {
  17069. p->SrcPort = p->DestPort = MAKE_SPECIAL_PORT(50);
  17070. }
  17071. Add(recv_list, p);
  17072. }
  17073. stage_changed = true;
  17074. }
  17075. }
  17076. }
  17077. // Pass the received packet to the procedure
  17078. u->RecvProc(u, recv_list);
  17079. // Release the packet
  17080. for (i = 0;i < LIST_NUM(recv_list);i++)
  17081. {
  17082. UDPPACKET *p = LIST_DATA(recv_list, i);
  17083. FreeUdpPacket(p);
  17084. }
  17085. ReleaseList(recv_list);
  17086. cont_flag = true;
  17087. do
  17088. {
  17089. // When there are packets to be transmitted, transmit it
  17090. LockList(u->SendPacketList);
  17091. {
  17092. UDPLISTENER_SOCK *last_us = NULL;
  17093. IP last_src_ip;
  17094. UINT last_src_port;
  17095. Zero(&last_src_ip, sizeof(IP));
  17096. last_src_port = 0;
  17097. for (i = 0;i < LIST_NUM(u->SendPacketList);i++)
  17098. {
  17099. UDPPACKET *p = LIST_DATA(u->SendPacketList, i);
  17100. UDPLISTENER_SOCK *us;
  17101. if (last_us != NULL && last_src_port == p->SrcPort && CmpIpAddr(&last_src_ip, &p->SrcIP) == 0)
  17102. {
  17103. us = last_us;
  17104. }
  17105. else
  17106. {
  17107. // Search for a good interface for the transmission
  17108. us = DetermineUdpSocketForSending(u, p);
  17109. if (us != NULL)
  17110. {
  17111. last_us = us;
  17112. last_src_port = p->SrcPort;
  17113. Copy(&last_src_ip, &p->SrcIP, sizeof(IP));
  17114. }
  17115. }
  17116. if (us != NULL)
  17117. {
  17118. // Send
  17119. UINT ret = SendTo(us->Sock, &p->DstIP, p->DestPort, p->Data, p->Size);
  17120. if (ret == 0)
  17121. {
  17122. if (us->Sock->IgnoreSendErr == false)
  17123. {
  17124. // Socket failure
  17125. Debug("SendTo has Error.\n");
  17126. us->HasError = true;
  17127. last_us = NULL;
  17128. }
  17129. }
  17130. else
  17131. {
  17132. if (ret != SOCK_LATER)
  17133. {
  17134. stage_changed = true;
  17135. }
  17136. }
  17137. }
  17138. FreeUdpPacket(p);
  17139. }
  17140. DeleteAll(u->SendPacketList);
  17141. }
  17142. UnlockList(u->SendPacketList);
  17143. if (LIST_NUM(u->SendPacketList) == 0)
  17144. {
  17145. cont_flag = false;
  17146. }
  17147. }
  17148. while (cont_flag);
  17149. if (stage_changed && u->Halt == false)
  17150. {
  17151. goto LABEL_RESTART;
  17152. }
  17153. // Timing adjustment
  17154. interval = GetNextIntervalForInterrupt(u->Interrupts);
  17155. if (interval == INFINITE)
  17156. {
  17157. interval = UDPLISTENER_WAIT_INTERVAL;
  17158. }
  17159. else
  17160. {
  17161. interval = MIN(UDPLISTENER_WAIT_INTERVAL, interval);
  17162. }
  17163. if (interval >= 1)
  17164. {
  17165. WaitSockEvent(u->Event, interval);
  17166. }
  17167. }
  17168. if (u->GetNatTIpThread != NULL)
  17169. {
  17170. FreeQueryIpThread(u->GetNatTIpThread);
  17171. }
  17172. // Release of the socket list
  17173. for (i = 0;i < LIST_NUM(u->SockList);i++)
  17174. {
  17175. UDPLISTENER_SOCK *us = (UDPLISTENER_SOCK *)LIST_DATA(u->SockList, i);
  17176. Disconnect(us->Sock);
  17177. ReleaseSock(us->Sock);
  17178. Free(us);
  17179. }
  17180. ReleaseList(u->SockList);
  17181. FreeBuf(ip_list_buf);
  17182. Free(buf);
  17183. }
  17184. // Select the best UDP socket to be used for transmission
  17185. UDPLISTENER_SOCK *DetermineUdpSocketForSending(UDPLISTENER *u, UDPPACKET *p)
  17186. {
  17187. UINT i;
  17188. // Validate arguments
  17189. if (u == NULL || p == NULL)
  17190. {
  17191. return NULL;
  17192. }
  17193. for (i = 0;i < LIST_NUM(u->SockList);i++)
  17194. {
  17195. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, i);
  17196. if (us->Sock != NULL && us->HasError == false)
  17197. {
  17198. if (us->Port == p->SrcPort)
  17199. {
  17200. if (CmpIpAddr(&us->IpAddress, &p->SrcIP) == 0)
  17201. {
  17202. return us;
  17203. }
  17204. }
  17205. }
  17206. }
  17207. for (i = 0;i < LIST_NUM(u->SockList);i++)
  17208. {
  17209. UDPLISTENER_SOCK *us = LIST_DATA(u->SockList, i);
  17210. if (us->Sock != NULL && us->HasError == false)
  17211. {
  17212. if (us->Port == p->SrcPort)
  17213. {
  17214. if (IsZeroIP(&us->IpAddress))
  17215. {
  17216. if ((IsIP4(&p->DstIP) && IsIP4(&us->IpAddress)) ||
  17217. (IsIP6(&p->DstIP) && IsIP6(&us->IpAddress)))
  17218. {
  17219. return us;
  17220. }
  17221. }
  17222. }
  17223. }
  17224. }
  17225. return NULL;
  17226. }
  17227. // Release of the UDP packet
  17228. void FreeUdpPacket(UDPPACKET *p)
  17229. {
  17230. // Validate arguments
  17231. if (p == NULL)
  17232. {
  17233. return;
  17234. }
  17235. Free(p->Data);
  17236. Free(p);
  17237. }
  17238. // Create a new UDP packet
  17239. UDPPACKET *NewUdpPacket(IP *src_ip, UINT src_port, IP *dst_ip, UINT dst_port, void *data, UINT size)
  17240. {
  17241. UDPPACKET *p;
  17242. // Validate arguments
  17243. if (data == NULL || size == 0 || dst_ip == NULL || dst_port == 0)
  17244. {
  17245. return NULL;
  17246. }
  17247. p = ZeroMalloc(sizeof(UDPPACKET));
  17248. p->Data = data;
  17249. p->Size = size;
  17250. Copy(&p->SrcIP, src_ip, sizeof(IP));
  17251. p->SrcPort = src_port;
  17252. Copy(&p->DstIP, dst_ip, sizeof(IP));
  17253. p->DestPort = dst_port;
  17254. return p;
  17255. }
  17256. // Transmit the packets via UDP Listener
  17257. void UdpListenerSendPackets(UDPLISTENER *u, LIST *packet_list)
  17258. {
  17259. UINT num = 0;
  17260. // Validate arguments
  17261. if (u == NULL || packet_list == NULL)
  17262. {
  17263. return;
  17264. }
  17265. LockList(u->SendPacketList);
  17266. {
  17267. UINT i;
  17268. num = LIST_NUM(packet_list);
  17269. for (i = 0;i < LIST_NUM(packet_list);i++)
  17270. {
  17271. UDPPACKET *p = LIST_DATA(packet_list, i);
  17272. Add(u->SendPacketList, p);
  17273. }
  17274. }
  17275. UnlockList(u->SendPacketList);
  17276. if (num >= 1)
  17277. {
  17278. SetSockEvent(u->Event);
  17279. }
  17280. }
  17281. void UdpListenerSendPacket(UDPLISTENER *u, UDPPACKET *packet)
  17282. {
  17283. LIST *o;
  17284. // Validate arguments
  17285. if (u == NULL || packet == NULL)
  17286. {
  17287. return;
  17288. }
  17289. o = NewListFast(NULL);
  17290. Add(o, packet);
  17291. UdpListenerSendPackets(u, o);
  17292. ReleaseList(o);
  17293. }
  17294. // Creating a UDP listener
  17295. UDPLISTENER *NewUdpListener(UDPLISTENER_RECV_PROC *recv_proc, void *param)
  17296. {
  17297. UDPLISTENER *u;
  17298. // Validate arguments
  17299. if (recv_proc == NULL)
  17300. {
  17301. return NULL;
  17302. }
  17303. u = ZeroMalloc(sizeof(UDPLISTENER));
  17304. u->Param = param;
  17305. u->PortList = NewList(NULL);
  17306. u->Event = NewSockEvent();
  17307. u->RecvProc = recv_proc;
  17308. u->SendPacketList = NewList(NULL);
  17309. u->Interrupts = NewInterruptManager();
  17310. u->Thread = NewThread(UdpListenerThread, u);
  17311. return u;
  17312. }
  17313. // Release the UDP listener
  17314. void FreeUdpListener(UDPLISTENER *u)
  17315. {
  17316. UINT i;
  17317. // Validate arguments
  17318. if (u == NULL)
  17319. {
  17320. return;
  17321. }
  17322. u->Halt = true;
  17323. SetSockEvent(u->Event);
  17324. WaitThread(u->Thread, INFINITE);
  17325. ReleaseThread(u->Thread);
  17326. ReleaseSockEvent(u->Event);
  17327. ReleaseIntList(u->PortList);
  17328. for (i = 0;i < LIST_NUM(u->SendPacketList);i++)
  17329. {
  17330. UDPPACKET *p = LIST_DATA(u->SendPacketList, i);
  17331. FreeUdpPacket(p);
  17332. }
  17333. ReleaseList(u->SendPacketList);
  17334. FreeInterruptManager(u->Interrupts);
  17335. Free(u);
  17336. }
  17337. // Add the UDP port
  17338. void AddPortToUdpListener(UDPLISTENER *u, UINT port)
  17339. {
  17340. // Validate arguments
  17341. if (u == NULL || port == 0)
  17342. {
  17343. return;
  17344. }
  17345. LockList(u->PortList);
  17346. {
  17347. AddIntDistinct(u->PortList, port);
  17348. }
  17349. UnlockList(u->PortList);
  17350. SetSockEvent(u->Event);
  17351. }
  17352. // Get the port list
  17353. UINT GetUdpListenerPortList(UDPLISTENER *u, UINT **port_list)
  17354. {
  17355. UINT num_ports;
  17356. // Validate arguments
  17357. if (u == NULL || port_list == NULL)
  17358. {
  17359. return 0;
  17360. }
  17361. LockList(u->PortList);
  17362. {
  17363. UINT *ports;
  17364. UINT i;
  17365. num_ports = LIST_NUM(u->PortList);
  17366. ports = ZeroMalloc(sizeof(UINT) * num_ports);
  17367. for (i = 0;i < num_ports;i++)
  17368. {
  17369. ports[i] = *((UINT *)(LIST_DATA(u->PortList, i)));
  17370. }
  17371. *port_list = ports;
  17372. }
  17373. UnlockList(u->PortList);
  17374. return num_ports;
  17375. }
  17376. // Dekete all the UDP ports
  17377. void DeleteAllPortFromUdpListener(UDPLISTENER *u)
  17378. {
  17379. // Validate arguments
  17380. if (u == NULL)
  17381. {
  17382. return;
  17383. }
  17384. LockList(u->PortList);
  17385. {
  17386. UINT num_ports = LIST_NUM(u->PortList);
  17387. UINT *ports = ZeroMalloc(sizeof(UINT) * num_ports);
  17388. UINT i;
  17389. for (i = 0;i < num_ports;i++)
  17390. {
  17391. ports[i] = *((UINT *)(LIST_DATA(u->PortList, i)));
  17392. }
  17393. for (i = 0;i < num_ports;i++)
  17394. {
  17395. UINT port = ports[i];
  17396. DelInt(u->PortList, port);
  17397. }
  17398. Free(ports);
  17399. }
  17400. UnlockList(u->PortList);
  17401. SetSockEvent(u->Event);
  17402. }
  17403. // Delete the UDP port
  17404. void DeletePortFromUdpListener(UDPLISTENER *u, UINT port)
  17405. {
  17406. // Validate arguments
  17407. if (u == NULL || port == 0)
  17408. {
  17409. return;
  17410. }
  17411. LockList(u->PortList);
  17412. {
  17413. DelInt(u->PortList, port);
  17414. }
  17415. UnlockList(u->PortList);
  17416. SetSockEvent(u->Event);
  17417. }
  17418. // Sort function of the interrupt management list
  17419. int CmpInterruptManagerTickList(void *p1, void *p2)
  17420. {
  17421. UINT64 *v1, *v2;
  17422. if (p1 == NULL || p2 == NULL)
  17423. {
  17424. return 0;
  17425. }
  17426. v1 = *(UINT64 **)p1;
  17427. v2 = *(UINT64 **)p2;
  17428. if (v1 == NULL || v2 == NULL)
  17429. {
  17430. return 0;
  17431. }
  17432. if (*v1 > *v2)
  17433. {
  17434. return 1;
  17435. }
  17436. else if (*v1 < *v2)
  17437. {
  17438. return -1;
  17439. }
  17440. else
  17441. {
  17442. return 0;
  17443. }
  17444. }
  17445. // Initialization of the interrupt management
  17446. INTERRUPT_MANAGER *NewInterruptManager()
  17447. {
  17448. INTERRUPT_MANAGER *m = ZeroMalloc(sizeof(INTERRUPT_MANAGER));
  17449. m->TickList = NewList(CmpInterruptManagerTickList);
  17450. return m;
  17451. }
  17452. // Release of the interrupt management
  17453. void FreeInterruptManager(INTERRUPT_MANAGER *m)
  17454. {
  17455. UINT i;
  17456. // Validate arguments
  17457. if (m == NULL)
  17458. {
  17459. return;
  17460. }
  17461. for (i = 0;i < LIST_NUM(m->TickList);i++)
  17462. {
  17463. UINT64 *v = LIST_DATA(m->TickList, i);
  17464. Free(v);
  17465. }
  17466. ReleaseList(m->TickList);
  17467. Free(m);
  17468. }
  17469. // Add a number to the interrupt management
  17470. void AddInterrupt(INTERRUPT_MANAGER *m, UINT64 tick)
  17471. {
  17472. // Validate arguments
  17473. if (tick == 0)
  17474. {
  17475. return;
  17476. }
  17477. LockList(m->TickList);
  17478. {
  17479. if (Search(m->TickList, &tick) == NULL)
  17480. {
  17481. Insert(m->TickList, Clone(&tick, sizeof(UINT64)));
  17482. }
  17483. }
  17484. UnlockList(m->TickList);
  17485. }
  17486. // Get the interval to the next calling
  17487. UINT GetNextIntervalForInterrupt(INTERRUPT_MANAGER *m)
  17488. {
  17489. UINT ret = INFINITE;
  17490. UINT i;
  17491. LIST *o = NULL;
  17492. UINT64 now = Tick64();
  17493. // Validate arguments
  17494. if (m == NULL)
  17495. {
  17496. return 0;
  17497. }
  17498. LockList(m->TickList);
  17499. {
  17500. // Remove entries older than now already
  17501. for (i = 0;i < LIST_NUM(m->TickList);i++)
  17502. {
  17503. UINT64 *v = LIST_DATA(m->TickList, i);
  17504. if (now >= *v)
  17505. {
  17506. ret = 0;
  17507. if (o == NULL)
  17508. {
  17509. o = NewListFast(NULL);
  17510. }
  17511. Add(o, v);
  17512. }
  17513. else
  17514. {
  17515. break;
  17516. }
  17517. }
  17518. for (i = 0;i < LIST_NUM(o);i++)
  17519. {
  17520. UINT64 *v = LIST_DATA(o, i);
  17521. Free(v);
  17522. Delete(m->TickList, v);
  17523. }
  17524. if (o != NULL)
  17525. {
  17526. ReleaseList(o);
  17527. }
  17528. if (ret == INFINITE)
  17529. {
  17530. if (LIST_NUM(m->TickList) >= 1)
  17531. {
  17532. UINT64 *v = LIST_DATA(m->TickList, 0);
  17533. ret = (UINT)(*v - now);
  17534. }
  17535. }
  17536. }
  17537. UnlockList(m->TickList);
  17538. return ret;
  17539. }
  17540. // Let that the listening socket for the reverse socket to accept the new socket
  17541. void InjectNewReverseSocketToAccept(SOCK *listen_sock, SOCK *s, IP *client_ip, UINT client_port)
  17542. {
  17543. bool ok = false;
  17544. // Validate arguments
  17545. if (listen_sock == NULL || s == NULL)
  17546. {
  17547. return;
  17548. }
  17549. LockQueue(listen_sock->ReverseAcceptQueue);
  17550. {
  17551. if (listen_sock->CancelAccept == false && listen_sock->Disconnecting == false)
  17552. {
  17553. InsertQueue(listen_sock->ReverseAcceptQueue, s);
  17554. ok = true;
  17555. s->ServerMode = true;
  17556. s->IsReverseAcceptedSocket = true;
  17557. Copy(&s->RemoteIP, client_ip, sizeof(IP));
  17558. s->RemotePort = client_port;
  17559. }
  17560. }
  17561. UnlockQueue(listen_sock->ReverseAcceptQueue);
  17562. if (ok == false)
  17563. {
  17564. Disconnect(s);
  17565. ReleaseSock(s);
  17566. }
  17567. else
  17568. {
  17569. Set(listen_sock->ReverseAcceptEvent);
  17570. }
  17571. }
  17572. // Create a listening socket for the reverse socket
  17573. SOCK *ListenReverse()
  17574. {
  17575. SOCK *s = NewSock();
  17576. s->Type = SOCK_REVERSE_LISTEN;
  17577. s->ListenMode = true;
  17578. s->ReverseAcceptQueue = NewQueue();
  17579. s->ReverseAcceptEvent = NewEvent();
  17580. s->Connected = true;
  17581. return s;
  17582. }
  17583. // Accept on the reverse socket
  17584. SOCK *AcceptReverse(SOCK *s)
  17585. {
  17586. // Validate arguments
  17587. if (s == NULL || s->Type != SOCK_REVERSE_LISTEN || s->ListenMode == false)
  17588. {
  17589. return NULL;
  17590. }
  17591. while (true)
  17592. {
  17593. SOCK *ret;
  17594. if (s->Disconnecting || s->CancelAccept)
  17595. {
  17596. return NULL;
  17597. }
  17598. LockQueue(s->ReverseAcceptQueue);
  17599. {
  17600. ret = GetNext(s->ReverseAcceptQueue);
  17601. }
  17602. UnlockQueue(s->ReverseAcceptQueue);
  17603. if (ret != NULL)
  17604. {
  17605. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_AZURE);
  17606. return ret;
  17607. }
  17608. Wait(s->ReverseAcceptEvent, INFINITE);
  17609. }
  17610. }
  17611. // Start listening on the in-process socket
  17612. SOCK *ListenInProc()
  17613. {
  17614. SOCK *s = NewSock();
  17615. s->Type = SOCK_INPROC;
  17616. s->ListenMode = true;
  17617. s->InProcAcceptQueue = NewQueue();
  17618. s->InProcAcceptEvent = NewEvent();
  17619. s->Connected = true;
  17620. return s;
  17621. }
  17622. // Accept at the in-process socket
  17623. SOCK *AcceptInProc(SOCK *s)
  17624. {
  17625. // Validate arguments
  17626. if (s == NULL || s->Type != SOCK_INPROC || s->ListenMode == false)
  17627. {
  17628. return NULL;
  17629. }
  17630. while (true)
  17631. {
  17632. SOCK *ret;
  17633. if (s->Disconnecting || s->CancelAccept)
  17634. {
  17635. return NULL;
  17636. }
  17637. LockQueue(s->InProcAcceptQueue);
  17638. {
  17639. ret = GetNext(s->InProcAcceptQueue);
  17640. }
  17641. UnlockQueue(s->InProcAcceptQueue);
  17642. if (ret != NULL)
  17643. {
  17644. StrCpy(ret->UnderlayProtocol, sizeof(ret->UnderlayProtocol), SOCK_UNDERLAY_INPROC);
  17645. return ret;
  17646. }
  17647. Wait(s->InProcAcceptEvent, INFINITE);
  17648. }
  17649. }
  17650. // Connect by the in-process socket
  17651. SOCK *ConnectInProc(SOCK *listen_sock, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
  17652. {
  17653. SOCK *ss, *sc;
  17654. bool ok = false;
  17655. // Validate arguments
  17656. if (listen_sock == NULL || listen_sock->Type != SOCK_INPROC || listen_sock->ListenMode == false)
  17657. {
  17658. return NULL;
  17659. }
  17660. NewSocketPair(&sc, &ss, client_ip, client_port, server_ip, server_port);
  17661. LockQueue(listen_sock->InProcAcceptQueue);
  17662. {
  17663. if (listen_sock->CancelAccept == false && listen_sock->Disconnecting == false)
  17664. {
  17665. InsertQueue(listen_sock->InProcAcceptQueue, ss);
  17666. ok = true;
  17667. }
  17668. }
  17669. UnlockQueue(listen_sock->InProcAcceptQueue);
  17670. if (ok == false)
  17671. {
  17672. ReleaseSock(ss);
  17673. ReleaseSock(sc);
  17674. return NULL;
  17675. }
  17676. Set(listen_sock->InProcAcceptEvent);
  17677. return sc;
  17678. }
  17679. // Creating a new socket pair
  17680. void NewSocketPair(SOCK **client, SOCK **server, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
  17681. {
  17682. IP iptmp;
  17683. TUBE *t1, *t2;
  17684. SOCK *sc, *ss;
  17685. SOCK_EVENT *e1, *e2;
  17686. // Validate arguments
  17687. if (client == NULL || server == NULL)
  17688. {
  17689. return;
  17690. }
  17691. SetIP(&iptmp, 127, 0, 0, 1);
  17692. if (client_ip == NULL)
  17693. {
  17694. client_ip = &iptmp;
  17695. }
  17696. if (server_ip == NULL)
  17697. {
  17698. server_ip = &iptmp;
  17699. }
  17700. // Creating a tube
  17701. NewTubePair(&t1, &t2, 0); // t1: C -> S, t2: S -> C
  17702. // Creating a socket event
  17703. e1 = NewSockEvent();
  17704. e2 = NewSockEvent();
  17705. SetTubeSockEvent(t1, e1);
  17706. SetTubeSockEvent(t2, e2);
  17707. sc = NewInProcSocket(t1, t2);
  17708. ss = NewInProcSocket(t2, t1);
  17709. Copy(&sc->LocalIP, client_ip, sizeof(IP));
  17710. sc->LocalPort = client_port;
  17711. Copy(&sc->RemoteIP, server_ip, sizeof(IP));
  17712. sc->RemotePort = server_port;
  17713. Copy(&ss->LocalIP, server_ip, sizeof(IP));
  17714. ss->LocalPort = server_port;
  17715. Copy(&ss->RemoteIP, client_ip, sizeof(IP));
  17716. ss->RemotePort = client_port;
  17717. sc->Connected = true;
  17718. sc->ServerMode = false;
  17719. ss->Connected = true;
  17720. ss->ServerMode = true;
  17721. SetTimeout(sc, INFINITE);
  17722. SetTimeout(ss, INFINITE);
  17723. QuerySocketInformation(sc);
  17724. QuerySocketInformation(ss);
  17725. ReleaseSockEvent(e1);
  17726. ReleaseSockEvent(e2);
  17727. ReleaseTube(t1);
  17728. ReleaseTube(t2);
  17729. *client = sc;
  17730. *server = ss;
  17731. }
  17732. // Creating a new in-process socket
  17733. SOCK *NewInProcSocket(TUBE *tube_send, TUBE *tube_recv)
  17734. {
  17735. SOCK *s;
  17736. // Validate arguments
  17737. if (tube_recv == NULL || tube_send == NULL)
  17738. {
  17739. return NULL;
  17740. }
  17741. s = NewSock();
  17742. s->Type = SOCK_INPROC;
  17743. s->SendTube = tube_send;
  17744. s->RecvTube = tube_recv;
  17745. AddRef(tube_send->Ref);
  17746. AddRef(tube_recv->Ref);
  17747. s->InProcRecvFifo = NewFifo();
  17748. s->Connected = true;
  17749. return s;
  17750. }
  17751. // Transmission process for the in-process socket
  17752. UINT SendInProc(SOCK *sock, void *data, UINT size)
  17753. {
  17754. if (sock == NULL || sock->Type != SOCK_INPROC || sock->Disconnecting || sock->Connected == false)
  17755. {
  17756. return 0;
  17757. }
  17758. if (IsTubeConnected(sock->SendTube) == false)
  17759. {
  17760. return 0;
  17761. }
  17762. if (TubeSend(sock->SendTube, data, size, NULL) == false)
  17763. {
  17764. return 0;
  17765. }
  17766. return size;
  17767. }
  17768. // Receiving process for the in-process socket
  17769. UINT RecvInProc(SOCK *sock, void *data, UINT size)
  17770. {
  17771. FIFO *f;
  17772. UINT ret;
  17773. UINT timeout;
  17774. UINT64 giveup_time;
  17775. TUBEDATA *d = NULL;
  17776. if (sock == NULL || sock->Type != SOCK_INPROC || sock->Disconnecting || sock->Connected == false)
  17777. {
  17778. return 0;
  17779. }
  17780. if (IsTubeConnected(sock->SendTube) == false)
  17781. {
  17782. return 0;
  17783. }
  17784. f = sock->InProcRecvFifo;
  17785. if (f == NULL)
  17786. {
  17787. return 0;
  17788. }
  17789. // If there is data in the FIFO, return it immediately
  17790. ret = ReadFifo(f, data, size);
  17791. if (ret != 0)
  17792. {
  17793. return ret;
  17794. }
  17795. timeout = GetTimeout(sock);
  17796. giveup_time = Tick64() + (UINT)timeout;
  17797. // When there is no data in the FIFO, read the next data from the tube
  17798. d = NULL;
  17799. while (true)
  17800. {
  17801. UINT64 now = 0;
  17802. UINT interval;
  17803. if (sock->AsyncMode == false)
  17804. {
  17805. now = Tick64();
  17806. if (now >= giveup_time)
  17807. {
  17808. break;
  17809. }
  17810. }
  17811. d = TubeRecvAsync(sock->RecvTube);
  17812. if (d != NULL)
  17813. {
  17814. break;
  17815. }
  17816. if (IsTubeConnected(sock->RecvTube) == false)
  17817. {
  17818. break;
  17819. }
  17820. if (sock->AsyncMode)
  17821. {
  17822. break;
  17823. }
  17824. interval = (UINT)(giveup_time - now);
  17825. Wait(sock->RecvTube->Event, interval);
  17826. }
  17827. if (d == NULL)
  17828. {
  17829. if (IsTubeConnected(sock->RecvTube) == false)
  17830. {
  17831. return 0;
  17832. }
  17833. if (sock->AsyncMode == false)
  17834. {
  17835. // If a timeout occurs in synchronous mode, disconnect ir
  17836. Disconnect(sock);
  17837. return 0;
  17838. }
  17839. else
  17840. {
  17841. // If a timeout occurs in asynchronous mode, returns the blocking error
  17842. return SOCK_LATER;
  17843. }
  17844. }
  17845. else
  17846. {
  17847. // If the received data is larger than the requested size, write the rest to FIFO
  17848. if (d->DataSize > size)
  17849. {
  17850. WriteFifo(f, ((UCHAR *)d->Data) + size, d->DataSize - size);
  17851. ret = size;
  17852. }
  17853. else
  17854. {
  17855. ret = d->DataSize;
  17856. }
  17857. Copy(data, d->Data, ret);
  17858. FreeTubeData(d);
  17859. return ret;
  17860. }
  17861. }
  17862. // Wait for the arrival of data on multiple tubes
  17863. void WaitForTubes(TUBE **tubes, UINT num, UINT timeout)
  17864. {
  17865. // Validate arguments
  17866. if (num != 0 && tubes == NULL)
  17867. {
  17868. return;
  17869. }
  17870. if (timeout == 0)
  17871. {
  17872. return;
  17873. }
  17874. if (num == 0)
  17875. {
  17876. SleepThread(timeout);
  17877. return;
  17878. }
  17879. #ifdef OS_WIN32
  17880. Win32WaitForTubes(tubes, num, timeout);
  17881. #else // OS_WIN32
  17882. UnixWaitForTubes(tubes, num, timeout);
  17883. #endif // OS_WIN32
  17884. }
  17885. #ifdef OS_WIN32
  17886. void Win32WaitForTubes(TUBE **tubes, UINT num, UINT timeout)
  17887. {
  17888. HANDLE array[MAXIMUM_WAIT_OBJECTS];
  17889. UINT i;
  17890. Zero(array, sizeof(array));
  17891. for (i = 0;i < num;i++)
  17892. {
  17893. TUBE *t = tubes[i];
  17894. array[i] = t->Event->pData;
  17895. }
  17896. if (num == 1)
  17897. {
  17898. WaitForSingleObject(array[0], timeout);
  17899. }
  17900. else
  17901. {
  17902. WaitForMultipleObjects(num, array, false, timeout);
  17903. }
  17904. }
  17905. #else // OS_WIN32
  17906. void UnixWaitForTubes(TUBE **tubes, UINT num, UINT timeout)
  17907. {
  17908. int *fds;
  17909. UINT i;
  17910. char tmp[MAX_SIZE];
  17911. bool any_of_tubes_are_readable = false;
  17912. fds = ZeroMalloc(sizeof(int) * num);
  17913. for (i = 0;i < num;i++)
  17914. {
  17915. fds[i] = tubes[i]->SockEvent->pipe_read;
  17916. if (tubes[i]->SockEvent->current_pipe_data != 0)
  17917. {
  17918. any_of_tubes_are_readable = true;
  17919. }
  17920. }
  17921. if (any_of_tubes_are_readable == false)
  17922. {
  17923. UnixSelectInner(num, fds, 0, NULL, timeout);
  17924. }
  17925. for (i = 0;i < num;i++)
  17926. {
  17927. int fd = fds[i];
  17928. int readret;
  17929. tubes[i]->SockEvent->current_pipe_data = 0;
  17930. do
  17931. {
  17932. readret = read(fd, tmp, sizeof(tmp));
  17933. }
  17934. while (readret >= 1);
  17935. }
  17936. Free(fds);
  17937. }
  17938. #endif // OS_WIN32
  17939. // Creating a Tube Flush List
  17940. TUBE_FLUSH_LIST *NewTubeFlushList()
  17941. {
  17942. TUBE_FLUSH_LIST *f = ZeroMalloc(sizeof(TUBE_FLUSH_LIST));
  17943. f->List = NewListFast(NULL);
  17944. return f;
  17945. }
  17946. // Release of the Tube Flush List
  17947. void FreeTubeFlushList(TUBE_FLUSH_LIST *f)
  17948. {
  17949. UINT i;
  17950. // Validate arguments
  17951. if (f == NULL)
  17952. {
  17953. return;
  17954. }
  17955. for (i = 0;i < LIST_NUM(f->List);i++)
  17956. {
  17957. TUBE *t = LIST_DATA(f->List, i);
  17958. ReleaseTube(t);
  17959. }
  17960. ReleaseList(f->List);
  17961. Free(f);
  17962. }
  17963. // Add a Tube to the Tube Flush List
  17964. void AddTubeToFlushList(TUBE_FLUSH_LIST *f, TUBE *t)
  17965. {
  17966. // Validate arguments
  17967. if (f == NULL || t == NULL)
  17968. {
  17969. return;
  17970. }
  17971. if (t->IsInFlushList)
  17972. {
  17973. return;
  17974. }
  17975. if (IsInList(f->List, t) == false)
  17976. {
  17977. Add(f->List, t);
  17978. AddRef(t->Ref);
  17979. t->IsInFlushList = true;
  17980. }
  17981. }
  17982. // Flush the all tubes in the Tube Flush List
  17983. void FlushTubeFlushList(TUBE_FLUSH_LIST *f)
  17984. {
  17985. UINT i;
  17986. // Validate arguments
  17987. if (f == NULL)
  17988. {
  17989. return;
  17990. }
  17991. for (i = 0;i < LIST_NUM(f->List);i++)
  17992. {
  17993. TUBE *t = LIST_DATA(f->List, i);
  17994. TubeFlush(t);
  17995. t->IsInFlushList = false;
  17996. ReleaseTube(t);
  17997. }
  17998. DeleteAll(f->List);
  17999. }
  18000. // The server receives a PACK from the client
  18001. PACK *HttpServerRecv(SOCK *s)
  18002. {
  18003. BUF *b;
  18004. PACK *p;
  18005. HTTP_HEADER *h;
  18006. UINT size;
  18007. UCHAR *tmp;
  18008. HTTP_VALUE *v;
  18009. UINT num_noop = 0;
  18010. // Validate arguments
  18011. if (s == NULL)
  18012. {
  18013. return NULL;
  18014. }
  18015. START:
  18016. h = RecvHttpHeader(s);
  18017. if (h == NULL)
  18018. {
  18019. goto BAD_REQUEST;
  18020. }
  18021. if (StrCmpi(h->Method, "POST") != 0 ||
  18022. StrCmpi(h->Target, HTTP_VPN_TARGET) != 0 ||
  18023. StrCmpi(h->Version, "HTTP/1.1") != 0)
  18024. {
  18025. FreeHttpHeader(h);
  18026. goto BAD_REQUEST;
  18027. }
  18028. v = GetHttpValue(h, "Content-Type");
  18029. if (v == NULL || StrCmpi(v->Data, HTTP_CONTENT_TYPE2) != 0)
  18030. {
  18031. FreeHttpHeader(h);
  18032. goto BAD_REQUEST;
  18033. }
  18034. size = GetContentLength(h);
  18035. if (size == 0 || size > HTTP_PACK_MAX_SIZE)
  18036. {
  18037. FreeHttpHeader(h);
  18038. goto BAD_REQUEST;
  18039. }
  18040. tmp = MallocEx(size, true);
  18041. if (RecvAll(s, tmp, size, s->SecureMode) == false)
  18042. {
  18043. Free(tmp);
  18044. FreeHttpHeader(h);
  18045. return NULL;
  18046. }
  18047. b = NewBuf();
  18048. WriteBuf(b, tmp, size);
  18049. Free(tmp);
  18050. FreeHttpHeader(h);
  18051. SeekBuf(b, 0, 0);
  18052. p = BufToPack(b);
  18053. FreeBuf(b);
  18054. // Determine whether it's a NOOP
  18055. if (PackGetInt(p, "noop") != 0)
  18056. {
  18057. Debug("recv: noop\n");
  18058. FreePack(p);
  18059. p = PackError(0);
  18060. PackAddInt(p, "noop", 1);
  18061. if (HttpServerSend(s, p) == false)
  18062. {
  18063. FreePack(p);
  18064. return NULL;
  18065. }
  18066. FreePack(p);
  18067. num_noop++;
  18068. if (num_noop > MAX_NOOP_PER_SESSION)
  18069. {
  18070. return NULL;
  18071. }
  18072. goto START;
  18073. }
  18074. return p;
  18075. BAD_REQUEST:
  18076. // Return an error
  18077. return NULL;
  18078. }
  18079. // Store the error value into PACK
  18080. PACK *PackError(UINT error)
  18081. {
  18082. PACK *p;
  18083. p = NewPack();
  18084. PackAddInt(p, "error", error);
  18085. return p;
  18086. }
  18087. // Get the error value from PACK
  18088. UINT GetErrorFromPack(PACK *p)
  18089. {
  18090. // Validate arguments
  18091. if (p == NULL)
  18092. {
  18093. return 0;
  18094. }
  18095. return PackGetInt(p, "error");
  18096. }
  18097. // Client receives a PACK from the server
  18098. PACK *HttpClientRecv(SOCK *s)
  18099. {
  18100. BUF *b;
  18101. PACK *p;
  18102. HTTP_HEADER *h;
  18103. UINT size;
  18104. UCHAR *tmp;
  18105. HTTP_VALUE *v;
  18106. // Validate arguments
  18107. if (s == NULL)
  18108. {
  18109. return NULL;
  18110. }
  18111. h = RecvHttpHeader(s);
  18112. if (h == NULL)
  18113. {
  18114. return NULL;
  18115. }
  18116. if (StrCmpi(h->Method, "HTTP/1.1") != 0 ||
  18117. StrCmpi(h->Target, "200") != 0)
  18118. {
  18119. FreeHttpHeader(h);
  18120. return NULL;
  18121. }
  18122. v = GetHttpValue(h, "Content-Type");
  18123. if (v == NULL || StrCmpi(v->Data, HTTP_CONTENT_TYPE2) != 0)
  18124. {
  18125. FreeHttpHeader(h);
  18126. return NULL;
  18127. }
  18128. size = GetContentLength(h);
  18129. if (size == 0 || size > MAX_PACK_SIZE)
  18130. {
  18131. FreeHttpHeader(h);
  18132. return NULL;
  18133. }
  18134. tmp = MallocEx(size, true);
  18135. if (RecvAll(s, tmp, size, s->SecureMode) == false)
  18136. {
  18137. Free(tmp);
  18138. FreeHttpHeader(h);
  18139. return NULL;
  18140. }
  18141. b = NewBuf();
  18142. WriteBuf(b, tmp, size);
  18143. Free(tmp);
  18144. FreeHttpHeader(h);
  18145. SeekBuf(b, 0, 0);
  18146. p = BufToPack(b);
  18147. FreeBuf(b);
  18148. return p;
  18149. }
  18150. // Create an entry to PACK for the dummy
  18151. void CreateDummyValue(PACK *p)
  18152. {
  18153. UINT size;
  18154. UCHAR *buf;
  18155. // Validate arguments
  18156. if (p == NULL)
  18157. {
  18158. return;
  18159. }
  18160. size = Rand32() % HTTP_PACK_RAND_SIZE_MAX;
  18161. buf = Malloc(size);
  18162. Rand(buf, size);
  18163. PackAddData(p, "pencore", buf, size);
  18164. Free(buf);
  18165. }
  18166. // Client sends a PACK to the server
  18167. bool HttpClientSend(SOCK *s, PACK *p)
  18168. {
  18169. BUF *b;
  18170. bool ret;
  18171. HTTP_HEADER *h;
  18172. char date_str[MAX_SIZE];
  18173. char ip_str[MAX_SIZE];
  18174. // Validate arguments
  18175. if (s == NULL || p == NULL)
  18176. {
  18177. return false;
  18178. }
  18179. IPToStr(ip_str, sizeof(ip_str), &s->RemoteIP);
  18180. CreateDummyValue(p);
  18181. b = PackToBuf(p);
  18182. if (b == NULL)
  18183. {
  18184. return false;
  18185. }
  18186. h = NewHttpHeader("POST", HTTP_VPN_TARGET, "HTTP/1.1");
  18187. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18188. AddHttpValue(h, NewHttpValue("Date", date_str));
  18189. AddHttpValue(h, NewHttpValue("Host", ip_str));
  18190. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18191. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18192. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE2));
  18193. ret = PostHttp(s, h, b->Buf, b->Size);
  18194. FreeHttpHeader(h);
  18195. FreeBuf(b);
  18196. return ret;
  18197. }
  18198. // Server sends a PACK to the client
  18199. bool HttpServerSend(SOCK *s, PACK *p)
  18200. {
  18201. BUF *b;
  18202. bool ret;
  18203. HTTP_HEADER *h;
  18204. char date_str[MAX_SIZE];
  18205. // Validate arguments
  18206. if (s == NULL || p == NULL)
  18207. {
  18208. return false;
  18209. }
  18210. CreateDummyValue(p);
  18211. b = PackToBuf(p);
  18212. if (b == NULL)
  18213. {
  18214. return false;
  18215. }
  18216. h = NewHttpHeader("HTTP/1.1", "200", "OK");
  18217. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18218. AddHttpValue(h, NewHttpValue("Date", date_str));
  18219. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18220. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18221. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE2));
  18222. ret = PostHttp(s, h, b->Buf, b->Size);
  18223. FreeHttpHeader(h);
  18224. FreeBuf(b);
  18225. return ret;
  18226. }
  18227. // Replace unsafe characters in target
  18228. void ReplaceUnsafeCharInTarget(char *target){
  18229. UINT i;
  18230. for(i = 0; target[i] ; i++) {
  18231. if(target[i] == '<')
  18232. target[i] = '(';
  18233. else if(target[i] == '>')
  18234. target[i] = ')';
  18235. }
  18236. }
  18237. // Sending the 400 Bad Request: Invalid Hostname
  18238. bool HttpSendInvalidHostname(SOCK *s, char *method)
  18239. {
  18240. HTTP_HEADER *h;
  18241. char date_str[MAX_SIZE];
  18242. char *str;
  18243. bool ret;
  18244. char host[MAX_SIZE];
  18245. UINT port;
  18246. // Validate arguments
  18247. if (s == NULL)
  18248. {
  18249. return false;
  18250. }
  18251. // Get the host name
  18252. //GetMachineName(host, MAX_SIZE);
  18253. Zero(host, sizeof(host));
  18254. IPToStr(host, sizeof(host), &s->LocalIP);
  18255. // Get the port number
  18256. port = s->LocalPort;
  18257. // Creating a header
  18258. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18259. h = NewHttpHeader("HTTP/1.1", "400", "Bad Request");
  18260. AddHttpValue(h, NewHttpValue("Date", date_str));
  18261. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18262. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18263. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE));
  18264. // Creating a Data
  18265. str = "<h1>Bad Request (Invalid Hostname)</h1>\n";
  18266. // Transmission
  18267. ret = PostHttp(s, h, str, StrLen(str));
  18268. FreeHttpHeader(h);
  18269. return ret;
  18270. }
  18271. // Sending the 501 Not Implemented error
  18272. bool HttpSendNotImplemented(SOCK *s, char *method, char *target, char *version)
  18273. {
  18274. HTTP_HEADER *h;
  18275. char date_str[MAX_SIZE];
  18276. char *str;
  18277. UINT str_size;
  18278. char port_str[MAX_SIZE];
  18279. bool ret;
  18280. char host[MAX_SIZE];
  18281. UINT port;
  18282. // Validate arguments
  18283. if (s == NULL || target == NULL)
  18284. {
  18285. return false;
  18286. }
  18287. // Get the host name
  18288. //GetMachineName(host, MAX_SIZE);
  18289. Zero(host, sizeof(host));
  18290. IPToStr(host, sizeof(host), &s->LocalIP);
  18291. // Get the port number
  18292. port = s->LocalPort;
  18293. // Creating a header
  18294. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18295. h = NewHttpHeader("HTTP/1.1", "501", "Method Not Implemented");
  18296. AddHttpValue(h, NewHttpValue("Date", date_str));
  18297. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18298. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18299. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE));
  18300. // Creating a Data
  18301. str_size = sizeof(http_501_str) * 2 + StrLen(target) + StrLen(host) + StrLen(method) + StrLen(version);
  18302. str = Malloc(str_size);
  18303. StrCpy(str, str_size, http_501_str);
  18304. // TARGET
  18305. ReplaceUnsafeCharInTarget(target);
  18306. ReplaceStri(str, str_size, str, "$TARGET$", target);
  18307. // HOST
  18308. ReplaceStri(str, str_size, str, "$HOST$", host);
  18309. // PORT
  18310. ToStr(port_str, port);
  18311. ReplaceStri(str, str_size, str, "$PORT$", port_str);
  18312. // METHOD
  18313. ReplaceStri(str, str_size, str, "$METHOD$", method);
  18314. // VERSION
  18315. ReplaceStri(str, str_size, str, "$VERSION$", version);
  18316. // Transmission
  18317. ret = PostHttp(s, h, str, StrLen(str));
  18318. FreeHttpHeader(h);
  18319. Free(str);
  18320. return ret;
  18321. }
  18322. // Sending a 404 Not Found error
  18323. bool HttpSendNotFound(SOCK *s, char *target)
  18324. {
  18325. HTTP_HEADER *h;
  18326. char date_str[MAX_SIZE];
  18327. char *str;
  18328. UINT str_size;
  18329. char port_str[MAX_SIZE];
  18330. bool ret;
  18331. char host[MAX_SIZE];
  18332. UINT port;
  18333. // Validate arguments
  18334. if (s == NULL || target == NULL)
  18335. {
  18336. return false;
  18337. }
  18338. // Get the host name
  18339. //GetMachineName(host, MAX_SIZE);
  18340. Zero(host, sizeof(host));
  18341. IPToStr(host, sizeof(host), &s->LocalIP);
  18342. // Get the port number
  18343. port = s->LocalPort;
  18344. // Creating a header
  18345. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18346. h = NewHttpHeader("HTTP/1.1", "404", "Not Found");
  18347. AddHttpValue(h, NewHttpValue("Date", date_str));
  18348. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18349. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18350. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE));
  18351. // Creating a Data
  18352. str_size = sizeof(http_404_str) * 2 + StrLen(target) + StrLen(host);
  18353. str = Malloc(str_size);
  18354. StrCpy(str, str_size, http_404_str);
  18355. // TARGET
  18356. ReplaceUnsafeCharInTarget(target);
  18357. ReplaceStri(str, str_size, str, "$TARGET$", target);
  18358. // HOST
  18359. ReplaceStri(str, str_size, str, "$HOST$", host);
  18360. // PORT
  18361. ToStr(port_str, port);
  18362. ReplaceStri(str, str_size, str, "$PORT$", port_str);
  18363. // Transmission
  18364. ret = PostHttp(s, h, str, StrLen(str));
  18365. FreeHttpHeader(h);
  18366. Free(str);
  18367. return ret;
  18368. }
  18369. // Sending a 500 Server Error
  18370. bool HttpSendServerError(SOCK *s, char *target)
  18371. {
  18372. HTTP_HEADER *h;
  18373. char date_str[MAX_SIZE];
  18374. char *str;
  18375. UINT str_size;
  18376. char port_str[MAX_SIZE];
  18377. bool ret;
  18378. char host[MAX_SIZE];
  18379. UINT port;
  18380. // Validate arguments
  18381. if (s == NULL || target == NULL)
  18382. {
  18383. return false;
  18384. }
  18385. // Get the host name
  18386. //GetMachineName(host, MAX_SIZE);
  18387. Zero(host, sizeof(host));
  18388. IPToStr(host, sizeof(host), &s->LocalIP);
  18389. // Get the port number
  18390. port = s->LocalPort;
  18391. // Creating a header
  18392. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18393. h = NewHttpHeader("HTTP/1.1", "500", "Server Error");
  18394. AddHttpValue(h, NewHttpValue("Date", date_str));
  18395. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18396. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18397. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE));
  18398. // Creating a Data
  18399. str_size = sizeof(http_500_str) * 2 + StrLen(target) + StrLen(host);
  18400. str = Malloc(str_size);
  18401. StrCpy(str, str_size, http_500_str);
  18402. // TARGET
  18403. ReplaceUnsafeCharInTarget(target);
  18404. ReplaceStri(str, str_size, str, "$TARGET$", target);
  18405. // HOST
  18406. ReplaceStri(str, str_size, str, "$HOST$", host);
  18407. // PORT
  18408. ToStr(port_str, port);
  18409. ReplaceStri(str, str_size, str, "$PORT$", port_str);
  18410. // Transmission
  18411. ret = PostHttp(s, h, str, StrLen(str));
  18412. FreeHttpHeader(h);
  18413. Free(str);
  18414. return ret;
  18415. }
  18416. // Sending a 403 Forbidden error
  18417. bool HttpSendForbidden(SOCK *s, char *target, char *server_id)
  18418. {
  18419. HTTP_HEADER *h;
  18420. char date_str[MAX_SIZE];
  18421. char *str;
  18422. UINT str_size;
  18423. char port_str[MAX_SIZE];
  18424. bool ret;
  18425. char host[MAX_SIZE];
  18426. UINT port;
  18427. // Validate arguments
  18428. if (s == NULL || target == NULL)
  18429. {
  18430. return false;
  18431. }
  18432. // Get the host name
  18433. //GetMachineName(host, MAX_SIZE);
  18434. Zero(host, sizeof(host));
  18435. IPToStr(host, sizeof(host), &s->LocalIP);
  18436. // Get the port number
  18437. port = s->LocalPort;
  18438. // Creating a header
  18439. GetHttpDateStr(date_str, sizeof(date_str), SystemTime64());
  18440. h = NewHttpHeader("HTTP/1.1", "403", "Forbidden");
  18441. AddHttpValue(h, NewHttpValue("Date", date_str));
  18442. AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
  18443. AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
  18444. AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE));
  18445. // Creating a Data
  18446. str_size = sizeof(http_403_str) * 2 + StrLen(target) + StrLen(host);
  18447. str = Malloc(str_size);
  18448. StrCpy(str, str_size, http_403_str);
  18449. // TARGET
  18450. ReplaceUnsafeCharInTarget(target);
  18451. ReplaceStri(str, str_size, str, "$TARGET$", target);
  18452. // HOST
  18453. ReplaceStri(str, str_size, str, "$HOST$", host);
  18454. // PORT
  18455. ToStr(port_str, port);
  18456. ReplaceStri(str, str_size, str, "$PORT$", port_str);
  18457. // Transmission
  18458. ret = PostHttp(s, h, str, StrLen(str));
  18459. FreeHttpHeader(h);
  18460. Free(str);
  18461. return ret;
  18462. }
  18463. // Get the date and time string for the HTTP header
  18464. void GetHttpDateStr(char *str, UINT size, UINT64 t)
  18465. {
  18466. SYSTEMTIME s;
  18467. static char *wday[] =
  18468. {
  18469. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
  18470. };
  18471. static char *month[] =
  18472. {
  18473. "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
  18474. "Nov", "Dec",
  18475. };
  18476. // Validate arguments
  18477. if (str == NULL)
  18478. {
  18479. return;
  18480. }
  18481. UINT64ToSystem(&s, t);
  18482. Format(str, size, "%s, %02u %s %04u %02u:%02u:%02u GMT",
  18483. wday[s.wDayOfWeek], s.wDay, month[s.wMonth - 1], s.wYear,
  18484. s.wHour, s.wMinute, s.wSecond);
  18485. }
  18486. // Get the Content-Length from the HTTP header
  18487. UINT GetContentLength(HTTP_HEADER *header)
  18488. {
  18489. UINT ret;
  18490. HTTP_VALUE *v;
  18491. // Validate arguments
  18492. if (header == NULL)
  18493. {
  18494. return 0;
  18495. }
  18496. v = GetHttpValue(header, "Content-Length");
  18497. if (v == NULL)
  18498. {
  18499. return 0;
  18500. }
  18501. ret = ToInt(v->Data);
  18502. return ret;
  18503. }
  18504. // Send the data in the HTTP
  18505. bool PostHttp(SOCK *s, HTTP_HEADER *header, void *post_data, UINT post_size)
  18506. {
  18507. char *header_str;
  18508. BUF *b;
  18509. bool ret;
  18510. // Validate arguments
  18511. if (s == NULL || header == NULL || (post_size != 0 && post_data == NULL))
  18512. {
  18513. return false;
  18514. }
  18515. // Check whether the Content-Lentgh exists?
  18516. if (GetHttpValue(header, "Content-Length") == NULL)
  18517. {
  18518. char tmp[MAX_SIZE];
  18519. // Add because it does not exist
  18520. ToStr(tmp, post_size);
  18521. AddHttpValue(header, NewHttpValue("Content-Length", tmp));
  18522. }
  18523. // Convert the header to string
  18524. header_str = HttpHeaderToStr(header);
  18525. if (header_str == NULL)
  18526. {
  18527. return false;
  18528. }
  18529. b = NewBuf();
  18530. WriteBuf(b, header_str, StrLen(header_str));
  18531. Free(header_str);
  18532. // Append the data
  18533. WriteBuf(b, post_data, post_size);
  18534. // Send
  18535. ret = SendAll(s, b->Buf, b->Size, s->SecureMode);
  18536. FreeBuf(b);
  18537. return ret;
  18538. }
  18539. // Convert a HTTP header to a string
  18540. char *HttpHeaderToStr(HTTP_HEADER *header)
  18541. {
  18542. BUF *b;
  18543. char *tmp;
  18544. UINT i;
  18545. char *s;
  18546. // Validate arguments
  18547. if (header == NULL)
  18548. {
  18549. return NULL;
  18550. }
  18551. tmp = Malloc(HTTP_HEADER_LINE_MAX_SIZE);
  18552. b = NewBuf();
  18553. // Header
  18554. Format(tmp, HTTP_HEADER_LINE_MAX_SIZE,
  18555. "%s %s %s\r\n", header->Method, header->Target, header->Version);
  18556. WriteBuf(b, tmp, StrLen(tmp));
  18557. // Value
  18558. for (i = 0;i < LIST_NUM(header->ValueList);i++)
  18559. {
  18560. HTTP_VALUE *v = (HTTP_VALUE *)LIST_DATA(header->ValueList, i);
  18561. Format(tmp, HTTP_HEADER_LINE_MAX_SIZE,
  18562. "%s: %s\r\n", v->Name, v->Data);
  18563. WriteBuf(b, tmp, StrLen(tmp));
  18564. }
  18565. // Trailing newline
  18566. WriteBuf(b, "\r\n", 2);
  18567. s = Malloc(b->Size + 1);
  18568. Copy(s, b->Buf, b->Size);
  18569. s[b->Size] = 0;
  18570. FreeBuf(b);
  18571. Free(tmp);
  18572. return s;
  18573. }
  18574. // Send the HTTP header
  18575. bool SendHttpHeader(SOCK *s, HTTP_HEADER *header)
  18576. {
  18577. char *str;
  18578. bool ret;
  18579. // Validate arguments
  18580. if (s == NULL || header == NULL)
  18581. {
  18582. return false;
  18583. }
  18584. // Convert to string
  18585. str = HttpHeaderToStr(header);
  18586. // Transmission
  18587. ret = SendAll(s, str, StrLen(str), s->SecureMode);
  18588. Free(str);
  18589. return ret;
  18590. }
  18591. // Receive an HTTP header
  18592. HTTP_HEADER *RecvHttpHeader(SOCK *s)
  18593. {
  18594. TOKEN_LIST *token = NULL;
  18595. char *str = NULL;
  18596. HTTP_HEADER *header = NULL;
  18597. // Validate arguments
  18598. if (s == NULL)
  18599. {
  18600. return NULL;
  18601. }
  18602. // Get the first line
  18603. str = RecvLine(s, HTTP_HEADER_LINE_MAX_SIZE);
  18604. if (str == NULL)
  18605. {
  18606. goto LABEL_ERROR;
  18607. }
  18608. // Split into tokens
  18609. token = ParseToken(str, " ");
  18610. if (token->NumTokens < 3)
  18611. {
  18612. goto LABEL_ERROR;
  18613. }
  18614. Free(str);
  18615. str = NULL;
  18616. // Creating a header object
  18617. header = NewHttpHeader(token->Token[0], token->Token[1], token->Token[2]);
  18618. if (StrCmpi(header->Version, "HTTP/0.9") == 0)
  18619. {
  18620. // The header ends with this line
  18621. FreeToken(token);
  18622. return header;
  18623. }
  18624. // Get the subsequent lines
  18625. while (true)
  18626. {
  18627. UINT pos;
  18628. HTTP_VALUE *v;
  18629. char *value_name, *value_data;
  18630. str = RecvLine(s, HTTP_HEADER_LINE_MAX_SIZE);
  18631. if (str == NULL)
  18632. {
  18633. goto LABEL_ERROR;
  18634. }
  18635. Trim(str);
  18636. if (StrLen(str) == 0)
  18637. {
  18638. // End of header
  18639. Free(str);
  18640. str = NULL;
  18641. break;
  18642. }
  18643. // Get the position of the colon
  18644. pos = SearchStr(str, ":", 0);
  18645. if (pos == INFINITE)
  18646. {
  18647. // The colon does not exist
  18648. goto LABEL_ERROR;
  18649. }
  18650. if ((pos + 1) >= StrLen(str))
  18651. {
  18652. // There is no data
  18653. goto LABEL_ERROR;
  18654. }
  18655. // Divide into the name and the data
  18656. value_name = Malloc(pos + 1);
  18657. Copy(value_name, str, pos);
  18658. value_name[pos] = 0;
  18659. value_data = &str[pos + 1];
  18660. v = NewHttpValue(value_name, value_data);
  18661. if (v == NULL)
  18662. {
  18663. Free(value_name);
  18664. goto LABEL_ERROR;
  18665. }
  18666. Free(value_name);
  18667. AddHttpValue(header, v);
  18668. Free(str);
  18669. }
  18670. FreeToken(token);
  18671. return header;
  18672. LABEL_ERROR:
  18673. // Memory release
  18674. if (token)
  18675. {
  18676. FreeToken(token);
  18677. }
  18678. if (str)
  18679. {
  18680. Free(str);
  18681. }
  18682. if (header)
  18683. {
  18684. FreeHttpHeader(header);
  18685. }
  18686. return NULL;
  18687. }
  18688. // Receive a line
  18689. char *RecvLine(SOCK *s, UINT max_size)
  18690. {
  18691. BUF *b;
  18692. char c;
  18693. char *str;
  18694. // Validate arguments
  18695. if (s == NULL || max_size == 0)
  18696. {
  18697. return NULL;
  18698. }
  18699. b = NewBuf();
  18700. while (true)
  18701. {
  18702. UCHAR *buf;
  18703. if (RecvAll(s, &c, sizeof(c), s->SecureMode) == false)
  18704. {
  18705. FreeBuf(b);
  18706. return NULL;
  18707. }
  18708. WriteBuf(b, &c, sizeof(c));
  18709. buf = (UCHAR *)b->Buf;
  18710. if (b->Size > max_size)
  18711. {
  18712. FreeBuf(b);
  18713. return NULL;
  18714. }
  18715. if (b->Size >= 1)
  18716. {
  18717. if (buf[b->Size - 1] == '\n')
  18718. {
  18719. b->Size--;
  18720. if (b->Size >= 1)
  18721. {
  18722. if (buf[b->Size - 1] == '\r')
  18723. {
  18724. b->Size--;
  18725. }
  18726. }
  18727. str = Malloc(b->Size + 1);
  18728. Copy(str, b->Buf, b->Size);
  18729. str[b->Size] = 0;
  18730. FreeBuf(b);
  18731. return str;
  18732. }
  18733. }
  18734. }
  18735. }
  18736. // Creating a new HTTP value
  18737. HTTP_VALUE *NewHttpValue(char *name, char *data)
  18738. {
  18739. HTTP_VALUE *v;
  18740. // Validate arguments
  18741. if (name == NULL || data == NULL)
  18742. {
  18743. return NULL;
  18744. }
  18745. v = ZeroMalloc(sizeof(HTTP_VALUE));
  18746. v->Name = CopyStr(name);
  18747. v->Data = CopyStr(data);
  18748. Trim(v->Name);
  18749. Trim(v->Data);
  18750. return v;
  18751. }
  18752. // Look for the HTTP value from the HTTP header
  18753. HTTP_VALUE *GetHttpValue(HTTP_HEADER *header, char *name)
  18754. {
  18755. HTTP_VALUE *v, t;
  18756. // Validate arguments
  18757. if (header == NULL || name == NULL)
  18758. {
  18759. return NULL;
  18760. }
  18761. t.Name = name;
  18762. v = Search(header->ValueList, &t);
  18763. if (v == NULL)
  18764. {
  18765. return NULL;
  18766. }
  18767. return v;
  18768. }
  18769. // Add a HTTP value to the HTTP header
  18770. void AddHttpValue(HTTP_HEADER *header, HTTP_VALUE *value)
  18771. {
  18772. // Validate arguments
  18773. if (header == NULL || value == NULL)
  18774. {
  18775. return;
  18776. }
  18777. if (LIST_NUM(header->ValueList) < HTTP_HEADER_MAX_LINES)
  18778. {
  18779. Insert(header->ValueList, value);
  18780. }
  18781. else
  18782. {
  18783. FreeHttpValue(value);
  18784. }
  18785. }
  18786. // Create an HTTP header
  18787. HTTP_HEADER *NewHttpHeader(char *method, char *target, char *version)
  18788. {
  18789. return NewHttpHeaderEx(method, target, version, false);
  18790. }
  18791. HTTP_HEADER *NewHttpHeaderEx(char *method, char *target, char *version, bool no_sort)
  18792. {
  18793. HTTP_HEADER *header;
  18794. // Validate arguments
  18795. if (method == NULL || target == NULL || version == NULL)
  18796. {
  18797. return NULL;
  18798. }
  18799. header = ZeroMalloc(sizeof(HTTP_HEADER));
  18800. header->Method = CopyStr(method);
  18801. header->Target = CopyStr(target);
  18802. header->Version = CopyStr(version);
  18803. header->ValueList = NewListFast(no_sort ? NULL : CompareHttpValue);
  18804. return header;
  18805. }
  18806. // Comparison function of the HTTP value
  18807. int CompareHttpValue(void *p1, void *p2)
  18808. {
  18809. HTTP_VALUE *v1, *v2;
  18810. if (p1 == NULL || p2 == NULL)
  18811. {
  18812. return 0;
  18813. }
  18814. v1 = *(HTTP_VALUE **)p1;
  18815. v2 = *(HTTP_VALUE **)p2;
  18816. if (v1 == NULL || v2 == NULL)
  18817. {
  18818. return 0;
  18819. }
  18820. return StrCmpi(v1->Name, v2->Name);
  18821. }
  18822. // Release the HTTP value
  18823. void FreeHttpValue(HTTP_VALUE *value)
  18824. {
  18825. // Validate arguments
  18826. if (value == NULL)
  18827. {
  18828. return;
  18829. }
  18830. Free(value->Data);
  18831. Free(value->Name);
  18832. Free(value);
  18833. }
  18834. // Release the HTTP header
  18835. void FreeHttpHeader(HTTP_HEADER *header)
  18836. {
  18837. UINT i;
  18838. HTTP_VALUE **values;
  18839. // Validate arguments
  18840. if (header == NULL)
  18841. {
  18842. return;
  18843. }
  18844. Free(header->Method);
  18845. Free(header->Target);
  18846. Free(header->Version);
  18847. values = ToArray(header->ValueList);
  18848. for (i = 0;i < LIST_NUM(header->ValueList);i++)
  18849. {
  18850. FreeHttpValue(values[i]);
  18851. }
  18852. Free(values);
  18853. ReleaseList(header->ValueList);
  18854. Free(header);
  18855. }
  18856. // Receive a PACK
  18857. PACK *RecvPack(SOCK *s)
  18858. {
  18859. PACK *p;
  18860. BUF *b;
  18861. void *data;
  18862. UINT sz;
  18863. // Validate arguments
  18864. if (s == NULL || s->Type != SOCK_TCP)
  18865. {
  18866. return false;
  18867. }
  18868. if (RecvAll(s, &sz, sizeof(UINT), s->SecureMode) == false)
  18869. {
  18870. return false;
  18871. }
  18872. sz = Endian32(sz);
  18873. if (sz > MAX_PACK_SIZE)
  18874. {
  18875. return false;
  18876. }
  18877. data = MallocEx(sz, true);
  18878. if (RecvAll(s, data, sz, s->SecureMode) == false)
  18879. {
  18880. Free(data);
  18881. return false;
  18882. }
  18883. b = NewBuf();
  18884. WriteBuf(b, data, sz);
  18885. SeekBuf(b, 0, 0);
  18886. p = BufToPack(b);
  18887. FreeBuf(b);
  18888. Free(data);
  18889. return p;
  18890. }
  18891. // Receive a PACK (with checking the hash)
  18892. PACK *RecvPackWithHash(SOCK *s)
  18893. {
  18894. PACK *p;
  18895. BUF *b;
  18896. void *data;
  18897. UINT sz;
  18898. UCHAR hash1[SHA1_SIZE];
  18899. UCHAR hash2[SHA1_SIZE];
  18900. // Validate arguments
  18901. if (s == NULL || s->Type != SOCK_TCP)
  18902. {
  18903. return false;
  18904. }
  18905. if (RecvAll(s, &sz, sizeof(UINT), s->SecureMode) == false)
  18906. {
  18907. return false;
  18908. }
  18909. sz = Endian32(sz);
  18910. if (sz > MAX_PACK_SIZE)
  18911. {
  18912. return false;
  18913. }
  18914. data = MallocEx(sz, true);
  18915. if (RecvAll(s, data, sz, s->SecureMode) == false)
  18916. {
  18917. Free(data);
  18918. return false;
  18919. }
  18920. HashSha1(hash1, data, sz);
  18921. if (RecvAll(s, hash2, sizeof(hash2), s->SecureMode) == false)
  18922. {
  18923. Free(data);
  18924. return false;
  18925. }
  18926. if (Cmp(hash1, hash2, SHA1_SIZE) != 0)
  18927. {
  18928. Free(data);
  18929. return false;
  18930. }
  18931. b = NewBuf();
  18932. WriteBuf(b, data, sz);
  18933. SeekBuf(b, 0, 0);
  18934. p = BufToPack(b);
  18935. FreeBuf(b);
  18936. Free(data);
  18937. return p;
  18938. }
  18939. // Send a PACK
  18940. bool SendPack(SOCK *s, PACK *p)
  18941. {
  18942. BUF *b;
  18943. UINT sz;
  18944. // Validate arguments
  18945. if (s == NULL || p == NULL || s->Type != SOCK_TCP)
  18946. {
  18947. return false;
  18948. }
  18949. b = PackToBuf(p);
  18950. sz = Endian32(b->Size);
  18951. SendAdd(s, &sz, sizeof(UINT));
  18952. SendAdd(s, b->Buf, b->Size);
  18953. FreeBuf(b);
  18954. return SendNow(s, s->SecureMode);
  18955. }
  18956. // Send a Pack (with adding a hash)
  18957. bool SendPackWithHash(SOCK *s, PACK *p)
  18958. {
  18959. BUF *b;
  18960. UINT sz;
  18961. UCHAR hash[SHA1_SIZE];
  18962. // Validate arguments
  18963. if (s == NULL || p == NULL || s->Type != SOCK_TCP)
  18964. {
  18965. return false;
  18966. }
  18967. b = PackToBuf(p);
  18968. sz = Endian32(b->Size);
  18969. SendAdd(s, &sz, sizeof(UINT));
  18970. SendAdd(s, b->Buf, b->Size);
  18971. HashSha1(hash, b->Buf, b->Size);
  18972. SendAdd(s, hash, sizeof(hash));
  18973. FreeBuf(b);
  18974. return SendNow(s, s->SecureMode);
  18975. }
  18976. // Get SNI name from the data that has arrived to the TCP connection before accepting an SSL connection
  18977. bool GetSniNameFromPreSslConnection(SOCK *s, char *sni, UINT sni_size)
  18978. {
  18979. UCHAR tmp[1500];
  18980. UINT size;
  18981. // Validate arguments
  18982. if (s == NULL || sni == NULL)
  18983. {
  18984. return false;
  18985. }
  18986. size = Peek(s, tmp, sizeof(tmp));
  18987. if (size == 0)
  18988. {
  18989. return false;
  18990. }
  18991. return GetSniNameFromSslPacket(tmp, size, sni, sni_size);
  18992. }
  18993. // Get SNI name from the SSL packet
  18994. bool GetSniNameFromSslPacket(UCHAR *packet_buf, UINT packet_size, char *sni, UINT sni_size)
  18995. {
  18996. BUF *buf;
  18997. bool ret = false;
  18998. UCHAR content_type;
  18999. USHORT version;
  19000. USHORT handshake_length;
  19001. // Validate arguments
  19002. if (packet_buf == NULL || packet_size <= 11)
  19003. {
  19004. return false;
  19005. }
  19006. if (!(packet_buf[0] == 0x16 && packet_buf[1] >= 0x03 &&
  19007. packet_buf[5] == 0x01 && packet_buf[6] == 0x00 &&
  19008. packet_buf[9] >= 0x03))
  19009. {
  19010. return false;
  19011. }
  19012. buf = NewBufFromMemory(packet_buf, packet_size);
  19013. if (ReadBuf(buf, &content_type, sizeof(UCHAR)) == sizeof(UCHAR) &&
  19014. ReadBuf(buf, &version, sizeof(USHORT)) == sizeof(USHORT) &&
  19015. ReadBuf(buf, &handshake_length, sizeof(USHORT)) == sizeof(USHORT))
  19016. {
  19017. version = Endian16(version);
  19018. handshake_length = Endian16(handshake_length);
  19019. if (content_type == 0x16 && version >= 0x0301)
  19020. {
  19021. UCHAR *handshake_data = Malloc(handshake_length);
  19022. if (ReadBuf(buf, handshake_data, handshake_length) == handshake_length)
  19023. {
  19024. BUF *buf2 = NewBufFromMemory(handshake_data, handshake_length);
  19025. USHORT handshake_type;
  19026. USHORT handshake_length_2;
  19027. if (ReadBuf(buf2, &handshake_type, sizeof(USHORT)) == sizeof(USHORT) &&
  19028. ReadBuf(buf2, &handshake_length_2, sizeof(USHORT)) == sizeof(USHORT))
  19029. {
  19030. handshake_type = Endian16(handshake_type);
  19031. handshake_length_2 = Endian16(handshake_length_2);
  19032. if (handshake_type == 0x0100 && handshake_length_2 <= (handshake_length - 4))
  19033. {
  19034. USHORT version2;
  19035. if (ReadBuf(buf2, &version2, sizeof(USHORT)) == sizeof(USHORT))
  19036. {
  19037. version2 = Endian16(version2);
  19038. if (version2 >= 0x0301)
  19039. {
  19040. UCHAR rand[32];
  19041. if (ReadBuf(buf2, rand, sizeof(rand)) == sizeof(rand))
  19042. {
  19043. UCHAR session_id_len;
  19044. if (ReadBuf(buf2, &session_id_len, sizeof(UCHAR)) == sizeof(UCHAR))
  19045. {
  19046. if (ReadBuf(buf2, NULL, session_id_len) == session_id_len)
  19047. {
  19048. USHORT cipher_len;
  19049. if (ReadBuf(buf2, &cipher_len, sizeof(USHORT)) == sizeof(USHORT))
  19050. {
  19051. cipher_len = Endian16(cipher_len);
  19052. if (ReadBuf(buf2, NULL, cipher_len) == cipher_len)
  19053. {
  19054. UCHAR comps_len;
  19055. if (ReadBuf(buf2, &comps_len, sizeof(UCHAR)) == sizeof(UCHAR))
  19056. {
  19057. if (ReadBuf(buf2, NULL, comps_len) == comps_len)
  19058. {
  19059. USHORT ext_length;
  19060. if (ReadBuf(buf2, &ext_length, sizeof(USHORT)) == sizeof(USHORT))
  19061. {
  19062. UCHAR *ext_buf;
  19063. ext_length = Endian16(ext_length);
  19064. ext_buf = Malloc(ext_length);
  19065. if (ReadBuf(buf2, ext_buf, ext_length) == ext_length)
  19066. {
  19067. BUF *ebuf = NewBufFromMemory(ext_buf, ext_length);
  19068. while (ret == false)
  19069. {
  19070. USHORT type;
  19071. USHORT data_len;
  19072. UCHAR *data;
  19073. if (ReadBuf(ebuf, &type, sizeof(USHORT)) != sizeof(USHORT))
  19074. {
  19075. break;
  19076. }
  19077. if (ReadBuf(ebuf, &data_len, sizeof(USHORT)) != sizeof(USHORT))
  19078. {
  19079. break;
  19080. }
  19081. type = Endian16(type);
  19082. data_len = Endian16(data_len);
  19083. data = Malloc(data_len);
  19084. if (ReadBuf(ebuf, data, data_len) != data_len)
  19085. {
  19086. Free(data);
  19087. break;
  19088. }
  19089. if (type == 0x0000)
  19090. {
  19091. BUF *dbuf = NewBufFromMemory(data, data_len);
  19092. USHORT total_len;
  19093. if (ReadBuf(dbuf, &total_len, sizeof(USHORT)) == sizeof(USHORT))
  19094. {
  19095. UCHAR c;
  19096. total_len = Endian16(total_len);
  19097. if (ReadBuf(dbuf, &c, sizeof(UCHAR)) == sizeof(UCHAR))
  19098. {
  19099. if (c == 0)
  19100. {
  19101. USHORT name_len;
  19102. if (ReadBuf(dbuf, &name_len, sizeof(USHORT)) == sizeof(USHORT))
  19103. {
  19104. char *name_buf;
  19105. name_len = Endian16(name_len);
  19106. name_buf = ZeroMalloc(name_len + 1);
  19107. if (ReadBuf(dbuf, name_buf, name_len) == name_len)
  19108. {
  19109. if (StrLen(name_buf) >= 1)
  19110. {
  19111. ret = true;
  19112. StrCpy(sni, sni_size, name_buf);
  19113. }
  19114. }
  19115. Free(name_buf);
  19116. }
  19117. }
  19118. }
  19119. }
  19120. FreeBuf(dbuf);
  19121. }
  19122. Free(data);
  19123. }
  19124. FreeBuf(ebuf);
  19125. }
  19126. Free(ext_buf);
  19127. }
  19128. }
  19129. }
  19130. }
  19131. }
  19132. }
  19133. }
  19134. }
  19135. }
  19136. }
  19137. }
  19138. }
  19139. FreeBuf(buf2);
  19140. }
  19141. Free(handshake_data);
  19142. }
  19143. }
  19144. FreeBuf(buf);
  19145. if (ret)
  19146. {
  19147. Trim(sni);
  19148. if (IsEmptyStr(sni))
  19149. {
  19150. ret = false;
  19151. }
  19152. }
  19153. return ret;
  19154. }