DnsWebService.cs 293 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2021 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsApplicationCommon;
  16. using DnsServerCore.Dhcp;
  17. using DnsServerCore.Dhcp.Options;
  18. using DnsServerCore.Dns;
  19. using DnsServerCore.Dns.Applications;
  20. using DnsServerCore.Dns.ResourceRecords;
  21. using DnsServerCore.Dns.Zones;
  22. using Newtonsoft.Json;
  23. using Newtonsoft.Json.Converters;
  24. using System;
  25. using System.Collections.Concurrent;
  26. using System.Collections.Generic;
  27. using System.Globalization;
  28. using System.IO;
  29. using System.IO.Compression;
  30. using System.Net;
  31. using System.Net.Http;
  32. using System.Net.Security;
  33. using System.Net.Sockets;
  34. using System.Reflection;
  35. using System.Security.Cryptography;
  36. using System.Security.Cryptography.X509Certificates;
  37. using System.Text;
  38. using System.Threading;
  39. using System.Threading.Tasks;
  40. using TechnitiumLibrary.IO;
  41. using TechnitiumLibrary.Net;
  42. using TechnitiumLibrary.Net.Dns;
  43. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  44. using TechnitiumLibrary.Net.Http;
  45. using TechnitiumLibrary.Net.Proxy;
  46. namespace DnsServerCore
  47. {
  48. public sealed class DnsWebService : IDisposable
  49. {
  50. #region enum
  51. enum ServiceState
  52. {
  53. Stopped = 0,
  54. Starting = 1,
  55. Running = 2,
  56. Stopping = 3
  57. }
  58. #endregion
  59. #region variables
  60. readonly Version _currentVersion;
  61. readonly string _appFolder;
  62. readonly string _configFolder;
  63. readonly Uri _updateCheckUri;
  64. readonly Uri _appStoreUri;
  65. readonly LogManager _log;
  66. DnsServer _dnsServer;
  67. DhcpServer _dhcpServer;
  68. IReadOnlyList<IPAddress> _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
  69. int _webServiceHttpPort = 5380;
  70. int _webServiceTlsPort = 53443;
  71. bool _webServiceEnableTls;
  72. bool _webServiceHttpToTlsRedirect;
  73. string _webServiceTlsCertificatePath;
  74. string _webServiceTlsCertificatePassword;
  75. DateTime _webServiceTlsCertificateLastModifiedOn;
  76. HttpListener _webService;
  77. IReadOnlyList<Socket> _webServiceTlsListeners;
  78. X509Certificate2 _webServiceTlsCertificate;
  79. readonly IndependentTaskScheduler _webServiceTaskScheduler = new IndependentTaskScheduler(ThreadPriority.AboveNormal);
  80. string _webServiceHostname;
  81. IPEndPoint _webServiceHttpEP;
  82. string _dnsTlsCertificatePath;
  83. string _dnsTlsCertificatePassword;
  84. DateTime _dnsTlsCertificateLastModifiedOn;
  85. Timer _tlsCertificateUpdateTimer;
  86. const int TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL = 60000;
  87. const int TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL = 60000;
  88. const int MAX_LOGIN_ATTEMPTS = 5;
  89. const int BLOCK_ADDRESS_INTERVAL = 5 * 60 * 1000;
  90. readonly ConcurrentDictionary<IPAddress, int> _failedLoginAttempts = new ConcurrentDictionary<IPAddress, int>();
  91. readonly ConcurrentDictionary<IPAddress, DateTime> _blockedAddresses = new ConcurrentDictionary<IPAddress, DateTime>();
  92. readonly ConcurrentDictionary<string, string> _credentials = new ConcurrentDictionary<string, string>();
  93. readonly ConcurrentDictionary<string, UserSession> _sessions = new ConcurrentDictionary<string, UserSession>();
  94. volatile ServiceState _state = ServiceState.Stopped;
  95. Timer _blockListUpdateTimer;
  96. DateTime _blockListLastUpdatedOn;
  97. int _blockListUpdateIntervalHours = 24;
  98. const int BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL = 5000;
  99. const int BLOCK_LIST_UPDATE_TIMER_INTERVAL = 900000;
  100. List<string> _configDisabledZones;
  101. #endregion
  102. #region constructor
  103. public DnsWebService(string configFolder = null, Uri updateCheckUri = null, Uri appStoreUri = null)
  104. {
  105. Assembly assembly = Assembly.GetExecutingAssembly();
  106. AssemblyName assemblyName = assembly.GetName();
  107. _currentVersion = assemblyName.Version;
  108. _appFolder = Path.GetDirectoryName(assembly.Location);
  109. if (configFolder == null)
  110. _configFolder = Path.Combine(_appFolder, "config");
  111. else
  112. _configFolder = configFolder;
  113. if (!Directory.Exists(_configFolder))
  114. Directory.CreateDirectory(_configFolder);
  115. _updateCheckUri = updateCheckUri;
  116. _appStoreUri = appStoreUri;
  117. _log = new LogManager(_configFolder);
  118. string blockListsFolder = Path.Combine(_configFolder, "blocklists");
  119. if (!Directory.Exists(blockListsFolder))
  120. Directory.CreateDirectory(blockListsFolder);
  121. }
  122. #endregion
  123. #region IDisposable
  124. private bool _disposed;
  125. private void Dispose(bool disposing)
  126. {
  127. if (_disposed)
  128. return;
  129. if (disposing)
  130. {
  131. Stop();
  132. if (_webService != null)
  133. _webService.Close();
  134. if (_dnsServer != null)
  135. _dnsServer.Dispose();
  136. if (_dhcpServer != null)
  137. _dhcpServer.Dispose();
  138. if (_log != null)
  139. _log.Dispose();
  140. }
  141. _disposed = true;
  142. }
  143. public void Dispose()
  144. {
  145. Dispose(true);
  146. }
  147. #endregion
  148. #region private
  149. #region web service
  150. private async Task AcceptWebRequestAsync()
  151. {
  152. try
  153. {
  154. while (true)
  155. {
  156. HttpListenerContext context = await _webService.GetContextAsync();
  157. if ((_webServiceTlsListeners != null) && (_webServiceTlsListeners.Count > 0) && _webServiceHttpToTlsRedirect)
  158. {
  159. IPEndPoint remoteEP = context.Request.RemoteEndPoint;
  160. if ((remoteEP != null) && !IPAddress.IsLoopback(remoteEP.Address))
  161. {
  162. string domain = _webServiceTlsCertificate.GetNameInfo(X509NameType.DnsName, false);
  163. string redirectUri = "https://" + domain + ":" + _webServiceTlsPort + context.Request.Url.PathAndQuery;
  164. context.Response.Redirect(redirectUri);
  165. context.Response.Close();
  166. continue;
  167. }
  168. }
  169. _ = ProcessRequestAsync(context.Request, context.Response);
  170. }
  171. }
  172. catch (HttpListenerException ex)
  173. {
  174. if (ex.ErrorCode == 995)
  175. return; //web service stopping
  176. _log.Write(ex);
  177. }
  178. catch (ObjectDisposedException)
  179. {
  180. //web service stopped
  181. }
  182. catch (Exception ex)
  183. {
  184. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  185. return; //web service stopping
  186. _log.Write(ex);
  187. }
  188. }
  189. private async Task AcceptTlsWebRequestAsync(Socket tlsListener)
  190. {
  191. try
  192. {
  193. while (true)
  194. {
  195. Socket socket = await tlsListener.AcceptAsync();
  196. _ = TlsToHttpTunnelAsync(socket);
  197. }
  198. }
  199. catch (SocketException ex)
  200. {
  201. if (ex.SocketErrorCode == SocketError.OperationAborted)
  202. return; //web service stopping
  203. _log.Write(ex);
  204. }
  205. catch (ObjectDisposedException)
  206. {
  207. //web service stopped
  208. }
  209. catch (Exception ex)
  210. {
  211. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  212. return; //web service stopping
  213. _log.Write(ex);
  214. }
  215. }
  216. private async Task TlsToHttpTunnelAsync(Socket socket)
  217. {
  218. Socket tunnel = null;
  219. try
  220. {
  221. if (_webServiceLocalAddresses.Count < 1)
  222. return;
  223. string remoteIP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
  224. SslStream sslStream = new SslStream(new NetworkStream(socket, true));
  225. await sslStream.AuthenticateAsServerAsync(_webServiceTlsCertificate);
  226. tunnel = new Socket(_webServiceHttpEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  227. tunnel.Connect(_webServiceHttpEP);
  228. NetworkStream tunnelStream = new NetworkStream(tunnel, true);
  229. //copy tunnel to ssl
  230. _ = tunnelStream.CopyToAsync(sslStream).ContinueWith(delegate (Task prevTask) { sslStream.Dispose(); tunnelStream.Dispose(); });
  231. //copy ssl to tunnel
  232. try
  233. {
  234. while (true)
  235. {
  236. HttpRequest httpRequest = await HttpRequest.ReadRequestAsync(sslStream);
  237. if (httpRequest == null)
  238. return; //connection closed gracefully by client
  239. //inject X-Real-IP & host header
  240. httpRequest.Headers.Add("X-Real-IP", remoteIP);
  241. httpRequest.Headers[HttpRequestHeader.Host] = "localhost:" + _webServiceHttpPort.ToString();
  242. //relay request
  243. await tunnelStream.WriteAsync(Encoding.ASCII.GetBytes(httpRequest.HttpMethod + " " + httpRequest.RequestPathAndQuery + " " + httpRequest.Protocol + "\r\n"));
  244. await tunnelStream.WriteAsync(httpRequest.Headers.ToByteArray());
  245. if (httpRequest.InputStream != null)
  246. await httpRequest.InputStream.CopyToAsync(tunnelStream);
  247. await tunnelStream.FlushAsync();
  248. }
  249. }
  250. finally
  251. {
  252. sslStream.Dispose();
  253. tunnelStream.Dispose();
  254. }
  255. }
  256. catch (IOException)
  257. {
  258. //ignore
  259. }
  260. catch (Exception ex)
  261. {
  262. _log.Write(ex);
  263. }
  264. finally
  265. {
  266. socket.Dispose();
  267. if (tunnel != null)
  268. tunnel.Dispose();
  269. }
  270. }
  271. private async Task ProcessRequestAsync(HttpListenerRequest request, HttpListenerResponse response)
  272. {
  273. response.AddHeader("Server", "");
  274. response.AddHeader("X-Robots-Tag", "noindex, nofollow");
  275. try
  276. {
  277. Uri url = request.Url;
  278. string path = url.AbsolutePath;
  279. if (!path.StartsWith("/") || path.Contains("/../") || path.Contains("/.../"))
  280. {
  281. await SendErrorAsync(response, 404);
  282. return;
  283. }
  284. if (path.StartsWith("/api/"))
  285. {
  286. using (MemoryStream mS = new MemoryStream())
  287. {
  288. try
  289. {
  290. JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
  291. jsonWriter.WriteStartObject();
  292. switch (path)
  293. {
  294. case "/api/login":
  295. await LoginAsync(request, jsonWriter);
  296. break;
  297. case "/api/logout":
  298. Logout(request);
  299. break;
  300. default:
  301. if (!IsSessionValid(request))
  302. throw new InvalidTokenWebServiceException("Invalid token or session expired.");
  303. jsonWriter.WritePropertyName("response");
  304. jsonWriter.WriteStartObject();
  305. try
  306. {
  307. switch (path)
  308. {
  309. case "/api/changePassword":
  310. ChangePassword(request);
  311. break;
  312. case "/api/checkForUpdate":
  313. await CheckForUpdateAsync(request, jsonWriter);
  314. break;
  315. case "/api/getDnsSettings":
  316. GetDnsSettings(jsonWriter);
  317. break;
  318. case "/api/setDnsSettings":
  319. SetDnsSettings(request, jsonWriter);
  320. break;
  321. case "/api/forceUpdateBlockLists":
  322. ForceUpdateBlockLists(request);
  323. break;
  324. case "/api/backupSettings":
  325. await BackupSettingsAsync(request, response);
  326. return;
  327. case "/api/restoreSettings":
  328. await RestoreSettingsAsync(request, jsonWriter);
  329. break;
  330. case "/api/getStats":
  331. await GetStats(request, jsonWriter);
  332. break;
  333. case "/api/getTopStats":
  334. await GetTopStats(request, jsonWriter);
  335. break;
  336. case "/api/flushDnsCache":
  337. FlushCache(request);
  338. break;
  339. case "/api/listCachedZones":
  340. ListCachedZones(request, jsonWriter);
  341. break;
  342. case "/api/deleteCachedZone":
  343. DeleteCachedZone(request);
  344. break;
  345. case "/api/listAllowedZones":
  346. ListAllowedZones(request, jsonWriter);
  347. break;
  348. case "/api/importAllowedZones":
  349. ImportAllowedZones(request);
  350. break;
  351. case "/api/exportAllowedZones":
  352. ExportAllowedZones(response);
  353. return;
  354. case "/api/deleteAllowedZone":
  355. DeleteAllowedZone(request);
  356. break;
  357. case "/api/allowZone":
  358. AllowZone(request);
  359. break;
  360. case "/api/listBlockedZones":
  361. ListBlockedZones(request, jsonWriter);
  362. break;
  363. case "/api/importBlockedZones":
  364. ImportBlockedZones(request);
  365. break;
  366. case "/api/exportBlockedZones":
  367. ExportBlockedZones(response);
  368. return;
  369. case "/api/deleteBlockedZone":
  370. DeleteBlockedZone(request);
  371. break;
  372. case "/api/blockZone":
  373. BlockZone(request);
  374. break;
  375. case "/api/listZones":
  376. ListZones(jsonWriter);
  377. break;
  378. case "/api/createZone":
  379. await CreateZoneAsync(request, jsonWriter);
  380. break;
  381. case "/api/deleteZone":
  382. DeleteZone(request);
  383. break;
  384. case "/api/enableZone":
  385. EnableZone(request);
  386. break;
  387. case "/api/disableZone":
  388. DisableZone(request);
  389. break;
  390. case "/api/addRecord":
  391. AddRecord(request);
  392. break;
  393. case "/api/getRecords":
  394. GetRecords(request, jsonWriter);
  395. break;
  396. case "/api/deleteRecord":
  397. DeleteRecord(request);
  398. break;
  399. case "/api/updateRecord":
  400. UpdateRecord(request);
  401. break;
  402. case "/api/apps/list":
  403. await ListInstalledAppsAsync(jsonWriter);
  404. break;
  405. case "/api/apps/listStoreApps":
  406. await ListStoreApps(jsonWriter);
  407. break;
  408. case "/api/apps/downloadAndInstall":
  409. await DownloadAndInstallAppAsync(request);
  410. break;
  411. case "/api/apps/downloadAndUpdate":
  412. await DownloadAndUpdateAppAsync(request);
  413. break;
  414. case "/api/apps/install":
  415. await InstallAppAsync(request);
  416. break;
  417. case "/api/apps/update":
  418. await UpdateAppAsync(request);
  419. break;
  420. case "/api/apps/uninstall":
  421. UninstallApp(request);
  422. break;
  423. case "/api/apps/getConfig":
  424. await GetAppConfigAsync(request, jsonWriter);
  425. break;
  426. case "/api/apps/setConfig":
  427. await SetAppConfigAsync(request);
  428. break;
  429. case "/api/resolveQuery":
  430. await ResolveQuery(request, jsonWriter);
  431. break;
  432. case "/api/listLogs":
  433. ListLogs(jsonWriter);
  434. break;
  435. case "/api/deleteLog":
  436. DeleteLog(request);
  437. break;
  438. case "/api/deleteAllLogs":
  439. DeleteAllLogs(request);
  440. break;
  441. case "/api/deleteAllStats":
  442. DeleteAllStats(request);
  443. break;
  444. case "/api/listDhcpScopes":
  445. ListDhcpScopes(jsonWriter);
  446. break;
  447. case "/api/listDhcpLeases":
  448. ListDhcpLeases(jsonWriter);
  449. break;
  450. case "/api/getDhcpScope":
  451. GetDhcpScope(request, jsonWriter);
  452. break;
  453. case "/api/setDhcpScope":
  454. await SetDhcpScopeAsync(request);
  455. break;
  456. case "/api/enableDhcpScope":
  457. await EnableDhcpScopeAsync(request);
  458. break;
  459. case "/api/disableDhcpScope":
  460. DisableDhcpScope(request);
  461. break;
  462. case "/api/deleteDhcpScope":
  463. DeleteDhcpScope(request);
  464. break;
  465. case "/api/convertToReservedLease":
  466. ConvertToReservedLease(request);
  467. break;
  468. case "/api/convertToDynamicLease":
  469. ConvertToDynamicLease(request);
  470. break;
  471. default:
  472. await SendErrorAsync(response, 404);
  473. return;
  474. }
  475. }
  476. finally
  477. {
  478. jsonWriter.WriteEndObject();
  479. }
  480. break;
  481. }
  482. jsonWriter.WritePropertyName("status");
  483. jsonWriter.WriteValue("ok");
  484. jsonWriter.WriteEndObject();
  485. jsonWriter.Flush();
  486. }
  487. catch (InvalidTokenWebServiceException ex)
  488. {
  489. mS.SetLength(0);
  490. JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
  491. jsonWriter.WriteStartObject();
  492. jsonWriter.WritePropertyName("status");
  493. jsonWriter.WriteValue("invalid-token");
  494. jsonWriter.WritePropertyName("errorMessage");
  495. jsonWriter.WriteValue(ex.Message);
  496. jsonWriter.WriteEndObject();
  497. jsonWriter.Flush();
  498. }
  499. catch (Exception ex)
  500. {
  501. _log.Write(GetRequestRemoteEndPoint(request), ex);
  502. mS.SetLength(0);
  503. JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
  504. jsonWriter.WriteStartObject();
  505. jsonWriter.WritePropertyName("status");
  506. jsonWriter.WriteValue("error");
  507. jsonWriter.WritePropertyName("errorMessage");
  508. jsonWriter.WriteValue(ex.Message);
  509. jsonWriter.WritePropertyName("stackTrace");
  510. jsonWriter.WriteValue(ex.StackTrace);
  511. if (ex.InnerException != null)
  512. {
  513. jsonWriter.WritePropertyName("innerErrorMessage");
  514. jsonWriter.WriteValue(ex.InnerException.Message);
  515. }
  516. jsonWriter.WriteEndObject();
  517. jsonWriter.Flush();
  518. }
  519. response.ContentType = "application/json; charset=utf-8";
  520. response.ContentEncoding = Encoding.UTF8;
  521. response.ContentLength64 = mS.Length;
  522. mS.Position = 0;
  523. using (Stream stream = response.OutputStream)
  524. {
  525. await mS.CopyToAsync(stream);
  526. }
  527. }
  528. }
  529. else if (path.StartsWith("/log/"))
  530. {
  531. if (!IsSessionValid(request))
  532. {
  533. await SendErrorAsync(response, 403, "Invalid token or session expired.");
  534. return;
  535. }
  536. string[] pathParts = path.Split('/');
  537. string logFileName = pathParts[2];
  538. int limit = 0;
  539. string strLimit = request.QueryString["limit"];
  540. if (!string.IsNullOrEmpty(strLimit))
  541. limit = int.Parse(strLimit);
  542. await _log.DownloadLogAsync(request, response, logFileName, limit * 1024 * 1024);
  543. }
  544. else
  545. {
  546. if (path == "/")
  547. {
  548. path = "/index.html";
  549. }
  550. else if ((path == "/blocklist.txt") && !IPAddress.IsLoopback(GetRequestRemoteEndPoint(request).Address))
  551. {
  552. await SendErrorAsync(response, 403);
  553. return;
  554. }
  555. string wwwroot = Path.Combine(_appFolder, "www");
  556. path = Path.GetFullPath(wwwroot + path.Replace('/', Path.DirectorySeparatorChar));
  557. if (!path.StartsWith(wwwroot) || !File.Exists(path))
  558. {
  559. await SendErrorAsync(response, 404);
  560. return;
  561. }
  562. await SendFileAsync(request, response, path);
  563. }
  564. }
  565. catch (Exception ex)
  566. {
  567. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  568. return; //web service stopping
  569. _log.Write(GetRequestRemoteEndPoint(request), ex);
  570. await SendError(response, ex);
  571. }
  572. }
  573. private static IPEndPoint GetRequestRemoteEndPoint(HttpListenerRequest request)
  574. {
  575. try
  576. {
  577. if (request.RemoteEndPoint == null)
  578. return new IPEndPoint(IPAddress.Any, 0);
  579. if (NetUtilities.IsPrivateIP(request.RemoteEndPoint.Address))
  580. {
  581. string xRealIp = request.Headers["X-Real-IP"];
  582. if (IPAddress.TryParse(xRealIp, out IPAddress address))
  583. {
  584. //get the real IP address of the requesting client from X-Real-IP header set in nginx proxy_pass block
  585. return new IPEndPoint(address, 0);
  586. }
  587. }
  588. return request.RemoteEndPoint;
  589. }
  590. catch
  591. {
  592. return new IPEndPoint(IPAddress.Any, 0);
  593. }
  594. }
  595. public static Stream GetOutputStream(HttpListenerRequest request, HttpListenerResponse response)
  596. {
  597. string strAcceptEncoding = request.Headers["Accept-Encoding"];
  598. if (string.IsNullOrEmpty(strAcceptEncoding))
  599. {
  600. return response.OutputStream;
  601. }
  602. else
  603. {
  604. if (strAcceptEncoding.Contains("gzip"))
  605. {
  606. response.AddHeader("Content-Encoding", "gzip");
  607. return new GZipStream(response.OutputStream, CompressionMode.Compress);
  608. }
  609. else if (strAcceptEncoding.Contains("deflate"))
  610. {
  611. response.AddHeader("Content-Encoding", "deflate");
  612. return new DeflateStream(response.OutputStream, CompressionMode.Compress);
  613. }
  614. else
  615. {
  616. return response.OutputStream;
  617. }
  618. }
  619. }
  620. private static Task SendError(HttpListenerResponse response, Exception ex)
  621. {
  622. return SendErrorAsync(response, 500, ex.ToString());
  623. }
  624. private static async Task SendErrorAsync(HttpListenerResponse response, int statusCode, string message = null)
  625. {
  626. try
  627. {
  628. string statusString = statusCode + " " + DnsServer.GetHttpStatusString((HttpStatusCode)statusCode);
  629. byte[] buffer = Encoding.UTF8.GetBytes("<html><head><title>" + statusString + "</title></head><body><h1>" + statusString + "</h1>" + (message == null ? "" : "<p>" + message + "</p>") + "</body></html>");
  630. response.StatusCode = statusCode;
  631. response.ContentType = "text/html";
  632. response.ContentLength64 = buffer.Length;
  633. using (Stream stream = response.OutputStream)
  634. {
  635. await stream.WriteAsync(buffer);
  636. }
  637. }
  638. catch
  639. { }
  640. }
  641. private static async Task SendFileAsync(HttpListenerRequest request, HttpListenerResponse response, string filePath)
  642. {
  643. using (FileStream fS = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  644. {
  645. response.ContentType = WebUtilities.GetContentType(filePath).MediaType;
  646. response.AddHeader("Cache-Control", "private, max-age=300");
  647. using (Stream stream = GetOutputStream(request, response))
  648. {
  649. try
  650. {
  651. await fS.CopyToAsync(stream);
  652. }
  653. catch (HttpListenerException)
  654. {
  655. //ignore this error
  656. }
  657. }
  658. }
  659. }
  660. #endregion
  661. #region user session
  662. private string CreateSession(string username)
  663. {
  664. string token = BinaryNumber.GenerateRandomNumber256().ToString();
  665. if (!_sessions.TryAdd(token, new UserSession(username)))
  666. throw new DnsWebServiceException("Error while creating session. Please try again.");
  667. return token;
  668. }
  669. private UserSession GetSession(string token)
  670. {
  671. if (_sessions.TryGetValue(token, out UserSession session))
  672. return session;
  673. return null;
  674. }
  675. private UserSession GetSession(HttpListenerRequest request)
  676. {
  677. string strToken = request.QueryString["token"];
  678. if (string.IsNullOrEmpty(strToken))
  679. throw new DnsWebServiceException("Parameter 'token' missing.");
  680. return GetSession(strToken);
  681. }
  682. private UserSession DeleteSession(string token)
  683. {
  684. if (_sessions.TryRemove(token, out UserSession session))
  685. return session;
  686. return null;
  687. }
  688. private UserSession DeleteSession(HttpListenerRequest request)
  689. {
  690. string strToken = request.QueryString["token"];
  691. if (string.IsNullOrEmpty(strToken))
  692. throw new DnsWebServiceException("Parameter 'token' missing.");
  693. return DeleteSession(strToken);
  694. }
  695. private void FailedLoginAttempt(IPAddress address)
  696. {
  697. _failedLoginAttempts.AddOrUpdate(address, 1, delegate (IPAddress key, int attempts)
  698. {
  699. return attempts + 1;
  700. });
  701. }
  702. private bool LoginAttemptsExceedLimit(IPAddress address, int limit)
  703. {
  704. if (!_failedLoginAttempts.TryGetValue(address, out int attempts))
  705. return false;
  706. return attempts >= limit;
  707. }
  708. private void ResetFailedLoginAttempt(IPAddress address)
  709. {
  710. _failedLoginAttempts.TryRemove(address, out _);
  711. }
  712. private void BlockAddress(IPAddress address, int interval)
  713. {
  714. _blockedAddresses.TryAdd(address, DateTime.UtcNow.AddMilliseconds(interval));
  715. }
  716. private bool IsAddressBlocked(IPAddress address)
  717. {
  718. if (!_blockedAddresses.TryGetValue(address, out DateTime expiry))
  719. return false;
  720. if (expiry > DateTime.UtcNow)
  721. {
  722. return true;
  723. }
  724. else
  725. {
  726. UnblockAddress(address);
  727. ResetFailedLoginAttempt(address);
  728. return false;
  729. }
  730. }
  731. private void UnblockAddress(IPAddress address)
  732. {
  733. _blockedAddresses.TryRemove(address, out _);
  734. }
  735. #endregion
  736. #region auth api
  737. private async Task LoginAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
  738. {
  739. string strUsername = request.QueryString["user"];
  740. if (string.IsNullOrEmpty(strUsername))
  741. throw new DnsWebServiceException("Parameter 'user' missing.");
  742. string strPassword = request.QueryString["pass"];
  743. if (string.IsNullOrEmpty(strPassword))
  744. throw new DnsWebServiceException("Parameter 'pass' missing.");
  745. IPEndPoint remoteEP = GetRequestRemoteEndPoint(request);
  746. if (IsAddressBlocked(remoteEP.Address))
  747. throw new DnsWebServiceException("Max limit of " + MAX_LOGIN_ATTEMPTS + " attempts exceeded. Access blocked for " + (BLOCK_ADDRESS_INTERVAL / 1000) + " seconds.");
  748. strUsername = strUsername.ToLower();
  749. string strPasswordHash = GetPasswordHash(strUsername, strPassword);
  750. if (!_credentials.TryGetValue(strUsername, out string passwordHash) || (passwordHash != strPasswordHash))
  751. {
  752. if (strPassword != "admin") //exception for default password
  753. {
  754. FailedLoginAttempt(remoteEP.Address);
  755. if (LoginAttemptsExceedLimit(remoteEP.Address, MAX_LOGIN_ATTEMPTS))
  756. BlockAddress(remoteEP.Address, BLOCK_ADDRESS_INTERVAL);
  757. await Task.Delay(1000);
  758. }
  759. throw new DnsWebServiceException("Invalid username or password: " + strUsername);
  760. }
  761. ResetFailedLoginAttempt(remoteEP.Address);
  762. _log.Write(remoteEP, "[" + strUsername + "] User logged in.");
  763. string token = CreateSession(strUsername);
  764. jsonWriter.WritePropertyName("token");
  765. jsonWriter.WriteValue(token);
  766. }
  767. private bool IsSessionValid(HttpListenerRequest request)
  768. {
  769. UserSession session = GetSession(request);
  770. if (session == null)
  771. return false;
  772. if (session.HasExpired())
  773. {
  774. DeleteSession(request);
  775. return false;
  776. }
  777. session.UpdateLastSeen();
  778. return true;
  779. }
  780. private void ChangePassword(HttpListenerRequest request)
  781. {
  782. string strToken = request.QueryString["token"];
  783. if (string.IsNullOrEmpty(strToken))
  784. throw new DnsWebServiceException("Parameter 'token' missing.");
  785. string strPassword = request.QueryString["pass"];
  786. if (string.IsNullOrEmpty(strPassword))
  787. throw new DnsWebServiceException("Parameter 'pass' missing.");
  788. UserSession session = GetSession(strToken);
  789. if (session == null)
  790. throw new DnsWebServiceException("User session does not exists.");
  791. SetCredentials(session.Username, strPassword);
  792. SaveConfigFile();
  793. _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] Password was changed for user.");
  794. }
  795. private void Logout(HttpListenerRequest request)
  796. {
  797. string strToken = request.QueryString["token"];
  798. if (string.IsNullOrEmpty(strToken))
  799. throw new DnsWebServiceException("Parameter 'token' missing.");
  800. UserSession session = DeleteSession(strToken);
  801. if (session != null)
  802. _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] User logged out.");
  803. }
  804. #endregion
  805. #region update api
  806. public static void CreateUpdateInfo(Stream s, string version, string displayText, string downloadLink)
  807. {
  808. BinaryWriter bW = new BinaryWriter(s);
  809. bW.Write(Encoding.ASCII.GetBytes("DU")); //format
  810. bW.Write((byte)2); //version
  811. bW.WriteShortString(version);
  812. bW.WriteShortString(displayText);
  813. bW.WriteShortString(downloadLink);
  814. }
  815. private async Task CheckForUpdateAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
  816. {
  817. Version updateVersion = null;
  818. string displayText = null;
  819. string downloadLink = null;
  820. bool updateAvailable = false;
  821. if (_updateCheckUri != null)
  822. {
  823. try
  824. {
  825. SocketsHttpHandler handler = new SocketsHttpHandler();
  826. handler.Proxy = _dnsServer.Proxy;
  827. using (HttpClient http = new HttpClient(handler))
  828. {
  829. byte[] response = await http.GetByteArrayAsync(_updateCheckUri);
  830. using (MemoryStream mS = new MemoryStream(response, false))
  831. {
  832. BinaryReader bR = new BinaryReader(mS);
  833. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DU") //format
  834. throw new InvalidDataException("DNS Server update info format is invalid.");
  835. switch (bR.ReadByte()) //version
  836. {
  837. case 2:
  838. updateVersion = new Version(bR.ReadShortString());
  839. displayText = bR.ReadShortString();
  840. downloadLink = bR.ReadShortString();
  841. break;
  842. default:
  843. throw new InvalidDataException("DNS Server update info version not supported.");
  844. }
  845. updateAvailable = updateVersion > _currentVersion;
  846. }
  847. }
  848. _log.Write(GetRequestRemoteEndPoint(request), "Check for update was done {updateAvailable: " + updateAvailable + "; updateVersion: " + updateVersion + "; displayText: " + displayText + "; downloadLink: " + downloadLink + ";}");
  849. }
  850. catch (Exception ex)
  851. {
  852. _log.Write(GetRequestRemoteEndPoint(request), "Check for update was done {updateAvailable: False;}\r\n" + ex.ToString());
  853. }
  854. }
  855. jsonWriter.WritePropertyName("updateAvailable");
  856. jsonWriter.WriteValue(updateAvailable);
  857. if (updateAvailable)
  858. {
  859. if (!string.IsNullOrEmpty(displayText))
  860. {
  861. jsonWriter.WritePropertyName("displayText");
  862. jsonWriter.WriteValue(displayText);
  863. }
  864. jsonWriter.WritePropertyName("downloadLink");
  865. jsonWriter.WriteValue(downloadLink);
  866. }
  867. }
  868. private static string GetCleanVersion(Version version)
  869. {
  870. string strVersion = version.Major + "." + version.Minor;
  871. if (version.Build > 0)
  872. strVersion += "." + version.Build;
  873. if (version.Revision > 0)
  874. strVersion += "." + version.Revision;
  875. return strVersion;
  876. }
  877. #endregion
  878. #region settings api
  879. private void GetDnsSettings(JsonTextWriter jsonWriter)
  880. {
  881. jsonWriter.WritePropertyName("version");
  882. jsonWriter.WriteValue(GetCleanVersion(_currentVersion));
  883. jsonWriter.WritePropertyName("dnsServerDomain");
  884. jsonWriter.WriteValue(_dnsServer.ServerDomain);
  885. jsonWriter.WritePropertyName("dnsServerLocalEndPoints");
  886. jsonWriter.WriteStartArray();
  887. foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
  888. jsonWriter.WriteValue(localEP.ToString());
  889. jsonWriter.WriteEndArray();
  890. jsonWriter.WritePropertyName("webServiceLocalAddresses");
  891. jsonWriter.WriteStartArray();
  892. foreach (IPAddress localAddress in _webServiceLocalAddresses)
  893. {
  894. if (localAddress.AddressFamily == AddressFamily.InterNetworkV6)
  895. jsonWriter.WriteValue("[" + localAddress.ToString() + "]");
  896. else
  897. jsonWriter.WriteValue(localAddress.ToString());
  898. }
  899. jsonWriter.WriteEndArray();
  900. jsonWriter.WritePropertyName("webServiceHttpPort");
  901. jsonWriter.WriteValue(_webServiceHttpPort);
  902. jsonWriter.WritePropertyName("webServiceEnableTls");
  903. jsonWriter.WriteValue(_webServiceEnableTls);
  904. jsonWriter.WritePropertyName("webServiceHttpToTlsRedirect");
  905. jsonWriter.WriteValue(_webServiceHttpToTlsRedirect);
  906. jsonWriter.WritePropertyName("webServiceTlsPort");
  907. jsonWriter.WriteValue(_webServiceTlsPort);
  908. jsonWriter.WritePropertyName("webServiceTlsCertificatePath");
  909. jsonWriter.WriteValue(_webServiceTlsCertificatePath);
  910. jsonWriter.WritePropertyName("webServiceTlsCertificatePassword");
  911. jsonWriter.WriteValue("************");
  912. jsonWriter.WritePropertyName("enableDnsOverHttp");
  913. jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttp);
  914. jsonWriter.WritePropertyName("enableDnsOverTls");
  915. jsonWriter.WriteValue(_dnsServer.EnableDnsOverTls);
  916. jsonWriter.WritePropertyName("enableDnsOverHttps");
  917. jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttps);
  918. jsonWriter.WritePropertyName("dnsTlsCertificatePath");
  919. jsonWriter.WriteValue(_dnsTlsCertificatePath);
  920. jsonWriter.WritePropertyName("dnsTlsCertificatePassword");
  921. jsonWriter.WriteValue("************");
  922. jsonWriter.WritePropertyName("preferIPv6");
  923. jsonWriter.WriteValue(_dnsServer.PreferIPv6);
  924. jsonWriter.WritePropertyName("enableLogging");
  925. jsonWriter.WriteValue(_log.EnableLogging);
  926. jsonWriter.WritePropertyName("logQueries");
  927. jsonWriter.WriteValue(_dnsServer.QueryLogManager != null);
  928. jsonWriter.WritePropertyName("useLocalTime");
  929. jsonWriter.WriteValue(_log.UseLocalTime);
  930. jsonWriter.WritePropertyName("logFolder");
  931. jsonWriter.WriteValue(_log.LogFolder);
  932. jsonWriter.WritePropertyName("maxLogFileDays");
  933. jsonWriter.WriteValue(_log.MaxLogFileDays);
  934. jsonWriter.WritePropertyName("maxStatFileDays");
  935. jsonWriter.WriteValue(_dnsServer.StatsManager.MaxStatFileDays);
  936. jsonWriter.WritePropertyName("allowRecursion");
  937. jsonWriter.WriteValue(_dnsServer.AllowRecursion);
  938. jsonWriter.WritePropertyName("allowRecursionOnlyForPrivateNetworks");
  939. jsonWriter.WriteValue(_dnsServer.AllowRecursionOnlyForPrivateNetworks);
  940. jsonWriter.WritePropertyName("randomizeName");
  941. jsonWriter.WriteValue(_dnsServer.RandomizeName);
  942. jsonWriter.WritePropertyName("qnameMinimization");
  943. jsonWriter.WriteValue(_dnsServer.QnameMinimization);
  944. jsonWriter.WritePropertyName("serveStale");
  945. jsonWriter.WriteValue(_dnsServer.ServeStale);
  946. jsonWriter.WritePropertyName("serveStaleTtl");
  947. jsonWriter.WriteValue(_dnsServer.CacheZoneManager.ServeStaleTtl);
  948. jsonWriter.WritePropertyName("cachePrefetchEligibility");
  949. jsonWriter.WriteValue(_dnsServer.CachePrefetchEligibility);
  950. jsonWriter.WritePropertyName("cachePrefetchTrigger");
  951. jsonWriter.WriteValue(_dnsServer.CachePrefetchTrigger);
  952. jsonWriter.WritePropertyName("cachePrefetchSampleIntervalInMinutes");
  953. jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleIntervalInMinutes);
  954. jsonWriter.WritePropertyName("cachePrefetchSampleEligibilityHitsPerHour");
  955. jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
  956. jsonWriter.WritePropertyName("proxy");
  957. if (_dnsServer.Proxy == null)
  958. {
  959. jsonWriter.WriteNull();
  960. }
  961. else
  962. {
  963. jsonWriter.WriteStartObject();
  964. NetProxy proxy = _dnsServer.Proxy;
  965. jsonWriter.WritePropertyName("type");
  966. jsonWriter.WriteValue(proxy.Type.ToString());
  967. jsonWriter.WritePropertyName("address");
  968. jsonWriter.WriteValue(proxy.Address);
  969. jsonWriter.WritePropertyName("port");
  970. jsonWriter.WriteValue(proxy.Port);
  971. NetworkCredential credential = proxy.Credential;
  972. if (credential != null)
  973. {
  974. jsonWriter.WritePropertyName("username");
  975. jsonWriter.WriteValue(credential.UserName);
  976. jsonWriter.WritePropertyName("password");
  977. jsonWriter.WriteValue(credential.Password);
  978. }
  979. jsonWriter.WritePropertyName("bypass");
  980. jsonWriter.WriteStartArray();
  981. foreach (NetProxyBypassItem item in proxy.BypassList)
  982. jsonWriter.WriteValue(item.Value);
  983. jsonWriter.WriteEndArray();
  984. jsonWriter.WriteEndObject();
  985. }
  986. jsonWriter.WritePropertyName("forwarders");
  987. DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
  988. if (_dnsServer.Forwarders == null)
  989. {
  990. jsonWriter.WriteNull();
  991. }
  992. else
  993. {
  994. forwarderProtocol = _dnsServer.Forwarders[0].Protocol;
  995. jsonWriter.WriteStartArray();
  996. foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
  997. jsonWriter.WriteValue(forwarder.OriginalAddress);
  998. jsonWriter.WriteEndArray();
  999. }
  1000. jsonWriter.WritePropertyName("forwarderProtocol");
  1001. jsonWriter.WriteValue(forwarderProtocol.ToString());
  1002. jsonWriter.WritePropertyName("useNxDomainForBlocking");
  1003. jsonWriter.WriteValue(_dnsServer.UseNxDomainForBlocking);
  1004. jsonWriter.WritePropertyName("blockListUrls");
  1005. if ((_dnsServer.BlockListZoneManager.AllowListUrls.Count == 0) && (_dnsServer.BlockListZoneManager.BlockListUrls.Count == 0))
  1006. {
  1007. jsonWriter.WriteNull();
  1008. }
  1009. else
  1010. {
  1011. jsonWriter.WriteStartArray();
  1012. foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
  1013. jsonWriter.WriteValue("!" + allowListUrl.AbsoluteUri);
  1014. foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
  1015. jsonWriter.WriteValue(blockListUrl.AbsoluteUri);
  1016. jsonWriter.WriteEndArray();
  1017. }
  1018. jsonWriter.WritePropertyName("blockListUpdateIntervalHours");
  1019. jsonWriter.WriteValue(_blockListUpdateIntervalHours);
  1020. jsonWriter.WritePropertyName("blockListNextUpdatedOn");
  1021. jsonWriter.WriteValue(_blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours).ToLocalTime().ToString());
  1022. }
  1023. private void SetDnsSettings(HttpListenerRequest request, JsonTextWriter jsonWriter)
  1024. {
  1025. bool restartDnsService = false;
  1026. bool restartWebService = false;
  1027. string strDnsServerDomain = request.QueryString["dnsServerDomain"];
  1028. if (!string.IsNullOrEmpty(strDnsServerDomain))
  1029. _dnsServer.ServerDomain = strDnsServerDomain;
  1030. string strDnsServerLocalEndPoints = request.QueryString["dnsServerLocalEndPoints"];
  1031. if (strDnsServerLocalEndPoints != null)
  1032. {
  1033. if (string.IsNullOrEmpty(strDnsServerLocalEndPoints))
  1034. strDnsServerLocalEndPoints = "0.0.0.0:53,[::]:53";
  1035. string[] strLocalEndPoints = strDnsServerLocalEndPoints.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1036. List<IPEndPoint> localEndPoints = new List<IPEndPoint>(strLocalEndPoints.Length);
  1037. for (int i = 0; i < strLocalEndPoints.Length; i++)
  1038. {
  1039. NameServerAddress nameServer = new NameServerAddress(strLocalEndPoints[i]);
  1040. if (nameServer.IPEndPoint != null)
  1041. localEndPoints.Add(nameServer.IPEndPoint);
  1042. }
  1043. if (localEndPoints.Count > 0)
  1044. {
  1045. if (_dnsServer.LocalEndPoints.Count != localEndPoints.Count)
  1046. {
  1047. restartDnsService = true;
  1048. }
  1049. else
  1050. {
  1051. foreach (IPEndPoint currentLocalEP in _dnsServer.LocalEndPoints)
  1052. {
  1053. if (!localEndPoints.Contains(currentLocalEP))
  1054. {
  1055. restartDnsService = true;
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. _dnsServer.LocalEndPoints = localEndPoints;
  1061. }
  1062. }
  1063. string strWebServiceLocalAddresses = request.QueryString["webServiceLocalAddresses"];
  1064. if (strWebServiceLocalAddresses != null)
  1065. {
  1066. if (string.IsNullOrEmpty(strWebServiceLocalAddresses))
  1067. strWebServiceLocalAddresses = "0.0.0.0,[::]";
  1068. string[] strLocalAddresses = strWebServiceLocalAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1069. List<IPAddress> localAddresses = new List<IPAddress>(strLocalAddresses.Length);
  1070. for (int i = 0; i < strLocalAddresses.Length; i++)
  1071. {
  1072. if (IPAddress.TryParse(strLocalAddresses[i], out IPAddress localAddress))
  1073. localAddresses.Add(localAddress);
  1074. }
  1075. if (localAddresses.Count > 0)
  1076. {
  1077. if (_webServiceLocalAddresses.Count != localAddresses.Count)
  1078. {
  1079. restartWebService = true;
  1080. }
  1081. else
  1082. {
  1083. foreach (IPAddress currentlocalAddress in _webServiceLocalAddresses)
  1084. {
  1085. if (!localAddresses.Contains(currentlocalAddress))
  1086. {
  1087. restartWebService = true;
  1088. break;
  1089. }
  1090. }
  1091. }
  1092. _webServiceLocalAddresses = localAddresses;
  1093. }
  1094. }
  1095. int oldWebServiceHttpPort = _webServiceHttpPort;
  1096. string strWebServiceHttpPort = request.QueryString["webServiceHttpPort"];
  1097. if (!string.IsNullOrEmpty(strWebServiceHttpPort))
  1098. {
  1099. _webServiceHttpPort = int.Parse(strWebServiceHttpPort);
  1100. if (oldWebServiceHttpPort != _webServiceHttpPort)
  1101. restartWebService = true;
  1102. }
  1103. string strWebServiceEnableTls = request.QueryString["webServiceEnableTls"];
  1104. if (!string.IsNullOrEmpty(strWebServiceEnableTls))
  1105. {
  1106. bool oldWebServiceEnableTls = _webServiceEnableTls;
  1107. _webServiceEnableTls = bool.Parse(strWebServiceEnableTls);
  1108. if (oldWebServiceEnableTls != _webServiceEnableTls)
  1109. restartWebService = true;
  1110. }
  1111. string strWebServiceHttpToTlsRedirect = request.QueryString["webServiceHttpToTlsRedirect"];
  1112. if (!string.IsNullOrEmpty(strWebServiceHttpToTlsRedirect))
  1113. _webServiceHttpToTlsRedirect = bool.Parse(strWebServiceHttpToTlsRedirect);
  1114. string strWebServiceTlsPort = request.QueryString["webServiceTlsPort"];
  1115. if (!string.IsNullOrEmpty(strWebServiceTlsPort))
  1116. {
  1117. int oldWebServiceTlsPort = _webServiceTlsPort;
  1118. _webServiceTlsPort = int.Parse(strWebServiceTlsPort);
  1119. if (oldWebServiceTlsPort != _webServiceTlsPort)
  1120. restartWebService = true;
  1121. }
  1122. string strWebServiceTlsCertificatePath = request.QueryString["webServiceTlsCertificatePath"];
  1123. string strWebServiceTlsCertificatePassword = request.QueryString["webServiceTlsCertificatePassword"];
  1124. if (string.IsNullOrEmpty(strWebServiceTlsCertificatePath))
  1125. {
  1126. _webServiceTlsCertificatePath = null;
  1127. _webServiceTlsCertificatePassword = "";
  1128. }
  1129. else
  1130. {
  1131. if (strWebServiceTlsCertificatePassword == "************")
  1132. strWebServiceTlsCertificatePassword = _webServiceTlsCertificatePassword;
  1133. if ((strWebServiceTlsCertificatePath != _webServiceTlsCertificatePath) || (strWebServiceTlsCertificatePassword != _webServiceTlsCertificatePassword))
  1134. {
  1135. LoadWebServiceTlsCertificate(strWebServiceTlsCertificatePath, strWebServiceTlsCertificatePassword);
  1136. _webServiceTlsCertificatePath = strWebServiceTlsCertificatePath;
  1137. _webServiceTlsCertificatePassword = strWebServiceTlsCertificatePassword;
  1138. StartTlsCertificateUpdateTimer();
  1139. }
  1140. }
  1141. string enableDnsOverHttp = request.QueryString["enableDnsOverHttp"];
  1142. if (!string.IsNullOrEmpty(enableDnsOverHttp))
  1143. {
  1144. bool oldEnableDnsOverHttp = _dnsServer.EnableDnsOverHttp;
  1145. _dnsServer.EnableDnsOverHttp = bool.Parse(enableDnsOverHttp);
  1146. if (oldEnableDnsOverHttp != _dnsServer.EnableDnsOverHttp)
  1147. restartDnsService = true;
  1148. }
  1149. string strEnableDnsOverTls = request.QueryString["enableDnsOverTls"];
  1150. if (!string.IsNullOrEmpty(strEnableDnsOverTls))
  1151. {
  1152. bool oldEnableDnsOverTls = _dnsServer.EnableDnsOverTls;
  1153. _dnsServer.EnableDnsOverTls = bool.Parse(strEnableDnsOverTls);
  1154. if (oldEnableDnsOverTls != _dnsServer.EnableDnsOverTls)
  1155. restartDnsService = true;
  1156. }
  1157. string strEnableDnsOverHttps = request.QueryString["enableDnsOverHttps"];
  1158. if (!string.IsNullOrEmpty(strEnableDnsOverHttps))
  1159. {
  1160. bool oldEnableDnsOverHttps = _dnsServer.EnableDnsOverHttps;
  1161. _dnsServer.EnableDnsOverHttps = bool.Parse(strEnableDnsOverHttps);
  1162. if (oldEnableDnsOverHttps != _dnsServer.EnableDnsOverHttps)
  1163. restartDnsService = true;
  1164. }
  1165. string strDnsTlsCertificatePath = request.QueryString["dnsTlsCertificatePath"];
  1166. string strDnsTlsCertificatePassword = request.QueryString["dnsTlsCertificatePassword"];
  1167. if (string.IsNullOrEmpty(strDnsTlsCertificatePath))
  1168. {
  1169. _dnsTlsCertificatePath = null;
  1170. _dnsTlsCertificatePassword = "";
  1171. }
  1172. else
  1173. {
  1174. if (strDnsTlsCertificatePassword == "************")
  1175. strDnsTlsCertificatePassword = _dnsTlsCertificatePassword;
  1176. if ((strDnsTlsCertificatePath != _dnsTlsCertificatePath) || (strDnsTlsCertificatePassword != _dnsTlsCertificatePassword))
  1177. {
  1178. LoadDnsTlsCertificate(strDnsTlsCertificatePath, strDnsTlsCertificatePassword);
  1179. _dnsTlsCertificatePath = strDnsTlsCertificatePath;
  1180. _dnsTlsCertificatePassword = strDnsTlsCertificatePassword;
  1181. StartTlsCertificateUpdateTimer();
  1182. }
  1183. }
  1184. string strPreferIPv6 = request.QueryString["preferIPv6"];
  1185. if (!string.IsNullOrEmpty(strPreferIPv6))
  1186. _dnsServer.PreferIPv6 = bool.Parse(strPreferIPv6);
  1187. string strEnableLogging = request.QueryString["enableLogging"];
  1188. if (!string.IsNullOrEmpty(strEnableLogging))
  1189. _log.EnableLogging = bool.Parse(strEnableLogging);
  1190. string strLogQueries = request.QueryString["logQueries"];
  1191. if (!string.IsNullOrEmpty(strLogQueries))
  1192. {
  1193. if (bool.Parse(strLogQueries))
  1194. _dnsServer.QueryLogManager = _log;
  1195. else
  1196. _dnsServer.QueryLogManager = null;
  1197. }
  1198. string strUseLocalTime = request.QueryString["useLocalTime"];
  1199. if (!string.IsNullOrEmpty(strUseLocalTime))
  1200. _log.UseLocalTime = bool.Parse(strUseLocalTime);
  1201. string strLogFolder = request.QueryString["logFolder"];
  1202. if (!string.IsNullOrEmpty(strLogFolder))
  1203. _log.LogFolder = strLogFolder;
  1204. string strMaxLogFileDays = request.QueryString["maxLogFileDays"];
  1205. if (!string.IsNullOrEmpty(strMaxLogFileDays))
  1206. _log.MaxLogFileDays = int.Parse(strMaxLogFileDays);
  1207. string strMaxStatFileDays = request.QueryString["maxStatFileDays"];
  1208. if (!string.IsNullOrEmpty(strMaxStatFileDays))
  1209. _dnsServer.StatsManager.MaxStatFileDays = int.Parse(strMaxStatFileDays);
  1210. string strAllowRecursion = request.QueryString["allowRecursion"];
  1211. if (!string.IsNullOrEmpty(strAllowRecursion))
  1212. _dnsServer.AllowRecursion = bool.Parse(strAllowRecursion);
  1213. string strAllowRecursionOnlyForPrivateNetworks = request.QueryString["allowRecursionOnlyForPrivateNetworks"];
  1214. if (!string.IsNullOrEmpty(strAllowRecursionOnlyForPrivateNetworks))
  1215. _dnsServer.AllowRecursionOnlyForPrivateNetworks = bool.Parse(strAllowRecursionOnlyForPrivateNetworks);
  1216. string strRandomizeName = request.QueryString["randomizeName"];
  1217. if (!string.IsNullOrEmpty(strRandomizeName))
  1218. _dnsServer.RandomizeName = bool.Parse(strRandomizeName);
  1219. string strQnameMinimization = request.QueryString["qnameMinimization"];
  1220. if (!string.IsNullOrEmpty(strQnameMinimization))
  1221. _dnsServer.QnameMinimization = bool.Parse(strQnameMinimization);
  1222. string strServeStale = request.QueryString["serveStale"];
  1223. if (!string.IsNullOrEmpty(strServeStale))
  1224. _dnsServer.ServeStale = bool.Parse(strServeStale);
  1225. string strServeStaleTtl = request.QueryString["serveStaleTtl"];
  1226. if (!string.IsNullOrEmpty(strServeStaleTtl))
  1227. _dnsServer.CacheZoneManager.ServeStaleTtl = uint.Parse(strServeStaleTtl);
  1228. string strCachePrefetchEligibility = request.QueryString["cachePrefetchEligibility"];
  1229. if (!string.IsNullOrEmpty(strCachePrefetchEligibility))
  1230. _dnsServer.CachePrefetchEligibility = int.Parse(strCachePrefetchEligibility);
  1231. string strCachePrefetchTrigger = request.QueryString["cachePrefetchTrigger"];
  1232. if (!string.IsNullOrEmpty(strCachePrefetchTrigger))
  1233. _dnsServer.CachePrefetchTrigger = int.Parse(strCachePrefetchTrigger);
  1234. string strCachePrefetchSampleIntervalInMinutes = request.QueryString["cachePrefetchSampleIntervalInMinutes"];
  1235. if (!string.IsNullOrEmpty(strCachePrefetchSampleIntervalInMinutes))
  1236. _dnsServer.CachePrefetchSampleIntervalInMinutes = int.Parse(strCachePrefetchSampleIntervalInMinutes);
  1237. string strCachePrefetchSampleEligibilityHitsPerHour = request.QueryString["cachePrefetchSampleEligibilityHitsPerHour"];
  1238. if (!string.IsNullOrEmpty(strCachePrefetchSampleEligibilityHitsPerHour))
  1239. _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = int.Parse(strCachePrefetchSampleEligibilityHitsPerHour);
  1240. string strProxyType = request.QueryString["proxyType"];
  1241. if (!string.IsNullOrEmpty(strProxyType))
  1242. {
  1243. NetProxyType proxyType = (NetProxyType)Enum.Parse(typeof(NetProxyType), strProxyType, true);
  1244. if (proxyType == NetProxyType.None)
  1245. {
  1246. _dnsServer.Proxy = null;
  1247. }
  1248. else
  1249. {
  1250. NetworkCredential credential = null;
  1251. string strUsername = request.QueryString["proxyUsername"];
  1252. if (!string.IsNullOrEmpty(strUsername))
  1253. credential = new NetworkCredential(strUsername, request.QueryString["proxyPassword"]);
  1254. _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, request.QueryString["proxyAddress"], int.Parse(request.QueryString["proxyPort"]), credential);
  1255. string strProxyBypass = request.QueryString["proxyBypass"];
  1256. if (!string.IsNullOrEmpty(strProxyBypass))
  1257. {
  1258. string[] strBypassList = strProxyBypass.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1259. List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(strBypassList.Length);
  1260. for (int i = 0; i < strBypassList.Length; i++)
  1261. bypassList.Add(new NetProxyBypassItem(strBypassList[i]));
  1262. _dnsServer.Proxy.BypassList = bypassList;
  1263. }
  1264. }
  1265. }
  1266. DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
  1267. string strForwarderProtocol = request.QueryString["forwarderProtocol"];
  1268. if (!string.IsNullOrEmpty(strForwarderProtocol))
  1269. forwarderProtocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strForwarderProtocol, true);
  1270. string strForwarders = request.QueryString["forwarders"];
  1271. if (!string.IsNullOrEmpty(strForwarders))
  1272. {
  1273. if (strForwarders == "false")
  1274. {
  1275. _dnsServer.Forwarders = null;
  1276. }
  1277. else
  1278. {
  1279. string[] strForwardersList = strForwarders.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1280. NameServerAddress[] forwarders = new NameServerAddress[strForwardersList.Length];
  1281. for (int i = 0; i < strForwardersList.Length; i++)
  1282. {
  1283. if ((forwarderProtocol == DnsTransportProtocol.Tls) && IPAddress.TryParse(strForwardersList[i], out _))
  1284. strForwardersList[i] += ":853";
  1285. forwarders[i] = new NameServerAddress(strForwardersList[i], forwarderProtocol);
  1286. }
  1287. _dnsServer.Forwarders = forwarders;
  1288. }
  1289. }
  1290. string strUseNxDomainForBlocking = request.QueryString["useNxDomainForBlocking"];
  1291. if (!string.IsNullOrEmpty(strUseNxDomainForBlocking))
  1292. _dnsServer.UseNxDomainForBlocking = bool.Parse(strUseNxDomainForBlocking);
  1293. string strBlockListUrls = request.QueryString["blockListUrls"];
  1294. if (!string.IsNullOrEmpty(strBlockListUrls))
  1295. {
  1296. if (strBlockListUrls == "false")
  1297. {
  1298. StopBlockListUpdateTimer();
  1299. _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
  1300. _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
  1301. _dnsServer.BlockListZoneManager.Flush();
  1302. }
  1303. else
  1304. {
  1305. bool updated = false;
  1306. string[] strBlockListUrlList = strBlockListUrls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1307. if (oldWebServiceHttpPort != _webServiceHttpPort)
  1308. {
  1309. for (int i = 0; i < strBlockListUrlList.Length; i++)
  1310. {
  1311. if (strBlockListUrlList[i].Contains("http://localhost:" + oldWebServiceHttpPort + "/blocklist.txt"))
  1312. {
  1313. strBlockListUrlList[i] = "http://localhost:" + _webServiceHttpPort + "/blocklist.txt";
  1314. updated = true;
  1315. break;
  1316. }
  1317. }
  1318. }
  1319. if (!updated)
  1320. {
  1321. if (strBlockListUrlList.Length != (_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count))
  1322. {
  1323. updated = true;
  1324. }
  1325. else
  1326. {
  1327. foreach (string strBlockListUrl in strBlockListUrlList)
  1328. {
  1329. if (strBlockListUrl.StartsWith("!"))
  1330. {
  1331. string strAllowListUrl = strBlockListUrl.Substring(1);
  1332. if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(new Uri(strAllowListUrl)))
  1333. {
  1334. updated = true;
  1335. break;
  1336. }
  1337. }
  1338. else
  1339. {
  1340. if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(new Uri(strBlockListUrl)))
  1341. {
  1342. updated = true;
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. }
  1349. if (updated)
  1350. {
  1351. _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
  1352. _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
  1353. foreach (string strBlockListUrl in strBlockListUrlList)
  1354. {
  1355. if (strBlockListUrl.StartsWith("!"))
  1356. {
  1357. Uri allowListUrl = new Uri(strBlockListUrl.Substring(1));
  1358. if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(allowListUrl))
  1359. _dnsServer.BlockListZoneManager.AllowListUrls.Add(allowListUrl);
  1360. }
  1361. else
  1362. {
  1363. Uri blockListUrl = new Uri(strBlockListUrl);
  1364. if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(blockListUrl))
  1365. _dnsServer.BlockListZoneManager.BlockListUrls.Add(blockListUrl);
  1366. }
  1367. }
  1368. ForceUpdateBlockLists();
  1369. }
  1370. }
  1371. }
  1372. string strBlockListUpdateIntervalHours = request.QueryString["blockListUpdateIntervalHours"];
  1373. if (!string.IsNullOrEmpty(strBlockListUpdateIntervalHours))
  1374. {
  1375. int blockListUpdateIntervalHours = int.Parse(strBlockListUpdateIntervalHours);
  1376. if ((blockListUpdateIntervalHours < 1) || (blockListUpdateIntervalHours > 168))
  1377. throw new ArgumentOutOfRangeException("Parameter `blockListUpdateIntervalHours` must be between 1 hour and 168 hours (7 days).");
  1378. _blockListUpdateIntervalHours = blockListUpdateIntervalHours;
  1379. }
  1380. SaveConfigFile();
  1381. _log.Save();
  1382. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS Settings were updated {dnsServerDomain: " + _dnsServer.ServerDomain + "; dnsServerLocalEndPoints: " + strDnsServerLocalEndPoints + "; webServiceLocalAddresses: " + strWebServiceLocalAddresses + "; webServiceHttpPort: " + _webServiceHttpPort + "; webServiceEnableTls: " + strWebServiceEnableTls + "; webServiceHttpToTlsRedirect: " + strWebServiceHttpToTlsRedirect + "; webServiceTlsPort: " + strWebServiceTlsPort + "; webServiceTlsCertificatePath: " + strWebServiceTlsCertificatePath + "; enableDnsOverHttp: " + _dnsServer.EnableDnsOverHttp + "; enableDnsOverTls: " + _dnsServer.EnableDnsOverTls + "; enableDnsOverHttps: " + _dnsServer.EnableDnsOverHttps + "; dnsTlsCertificatePath: " + _dnsTlsCertificatePath + "; preferIPv6: " + _dnsServer.PreferIPv6 + "; enableLogging: " + strEnableLogging + "; logQueries: " + (_dnsServer.QueryLogManager != null) + "; useLocalTime: " + strUseLocalTime + "; logFolder: " + strLogFolder + "; maxLogFileDays: " + strMaxLogFileDays + "; allowRecursion: " + _dnsServer.AllowRecursion + "; allowRecursionOnlyForPrivateNetworks: " + _dnsServer.AllowRecursionOnlyForPrivateNetworks + "; randomizeName: " + strRandomizeName + "; serveStale: " + strServeStale + "; serveStaleTtl: " + strServeStaleTtl + "; cachePrefetchEligibility: " + strCachePrefetchEligibility + "; cachePrefetchTrigger: " + strCachePrefetchTrigger + "; cachePrefetchSampleIntervalInMinutes: " + strCachePrefetchSampleIntervalInMinutes + "; cachePrefetchSampleEligibilityHitsPerHour: " + strCachePrefetchSampleEligibilityHitsPerHour + "; proxyType: " + strProxyType + "; forwarders: " + strForwarders + "; forwarderProtocol: " + strForwarderProtocol + "; blockListUrl: " + strBlockListUrls + "; blockListUpdateIntervalHours: " + strBlockListUpdateIntervalHours + ";}");
  1383. if ((_webServiceTlsCertificatePath == null) && (_dnsTlsCertificatePath == null))
  1384. StopTlsCertificateUpdateTimer();
  1385. GetDnsSettings(jsonWriter);
  1386. RestartService(restartDnsService, restartWebService);
  1387. }
  1388. private void RestartService(bool restartDnsService, bool restartWebService)
  1389. {
  1390. if (restartDnsService)
  1391. {
  1392. _ = Task.Run(delegate ()
  1393. {
  1394. _log.Write("Attempting to restart DNS service.");
  1395. try
  1396. {
  1397. _dnsServer.Stop();
  1398. _dnsServer.Start();
  1399. _log.Write("DNS service was restarted successfully.");
  1400. }
  1401. catch (Exception ex)
  1402. {
  1403. _log.Write("Failed to restart DNS service.");
  1404. _log.Write(ex);
  1405. }
  1406. });
  1407. }
  1408. if (restartWebService)
  1409. {
  1410. _ = Task.Run(async delegate ()
  1411. {
  1412. await Task.Delay(2000); //wait for this HTTP response to be delivered before stopping web server
  1413. _log.Write("Attempting to restart web service.");
  1414. try
  1415. {
  1416. StopDnsWebService();
  1417. StartDnsWebService();
  1418. _log.Write("Web service was restarted successfully.");
  1419. }
  1420. catch (Exception ex)
  1421. {
  1422. _log.Write("Failed to restart web service.");
  1423. _log.Write(ex);
  1424. }
  1425. });
  1426. }
  1427. }
  1428. private async Task BackupSettingsAsync(HttpListenerRequest request, HttpListenerResponse response)
  1429. {
  1430. bool blockLists = false;
  1431. bool logs = false;
  1432. bool scopes = false;
  1433. bool apps = false;
  1434. bool stats = false;
  1435. bool zones = false;
  1436. bool allowedZones = false;
  1437. bool blockedZones = false;
  1438. bool dnsSettings = false;
  1439. bool logSettings = false;
  1440. string strBlockLists = request.QueryString["blockLists"];
  1441. if (!string.IsNullOrEmpty(strBlockLists))
  1442. blockLists = bool.Parse(strBlockLists);
  1443. string strLogs = request.QueryString["logs"];
  1444. if (!string.IsNullOrEmpty(strLogs))
  1445. logs = bool.Parse(strLogs);
  1446. string strScopes = request.QueryString["scopes"];
  1447. if (!string.IsNullOrEmpty(strScopes))
  1448. scopes = bool.Parse(strScopes);
  1449. string strApps = request.QueryString["apps"];
  1450. if (!string.IsNullOrEmpty(strApps))
  1451. apps = bool.Parse(strApps);
  1452. string strStats = request.QueryString["stats"];
  1453. if (!string.IsNullOrEmpty(strStats))
  1454. stats = bool.Parse(strStats);
  1455. string strZones = request.QueryString["zones"];
  1456. if (!string.IsNullOrEmpty(strZones))
  1457. zones = bool.Parse(strZones);
  1458. string strAllowedZones = request.QueryString["allowedZones"];
  1459. if (!string.IsNullOrEmpty(strAllowedZones))
  1460. allowedZones = bool.Parse(strAllowedZones);
  1461. string strBlockedZones = request.QueryString["blockedZones"];
  1462. if (!string.IsNullOrEmpty(strBlockedZones))
  1463. blockedZones = bool.Parse(strBlockedZones);
  1464. string strDnsSettings = request.QueryString["dnsSettings"];
  1465. if (!string.IsNullOrEmpty(strDnsSettings))
  1466. dnsSettings = bool.Parse(strDnsSettings);
  1467. string strLogSettings = request.QueryString["logSettings"];
  1468. if (!string.IsNullOrEmpty(strLogSettings))
  1469. logSettings = bool.Parse(strLogSettings);
  1470. string tmpFile = Path.GetTempFileName();
  1471. try
  1472. {
  1473. using (FileStream backupZipStream = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  1474. {
  1475. //create backup zip
  1476. using (ZipArchive backupZip = new ZipArchive(backupZipStream, ZipArchiveMode.Create, true, Encoding.UTF8))
  1477. {
  1478. if (blockLists)
  1479. {
  1480. string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
  1481. foreach (string blockListFile in blockListFiles)
  1482. {
  1483. string entryName = "blocklists/" + Path.GetFileName(blockListFile);
  1484. backupZip.CreateEntryFromFile(blockListFile, entryName);
  1485. }
  1486. }
  1487. if (logs)
  1488. {
  1489. string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
  1490. foreach (string logFile in logFiles)
  1491. {
  1492. string entryName = "logs/" + Path.GetFileName(logFile);
  1493. if (logFile.Equals(_log.CurrentLogFile, StringComparison.OrdinalIgnoreCase))
  1494. {
  1495. using (FileStream fS = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  1496. {
  1497. ZipArchiveEntry entry = backupZip.CreateEntry(entryName);
  1498. using (Stream s = entry.Open())
  1499. {
  1500. await fS.CopyToAsync(s);
  1501. }
  1502. }
  1503. }
  1504. else
  1505. {
  1506. backupZip.CreateEntryFromFile(logFile, entryName);
  1507. }
  1508. }
  1509. }
  1510. if (scopes)
  1511. {
  1512. string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
  1513. foreach (string scopeFile in scopeFiles)
  1514. {
  1515. string entryName = "scopes/" + Path.GetFileName(scopeFile);
  1516. backupZip.CreateEntryFromFile(scopeFile, entryName);
  1517. }
  1518. }
  1519. if (apps)
  1520. {
  1521. string[] appFiles = Directory.GetFiles(Path.Combine(_configFolder, "apps"), "*", SearchOption.AllDirectories);
  1522. foreach (string appFile in appFiles)
  1523. {
  1524. string entryName = appFile.Substring(_configFolder.Length);
  1525. if (Path.DirectorySeparatorChar != '/')
  1526. entryName = entryName.Replace(Path.DirectorySeparatorChar, '/');
  1527. entryName = entryName.TrimStart('/');
  1528. backupZip.CreateEntryFromFile(appFile, entryName);
  1529. }
  1530. }
  1531. if (stats)
  1532. {
  1533. string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
  1534. foreach (string hourlyStatsFile in hourlyStatsFiles)
  1535. {
  1536. string entryName = "stats/" + Path.GetFileName(hourlyStatsFile);
  1537. backupZip.CreateEntryFromFile(hourlyStatsFile, entryName);
  1538. }
  1539. string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
  1540. foreach (string dailyStatsFile in dailyStatsFiles)
  1541. {
  1542. string entryName = "stats/" + Path.GetFileName(dailyStatsFile);
  1543. backupZip.CreateEntryFromFile(dailyStatsFile, entryName);
  1544. }
  1545. }
  1546. if (zones)
  1547. {
  1548. string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
  1549. foreach (string zoneFile in zoneFiles)
  1550. {
  1551. string entryName = "zones/" + Path.GetFileName(zoneFile);
  1552. backupZip.CreateEntryFromFile(zoneFile, entryName);
  1553. }
  1554. }
  1555. if (allowedZones)
  1556. {
  1557. string allowedZonesFile = Path.Combine(_configFolder, "allowed.config");
  1558. if (File.Exists(allowedZonesFile))
  1559. backupZip.CreateEntryFromFile(allowedZonesFile, "allowed.config");
  1560. }
  1561. if (blockedZones)
  1562. {
  1563. string blockedZonesFile = Path.Combine(_configFolder, "blocked.config");
  1564. if (File.Exists(blockedZonesFile))
  1565. backupZip.CreateEntryFromFile(blockedZonesFile, "blocked.config");
  1566. }
  1567. if (dnsSettings)
  1568. {
  1569. string dnsSettingsFile = Path.Combine(_configFolder, "dns.config");
  1570. if (File.Exists(dnsSettingsFile))
  1571. backupZip.CreateEntryFromFile(dnsSettingsFile, "dns.config");
  1572. }
  1573. if (logSettings)
  1574. {
  1575. string logSettingsFile = Path.Combine(_configFolder, "log.config");
  1576. if (File.Exists(logSettingsFile))
  1577. backupZip.CreateEntryFromFile(logSettingsFile, "log.config");
  1578. }
  1579. }
  1580. //send zip file
  1581. backupZipStream.Position = 0;
  1582. response.ContentType = "application/zip";
  1583. response.ContentLength64 = backupZipStream.Length;
  1584. response.AddHeader("Content-Disposition", "attachment;filename=DnsServerBackup.zip");
  1585. using (Stream output = response.OutputStream)
  1586. {
  1587. await backupZipStream.CopyToAsync(output);
  1588. }
  1589. }
  1590. }
  1591. finally
  1592. {
  1593. try
  1594. {
  1595. File.Delete(tmpFile);
  1596. }
  1597. catch (Exception ex)
  1598. {
  1599. _log.Write(ex);
  1600. }
  1601. }
  1602. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was exported.");
  1603. }
  1604. private async Task RestoreSettingsAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
  1605. {
  1606. bool blockLists = false;
  1607. bool logs = false;
  1608. bool scopes = false;
  1609. bool apps = false;
  1610. bool stats = false;
  1611. bool zones = false;
  1612. bool allowedZones = false;
  1613. bool blockedZones = false;
  1614. bool dnsSettings = false;
  1615. bool logSettings = false;
  1616. bool deleteExistingFiles = false;
  1617. string strBlockLists = request.QueryString["blockLists"];
  1618. if (!string.IsNullOrEmpty(strBlockLists))
  1619. blockLists = bool.Parse(strBlockLists);
  1620. string strLogs = request.QueryString["logs"];
  1621. if (!string.IsNullOrEmpty(strLogs))
  1622. logs = bool.Parse(strLogs);
  1623. string strScopes = request.QueryString["scopes"];
  1624. if (!string.IsNullOrEmpty(strScopes))
  1625. scopes = bool.Parse(strScopes);
  1626. string strApps = request.QueryString["apps"];
  1627. if (!string.IsNullOrEmpty(strApps))
  1628. apps = bool.Parse(strApps);
  1629. string strStats = request.QueryString["stats"];
  1630. if (!string.IsNullOrEmpty(strStats))
  1631. stats = bool.Parse(strStats);
  1632. string strZones = request.QueryString["zones"];
  1633. if (!string.IsNullOrEmpty(strZones))
  1634. zones = bool.Parse(strZones);
  1635. string strAllowedZones = request.QueryString["allowedZones"];
  1636. if (!string.IsNullOrEmpty(strAllowedZones))
  1637. allowedZones = bool.Parse(strAllowedZones);
  1638. string strBlockedZones = request.QueryString["blockedZones"];
  1639. if (!string.IsNullOrEmpty(strBlockedZones))
  1640. blockedZones = bool.Parse(strBlockedZones);
  1641. string strDnsSettings = request.QueryString["dnsSettings"];
  1642. if (!string.IsNullOrEmpty(strDnsSettings))
  1643. dnsSettings = bool.Parse(strDnsSettings);
  1644. string strLogSettings = request.QueryString["logSettings"];
  1645. if (!string.IsNullOrEmpty(strLogSettings))
  1646. logSettings = bool.Parse(strLogSettings);
  1647. string strDeleteExistingFiles = request.QueryString["deleteExistingFiles"];
  1648. if (!string.IsNullOrEmpty(strDeleteExistingFiles))
  1649. deleteExistingFiles = bool.Parse(strDeleteExistingFiles);
  1650. #region skip to content
  1651. int crlfCount = 0;
  1652. int byteRead;
  1653. while (crlfCount != 4)
  1654. {
  1655. byteRead = request.InputStream.ReadByte();
  1656. switch (byteRead)
  1657. {
  1658. case -1:
  1659. throw new EndOfStreamException();
  1660. case 13: //CR
  1661. case 10: //LF
  1662. crlfCount++;
  1663. break;
  1664. default:
  1665. crlfCount = 0;
  1666. break;
  1667. }
  1668. }
  1669. #endregion
  1670. //write to temp file
  1671. string tmpFile = Path.GetTempFileName();
  1672. try
  1673. {
  1674. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  1675. {
  1676. await request.InputStream.CopyToAsync(fS);
  1677. fS.Position = 0;
  1678. using (ZipArchive backupZip = new ZipArchive(fS, ZipArchiveMode.Read, false, Encoding.UTF8))
  1679. {
  1680. if (logSettings || logs)
  1681. {
  1682. //stop logging
  1683. _log.StopLogging();
  1684. }
  1685. try
  1686. {
  1687. if (logSettings)
  1688. {
  1689. ZipArchiveEntry entry = backupZip.GetEntry("log.config");
  1690. if (entry != null)
  1691. entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
  1692. //reload config
  1693. _log.LoadConfig();
  1694. }
  1695. if (logs)
  1696. {
  1697. if (deleteExistingFiles)
  1698. {
  1699. //delete existing log files
  1700. string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
  1701. foreach (string logFile in logFiles)
  1702. {
  1703. File.Delete(logFile);
  1704. }
  1705. }
  1706. //extract log files from backup
  1707. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1708. {
  1709. if (entry.FullName.StartsWith("logs/"))
  1710. entry.ExtractToFile(Path.Combine(_log.LogFolderAbsolutePath, entry.Name), true);
  1711. }
  1712. }
  1713. }
  1714. finally
  1715. {
  1716. if (logSettings || logs)
  1717. {
  1718. //start logging
  1719. if (_log.EnableLogging)
  1720. _log.StartLogging();
  1721. }
  1722. }
  1723. if (blockLists)
  1724. {
  1725. if (deleteExistingFiles)
  1726. {
  1727. //delete existing block list files
  1728. string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
  1729. foreach (string blockListFile in blockListFiles)
  1730. {
  1731. File.Delete(blockListFile);
  1732. }
  1733. }
  1734. //extract block list files from backup
  1735. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1736. {
  1737. if (entry.FullName.StartsWith("blocklists/"))
  1738. entry.ExtractToFile(Path.Combine(_configFolder, "blocklists", entry.Name), true);
  1739. }
  1740. }
  1741. if (scopes)
  1742. {
  1743. //stop dhcp server
  1744. _dhcpServer.Stop();
  1745. try
  1746. {
  1747. if (deleteExistingFiles)
  1748. {
  1749. //delete existing scope files
  1750. string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
  1751. foreach (string scopeFile in scopeFiles)
  1752. {
  1753. File.Delete(scopeFile);
  1754. }
  1755. }
  1756. //extract scope files from backup
  1757. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1758. {
  1759. if (entry.FullName.StartsWith("scopes/"))
  1760. entry.ExtractToFile(Path.Combine(_configFolder, "scopes", entry.Name), true);
  1761. }
  1762. }
  1763. finally
  1764. {
  1765. //start dhcp server
  1766. _dhcpServer.Start();
  1767. }
  1768. }
  1769. if (apps)
  1770. {
  1771. //unload apps
  1772. _dnsServer.DnsApplicationManager.UnloadAllApplications();
  1773. if (deleteExistingFiles)
  1774. {
  1775. //delete existing apps
  1776. string appFolder = Path.Combine(_configFolder, "apps");
  1777. if (Directory.Exists(appFolder))
  1778. Directory.Delete(appFolder, true);
  1779. }
  1780. //extract apps files from backup
  1781. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1782. {
  1783. if (entry.FullName.StartsWith("apps/"))
  1784. {
  1785. string entryPath = entry.FullName;
  1786. if (Path.DirectorySeparatorChar != '/')
  1787. entryPath = entryPath.Replace('/', '\\');
  1788. string filePath = Path.Combine(_configFolder, entryPath);
  1789. Directory.CreateDirectory(Path.GetDirectoryName(filePath));
  1790. entry.ExtractToFile(filePath, true);
  1791. }
  1792. }
  1793. //reload apps
  1794. _dnsServer.DnsApplicationManager.LoadAllApplications();
  1795. }
  1796. if (stats)
  1797. {
  1798. if (deleteExistingFiles)
  1799. {
  1800. //delete existing stats files
  1801. string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
  1802. foreach (string hourlyStatsFile in hourlyStatsFiles)
  1803. {
  1804. File.Delete(hourlyStatsFile);
  1805. }
  1806. string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
  1807. foreach (string dailyStatsFile in dailyStatsFiles)
  1808. {
  1809. File.Delete(dailyStatsFile);
  1810. }
  1811. }
  1812. //extract stats files from backup
  1813. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1814. {
  1815. if (entry.FullName.StartsWith("stats/"))
  1816. entry.ExtractToFile(Path.Combine(_configFolder, "stats", entry.Name), true);
  1817. }
  1818. //reload stats
  1819. _dnsServer.StatsManager.ReloadStats();
  1820. }
  1821. if (zones)
  1822. {
  1823. if (deleteExistingFiles)
  1824. {
  1825. //delete existing zone files
  1826. string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
  1827. foreach (string zoneFile in zoneFiles)
  1828. {
  1829. File.Delete(zoneFile);
  1830. }
  1831. }
  1832. //extract zone files from backup
  1833. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1834. {
  1835. if (entry.FullName.StartsWith("zones/"))
  1836. entry.ExtractToFile(Path.Combine(_configFolder, "zones", entry.Name), true);
  1837. }
  1838. //reload zones
  1839. _dnsServer.AuthZoneManager.LoadAllZoneFiles();
  1840. }
  1841. if (allowedZones)
  1842. {
  1843. ZipArchiveEntry entry = backupZip.GetEntry("allowed.config");
  1844. if (entry == null)
  1845. {
  1846. string fileName = Path.Combine(_configFolder, "allowed.config");
  1847. if (File.Exists(fileName))
  1848. File.Delete(fileName);
  1849. }
  1850. else
  1851. {
  1852. entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
  1853. }
  1854. //reload
  1855. _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
  1856. }
  1857. if (blockedZones)
  1858. {
  1859. ZipArchiveEntry entry = backupZip.GetEntry("blocked.config");
  1860. if (entry == null)
  1861. {
  1862. string fileName = Path.Combine(_configFolder, "allowed.config");
  1863. if (File.Exists(fileName))
  1864. File.Delete(fileName);
  1865. }
  1866. else
  1867. {
  1868. entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
  1869. }
  1870. //reload
  1871. _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
  1872. }
  1873. if (dnsSettings)
  1874. {
  1875. ZipArchiveEntry entry = backupZip.GetEntry("dns.config");
  1876. if (entry != null)
  1877. entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
  1878. //reload settings and block list zone
  1879. LoadConfigFile();
  1880. _dnsServer.BlockListZoneManager.LoadBlockLists();
  1881. }
  1882. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was restored.");
  1883. }
  1884. }
  1885. }
  1886. finally
  1887. {
  1888. try
  1889. {
  1890. File.Delete(tmpFile);
  1891. }
  1892. catch (Exception ex)
  1893. {
  1894. _log.Write(ex);
  1895. }
  1896. }
  1897. if (dnsSettings)
  1898. RestartService(true, true);
  1899. GetDnsSettings(jsonWriter);
  1900. }
  1901. private void ForceUpdateBlockLists(HttpListenerRequest request)
  1902. {
  1903. ForceUpdateBlockLists();
  1904. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Block list update was triggered.");
  1905. }
  1906. #endregion
  1907. #region dashboard
  1908. private async Task GetStats(HttpListenerRequest request, JsonTextWriter jsonWriter)
  1909. {
  1910. string strType = request.QueryString["type"];
  1911. if (string.IsNullOrEmpty(strType))
  1912. strType = "lastHour";
  1913. Dictionary<string, List<KeyValuePair<string, int>>> data;
  1914. switch (strType)
  1915. {
  1916. case "lastHour":
  1917. data = _dnsServer.StatsManager.GetLastHourMinuteWiseStats();
  1918. break;
  1919. case "lastDay":
  1920. data = _dnsServer.StatsManager.GetLastDayHourWiseStats();
  1921. break;
  1922. case "lastWeek":
  1923. data = _dnsServer.StatsManager.GetLastWeekDayWiseStats();
  1924. break;
  1925. case "lastMonth":
  1926. data = _dnsServer.StatsManager.GetLastMonthDayWiseStats();
  1927. break;
  1928. case "lastYear":
  1929. data = _dnsServer.StatsManager.GetLastYearMonthWiseStats();
  1930. break;
  1931. case "custom":
  1932. string strStartDate = request.QueryString["start"];
  1933. if (string.IsNullOrEmpty(strStartDate))
  1934. throw new DnsWebServiceException("Parameter 'start' missing.");
  1935. string strEndDate = request.QueryString["end"];
  1936. if (string.IsNullOrEmpty(strEndDate))
  1937. throw new DnsWebServiceException("Parameter 'end' missing.");
  1938. if (!DateTime.TryParseExact(strStartDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
  1939. throw new DnsWebServiceException("Invalid start date format.");
  1940. if (!DateTime.TryParseExact(strEndDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
  1941. throw new DnsWebServiceException("Invalid end date format.");
  1942. if (startDate > endDate)
  1943. throw new DnsWebServiceException("Start date must be less than or equal to end date.");
  1944. if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
  1945. data = _dnsServer.StatsManager.GetDayWiseStats(startDate, endDate);
  1946. else
  1947. data = _dnsServer.StatsManager.GetHourWiseStats(startDate, endDate);
  1948. break;
  1949. default:
  1950. throw new DnsWebServiceException("Unknown stats type requested: " + strType);
  1951. }
  1952. //stats
  1953. {
  1954. List<KeyValuePair<string, int>> stats = data["stats"];
  1955. jsonWriter.WritePropertyName("stats");
  1956. jsonWriter.WriteStartObject();
  1957. foreach (KeyValuePair<string, int> item in stats)
  1958. {
  1959. jsonWriter.WritePropertyName(item.Key);
  1960. jsonWriter.WriteValue(item.Value);
  1961. }
  1962. jsonWriter.WritePropertyName("zones");
  1963. jsonWriter.WriteValue(_dnsServer.AuthZoneManager.TotalZones);
  1964. jsonWriter.WritePropertyName("allowedZones");
  1965. jsonWriter.WriteValue(_dnsServer.AllowedZoneManager.TotalZonesAllowed);
  1966. jsonWriter.WritePropertyName("blockedZones");
  1967. jsonWriter.WriteValue(_dnsServer.BlockedZoneManager.TotalZonesBlocked);
  1968. jsonWriter.WritePropertyName("blockListZones");
  1969. jsonWriter.WriteValue(_dnsServer.BlockListZoneManager.TotalZonesBlocked);
  1970. jsonWriter.WriteEndObject();
  1971. }
  1972. //main chart
  1973. {
  1974. jsonWriter.WritePropertyName("mainChartData");
  1975. jsonWriter.WriteStartObject();
  1976. //label
  1977. {
  1978. List<KeyValuePair<string, int>> statsPerInterval = data["totalQueriesPerInterval"];
  1979. jsonWriter.WritePropertyName("labels");
  1980. jsonWriter.WriteStartArray();
  1981. foreach (KeyValuePair<string, int> item in statsPerInterval)
  1982. jsonWriter.WriteValue(item.Key);
  1983. jsonWriter.WriteEndArray();
  1984. }
  1985. //datasets
  1986. {
  1987. jsonWriter.WritePropertyName("datasets");
  1988. jsonWriter.WriteStartArray();
  1989. WriteChartDataSet(jsonWriter, "Total", "rgba(102, 153, 255, 0.1)", "rgb(102, 153, 255)", data["totalQueriesPerInterval"]);
  1990. WriteChartDataSet(jsonWriter, "No Error", "rgba(92, 184, 92, 0.1)", "rgb(92, 184, 92)", data["totalNoErrorPerInterval"]);
  1991. WriteChartDataSet(jsonWriter, "Server Failure", "rgba(217, 83, 79, 0.1)", "rgb(217, 83, 79)", data["totalServerFailurePerInterval"]);
  1992. WriteChartDataSet(jsonWriter, "NX Domain", "rgba(7, 7, 7, 0.1)", "rgb(7, 7, 7)", data["totalNxDomainPerInterval"]);
  1993. WriteChartDataSet(jsonWriter, "Refused", "rgba(91, 192, 222, 0.1)", "rgb(91, 192, 222)", data["totalRefusedPerInterval"]);
  1994. WriteChartDataSet(jsonWriter, "Authoritative", "rgba(150, 150, 0, 0.1)", "rgb(150, 150, 0)", data["totalAuthHitPerInterval"]);
  1995. WriteChartDataSet(jsonWriter, "Recursive", "rgba(23, 162, 184, 0.1)", "rgb(23, 162, 184)", data["totalRecursionsPerInterval"]);
  1996. WriteChartDataSet(jsonWriter, "Cached", "rgba(111, 84, 153, 0.1)", "rgb(111, 84, 153)", data["totalCacheHitPerInterval"]);
  1997. WriteChartDataSet(jsonWriter, "Blocked", "rgba(255, 165, 0, 0.1)", "rgb(255, 165, 0)", data["totalBlockedPerInterval"]);
  1998. WriteChartDataSet(jsonWriter, "Clients", "rgba(51, 122, 183, 0.1)", "rgb(51, 122, 183)", data["totalClientsPerInterval"]);
  1999. jsonWriter.WriteEndArray();
  2000. }
  2001. jsonWriter.WriteEndObject();
  2002. }
  2003. //query response chart
  2004. {
  2005. jsonWriter.WritePropertyName("queryResponseChartData");
  2006. jsonWriter.WriteStartObject();
  2007. List<KeyValuePair<string, int>> stats = data["stats"];
  2008. //labels
  2009. {
  2010. jsonWriter.WritePropertyName("labels");
  2011. jsonWriter.WriteStartArray();
  2012. foreach (KeyValuePair<string, int> item in stats)
  2013. {
  2014. switch (item.Key)
  2015. {
  2016. case "totalAuthoritative":
  2017. jsonWriter.WriteValue("Authoritative");
  2018. break;
  2019. case "totalRecursive":
  2020. jsonWriter.WriteValue("Recursive");
  2021. break;
  2022. case "totalCached":
  2023. jsonWriter.WriteValue("Cached");
  2024. break;
  2025. case "totalBlocked":
  2026. jsonWriter.WriteValue("Blocked");
  2027. break;
  2028. }
  2029. }
  2030. jsonWriter.WriteEndArray();
  2031. }
  2032. //datasets
  2033. {
  2034. jsonWriter.WritePropertyName("datasets");
  2035. jsonWriter.WriteStartArray();
  2036. jsonWriter.WriteStartObject();
  2037. jsonWriter.WritePropertyName("data");
  2038. jsonWriter.WriteStartArray();
  2039. foreach (KeyValuePair<string, int> item in stats)
  2040. {
  2041. switch (item.Key)
  2042. {
  2043. case "totalAuthoritative":
  2044. case "totalRecursive":
  2045. case "totalCached":
  2046. case "totalBlocked":
  2047. jsonWriter.WriteValue(item.Value);
  2048. break;
  2049. }
  2050. }
  2051. jsonWriter.WriteEndArray();
  2052. jsonWriter.WritePropertyName("backgroundColor");
  2053. jsonWriter.WriteStartArray();
  2054. jsonWriter.WriteValue("rgba(150, 150, 0, 0.5)");
  2055. jsonWriter.WriteValue("rgba(23, 162, 184, 0.5)");
  2056. jsonWriter.WriteValue("rgba(111, 84, 153, 0.5)");
  2057. jsonWriter.WriteValue("rgba(255, 165, 0, 0.5)");
  2058. jsonWriter.WriteEndArray();
  2059. jsonWriter.WriteEndObject();
  2060. jsonWriter.WriteEndArray();
  2061. }
  2062. jsonWriter.WriteEndObject();
  2063. }
  2064. //query type chart
  2065. {
  2066. jsonWriter.WritePropertyName("queryTypeChartData");
  2067. jsonWriter.WriteStartObject();
  2068. List<KeyValuePair<string, int>> queryTypes = data["queryTypes"];
  2069. //labels
  2070. {
  2071. jsonWriter.WritePropertyName("labels");
  2072. jsonWriter.WriteStartArray();
  2073. foreach (KeyValuePair<string, int> item in queryTypes)
  2074. jsonWriter.WriteValue(item.Key);
  2075. jsonWriter.WriteEndArray();
  2076. }
  2077. //datasets
  2078. {
  2079. jsonWriter.WritePropertyName("datasets");
  2080. jsonWriter.WriteStartArray();
  2081. jsonWriter.WriteStartObject();
  2082. jsonWriter.WritePropertyName("data");
  2083. jsonWriter.WriteStartArray();
  2084. foreach (KeyValuePair<string, int> item in queryTypes)
  2085. jsonWriter.WriteValue(item.Value);
  2086. jsonWriter.WriteEndArray();
  2087. jsonWriter.WritePropertyName("backgroundColor");
  2088. jsonWriter.WriteStartArray();
  2089. jsonWriter.WriteValue("rgba(102, 153, 255, 0.5)");
  2090. jsonWriter.WriteValue("rgba(92, 184, 92, 0.5)");
  2091. jsonWriter.WriteValue("rgba(7, 7, 7, 0.5)");
  2092. jsonWriter.WriteValue("rgba(91, 192, 222, 0.5)");
  2093. jsonWriter.WriteValue("rgba(150, 150, 0, 0.5)");
  2094. jsonWriter.WriteValue("rgba(23, 162, 184, 0.5)");
  2095. jsonWriter.WriteValue("rgba(111, 84, 153, 0.5)");
  2096. jsonWriter.WriteValue("rgba(255, 165, 0, 0.5)");
  2097. jsonWriter.WriteValue("rgba(51, 122, 183, 0.5)");
  2098. jsonWriter.WriteValue("rgba(150, 150, 150, 0.5)");
  2099. jsonWriter.WriteEndArray();
  2100. jsonWriter.WriteEndObject();
  2101. jsonWriter.WriteEndArray();
  2102. }
  2103. jsonWriter.WriteEndObject();
  2104. }
  2105. //top clients
  2106. {
  2107. List<KeyValuePair<string, int>> topClients = data["topClients"];
  2108. IDictionary<string, string> clientIpMap = await ResolvePtrTopClientsAsync(topClients);
  2109. jsonWriter.WritePropertyName("topClients");
  2110. jsonWriter.WriteStartArray();
  2111. foreach (KeyValuePair<string, int> item in topClients)
  2112. {
  2113. jsonWriter.WriteStartObject();
  2114. jsonWriter.WritePropertyName("name");
  2115. jsonWriter.WriteValue(item.Key);
  2116. if (clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
  2117. {
  2118. jsonWriter.WritePropertyName("domain");
  2119. jsonWriter.WriteValue(clientDomain);
  2120. }
  2121. jsonWriter.WritePropertyName("hits");
  2122. jsonWriter.WriteValue(item.Value);
  2123. jsonWriter.WriteEndObject();
  2124. }
  2125. jsonWriter.WriteEndArray();
  2126. }
  2127. //top domains
  2128. {
  2129. List<KeyValuePair<string, int>> topDomains = data["topDomains"];
  2130. jsonWriter.WritePropertyName("topDomains");
  2131. jsonWriter.WriteStartArray();
  2132. foreach (KeyValuePair<string, int> item in topDomains)
  2133. {
  2134. jsonWriter.WriteStartObject();
  2135. jsonWriter.WritePropertyName("name");
  2136. jsonWriter.WriteValue(item.Key);
  2137. jsonWriter.WritePropertyName("hits");
  2138. jsonWriter.WriteValue(item.Value);
  2139. jsonWriter.WriteEndObject();
  2140. }
  2141. jsonWriter.WriteEndArray();
  2142. }
  2143. //top blocked domains
  2144. {
  2145. List<KeyValuePair<string, int>> topBlockedDomains = data["topBlockedDomains"];
  2146. jsonWriter.WritePropertyName("topBlockedDomains");
  2147. jsonWriter.WriteStartArray();
  2148. foreach (KeyValuePair<string, int> item in topBlockedDomains)
  2149. {
  2150. jsonWriter.WriteStartObject();
  2151. jsonWriter.WritePropertyName("name");
  2152. jsonWriter.WriteValue(item.Key);
  2153. jsonWriter.WritePropertyName("hits");
  2154. jsonWriter.WriteValue(item.Value);
  2155. jsonWriter.WriteEndObject();
  2156. }
  2157. jsonWriter.WriteEndArray();
  2158. }
  2159. }
  2160. private static void WriteChartDataSet(JsonTextWriter jsonWriter, string label, string backgroundColor, string borderColor, List<KeyValuePair<string, int>> statsPerInterval)
  2161. {
  2162. jsonWriter.WriteStartObject();
  2163. jsonWriter.WritePropertyName("label");
  2164. jsonWriter.WriteValue(label);
  2165. jsonWriter.WritePropertyName("backgroundColor");
  2166. jsonWriter.WriteValue(backgroundColor);
  2167. jsonWriter.WritePropertyName("borderColor");
  2168. jsonWriter.WriteValue(borderColor);
  2169. jsonWriter.WritePropertyName("borderWidth");
  2170. jsonWriter.WriteValue(2);
  2171. jsonWriter.WritePropertyName("fill");
  2172. jsonWriter.WriteValue(true);
  2173. jsonWriter.WritePropertyName("data");
  2174. jsonWriter.WriteStartArray();
  2175. foreach (KeyValuePair<string, int> item in statsPerInterval)
  2176. jsonWriter.WriteValue(item.Value);
  2177. jsonWriter.WriteEndArray();
  2178. jsonWriter.WriteEndObject();
  2179. }
  2180. private async Task GetTopStats(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2181. {
  2182. string strType = request.QueryString["type"];
  2183. if (string.IsNullOrEmpty(strType))
  2184. strType = "lastHour";
  2185. string strStatsType = request.QueryString["statsType"];
  2186. if (string.IsNullOrEmpty(strStatsType))
  2187. throw new DnsWebServiceException("Parameter 'statsType' missing.");
  2188. string strLimit = request.QueryString["limit"];
  2189. if (string.IsNullOrEmpty(strLimit))
  2190. strLimit = "1000";
  2191. TopStatsType statsType = (TopStatsType)Enum.Parse(typeof(TopStatsType), strStatsType, true);
  2192. int limit = int.Parse(strLimit);
  2193. List<KeyValuePair<string, int>> topStatsData;
  2194. switch (strType)
  2195. {
  2196. case "lastHour":
  2197. topStatsData = _dnsServer.StatsManager.GetLastHourTopStats(statsType, limit);
  2198. break;
  2199. case "lastDay":
  2200. topStatsData = _dnsServer.StatsManager.GetLastDayTopStats(statsType, limit);
  2201. break;
  2202. case "lastWeek":
  2203. topStatsData = _dnsServer.StatsManager.GetLastWeekTopStats(statsType, limit);
  2204. break;
  2205. case "lastMonth":
  2206. topStatsData = _dnsServer.StatsManager.GetLastMonthTopStats(statsType, limit);
  2207. break;
  2208. case "lastYear":
  2209. topStatsData = _dnsServer.StatsManager.GetLastYearTopStats(statsType, limit);
  2210. break;
  2211. case "custom":
  2212. string strStartDate = request.QueryString["start"];
  2213. if (string.IsNullOrEmpty(strStartDate))
  2214. throw new DnsWebServiceException("Parameter 'start' missing.");
  2215. string strEndDate = request.QueryString["end"];
  2216. if (string.IsNullOrEmpty(strEndDate))
  2217. throw new DnsWebServiceException("Parameter 'end' missing.");
  2218. if (!DateTime.TryParseExact(strStartDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
  2219. throw new DnsWebServiceException("Invalid start date format.");
  2220. if (!DateTime.TryParseExact(strEndDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
  2221. throw new DnsWebServiceException("Invalid end date format.");
  2222. if (startDate > endDate)
  2223. throw new DnsWebServiceException("Start date must be less than or equal to end date.");
  2224. if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
  2225. topStatsData = _dnsServer.StatsManager.GetDayWiseTopStats(startDate, endDate, statsType, limit);
  2226. else
  2227. topStatsData = _dnsServer.StatsManager.GetHourWiseTopStats(startDate, endDate, statsType, limit);
  2228. break;
  2229. default:
  2230. throw new DnsWebServiceException("Unknown stats type requested: " + strType);
  2231. }
  2232. switch (statsType)
  2233. {
  2234. case TopStatsType.TopClients:
  2235. {
  2236. IDictionary<string, string> clientIpMap = await ResolvePtrTopClientsAsync(topStatsData);
  2237. jsonWriter.WritePropertyName("topClients");
  2238. jsonWriter.WriteStartArray();
  2239. foreach (KeyValuePair<string, int> item in topStatsData)
  2240. {
  2241. jsonWriter.WriteStartObject();
  2242. jsonWriter.WritePropertyName("name");
  2243. jsonWriter.WriteValue(item.Key);
  2244. if (clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
  2245. {
  2246. jsonWriter.WritePropertyName("domain");
  2247. jsonWriter.WriteValue(clientDomain);
  2248. }
  2249. jsonWriter.WritePropertyName("hits");
  2250. jsonWriter.WriteValue(item.Value);
  2251. jsonWriter.WriteEndObject();
  2252. }
  2253. jsonWriter.WriteEndArray();
  2254. }
  2255. break;
  2256. case TopStatsType.TopDomains:
  2257. {
  2258. jsonWriter.WritePropertyName("topDomains");
  2259. jsonWriter.WriteStartArray();
  2260. foreach (KeyValuePair<string, int> item in topStatsData)
  2261. {
  2262. jsonWriter.WriteStartObject();
  2263. jsonWriter.WritePropertyName("name");
  2264. jsonWriter.WriteValue(item.Key);
  2265. jsonWriter.WritePropertyName("hits");
  2266. jsonWriter.WriteValue(item.Value);
  2267. jsonWriter.WriteEndObject();
  2268. }
  2269. jsonWriter.WriteEndArray();
  2270. }
  2271. break;
  2272. case TopStatsType.TopBlockedDomains:
  2273. {
  2274. jsonWriter.WritePropertyName("topBlockedDomains");
  2275. jsonWriter.WriteStartArray();
  2276. foreach (KeyValuePair<string, int> item in topStatsData)
  2277. {
  2278. jsonWriter.WriteStartObject();
  2279. jsonWriter.WritePropertyName("name");
  2280. jsonWriter.WriteValue(item.Key);
  2281. jsonWriter.WritePropertyName("hits");
  2282. jsonWriter.WriteValue(item.Value);
  2283. jsonWriter.WriteEndObject();
  2284. }
  2285. jsonWriter.WriteEndArray();
  2286. }
  2287. break;
  2288. default:
  2289. throw new NotSupportedException();
  2290. }
  2291. }
  2292. private async Task<IDictionary<string, string>> ResolvePtrTopClientsAsync(List<KeyValuePair<string, int>> topClients)
  2293. {
  2294. IDictionary<string, string> dhcpClientIpMap = _dhcpServer.GetAddressHostNameMap();
  2295. async Task<KeyValuePair<string, string>> ResolvePtrAsync(string ip)
  2296. {
  2297. if (dhcpClientIpMap.TryGetValue(ip, out string dhcpDomain))
  2298. return new KeyValuePair<string, string>(ip, dhcpDomain);
  2299. IPAddress address = IPAddress.Parse(ip);
  2300. if (IPAddress.IsLoopback(address))
  2301. return new KeyValuePair<string, string>(ip, "localhost");
  2302. DnsDatagram ptrResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(address, DnsClass.IN), 500);
  2303. if ((ptrResponse != null) && (ptrResponse.Answer.Count > 0))
  2304. {
  2305. IReadOnlyList<string> ptrDomains = DnsClient.ParseResponsePTR(ptrResponse);
  2306. if (ptrDomains != null)
  2307. return new KeyValuePair<string, string>(ip, ptrDomains[0]);
  2308. }
  2309. return new KeyValuePair<string, string>(ip, null);
  2310. }
  2311. List<Task<KeyValuePair<string, string>>> resolverTasks = new List<Task<KeyValuePair<string, string>>>();
  2312. foreach (KeyValuePair<string, int> item in topClients)
  2313. {
  2314. resolverTasks.Add(ResolvePtrAsync(item.Key));
  2315. }
  2316. Dictionary<string, string> result = new Dictionary<string, string>();
  2317. foreach (Task<KeyValuePair<string, string>> resolverTask in resolverTasks)
  2318. {
  2319. try
  2320. {
  2321. KeyValuePair<string, string> ptrResult = await resolverTask;
  2322. result[ptrResult.Key] = ptrResult.Value;
  2323. }
  2324. catch
  2325. { }
  2326. }
  2327. return result;
  2328. }
  2329. #endregion
  2330. #region cache api
  2331. private void FlushCache(HttpListenerRequest request)
  2332. {
  2333. _dnsServer.CacheZoneManager.Flush();
  2334. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Cache was flushed.");
  2335. }
  2336. private void ListCachedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2337. {
  2338. string domain = request.QueryString["domain"];
  2339. if (domain == null)
  2340. domain = "";
  2341. string direction = request.QueryString["direction"];
  2342. List<string> subZones;
  2343. List<DnsResourceRecord> records;
  2344. while (true)
  2345. {
  2346. subZones = _dnsServer.CacheZoneManager.ListSubDomains(domain);
  2347. records = _dnsServer.CacheZoneManager.ListAllRecords(domain);
  2348. if (records.Count > 0)
  2349. break;
  2350. if (subZones.Count != 1)
  2351. break;
  2352. if (direction == "up")
  2353. {
  2354. if (domain.Length == 0)
  2355. break;
  2356. int i = domain.IndexOf('.');
  2357. if (i < 0)
  2358. domain = "";
  2359. else
  2360. domain = domain.Substring(i + 1);
  2361. }
  2362. else if (domain.Length == 0)
  2363. {
  2364. domain = subZones[0];
  2365. }
  2366. else
  2367. {
  2368. domain = subZones[0] + "." + domain;
  2369. }
  2370. }
  2371. subZones.Sort();
  2372. jsonWriter.WritePropertyName("domain");
  2373. jsonWriter.WriteValue(domain);
  2374. jsonWriter.WritePropertyName("zones");
  2375. jsonWriter.WriteStartArray();
  2376. if (domain.Length != 0)
  2377. domain = "." + domain;
  2378. foreach (string subZone in subZones)
  2379. jsonWriter.WriteValue(subZone + domain);
  2380. jsonWriter.WriteEndArray();
  2381. WriteRecordsAsJson(records, jsonWriter, false);
  2382. }
  2383. private void DeleteCachedZone(HttpListenerRequest request)
  2384. {
  2385. string domain = request.QueryString["domain"];
  2386. if (string.IsNullOrEmpty(domain))
  2387. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2388. if (_dnsServer.CacheZoneManager.DeleteZone(domain))
  2389. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Cached zone was deleted: " + domain);
  2390. }
  2391. #endregion
  2392. #region allowed zones api
  2393. private void ListAllowedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2394. {
  2395. string domain = request.QueryString["domain"];
  2396. if (domain == null)
  2397. domain = "";
  2398. string direction = request.QueryString["direction"];
  2399. List<string> subZones;
  2400. IReadOnlyList<DnsResourceRecord> records;
  2401. while (true)
  2402. {
  2403. subZones = _dnsServer.AllowedZoneManager.ListSubDomains(domain);
  2404. records = _dnsServer.AllowedZoneManager.QueryRecords(domain, DnsResourceRecordType.ANY);
  2405. if (records.Count > 0)
  2406. break;
  2407. if (subZones.Count != 1)
  2408. break;
  2409. if (direction == "up")
  2410. {
  2411. if (domain.Length == 0)
  2412. break;
  2413. int i = domain.IndexOf('.');
  2414. if (i < 0)
  2415. domain = "";
  2416. else
  2417. domain = domain.Substring(i + 1);
  2418. }
  2419. else if (domain.Length == 0)
  2420. {
  2421. domain = subZones[0];
  2422. }
  2423. else
  2424. {
  2425. domain = subZones[0] + "." + domain;
  2426. }
  2427. }
  2428. subZones.Sort();
  2429. jsonWriter.WritePropertyName("domain");
  2430. jsonWriter.WriteValue(domain);
  2431. jsonWriter.WritePropertyName("zones");
  2432. jsonWriter.WriteStartArray();
  2433. if (domain.Length != 0)
  2434. domain = "." + domain;
  2435. foreach (string subZone in subZones)
  2436. jsonWriter.WriteValue(subZone + domain);
  2437. jsonWriter.WriteEndArray();
  2438. WriteRecordsAsJson(new List<DnsResourceRecord>(records), jsonWriter, false);
  2439. }
  2440. private void ImportAllowedZones(HttpListenerRequest request)
  2441. {
  2442. if (!request.ContentType.StartsWith("application/x-www-form-urlencoded"))
  2443. throw new DnsWebServiceException("Invalid content type. Expected application/x-www-form-urlencoded.");
  2444. string formRequest;
  2445. using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
  2446. {
  2447. formRequest = sR.ReadToEnd();
  2448. }
  2449. string[] formParts = formRequest.Split('&');
  2450. foreach (string formPart in formParts)
  2451. {
  2452. if (formPart.StartsWith("allowedZones="))
  2453. {
  2454. string[] allowedZones = formPart.Substring(13).Split(',');
  2455. bool added = false;
  2456. foreach (string allowedZone in allowedZones)
  2457. {
  2458. if (_dnsServer.AllowedZoneManager.AllowZone(allowedZone))
  2459. added = true;
  2460. }
  2461. if (added)
  2462. {
  2463. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Total " + allowedZones.Length + " zones were imported into allowed zone successfully.");
  2464. _dnsServer.AllowedZoneManager.SaveZoneFile();
  2465. }
  2466. return;
  2467. }
  2468. }
  2469. throw new DnsWebServiceException("Parameter 'allowedZones' missing.");
  2470. }
  2471. private void ExportAllowedZones(HttpListenerResponse response)
  2472. {
  2473. IReadOnlyList<AuthZoneInfo> zoneInfoList = _dnsServer.AllowedZoneManager.ListZones();
  2474. response.ContentType = "text/plain";
  2475. response.AddHeader("Content-Disposition", "attachment;filename=AllowedZones.txt");
  2476. using (StreamWriter sW = new StreamWriter(new BufferedStream(response.OutputStream)))
  2477. {
  2478. foreach (AuthZoneInfo zoneInfo in zoneInfoList)
  2479. sW.WriteLine(zoneInfo.Name);
  2480. }
  2481. }
  2482. private void DeleteAllowedZone(HttpListenerRequest request)
  2483. {
  2484. string domain = request.QueryString["domain"];
  2485. if (string.IsNullOrEmpty(domain))
  2486. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2487. if (_dnsServer.AllowedZoneManager.DeleteZone(domain))
  2488. {
  2489. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Allowed zone was deleted: " + domain);
  2490. _dnsServer.AllowedZoneManager.SaveZoneFile();
  2491. }
  2492. }
  2493. private void AllowZone(HttpListenerRequest request)
  2494. {
  2495. string domain = request.QueryString["domain"];
  2496. if (string.IsNullOrEmpty(domain))
  2497. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2498. if (IPAddress.TryParse(domain, out IPAddress ipAddress))
  2499. domain = (new DnsQuestionRecord(ipAddress, DnsClass.IN)).Name;
  2500. if (_dnsServer.AllowedZoneManager.AllowZone(domain))
  2501. {
  2502. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Zone was allowed: " + domain);
  2503. _dnsServer.AllowedZoneManager.SaveZoneFile();
  2504. }
  2505. }
  2506. #endregion
  2507. #region blocked zones api
  2508. private void ListBlockedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2509. {
  2510. string domain = request.QueryString["domain"];
  2511. if (domain == null)
  2512. domain = "";
  2513. string direction = request.QueryString["direction"];
  2514. List<string> subZones;
  2515. IReadOnlyList<DnsResourceRecord> records;
  2516. while (true)
  2517. {
  2518. subZones = _dnsServer.BlockedZoneManager.ListSubDomains(domain);
  2519. records = _dnsServer.BlockedZoneManager.QueryRecords(domain, DnsResourceRecordType.ANY);
  2520. if (records.Count > 0)
  2521. break;
  2522. if (subZones.Count != 1)
  2523. break;
  2524. if (direction == "up")
  2525. {
  2526. if (domain.Length == 0)
  2527. break;
  2528. int i = domain.IndexOf('.');
  2529. if (i < 0)
  2530. domain = "";
  2531. else
  2532. domain = domain.Substring(i + 1);
  2533. }
  2534. else if (domain.Length == 0)
  2535. {
  2536. domain = subZones[0];
  2537. }
  2538. else
  2539. {
  2540. domain = subZones[0] + "." + domain;
  2541. }
  2542. }
  2543. subZones.Sort();
  2544. jsonWriter.WritePropertyName("domain");
  2545. jsonWriter.WriteValue(domain);
  2546. jsonWriter.WritePropertyName("zones");
  2547. jsonWriter.WriteStartArray();
  2548. if (domain.Length != 0)
  2549. domain = "." + domain;
  2550. foreach (string subZone in subZones)
  2551. jsonWriter.WriteValue(subZone + domain);
  2552. jsonWriter.WriteEndArray();
  2553. WriteRecordsAsJson(new List<DnsResourceRecord>(records), jsonWriter, false);
  2554. }
  2555. private void ImportBlockedZones(HttpListenerRequest request)
  2556. {
  2557. if (!request.ContentType.StartsWith("application/x-www-form-urlencoded"))
  2558. throw new DnsWebServiceException("Invalid content type. Expected application/x-www-form-urlencoded.");
  2559. string formRequest;
  2560. using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
  2561. {
  2562. formRequest = sR.ReadToEnd();
  2563. }
  2564. string[] formParts = formRequest.Split('&');
  2565. foreach (string formPart in formParts)
  2566. {
  2567. if (formPart.StartsWith("blockedZones="))
  2568. {
  2569. string[] blockedZones = formPart.Substring(13).Split(',');
  2570. bool added = false;
  2571. foreach (string blockedZone in blockedZones)
  2572. {
  2573. if (_dnsServer.BlockedZoneManager.BlockZone(blockedZone))
  2574. added = true;
  2575. }
  2576. if (added)
  2577. {
  2578. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Total " + blockedZones.Length + " zones were imported into blocked zone successfully.");
  2579. _dnsServer.BlockedZoneManager.SaveZoneFile();
  2580. }
  2581. return;
  2582. }
  2583. }
  2584. throw new DnsWebServiceException("Parameter 'blockedZones' missing.");
  2585. }
  2586. private void ExportBlockedZones(HttpListenerResponse response)
  2587. {
  2588. IReadOnlyList<AuthZoneInfo> zoneInfoList = _dnsServer.BlockedZoneManager.ListZones();
  2589. response.ContentType = "text/plain";
  2590. response.AddHeader("Content-Disposition", "attachment;filename=BlockedZones.txt");
  2591. using (StreamWriter sW = new StreamWriter(new BufferedStream(response.OutputStream)))
  2592. {
  2593. foreach (AuthZoneInfo zoneInfo in zoneInfoList)
  2594. sW.WriteLine(zoneInfo.Name);
  2595. }
  2596. }
  2597. private void DeleteBlockedZone(HttpListenerRequest request)
  2598. {
  2599. string domain = request.QueryString["domain"];
  2600. if (string.IsNullOrEmpty(domain))
  2601. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2602. if (_dnsServer.BlockedZoneManager.DeleteZone(domain))
  2603. {
  2604. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Blocked zone was deleted: " + domain);
  2605. _dnsServer.BlockedZoneManager.SaveZoneFile();
  2606. }
  2607. }
  2608. private void BlockZone(HttpListenerRequest request)
  2609. {
  2610. string domain = request.QueryString["domain"];
  2611. if (string.IsNullOrEmpty(domain))
  2612. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2613. if (IPAddress.TryParse(domain, out IPAddress ipAddress))
  2614. domain = (new DnsQuestionRecord(ipAddress, DnsClass.IN)).Name;
  2615. if (_dnsServer.BlockedZoneManager.BlockZone(domain))
  2616. {
  2617. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Domain was added to blocked zone: " + domain);
  2618. _dnsServer.BlockedZoneManager.SaveZoneFile();
  2619. }
  2620. }
  2621. #endregion
  2622. #region zones api
  2623. private void ListZones(JsonTextWriter jsonWriter)
  2624. {
  2625. List<AuthZoneInfo> zones = _dnsServer.AuthZoneManager.ListZones();
  2626. zones.Sort();
  2627. jsonWriter.WritePropertyName("zones");
  2628. jsonWriter.WriteStartArray();
  2629. foreach (AuthZoneInfo zone in zones)
  2630. {
  2631. jsonWriter.WriteStartObject();
  2632. jsonWriter.WritePropertyName("name");
  2633. jsonWriter.WriteValue(zone.Name);
  2634. jsonWriter.WritePropertyName("type");
  2635. jsonWriter.WriteValue(zone.Type.ToString());
  2636. switch (zone.Type)
  2637. {
  2638. case AuthZoneType.Primary:
  2639. jsonWriter.WritePropertyName("internal");
  2640. jsonWriter.WriteValue(zone.Internal);
  2641. break;
  2642. case AuthZoneType.Secondary:
  2643. case AuthZoneType.Stub:
  2644. jsonWriter.WritePropertyName("expiry");
  2645. jsonWriter.WriteValue(zone.Expiry.ToLocalTime().ToString("dd MMM yyyy HH:mm:ss"));
  2646. jsonWriter.WritePropertyName("isExpired");
  2647. jsonWriter.WriteValue(zone.IsExpired);
  2648. break;
  2649. }
  2650. jsonWriter.WritePropertyName("disabled");
  2651. jsonWriter.WriteValue(zone.Disabled);
  2652. jsonWriter.WriteEndObject();
  2653. }
  2654. jsonWriter.WriteEndArray();
  2655. }
  2656. private async Task CreateZoneAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2657. {
  2658. string domain = request.QueryString["domain"];
  2659. if (string.IsNullOrEmpty(domain))
  2660. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2661. if (domain.Contains("*"))
  2662. throw new DnsWebServiceException("Domain name for a zone cannot contain wildcard character.");
  2663. if (IPAddress.TryParse(domain, out IPAddress ipAddress))
  2664. {
  2665. domain = new DnsQuestionRecord(ipAddress, DnsClass.IN).Name.ToLower();
  2666. }
  2667. else if (domain.Contains("/"))
  2668. {
  2669. string[] parts = domain.Split('/');
  2670. if ((parts.Length == 2) && IPAddress.TryParse(parts[0], out ipAddress) && int.TryParse(parts[1], out int subnetMaskWidth))
  2671. domain = Zone.GetReverseZone(ipAddress, subnetMaskWidth);
  2672. }
  2673. else if (domain.EndsWith("."))
  2674. {
  2675. domain = domain.Substring(0, domain.Length - 1);
  2676. }
  2677. AuthZoneType type = AuthZoneType.Primary;
  2678. string strType = request.QueryString["type"];
  2679. if (!string.IsNullOrEmpty(strType))
  2680. type = (AuthZoneType)Enum.Parse(typeof(AuthZoneType), strType, true);
  2681. switch (type)
  2682. {
  2683. case AuthZoneType.Primary:
  2684. if (_dnsServer.AuthZoneManager.CreatePrimaryZone(domain, _dnsServer.ServerDomain, false) == null)
  2685. throw new DnsWebServiceException("Zone already exists: " + domain);
  2686. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Authoritative primary zone was created: " + domain);
  2687. _dnsServer.AuthZoneManager.SaveZoneFile(domain);
  2688. break;
  2689. case AuthZoneType.Secondary:
  2690. {
  2691. string strPrimaryNameServerAddresses = request.QueryString["primaryNameServerAddresses"];
  2692. if (string.IsNullOrEmpty(strPrimaryNameServerAddresses))
  2693. strPrimaryNameServerAddresses = null;
  2694. if (await _dnsServer.AuthZoneManager.CreateSecondaryZoneAsync(domain, strPrimaryNameServerAddresses) == null)
  2695. throw new DnsWebServiceException("Zone already exists: " + domain);
  2696. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Authoritative secondary zone was created: " + domain);
  2697. _dnsServer.AuthZoneManager.SaveZoneFile(domain);
  2698. }
  2699. break;
  2700. case AuthZoneType.Stub:
  2701. {
  2702. string strPrimaryNameServerAddresses = request.QueryString["primaryNameServerAddresses"];
  2703. if (string.IsNullOrEmpty(strPrimaryNameServerAddresses))
  2704. strPrimaryNameServerAddresses = null;
  2705. if (await _dnsServer.AuthZoneManager.CreateStubZoneAsync(domain, strPrimaryNameServerAddresses) == null)
  2706. throw new DnsWebServiceException("Zone already exists: " + domain);
  2707. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Stub zone was created: " + domain);
  2708. _dnsServer.AuthZoneManager.SaveZoneFile(domain);
  2709. }
  2710. break;
  2711. case AuthZoneType.Forwarder:
  2712. {
  2713. DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
  2714. string strForwarderProtocol = request.QueryString["protocol"];
  2715. if (!string.IsNullOrEmpty(strForwarderProtocol))
  2716. forwarderProtocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strForwarderProtocol, true);
  2717. string strForwarder = request.QueryString["forwarder"];
  2718. if (string.IsNullOrEmpty(strForwarder))
  2719. throw new DnsWebServiceException("Parameter 'forwarder' missing.");
  2720. if (_dnsServer.AuthZoneManager.CreateForwarderZone(domain, forwarderProtocol, strForwarder) == null)
  2721. throw new DnsWebServiceException("Zone already exists: " + domain);
  2722. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Forwarder zone was created: " + domain);
  2723. _dnsServer.AuthZoneManager.SaveZoneFile(domain);
  2724. }
  2725. break;
  2726. default:
  2727. throw new NotSupportedException("Zone type not supported.");
  2728. }
  2729. //delete cache for this zone to allow rebuilding cache data as needed by stub or forwarder zones
  2730. _dnsServer.CacheZoneManager.DeleteZone(domain);
  2731. jsonWriter.WritePropertyName("domain");
  2732. jsonWriter.WriteValue(string.IsNullOrEmpty(domain) ? "." : domain);
  2733. }
  2734. private void DeleteZone(HttpListenerRequest request)
  2735. {
  2736. string domain = request.QueryString["domain"];
  2737. if (string.IsNullOrEmpty(domain))
  2738. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2739. if (domain.EndsWith("."))
  2740. domain = domain.Substring(0, domain.Length - 1);
  2741. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  2742. if (zoneInfo == null)
  2743. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  2744. if (zoneInfo.Internal)
  2745. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  2746. if (!_dnsServer.AuthZoneManager.DeleteZone(domain))
  2747. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  2748. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was deleted: " + domain);
  2749. _dnsServer.AuthZoneManager.DeleteZoneFile(zoneInfo.Name);
  2750. }
  2751. private void EnableZone(HttpListenerRequest request)
  2752. {
  2753. string domain = request.QueryString["domain"];
  2754. if (string.IsNullOrEmpty(domain))
  2755. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2756. if (domain.EndsWith("."))
  2757. domain = domain.Substring(0, domain.Length - 1);
  2758. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  2759. if (zoneInfo == null)
  2760. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  2761. if (zoneInfo.Internal)
  2762. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  2763. zoneInfo.Disabled = false;
  2764. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was enabled: " + zoneInfo.Name);
  2765. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  2766. //delete cache for this zone to allow rebuilding cache data as needed by stub or forwarder zones
  2767. _dnsServer.CacheZoneManager.DeleteZone(zoneInfo.Name);
  2768. }
  2769. private void DisableZone(HttpListenerRequest request)
  2770. {
  2771. string domain = request.QueryString["domain"];
  2772. if (string.IsNullOrEmpty(domain))
  2773. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2774. if (domain.EndsWith("."))
  2775. domain = domain.Substring(0, domain.Length - 1);
  2776. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  2777. if (zoneInfo == null)
  2778. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  2779. if (zoneInfo.Internal)
  2780. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  2781. zoneInfo.Disabled = true;
  2782. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was disabled: " + zoneInfo.Name);
  2783. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  2784. }
  2785. private void AddRecord(HttpListenerRequest request)
  2786. {
  2787. string domain = request.QueryString["domain"];
  2788. if (string.IsNullOrEmpty(domain))
  2789. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2790. if (domain.EndsWith("."))
  2791. domain = domain.Substring(0, domain.Length - 1);
  2792. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  2793. if (zoneInfo == null)
  2794. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  2795. if (zoneInfo.Internal)
  2796. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  2797. string strType = request.QueryString["type"];
  2798. if (string.IsNullOrEmpty(strType))
  2799. throw new DnsWebServiceException("Parameter 'type' missing.");
  2800. DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
  2801. string value = request.QueryString["value"];
  2802. if (string.IsNullOrEmpty(value))
  2803. throw new DnsWebServiceException("Parameter 'value' missing.");
  2804. uint ttl;
  2805. string strTtl = request.QueryString["ttl"];
  2806. if (string.IsNullOrEmpty(strTtl))
  2807. ttl = 3600;
  2808. else
  2809. ttl = uint.Parse(strTtl);
  2810. bool overwrite = false;
  2811. string strOverwrite = request.QueryString["overwrite"];
  2812. if (!string.IsNullOrEmpty(strOverwrite))
  2813. overwrite = bool.Parse(strOverwrite);
  2814. switch (type)
  2815. {
  2816. case DnsResourceRecordType.A:
  2817. case DnsResourceRecordType.AAAA:
  2818. {
  2819. IPAddress ipAddress = IPAddress.Parse(value);
  2820. bool ptr = false;
  2821. string strPtr = request.QueryString["ptr"];
  2822. if (!string.IsNullOrEmpty(strPtr))
  2823. ptr = bool.Parse(strPtr);
  2824. if (ptr)
  2825. {
  2826. string ptrDomain = Zone.GetReverseZone(ipAddress, type == DnsResourceRecordType.A ? 32 : 128);
  2827. AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
  2828. if (reverseZoneInfo == null)
  2829. {
  2830. bool createPtrZone = false;
  2831. string strCreatePtrZone = request.QueryString["createPtrZone"];
  2832. if (!string.IsNullOrEmpty(strCreatePtrZone))
  2833. createPtrZone = bool.Parse(strCreatePtrZone);
  2834. if (!createPtrZone)
  2835. throw new DnsServerException("No reverse zone available to add PTR record.");
  2836. string ptrZone = Zone.GetReverseZone(ipAddress, type == DnsResourceRecordType.A ? 24 : 64);
  2837. reverseZoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(ptrZone, _dnsServer.ServerDomain, false);
  2838. if (reverseZoneInfo == null)
  2839. throw new DnsServerException("Failed to create reverse zone to add PTR record: " + ptrZone);
  2840. }
  2841. if (reverseZoneInfo.Internal)
  2842. throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is an internal zone.");
  2843. if (reverseZoneInfo.Type != AuthZoneType.Primary)
  2844. throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is not a primary zone.");
  2845. _dnsServer.AuthZoneManager.SetRecords(ptrDomain, DnsResourceRecordType.PTR, ttl, new DnsPTRRecord[] { new DnsPTRRecord(domain) });
  2846. _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
  2847. }
  2848. DnsResourceRecord newRecord;
  2849. if (type == DnsResourceRecordType.A)
  2850. newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsARecord(ipAddress));
  2851. else
  2852. newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsAAAARecord(ipAddress));
  2853. if (overwrite)
  2854. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2855. else
  2856. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2857. }
  2858. break;
  2859. case DnsResourceRecordType.MX:
  2860. {
  2861. string preference = request.QueryString["preference"];
  2862. if (string.IsNullOrEmpty(preference))
  2863. throw new DnsWebServiceException("Parameter 'preference' missing.");
  2864. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsMXRecord(ushort.Parse(preference), value));
  2865. if (overwrite)
  2866. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2867. else
  2868. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2869. }
  2870. break;
  2871. case DnsResourceRecordType.TXT:
  2872. {
  2873. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsTXTRecord(value));
  2874. if (overwrite)
  2875. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2876. else
  2877. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2878. }
  2879. break;
  2880. case DnsResourceRecordType.NS:
  2881. {
  2882. string glueAddresses = request.QueryString["glue"];
  2883. if (string.IsNullOrEmpty(glueAddresses))
  2884. glueAddresses = null;
  2885. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsNSRecord(value));
  2886. if (glueAddresses != null)
  2887. newRecord.SetGlueRecords(glueAddresses);
  2888. if (overwrite)
  2889. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2890. else
  2891. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2892. }
  2893. break;
  2894. case DnsResourceRecordType.PTR:
  2895. {
  2896. if (!overwrite)
  2897. {
  2898. IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
  2899. if (existingRecords.Count > 0)
  2900. throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
  2901. }
  2902. _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsPTRRecord(value) });
  2903. }
  2904. break;
  2905. case DnsResourceRecordType.CNAME:
  2906. {
  2907. if (!overwrite)
  2908. {
  2909. IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
  2910. if (existingRecords.Count > 0)
  2911. throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
  2912. }
  2913. _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsCNAMERecord(value) });
  2914. }
  2915. break;
  2916. case DnsResourceRecordType.SRV:
  2917. {
  2918. string priority = request.QueryString["priority"];
  2919. if (string.IsNullOrEmpty(priority))
  2920. throw new DnsWebServiceException("Parameter 'priority' missing.");
  2921. string weight = request.QueryString["weight"];
  2922. if (string.IsNullOrEmpty(weight))
  2923. throw new DnsWebServiceException("Parameter 'weight' missing.");
  2924. string port = request.QueryString["port"];
  2925. if (string.IsNullOrEmpty(port))
  2926. throw new DnsWebServiceException("Parameter 'port' missing.");
  2927. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsSRVRecord(ushort.Parse(priority), ushort.Parse(weight), ushort.Parse(port), value));
  2928. if (overwrite)
  2929. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2930. else
  2931. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2932. }
  2933. break;
  2934. case DnsResourceRecordType.CAA:
  2935. {
  2936. string flags = request.QueryString["flags"];
  2937. if (string.IsNullOrEmpty(flags))
  2938. throw new DnsWebServiceException("Parameter 'flags' missing.");
  2939. string tag = request.QueryString["tag"];
  2940. if (string.IsNullOrEmpty(tag))
  2941. throw new DnsWebServiceException("Parameter 'tag' missing.");
  2942. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsCAARecord(byte.Parse(flags), tag, value));
  2943. if (overwrite)
  2944. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2945. else
  2946. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2947. }
  2948. break;
  2949. case DnsResourceRecordType.ANAME:
  2950. {
  2951. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsANAMERecord(value));
  2952. if (overwrite)
  2953. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2954. else
  2955. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2956. }
  2957. break;
  2958. case DnsResourceRecordType.FWD:
  2959. {
  2960. string protocol = request.QueryString["protocol"];
  2961. if (string.IsNullOrEmpty(protocol))
  2962. protocol = "Udp";
  2963. DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsForwarderRecord((DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), protocol, true), value));
  2964. if (overwrite)
  2965. _dnsServer.AuthZoneManager.SetRecord(newRecord);
  2966. else
  2967. _dnsServer.AuthZoneManager.AddRecord(newRecord);
  2968. }
  2969. break;
  2970. case DnsResourceRecordType.APP:
  2971. {
  2972. string classPath = request.QueryString["classPath"];
  2973. if (string.IsNullOrEmpty(classPath))
  2974. throw new DnsWebServiceException("Parameter 'classPath' missing.");
  2975. string recordData = request.QueryString["recordData"];
  2976. if (string.IsNullOrEmpty(recordData))
  2977. recordData = "";
  2978. if (!overwrite)
  2979. {
  2980. IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
  2981. if (existingRecords.Count > 0)
  2982. throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
  2983. }
  2984. _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsApplicationRecord(value, classPath, recordData) });
  2985. }
  2986. break;
  2987. default:
  2988. throw new DnsWebServiceException("Type not supported for AddRecords().");
  2989. }
  2990. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] New record was added to authoritative zone {domain: " + domain + "; type: " + type + "; value: " + value + "; ttl: " + ttl + ";}");
  2991. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  2992. }
  2993. private void GetRecords(HttpListenerRequest request, JsonTextWriter jsonWriter)
  2994. {
  2995. string domain = request.QueryString["domain"];
  2996. if (string.IsNullOrEmpty(domain))
  2997. throw new DnsWebServiceException("Parameter 'domain' missing.");
  2998. if (domain.EndsWith("."))
  2999. domain = domain.Substring(0, domain.Length - 1);
  3000. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  3001. if (zoneInfo == null)
  3002. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  3003. jsonWriter.WritePropertyName("zone");
  3004. jsonWriter.WriteStartObject();
  3005. jsonWriter.WritePropertyName("name");
  3006. jsonWriter.WriteValue(zoneInfo.Name);
  3007. jsonWriter.WritePropertyName("type");
  3008. jsonWriter.WriteValue(zoneInfo.Type.ToString());
  3009. switch (zoneInfo.Type)
  3010. {
  3011. case AuthZoneType.Primary:
  3012. jsonWriter.WritePropertyName("internal");
  3013. jsonWriter.WriteValue(zoneInfo.Internal);
  3014. break;
  3015. case AuthZoneType.Secondary:
  3016. case AuthZoneType.Stub:
  3017. jsonWriter.WritePropertyName("expiry");
  3018. jsonWriter.WriteValue(zoneInfo.Expiry.ToLocalTime().ToString("dd MMM yyyy HH:mm:ss"));
  3019. jsonWriter.WritePropertyName("isExpired");
  3020. jsonWriter.WriteValue(zoneInfo.IsExpired);
  3021. break;
  3022. }
  3023. jsonWriter.WritePropertyName("disabled");
  3024. jsonWriter.WriteValue(zoneInfo.Disabled);
  3025. jsonWriter.WriteEndObject();
  3026. List<DnsResourceRecord> records = _dnsServer.AuthZoneManager.ListAllRecords(domain);
  3027. WriteRecordsAsJson(records, jsonWriter, true);
  3028. }
  3029. private static void WriteRecordsAsJson(List<DnsResourceRecord> records, JsonTextWriter jsonWriter, bool authoritativeZoneRecords)
  3030. {
  3031. if (records == null)
  3032. {
  3033. jsonWriter.WritePropertyName("records");
  3034. jsonWriter.WriteStartArray();
  3035. jsonWriter.WriteEndArray();
  3036. return;
  3037. }
  3038. records.Sort();
  3039. Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> groupedByDomainRecords = DnsResourceRecord.GroupRecords(records);
  3040. jsonWriter.WritePropertyName("records");
  3041. jsonWriter.WriteStartArray();
  3042. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> groupedByTypeRecords in groupedByDomainRecords)
  3043. {
  3044. foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> groupedRecords in groupedByTypeRecords.Value)
  3045. {
  3046. foreach (DnsResourceRecord record in groupedRecords.Value)
  3047. {
  3048. jsonWriter.WriteStartObject();
  3049. if (authoritativeZoneRecords)
  3050. {
  3051. jsonWriter.WritePropertyName("disabled");
  3052. jsonWriter.WriteValue(record.IsDisabled());
  3053. }
  3054. jsonWriter.WritePropertyName("name");
  3055. jsonWriter.WriteValue(record.Name);
  3056. jsonWriter.WritePropertyName("type");
  3057. jsonWriter.WriteValue(record.Type.ToString());
  3058. jsonWriter.WritePropertyName("ttl");
  3059. if (authoritativeZoneRecords)
  3060. jsonWriter.WriteValue(record.TtlValue);
  3061. else
  3062. jsonWriter.WriteValue(record.TTL);
  3063. jsonWriter.WritePropertyName("rData");
  3064. jsonWriter.WriteStartObject();
  3065. switch (record.Type)
  3066. {
  3067. case DnsResourceRecordType.A:
  3068. {
  3069. DnsARecord rdata = record.RDATA as DnsARecord;
  3070. if (rdata == null)
  3071. {
  3072. jsonWriter.WritePropertyName("dataType");
  3073. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3074. jsonWriter.WritePropertyName("data");
  3075. jsonWriter.WriteValue(record.RDATA.ToString());
  3076. }
  3077. else
  3078. {
  3079. jsonWriter.WritePropertyName("value");
  3080. jsonWriter.WriteValue(rdata.IPAddress);
  3081. }
  3082. }
  3083. break;
  3084. case DnsResourceRecordType.AAAA:
  3085. {
  3086. DnsAAAARecord rdata = record.RDATA as DnsAAAARecord;
  3087. if (rdata == null)
  3088. {
  3089. jsonWriter.WritePropertyName("dataType");
  3090. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3091. jsonWriter.WritePropertyName("data");
  3092. jsonWriter.WriteValue(record.RDATA.ToString());
  3093. }
  3094. else
  3095. {
  3096. jsonWriter.WritePropertyName("value");
  3097. jsonWriter.WriteValue(rdata.IPAddress);
  3098. }
  3099. }
  3100. break;
  3101. case DnsResourceRecordType.SOA:
  3102. {
  3103. DnsSOARecord rdata = record.RDATA as DnsSOARecord;
  3104. if (rdata == null)
  3105. {
  3106. jsonWriter.WritePropertyName("dataType");
  3107. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3108. jsonWriter.WritePropertyName("data");
  3109. jsonWriter.WriteValue(record.RDATA.ToString());
  3110. }
  3111. else
  3112. {
  3113. jsonWriter.WritePropertyName("primaryNameServer");
  3114. jsonWriter.WriteValue(rdata.PrimaryNameServer);
  3115. jsonWriter.WritePropertyName("responsiblePerson");
  3116. jsonWriter.WriteValue(rdata.ResponsiblePerson);
  3117. jsonWriter.WritePropertyName("serial");
  3118. jsonWriter.WriteValue(rdata.Serial);
  3119. jsonWriter.WritePropertyName("refresh");
  3120. jsonWriter.WriteValue(rdata.Refresh);
  3121. jsonWriter.WritePropertyName("retry");
  3122. jsonWriter.WriteValue(rdata.Retry);
  3123. jsonWriter.WritePropertyName("expire");
  3124. jsonWriter.WriteValue(rdata.Expire);
  3125. jsonWriter.WritePropertyName("minimum");
  3126. jsonWriter.WriteValue(rdata.Minimum);
  3127. }
  3128. IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
  3129. if (glueRecords.Count > 0)
  3130. {
  3131. string primaryAddresses = null;
  3132. foreach (DnsResourceRecord glueRecord in glueRecords)
  3133. {
  3134. if (primaryAddresses == null)
  3135. primaryAddresses = glueRecord.RDATA.ToString();
  3136. else
  3137. primaryAddresses = primaryAddresses + ", " + glueRecord.RDATA.ToString();
  3138. }
  3139. jsonWriter.WritePropertyName("primaryAddresses");
  3140. jsonWriter.WriteValue(primaryAddresses);
  3141. }
  3142. }
  3143. break;
  3144. case DnsResourceRecordType.PTR:
  3145. {
  3146. DnsPTRRecord rdata = record.RDATA as DnsPTRRecord;
  3147. if (rdata == null)
  3148. {
  3149. jsonWriter.WritePropertyName("dataType");
  3150. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3151. jsonWriter.WritePropertyName("data");
  3152. jsonWriter.WriteValue(record.RDATA.ToString());
  3153. }
  3154. else
  3155. {
  3156. jsonWriter.WritePropertyName("value");
  3157. jsonWriter.WriteValue(rdata.Domain);
  3158. }
  3159. }
  3160. break;
  3161. case DnsResourceRecordType.MX:
  3162. {
  3163. DnsMXRecord rdata = record.RDATA as DnsMXRecord;
  3164. if (rdata == null)
  3165. {
  3166. jsonWriter.WritePropertyName("dataType");
  3167. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3168. jsonWriter.WritePropertyName("data");
  3169. jsonWriter.WriteValue(record.RDATA.ToString());
  3170. }
  3171. else
  3172. {
  3173. jsonWriter.WritePropertyName("preference");
  3174. jsonWriter.WriteValue(rdata.Preference);
  3175. jsonWriter.WritePropertyName("value");
  3176. jsonWriter.WriteValue(rdata.Exchange);
  3177. IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
  3178. if (glueRecords.Count > 0)
  3179. {
  3180. string glue = null;
  3181. foreach (DnsResourceRecord glueRecord in glueRecords)
  3182. {
  3183. if (glue == null)
  3184. glue = glueRecord.RDATA.ToString();
  3185. else
  3186. glue = glue + ", " + glueRecord.RDATA.ToString();
  3187. }
  3188. jsonWriter.WritePropertyName("glue");
  3189. jsonWriter.WriteValue(glue);
  3190. }
  3191. }
  3192. }
  3193. break;
  3194. case DnsResourceRecordType.TXT:
  3195. {
  3196. DnsTXTRecord rdata = record.RDATA as DnsTXTRecord;
  3197. if (rdata == null)
  3198. {
  3199. jsonWriter.WritePropertyName("dataType");
  3200. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3201. jsonWriter.WritePropertyName("data");
  3202. jsonWriter.WriteValue(record.RDATA.ToString());
  3203. }
  3204. else
  3205. {
  3206. jsonWriter.WritePropertyName("value");
  3207. jsonWriter.WriteValue(rdata.Text);
  3208. }
  3209. }
  3210. break;
  3211. case DnsResourceRecordType.NS:
  3212. {
  3213. DnsNSRecord rdata = record.RDATA as DnsNSRecord;
  3214. if (rdata == null)
  3215. {
  3216. jsonWriter.WritePropertyName("dataType");
  3217. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3218. jsonWriter.WritePropertyName("data");
  3219. jsonWriter.WriteValue(record.RDATA.ToString());
  3220. }
  3221. else
  3222. {
  3223. jsonWriter.WritePropertyName("value");
  3224. jsonWriter.WriteValue(rdata.NameServer);
  3225. IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
  3226. if (glueRecords.Count > 0)
  3227. {
  3228. string glue = null;
  3229. foreach (DnsResourceRecord glueRecord in glueRecords)
  3230. {
  3231. if (glue == null)
  3232. glue = glueRecord.RDATA.ToString();
  3233. else
  3234. glue = glue + ", " + glueRecord.RDATA.ToString();
  3235. }
  3236. jsonWriter.WritePropertyName("glue");
  3237. jsonWriter.WriteValue(glue);
  3238. }
  3239. }
  3240. }
  3241. break;
  3242. case DnsResourceRecordType.CNAME:
  3243. {
  3244. DnsCNAMERecord rdata = record.RDATA as DnsCNAMERecord;
  3245. if (rdata == null)
  3246. {
  3247. jsonWriter.WritePropertyName("dataType");
  3248. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3249. jsonWriter.WritePropertyName("data");
  3250. jsonWriter.WriteValue(record.RDATA.ToString());
  3251. }
  3252. else
  3253. {
  3254. jsonWriter.WritePropertyName("value");
  3255. jsonWriter.WriteValue(rdata.Domain);
  3256. }
  3257. }
  3258. break;
  3259. case DnsResourceRecordType.SRV:
  3260. {
  3261. DnsSRVRecord rdata = record.RDATA as DnsSRVRecord;
  3262. if (rdata == null)
  3263. {
  3264. jsonWriter.WritePropertyName("dataType");
  3265. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3266. jsonWriter.WritePropertyName("data");
  3267. jsonWriter.WriteValue(record.RDATA.ToString());
  3268. }
  3269. else
  3270. {
  3271. jsonWriter.WritePropertyName("priority");
  3272. jsonWriter.WriteValue(rdata.Priority);
  3273. jsonWriter.WritePropertyName("weight");
  3274. jsonWriter.WriteValue(rdata.Weight);
  3275. jsonWriter.WritePropertyName("port");
  3276. jsonWriter.WriteValue(rdata.Port);
  3277. jsonWriter.WritePropertyName("value");
  3278. jsonWriter.WriteValue(rdata.Target);
  3279. IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
  3280. if (glueRecords.Count > 0)
  3281. {
  3282. string glue = null;
  3283. foreach (DnsResourceRecord glueRecord in glueRecords)
  3284. {
  3285. if (glue == null)
  3286. glue = glueRecord.RDATA.ToString();
  3287. else
  3288. glue = glue + ", " + glueRecord.RDATA.ToString();
  3289. }
  3290. jsonWriter.WritePropertyName("glue");
  3291. jsonWriter.WriteValue(glue);
  3292. }
  3293. }
  3294. }
  3295. break;
  3296. case DnsResourceRecordType.CAA:
  3297. {
  3298. DnsCAARecord rdata = record.RDATA as DnsCAARecord;
  3299. if (rdata == null)
  3300. {
  3301. jsonWriter.WritePropertyName("dataType");
  3302. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3303. jsonWriter.WritePropertyName("data");
  3304. jsonWriter.WriteValue(record.RDATA.ToString());
  3305. }
  3306. else
  3307. {
  3308. jsonWriter.WritePropertyName("flags");
  3309. jsonWriter.WriteValue(rdata.Flags);
  3310. jsonWriter.WritePropertyName("tag");
  3311. jsonWriter.WriteValue(rdata.Tag);
  3312. jsonWriter.WritePropertyName("value");
  3313. jsonWriter.WriteValue(rdata.Value);
  3314. }
  3315. }
  3316. break;
  3317. case DnsResourceRecordType.ANAME:
  3318. {
  3319. DnsANAMERecord rdata = record.RDATA as DnsANAMERecord;
  3320. if (rdata == null)
  3321. {
  3322. jsonWriter.WritePropertyName("dataType");
  3323. jsonWriter.WriteValue(record.RDATA.GetType().Name);
  3324. jsonWriter.WritePropertyName("data");
  3325. jsonWriter.WriteValue(record.RDATA.ToString());
  3326. }
  3327. else
  3328. {
  3329. jsonWriter.WritePropertyName("value");
  3330. jsonWriter.WriteValue(rdata.Domain);
  3331. }
  3332. }
  3333. break;
  3334. case DnsResourceRecordType.FWD:
  3335. {
  3336. DnsForwarderRecord rdata = record.RDATA as DnsForwarderRecord;
  3337. if (rdata != null)
  3338. {
  3339. jsonWriter.WritePropertyName("protocol");
  3340. jsonWriter.WriteValue(rdata.Protocol.ToString());
  3341. jsonWriter.WritePropertyName("value");
  3342. jsonWriter.WriteValue(rdata.Forwarder);
  3343. }
  3344. }
  3345. break;
  3346. case DnsResourceRecordType.APP:
  3347. {
  3348. DnsApplicationRecord rdata = record.RDATA as DnsApplicationRecord;
  3349. if (rdata != null)
  3350. {
  3351. jsonWriter.WritePropertyName("value");
  3352. jsonWriter.WriteValue(rdata.AppName);
  3353. jsonWriter.WritePropertyName("classPath");
  3354. jsonWriter.WriteValue(rdata.ClassPath);
  3355. jsonWriter.WritePropertyName("data");
  3356. jsonWriter.WriteValue(rdata.Data);
  3357. }
  3358. }
  3359. break;
  3360. default:
  3361. {
  3362. jsonWriter.WritePropertyName("value");
  3363. using (MemoryStream mS = new MemoryStream())
  3364. {
  3365. record.RDATA.WriteTo(mS, new List<DnsDomainOffset>());
  3366. jsonWriter.WriteValue(Convert.ToBase64String(mS.ToArray()));
  3367. }
  3368. }
  3369. break;
  3370. }
  3371. jsonWriter.WriteEndObject();
  3372. jsonWriter.WriteEndObject();
  3373. }
  3374. }
  3375. }
  3376. jsonWriter.WriteEndArray();
  3377. }
  3378. private void DeleteRecord(HttpListenerRequest request)
  3379. {
  3380. string domain = request.QueryString["domain"];
  3381. if (string.IsNullOrEmpty(domain))
  3382. throw new DnsWebServiceException("Parameter 'domain' missing.");
  3383. if (domain.EndsWith("."))
  3384. domain = domain.Substring(0, domain.Length - 1);
  3385. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  3386. if (zoneInfo == null)
  3387. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  3388. if (zoneInfo.Internal)
  3389. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  3390. string strType = request.QueryString["type"];
  3391. if (string.IsNullOrEmpty(strType))
  3392. throw new DnsWebServiceException("Parameter 'type' missing.");
  3393. DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
  3394. string value = request.QueryString["value"];
  3395. if (string.IsNullOrEmpty(value))
  3396. throw new DnsWebServiceException("Parameter 'value' missing.");
  3397. switch (type)
  3398. {
  3399. case DnsResourceRecordType.A:
  3400. case DnsResourceRecordType.AAAA:
  3401. {
  3402. IPAddress address = IPAddress.Parse(value);
  3403. if (type == DnsResourceRecordType.A)
  3404. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsARecord(address));
  3405. else
  3406. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsAAAARecord(address));
  3407. string ptrDomain = Zone.GetReverseZone(address, type == DnsResourceRecordType.A ? 32 : 128);
  3408. AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
  3409. if ((reverseZoneInfo != null) && !reverseZoneInfo.Internal && (reverseZoneInfo.Type == AuthZoneType.Primary))
  3410. {
  3411. IReadOnlyList<DnsResourceRecord> ptrRecords = _dnsServer.AuthZoneManager.QueryRecords(ptrDomain, DnsResourceRecordType.PTR);
  3412. if (ptrRecords.Count > 0)
  3413. {
  3414. foreach (DnsResourceRecord ptrRecord in ptrRecords)
  3415. {
  3416. if ((ptrRecord.RDATA as DnsPTRRecord).Domain.Equals(domain, StringComparison.OrdinalIgnoreCase))
  3417. {
  3418. //delete PTR record and save reverse zone
  3419. _dnsServer.AuthZoneManager.DeleteRecord(ptrDomain, DnsResourceRecordType.PTR, ptrRecord.RDATA);
  3420. _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
  3421. break;
  3422. }
  3423. }
  3424. }
  3425. }
  3426. }
  3427. break;
  3428. case DnsResourceRecordType.MX:
  3429. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsMXRecord(0, value));
  3430. break;
  3431. case DnsResourceRecordType.TXT:
  3432. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsTXTRecord(value));
  3433. break;
  3434. case DnsResourceRecordType.NS:
  3435. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsNSRecord(value));
  3436. break;
  3437. case DnsResourceRecordType.ANAME:
  3438. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsANAMERecord(value));
  3439. break;
  3440. case DnsResourceRecordType.CNAME:
  3441. case DnsResourceRecordType.PTR:
  3442. case DnsResourceRecordType.APP:
  3443. _dnsServer.AuthZoneManager.DeleteRecords(domain, type);
  3444. break;
  3445. case DnsResourceRecordType.SRV:
  3446. {
  3447. string port = request.QueryString["port"];
  3448. if (string.IsNullOrEmpty(port))
  3449. throw new DnsWebServiceException("Parameter 'port' missing.");
  3450. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsSRVRecord(0, 0, ushort.Parse(port), value));
  3451. }
  3452. break;
  3453. case DnsResourceRecordType.CAA:
  3454. {
  3455. string flags = request.QueryString["flags"];
  3456. if (string.IsNullOrEmpty(flags))
  3457. throw new DnsWebServiceException("Parameter 'flags' missing.");
  3458. string tag = request.QueryString["tag"];
  3459. if (string.IsNullOrEmpty(tag))
  3460. throw new DnsWebServiceException("Parameter 'tag' missing.");
  3461. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsCAARecord(byte.Parse(flags), tag, value));
  3462. }
  3463. break;
  3464. case DnsResourceRecordType.FWD:
  3465. {
  3466. string strProtocol = request.QueryString["protocol"];
  3467. if (string.IsNullOrEmpty(strProtocol))
  3468. strProtocol = "Udp";
  3469. _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsForwarderRecord((DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true), value));
  3470. }
  3471. break;
  3472. default:
  3473. throw new DnsWebServiceException("Type not supported for DeleteRecord().");
  3474. }
  3475. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Record was deleted from authoritative zone {domain: " + domain + "; type: " + type + "; value: " + value + ";}");
  3476. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  3477. }
  3478. private void UpdateRecord(HttpListenerRequest request)
  3479. {
  3480. string strType = request.QueryString["type"];
  3481. if (string.IsNullOrEmpty(strType))
  3482. throw new DnsWebServiceException("Parameter 'type' missing.");
  3483. DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
  3484. string domain = request.QueryString["domain"];
  3485. if (string.IsNullOrEmpty(domain))
  3486. throw new DnsWebServiceException("Parameter 'domain' missing.");
  3487. if (domain.EndsWith("."))
  3488. domain = domain.Substring(0, domain.Length - 1);
  3489. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  3490. if (zoneInfo == null)
  3491. throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
  3492. if (zoneInfo.Internal)
  3493. throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
  3494. string newDomain = request.QueryString["newDomain"];
  3495. if (string.IsNullOrEmpty(newDomain))
  3496. newDomain = domain;
  3497. if (newDomain.EndsWith("."))
  3498. newDomain = newDomain.Substring(0, newDomain.Length - 1);
  3499. uint ttl;
  3500. string strTtl = request.QueryString["ttl"];
  3501. if (string.IsNullOrEmpty(strTtl))
  3502. ttl = 3600;
  3503. else
  3504. ttl = uint.Parse(strTtl);
  3505. string value = request.QueryString["value"];
  3506. string newValue = request.QueryString["newValue"];
  3507. if (string.IsNullOrEmpty(newValue))
  3508. newValue = value;
  3509. bool disable = false;
  3510. string strDisable = request.QueryString["disable"];
  3511. if (!string.IsNullOrEmpty(strDisable))
  3512. disable = bool.Parse(strDisable);
  3513. switch (type)
  3514. {
  3515. case DnsResourceRecordType.A:
  3516. case DnsResourceRecordType.AAAA:
  3517. {
  3518. IPAddress oldIpAddress = IPAddress.Parse(value);
  3519. IPAddress newIpAddress = IPAddress.Parse(newValue);
  3520. bool ptr = false;
  3521. string strPtr = request.QueryString["ptr"];
  3522. if (!string.IsNullOrEmpty(strPtr))
  3523. ptr = bool.Parse(strPtr);
  3524. if (ptr)
  3525. {
  3526. string ptrDomain = Zone.GetReverseZone(newIpAddress, type == DnsResourceRecordType.A ? 32 : 128);
  3527. AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
  3528. if (reverseZoneInfo == null)
  3529. {
  3530. bool createPtrZone = false;
  3531. string strCreatePtrZone = request.QueryString["createPtrZone"];
  3532. if (!string.IsNullOrEmpty(strCreatePtrZone))
  3533. createPtrZone = bool.Parse(strCreatePtrZone);
  3534. if (!createPtrZone)
  3535. throw new DnsServerException("No reverse zone available to add PTR record.");
  3536. string ptrZone = Zone.GetReverseZone(newIpAddress, type == DnsResourceRecordType.A ? 24 : 64);
  3537. reverseZoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(ptrZone, _dnsServer.ServerDomain, false);
  3538. if (reverseZoneInfo == null)
  3539. throw new DnsServerException("Failed to create reverse zone to add PTR record: " + ptrZone);
  3540. }
  3541. if (reverseZoneInfo.Internal)
  3542. throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is an internal zone.");
  3543. if (reverseZoneInfo.Type != AuthZoneType.Primary)
  3544. throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is not a primary zone.");
  3545. string oldPtrDomain = Zone.GetReverseZone(oldIpAddress, type == DnsResourceRecordType.A ? 32 : 128);
  3546. AuthZoneInfo oldReverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(oldPtrDomain);
  3547. if ((oldReverseZoneInfo != null) && !oldReverseZoneInfo.Internal && (oldReverseZoneInfo.Type == AuthZoneType.Primary))
  3548. {
  3549. //delete old PTR record if any and save old reverse zone
  3550. _dnsServer.AuthZoneManager.DeleteRecords(oldPtrDomain, DnsResourceRecordType.PTR);
  3551. _dnsServer.AuthZoneManager.SaveZoneFile(oldReverseZoneInfo.Name);
  3552. }
  3553. //add new PTR record and save reverse zone
  3554. _dnsServer.AuthZoneManager.SetRecords(ptrDomain, DnsResourceRecordType.PTR, ttl, new DnsPTRRecord[] { new DnsPTRRecord(domain) });
  3555. _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
  3556. }
  3557. DnsResourceRecord oldRecord;
  3558. DnsResourceRecord newRecord;
  3559. if (type == DnsResourceRecordType.A)
  3560. {
  3561. oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsARecord(oldIpAddress));
  3562. newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsARecord(newIpAddress));
  3563. }
  3564. else
  3565. {
  3566. oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsAAAARecord(oldIpAddress));
  3567. newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsAAAARecord(newIpAddress));
  3568. }
  3569. if (disable)
  3570. newRecord.Disable();
  3571. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3572. }
  3573. break;
  3574. case DnsResourceRecordType.MX:
  3575. {
  3576. string preference = request.QueryString["preference"];
  3577. if (string.IsNullOrEmpty(preference))
  3578. preference = "1";
  3579. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsMXRecord(0, value));
  3580. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsMXRecord(ushort.Parse(preference), newValue));
  3581. if (disable)
  3582. newRecord.Disable();
  3583. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3584. }
  3585. break;
  3586. case DnsResourceRecordType.TXT:
  3587. {
  3588. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsTXTRecord(value));
  3589. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsTXTRecord(newValue));
  3590. if (disable)
  3591. newRecord.Disable();
  3592. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3593. }
  3594. break;
  3595. case DnsResourceRecordType.NS:
  3596. {
  3597. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsNSRecord(value));
  3598. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsNSRecord(newValue));
  3599. if (disable)
  3600. newRecord.Disable();
  3601. string glueAddresses = request.QueryString["glue"];
  3602. if (!string.IsNullOrEmpty(glueAddresses))
  3603. newRecord.SetGlueRecords(glueAddresses);
  3604. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3605. }
  3606. break;
  3607. case DnsResourceRecordType.SOA:
  3608. {
  3609. string primaryNameServer = request.QueryString["primaryNameServer"];
  3610. if (string.IsNullOrEmpty(primaryNameServer))
  3611. throw new DnsWebServiceException("Parameter 'primaryNameServer' missing.");
  3612. string responsiblePerson = request.QueryString["responsiblePerson"];
  3613. if (string.IsNullOrEmpty(responsiblePerson))
  3614. throw new DnsWebServiceException("Parameter 'responsiblePerson' missing.");
  3615. string serial = request.QueryString["serial"];
  3616. if (string.IsNullOrEmpty(serial))
  3617. throw new DnsWebServiceException("Parameter 'serial' missing.");
  3618. string refresh = request.QueryString["refresh"];
  3619. if (string.IsNullOrEmpty(refresh))
  3620. throw new DnsWebServiceException("Parameter 'refresh' missing.");
  3621. string retry = request.QueryString["retry"];
  3622. if (string.IsNullOrEmpty(retry))
  3623. throw new DnsWebServiceException("Parameter 'retry' missing.");
  3624. string expire = request.QueryString["expire"];
  3625. if (string.IsNullOrEmpty(expire))
  3626. throw new DnsWebServiceException("Parameter 'expire' missing.");
  3627. string minimum = request.QueryString["minimum"];
  3628. if (string.IsNullOrEmpty(minimum))
  3629. throw new DnsWebServiceException("Parameter 'minimum' missing.");
  3630. DnsResourceRecord soaRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsSOARecord(primaryNameServer, responsiblePerson, uint.Parse(serial), uint.Parse(refresh), uint.Parse(retry), uint.Parse(expire), uint.Parse(minimum)));
  3631. string primaryAddresses = request.QueryString["primaryAddresses"];
  3632. if (!string.IsNullOrEmpty(primaryAddresses))
  3633. soaRecord.SetGlueRecords(primaryAddresses);
  3634. _dnsServer.AuthZoneManager.SetRecord(soaRecord);
  3635. }
  3636. break;
  3637. case DnsResourceRecordType.PTR:
  3638. {
  3639. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsPTRRecord(value));
  3640. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsPTRRecord(newValue));
  3641. if (disable)
  3642. newRecord.Disable();
  3643. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3644. }
  3645. break;
  3646. case DnsResourceRecordType.CNAME:
  3647. {
  3648. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsCNAMERecord(value));
  3649. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsCNAMERecord(newValue));
  3650. if (disable)
  3651. newRecord.Disable();
  3652. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3653. }
  3654. break;
  3655. case DnsResourceRecordType.SRV:
  3656. {
  3657. string port = request.QueryString["port"];
  3658. if (string.IsNullOrEmpty(port))
  3659. throw new DnsWebServiceException("Parameter 'port' missing.");
  3660. string priority = request.QueryString["priority"];
  3661. if (string.IsNullOrEmpty(priority))
  3662. throw new DnsWebServiceException("Parameter 'priority' missing.");
  3663. string weight = request.QueryString["weight"];
  3664. if (string.IsNullOrEmpty(weight))
  3665. throw new DnsWebServiceException("Parameter 'weight' missing.");
  3666. string newPort = request.QueryString["newPort"];
  3667. if (string.IsNullOrEmpty(newPort))
  3668. newPort = port;
  3669. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsSRVRecord(0, 0, ushort.Parse(port), value));
  3670. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsSRVRecord(ushort.Parse(priority), ushort.Parse(weight), ushort.Parse(newPort), newValue));
  3671. if (disable)
  3672. newRecord.Disable();
  3673. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3674. }
  3675. break;
  3676. case DnsResourceRecordType.CAA:
  3677. {
  3678. string flags = request.QueryString["flags"];
  3679. if (string.IsNullOrEmpty(flags))
  3680. throw new DnsWebServiceException("Parameter 'flags' missing.");
  3681. string tag = request.QueryString["tag"];
  3682. if (string.IsNullOrEmpty(tag))
  3683. throw new DnsWebServiceException("Parameter 'tag' missing.");
  3684. string newFlags = request.QueryString["newFlags"];
  3685. if (string.IsNullOrEmpty(newFlags))
  3686. newFlags = flags;
  3687. string newTag = request.QueryString["newTag"];
  3688. if (string.IsNullOrEmpty(newTag))
  3689. newTag = tag;
  3690. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsCAARecord(byte.Parse(flags), tag, value));
  3691. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsCAARecord(byte.Parse(newFlags), newTag, newValue));
  3692. if (disable)
  3693. newRecord.Disable();
  3694. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3695. }
  3696. break;
  3697. case DnsResourceRecordType.ANAME:
  3698. {
  3699. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsANAMERecord(value));
  3700. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsANAMERecord(newValue));
  3701. if (disable)
  3702. newRecord.Disable();
  3703. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3704. }
  3705. break;
  3706. case DnsResourceRecordType.FWD:
  3707. {
  3708. string strProtocol = request.QueryString["protocol"];
  3709. if (string.IsNullOrEmpty(strProtocol))
  3710. strProtocol = "Udp";
  3711. DnsTransportProtocol protocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true);
  3712. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsForwarderRecord(protocol, value));
  3713. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsForwarderRecord(protocol, newValue));
  3714. if (disable)
  3715. newRecord.Disable();
  3716. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3717. }
  3718. break;
  3719. case DnsResourceRecordType.APP:
  3720. {
  3721. string classPath = request.QueryString["classPath"];
  3722. if (string.IsNullOrEmpty(classPath))
  3723. throw new DnsWebServiceException("Parameter 'classPath' missing.");
  3724. string recordData = request.QueryString["recordData"];
  3725. if (string.IsNullOrEmpty(recordData))
  3726. recordData = "";
  3727. DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsApplicationRecord(value, classPath, recordData));
  3728. DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsApplicationRecord(newValue, classPath, recordData));
  3729. if (disable)
  3730. newRecord.Disable();
  3731. _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
  3732. }
  3733. break;
  3734. default:
  3735. throw new DnsWebServiceException("Type not supported for UpdateRecords().");
  3736. }
  3737. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Record was updated for authoritative zone {oldDomain: " + domain + "; domain: " + newDomain + "; type: " + type + "; oldValue: " + value + "; value: " + newValue + "; ttl: " + ttl + "; disabled: " + disable + ";}");
  3738. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  3739. }
  3740. #endregion
  3741. #region dns apps api
  3742. string _storeAppsJsonData;
  3743. DateTime _storeAppsJsonDataUpdatedOn;
  3744. const int STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS = 300;
  3745. private async Task<string> GetStoreAppsJsonData()
  3746. {
  3747. if ((_storeAppsJsonData == null) || (DateTime.UtcNow > _storeAppsJsonDataUpdatedOn.AddSeconds(STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS)))
  3748. {
  3749. SocketsHttpHandler handler = new SocketsHttpHandler();
  3750. handler.Proxy = _dnsServer.Proxy;
  3751. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  3752. using (HttpClient http = new HttpClient(handler))
  3753. {
  3754. _storeAppsJsonData = await http.GetStringAsync(_appStoreUri);
  3755. _storeAppsJsonDataUpdatedOn = DateTime.UtcNow;
  3756. }
  3757. }
  3758. return _storeAppsJsonData;
  3759. }
  3760. private async Task ListInstalledAppsAsync(JsonTextWriter jsonWriter)
  3761. {
  3762. List<string> apps = new List<string>(_dnsServer.DnsApplicationManager.Applications.Keys);
  3763. apps.Sort();
  3764. dynamic jsonStoreAppsArray = null;
  3765. if (apps.Count > 0)
  3766. {
  3767. try
  3768. {
  3769. string storeAppsJsonData = await GetStoreAppsJsonData().WithTimeout(5000);
  3770. jsonStoreAppsArray = JsonConvert.DeserializeObject(storeAppsJsonData);
  3771. }
  3772. catch
  3773. { }
  3774. }
  3775. jsonWriter.WritePropertyName("apps");
  3776. jsonWriter.WriteStartArray();
  3777. foreach (string app in apps)
  3778. {
  3779. if (_dnsServer.DnsApplicationManager.Applications.TryGetValue(app, out DnsApplication application))
  3780. {
  3781. jsonWriter.WriteStartObject();
  3782. jsonWriter.WritePropertyName("name");
  3783. jsonWriter.WriteValue(application.AppName);
  3784. jsonWriter.WritePropertyName("version");
  3785. jsonWriter.WriteValue(GetCleanVersion(application.Version));
  3786. if (jsonStoreAppsArray != null)
  3787. {
  3788. foreach (dynamic jsonStoreApp in jsonStoreAppsArray)
  3789. {
  3790. string name = jsonStoreApp.name.Value;
  3791. if (name.Equals(application.AppName))
  3792. {
  3793. string version = jsonStoreApp.version.Value;
  3794. string url = jsonStoreApp.url.Value;
  3795. jsonWriter.WritePropertyName("updateVersion");
  3796. jsonWriter.WriteValue(version);
  3797. jsonWriter.WritePropertyName("updateUrl");
  3798. jsonWriter.WriteValue(url);
  3799. jsonWriter.WritePropertyName("updateAvailable");
  3800. jsonWriter.WriteValue(new Version(version) > application.Version);
  3801. break;
  3802. }
  3803. }
  3804. }
  3805. jsonWriter.WritePropertyName("details");
  3806. jsonWriter.WriteStartArray();
  3807. foreach (KeyValuePair<string, IDnsApplicationRequestHandler> handler in application.DnsRequestHandlers)
  3808. {
  3809. jsonWriter.WriteStartObject();
  3810. jsonWriter.WritePropertyName("classPath");
  3811. jsonWriter.WriteValue(handler.Key);
  3812. jsonWriter.WritePropertyName("description");
  3813. jsonWriter.WriteValue(handler.Value.Description);
  3814. jsonWriter.WritePropertyName("recordDataTemplate");
  3815. jsonWriter.WriteValue(handler.Value.ApplicationRecordDataTemplate);
  3816. jsonWriter.WriteEndObject();
  3817. }
  3818. jsonWriter.WriteEndArray();
  3819. jsonWriter.WriteEndObject();
  3820. }
  3821. }
  3822. jsonWriter.WriteEndArray();
  3823. }
  3824. private async Task ListStoreApps(JsonTextWriter jsonWriter)
  3825. {
  3826. string storeAppsJsonData = await GetStoreAppsJsonData();
  3827. dynamic jsonStoreAppsArray = JsonConvert.DeserializeObject(storeAppsJsonData);
  3828. jsonWriter.WritePropertyName("storeApps");
  3829. jsonWriter.WriteStartArray();
  3830. foreach (dynamic jsonStoreApp in jsonStoreAppsArray)
  3831. {
  3832. string name = jsonStoreApp.name.Value;
  3833. string version = jsonStoreApp.version.Value;
  3834. string description = jsonStoreApp.description.Value;
  3835. string url = jsonStoreApp.url.Value;
  3836. string size = jsonStoreApp.size.Value;
  3837. jsonWriter.WriteStartObject();
  3838. jsonWriter.WritePropertyName("name");
  3839. jsonWriter.WriteValue(name);
  3840. jsonWriter.WritePropertyName("version");
  3841. jsonWriter.WriteValue(version);
  3842. jsonWriter.WritePropertyName("description");
  3843. jsonWriter.WriteValue(description);
  3844. jsonWriter.WritePropertyName("url");
  3845. jsonWriter.WriteValue(url);
  3846. jsonWriter.WritePropertyName("size");
  3847. jsonWriter.WriteValue(size);
  3848. bool installed = _dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication installedApp);
  3849. jsonWriter.WritePropertyName("installed");
  3850. jsonWriter.WriteValue(installed);
  3851. if (installed)
  3852. {
  3853. jsonWriter.WritePropertyName("installedVersion");
  3854. jsonWriter.WriteValue(GetCleanVersion(installedApp.Version));
  3855. jsonWriter.WritePropertyName("updateAvailable");
  3856. jsonWriter.WriteValue(new Version(version) > installedApp.Version);
  3857. }
  3858. jsonWriter.WriteEndObject();
  3859. }
  3860. jsonWriter.WriteEndArray();
  3861. }
  3862. private async Task DownloadAndInstallAppAsync(HttpListenerRequest request)
  3863. {
  3864. string name = request.QueryString["name"];
  3865. if (string.IsNullOrEmpty(name))
  3866. throw new DnsWebServiceException("Parameter 'name' missing.");
  3867. string url = request.QueryString["url"];
  3868. if (string.IsNullOrEmpty(url))
  3869. throw new DnsWebServiceException("Parameter 'url' missing.");
  3870. if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  3871. throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
  3872. string tmpFile = Path.GetTempFileName();
  3873. try
  3874. {
  3875. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  3876. {
  3877. //download to temp file
  3878. SocketsHttpHandler handler = new SocketsHttpHandler();
  3879. handler.Proxy = _dnsServer.Proxy;
  3880. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  3881. using (HttpClient http = new HttpClient(handler))
  3882. {
  3883. using (Stream httpStream = await http.GetStreamAsync(url))
  3884. {
  3885. await httpStream.CopyToAsync(fS);
  3886. }
  3887. }
  3888. //install app
  3889. fS.Position = 0;
  3890. await _dnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
  3891. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was installed successfully from: " + url);
  3892. }
  3893. }
  3894. finally
  3895. {
  3896. try
  3897. {
  3898. File.Delete(tmpFile);
  3899. }
  3900. catch (Exception ex)
  3901. {
  3902. _log.Write(ex);
  3903. }
  3904. }
  3905. }
  3906. private async Task DownloadAndUpdateAppAsync(HttpListenerRequest request)
  3907. {
  3908. string name = request.QueryString["name"];
  3909. if (string.IsNullOrEmpty(name))
  3910. throw new DnsWebServiceException("Parameter 'name' missing.");
  3911. string url = request.QueryString["url"];
  3912. if (string.IsNullOrEmpty(url))
  3913. throw new DnsWebServiceException("Parameter 'url' missing.");
  3914. if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  3915. throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
  3916. string tmpFile = Path.GetTempFileName();
  3917. try
  3918. {
  3919. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  3920. {
  3921. //download to temp file
  3922. SocketsHttpHandler handler = new SocketsHttpHandler();
  3923. handler.Proxy = _dnsServer.Proxy;
  3924. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  3925. using (HttpClient http = new HttpClient(handler))
  3926. {
  3927. using (Stream httpStream = await http.GetStreamAsync(url))
  3928. {
  3929. await httpStream.CopyToAsync(fS);
  3930. }
  3931. }
  3932. //update app
  3933. fS.Position = 0;
  3934. await _dnsServer.DnsApplicationManager.UpdateApplicationAsync(name, fS);
  3935. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was updated successfully from: " + url);
  3936. }
  3937. }
  3938. finally
  3939. {
  3940. try
  3941. {
  3942. File.Delete(tmpFile);
  3943. }
  3944. catch (Exception ex)
  3945. {
  3946. _log.Write(ex);
  3947. }
  3948. }
  3949. }
  3950. private async Task InstallAppAsync(HttpListenerRequest request)
  3951. {
  3952. string name = request.QueryString["name"];
  3953. if (string.IsNullOrEmpty(name))
  3954. throw new DnsWebServiceException("Parameter 'name' missing.");
  3955. #region skip to content
  3956. int crlfCount = 0;
  3957. int byteRead;
  3958. while (crlfCount != 4)
  3959. {
  3960. byteRead = request.InputStream.ReadByte();
  3961. switch (byteRead)
  3962. {
  3963. case -1:
  3964. throw new EndOfStreamException();
  3965. case 13: //CR
  3966. case 10: //LF
  3967. crlfCount++;
  3968. break;
  3969. default:
  3970. crlfCount = 0;
  3971. break;
  3972. }
  3973. }
  3974. #endregion
  3975. string tmpFile = Path.GetTempFileName();
  3976. try
  3977. {
  3978. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  3979. {
  3980. //write to temp file
  3981. await request.InputStream.CopyToAsync(fS);
  3982. //install app
  3983. fS.Position = 0;
  3984. await _dnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
  3985. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was installed successfully.");
  3986. }
  3987. }
  3988. finally
  3989. {
  3990. try
  3991. {
  3992. File.Delete(tmpFile);
  3993. }
  3994. catch (Exception ex)
  3995. {
  3996. _log.Write(ex);
  3997. }
  3998. }
  3999. }
  4000. private async Task UpdateAppAsync(HttpListenerRequest request)
  4001. {
  4002. string name = request.QueryString["name"];
  4003. if (string.IsNullOrEmpty(name))
  4004. throw new DnsWebServiceException("Parameter 'name' missing.");
  4005. #region skip to content
  4006. int crlfCount = 0;
  4007. int byteRead;
  4008. while (crlfCount != 4)
  4009. {
  4010. byteRead = request.InputStream.ReadByte();
  4011. switch (byteRead)
  4012. {
  4013. case -1:
  4014. throw new EndOfStreamException();
  4015. case 13: //CR
  4016. case 10: //LF
  4017. crlfCount++;
  4018. break;
  4019. default:
  4020. crlfCount = 0;
  4021. break;
  4022. }
  4023. }
  4024. #endregion
  4025. string tmpFile = Path.GetTempFileName();
  4026. try
  4027. {
  4028. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  4029. {
  4030. //write to temp file
  4031. await request.InputStream.CopyToAsync(fS);
  4032. //update app
  4033. fS.Position = 0;
  4034. await _dnsServer.DnsApplicationManager.UpdateApplicationAsync(name, fS);
  4035. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was updated successfully.");
  4036. }
  4037. }
  4038. finally
  4039. {
  4040. try
  4041. {
  4042. File.Delete(tmpFile);
  4043. }
  4044. catch (Exception ex)
  4045. {
  4046. _log.Write(ex);
  4047. }
  4048. }
  4049. }
  4050. private void UninstallApp(HttpListenerRequest request)
  4051. {
  4052. string name = request.QueryString["name"];
  4053. if (string.IsNullOrEmpty(name))
  4054. throw new DnsWebServiceException("Parameter 'name' missing.");
  4055. _dnsServer.DnsApplicationManager.UninstallApplication(name);
  4056. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was uninstalled successfully.");
  4057. }
  4058. private async Task GetAppConfigAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
  4059. {
  4060. string name = request.QueryString["name"];
  4061. if (string.IsNullOrEmpty(name))
  4062. throw new DnsWebServiceException("Parameter 'name' missing.");
  4063. if (!_dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
  4064. throw new DnsWebServiceException("DNS application was not found: " + name);
  4065. string config = await application.GetConfigAsync();
  4066. jsonWriter.WritePropertyName("config");
  4067. jsonWriter.WriteValue(config);
  4068. }
  4069. private async Task SetAppConfigAsync(HttpListenerRequest request)
  4070. {
  4071. string name = request.QueryString["name"];
  4072. if (string.IsNullOrEmpty(name))
  4073. throw new DnsWebServiceException("Parameter 'name' missing.");
  4074. if (!_dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
  4075. throw new DnsWebServiceException("DNS application was not found: " + name);
  4076. string formRequest;
  4077. using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
  4078. {
  4079. formRequest = sR.ReadToEnd();
  4080. }
  4081. string[] formParts = formRequest.Split('&');
  4082. foreach (string formPart in formParts)
  4083. {
  4084. if (formPart.StartsWith("config="))
  4085. {
  4086. string config = formPart.Substring(7);
  4087. if (config.Length == 0)
  4088. config = null;
  4089. await application.SetConfigAsync(config);
  4090. break;
  4091. }
  4092. }
  4093. }
  4094. #endregion
  4095. #region dns client api
  4096. private async Task ResolveQuery(HttpListenerRequest request, JsonTextWriter jsonWriter)
  4097. {
  4098. string server = request.QueryString["server"];
  4099. if (string.IsNullOrEmpty(server))
  4100. throw new DnsWebServiceException("Parameter 'server' missing.");
  4101. string domain = request.QueryString["domain"];
  4102. if (string.IsNullOrEmpty(domain))
  4103. throw new DnsWebServiceException("Parameter 'domain' missing.");
  4104. domain = domain.Trim();
  4105. if (domain.EndsWith("."))
  4106. domain = domain.Substring(0, domain.Length - 1);
  4107. string strType = request.QueryString["type"];
  4108. if (string.IsNullOrEmpty(strType))
  4109. throw new DnsWebServiceException("Parameter 'type' missing.");
  4110. DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
  4111. string strProtocol = request.QueryString["protocol"];
  4112. if (string.IsNullOrEmpty(strProtocol))
  4113. strProtocol = "Udp";
  4114. bool importRecords = false;
  4115. string strImport = request.QueryString["import"];
  4116. if (!string.IsNullOrEmpty(strImport))
  4117. importRecords = bool.Parse(strImport);
  4118. NetProxy proxy = _dnsServer.Proxy;
  4119. bool preferIPv6 = _dnsServer.PreferIPv6;
  4120. bool randomizeName = false;
  4121. bool qnameMinimization = _dnsServer.QnameMinimization;
  4122. DnsTransportProtocol protocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true);
  4123. const int RETRIES = 1;
  4124. const int TIMEOUT = 10000;
  4125. DnsDatagram dnsResponse;
  4126. if (server.Equals("recursive-resolver", StringComparison.OrdinalIgnoreCase))
  4127. {
  4128. if (type == DnsResourceRecordType.AXFR)
  4129. throw new DnsServerException("Cannot do zone transfer (AXFR) for 'recursive-resolver'.");
  4130. DnsQuestionRecord question;
  4131. if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress address))
  4132. question = new DnsQuestionRecord(address, DnsClass.IN);
  4133. else
  4134. question = new DnsQuestionRecord(domain, type, DnsClass.IN);
  4135. dnsResponse = await DnsClient.RecursiveResolveAsync(question, null, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
  4136. }
  4137. else
  4138. {
  4139. if (type == DnsResourceRecordType.AXFR)
  4140. protocol = DnsTransportProtocol.Tcp;
  4141. NameServerAddress nameServer;
  4142. if (server.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  4143. {
  4144. switch (protocol)
  4145. {
  4146. case DnsTransportProtocol.Udp:
  4147. nameServer = _dnsServer.ThisServer;
  4148. break;
  4149. case DnsTransportProtocol.Tcp:
  4150. nameServer = new NameServerAddress(_dnsServer.ThisServer, DnsTransportProtocol.Tcp);
  4151. break;
  4152. case DnsTransportProtocol.Tls:
  4153. throw new DnsServerException("Cannot use DNS-over-TLS protocol for 'this-server'. Please use the TLS certificate domain name as the server.");
  4154. case DnsTransportProtocol.Https:
  4155. throw new DnsServerException("Cannot use DNS-over-HTTPS protocol for 'this-server'. Please use the TLS certificate domain name with a url as the server.");
  4156. case DnsTransportProtocol.HttpsJson:
  4157. throw new DnsServerException("Cannot use DNS-over-HTTPS (JSON) protocol for 'this-server'. Please use the TLS certificate domain name with a url as the server.");
  4158. default:
  4159. throw new InvalidOperationException();
  4160. }
  4161. proxy = null; //no proxy required for this server
  4162. }
  4163. else
  4164. {
  4165. if ((protocol == DnsTransportProtocol.Tls) && !server.Contains(":853"))
  4166. server += ":853";
  4167. nameServer = new NameServerAddress(server, protocol);
  4168. if (nameServer.IPEndPoint == null)
  4169. {
  4170. if (proxy == null)
  4171. {
  4172. if (_dnsServer.AllowRecursion)
  4173. await nameServer.ResolveIPAddressAsync(new NameServerAddress[] { _dnsServer.ThisServer }, proxy, preferIPv6, randomizeName, RETRIES, TIMEOUT);
  4174. else
  4175. await nameServer.RecursiveResolveIPAddressAsync(_dnsServer.DnsCache, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
  4176. }
  4177. }
  4178. else if (protocol != DnsTransportProtocol.Tls)
  4179. {
  4180. try
  4181. {
  4182. if (_dnsServer.AllowRecursion)
  4183. await nameServer.ResolveDomainNameAsync(new NameServerAddress[] { _dnsServer.ThisServer }, proxy, preferIPv6, randomizeName, RETRIES, TIMEOUT);
  4184. else
  4185. await nameServer.RecursiveResolveDomainNameAsync(_dnsServer.DnsCache, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
  4186. }
  4187. catch
  4188. { }
  4189. }
  4190. }
  4191. dnsResponse = await new DnsClient(nameServer) { Proxy = proxy, PreferIPv6 = preferIPv6, RandomizeName = randomizeName, Retries = RETRIES, Timeout = TIMEOUT }.ResolveAsync(domain, type);
  4192. }
  4193. if (importRecords)
  4194. {
  4195. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  4196. if (zoneInfo == null)
  4197. {
  4198. zoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(domain, _dnsServer.ServerDomain, false);
  4199. if (zoneInfo == null)
  4200. throw new DnsServerException("Cannot import records: failed to create primary zone.");
  4201. }
  4202. else
  4203. {
  4204. switch (zoneInfo.Type)
  4205. {
  4206. case AuthZoneType.Primary:
  4207. case AuthZoneType.Forwarder:
  4208. break;
  4209. default:
  4210. throw new DnsServerException("Cannot import records: import zone must be of primary or forwarder type.");
  4211. }
  4212. }
  4213. if (type == DnsResourceRecordType.AXFR)
  4214. {
  4215. bool dontRemoveRecords = zoneInfo.Type == AuthZoneType.Forwarder;
  4216. _dnsServer.AuthZoneManager.SyncRecords(domain, dnsResponse.Answer, null, dontRemoveRecords);
  4217. }
  4218. else
  4219. {
  4220. List<DnsResourceRecord> syncRecords = new List<DnsResourceRecord>();
  4221. foreach (DnsResourceRecord record in dnsResponse.Answer)
  4222. {
  4223. if (record.Name.Equals(domain, StringComparison.OrdinalIgnoreCase))
  4224. {
  4225. record.RemoveExpiry();
  4226. syncRecords.Add(record);
  4227. }
  4228. }
  4229. _dnsServer.AuthZoneManager.SyncRecords(domain, syncRecords, null, true);
  4230. }
  4231. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS Client imported record(s) for authoritative zone {server: " + server + "; domain: " + domain + "; type: " + type + ";}");
  4232. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  4233. }
  4234. jsonWriter.WritePropertyName("result");
  4235. jsonWriter.WriteRawValue(JsonConvert.SerializeObject(dnsResponse, new StringEnumConverter()));
  4236. }
  4237. #endregion
  4238. #region logs api
  4239. private void ListLogs(JsonTextWriter jsonWriter)
  4240. {
  4241. string[] logFiles = _log.ListLogFiles();
  4242. Array.Sort(logFiles);
  4243. Array.Reverse(logFiles);
  4244. jsonWriter.WritePropertyName("logFiles");
  4245. jsonWriter.WriteStartArray();
  4246. foreach (string logFile in logFiles)
  4247. {
  4248. jsonWriter.WriteStartObject();
  4249. jsonWriter.WritePropertyName("fileName");
  4250. jsonWriter.WriteValue(Path.GetFileNameWithoutExtension(logFile));
  4251. jsonWriter.WritePropertyName("size");
  4252. jsonWriter.WriteValue(WebUtilities.GetFormattedSize(new FileInfo(logFile).Length));
  4253. jsonWriter.WriteEndObject();
  4254. }
  4255. jsonWriter.WriteEndArray();
  4256. }
  4257. private void DeleteLog(HttpListenerRequest request)
  4258. {
  4259. string log = request.QueryString["log"];
  4260. if (string.IsNullOrEmpty(log))
  4261. throw new DnsWebServiceException("Parameter 'log' missing.");
  4262. _log.DeleteLog(log);
  4263. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Log file was deleted: " + log);
  4264. }
  4265. private void DeleteAllLogs(HttpListenerRequest request)
  4266. {
  4267. _log.DeleteAllLogs();
  4268. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] All log files were deleted.");
  4269. }
  4270. private void DeleteAllStats(HttpListenerRequest request)
  4271. {
  4272. _dnsServer.StatsManager.DeleteAllStats();
  4273. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] All stats files were deleted.");
  4274. }
  4275. #endregion
  4276. #region dhcp api
  4277. private void ListDhcpLeases(JsonTextWriter jsonWriter)
  4278. {
  4279. IReadOnlyDictionary<string, Scope> scopes = _dhcpServer.Scopes;
  4280. //sort by name
  4281. List<Scope> sortedScopes = new List<Scope>(scopes.Count);
  4282. foreach (KeyValuePair<string, Scope> entry in scopes)
  4283. sortedScopes.Add(entry.Value);
  4284. sortedScopes.Sort();
  4285. jsonWriter.WritePropertyName("leases");
  4286. jsonWriter.WriteStartArray();
  4287. foreach (Scope scope in sortedScopes)
  4288. {
  4289. IReadOnlyDictionary<ClientIdentifierOption, Lease> leases = scope.Leases;
  4290. //sort by address
  4291. List<Lease> sortedLeases = new List<Lease>(leases.Count);
  4292. foreach (KeyValuePair<ClientIdentifierOption, Lease> entry in leases)
  4293. sortedLeases.Add(entry.Value);
  4294. sortedLeases.Sort();
  4295. foreach (Lease lease in sortedLeases)
  4296. {
  4297. jsonWriter.WriteStartObject();
  4298. jsonWriter.WritePropertyName("scope");
  4299. jsonWriter.WriteValue(scope.Name);
  4300. jsonWriter.WritePropertyName("type");
  4301. jsonWriter.WriteValue(lease.Type.ToString());
  4302. jsonWriter.WritePropertyName("hardwareAddress");
  4303. jsonWriter.WriteValue(BitConverter.ToString(lease.HardwareAddress));
  4304. jsonWriter.WritePropertyName("address");
  4305. jsonWriter.WriteValue(lease.Address.ToString());
  4306. jsonWriter.WritePropertyName("hostName");
  4307. jsonWriter.WriteValue(lease.HostName);
  4308. jsonWriter.WritePropertyName("leaseObtained");
  4309. jsonWriter.WriteValue(lease.LeaseObtained.ToLocalTime().ToString());
  4310. jsonWriter.WritePropertyName("leaseExpires");
  4311. jsonWriter.WriteValue(lease.LeaseExpires.ToLocalTime().ToString());
  4312. jsonWriter.WriteEndObject();
  4313. }
  4314. }
  4315. jsonWriter.WriteEndArray();
  4316. }
  4317. private void ListDhcpScopes(JsonTextWriter jsonWriter)
  4318. {
  4319. IReadOnlyDictionary<string, Scope> scopes = _dhcpServer.Scopes;
  4320. //sort by name
  4321. List<Scope> sortedScopes = new List<Scope>(scopes.Count);
  4322. foreach (KeyValuePair<string, Scope> entry in scopes)
  4323. sortedScopes.Add(entry.Value);
  4324. sortedScopes.Sort();
  4325. jsonWriter.WritePropertyName("scopes");
  4326. jsonWriter.WriteStartArray();
  4327. foreach (Scope scope in sortedScopes)
  4328. {
  4329. jsonWriter.WriteStartObject();
  4330. jsonWriter.WritePropertyName("name");
  4331. jsonWriter.WriteValue(scope.Name);
  4332. jsonWriter.WritePropertyName("enabled");
  4333. jsonWriter.WriteValue(scope.Enabled);
  4334. jsonWriter.WritePropertyName("startingAddress");
  4335. jsonWriter.WriteValue(scope.StartingAddress.ToString());
  4336. jsonWriter.WritePropertyName("endingAddress");
  4337. jsonWriter.WriteValue(scope.EndingAddress.ToString());
  4338. jsonWriter.WritePropertyName("subnetMask");
  4339. jsonWriter.WriteValue(scope.SubnetMask.ToString());
  4340. jsonWriter.WritePropertyName("networkAddress");
  4341. jsonWriter.WriteValue(scope.NetworkAddress.ToString());
  4342. jsonWriter.WritePropertyName("broadcastAddress");
  4343. jsonWriter.WriteValue(scope.BroadcastAddress.ToString());
  4344. if (scope.InterfaceAddress != null)
  4345. {
  4346. jsonWriter.WritePropertyName("interfaceAddress");
  4347. jsonWriter.WriteValue(scope.InterfaceAddress.ToString());
  4348. }
  4349. jsonWriter.WriteEndObject();
  4350. }
  4351. jsonWriter.WriteEndArray();
  4352. }
  4353. private void GetDhcpScope(HttpListenerRequest request, JsonTextWriter jsonWriter)
  4354. {
  4355. string scopeName = request.QueryString["name"];
  4356. if (string.IsNullOrEmpty(scopeName))
  4357. throw new DnsWebServiceException("Parameter 'name' missing.");
  4358. Scope scope = _dhcpServer.GetScope(scopeName);
  4359. if (scope == null)
  4360. throw new DnsWebServiceException("DHCP scope was not found: " + scopeName);
  4361. jsonWriter.WritePropertyName("name");
  4362. jsonWriter.WriteValue(scope.Name);
  4363. jsonWriter.WritePropertyName("startingAddress");
  4364. jsonWriter.WriteValue(scope.StartingAddress.ToString());
  4365. jsonWriter.WritePropertyName("endingAddress");
  4366. jsonWriter.WriteValue(scope.EndingAddress.ToString());
  4367. jsonWriter.WritePropertyName("subnetMask");
  4368. jsonWriter.WriteValue(scope.SubnetMask.ToString());
  4369. jsonWriter.WritePropertyName("leaseTimeDays");
  4370. jsonWriter.WriteValue(scope.LeaseTimeDays);
  4371. jsonWriter.WritePropertyName("leaseTimeHours");
  4372. jsonWriter.WriteValue(scope.LeaseTimeHours);
  4373. jsonWriter.WritePropertyName("leaseTimeMinutes");
  4374. jsonWriter.WriteValue(scope.LeaseTimeMinutes);
  4375. jsonWriter.WritePropertyName("offerDelayTime");
  4376. jsonWriter.WriteValue(scope.OfferDelayTime);
  4377. if (!string.IsNullOrEmpty(scope.DomainName))
  4378. {
  4379. jsonWriter.WritePropertyName("domainName");
  4380. jsonWriter.WriteValue(scope.DomainName);
  4381. }
  4382. jsonWriter.WritePropertyName("dnsTtl");
  4383. jsonWriter.WriteValue(scope.DnsTtl);
  4384. if (scope.ServerAddress != null)
  4385. {
  4386. jsonWriter.WritePropertyName("serverAddress");
  4387. jsonWriter.WriteValue(scope.ServerAddress.ToString());
  4388. }
  4389. if (scope.ServerHostName != null)
  4390. {
  4391. jsonWriter.WritePropertyName("serverHostName");
  4392. jsonWriter.WriteValue(scope.ServerHostName);
  4393. }
  4394. if (scope.BootFileName != null)
  4395. {
  4396. jsonWriter.WritePropertyName("bootFileName");
  4397. jsonWriter.WriteValue(scope.BootFileName);
  4398. }
  4399. if (scope.RouterAddress != null)
  4400. {
  4401. jsonWriter.WritePropertyName("routerAddress");
  4402. jsonWriter.WriteValue(scope.RouterAddress.ToString());
  4403. }
  4404. jsonWriter.WritePropertyName("useThisDnsServer");
  4405. jsonWriter.WriteValue(scope.UseThisDnsServer);
  4406. if (scope.DnsServers != null)
  4407. {
  4408. jsonWriter.WritePropertyName("dnsServers");
  4409. jsonWriter.WriteStartArray();
  4410. foreach (IPAddress dnsServer in scope.DnsServers)
  4411. jsonWriter.WriteValue(dnsServer.ToString());
  4412. jsonWriter.WriteEndArray();
  4413. }
  4414. if (scope.WinsServers != null)
  4415. {
  4416. jsonWriter.WritePropertyName("winsServers");
  4417. jsonWriter.WriteStartArray();
  4418. foreach (IPAddress winsServer in scope.WinsServers)
  4419. jsonWriter.WriteValue(winsServer.ToString());
  4420. jsonWriter.WriteEndArray();
  4421. }
  4422. if (scope.NtpServers != null)
  4423. {
  4424. jsonWriter.WritePropertyName("ntpServers");
  4425. jsonWriter.WriteStartArray();
  4426. foreach (IPAddress ntpServer in scope.NtpServers)
  4427. jsonWriter.WriteValue(ntpServer.ToString());
  4428. jsonWriter.WriteEndArray();
  4429. }
  4430. if (scope.StaticRoutes != null)
  4431. {
  4432. jsonWriter.WritePropertyName("staticRoutes");
  4433. jsonWriter.WriteStartArray();
  4434. foreach (ClasslessStaticRouteOption.Route route in scope.StaticRoutes)
  4435. {
  4436. jsonWriter.WriteStartObject();
  4437. jsonWriter.WritePropertyName("destination");
  4438. jsonWriter.WriteValue(route.Destination.ToString());
  4439. jsonWriter.WritePropertyName("subnetMask");
  4440. jsonWriter.WriteValue(route.SubnetMask.ToString());
  4441. jsonWriter.WritePropertyName("router");
  4442. jsonWriter.WriteValue(route.Router.ToString());
  4443. jsonWriter.WriteEndObject();
  4444. }
  4445. jsonWriter.WriteEndArray();
  4446. }
  4447. if (scope.VendorInfo != null)
  4448. {
  4449. jsonWriter.WritePropertyName("vendorInfo");
  4450. jsonWriter.WriteStartArray();
  4451. foreach (KeyValuePair<string, VendorSpecificInformationOption> entry in scope.VendorInfo)
  4452. {
  4453. jsonWriter.WriteStartObject();
  4454. jsonWriter.WritePropertyName("identifier");
  4455. jsonWriter.WriteValue(entry.Key);
  4456. jsonWriter.WritePropertyName("information");
  4457. jsonWriter.WriteValue(entry.Value.ToString());
  4458. jsonWriter.WriteEndObject();
  4459. }
  4460. jsonWriter.WriteEndArray();
  4461. }
  4462. if (scope.Exclusions != null)
  4463. {
  4464. jsonWriter.WritePropertyName("exclusions");
  4465. jsonWriter.WriteStartArray();
  4466. foreach (Exclusion exclusion in scope.Exclusions)
  4467. {
  4468. jsonWriter.WriteStartObject();
  4469. jsonWriter.WritePropertyName("startingAddress");
  4470. jsonWriter.WriteValue(exclusion.StartingAddress.ToString());
  4471. jsonWriter.WritePropertyName("endingAddress");
  4472. jsonWriter.WriteValue(exclusion.EndingAddress.ToString());
  4473. jsonWriter.WriteEndObject();
  4474. }
  4475. jsonWriter.WriteEndArray();
  4476. }
  4477. jsonWriter.WritePropertyName("reservedLeases");
  4478. jsonWriter.WriteStartArray();
  4479. foreach (Lease reservedLease in scope.ReservedLeases)
  4480. {
  4481. jsonWriter.WriteStartObject();
  4482. jsonWriter.WritePropertyName("hostName");
  4483. jsonWriter.WriteValue(reservedLease.HostName);
  4484. jsonWriter.WritePropertyName("hardwareAddress");
  4485. jsonWriter.WriteValue(BitConverter.ToString(reservedLease.HardwareAddress));
  4486. jsonWriter.WritePropertyName("address");
  4487. jsonWriter.WriteValue(reservedLease.Address.ToString());
  4488. jsonWriter.WritePropertyName("comments");
  4489. jsonWriter.WriteValue(reservedLease.Comments);
  4490. jsonWriter.WriteEndObject();
  4491. }
  4492. jsonWriter.WriteEndArray();
  4493. jsonWriter.WritePropertyName("allowOnlyReservedLeases");
  4494. jsonWriter.WriteValue(scope.AllowOnlyReservedLeases);
  4495. }
  4496. private async Task SetDhcpScopeAsync(HttpListenerRequest request)
  4497. {
  4498. string scopeName = request.QueryString["name"];
  4499. if (string.IsNullOrEmpty(scopeName))
  4500. throw new DnsWebServiceException("Parameter 'name' missing.");
  4501. string newName = request.QueryString["newName"];
  4502. if (!string.IsNullOrEmpty(newName) && !newName.Equals(scopeName))
  4503. {
  4504. _dhcpServer.RenameScope(scopeName, newName);
  4505. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was renamed successfully: '" + scopeName + "' to '" + newName + "'");
  4506. scopeName = newName;
  4507. }
  4508. string strStartingAddress = request.QueryString["startingAddress"];
  4509. if (string.IsNullOrEmpty(strStartingAddress))
  4510. throw new DnsWebServiceException("Parameter 'startingAddress' missing.");
  4511. string strEndingAddress = request.QueryString["endingAddress"];
  4512. if (string.IsNullOrEmpty(strEndingAddress))
  4513. throw new DnsWebServiceException("Parameter 'endingAddress' missing.");
  4514. string strSubnetMask = request.QueryString["subnetMask"];
  4515. if (string.IsNullOrEmpty(strSubnetMask))
  4516. throw new DnsWebServiceException("Parameter 'subnetMask' missing.");
  4517. bool scopeExists;
  4518. Scope scope = _dhcpServer.GetScope(scopeName);
  4519. if (scope == null)
  4520. {
  4521. //scope does not exists; create new scope
  4522. scopeExists = false;
  4523. scope = new Scope(scopeName, true, IPAddress.Parse(strStartingAddress), IPAddress.Parse(strEndingAddress), IPAddress.Parse(strSubnetMask));
  4524. }
  4525. else
  4526. {
  4527. scopeExists = true;
  4528. IPAddress startingAddress = IPAddress.Parse(strStartingAddress);
  4529. IPAddress endingAddress = IPAddress.Parse(strEndingAddress);
  4530. //validate scope address
  4531. foreach (KeyValuePair<string, Scope> entry in _dhcpServer.Scopes)
  4532. {
  4533. Scope existingScope = entry.Value;
  4534. if (existingScope.Equals(scope))
  4535. continue;
  4536. if (existingScope.IsAddressInRange(startingAddress) || existingScope.IsAddressInRange(endingAddress))
  4537. throw new DhcpServerException("Scope with overlapping range already exists: " + existingScope.StartingAddress.ToString() + "-" + existingScope.EndingAddress.ToString());
  4538. }
  4539. scope.ChangeNetwork(startingAddress, endingAddress, IPAddress.Parse(strSubnetMask));
  4540. }
  4541. string strLeaseTimeDays = request.QueryString["leaseTimeDays"];
  4542. if (!string.IsNullOrEmpty(strLeaseTimeDays))
  4543. scope.LeaseTimeDays = ushort.Parse(strLeaseTimeDays);
  4544. string strLeaseTimeHours = request.QueryString["leaseTimeHours"];
  4545. if (!string.IsNullOrEmpty(strLeaseTimeHours))
  4546. scope.LeaseTimeHours = byte.Parse(strLeaseTimeHours);
  4547. string strLeaseTimeMinutes = request.QueryString["leaseTimeMinutes"];
  4548. if (!string.IsNullOrEmpty(strLeaseTimeMinutes))
  4549. scope.LeaseTimeMinutes = byte.Parse(strLeaseTimeMinutes);
  4550. string strOfferDelayTime = request.QueryString["offerDelayTime"];
  4551. if (!string.IsNullOrEmpty(strOfferDelayTime))
  4552. scope.OfferDelayTime = ushort.Parse(strOfferDelayTime);
  4553. string strDomainName = request.QueryString["domainName"];
  4554. if (strDomainName != null)
  4555. scope.DomainName = strDomainName.Length == 0 ? null : strDomainName;
  4556. string strDnsTtl = request.QueryString["dnsTtl"];
  4557. if (!string.IsNullOrEmpty(strDnsTtl))
  4558. scope.DnsTtl = uint.Parse(strDnsTtl);
  4559. string strServerAddress = request.QueryString["serverAddress"];
  4560. if (strServerAddress != null)
  4561. scope.ServerAddress = strServerAddress.Length == 0 ? null : IPAddress.Parse(strServerAddress);
  4562. string strServerHostName = request.QueryString["serverHostName"];
  4563. if (strServerHostName != null)
  4564. scope.ServerHostName = strServerHostName.Length == 0 ? null : strServerHostName;
  4565. string strBootFileName = request.QueryString["bootFileName"];
  4566. if (strBootFileName != null)
  4567. scope.BootFileName = strBootFileName.Length == 0 ? null : strBootFileName;
  4568. string strRouterAddress = request.QueryString["routerAddress"];
  4569. if (strRouterAddress != null)
  4570. scope.RouterAddress = strRouterAddress.Length == 0 ? null : IPAddress.Parse(strRouterAddress);
  4571. string strUseThisDnsServer = request.QueryString["useThisDnsServer"];
  4572. if (!string.IsNullOrEmpty(strUseThisDnsServer))
  4573. scope.UseThisDnsServer = bool.Parse(strUseThisDnsServer);
  4574. if (!scope.UseThisDnsServer)
  4575. {
  4576. string strDnsServers = request.QueryString["dnsServers"];
  4577. if (strDnsServers != null)
  4578. {
  4579. if (strDnsServers.Length == 0)
  4580. {
  4581. scope.DnsServers = null;
  4582. }
  4583. else
  4584. {
  4585. string[] strDnsServerParts = strDnsServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  4586. IPAddress[] dnsServers = new IPAddress[strDnsServerParts.Length];
  4587. for (int i = 0; i < strDnsServerParts.Length; i++)
  4588. dnsServers[i] = IPAddress.Parse(strDnsServerParts[i]);
  4589. scope.DnsServers = dnsServers;
  4590. }
  4591. }
  4592. }
  4593. string strWinsServers = request.QueryString["winsServers"];
  4594. if (strWinsServers != null)
  4595. {
  4596. if (strWinsServers.Length == 0)
  4597. {
  4598. scope.WinsServers = null;
  4599. }
  4600. else
  4601. {
  4602. string[] strWinsServerParts = strWinsServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  4603. IPAddress[] winsServers = new IPAddress[strWinsServerParts.Length];
  4604. for (int i = 0; i < strWinsServerParts.Length; i++)
  4605. winsServers[i] = IPAddress.Parse(strWinsServerParts[i]);
  4606. scope.WinsServers = winsServers;
  4607. }
  4608. }
  4609. string strNtpServers = request.QueryString["ntpServers"];
  4610. if (strNtpServers != null)
  4611. {
  4612. if (strNtpServers.Length == 0)
  4613. {
  4614. scope.NtpServers = null;
  4615. }
  4616. else
  4617. {
  4618. string[] strNtpServerParts = strNtpServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  4619. IPAddress[] ntpServers = new IPAddress[strNtpServerParts.Length];
  4620. for (int i = 0; i < strNtpServerParts.Length; i++)
  4621. ntpServers[i] = IPAddress.Parse(strNtpServerParts[i]);
  4622. scope.NtpServers = ntpServers;
  4623. }
  4624. }
  4625. string strStaticRoutes = request.QueryString["staticRoutes"];
  4626. if (strStaticRoutes != null)
  4627. {
  4628. if (strStaticRoutes.Length == 0)
  4629. {
  4630. scope.StaticRoutes = null;
  4631. }
  4632. else
  4633. {
  4634. string[] strStaticRoutesParts = strStaticRoutes.Split('|');
  4635. List<ClasslessStaticRouteOption.Route> staticRoutes = new List<ClasslessStaticRouteOption.Route>();
  4636. for (int i = 0; i < strStaticRoutesParts.Length; i += 3)
  4637. {
  4638. staticRoutes.Add(new ClasslessStaticRouteOption.Route(IPAddress.Parse(strStaticRoutesParts[i + 0]), IPAddress.Parse(strStaticRoutesParts[i + 1]), IPAddress.Parse(strStaticRoutesParts[i + 2])));
  4639. }
  4640. scope.StaticRoutes = staticRoutes;
  4641. }
  4642. }
  4643. string strVendorInfo = request.QueryString["vendorInfo"];
  4644. if (strVendorInfo != null)
  4645. {
  4646. if (strVendorInfo.Length == 0)
  4647. {
  4648. scope.VendorInfo = null;
  4649. }
  4650. else
  4651. {
  4652. string[] strVendorInfoParts = strVendorInfo.Split('|');
  4653. Dictionary<string, VendorSpecificInformationOption> vendorInfo = new Dictionary<string, VendorSpecificInformationOption>();
  4654. for (int i = 0; i < strVendorInfoParts.Length; i += 2)
  4655. {
  4656. vendorInfo.Add(strVendorInfoParts[i + 0], new VendorSpecificInformationOption(strVendorInfoParts[i + 1]));
  4657. }
  4658. scope.VendorInfo = vendorInfo;
  4659. }
  4660. }
  4661. string strExclusions = request.QueryString["exclusions"];
  4662. if (strExclusions != null)
  4663. {
  4664. if (strExclusions.Length == 0)
  4665. {
  4666. scope.Exclusions = null;
  4667. }
  4668. else
  4669. {
  4670. string[] strExclusionsParts = strExclusions.Split('|');
  4671. List<Exclusion> exclusions = new List<Exclusion>();
  4672. for (int i = 0; i < strExclusionsParts.Length; i += 2)
  4673. {
  4674. exclusions.Add(new Exclusion(IPAddress.Parse(strExclusionsParts[i + 0]), IPAddress.Parse(strExclusionsParts[i + 1])));
  4675. }
  4676. scope.Exclusions = exclusions;
  4677. }
  4678. }
  4679. string strReservedLeases = request.QueryString["reservedLeases"];
  4680. if (strReservedLeases != null)
  4681. {
  4682. if (strReservedLeases.Length == 0)
  4683. {
  4684. scope.ReservedLeases = null;
  4685. }
  4686. else
  4687. {
  4688. string[] strReservedLeaseParts = strReservedLeases.Split('|');
  4689. List<Lease> reservedLeases = new List<Lease>();
  4690. for (int i = 0; i < strReservedLeaseParts.Length; i += 4)
  4691. {
  4692. reservedLeases.Add(new Lease(LeaseType.Reserved, strReservedLeaseParts[i + 0], DhcpMessageHardwareAddressType.Ethernet, strReservedLeaseParts[i + 1], IPAddress.Parse(strReservedLeaseParts[i + 2]), strReservedLeaseParts[i + 3]));
  4693. }
  4694. scope.ReservedLeases = reservedLeases;
  4695. }
  4696. }
  4697. string strAllowOnlyReservedLeases = request.QueryString["allowOnlyReservedLeases"];
  4698. if (!string.IsNullOrEmpty(strAllowOnlyReservedLeases))
  4699. scope.AllowOnlyReservedLeases = bool.Parse(strAllowOnlyReservedLeases);
  4700. if (scopeExists)
  4701. {
  4702. _dhcpServer.SaveScope(scopeName);
  4703. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
  4704. }
  4705. else
  4706. {
  4707. await _dhcpServer.AddScopeAsync(scope);
  4708. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was added successfully: " + scopeName);
  4709. }
  4710. }
  4711. private async Task EnableDhcpScopeAsync(HttpListenerRequest request)
  4712. {
  4713. string scopeName = request.QueryString["name"];
  4714. if (string.IsNullOrEmpty(scopeName))
  4715. throw new DnsWebServiceException("Parameter 'name' missing.");
  4716. if (!await _dhcpServer.EnableScopeAsync(scopeName))
  4717. throw new DnsWebServiceException("Failed to enable DHCP scope, please check logs for details: " + scopeName);
  4718. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was enabled successfully: " + scopeName);
  4719. }
  4720. private void DisableDhcpScope(HttpListenerRequest request)
  4721. {
  4722. string scopeName = request.QueryString["name"];
  4723. if (string.IsNullOrEmpty(scopeName))
  4724. throw new DnsWebServiceException("Parameter 'name' missing.");
  4725. if (!_dhcpServer.DisableScope(scopeName))
  4726. throw new DnsWebServiceException("Failed to disable DHCP scope, please check logs for details: " + scopeName);
  4727. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was disabled successfully: " + scopeName);
  4728. }
  4729. private void DeleteDhcpScope(HttpListenerRequest request)
  4730. {
  4731. string scopeName = request.QueryString["name"];
  4732. if (string.IsNullOrEmpty(scopeName))
  4733. throw new DnsWebServiceException("Parameter 'name' missing.");
  4734. _dhcpServer.DeleteScope(scopeName);
  4735. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was deleted successfully: " + scopeName);
  4736. }
  4737. private void ConvertToReservedLease(HttpListenerRequest request)
  4738. {
  4739. string scopeName = request.QueryString["name"];
  4740. if (string.IsNullOrEmpty(scopeName))
  4741. throw new DnsWebServiceException("Parameter 'name' missing.");
  4742. Scope scope = _dhcpServer.GetScope(scopeName);
  4743. if (scope == null)
  4744. throw new DnsWebServiceException("DHCP scope does not exists: " + scopeName);
  4745. string strHardwareAddress = request.QueryString["hardwareAddress"];
  4746. if (string.IsNullOrEmpty(strHardwareAddress))
  4747. throw new DnsWebServiceException("Parameter 'hardwareAddress' missing.");
  4748. scope.ConvertToReservedLease(strHardwareAddress);
  4749. _dhcpServer.SaveScope(scopeName);
  4750. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
  4751. }
  4752. private void ConvertToDynamicLease(HttpListenerRequest request)
  4753. {
  4754. string scopeName = request.QueryString["name"];
  4755. if (string.IsNullOrEmpty(scopeName))
  4756. throw new DnsWebServiceException("Parameter 'name' missing.");
  4757. Scope scope = _dhcpServer.GetScope(scopeName);
  4758. if (scope == null)
  4759. throw new DnsWebServiceException("DHCP scope does not exists: " + scopeName);
  4760. string strHardwareAddress = request.QueryString["hardwareAddress"];
  4761. if (string.IsNullOrEmpty(strHardwareAddress))
  4762. throw new DnsWebServiceException("Parameter 'hardwareAddress' missing.");
  4763. scope.ConvertToDynamicLease(strHardwareAddress);
  4764. _dhcpServer.SaveScope(scopeName);
  4765. _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
  4766. }
  4767. #endregion
  4768. #region auth
  4769. private void SetCredentials(string username, string password)
  4770. {
  4771. username = username.ToLower();
  4772. string passwordHash = GetPasswordHash(username, password);
  4773. _credentials[username] = passwordHash;
  4774. }
  4775. private void LoadCredentials(string username, string passwordHash)
  4776. {
  4777. username = username.ToLower();
  4778. _credentials[username] = passwordHash;
  4779. }
  4780. private static string GetPasswordHash(string username, string password)
  4781. {
  4782. using (HMAC hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password)))
  4783. {
  4784. return BitConverter.ToString(hmac.ComputeHash(Encoding.UTF8.GetBytes(username))).Replace("-", "").ToLower();
  4785. }
  4786. }
  4787. #endregion
  4788. #region block list
  4789. private void ForceUpdateBlockLists()
  4790. {
  4791. _blockListLastUpdatedOn = new DateTime();
  4792. StopBlockListUpdateTimer();
  4793. StartBlockListUpdateTimer();
  4794. }
  4795. private void StartBlockListUpdateTimer()
  4796. {
  4797. if (_blockListUpdateTimer == null)
  4798. {
  4799. _blockListUpdateTimer = new Timer(async delegate (object state)
  4800. {
  4801. try
  4802. {
  4803. if (DateTime.UtcNow > _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours))
  4804. {
  4805. if (await _dnsServer.BlockListZoneManager.UpdateBlockListsAsync())
  4806. {
  4807. //block lists were updated
  4808. //save last updated on time
  4809. _blockListLastUpdatedOn = DateTime.UtcNow;
  4810. SaveConfigFile();
  4811. }
  4812. }
  4813. }
  4814. catch (Exception ex)
  4815. {
  4816. _log.Write("DNS Server encountered an error while updating block lists.\r\n" + ex.ToString());
  4817. }
  4818. }, null, BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL, BLOCK_LIST_UPDATE_TIMER_INTERVAL);
  4819. }
  4820. }
  4821. private void StopBlockListUpdateTimer()
  4822. {
  4823. if (_blockListUpdateTimer != null)
  4824. {
  4825. _blockListUpdateTimer.Dispose();
  4826. _blockListUpdateTimer = null;
  4827. }
  4828. }
  4829. #endregion
  4830. #region tls
  4831. private void StartTlsCertificateUpdateTimer()
  4832. {
  4833. if (_tlsCertificateUpdateTimer == null)
  4834. {
  4835. _tlsCertificateUpdateTimer = new Timer(delegate (object state)
  4836. {
  4837. if (!string.IsNullOrEmpty(_webServiceTlsCertificatePath))
  4838. {
  4839. try
  4840. {
  4841. FileInfo fileInfo = new FileInfo(_webServiceTlsCertificatePath);
  4842. if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _webServiceTlsCertificateLastModifiedOn))
  4843. LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
  4844. }
  4845. catch (Exception ex)
  4846. {
  4847. _log.Write("DNS Server encountered an error while updating Web Service TLS Certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
  4848. }
  4849. }
  4850. if (!string.IsNullOrEmpty(_dnsTlsCertificatePath))
  4851. {
  4852. try
  4853. {
  4854. FileInfo fileInfo = new FileInfo(_dnsTlsCertificatePath);
  4855. if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _dnsTlsCertificateLastModifiedOn))
  4856. LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
  4857. }
  4858. catch (Exception ex)
  4859. {
  4860. _log.Write("DNS Server encountered an error while updating DNS Server TLS Certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
  4861. }
  4862. }
  4863. }, null, TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL, TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL);
  4864. }
  4865. }
  4866. private void StopTlsCertificateUpdateTimer()
  4867. {
  4868. if (_tlsCertificateUpdateTimer != null)
  4869. {
  4870. _tlsCertificateUpdateTimer.Dispose();
  4871. _tlsCertificateUpdateTimer = null;
  4872. }
  4873. }
  4874. private void LoadWebServiceTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
  4875. {
  4876. FileInfo fileInfo = new FileInfo(tlsCertificatePath);
  4877. if (!fileInfo.Exists)
  4878. throw new ArgumentException("Web Service TLS certificate file does not exists: " + tlsCertificatePath);
  4879. if (Path.GetExtension(tlsCertificatePath) != ".pfx")
  4880. throw new ArgumentException("Web Service TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
  4881. X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
  4882. _webServiceTlsCertificate = certificate;
  4883. _webServiceTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
  4884. _log.Write("Web Service TLS certificate was loaded: " + tlsCertificatePath);
  4885. }
  4886. private void LoadDnsTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
  4887. {
  4888. FileInfo fileInfo = new FileInfo(tlsCertificatePath);
  4889. if (!fileInfo.Exists)
  4890. throw new ArgumentException("DNS Server TLS certificate file does not exists: " + tlsCertificatePath);
  4891. if (Path.GetExtension(tlsCertificatePath) != ".pfx")
  4892. throw new ArgumentException("DNS Server TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
  4893. X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
  4894. _dnsServer.Certificate = certificate;
  4895. _dnsTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
  4896. _log.Write("DNS Server TLS certificate was loaded: " + tlsCertificatePath);
  4897. }
  4898. #endregion
  4899. #region config
  4900. private void LoadConfigFile()
  4901. {
  4902. string configFile = Path.Combine(_configFolder, "dns.config");
  4903. try
  4904. {
  4905. bool passwordResetOption = false;
  4906. if (!File.Exists(configFile))
  4907. {
  4908. string passwordResetConfigFile = Path.Combine(_configFolder, "reset.config");
  4909. if (File.Exists(passwordResetConfigFile))
  4910. {
  4911. passwordResetOption = true;
  4912. configFile = passwordResetConfigFile;
  4913. }
  4914. }
  4915. byte version;
  4916. using (FileStream fS = new FileStream(configFile, FileMode.Open, FileAccess.Read))
  4917. {
  4918. BinaryReader bR = new BinaryReader(fS);
  4919. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  4920. throw new InvalidDataException("DnsServer config file format is invalid.");
  4921. version = bR.ReadByte();
  4922. switch (version)
  4923. {
  4924. case 2:
  4925. case 3:
  4926. case 4:
  4927. case 5:
  4928. case 6:
  4929. case 7:
  4930. case 8:
  4931. case 9:
  4932. case 10:
  4933. case 11:
  4934. case 12:
  4935. case 13:
  4936. case 14:
  4937. case 15:
  4938. case 16:
  4939. _dnsServer.ServerDomain = bR.ReadShortString();
  4940. _webServiceHttpPort = bR.ReadInt32();
  4941. if (version >= 13)
  4942. {
  4943. {
  4944. int count = bR.ReadByte();
  4945. if (count > 0)
  4946. {
  4947. IPAddress[] localAddresses = new IPAddress[count];
  4948. for (int i = 0; i < count; i++)
  4949. localAddresses[i] = IPAddressExtension.Parse(bR);
  4950. _webServiceLocalAddresses = localAddresses;
  4951. }
  4952. }
  4953. _webServiceTlsPort = bR.ReadInt32();
  4954. _webServiceEnableTls = bR.ReadBoolean();
  4955. _webServiceHttpToTlsRedirect = bR.ReadBoolean();
  4956. _webServiceTlsCertificatePath = bR.ReadShortString();
  4957. _webServiceTlsCertificatePassword = bR.ReadShortString();
  4958. if (_webServiceTlsCertificatePath.Length == 0)
  4959. _webServiceTlsCertificatePath = null;
  4960. if (_webServiceTlsCertificatePath != null)
  4961. {
  4962. try
  4963. {
  4964. LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
  4965. }
  4966. catch (Exception ex)
  4967. {
  4968. _log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
  4969. }
  4970. StartTlsCertificateUpdateTimer();
  4971. }
  4972. }
  4973. _dnsServer.PreferIPv6 = bR.ReadBoolean();
  4974. if (bR.ReadBoolean()) //logQueries
  4975. _dnsServer.QueryLogManager = _log;
  4976. if (version >= 14)
  4977. _dnsServer.StatsManager.MaxStatFileDays = bR.ReadInt32();
  4978. _dnsServer.AllowRecursion = bR.ReadBoolean();
  4979. if (version >= 4)
  4980. _dnsServer.AllowRecursionOnlyForPrivateNetworks = bR.ReadBoolean();
  4981. else
  4982. _dnsServer.AllowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
  4983. if (version >= 12)
  4984. _dnsServer.RandomizeName = bR.ReadBoolean();
  4985. else
  4986. _dnsServer.RandomizeName = true; //default true to enable security feature
  4987. if (version >= 15)
  4988. _dnsServer.QnameMinimization = bR.ReadBoolean();
  4989. else
  4990. _dnsServer.QnameMinimization = true; //default true to enable privacy feature
  4991. if (version >= 13)
  4992. {
  4993. _dnsServer.ServeStale = bR.ReadBoolean();
  4994. _dnsServer.CacheZoneManager.ServeStaleTtl = bR.ReadUInt32();
  4995. }
  4996. if (version >= 9)
  4997. {
  4998. _dnsServer.CachePrefetchEligibility = bR.ReadInt32();
  4999. _dnsServer.CachePrefetchTrigger = bR.ReadInt32();
  5000. _dnsServer.CachePrefetchSampleIntervalInMinutes = bR.ReadInt32();
  5001. _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = bR.ReadInt32();
  5002. }
  5003. NetProxyType proxyType = (NetProxyType)bR.ReadByte();
  5004. if (proxyType != NetProxyType.None)
  5005. {
  5006. string address = bR.ReadShortString();
  5007. int port = bR.ReadInt32();
  5008. NetworkCredential credential = null;
  5009. if (bR.ReadBoolean()) //credential set
  5010. credential = new NetworkCredential(bR.ReadShortString(), bR.ReadShortString());
  5011. _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, address, port, credential);
  5012. if (version >= 10)
  5013. {
  5014. int count = bR.ReadByte();
  5015. List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(count);
  5016. for (int i = 0; i < count; i++)
  5017. bypassList.Add(new NetProxyBypassItem(bR.ReadShortString()));
  5018. _dnsServer.Proxy.BypassList = bypassList;
  5019. }
  5020. }
  5021. else
  5022. {
  5023. _dnsServer.Proxy = null;
  5024. }
  5025. {
  5026. int count = bR.ReadByte();
  5027. if (count > 0)
  5028. {
  5029. NameServerAddress[] forwarders = new NameServerAddress[count];
  5030. for (int i = 0; i < count; i++)
  5031. forwarders[i] = new NameServerAddress(bR);
  5032. _dnsServer.Forwarders = forwarders;
  5033. }
  5034. }
  5035. if (version <= 10)
  5036. {
  5037. DnsTransportProtocol forwarderProtocol = (DnsTransportProtocol)bR.ReadByte();
  5038. if (_dnsServer.Forwarders != null)
  5039. {
  5040. List<NameServerAddress> forwarders = new List<NameServerAddress>();
  5041. foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
  5042. {
  5043. if (forwarder.Protocol == forwarderProtocol)
  5044. forwarders.Add(forwarder);
  5045. else
  5046. forwarders.Add(new NameServerAddress(forwarder, forwarderProtocol));
  5047. }
  5048. _dnsServer.Forwarders = forwarders;
  5049. }
  5050. }
  5051. {
  5052. int count = bR.ReadByte();
  5053. if (count > 0)
  5054. {
  5055. if (version > 2)
  5056. {
  5057. for (int i = 0; i < count; i++)
  5058. LoadCredentials(bR.ReadShortString(), bR.ReadShortString());
  5059. }
  5060. else
  5061. {
  5062. for (int i = 0; i < count; i++)
  5063. SetCredentials(bR.ReadShortString(), bR.ReadShortString());
  5064. }
  5065. }
  5066. }
  5067. if (version <= 6)
  5068. {
  5069. int count = bR.ReadInt32();
  5070. _configDisabledZones = new List<string>(count);
  5071. for (int i = 0; i < count; i++)
  5072. {
  5073. string domain = bR.ReadShortString();
  5074. _configDisabledZones.Add(domain);
  5075. }
  5076. }
  5077. if (version >= 16)
  5078. _dnsServer.UseNxDomainForBlocking = bR.ReadBoolean();
  5079. if (version > 4)
  5080. {
  5081. //read block list urls
  5082. int count = bR.ReadByte();
  5083. for (int i = 0; i < count; i++)
  5084. {
  5085. string listUrl = bR.ReadShortString();
  5086. if (listUrl.StartsWith("!"))
  5087. _dnsServer.BlockListZoneManager.AllowListUrls.Add(new Uri(listUrl.Substring(1)));
  5088. else
  5089. _dnsServer.BlockListZoneManager.BlockListUrls.Add(new Uri(listUrl));
  5090. }
  5091. _blockListLastUpdatedOn = bR.ReadDate();
  5092. if (version >= 13)
  5093. _blockListUpdateIntervalHours = bR.ReadInt32();
  5094. }
  5095. if (version >= 11)
  5096. {
  5097. int count = bR.ReadByte();
  5098. if (count > 0)
  5099. {
  5100. IPEndPoint[] localEndPoints = new IPEndPoint[count];
  5101. for (int i = 0; i < count; i++)
  5102. localEndPoints[i] = (IPEndPoint)EndPointExtension.Parse(bR);
  5103. _dnsServer.LocalEndPoints = localEndPoints;
  5104. }
  5105. }
  5106. else if (version >= 6)
  5107. {
  5108. int count = bR.ReadByte();
  5109. if (count > 0)
  5110. {
  5111. IPEndPoint[] localEndPoints = new IPEndPoint[count];
  5112. for (int i = 0; i < count; i++)
  5113. localEndPoints[i] = new IPEndPoint(IPAddressExtension.Parse(bR), 53);
  5114. _dnsServer.LocalEndPoints = localEndPoints;
  5115. }
  5116. }
  5117. if (version >= 8)
  5118. {
  5119. _dnsServer.EnableDnsOverHttp = bR.ReadBoolean();
  5120. _dnsServer.EnableDnsOverTls = bR.ReadBoolean();
  5121. _dnsServer.EnableDnsOverHttps = bR.ReadBoolean();
  5122. _dnsTlsCertificatePath = bR.ReadShortString();
  5123. _dnsTlsCertificatePassword = bR.ReadShortString();
  5124. if (_dnsTlsCertificatePath.Length == 0)
  5125. _dnsTlsCertificatePath = null;
  5126. if (_dnsTlsCertificatePath != null)
  5127. {
  5128. try
  5129. {
  5130. LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
  5131. }
  5132. catch (Exception ex)
  5133. {
  5134. _log.Write("DNS Server encountered an error while loading DNS Server TLS certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
  5135. }
  5136. StartTlsCertificateUpdateTimer();
  5137. }
  5138. }
  5139. break;
  5140. default:
  5141. throw new InvalidDataException("DNS Server config version not supported.");
  5142. }
  5143. }
  5144. _log.Write("DNS Server config file was loaded: " + configFile);
  5145. if (passwordResetOption)
  5146. {
  5147. SetCredentials("admin", "admin");
  5148. _log.Write("DNS Server reset password for user: admin");
  5149. SaveConfigFile();
  5150. try
  5151. {
  5152. File.Delete(configFile);
  5153. }
  5154. catch
  5155. { }
  5156. }
  5157. if (version <= 6)
  5158. SaveConfigFile(); //save as new config version to avoid loading old version next time
  5159. }
  5160. catch (FileNotFoundException)
  5161. {
  5162. _log.Write("DNS Server config file was not found: " + configFile);
  5163. _log.Write("DNS Server is restoring default config file.");
  5164. SetCredentials("admin", "admin");
  5165. _dnsServer.AllowRecursion = true;
  5166. _dnsServer.AllowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
  5167. _dnsServer.RandomizeName = true; //default true to enable security feature
  5168. _dnsServer.QnameMinimization = true; //default true to enable privacy feature
  5169. SaveConfigFile();
  5170. }
  5171. catch (Exception ex)
  5172. {
  5173. _log.Write("DNS Server encountered an error while loading config file: " + configFile + "\r\n" + ex.ToString());
  5174. _log.Write("Note: You may try deleting the config file to fix this issue. However, you will lose DNS settings but, zone data wont be affected.");
  5175. throw;
  5176. }
  5177. }
  5178. private void SaveConfigFile()
  5179. {
  5180. string configFile = Path.Combine(_configFolder, "dns.config");
  5181. using (MemoryStream mS = new MemoryStream())
  5182. {
  5183. //serialize config
  5184. BinaryWriter bW = new BinaryWriter(mS);
  5185. bW.Write(Encoding.ASCII.GetBytes("DS")); //format
  5186. bW.Write((byte)16); //version
  5187. bW.WriteShortString(_dnsServer.ServerDomain);
  5188. bW.Write(_webServiceHttpPort);
  5189. {
  5190. bW.Write(Convert.ToByte(_webServiceLocalAddresses.Count));
  5191. foreach (IPAddress localAddress in _webServiceLocalAddresses)
  5192. localAddress.WriteTo(bW);
  5193. }
  5194. bW.Write(_webServiceTlsPort);
  5195. bW.Write(_webServiceEnableTls);
  5196. bW.Write(_webServiceHttpToTlsRedirect);
  5197. if (_webServiceTlsCertificatePath == null)
  5198. bW.WriteShortString(string.Empty);
  5199. else
  5200. bW.WriteShortString(_webServiceTlsCertificatePath);
  5201. if (_webServiceTlsCertificatePassword == null)
  5202. bW.WriteShortString(string.Empty);
  5203. else
  5204. bW.WriteShortString(_webServiceTlsCertificatePassword);
  5205. bW.Write(_dnsServer.PreferIPv6);
  5206. bW.Write(_dnsServer.QueryLogManager != null); //logQueries
  5207. bW.Write(_dnsServer.StatsManager.MaxStatFileDays);
  5208. bW.Write(_dnsServer.AllowRecursion);
  5209. bW.Write(_dnsServer.AllowRecursionOnlyForPrivateNetworks);
  5210. bW.Write(_dnsServer.RandomizeName);
  5211. bW.Write(_dnsServer.QnameMinimization);
  5212. bW.Write(_dnsServer.ServeStale);
  5213. bW.Write(_dnsServer.CacheZoneManager.ServeStaleTtl);
  5214. bW.Write(_dnsServer.CachePrefetchEligibility);
  5215. bW.Write(_dnsServer.CachePrefetchTrigger);
  5216. bW.Write(_dnsServer.CachePrefetchSampleIntervalInMinutes);
  5217. bW.Write(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
  5218. if (_dnsServer.Proxy == null)
  5219. {
  5220. bW.Write((byte)NetProxyType.None);
  5221. }
  5222. else
  5223. {
  5224. bW.Write((byte)_dnsServer.Proxy.Type);
  5225. bW.WriteShortString(_dnsServer.Proxy.Address);
  5226. bW.Write(_dnsServer.Proxy.Port);
  5227. NetworkCredential credential = _dnsServer.Proxy.Credential;
  5228. if (credential == null)
  5229. {
  5230. bW.Write(false);
  5231. }
  5232. else
  5233. {
  5234. bW.Write(true);
  5235. bW.WriteShortString(credential.UserName);
  5236. bW.WriteShortString(credential.Password);
  5237. }
  5238. //bypass list
  5239. {
  5240. bW.Write(Convert.ToByte(_dnsServer.Proxy.BypassList.Count));
  5241. foreach (NetProxyBypassItem item in _dnsServer.Proxy.BypassList)
  5242. bW.WriteShortString(item.Value);
  5243. }
  5244. }
  5245. if (_dnsServer.Forwarders == null)
  5246. {
  5247. bW.Write((byte)0);
  5248. }
  5249. else
  5250. {
  5251. bW.Write(Convert.ToByte(_dnsServer.Forwarders.Count));
  5252. foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
  5253. forwarder.WriteTo(bW);
  5254. }
  5255. {
  5256. bW.Write(Convert.ToByte(_credentials.Count));
  5257. foreach (KeyValuePair<string, string> credential in _credentials)
  5258. {
  5259. bW.WriteShortString(credential.Key);
  5260. bW.WriteShortString(credential.Value);
  5261. }
  5262. }
  5263. //block list
  5264. bW.Write(_dnsServer.UseNxDomainForBlocking);
  5265. {
  5266. bW.Write(Convert.ToByte(_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count));
  5267. foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
  5268. bW.WriteShortString("!" + allowListUrl.AbsoluteUri);
  5269. foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
  5270. bW.WriteShortString(blockListUrl.AbsoluteUri);
  5271. bW.Write(_blockListLastUpdatedOn);
  5272. bW.Write(_blockListUpdateIntervalHours);
  5273. }
  5274. {
  5275. bW.Write(Convert.ToByte(_dnsServer.LocalEndPoints.Count));
  5276. foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
  5277. localEP.WriteTo(bW);
  5278. }
  5279. bW.Write(_dnsServer.EnableDnsOverHttp);
  5280. bW.Write(_dnsServer.EnableDnsOverTls);
  5281. bW.Write(_dnsServer.EnableDnsOverHttps);
  5282. if (_dnsTlsCertificatePath == null)
  5283. bW.WriteShortString(string.Empty);
  5284. else
  5285. bW.WriteShortString(_dnsTlsCertificatePath);
  5286. if (_dnsTlsCertificatePassword == null)
  5287. bW.WriteShortString(string.Empty);
  5288. else
  5289. bW.WriteShortString(_dnsTlsCertificatePassword);
  5290. //write config
  5291. mS.Position = 0;
  5292. using (FileStream fS = new FileStream(configFile, FileMode.Create, FileAccess.Write))
  5293. {
  5294. mS.CopyTo(fS);
  5295. }
  5296. }
  5297. _log.Write("DNS Server config file was saved: " + configFile);
  5298. }
  5299. #endregion
  5300. #region web service start stop
  5301. private void StartDnsWebService()
  5302. {
  5303. int acceptTasks = Math.Max(1, Environment.ProcessorCount);
  5304. //HTTP service
  5305. try
  5306. {
  5307. string webServiceHostname = null;
  5308. _webService = new HttpListener();
  5309. IPAddress httpAddress = null;
  5310. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  5311. {
  5312. string host;
  5313. if (webServiceLocalAddress.Equals(IPAddress.Any))
  5314. {
  5315. host = "+";
  5316. httpAddress = IPAddress.Loopback;
  5317. }
  5318. else if (webServiceLocalAddress.Equals(IPAddress.IPv6Any))
  5319. {
  5320. host = "+";
  5321. if ((httpAddress == null) || !IPAddress.IsLoopback(httpAddress))
  5322. httpAddress = IPAddress.IPv6Loopback;
  5323. }
  5324. else
  5325. {
  5326. if (webServiceLocalAddress.AddressFamily == AddressFamily.InterNetworkV6)
  5327. host = "[" + webServiceLocalAddress.ToString() + "]";
  5328. else
  5329. host = webServiceLocalAddress.ToString();
  5330. if (httpAddress == null)
  5331. httpAddress = webServiceLocalAddress;
  5332. if (webServiceHostname == null)
  5333. webServiceHostname = host;
  5334. }
  5335. _webService.Prefixes.Add("http://" + host + ":" + _webServiceHttpPort + "/");
  5336. }
  5337. _webService.Start();
  5338. if (httpAddress == null)
  5339. httpAddress = IPAddress.Loopback;
  5340. _webServiceHttpEP = new IPEndPoint(httpAddress, _webServiceHttpPort);
  5341. _webServiceHostname = webServiceHostname ?? Environment.MachineName.ToLower();
  5342. }
  5343. catch (Exception ex)
  5344. {
  5345. _log.Write("Web Service failed to bind using default hostname. Attempting to bind again using 'localhost' hostname.\r\n" + ex.ToString());
  5346. try
  5347. {
  5348. _webService = new HttpListener();
  5349. _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
  5350. _webService.Prefixes.Add("http://127.0.0.1:" + _webServiceHttpPort + "/");
  5351. _webService.Start();
  5352. }
  5353. catch
  5354. {
  5355. _webService = new HttpListener();
  5356. _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
  5357. _webService.Start();
  5358. }
  5359. _webServiceHttpEP = new IPEndPoint(IPAddress.Loopback, _webServiceHttpPort);
  5360. _webServiceHostname = "localhost";
  5361. }
  5362. _webService.IgnoreWriteExceptions = true;
  5363. for (int i = 0; i < acceptTasks; i++)
  5364. {
  5365. _ = Task.Factory.StartNew(delegate ()
  5366. {
  5367. return AcceptWebRequestAsync();
  5368. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
  5369. }
  5370. _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "HTTP Web Service was started successfully.");
  5371. //TLS service
  5372. if (_webServiceEnableTls && (_webServiceTlsCertificate != null))
  5373. {
  5374. List<Socket> webServiceTlsListeners = new List<Socket>();
  5375. try
  5376. {
  5377. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  5378. {
  5379. Socket tlsListener = new Socket(webServiceLocalAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  5380. tlsListener.Bind(new IPEndPoint(webServiceLocalAddress, _webServiceTlsPort));
  5381. tlsListener.Listen(10);
  5382. webServiceTlsListeners.Add(tlsListener);
  5383. }
  5384. foreach (Socket tlsListener in webServiceTlsListeners)
  5385. {
  5386. for (int i = 0; i < acceptTasks; i++)
  5387. {
  5388. _ = Task.Factory.StartNew(delegate ()
  5389. {
  5390. return AcceptTlsWebRequestAsync(tlsListener);
  5391. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
  5392. }
  5393. }
  5394. _webServiceTlsListeners = webServiceTlsListeners;
  5395. _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "TLS Web Service was started successfully.");
  5396. }
  5397. catch (Exception ex)
  5398. {
  5399. _log.Write("TLS Web Service failed to start.\r\n" + ex.ToString());
  5400. foreach (Socket tlsListener in webServiceTlsListeners)
  5401. tlsListener.Dispose();
  5402. }
  5403. }
  5404. }
  5405. private void StopDnsWebService()
  5406. {
  5407. _webService.Stop();
  5408. if (_webServiceTlsListeners != null)
  5409. {
  5410. foreach (Socket tlsListener in _webServiceTlsListeners)
  5411. tlsListener.Dispose();
  5412. _webServiceTlsListeners = null;
  5413. }
  5414. }
  5415. #endregion
  5416. #endregion
  5417. #region public
  5418. public void Start()
  5419. {
  5420. if (_disposed)
  5421. throw new ObjectDisposedException("WebService");
  5422. if (_state != ServiceState.Stopped)
  5423. throw new InvalidOperationException("Web Service is already running.");
  5424. _state = ServiceState.Starting;
  5425. try
  5426. {
  5427. //get initial server domain
  5428. string dnsServerDomain = Environment.MachineName.ToLower();
  5429. if (!DnsClient.IsDomainNameValid(dnsServerDomain))
  5430. dnsServerDomain = "dns-server-1"; //use this name instead since machine name is not a valid domain name
  5431. //init dns server
  5432. _dnsServer = new DnsServer(dnsServerDomain, _configFolder, Path.Combine(_appFolder, "dohwww"), _log);
  5433. //init dhcp server
  5434. _dhcpServer = new DhcpServer(Path.Combine(_configFolder, "scopes"), _log);
  5435. _dhcpServer.AuthZoneManager = _dnsServer.AuthZoneManager;
  5436. //load config
  5437. LoadConfigFile();
  5438. //load all dns applications
  5439. _dnsServer.DnsApplicationManager.LoadAllApplications();
  5440. //load all zones files
  5441. _dnsServer.AuthZoneManager.LoadAllZoneFiles();
  5442. //disable zones from old config format
  5443. if (_configDisabledZones != null)
  5444. {
  5445. foreach (string domain in _configDisabledZones)
  5446. {
  5447. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  5448. if (zoneInfo != null)
  5449. {
  5450. zoneInfo.Disabled = true;
  5451. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  5452. }
  5453. }
  5454. }
  5455. //load allowed zone and blocked zone
  5456. _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
  5457. _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
  5458. //load block list zone async
  5459. if (_dnsServer.BlockListZoneManager.BlockListUrls.Count > 0)
  5460. {
  5461. ThreadPool.QueueUserWorkItem(delegate (object state)
  5462. {
  5463. try
  5464. {
  5465. _dnsServer.BlockListZoneManager.LoadBlockLists();
  5466. StartBlockListUpdateTimer();
  5467. }
  5468. catch (Exception ex)
  5469. {
  5470. _log.Write(ex);
  5471. }
  5472. });
  5473. }
  5474. //start dns and dhcp
  5475. _dnsServer.Start();
  5476. _dhcpServer.Start();
  5477. //start web service
  5478. StartDnsWebService();
  5479. _state = ServiceState.Running;
  5480. _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was started successfully.");
  5481. }
  5482. catch (Exception ex)
  5483. {
  5484. _log.Write("Failed to start DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
  5485. throw;
  5486. }
  5487. }
  5488. public void Stop()
  5489. {
  5490. if (_state != ServiceState.Running)
  5491. return;
  5492. _state = ServiceState.Stopping;
  5493. try
  5494. {
  5495. StopDnsWebService();
  5496. _dnsServer.Dispose();
  5497. _dhcpServer.Dispose();
  5498. StopBlockListUpdateTimer();
  5499. StopTlsCertificateUpdateTimer();
  5500. _state = ServiceState.Stopped;
  5501. _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was stopped successfully.");
  5502. }
  5503. catch (Exception ex)
  5504. {
  5505. _log.Write("Failed to stop DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
  5506. throw;
  5507. }
  5508. }
  5509. #endregion
  5510. #region properties
  5511. public string ConfigFolder
  5512. { get { return _configFolder; } }
  5513. public int WebServiceHttpPort
  5514. { get { return _webServiceHttpPort; } }
  5515. public string WebServiceHostname
  5516. { get { return _webServiceHostname; } }
  5517. #endregion
  5518. }
  5519. }