1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045 |
- /*
- Technitium DNS Server
- Copyright (C) 2021 Shreyas Zare (shreyas@technitium.com)
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- using DnsApplicationCommon;
- using DnsServerCore.Dhcp;
- using DnsServerCore.Dhcp.Options;
- using DnsServerCore.Dns;
- using DnsServerCore.Dns.Applications;
- using DnsServerCore.Dns.ResourceRecords;
- using DnsServerCore.Dns.Zones;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Converters;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.IO.Compression;
- using System.Net;
- using System.Net.Http;
- using System.Net.Security;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using TechnitiumLibrary.IO;
- using TechnitiumLibrary.Net;
- using TechnitiumLibrary.Net.Dns;
- using TechnitiumLibrary.Net.Dns.ResourceRecords;
- using TechnitiumLibrary.Net.Http;
- using TechnitiumLibrary.Net.Proxy;
- namespace DnsServerCore
- {
- public sealed class DnsWebService : IDisposable
- {
- #region enum
- enum ServiceState
- {
- Stopped = 0,
- Starting = 1,
- Running = 2,
- Stopping = 3
- }
- #endregion
- #region variables
- readonly Version _currentVersion;
- readonly string _appFolder;
- readonly string _configFolder;
- readonly Uri _updateCheckUri;
- readonly Uri _appStoreUri;
- readonly LogManager _log;
- DnsServer _dnsServer;
- DhcpServer _dhcpServer;
- IReadOnlyList<IPAddress> _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
- int _webServiceHttpPort = 5380;
- int _webServiceTlsPort = 53443;
- bool _webServiceEnableTls;
- bool _webServiceHttpToTlsRedirect;
- string _webServiceTlsCertificatePath;
- string _webServiceTlsCertificatePassword;
- DateTime _webServiceTlsCertificateLastModifiedOn;
- HttpListener _webService;
- IReadOnlyList<Socket> _webServiceTlsListeners;
- X509Certificate2 _webServiceTlsCertificate;
- readonly IndependentTaskScheduler _webServiceTaskScheduler = new IndependentTaskScheduler(ThreadPriority.AboveNormal);
- string _webServiceHostname;
- IPEndPoint _webServiceHttpEP;
- string _dnsTlsCertificatePath;
- string _dnsTlsCertificatePassword;
- DateTime _dnsTlsCertificateLastModifiedOn;
- Timer _tlsCertificateUpdateTimer;
- const int TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL = 60000;
- const int TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL = 60000;
- const int MAX_LOGIN_ATTEMPTS = 5;
- const int BLOCK_ADDRESS_INTERVAL = 5 * 60 * 1000;
- readonly ConcurrentDictionary<IPAddress, int> _failedLoginAttempts = new ConcurrentDictionary<IPAddress, int>();
- readonly ConcurrentDictionary<IPAddress, DateTime> _blockedAddresses = new ConcurrentDictionary<IPAddress, DateTime>();
- readonly ConcurrentDictionary<string, string> _credentials = new ConcurrentDictionary<string, string>();
- readonly ConcurrentDictionary<string, UserSession> _sessions = new ConcurrentDictionary<string, UserSession>();
- volatile ServiceState _state = ServiceState.Stopped;
- Timer _blockListUpdateTimer;
- DateTime _blockListLastUpdatedOn;
- int _blockListUpdateIntervalHours = 24;
- const int BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL = 5000;
- const int BLOCK_LIST_UPDATE_TIMER_INTERVAL = 900000;
- List<string> _configDisabledZones;
- #endregion
- #region constructor
- public DnsWebService(string configFolder = null, Uri updateCheckUri = null, Uri appStoreUri = null)
- {
- Assembly assembly = Assembly.GetExecutingAssembly();
- AssemblyName assemblyName = assembly.GetName();
- _currentVersion = assemblyName.Version;
- _appFolder = Path.GetDirectoryName(assembly.Location);
- if (configFolder == null)
- _configFolder = Path.Combine(_appFolder, "config");
- else
- _configFolder = configFolder;
- if (!Directory.Exists(_configFolder))
- Directory.CreateDirectory(_configFolder);
- _updateCheckUri = updateCheckUri;
- _appStoreUri = appStoreUri;
- _log = new LogManager(_configFolder);
- string blockListsFolder = Path.Combine(_configFolder, "blocklists");
- if (!Directory.Exists(blockListsFolder))
- Directory.CreateDirectory(blockListsFolder);
- }
- #endregion
- #region IDisposable
- private bool _disposed;
- private void Dispose(bool disposing)
- {
- if (_disposed)
- return;
- if (disposing)
- {
- Stop();
- if (_webService != null)
- _webService.Close();
- if (_dnsServer != null)
- _dnsServer.Dispose();
- if (_dhcpServer != null)
- _dhcpServer.Dispose();
- if (_log != null)
- _log.Dispose();
- }
- _disposed = true;
- }
- public void Dispose()
- {
- Dispose(true);
- }
- #endregion
- #region private
- #region web service
- private async Task AcceptWebRequestAsync()
- {
- try
- {
- while (true)
- {
- HttpListenerContext context = await _webService.GetContextAsync();
- if ((_webServiceTlsListeners != null) && (_webServiceTlsListeners.Count > 0) && _webServiceHttpToTlsRedirect)
- {
- IPEndPoint remoteEP = context.Request.RemoteEndPoint;
- if ((remoteEP != null) && !IPAddress.IsLoopback(remoteEP.Address))
- {
- string domain = _webServiceTlsCertificate.GetNameInfo(X509NameType.DnsName, false);
- string redirectUri = "https://" + domain + ":" + _webServiceTlsPort + context.Request.Url.PathAndQuery;
- context.Response.Redirect(redirectUri);
- context.Response.Close();
- continue;
- }
- }
- _ = ProcessRequestAsync(context.Request, context.Response);
- }
- }
- catch (HttpListenerException ex)
- {
- if (ex.ErrorCode == 995)
- return; //web service stopping
- _log.Write(ex);
- }
- catch (ObjectDisposedException)
- {
- //web service stopped
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(ex);
- }
- }
- private async Task AcceptTlsWebRequestAsync(Socket tlsListener)
- {
- try
- {
- while (true)
- {
- Socket socket = await tlsListener.AcceptAsync();
- _ = TlsToHttpTunnelAsync(socket);
- }
- }
- catch (SocketException ex)
- {
- if (ex.SocketErrorCode == SocketError.OperationAborted)
- return; //web service stopping
- _log.Write(ex);
- }
- catch (ObjectDisposedException)
- {
- //web service stopped
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(ex);
- }
- }
- private async Task TlsToHttpTunnelAsync(Socket socket)
- {
- Socket tunnel = null;
- try
- {
- if (_webServiceLocalAddresses.Count < 1)
- return;
- string remoteIP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
- SslStream sslStream = new SslStream(new NetworkStream(socket, true));
- await sslStream.AuthenticateAsServerAsync(_webServiceTlsCertificate);
- tunnel = new Socket(_webServiceHttpEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- tunnel.Connect(_webServiceHttpEP);
- NetworkStream tunnelStream = new NetworkStream(tunnel, true);
- //copy tunnel to ssl
- _ = tunnelStream.CopyToAsync(sslStream).ContinueWith(delegate (Task prevTask) { sslStream.Dispose(); tunnelStream.Dispose(); });
- //copy ssl to tunnel
- try
- {
- while (true)
- {
- HttpRequest httpRequest = await HttpRequest.ReadRequestAsync(sslStream);
- if (httpRequest == null)
- return; //connection closed gracefully by client
- //inject X-Real-IP & host header
- httpRequest.Headers.Add("X-Real-IP", remoteIP);
- httpRequest.Headers[HttpRequestHeader.Host] = "localhost:" + _webServiceHttpPort.ToString();
- //relay request
- await tunnelStream.WriteAsync(Encoding.ASCII.GetBytes(httpRequest.HttpMethod + " " + httpRequest.RequestPathAndQuery + " " + httpRequest.Protocol + "\r\n"));
- await tunnelStream.WriteAsync(httpRequest.Headers.ToByteArray());
- if (httpRequest.InputStream != null)
- await httpRequest.InputStream.CopyToAsync(tunnelStream);
- await tunnelStream.FlushAsync();
- }
- }
- finally
- {
- sslStream.Dispose();
- tunnelStream.Dispose();
- }
- }
- catch (IOException)
- {
- //ignore
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- finally
- {
- socket.Dispose();
- if (tunnel != null)
- tunnel.Dispose();
- }
- }
- private async Task ProcessRequestAsync(HttpListenerRequest request, HttpListenerResponse response)
- {
- response.AddHeader("Server", "");
- response.AddHeader("X-Robots-Tag", "noindex, nofollow");
- try
- {
- Uri url = request.Url;
- string path = url.AbsolutePath;
- if (!path.StartsWith("/") || path.Contains("/../") || path.Contains("/.../"))
- {
- await SendErrorAsync(response, 404);
- return;
- }
- if (path.StartsWith("/api/"))
- {
- using (MemoryStream mS = new MemoryStream())
- {
- try
- {
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- switch (path)
- {
- case "/api/login":
- await LoginAsync(request, jsonWriter);
- break;
- case "/api/logout":
- Logout(request);
- break;
- default:
- if (!IsSessionValid(request))
- throw new InvalidTokenWebServiceException("Invalid token or session expired.");
- jsonWriter.WritePropertyName("response");
- jsonWriter.WriteStartObject();
- try
- {
- switch (path)
- {
- case "/api/changePassword":
- ChangePassword(request);
- break;
- case "/api/checkForUpdate":
- await CheckForUpdateAsync(request, jsonWriter);
- break;
- case "/api/getDnsSettings":
- GetDnsSettings(jsonWriter);
- break;
- case "/api/setDnsSettings":
- SetDnsSettings(request, jsonWriter);
- break;
- case "/api/forceUpdateBlockLists":
- ForceUpdateBlockLists(request);
- break;
- case "/api/backupSettings":
- await BackupSettingsAsync(request, response);
- return;
- case "/api/restoreSettings":
- await RestoreSettingsAsync(request, jsonWriter);
- break;
- case "/api/getStats":
- await GetStats(request, jsonWriter);
- break;
- case "/api/getTopStats":
- await GetTopStats(request, jsonWriter);
- break;
- case "/api/flushDnsCache":
- FlushCache(request);
- break;
- case "/api/listCachedZones":
- ListCachedZones(request, jsonWriter);
- break;
- case "/api/deleteCachedZone":
- DeleteCachedZone(request);
- break;
- case "/api/listAllowedZones":
- ListAllowedZones(request, jsonWriter);
- break;
- case "/api/importAllowedZones":
- ImportAllowedZones(request);
- break;
- case "/api/exportAllowedZones":
- ExportAllowedZones(response);
- return;
- case "/api/deleteAllowedZone":
- DeleteAllowedZone(request);
- break;
- case "/api/allowZone":
- AllowZone(request);
- break;
- case "/api/listBlockedZones":
- ListBlockedZones(request, jsonWriter);
- break;
- case "/api/importBlockedZones":
- ImportBlockedZones(request);
- break;
- case "/api/exportBlockedZones":
- ExportBlockedZones(response);
- return;
- case "/api/deleteBlockedZone":
- DeleteBlockedZone(request);
- break;
- case "/api/blockZone":
- BlockZone(request);
- break;
- case "/api/listZones":
- ListZones(jsonWriter);
- break;
- case "/api/createZone":
- await CreateZoneAsync(request, jsonWriter);
- break;
- case "/api/deleteZone":
- DeleteZone(request);
- break;
- case "/api/enableZone":
- EnableZone(request);
- break;
- case "/api/disableZone":
- DisableZone(request);
- break;
- case "/api/addRecord":
- AddRecord(request);
- break;
- case "/api/getRecords":
- GetRecords(request, jsonWriter);
- break;
- case "/api/deleteRecord":
- DeleteRecord(request);
- break;
- case "/api/updateRecord":
- UpdateRecord(request);
- break;
- case "/api/apps/list":
- await ListInstalledAppsAsync(jsonWriter);
- break;
- case "/api/apps/listStoreApps":
- await ListStoreApps(jsonWriter);
- break;
- case "/api/apps/downloadAndInstall":
- await DownloadAndInstallAppAsync(request);
- break;
- case "/api/apps/downloadAndUpdate":
- await DownloadAndUpdateAppAsync(request);
- break;
- case "/api/apps/install":
- await InstallAppAsync(request);
- break;
- case "/api/apps/update":
- await UpdateAppAsync(request);
- break;
- case "/api/apps/uninstall":
- UninstallApp(request);
- break;
- case "/api/apps/getConfig":
- await GetAppConfigAsync(request, jsonWriter);
- break;
- case "/api/apps/setConfig":
- await SetAppConfigAsync(request);
- break;
- case "/api/resolveQuery":
- await ResolveQuery(request, jsonWriter);
- break;
- case "/api/listLogs":
- ListLogs(jsonWriter);
- break;
- case "/api/deleteLog":
- DeleteLog(request);
- break;
- case "/api/deleteAllLogs":
- DeleteAllLogs(request);
- break;
- case "/api/deleteAllStats":
- DeleteAllStats(request);
- break;
- case "/api/listDhcpScopes":
- ListDhcpScopes(jsonWriter);
- break;
- case "/api/listDhcpLeases":
- ListDhcpLeases(jsonWriter);
- break;
- case "/api/getDhcpScope":
- GetDhcpScope(request, jsonWriter);
- break;
- case "/api/setDhcpScope":
- await SetDhcpScopeAsync(request);
- break;
- case "/api/enableDhcpScope":
- await EnableDhcpScopeAsync(request);
- break;
- case "/api/disableDhcpScope":
- DisableDhcpScope(request);
- break;
- case "/api/deleteDhcpScope":
- DeleteDhcpScope(request);
- break;
- case "/api/convertToReservedLease":
- ConvertToReservedLease(request);
- break;
- case "/api/convertToDynamicLease":
- ConvertToDynamicLease(request);
- break;
- default:
- await SendErrorAsync(response, 404);
- return;
- }
- }
- finally
- {
- jsonWriter.WriteEndObject();
- }
- break;
- }
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("ok");
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- catch (InvalidTokenWebServiceException ex)
- {
- mS.SetLength(0);
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("invalid-token");
- jsonWriter.WritePropertyName("errorMessage");
- jsonWriter.WriteValue(ex.Message);
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- catch (Exception ex)
- {
- _log.Write(GetRequestRemoteEndPoint(request), ex);
- mS.SetLength(0);
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("error");
- jsonWriter.WritePropertyName("errorMessage");
- jsonWriter.WriteValue(ex.Message);
- jsonWriter.WritePropertyName("stackTrace");
- jsonWriter.WriteValue(ex.StackTrace);
- if (ex.InnerException != null)
- {
- jsonWriter.WritePropertyName("innerErrorMessage");
- jsonWriter.WriteValue(ex.InnerException.Message);
- }
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- response.ContentType = "application/json; charset=utf-8";
- response.ContentEncoding = Encoding.UTF8;
- response.ContentLength64 = mS.Length;
- mS.Position = 0;
- using (Stream stream = response.OutputStream)
- {
- await mS.CopyToAsync(stream);
- }
- }
- }
- else if (path.StartsWith("/log/"))
- {
- if (!IsSessionValid(request))
- {
- await SendErrorAsync(response, 403, "Invalid token or session expired.");
- return;
- }
- string[] pathParts = path.Split('/');
- string logFileName = pathParts[2];
- int limit = 0;
- string strLimit = request.QueryString["limit"];
- if (!string.IsNullOrEmpty(strLimit))
- limit = int.Parse(strLimit);
- await _log.DownloadLogAsync(request, response, logFileName, limit * 1024 * 1024);
- }
- else
- {
- if (path == "/")
- {
- path = "/index.html";
- }
- else if ((path == "/blocklist.txt") && !IPAddress.IsLoopback(GetRequestRemoteEndPoint(request).Address))
- {
- await SendErrorAsync(response, 403);
- return;
- }
- string wwwroot = Path.Combine(_appFolder, "www");
- path = Path.GetFullPath(wwwroot + path.Replace('/', Path.DirectorySeparatorChar));
- if (!path.StartsWith(wwwroot) || !File.Exists(path))
- {
- await SendErrorAsync(response, 404);
- return;
- }
- await SendFileAsync(request, response, path);
- }
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(GetRequestRemoteEndPoint(request), ex);
- await SendError(response, ex);
- }
- }
- private static IPEndPoint GetRequestRemoteEndPoint(HttpListenerRequest request)
- {
- try
- {
- if (request.RemoteEndPoint == null)
- return new IPEndPoint(IPAddress.Any, 0);
- if (NetUtilities.IsPrivateIP(request.RemoteEndPoint.Address))
- {
- string xRealIp = request.Headers["X-Real-IP"];
- if (IPAddress.TryParse(xRealIp, out IPAddress address))
- {
- //get the real IP address of the requesting client from X-Real-IP header set in nginx proxy_pass block
- return new IPEndPoint(address, 0);
- }
- }
- return request.RemoteEndPoint;
- }
- catch
- {
- return new IPEndPoint(IPAddress.Any, 0);
- }
- }
- public static Stream GetOutputStream(HttpListenerRequest request, HttpListenerResponse response)
- {
- string strAcceptEncoding = request.Headers["Accept-Encoding"];
- if (string.IsNullOrEmpty(strAcceptEncoding))
- {
- return response.OutputStream;
- }
- else
- {
- if (strAcceptEncoding.Contains("gzip"))
- {
- response.AddHeader("Content-Encoding", "gzip");
- return new GZipStream(response.OutputStream, CompressionMode.Compress);
- }
- else if (strAcceptEncoding.Contains("deflate"))
- {
- response.AddHeader("Content-Encoding", "deflate");
- return new DeflateStream(response.OutputStream, CompressionMode.Compress);
- }
- else
- {
- return response.OutputStream;
- }
- }
- }
- private static Task SendError(HttpListenerResponse response, Exception ex)
- {
- return SendErrorAsync(response, 500, ex.ToString());
- }
- private static async Task SendErrorAsync(HttpListenerResponse response, int statusCode, string message = null)
- {
- try
- {
- string statusString = statusCode + " " + DnsServer.GetHttpStatusString((HttpStatusCode)statusCode);
- byte[] buffer = Encoding.UTF8.GetBytes("<html><head><title>" + statusString + "</title></head><body><h1>" + statusString + "</h1>" + (message == null ? "" : "<p>" + message + "</p>") + "</body></html>");
- response.StatusCode = statusCode;
- response.ContentType = "text/html";
- response.ContentLength64 = buffer.Length;
- using (Stream stream = response.OutputStream)
- {
- await stream.WriteAsync(buffer);
- }
- }
- catch
- { }
- }
- private static async Task SendFileAsync(HttpListenerRequest request, HttpListenerResponse response, string filePath)
- {
- using (FileStream fS = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- response.ContentType = WebUtilities.GetContentType(filePath).MediaType;
- response.AddHeader("Cache-Control", "private, max-age=300");
- using (Stream stream = GetOutputStream(request, response))
- {
- try
- {
- await fS.CopyToAsync(stream);
- }
- catch (HttpListenerException)
- {
- //ignore this error
- }
- }
- }
- }
- #endregion
- #region user session
- private string CreateSession(string username)
- {
- string token = BinaryNumber.GenerateRandomNumber256().ToString();
- if (!_sessions.TryAdd(token, new UserSession(username)))
- throw new DnsWebServiceException("Error while creating session. Please try again.");
- return token;
- }
- private UserSession GetSession(string token)
- {
- if (_sessions.TryGetValue(token, out UserSession session))
- return session;
- return null;
- }
- private UserSession GetSession(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- return GetSession(strToken);
- }
- private UserSession DeleteSession(string token)
- {
- if (_sessions.TryRemove(token, out UserSession session))
- return session;
- return null;
- }
- private UserSession DeleteSession(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- return DeleteSession(strToken);
- }
- private void FailedLoginAttempt(IPAddress address)
- {
- _failedLoginAttempts.AddOrUpdate(address, 1, delegate (IPAddress key, int attempts)
- {
- return attempts + 1;
- });
- }
- private bool LoginAttemptsExceedLimit(IPAddress address, int limit)
- {
- if (!_failedLoginAttempts.TryGetValue(address, out int attempts))
- return false;
- return attempts >= limit;
- }
- private void ResetFailedLoginAttempt(IPAddress address)
- {
- _failedLoginAttempts.TryRemove(address, out _);
- }
- private void BlockAddress(IPAddress address, int interval)
- {
- _blockedAddresses.TryAdd(address, DateTime.UtcNow.AddMilliseconds(interval));
- }
- private bool IsAddressBlocked(IPAddress address)
- {
- if (!_blockedAddresses.TryGetValue(address, out DateTime expiry))
- return false;
- if (expiry > DateTime.UtcNow)
- {
- return true;
- }
- else
- {
- UnblockAddress(address);
- ResetFailedLoginAttempt(address);
- return false;
- }
- }
- private void UnblockAddress(IPAddress address)
- {
- _blockedAddresses.TryRemove(address, out _);
- }
- #endregion
- #region auth api
- private async Task LoginAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string strUsername = request.QueryString["user"];
- if (string.IsNullOrEmpty(strUsername))
- throw new DnsWebServiceException("Parameter 'user' missing.");
- string strPassword = request.QueryString["pass"];
- if (string.IsNullOrEmpty(strPassword))
- throw new DnsWebServiceException("Parameter 'pass' missing.");
- IPEndPoint remoteEP = GetRequestRemoteEndPoint(request);
- if (IsAddressBlocked(remoteEP.Address))
- throw new DnsWebServiceException("Max limit of " + MAX_LOGIN_ATTEMPTS + " attempts exceeded. Access blocked for " + (BLOCK_ADDRESS_INTERVAL / 1000) + " seconds.");
- strUsername = strUsername.ToLower();
- string strPasswordHash = GetPasswordHash(strUsername, strPassword);
- if (!_credentials.TryGetValue(strUsername, out string passwordHash) || (passwordHash != strPasswordHash))
- {
- if (strPassword != "admin") //exception for default password
- {
- FailedLoginAttempt(remoteEP.Address);
- if (LoginAttemptsExceedLimit(remoteEP.Address, MAX_LOGIN_ATTEMPTS))
- BlockAddress(remoteEP.Address, BLOCK_ADDRESS_INTERVAL);
- await Task.Delay(1000);
- }
- throw new DnsWebServiceException("Invalid username or password: " + strUsername);
- }
- ResetFailedLoginAttempt(remoteEP.Address);
- _log.Write(remoteEP, "[" + strUsername + "] User logged in.");
- string token = CreateSession(strUsername);
- jsonWriter.WritePropertyName("token");
- jsonWriter.WriteValue(token);
- }
- private bool IsSessionValid(HttpListenerRequest request)
- {
- UserSession session = GetSession(request);
- if (session == null)
- return false;
- if (session.HasExpired())
- {
- DeleteSession(request);
- return false;
- }
- session.UpdateLastSeen();
- return true;
- }
- private void ChangePassword(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- string strPassword = request.QueryString["pass"];
- if (string.IsNullOrEmpty(strPassword))
- throw new DnsWebServiceException("Parameter 'pass' missing.");
- UserSession session = GetSession(strToken);
- if (session == null)
- throw new DnsWebServiceException("User session does not exists.");
- SetCredentials(session.Username, strPassword);
- SaveConfigFile();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] Password was changed for user.");
- }
- private void Logout(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- UserSession session = DeleteSession(strToken);
- if (session != null)
- _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] User logged out.");
- }
- #endregion
- #region update api
- public static void CreateUpdateInfo(Stream s, string version, string displayText, string downloadLink)
- {
- BinaryWriter bW = new BinaryWriter(s);
- bW.Write(Encoding.ASCII.GetBytes("DU")); //format
- bW.Write((byte)2); //version
- bW.WriteShortString(version);
- bW.WriteShortString(displayText);
- bW.WriteShortString(downloadLink);
- }
- private async Task CheckForUpdateAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- Version updateVersion = null;
- string displayText = null;
- string downloadLink = null;
- bool updateAvailable = false;
- if (_updateCheckUri != null)
- {
- try
- {
- SocketsHttpHandler handler = new SocketsHttpHandler();
- handler.Proxy = _dnsServer.Proxy;
- using (HttpClient http = new HttpClient(handler))
- {
- byte[] response = await http.GetByteArrayAsync(_updateCheckUri);
- using (MemoryStream mS = new MemoryStream(response, false))
- {
- BinaryReader bR = new BinaryReader(mS);
- if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DU") //format
- throw new InvalidDataException("DNS Server update info format is invalid.");
- switch (bR.ReadByte()) //version
- {
- case 2:
- updateVersion = new Version(bR.ReadShortString());
- displayText = bR.ReadShortString();
- downloadLink = bR.ReadShortString();
- break;
- default:
- throw new InvalidDataException("DNS Server update info version not supported.");
- }
- updateAvailable = updateVersion > _currentVersion;
- }
- }
- _log.Write(GetRequestRemoteEndPoint(request), "Check for update was done {updateAvailable: " + updateAvailable + "; updateVersion: " + updateVersion + "; displayText: " + displayText + "; downloadLink: " + downloadLink + ";}");
- }
- catch (Exception ex)
- {
- _log.Write(GetRequestRemoteEndPoint(request), "Check for update was done {updateAvailable: False;}\r\n" + ex.ToString());
- }
- }
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(updateAvailable);
- if (updateAvailable)
- {
- if (!string.IsNullOrEmpty(displayText))
- {
- jsonWriter.WritePropertyName("displayText");
- jsonWriter.WriteValue(displayText);
- }
- jsonWriter.WritePropertyName("downloadLink");
- jsonWriter.WriteValue(downloadLink);
- }
- }
- private static string GetCleanVersion(Version version)
- {
- string strVersion = version.Major + "." + version.Minor;
- if (version.Build > 0)
- strVersion += "." + version.Build;
- if (version.Revision > 0)
- strVersion += "." + version.Revision;
- return strVersion;
- }
- #endregion
- #region settings api
- private void GetDnsSettings(JsonTextWriter jsonWriter)
- {
- jsonWriter.WritePropertyName("version");
- jsonWriter.WriteValue(GetCleanVersion(_currentVersion));
- jsonWriter.WritePropertyName("dnsServerDomain");
- jsonWriter.WriteValue(_dnsServer.ServerDomain);
- jsonWriter.WritePropertyName("dnsServerLocalEndPoints");
- jsonWriter.WriteStartArray();
- foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
- jsonWriter.WriteValue(localEP.ToString());
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("webServiceLocalAddresses");
- jsonWriter.WriteStartArray();
- foreach (IPAddress localAddress in _webServiceLocalAddresses)
- {
- if (localAddress.AddressFamily == AddressFamily.InterNetworkV6)
- jsonWriter.WriteValue("[" + localAddress.ToString() + "]");
- else
- jsonWriter.WriteValue(localAddress.ToString());
- }
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("webServiceHttpPort");
- jsonWriter.WriteValue(_webServiceHttpPort);
- jsonWriter.WritePropertyName("webServiceEnableTls");
- jsonWriter.WriteValue(_webServiceEnableTls);
- jsonWriter.WritePropertyName("webServiceHttpToTlsRedirect");
- jsonWriter.WriteValue(_webServiceHttpToTlsRedirect);
- jsonWriter.WritePropertyName("webServiceTlsPort");
- jsonWriter.WriteValue(_webServiceTlsPort);
- jsonWriter.WritePropertyName("webServiceTlsCertificatePath");
- jsonWriter.WriteValue(_webServiceTlsCertificatePath);
- jsonWriter.WritePropertyName("webServiceTlsCertificatePassword");
- jsonWriter.WriteValue("************");
- jsonWriter.WritePropertyName("enableDnsOverHttp");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttp);
- jsonWriter.WritePropertyName("enableDnsOverTls");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverTls);
- jsonWriter.WritePropertyName("enableDnsOverHttps");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttps);
- jsonWriter.WritePropertyName("dnsTlsCertificatePath");
- jsonWriter.WriteValue(_dnsTlsCertificatePath);
- jsonWriter.WritePropertyName("dnsTlsCertificatePassword");
- jsonWriter.WriteValue("************");
- jsonWriter.WritePropertyName("preferIPv6");
- jsonWriter.WriteValue(_dnsServer.PreferIPv6);
- jsonWriter.WritePropertyName("enableLogging");
- jsonWriter.WriteValue(_log.EnableLogging);
- jsonWriter.WritePropertyName("logQueries");
- jsonWriter.WriteValue(_dnsServer.QueryLogManager != null);
- jsonWriter.WritePropertyName("useLocalTime");
- jsonWriter.WriteValue(_log.UseLocalTime);
- jsonWriter.WritePropertyName("logFolder");
- jsonWriter.WriteValue(_log.LogFolder);
- jsonWriter.WritePropertyName("maxLogFileDays");
- jsonWriter.WriteValue(_log.MaxLogFileDays);
- jsonWriter.WritePropertyName("maxStatFileDays");
- jsonWriter.WriteValue(_dnsServer.StatsManager.MaxStatFileDays);
- jsonWriter.WritePropertyName("allowRecursion");
- jsonWriter.WriteValue(_dnsServer.AllowRecursion);
- jsonWriter.WritePropertyName("allowRecursionOnlyForPrivateNetworks");
- jsonWriter.WriteValue(_dnsServer.AllowRecursionOnlyForPrivateNetworks);
- jsonWriter.WritePropertyName("randomizeName");
- jsonWriter.WriteValue(_dnsServer.RandomizeName);
- jsonWriter.WritePropertyName("qnameMinimization");
- jsonWriter.WriteValue(_dnsServer.QnameMinimization);
- jsonWriter.WritePropertyName("serveStale");
- jsonWriter.WriteValue(_dnsServer.ServeStale);
- jsonWriter.WritePropertyName("serveStaleTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.ServeStaleTtl);
- jsonWriter.WritePropertyName("cachePrefetchEligibility");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchEligibility);
- jsonWriter.WritePropertyName("cachePrefetchTrigger");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchTrigger);
- jsonWriter.WritePropertyName("cachePrefetchSampleIntervalInMinutes");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleIntervalInMinutes);
- jsonWriter.WritePropertyName("cachePrefetchSampleEligibilityHitsPerHour");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
- jsonWriter.WritePropertyName("proxy");
- if (_dnsServer.Proxy == null)
- {
- jsonWriter.WriteNull();
- }
- else
- {
- jsonWriter.WriteStartObject();
- NetProxy proxy = _dnsServer.Proxy;
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(proxy.Type.ToString());
- jsonWriter.WritePropertyName("address");
- jsonWriter.WriteValue(proxy.Address);
- jsonWriter.WritePropertyName("port");
- jsonWriter.WriteValue(proxy.Port);
- NetworkCredential credential = proxy.Credential;
- if (credential != null)
- {
- jsonWriter.WritePropertyName("username");
- jsonWriter.WriteValue(credential.UserName);
- jsonWriter.WritePropertyName("password");
- jsonWriter.WriteValue(credential.Password);
- }
- jsonWriter.WritePropertyName("bypass");
- jsonWriter.WriteStartArray();
- foreach (NetProxyBypassItem item in proxy.BypassList)
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WritePropertyName("forwarders");
- DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
- if (_dnsServer.Forwarders == null)
- {
- jsonWriter.WriteNull();
- }
- else
- {
- forwarderProtocol = _dnsServer.Forwarders[0].Protocol;
- jsonWriter.WriteStartArray();
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- jsonWriter.WriteValue(forwarder.OriginalAddress);
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("forwarderProtocol");
- jsonWriter.WriteValue(forwarderProtocol.ToString());
- jsonWriter.WritePropertyName("useNxDomainForBlocking");
- jsonWriter.WriteValue(_dnsServer.UseNxDomainForBlocking);
- jsonWriter.WritePropertyName("blockListUrls");
- if ((_dnsServer.BlockListZoneManager.AllowListUrls.Count == 0) && (_dnsServer.BlockListZoneManager.BlockListUrls.Count == 0))
- {
- jsonWriter.WriteNull();
- }
- else
- {
- jsonWriter.WriteStartArray();
- foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
- jsonWriter.WriteValue("!" + allowListUrl.AbsoluteUri);
- foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
- jsonWriter.WriteValue(blockListUrl.AbsoluteUri);
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("blockListUpdateIntervalHours");
- jsonWriter.WriteValue(_blockListUpdateIntervalHours);
- jsonWriter.WritePropertyName("blockListNextUpdatedOn");
- jsonWriter.WriteValue(_blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours).ToLocalTime().ToString());
- }
- private void SetDnsSettings(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- bool restartDnsService = false;
- bool restartWebService = false;
- string strDnsServerDomain = request.QueryString["dnsServerDomain"];
- if (!string.IsNullOrEmpty(strDnsServerDomain))
- _dnsServer.ServerDomain = strDnsServerDomain;
- string strDnsServerLocalEndPoints = request.QueryString["dnsServerLocalEndPoints"];
- if (strDnsServerLocalEndPoints != null)
- {
- if (string.IsNullOrEmpty(strDnsServerLocalEndPoints))
- strDnsServerLocalEndPoints = "0.0.0.0:53,[::]:53";
- string[] strLocalEndPoints = strDnsServerLocalEndPoints.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<IPEndPoint> localEndPoints = new List<IPEndPoint>(strLocalEndPoints.Length);
- for (int i = 0; i < strLocalEndPoints.Length; i++)
- {
- NameServerAddress nameServer = new NameServerAddress(strLocalEndPoints[i]);
- if (nameServer.IPEndPoint != null)
- localEndPoints.Add(nameServer.IPEndPoint);
- }
- if (localEndPoints.Count > 0)
- {
- if (_dnsServer.LocalEndPoints.Count != localEndPoints.Count)
- {
- restartDnsService = true;
- }
- else
- {
- foreach (IPEndPoint currentLocalEP in _dnsServer.LocalEndPoints)
- {
- if (!localEndPoints.Contains(currentLocalEP))
- {
- restartDnsService = true;
- break;
- }
- }
- }
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- string strWebServiceLocalAddresses = request.QueryString["webServiceLocalAddresses"];
- if (strWebServiceLocalAddresses != null)
- {
- if (string.IsNullOrEmpty(strWebServiceLocalAddresses))
- strWebServiceLocalAddresses = "0.0.0.0,[::]";
- string[] strLocalAddresses = strWebServiceLocalAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<IPAddress> localAddresses = new List<IPAddress>(strLocalAddresses.Length);
- for (int i = 0; i < strLocalAddresses.Length; i++)
- {
- if (IPAddress.TryParse(strLocalAddresses[i], out IPAddress localAddress))
- localAddresses.Add(localAddress);
- }
- if (localAddresses.Count > 0)
- {
- if (_webServiceLocalAddresses.Count != localAddresses.Count)
- {
- restartWebService = true;
- }
- else
- {
- foreach (IPAddress currentlocalAddress in _webServiceLocalAddresses)
- {
- if (!localAddresses.Contains(currentlocalAddress))
- {
- restartWebService = true;
- break;
- }
- }
- }
- _webServiceLocalAddresses = localAddresses;
- }
- }
- int oldWebServiceHttpPort = _webServiceHttpPort;
- string strWebServiceHttpPort = request.QueryString["webServiceHttpPort"];
- if (!string.IsNullOrEmpty(strWebServiceHttpPort))
- {
- _webServiceHttpPort = int.Parse(strWebServiceHttpPort);
- if (oldWebServiceHttpPort != _webServiceHttpPort)
- restartWebService = true;
- }
- string strWebServiceEnableTls = request.QueryString["webServiceEnableTls"];
- if (!string.IsNullOrEmpty(strWebServiceEnableTls))
- {
- bool oldWebServiceEnableTls = _webServiceEnableTls;
- _webServiceEnableTls = bool.Parse(strWebServiceEnableTls);
- if (oldWebServiceEnableTls != _webServiceEnableTls)
- restartWebService = true;
- }
- string strWebServiceHttpToTlsRedirect = request.QueryString["webServiceHttpToTlsRedirect"];
- if (!string.IsNullOrEmpty(strWebServiceHttpToTlsRedirect))
- _webServiceHttpToTlsRedirect = bool.Parse(strWebServiceHttpToTlsRedirect);
- string strWebServiceTlsPort = request.QueryString["webServiceTlsPort"];
- if (!string.IsNullOrEmpty(strWebServiceTlsPort))
- {
- int oldWebServiceTlsPort = _webServiceTlsPort;
- _webServiceTlsPort = int.Parse(strWebServiceTlsPort);
- if (oldWebServiceTlsPort != _webServiceTlsPort)
- restartWebService = true;
- }
- string strWebServiceTlsCertificatePath = request.QueryString["webServiceTlsCertificatePath"];
- string strWebServiceTlsCertificatePassword = request.QueryString["webServiceTlsCertificatePassword"];
- if (string.IsNullOrEmpty(strWebServiceTlsCertificatePath))
- {
- _webServiceTlsCertificatePath = null;
- _webServiceTlsCertificatePassword = "";
- }
- else
- {
- if (strWebServiceTlsCertificatePassword == "************")
- strWebServiceTlsCertificatePassword = _webServiceTlsCertificatePassword;
- if ((strWebServiceTlsCertificatePath != _webServiceTlsCertificatePath) || (strWebServiceTlsCertificatePassword != _webServiceTlsCertificatePassword))
- {
- LoadWebServiceTlsCertificate(strWebServiceTlsCertificatePath, strWebServiceTlsCertificatePassword);
- _webServiceTlsCertificatePath = strWebServiceTlsCertificatePath;
- _webServiceTlsCertificatePassword = strWebServiceTlsCertificatePassword;
- StartTlsCertificateUpdateTimer();
- }
- }
- string enableDnsOverHttp = request.QueryString["enableDnsOverHttp"];
- if (!string.IsNullOrEmpty(enableDnsOverHttp))
- {
- bool oldEnableDnsOverHttp = _dnsServer.EnableDnsOverHttp;
- _dnsServer.EnableDnsOverHttp = bool.Parse(enableDnsOverHttp);
- if (oldEnableDnsOverHttp != _dnsServer.EnableDnsOverHttp)
- restartDnsService = true;
- }
- string strEnableDnsOverTls = request.QueryString["enableDnsOverTls"];
- if (!string.IsNullOrEmpty(strEnableDnsOverTls))
- {
- bool oldEnableDnsOverTls = _dnsServer.EnableDnsOverTls;
- _dnsServer.EnableDnsOverTls = bool.Parse(strEnableDnsOverTls);
- if (oldEnableDnsOverTls != _dnsServer.EnableDnsOverTls)
- restartDnsService = true;
- }
- string strEnableDnsOverHttps = request.QueryString["enableDnsOverHttps"];
- if (!string.IsNullOrEmpty(strEnableDnsOverHttps))
- {
- bool oldEnableDnsOverHttps = _dnsServer.EnableDnsOverHttps;
- _dnsServer.EnableDnsOverHttps = bool.Parse(strEnableDnsOverHttps);
- if (oldEnableDnsOverHttps != _dnsServer.EnableDnsOverHttps)
- restartDnsService = true;
- }
- string strDnsTlsCertificatePath = request.QueryString["dnsTlsCertificatePath"];
- string strDnsTlsCertificatePassword = request.QueryString["dnsTlsCertificatePassword"];
- if (string.IsNullOrEmpty(strDnsTlsCertificatePath))
- {
- _dnsTlsCertificatePath = null;
- _dnsTlsCertificatePassword = "";
- }
- else
- {
- if (strDnsTlsCertificatePassword == "************")
- strDnsTlsCertificatePassword = _dnsTlsCertificatePassword;
- if ((strDnsTlsCertificatePath != _dnsTlsCertificatePath) || (strDnsTlsCertificatePassword != _dnsTlsCertificatePassword))
- {
- LoadDnsTlsCertificate(strDnsTlsCertificatePath, strDnsTlsCertificatePassword);
- _dnsTlsCertificatePath = strDnsTlsCertificatePath;
- _dnsTlsCertificatePassword = strDnsTlsCertificatePassword;
- StartTlsCertificateUpdateTimer();
- }
- }
- string strPreferIPv6 = request.QueryString["preferIPv6"];
- if (!string.IsNullOrEmpty(strPreferIPv6))
- _dnsServer.PreferIPv6 = bool.Parse(strPreferIPv6);
- string strEnableLogging = request.QueryString["enableLogging"];
- if (!string.IsNullOrEmpty(strEnableLogging))
- _log.EnableLogging = bool.Parse(strEnableLogging);
- string strLogQueries = request.QueryString["logQueries"];
- if (!string.IsNullOrEmpty(strLogQueries))
- {
- if (bool.Parse(strLogQueries))
- _dnsServer.QueryLogManager = _log;
- else
- _dnsServer.QueryLogManager = null;
- }
- string strUseLocalTime = request.QueryString["useLocalTime"];
- if (!string.IsNullOrEmpty(strUseLocalTime))
- _log.UseLocalTime = bool.Parse(strUseLocalTime);
- string strLogFolder = request.QueryString["logFolder"];
- if (!string.IsNullOrEmpty(strLogFolder))
- _log.LogFolder = strLogFolder;
- string strMaxLogFileDays = request.QueryString["maxLogFileDays"];
- if (!string.IsNullOrEmpty(strMaxLogFileDays))
- _log.MaxLogFileDays = int.Parse(strMaxLogFileDays);
- string strMaxStatFileDays = request.QueryString["maxStatFileDays"];
- if (!string.IsNullOrEmpty(strMaxStatFileDays))
- _dnsServer.StatsManager.MaxStatFileDays = int.Parse(strMaxStatFileDays);
- string strAllowRecursion = request.QueryString["allowRecursion"];
- if (!string.IsNullOrEmpty(strAllowRecursion))
- _dnsServer.AllowRecursion = bool.Parse(strAllowRecursion);
- string strAllowRecursionOnlyForPrivateNetworks = request.QueryString["allowRecursionOnlyForPrivateNetworks"];
- if (!string.IsNullOrEmpty(strAllowRecursionOnlyForPrivateNetworks))
- _dnsServer.AllowRecursionOnlyForPrivateNetworks = bool.Parse(strAllowRecursionOnlyForPrivateNetworks);
- string strRandomizeName = request.QueryString["randomizeName"];
- if (!string.IsNullOrEmpty(strRandomizeName))
- _dnsServer.RandomizeName = bool.Parse(strRandomizeName);
- string strQnameMinimization = request.QueryString["qnameMinimization"];
- if (!string.IsNullOrEmpty(strQnameMinimization))
- _dnsServer.QnameMinimization = bool.Parse(strQnameMinimization);
- string strServeStale = request.QueryString["serveStale"];
- if (!string.IsNullOrEmpty(strServeStale))
- _dnsServer.ServeStale = bool.Parse(strServeStale);
- string strServeStaleTtl = request.QueryString["serveStaleTtl"];
- if (!string.IsNullOrEmpty(strServeStaleTtl))
- _dnsServer.CacheZoneManager.ServeStaleTtl = uint.Parse(strServeStaleTtl);
- string strCachePrefetchEligibility = request.QueryString["cachePrefetchEligibility"];
- if (!string.IsNullOrEmpty(strCachePrefetchEligibility))
- _dnsServer.CachePrefetchEligibility = int.Parse(strCachePrefetchEligibility);
- string strCachePrefetchTrigger = request.QueryString["cachePrefetchTrigger"];
- if (!string.IsNullOrEmpty(strCachePrefetchTrigger))
- _dnsServer.CachePrefetchTrigger = int.Parse(strCachePrefetchTrigger);
- string strCachePrefetchSampleIntervalInMinutes = request.QueryString["cachePrefetchSampleIntervalInMinutes"];
- if (!string.IsNullOrEmpty(strCachePrefetchSampleIntervalInMinutes))
- _dnsServer.CachePrefetchSampleIntervalInMinutes = int.Parse(strCachePrefetchSampleIntervalInMinutes);
- string strCachePrefetchSampleEligibilityHitsPerHour = request.QueryString["cachePrefetchSampleEligibilityHitsPerHour"];
- if (!string.IsNullOrEmpty(strCachePrefetchSampleEligibilityHitsPerHour))
- _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = int.Parse(strCachePrefetchSampleEligibilityHitsPerHour);
- string strProxyType = request.QueryString["proxyType"];
- if (!string.IsNullOrEmpty(strProxyType))
- {
- NetProxyType proxyType = (NetProxyType)Enum.Parse(typeof(NetProxyType), strProxyType, true);
- if (proxyType == NetProxyType.None)
- {
- _dnsServer.Proxy = null;
- }
- else
- {
- NetworkCredential credential = null;
- string strUsername = request.QueryString["proxyUsername"];
- if (!string.IsNullOrEmpty(strUsername))
- credential = new NetworkCredential(strUsername, request.QueryString["proxyPassword"]);
- _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, request.QueryString["proxyAddress"], int.Parse(request.QueryString["proxyPort"]), credential);
- string strProxyBypass = request.QueryString["proxyBypass"];
- if (!string.IsNullOrEmpty(strProxyBypass))
- {
- string[] strBypassList = strProxyBypass.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(strBypassList.Length);
- for (int i = 0; i < strBypassList.Length; i++)
- bypassList.Add(new NetProxyBypassItem(strBypassList[i]));
- _dnsServer.Proxy.BypassList = bypassList;
- }
- }
- }
- DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
- string strForwarderProtocol = request.QueryString["forwarderProtocol"];
- if (!string.IsNullOrEmpty(strForwarderProtocol))
- forwarderProtocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strForwarderProtocol, true);
- string strForwarders = request.QueryString["forwarders"];
- if (!string.IsNullOrEmpty(strForwarders))
- {
- if (strForwarders == "false")
- {
- _dnsServer.Forwarders = null;
- }
- else
- {
- string[] strForwardersList = strForwarders.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NameServerAddress[] forwarders = new NameServerAddress[strForwardersList.Length];
- for (int i = 0; i < strForwardersList.Length; i++)
- {
- if ((forwarderProtocol == DnsTransportProtocol.Tls) && IPAddress.TryParse(strForwardersList[i], out _))
- strForwardersList[i] += ":853";
- forwarders[i] = new NameServerAddress(strForwardersList[i], forwarderProtocol);
- }
- _dnsServer.Forwarders = forwarders;
- }
- }
- string strUseNxDomainForBlocking = request.QueryString["useNxDomainForBlocking"];
- if (!string.IsNullOrEmpty(strUseNxDomainForBlocking))
- _dnsServer.UseNxDomainForBlocking = bool.Parse(strUseNxDomainForBlocking);
- string strBlockListUrls = request.QueryString["blockListUrls"];
- if (!string.IsNullOrEmpty(strBlockListUrls))
- {
- if (strBlockListUrls == "false")
- {
- StopBlockListUpdateTimer();
- _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
- _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
- _dnsServer.BlockListZoneManager.Flush();
- }
- else
- {
- bool updated = false;
- string[] strBlockListUrlList = strBlockListUrls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- if (oldWebServiceHttpPort != _webServiceHttpPort)
- {
- for (int i = 0; i < strBlockListUrlList.Length; i++)
- {
- if (strBlockListUrlList[i].Contains("http://localhost:" + oldWebServiceHttpPort + "/blocklist.txt"))
- {
- strBlockListUrlList[i] = "http://localhost:" + _webServiceHttpPort + "/blocklist.txt";
- updated = true;
- break;
- }
- }
- }
- if (!updated)
- {
- if (strBlockListUrlList.Length != (_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count))
- {
- updated = true;
- }
- else
- {
- foreach (string strBlockListUrl in strBlockListUrlList)
- {
- if (strBlockListUrl.StartsWith("!"))
- {
- string strAllowListUrl = strBlockListUrl.Substring(1);
- if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(new Uri(strAllowListUrl)))
- {
- updated = true;
- break;
- }
- }
- else
- {
- if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(new Uri(strBlockListUrl)))
- {
- updated = true;
- break;
- }
- }
- }
- }
- }
- if (updated)
- {
- _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
- _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
- foreach (string strBlockListUrl in strBlockListUrlList)
- {
- if (strBlockListUrl.StartsWith("!"))
- {
- Uri allowListUrl = new Uri(strBlockListUrl.Substring(1));
- if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(allowListUrl))
- _dnsServer.BlockListZoneManager.AllowListUrls.Add(allowListUrl);
- }
- else
- {
- Uri blockListUrl = new Uri(strBlockListUrl);
- if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(blockListUrl))
- _dnsServer.BlockListZoneManager.BlockListUrls.Add(blockListUrl);
- }
- }
- ForceUpdateBlockLists();
- }
- }
- }
- string strBlockListUpdateIntervalHours = request.QueryString["blockListUpdateIntervalHours"];
- if (!string.IsNullOrEmpty(strBlockListUpdateIntervalHours))
- {
- int blockListUpdateIntervalHours = int.Parse(strBlockListUpdateIntervalHours);
- if ((blockListUpdateIntervalHours < 1) || (blockListUpdateIntervalHours > 168))
- throw new ArgumentOutOfRangeException("Parameter `blockListUpdateIntervalHours` must be between 1 hour and 168 hours (7 days).");
- _blockListUpdateIntervalHours = blockListUpdateIntervalHours;
- }
- SaveConfigFile();
- _log.Save();
- _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 + ";}");
- if ((_webServiceTlsCertificatePath == null) && (_dnsTlsCertificatePath == null))
- StopTlsCertificateUpdateTimer();
- GetDnsSettings(jsonWriter);
- RestartService(restartDnsService, restartWebService);
- }
- private void RestartService(bool restartDnsService, bool restartWebService)
- {
- if (restartDnsService)
- {
- _ = Task.Run(delegate ()
- {
- _log.Write("Attempting to restart DNS service.");
- try
- {
- _dnsServer.Stop();
- _dnsServer.Start();
- _log.Write("DNS service was restarted successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to restart DNS service.");
- _log.Write(ex);
- }
- });
- }
- if (restartWebService)
- {
- _ = Task.Run(async delegate ()
- {
- await Task.Delay(2000); //wait for this HTTP response to be delivered before stopping web server
- _log.Write("Attempting to restart web service.");
- try
- {
- StopDnsWebService();
- StartDnsWebService();
- _log.Write("Web service was restarted successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to restart web service.");
- _log.Write(ex);
- }
- });
- }
- }
- private async Task BackupSettingsAsync(HttpListenerRequest request, HttpListenerResponse response)
- {
- bool blockLists = false;
- bool logs = false;
- bool scopes = false;
- bool apps = false;
- bool stats = false;
- bool zones = false;
- bool allowedZones = false;
- bool blockedZones = false;
- bool dnsSettings = false;
- bool logSettings = false;
- string strBlockLists = request.QueryString["blockLists"];
- if (!string.IsNullOrEmpty(strBlockLists))
- blockLists = bool.Parse(strBlockLists);
- string strLogs = request.QueryString["logs"];
- if (!string.IsNullOrEmpty(strLogs))
- logs = bool.Parse(strLogs);
- string strScopes = request.QueryString["scopes"];
- if (!string.IsNullOrEmpty(strScopes))
- scopes = bool.Parse(strScopes);
- string strApps = request.QueryString["apps"];
- if (!string.IsNullOrEmpty(strApps))
- apps = bool.Parse(strApps);
- string strStats = request.QueryString["stats"];
- if (!string.IsNullOrEmpty(strStats))
- stats = bool.Parse(strStats);
- string strZones = request.QueryString["zones"];
- if (!string.IsNullOrEmpty(strZones))
- zones = bool.Parse(strZones);
- string strAllowedZones = request.QueryString["allowedZones"];
- if (!string.IsNullOrEmpty(strAllowedZones))
- allowedZones = bool.Parse(strAllowedZones);
- string strBlockedZones = request.QueryString["blockedZones"];
- if (!string.IsNullOrEmpty(strBlockedZones))
- blockedZones = bool.Parse(strBlockedZones);
- string strDnsSettings = request.QueryString["dnsSettings"];
- if (!string.IsNullOrEmpty(strDnsSettings))
- dnsSettings = bool.Parse(strDnsSettings);
- string strLogSettings = request.QueryString["logSettings"];
- if (!string.IsNullOrEmpty(strLogSettings))
- logSettings = bool.Parse(strLogSettings);
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream backupZipStream = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //create backup zip
- using (ZipArchive backupZip = new ZipArchive(backupZipStream, ZipArchiveMode.Create, true, Encoding.UTF8))
- {
- if (blockLists)
- {
- string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
- foreach (string blockListFile in blockListFiles)
- {
- string entryName = "blocklists/" + Path.GetFileName(blockListFile);
- backupZip.CreateEntryFromFile(blockListFile, entryName);
- }
- }
- if (logs)
- {
- string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
- foreach (string logFile in logFiles)
- {
- string entryName = "logs/" + Path.GetFileName(logFile);
- if (logFile.Equals(_log.CurrentLogFile, StringComparison.OrdinalIgnoreCase))
- {
- using (FileStream fS = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- ZipArchiveEntry entry = backupZip.CreateEntry(entryName);
- using (Stream s = entry.Open())
- {
- await fS.CopyToAsync(s);
- }
- }
- }
- else
- {
- backupZip.CreateEntryFromFile(logFile, entryName);
- }
- }
- }
- if (scopes)
- {
- string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
- foreach (string scopeFile in scopeFiles)
- {
- string entryName = "scopes/" + Path.GetFileName(scopeFile);
- backupZip.CreateEntryFromFile(scopeFile, entryName);
- }
- }
- if (apps)
- {
- string[] appFiles = Directory.GetFiles(Path.Combine(_configFolder, "apps"), "*", SearchOption.AllDirectories);
- foreach (string appFile in appFiles)
- {
- string entryName = appFile.Substring(_configFolder.Length);
- if (Path.DirectorySeparatorChar != '/')
- entryName = entryName.Replace(Path.DirectorySeparatorChar, '/');
- entryName = entryName.TrimStart('/');
- backupZip.CreateEntryFromFile(appFile, entryName);
- }
- }
- if (stats)
- {
- string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
- foreach (string hourlyStatsFile in hourlyStatsFiles)
- {
- string entryName = "stats/" + Path.GetFileName(hourlyStatsFile);
- backupZip.CreateEntryFromFile(hourlyStatsFile, entryName);
- }
- string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
- foreach (string dailyStatsFile in dailyStatsFiles)
- {
- string entryName = "stats/" + Path.GetFileName(dailyStatsFile);
- backupZip.CreateEntryFromFile(dailyStatsFile, entryName);
- }
- }
- if (zones)
- {
- string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
- foreach (string zoneFile in zoneFiles)
- {
- string entryName = "zones/" + Path.GetFileName(zoneFile);
- backupZip.CreateEntryFromFile(zoneFile, entryName);
- }
- }
- if (allowedZones)
- {
- string allowedZonesFile = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(allowedZonesFile))
- backupZip.CreateEntryFromFile(allowedZonesFile, "allowed.config");
- }
- if (blockedZones)
- {
- string blockedZonesFile = Path.Combine(_configFolder, "blocked.config");
- if (File.Exists(blockedZonesFile))
- backupZip.CreateEntryFromFile(blockedZonesFile, "blocked.config");
- }
- if (dnsSettings)
- {
- string dnsSettingsFile = Path.Combine(_configFolder, "dns.config");
- if (File.Exists(dnsSettingsFile))
- backupZip.CreateEntryFromFile(dnsSettingsFile, "dns.config");
- }
- if (logSettings)
- {
- string logSettingsFile = Path.Combine(_configFolder, "log.config");
- if (File.Exists(logSettingsFile))
- backupZip.CreateEntryFromFile(logSettingsFile, "log.config");
- }
- }
- //send zip file
- backupZipStream.Position = 0;
- response.ContentType = "application/zip";
- response.ContentLength64 = backupZipStream.Length;
- response.AddHeader("Content-Disposition", "attachment;filename=DnsServerBackup.zip");
- using (Stream output = response.OutputStream)
- {
- await backupZipStream.CopyToAsync(output);
- }
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was exported.");
- }
- private async Task RestoreSettingsAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- bool blockLists = false;
- bool logs = false;
- bool scopes = false;
- bool apps = false;
- bool stats = false;
- bool zones = false;
- bool allowedZones = false;
- bool blockedZones = false;
- bool dnsSettings = false;
- bool logSettings = false;
- bool deleteExistingFiles = false;
- string strBlockLists = request.QueryString["blockLists"];
- if (!string.IsNullOrEmpty(strBlockLists))
- blockLists = bool.Parse(strBlockLists);
- string strLogs = request.QueryString["logs"];
- if (!string.IsNullOrEmpty(strLogs))
- logs = bool.Parse(strLogs);
- string strScopes = request.QueryString["scopes"];
- if (!string.IsNullOrEmpty(strScopes))
- scopes = bool.Parse(strScopes);
- string strApps = request.QueryString["apps"];
- if (!string.IsNullOrEmpty(strApps))
- apps = bool.Parse(strApps);
- string strStats = request.QueryString["stats"];
- if (!string.IsNullOrEmpty(strStats))
- stats = bool.Parse(strStats);
- string strZones = request.QueryString["zones"];
- if (!string.IsNullOrEmpty(strZones))
- zones = bool.Parse(strZones);
- string strAllowedZones = request.QueryString["allowedZones"];
- if (!string.IsNullOrEmpty(strAllowedZones))
- allowedZones = bool.Parse(strAllowedZones);
- string strBlockedZones = request.QueryString["blockedZones"];
- if (!string.IsNullOrEmpty(strBlockedZones))
- blockedZones = bool.Parse(strBlockedZones);
- string strDnsSettings = request.QueryString["dnsSettings"];
- if (!string.IsNullOrEmpty(strDnsSettings))
- dnsSettings = bool.Parse(strDnsSettings);
- string strLogSettings = request.QueryString["logSettings"];
- if (!string.IsNullOrEmpty(strLogSettings))
- logSettings = bool.Parse(strLogSettings);
- string strDeleteExistingFiles = request.QueryString["deleteExistingFiles"];
- if (!string.IsNullOrEmpty(strDeleteExistingFiles))
- deleteExistingFiles = bool.Parse(strDeleteExistingFiles);
- #region skip to content
- int crlfCount = 0;
- int byteRead;
- while (crlfCount != 4)
- {
- byteRead = request.InputStream.ReadByte();
- switch (byteRead)
- {
- case -1:
- throw new EndOfStreamException();
- case 13: //CR
- case 10: //LF
- crlfCount++;
- break;
- default:
- crlfCount = 0;
- break;
- }
- }
- #endregion
- //write to temp file
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- await request.InputStream.CopyToAsync(fS);
- fS.Position = 0;
- using (ZipArchive backupZip = new ZipArchive(fS, ZipArchiveMode.Read, false, Encoding.UTF8))
- {
- if (logSettings || logs)
- {
- //stop logging
- _log.StopLogging();
- }
- try
- {
- if (logSettings)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("log.config");
- if (entry != null)
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- //reload config
- _log.LoadConfig();
- }
- if (logs)
- {
- if (deleteExistingFiles)
- {
- //delete existing log files
- string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
- foreach (string logFile in logFiles)
- {
- File.Delete(logFile);
- }
- }
- //extract log files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("logs/"))
- entry.ExtractToFile(Path.Combine(_log.LogFolderAbsolutePath, entry.Name), true);
- }
- }
- }
- finally
- {
- if (logSettings || logs)
- {
- //start logging
- if (_log.EnableLogging)
- _log.StartLogging();
- }
- }
- if (blockLists)
- {
- if (deleteExistingFiles)
- {
- //delete existing block list files
- string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
- foreach (string blockListFile in blockListFiles)
- {
- File.Delete(blockListFile);
- }
- }
- //extract block list files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("blocklists/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "blocklists", entry.Name), true);
- }
- }
- if (scopes)
- {
- //stop dhcp server
- _dhcpServer.Stop();
- try
- {
- if (deleteExistingFiles)
- {
- //delete existing scope files
- string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
- foreach (string scopeFile in scopeFiles)
- {
- File.Delete(scopeFile);
- }
- }
- //extract scope files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("scopes/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "scopes", entry.Name), true);
- }
- }
- finally
- {
- //start dhcp server
- _dhcpServer.Start();
- }
- }
- if (apps)
- {
- //unload apps
- _dnsServer.DnsApplicationManager.UnloadAllApplications();
- if (deleteExistingFiles)
- {
- //delete existing apps
- string appFolder = Path.Combine(_configFolder, "apps");
- if (Directory.Exists(appFolder))
- Directory.Delete(appFolder, true);
- }
- //extract apps files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("apps/"))
- {
- string entryPath = entry.FullName;
- if (Path.DirectorySeparatorChar != '/')
- entryPath = entryPath.Replace('/', '\\');
- string filePath = Path.Combine(_configFolder, entryPath);
- Directory.CreateDirectory(Path.GetDirectoryName(filePath));
- entry.ExtractToFile(filePath, true);
- }
- }
- //reload apps
- _dnsServer.DnsApplicationManager.LoadAllApplications();
- }
- if (stats)
- {
- if (deleteExistingFiles)
- {
- //delete existing stats files
- string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
- foreach (string hourlyStatsFile in hourlyStatsFiles)
- {
- File.Delete(hourlyStatsFile);
- }
- string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
- foreach (string dailyStatsFile in dailyStatsFiles)
- {
- File.Delete(dailyStatsFile);
- }
- }
- //extract stats files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("stats/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "stats", entry.Name), true);
- }
- //reload stats
- _dnsServer.StatsManager.ReloadStats();
- }
- if (zones)
- {
- if (deleteExistingFiles)
- {
- //delete existing zone files
- string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
- foreach (string zoneFile in zoneFiles)
- {
- File.Delete(zoneFile);
- }
- }
- //extract zone files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("zones/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "zones", entry.Name), true);
- }
- //reload zones
- _dnsServer.AuthZoneManager.LoadAllZoneFiles();
- }
- if (allowedZones)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("allowed.config");
- if (entry == null)
- {
- string fileName = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(fileName))
- File.Delete(fileName);
- }
- else
- {
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- }
- //reload
- _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
- }
- if (blockedZones)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("blocked.config");
- if (entry == null)
- {
- string fileName = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(fileName))
- File.Delete(fileName);
- }
- else
- {
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- }
- //reload
- _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
- }
- if (dnsSettings)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("dns.config");
- if (entry != null)
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- //reload settings and block list zone
- LoadConfigFile();
- _dnsServer.BlockListZoneManager.LoadBlockLists();
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was restored.");
- }
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- if (dnsSettings)
- RestartService(true, true);
- GetDnsSettings(jsonWriter);
- }
- private void ForceUpdateBlockLists(HttpListenerRequest request)
- {
- ForceUpdateBlockLists();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Block list update was triggered.");
- }
- #endregion
- #region dashboard
- private async Task GetStats(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- strType = "lastHour";
- Dictionary<string, List<KeyValuePair<string, int>>> data;
- switch (strType)
- {
- case "lastHour":
- data = _dnsServer.StatsManager.GetLastHourMinuteWiseStats();
- break;
- case "lastDay":
- data = _dnsServer.StatsManager.GetLastDayHourWiseStats();
- break;
- case "lastWeek":
- data = _dnsServer.StatsManager.GetLastWeekDayWiseStats();
- break;
- case "lastMonth":
- data = _dnsServer.StatsManager.GetLastMonthDayWiseStats();
- break;
- case "lastYear":
- data = _dnsServer.StatsManager.GetLastYearMonthWiseStats();
- break;
- case "custom":
- string strStartDate = request.QueryString["start"];
- if (string.IsNullOrEmpty(strStartDate))
- throw new DnsWebServiceException("Parameter 'start' missing.");
- string strEndDate = request.QueryString["end"];
- if (string.IsNullOrEmpty(strEndDate))
- throw new DnsWebServiceException("Parameter 'end' missing.");
- if (!DateTime.TryParseExact(strStartDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
- throw new DnsWebServiceException("Invalid start date format.");
- if (!DateTime.TryParseExact(strEndDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
- throw new DnsWebServiceException("Invalid end date format.");
- if (startDate > endDate)
- throw new DnsWebServiceException("Start date must be less than or equal to end date.");
- if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
- data = _dnsServer.StatsManager.GetDayWiseStats(startDate, endDate);
- else
- data = _dnsServer.StatsManager.GetHourWiseStats(startDate, endDate);
- break;
- default:
- throw new DnsWebServiceException("Unknown stats type requested: " + strType);
- }
- //stats
- {
- List<KeyValuePair<string, int>> stats = data["stats"];
- jsonWriter.WritePropertyName("stats");
- jsonWriter.WriteStartObject();
- foreach (KeyValuePair<string, int> item in stats)
- {
- jsonWriter.WritePropertyName(item.Key);
- jsonWriter.WriteValue(item.Value);
- }
- jsonWriter.WritePropertyName("zones");
- jsonWriter.WriteValue(_dnsServer.AuthZoneManager.TotalZones);
- jsonWriter.WritePropertyName("allowedZones");
- jsonWriter.WriteValue(_dnsServer.AllowedZoneManager.TotalZonesAllowed);
- jsonWriter.WritePropertyName("blockedZones");
- jsonWriter.WriteValue(_dnsServer.BlockedZoneManager.TotalZonesBlocked);
- jsonWriter.WritePropertyName("blockListZones");
- jsonWriter.WriteValue(_dnsServer.BlockListZoneManager.TotalZonesBlocked);
- jsonWriter.WriteEndObject();
- }
- //main chart
- {
- jsonWriter.WritePropertyName("mainChartData");
- jsonWriter.WriteStartObject();
- //label
- {
- List<KeyValuePair<string, int>> statsPerInterval = data["totalQueriesPerInterval"];
- jsonWriter.WritePropertyName("labels");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in statsPerInterval)
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WriteEndArray();
- }
- //datasets
- {
- jsonWriter.WritePropertyName("datasets");
- jsonWriter.WriteStartArray();
- WriteChartDataSet(jsonWriter, "Total", "rgba(102, 153, 255, 0.1)", "rgb(102, 153, 255)", data["totalQueriesPerInterval"]);
- WriteChartDataSet(jsonWriter, "No Error", "rgba(92, 184, 92, 0.1)", "rgb(92, 184, 92)", data["totalNoErrorPerInterval"]);
- WriteChartDataSet(jsonWriter, "Server Failure", "rgba(217, 83, 79, 0.1)", "rgb(217, 83, 79)", data["totalServerFailurePerInterval"]);
- WriteChartDataSet(jsonWriter, "NX Domain", "rgba(7, 7, 7, 0.1)", "rgb(7, 7, 7)", data["totalNxDomainPerInterval"]);
- WriteChartDataSet(jsonWriter, "Refused", "rgba(91, 192, 222, 0.1)", "rgb(91, 192, 222)", data["totalRefusedPerInterval"]);
- WriteChartDataSet(jsonWriter, "Authoritative", "rgba(150, 150, 0, 0.1)", "rgb(150, 150, 0)", data["totalAuthHitPerInterval"]);
- WriteChartDataSet(jsonWriter, "Recursive", "rgba(23, 162, 184, 0.1)", "rgb(23, 162, 184)", data["totalRecursionsPerInterval"]);
- WriteChartDataSet(jsonWriter, "Cached", "rgba(111, 84, 153, 0.1)", "rgb(111, 84, 153)", data["totalCacheHitPerInterval"]);
- WriteChartDataSet(jsonWriter, "Blocked", "rgba(255, 165, 0, 0.1)", "rgb(255, 165, 0)", data["totalBlockedPerInterval"]);
- WriteChartDataSet(jsonWriter, "Clients", "rgba(51, 122, 183, 0.1)", "rgb(51, 122, 183)", data["totalClientsPerInterval"]);
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WriteEndObject();
- }
- //query response chart
- {
- jsonWriter.WritePropertyName("queryResponseChartData");
- jsonWriter.WriteStartObject();
- List<KeyValuePair<string, int>> stats = data["stats"];
- //labels
- {
- jsonWriter.WritePropertyName("labels");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in stats)
- {
- switch (item.Key)
- {
- case "totalAuthoritative":
- jsonWriter.WriteValue("Authoritative");
- break;
- case "totalRecursive":
- jsonWriter.WriteValue("Recursive");
- break;
- case "totalCached":
- jsonWriter.WriteValue("Cached");
- break;
- case "totalBlocked":
- jsonWriter.WriteValue("Blocked");
- break;
- }
- }
- jsonWriter.WriteEndArray();
- }
- //datasets
- {
- jsonWriter.WritePropertyName("datasets");
- jsonWriter.WriteStartArray();
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in stats)
- {
- switch (item.Key)
- {
- case "totalAuthoritative":
- case "totalRecursive":
- case "totalCached":
- case "totalBlocked":
- jsonWriter.WriteValue(item.Value);
- break;
- }
- }
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("backgroundColor");
- jsonWriter.WriteStartArray();
- jsonWriter.WriteValue("rgba(150, 150, 0, 0.5)");
- jsonWriter.WriteValue("rgba(23, 162, 184, 0.5)");
- jsonWriter.WriteValue("rgba(111, 84, 153, 0.5)");
- jsonWriter.WriteValue("rgba(255, 165, 0, 0.5)");
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WriteEndObject();
- }
- //query type chart
- {
- jsonWriter.WritePropertyName("queryTypeChartData");
- jsonWriter.WriteStartObject();
- List<KeyValuePair<string, int>> queryTypes = data["queryTypes"];
- //labels
- {
- jsonWriter.WritePropertyName("labels");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in queryTypes)
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WriteEndArray();
- }
- //datasets
- {
- jsonWriter.WritePropertyName("datasets");
- jsonWriter.WriteStartArray();
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in queryTypes)
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("backgroundColor");
- jsonWriter.WriteStartArray();
- jsonWriter.WriteValue("rgba(102, 153, 255, 0.5)");
- jsonWriter.WriteValue("rgba(92, 184, 92, 0.5)");
- jsonWriter.WriteValue("rgba(7, 7, 7, 0.5)");
- jsonWriter.WriteValue("rgba(91, 192, 222, 0.5)");
- jsonWriter.WriteValue("rgba(150, 150, 0, 0.5)");
- jsonWriter.WriteValue("rgba(23, 162, 184, 0.5)");
- jsonWriter.WriteValue("rgba(111, 84, 153, 0.5)");
- jsonWriter.WriteValue("rgba(255, 165, 0, 0.5)");
- jsonWriter.WriteValue("rgba(51, 122, 183, 0.5)");
- jsonWriter.WriteValue("rgba(150, 150, 150, 0.5)");
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WriteEndObject();
- }
- //top clients
- {
- List<KeyValuePair<string, int>> topClients = data["topClients"];
- IDictionary<string, string> clientIpMap = await ResolvePtrTopClientsAsync(topClients);
- jsonWriter.WritePropertyName("topClients");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topClients)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- if (clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
- {
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(clientDomain);
- }
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- //top domains
- {
- List<KeyValuePair<string, int>> topDomains = data["topDomains"];
- jsonWriter.WritePropertyName("topDomains");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topDomains)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- //top blocked domains
- {
- List<KeyValuePair<string, int>> topBlockedDomains = data["topBlockedDomains"];
- jsonWriter.WritePropertyName("topBlockedDomains");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topBlockedDomains)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- }
- private static void WriteChartDataSet(JsonTextWriter jsonWriter, string label, string backgroundColor, string borderColor, List<KeyValuePair<string, int>> statsPerInterval)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("label");
- jsonWriter.WriteValue(label);
- jsonWriter.WritePropertyName("backgroundColor");
- jsonWriter.WriteValue(backgroundColor);
- jsonWriter.WritePropertyName("borderColor");
- jsonWriter.WriteValue(borderColor);
- jsonWriter.WritePropertyName("borderWidth");
- jsonWriter.WriteValue(2);
- jsonWriter.WritePropertyName("fill");
- jsonWriter.WriteValue(true);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in statsPerInterval)
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- }
- private async Task GetTopStats(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- strType = "lastHour";
- string strStatsType = request.QueryString["statsType"];
- if (string.IsNullOrEmpty(strStatsType))
- throw new DnsWebServiceException("Parameter 'statsType' missing.");
- string strLimit = request.QueryString["limit"];
- if (string.IsNullOrEmpty(strLimit))
- strLimit = "1000";
- TopStatsType statsType = (TopStatsType)Enum.Parse(typeof(TopStatsType), strStatsType, true);
- int limit = int.Parse(strLimit);
- List<KeyValuePair<string, int>> topStatsData;
- switch (strType)
- {
- case "lastHour":
- topStatsData = _dnsServer.StatsManager.GetLastHourTopStats(statsType, limit);
- break;
- case "lastDay":
- topStatsData = _dnsServer.StatsManager.GetLastDayTopStats(statsType, limit);
- break;
- case "lastWeek":
- topStatsData = _dnsServer.StatsManager.GetLastWeekTopStats(statsType, limit);
- break;
- case "lastMonth":
- topStatsData = _dnsServer.StatsManager.GetLastMonthTopStats(statsType, limit);
- break;
- case "lastYear":
- topStatsData = _dnsServer.StatsManager.GetLastYearTopStats(statsType, limit);
- break;
- case "custom":
- string strStartDate = request.QueryString["start"];
- if (string.IsNullOrEmpty(strStartDate))
- throw new DnsWebServiceException("Parameter 'start' missing.");
- string strEndDate = request.QueryString["end"];
- if (string.IsNullOrEmpty(strEndDate))
- throw new DnsWebServiceException("Parameter 'end' missing.");
- if (!DateTime.TryParseExact(strStartDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime startDate))
- throw new DnsWebServiceException("Invalid start date format.");
- if (!DateTime.TryParseExact(strEndDate, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime endDate))
- throw new DnsWebServiceException("Invalid end date format.");
- if (startDate > endDate)
- throw new DnsWebServiceException("Start date must be less than or equal to end date.");
- if ((Convert.ToInt32((endDate - startDate).TotalDays) + 1) > 7)
- topStatsData = _dnsServer.StatsManager.GetDayWiseTopStats(startDate, endDate, statsType, limit);
- else
- topStatsData = _dnsServer.StatsManager.GetHourWiseTopStats(startDate, endDate, statsType, limit);
- break;
- default:
- throw new DnsWebServiceException("Unknown stats type requested: " + strType);
- }
- switch (statsType)
- {
- case TopStatsType.TopClients:
- {
- IDictionary<string, string> clientIpMap = await ResolvePtrTopClientsAsync(topStatsData);
- jsonWriter.WritePropertyName("topClients");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topStatsData)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- if (clientIpMap.TryGetValue(item.Key, out string clientDomain) && !string.IsNullOrEmpty(clientDomain))
- {
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(clientDomain);
- }
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- break;
- case TopStatsType.TopDomains:
- {
- jsonWriter.WritePropertyName("topDomains");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topStatsData)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- break;
- case TopStatsType.TopBlockedDomains:
- {
- jsonWriter.WritePropertyName("topBlockedDomains");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, int> item in topStatsData)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(item.Key);
- jsonWriter.WritePropertyName("hits");
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- break;
- default:
- throw new NotSupportedException();
- }
- }
- private async Task<IDictionary<string, string>> ResolvePtrTopClientsAsync(List<KeyValuePair<string, int>> topClients)
- {
- IDictionary<string, string> dhcpClientIpMap = _dhcpServer.GetAddressHostNameMap();
- async Task<KeyValuePair<string, string>> ResolvePtrAsync(string ip)
- {
- if (dhcpClientIpMap.TryGetValue(ip, out string dhcpDomain))
- return new KeyValuePair<string, string>(ip, dhcpDomain);
- IPAddress address = IPAddress.Parse(ip);
- if (IPAddress.IsLoopback(address))
- return new KeyValuePair<string, string>(ip, "localhost");
- DnsDatagram ptrResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(address, DnsClass.IN), 500);
- if ((ptrResponse != null) && (ptrResponse.Answer.Count > 0))
- {
- IReadOnlyList<string> ptrDomains = DnsClient.ParseResponsePTR(ptrResponse);
- if (ptrDomains != null)
- return new KeyValuePair<string, string>(ip, ptrDomains[0]);
- }
- return new KeyValuePair<string, string>(ip, null);
- }
- List<Task<KeyValuePair<string, string>>> resolverTasks = new List<Task<KeyValuePair<string, string>>>();
- foreach (KeyValuePair<string, int> item in topClients)
- {
- resolverTasks.Add(ResolvePtrAsync(item.Key));
- }
- Dictionary<string, string> result = new Dictionary<string, string>();
- foreach (Task<KeyValuePair<string, string>> resolverTask in resolverTasks)
- {
- try
- {
- KeyValuePair<string, string> ptrResult = await resolverTask;
- result[ptrResult.Key] = ptrResult.Value;
- }
- catch
- { }
- }
- return result;
- }
- #endregion
- #region cache api
- private void FlushCache(HttpListenerRequest request)
- {
- _dnsServer.CacheZoneManager.Flush();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Cache was flushed.");
- }
- private void ListCachedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string domain = request.QueryString["domain"];
- if (domain == null)
- domain = "";
- string direction = request.QueryString["direction"];
- List<string> subZones;
- List<DnsResourceRecord> records;
- while (true)
- {
- subZones = _dnsServer.CacheZoneManager.ListSubDomains(domain);
- records = _dnsServer.CacheZoneManager.ListAllRecords(domain);
- if (records.Count > 0)
- break;
- if (subZones.Count != 1)
- break;
- if (direction == "up")
- {
- if (domain.Length == 0)
- break;
- int i = domain.IndexOf('.');
- if (i < 0)
- domain = "";
- else
- domain = domain.Substring(i + 1);
- }
- else if (domain.Length == 0)
- {
- domain = subZones[0];
- }
- else
- {
- domain = subZones[0] + "." + domain;
- }
- }
- subZones.Sort();
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(domain);
- jsonWriter.WritePropertyName("zones");
- jsonWriter.WriteStartArray();
- if (domain.Length != 0)
- domain = "." + domain;
- foreach (string subZone in subZones)
- jsonWriter.WriteValue(subZone + domain);
- jsonWriter.WriteEndArray();
- WriteRecordsAsJson(records, jsonWriter, false);
- }
- private void DeleteCachedZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (_dnsServer.CacheZoneManager.DeleteZone(domain))
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Cached zone was deleted: " + domain);
- }
- #endregion
- #region allowed zones api
- private void ListAllowedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string domain = request.QueryString["domain"];
- if (domain == null)
- domain = "";
- string direction = request.QueryString["direction"];
- List<string> subZones;
- IReadOnlyList<DnsResourceRecord> records;
- while (true)
- {
- subZones = _dnsServer.AllowedZoneManager.ListSubDomains(domain);
- records = _dnsServer.AllowedZoneManager.QueryRecords(domain, DnsResourceRecordType.ANY);
- if (records.Count > 0)
- break;
- if (subZones.Count != 1)
- break;
- if (direction == "up")
- {
- if (domain.Length == 0)
- break;
- int i = domain.IndexOf('.');
- if (i < 0)
- domain = "";
- else
- domain = domain.Substring(i + 1);
- }
- else if (domain.Length == 0)
- {
- domain = subZones[0];
- }
- else
- {
- domain = subZones[0] + "." + domain;
- }
- }
- subZones.Sort();
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(domain);
- jsonWriter.WritePropertyName("zones");
- jsonWriter.WriteStartArray();
- if (domain.Length != 0)
- domain = "." + domain;
- foreach (string subZone in subZones)
- jsonWriter.WriteValue(subZone + domain);
- jsonWriter.WriteEndArray();
- WriteRecordsAsJson(new List<DnsResourceRecord>(records), jsonWriter, false);
- }
- private void ImportAllowedZones(HttpListenerRequest request)
- {
- if (!request.ContentType.StartsWith("application/x-www-form-urlencoded"))
- throw new DnsWebServiceException("Invalid content type. Expected application/x-www-form-urlencoded.");
- string formRequest;
- using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
- {
- formRequest = sR.ReadToEnd();
- }
- string[] formParts = formRequest.Split('&');
- foreach (string formPart in formParts)
- {
- if (formPart.StartsWith("allowedZones="))
- {
- string[] allowedZones = formPart.Substring(13).Split(',');
- bool added = false;
- foreach (string allowedZone in allowedZones)
- {
- if (_dnsServer.AllowedZoneManager.AllowZone(allowedZone))
- added = true;
- }
- if (added)
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Total " + allowedZones.Length + " zones were imported into allowed zone successfully.");
- _dnsServer.AllowedZoneManager.SaveZoneFile();
- }
- return;
- }
- }
- throw new DnsWebServiceException("Parameter 'allowedZones' missing.");
- }
- private void ExportAllowedZones(HttpListenerResponse response)
- {
- IReadOnlyList<AuthZoneInfo> zoneInfoList = _dnsServer.AllowedZoneManager.ListZones();
- response.ContentType = "text/plain";
- response.AddHeader("Content-Disposition", "attachment;filename=AllowedZones.txt");
- using (StreamWriter sW = new StreamWriter(new BufferedStream(response.OutputStream)))
- {
- foreach (AuthZoneInfo zoneInfo in zoneInfoList)
- sW.WriteLine(zoneInfo.Name);
- }
- }
- private void DeleteAllowedZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (_dnsServer.AllowedZoneManager.DeleteZone(domain))
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Allowed zone was deleted: " + domain);
- _dnsServer.AllowedZoneManager.SaveZoneFile();
- }
- }
- private void AllowZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (IPAddress.TryParse(domain, out IPAddress ipAddress))
- domain = (new DnsQuestionRecord(ipAddress, DnsClass.IN)).Name;
- if (_dnsServer.AllowedZoneManager.AllowZone(domain))
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Zone was allowed: " + domain);
- _dnsServer.AllowedZoneManager.SaveZoneFile();
- }
- }
- #endregion
- #region blocked zones api
- private void ListBlockedZones(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string domain = request.QueryString["domain"];
- if (domain == null)
- domain = "";
- string direction = request.QueryString["direction"];
- List<string> subZones;
- IReadOnlyList<DnsResourceRecord> records;
- while (true)
- {
- subZones = _dnsServer.BlockedZoneManager.ListSubDomains(domain);
- records = _dnsServer.BlockedZoneManager.QueryRecords(domain, DnsResourceRecordType.ANY);
- if (records.Count > 0)
- break;
- if (subZones.Count != 1)
- break;
- if (direction == "up")
- {
- if (domain.Length == 0)
- break;
- int i = domain.IndexOf('.');
- if (i < 0)
- domain = "";
- else
- domain = domain.Substring(i + 1);
- }
- else if (domain.Length == 0)
- {
- domain = subZones[0];
- }
- else
- {
- domain = subZones[0] + "." + domain;
- }
- }
- subZones.Sort();
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(domain);
- jsonWriter.WritePropertyName("zones");
- jsonWriter.WriteStartArray();
- if (domain.Length != 0)
- domain = "." + domain;
- foreach (string subZone in subZones)
- jsonWriter.WriteValue(subZone + domain);
- jsonWriter.WriteEndArray();
- WriteRecordsAsJson(new List<DnsResourceRecord>(records), jsonWriter, false);
- }
- private void ImportBlockedZones(HttpListenerRequest request)
- {
- if (!request.ContentType.StartsWith("application/x-www-form-urlencoded"))
- throw new DnsWebServiceException("Invalid content type. Expected application/x-www-form-urlencoded.");
- string formRequest;
- using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
- {
- formRequest = sR.ReadToEnd();
- }
- string[] formParts = formRequest.Split('&');
- foreach (string formPart in formParts)
- {
- if (formPart.StartsWith("blockedZones="))
- {
- string[] blockedZones = formPart.Substring(13).Split(',');
- bool added = false;
- foreach (string blockedZone in blockedZones)
- {
- if (_dnsServer.BlockedZoneManager.BlockZone(blockedZone))
- added = true;
- }
- if (added)
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Total " + blockedZones.Length + " zones were imported into blocked zone successfully.");
- _dnsServer.BlockedZoneManager.SaveZoneFile();
- }
- return;
- }
- }
- throw new DnsWebServiceException("Parameter 'blockedZones' missing.");
- }
- private void ExportBlockedZones(HttpListenerResponse response)
- {
- IReadOnlyList<AuthZoneInfo> zoneInfoList = _dnsServer.BlockedZoneManager.ListZones();
- response.ContentType = "text/plain";
- response.AddHeader("Content-Disposition", "attachment;filename=BlockedZones.txt");
- using (StreamWriter sW = new StreamWriter(new BufferedStream(response.OutputStream)))
- {
- foreach (AuthZoneInfo zoneInfo in zoneInfoList)
- sW.WriteLine(zoneInfo.Name);
- }
- }
- private void DeleteBlockedZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (_dnsServer.BlockedZoneManager.DeleteZone(domain))
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Blocked zone was deleted: " + domain);
- _dnsServer.BlockedZoneManager.SaveZoneFile();
- }
- }
- private void BlockZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (IPAddress.TryParse(domain, out IPAddress ipAddress))
- domain = (new DnsQuestionRecord(ipAddress, DnsClass.IN)).Name;
- if (_dnsServer.BlockedZoneManager.BlockZone(domain))
- {
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Domain was added to blocked zone: " + domain);
- _dnsServer.BlockedZoneManager.SaveZoneFile();
- }
- }
- #endregion
- #region zones api
- private void ListZones(JsonTextWriter jsonWriter)
- {
- List<AuthZoneInfo> zones = _dnsServer.AuthZoneManager.ListZones();
- zones.Sort();
- jsonWriter.WritePropertyName("zones");
- jsonWriter.WriteStartArray();
- foreach (AuthZoneInfo zone in zones)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(zone.Name);
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(zone.Type.ToString());
- switch (zone.Type)
- {
- case AuthZoneType.Primary:
- jsonWriter.WritePropertyName("internal");
- jsonWriter.WriteValue(zone.Internal);
- break;
- case AuthZoneType.Secondary:
- case AuthZoneType.Stub:
- jsonWriter.WritePropertyName("expiry");
- jsonWriter.WriteValue(zone.Expiry.ToLocalTime().ToString("dd MMM yyyy HH:mm:ss"));
- jsonWriter.WritePropertyName("isExpired");
- jsonWriter.WriteValue(zone.IsExpired);
- break;
- }
- jsonWriter.WritePropertyName("disabled");
- jsonWriter.WriteValue(zone.Disabled);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- private async Task CreateZoneAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.Contains("*"))
- throw new DnsWebServiceException("Domain name for a zone cannot contain wildcard character.");
- if (IPAddress.TryParse(domain, out IPAddress ipAddress))
- {
- domain = new DnsQuestionRecord(ipAddress, DnsClass.IN).Name.ToLower();
- }
- else if (domain.Contains("/"))
- {
- string[] parts = domain.Split('/');
- if ((parts.Length == 2) && IPAddress.TryParse(parts[0], out ipAddress) && int.TryParse(parts[1], out int subnetMaskWidth))
- domain = Zone.GetReverseZone(ipAddress, subnetMaskWidth);
- }
- else if (domain.EndsWith("."))
- {
- domain = domain.Substring(0, domain.Length - 1);
- }
- AuthZoneType type = AuthZoneType.Primary;
- string strType = request.QueryString["type"];
- if (!string.IsNullOrEmpty(strType))
- type = (AuthZoneType)Enum.Parse(typeof(AuthZoneType), strType, true);
- switch (type)
- {
- case AuthZoneType.Primary:
- if (_dnsServer.AuthZoneManager.CreatePrimaryZone(domain, _dnsServer.ServerDomain, false) == null)
- throw new DnsWebServiceException("Zone already exists: " + domain);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Authoritative primary zone was created: " + domain);
- _dnsServer.AuthZoneManager.SaveZoneFile(domain);
- break;
- case AuthZoneType.Secondary:
- {
- string strPrimaryNameServerAddresses = request.QueryString["primaryNameServerAddresses"];
- if (string.IsNullOrEmpty(strPrimaryNameServerAddresses))
- strPrimaryNameServerAddresses = null;
- if (await _dnsServer.AuthZoneManager.CreateSecondaryZoneAsync(domain, strPrimaryNameServerAddresses) == null)
- throw new DnsWebServiceException("Zone already exists: " + domain);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Authoritative secondary zone was created: " + domain);
- _dnsServer.AuthZoneManager.SaveZoneFile(domain);
- }
- break;
- case AuthZoneType.Stub:
- {
- string strPrimaryNameServerAddresses = request.QueryString["primaryNameServerAddresses"];
- if (string.IsNullOrEmpty(strPrimaryNameServerAddresses))
- strPrimaryNameServerAddresses = null;
- if (await _dnsServer.AuthZoneManager.CreateStubZoneAsync(domain, strPrimaryNameServerAddresses) == null)
- throw new DnsWebServiceException("Zone already exists: " + domain);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Stub zone was created: " + domain);
- _dnsServer.AuthZoneManager.SaveZoneFile(domain);
- }
- break;
- case AuthZoneType.Forwarder:
- {
- DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
- string strForwarderProtocol = request.QueryString["protocol"];
- if (!string.IsNullOrEmpty(strForwarderProtocol))
- forwarderProtocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strForwarderProtocol, true);
- string strForwarder = request.QueryString["forwarder"];
- if (string.IsNullOrEmpty(strForwarder))
- throw new DnsWebServiceException("Parameter 'forwarder' missing.");
- if (_dnsServer.AuthZoneManager.CreateForwarderZone(domain, forwarderProtocol, strForwarder) == null)
- throw new DnsWebServiceException("Zone already exists: " + domain);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Forwarder zone was created: " + domain);
- _dnsServer.AuthZoneManager.SaveZoneFile(domain);
- }
- break;
- default:
- throw new NotSupportedException("Zone type not supported.");
- }
- //delete cache for this zone to allow rebuilding cache data as needed by stub or forwarder zones
- _dnsServer.CacheZoneManager.DeleteZone(domain);
- jsonWriter.WritePropertyName("domain");
- jsonWriter.WriteValue(string.IsNullOrEmpty(domain) ? "." : domain);
- }
- private void DeleteZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- if (!_dnsServer.AuthZoneManager.DeleteZone(domain))
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was deleted: " + domain);
- _dnsServer.AuthZoneManager.DeleteZoneFile(zoneInfo.Name);
- }
- private void EnableZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- zoneInfo.Disabled = false;
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was enabled: " + zoneInfo.Name);
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- //delete cache for this zone to allow rebuilding cache data as needed by stub or forwarder zones
- _dnsServer.CacheZoneManager.DeleteZone(zoneInfo.Name);
- }
- private void DisableZone(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- zoneInfo.Disabled = true;
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] " + zoneInfo.Type.ToString() + " zone was disabled: " + zoneInfo.Name);
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- private void AddRecord(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- throw new DnsWebServiceException("Parameter 'type' missing.");
- DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
- string value = request.QueryString["value"];
- if (string.IsNullOrEmpty(value))
- throw new DnsWebServiceException("Parameter 'value' missing.");
- uint ttl;
- string strTtl = request.QueryString["ttl"];
- if (string.IsNullOrEmpty(strTtl))
- ttl = 3600;
- else
- ttl = uint.Parse(strTtl);
- bool overwrite = false;
- string strOverwrite = request.QueryString["overwrite"];
- if (!string.IsNullOrEmpty(strOverwrite))
- overwrite = bool.Parse(strOverwrite);
- switch (type)
- {
- case DnsResourceRecordType.A:
- case DnsResourceRecordType.AAAA:
- {
- IPAddress ipAddress = IPAddress.Parse(value);
- bool ptr = false;
- string strPtr = request.QueryString["ptr"];
- if (!string.IsNullOrEmpty(strPtr))
- ptr = bool.Parse(strPtr);
- if (ptr)
- {
- string ptrDomain = Zone.GetReverseZone(ipAddress, type == DnsResourceRecordType.A ? 32 : 128);
- AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
- if (reverseZoneInfo == null)
- {
- bool createPtrZone = false;
- string strCreatePtrZone = request.QueryString["createPtrZone"];
- if (!string.IsNullOrEmpty(strCreatePtrZone))
- createPtrZone = bool.Parse(strCreatePtrZone);
- if (!createPtrZone)
- throw new DnsServerException("No reverse zone available to add PTR record.");
- string ptrZone = Zone.GetReverseZone(ipAddress, type == DnsResourceRecordType.A ? 24 : 64);
- reverseZoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(ptrZone, _dnsServer.ServerDomain, false);
- if (reverseZoneInfo == null)
- throw new DnsServerException("Failed to create reverse zone to add PTR record: " + ptrZone);
- }
- if (reverseZoneInfo.Internal)
- throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is an internal zone.");
- if (reverseZoneInfo.Type != AuthZoneType.Primary)
- throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is not a primary zone.");
- _dnsServer.AuthZoneManager.SetRecords(ptrDomain, DnsResourceRecordType.PTR, ttl, new DnsPTRRecord[] { new DnsPTRRecord(domain) });
- _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
- }
- DnsResourceRecord newRecord;
- if (type == DnsResourceRecordType.A)
- newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsARecord(ipAddress));
- else
- newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsAAAARecord(ipAddress));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.MX:
- {
- string preference = request.QueryString["preference"];
- if (string.IsNullOrEmpty(preference))
- throw new DnsWebServiceException("Parameter 'preference' missing.");
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsMXRecord(ushort.Parse(preference), value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.TXT:
- {
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsTXTRecord(value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.NS:
- {
- string glueAddresses = request.QueryString["glue"];
- if (string.IsNullOrEmpty(glueAddresses))
- glueAddresses = null;
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsNSRecord(value));
- if (glueAddresses != null)
- newRecord.SetGlueRecords(glueAddresses);
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.PTR:
- {
- if (!overwrite)
- {
- IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
- if (existingRecords.Count > 0)
- throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
- }
- _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsPTRRecord(value) });
- }
- break;
- case DnsResourceRecordType.CNAME:
- {
- if (!overwrite)
- {
- IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
- if (existingRecords.Count > 0)
- throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
- }
- _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsCNAMERecord(value) });
- }
- break;
- case DnsResourceRecordType.SRV:
- {
- string priority = request.QueryString["priority"];
- if (string.IsNullOrEmpty(priority))
- throw new DnsWebServiceException("Parameter 'priority' missing.");
- string weight = request.QueryString["weight"];
- if (string.IsNullOrEmpty(weight))
- throw new DnsWebServiceException("Parameter 'weight' missing.");
- string port = request.QueryString["port"];
- if (string.IsNullOrEmpty(port))
- throw new DnsWebServiceException("Parameter 'port' missing.");
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsSRVRecord(ushort.Parse(priority), ushort.Parse(weight), ushort.Parse(port), value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.CAA:
- {
- string flags = request.QueryString["flags"];
- if (string.IsNullOrEmpty(flags))
- throw new DnsWebServiceException("Parameter 'flags' missing.");
- string tag = request.QueryString["tag"];
- if (string.IsNullOrEmpty(tag))
- throw new DnsWebServiceException("Parameter 'tag' missing.");
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsCAARecord(byte.Parse(flags), tag, value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.ANAME:
- {
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, ttl, new DnsANAMERecord(value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.FWD:
- {
- string protocol = request.QueryString["protocol"];
- if (string.IsNullOrEmpty(protocol))
- protocol = "Udp";
- DnsResourceRecord newRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsForwarderRecord((DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), protocol, true), value));
- if (overwrite)
- _dnsServer.AuthZoneManager.SetRecord(newRecord);
- else
- _dnsServer.AuthZoneManager.AddRecord(newRecord);
- }
- break;
- case DnsResourceRecordType.APP:
- {
- string classPath = request.QueryString["classPath"];
- if (string.IsNullOrEmpty(classPath))
- throw new DnsWebServiceException("Parameter 'classPath' missing.");
- string recordData = request.QueryString["recordData"];
- if (string.IsNullOrEmpty(recordData))
- recordData = "";
- if (!overwrite)
- {
- IReadOnlyList<DnsResourceRecord> existingRecords = _dnsServer.AuthZoneManager.GetRecords(domain, type);
- if (existingRecords.Count > 0)
- throw new DnsWebServiceException("Record already exists. Use overwrite option if you wish to overwrite existing records.");
- }
- _dnsServer.AuthZoneManager.SetRecords(domain, type, ttl, new DnsResourceRecordData[] { new DnsApplicationRecord(value, classPath, recordData) });
- }
- break;
- default:
- throw new DnsWebServiceException("Type not supported for AddRecords().");
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] New record was added to authoritative zone {domain: " + domain + "; type: " + type + "; value: " + value + "; ttl: " + ttl + ";}");
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- private void GetRecords(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- jsonWriter.WritePropertyName("zone");
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(zoneInfo.Name);
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(zoneInfo.Type.ToString());
- switch (zoneInfo.Type)
- {
- case AuthZoneType.Primary:
- jsonWriter.WritePropertyName("internal");
- jsonWriter.WriteValue(zoneInfo.Internal);
- break;
- case AuthZoneType.Secondary:
- case AuthZoneType.Stub:
- jsonWriter.WritePropertyName("expiry");
- jsonWriter.WriteValue(zoneInfo.Expiry.ToLocalTime().ToString("dd MMM yyyy HH:mm:ss"));
- jsonWriter.WritePropertyName("isExpired");
- jsonWriter.WriteValue(zoneInfo.IsExpired);
- break;
- }
- jsonWriter.WritePropertyName("disabled");
- jsonWriter.WriteValue(zoneInfo.Disabled);
- jsonWriter.WriteEndObject();
- List<DnsResourceRecord> records = _dnsServer.AuthZoneManager.ListAllRecords(domain);
- WriteRecordsAsJson(records, jsonWriter, true);
- }
- private static void WriteRecordsAsJson(List<DnsResourceRecord> records, JsonTextWriter jsonWriter, bool authoritativeZoneRecords)
- {
- if (records == null)
- {
- jsonWriter.WritePropertyName("records");
- jsonWriter.WriteStartArray();
- jsonWriter.WriteEndArray();
- return;
- }
- records.Sort();
- Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> groupedByDomainRecords = DnsResourceRecord.GroupRecords(records);
- jsonWriter.WritePropertyName("records");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> groupedByTypeRecords in groupedByDomainRecords)
- {
- foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> groupedRecords in groupedByTypeRecords.Value)
- {
- foreach (DnsResourceRecord record in groupedRecords.Value)
- {
- jsonWriter.WriteStartObject();
- if (authoritativeZoneRecords)
- {
- jsonWriter.WritePropertyName("disabled");
- jsonWriter.WriteValue(record.IsDisabled());
- }
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(record.Name);
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(record.Type.ToString());
- jsonWriter.WritePropertyName("ttl");
- if (authoritativeZoneRecords)
- jsonWriter.WriteValue(record.TtlValue);
- else
- jsonWriter.WriteValue(record.TTL);
- jsonWriter.WritePropertyName("rData");
- jsonWriter.WriteStartObject();
- switch (record.Type)
- {
- case DnsResourceRecordType.A:
- {
- DnsARecord rdata = record.RDATA as DnsARecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.IPAddress);
- }
- }
- break;
- case DnsResourceRecordType.AAAA:
- {
- DnsAAAARecord rdata = record.RDATA as DnsAAAARecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.IPAddress);
- }
- }
- break;
- case DnsResourceRecordType.SOA:
- {
- DnsSOARecord rdata = record.RDATA as DnsSOARecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("primaryNameServer");
- jsonWriter.WriteValue(rdata.PrimaryNameServer);
- jsonWriter.WritePropertyName("responsiblePerson");
- jsonWriter.WriteValue(rdata.ResponsiblePerson);
- jsonWriter.WritePropertyName("serial");
- jsonWriter.WriteValue(rdata.Serial);
- jsonWriter.WritePropertyName("refresh");
- jsonWriter.WriteValue(rdata.Refresh);
- jsonWriter.WritePropertyName("retry");
- jsonWriter.WriteValue(rdata.Retry);
- jsonWriter.WritePropertyName("expire");
- jsonWriter.WriteValue(rdata.Expire);
- jsonWriter.WritePropertyName("minimum");
- jsonWriter.WriteValue(rdata.Minimum);
- }
- IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
- if (glueRecords.Count > 0)
- {
- string primaryAddresses = null;
- foreach (DnsResourceRecord glueRecord in glueRecords)
- {
- if (primaryAddresses == null)
- primaryAddresses = glueRecord.RDATA.ToString();
- else
- primaryAddresses = primaryAddresses + ", " + glueRecord.RDATA.ToString();
- }
- jsonWriter.WritePropertyName("primaryAddresses");
- jsonWriter.WriteValue(primaryAddresses);
- }
- }
- break;
- case DnsResourceRecordType.PTR:
- {
- DnsPTRRecord rdata = record.RDATA as DnsPTRRecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Domain);
- }
- }
- break;
- case DnsResourceRecordType.MX:
- {
- DnsMXRecord rdata = record.RDATA as DnsMXRecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("preference");
- jsonWriter.WriteValue(rdata.Preference);
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Exchange);
- IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
- if (glueRecords.Count > 0)
- {
- string glue = null;
- foreach (DnsResourceRecord glueRecord in glueRecords)
- {
- if (glue == null)
- glue = glueRecord.RDATA.ToString();
- else
- glue = glue + ", " + glueRecord.RDATA.ToString();
- }
- jsonWriter.WritePropertyName("glue");
- jsonWriter.WriteValue(glue);
- }
- }
- }
- break;
- case DnsResourceRecordType.TXT:
- {
- DnsTXTRecord rdata = record.RDATA as DnsTXTRecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Text);
- }
- }
- break;
- case DnsResourceRecordType.NS:
- {
- DnsNSRecord rdata = record.RDATA as DnsNSRecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.NameServer);
- IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
- if (glueRecords.Count > 0)
- {
- string glue = null;
- foreach (DnsResourceRecord glueRecord in glueRecords)
- {
- if (glue == null)
- glue = glueRecord.RDATA.ToString();
- else
- glue = glue + ", " + glueRecord.RDATA.ToString();
- }
- jsonWriter.WritePropertyName("glue");
- jsonWriter.WriteValue(glue);
- }
- }
- }
- break;
- case DnsResourceRecordType.CNAME:
- {
- DnsCNAMERecord rdata = record.RDATA as DnsCNAMERecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Domain);
- }
- }
- break;
- case DnsResourceRecordType.SRV:
- {
- DnsSRVRecord rdata = record.RDATA as DnsSRVRecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("priority");
- jsonWriter.WriteValue(rdata.Priority);
- jsonWriter.WritePropertyName("weight");
- jsonWriter.WriteValue(rdata.Weight);
- jsonWriter.WritePropertyName("port");
- jsonWriter.WriteValue(rdata.Port);
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Target);
- IReadOnlyList<DnsResourceRecord> glueRecords = record.GetGlueRecords();
- if (glueRecords.Count > 0)
- {
- string glue = null;
- foreach (DnsResourceRecord glueRecord in glueRecords)
- {
- if (glue == null)
- glue = glueRecord.RDATA.ToString();
- else
- glue = glue + ", " + glueRecord.RDATA.ToString();
- }
- jsonWriter.WritePropertyName("glue");
- jsonWriter.WriteValue(glue);
- }
- }
- }
- break;
- case DnsResourceRecordType.CAA:
- {
- DnsCAARecord rdata = record.RDATA as DnsCAARecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("flags");
- jsonWriter.WriteValue(rdata.Flags);
- jsonWriter.WritePropertyName("tag");
- jsonWriter.WriteValue(rdata.Tag);
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Value);
- }
- }
- break;
- case DnsResourceRecordType.ANAME:
- {
- DnsANAMERecord rdata = record.RDATA as DnsANAMERecord;
- if (rdata == null)
- {
- jsonWriter.WritePropertyName("dataType");
- jsonWriter.WriteValue(record.RDATA.GetType().Name);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(record.RDATA.ToString());
- }
- else
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Domain);
- }
- }
- break;
- case DnsResourceRecordType.FWD:
- {
- DnsForwarderRecord rdata = record.RDATA as DnsForwarderRecord;
- if (rdata != null)
- {
- jsonWriter.WritePropertyName("protocol");
- jsonWriter.WriteValue(rdata.Protocol.ToString());
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.Forwarder);
- }
- }
- break;
- case DnsResourceRecordType.APP:
- {
- DnsApplicationRecord rdata = record.RDATA as DnsApplicationRecord;
- if (rdata != null)
- {
- jsonWriter.WritePropertyName("value");
- jsonWriter.WriteValue(rdata.AppName);
- jsonWriter.WritePropertyName("classPath");
- jsonWriter.WriteValue(rdata.ClassPath);
- jsonWriter.WritePropertyName("data");
- jsonWriter.WriteValue(rdata.Data);
- }
- }
- break;
- default:
- {
- jsonWriter.WritePropertyName("value");
- using (MemoryStream mS = new MemoryStream())
- {
- record.RDATA.WriteTo(mS, new List<DnsDomainOffset>());
- jsonWriter.WriteValue(Convert.ToBase64String(mS.ToArray()));
- }
- }
- break;
- }
- jsonWriter.WriteEndObject();
- jsonWriter.WriteEndObject();
- }
- }
- }
- jsonWriter.WriteEndArray();
- }
- private void DeleteRecord(HttpListenerRequest request)
- {
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- throw new DnsWebServiceException("Parameter 'type' missing.");
- DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
- string value = request.QueryString["value"];
- if (string.IsNullOrEmpty(value))
- throw new DnsWebServiceException("Parameter 'value' missing.");
- switch (type)
- {
- case DnsResourceRecordType.A:
- case DnsResourceRecordType.AAAA:
- {
- IPAddress address = IPAddress.Parse(value);
- if (type == DnsResourceRecordType.A)
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsARecord(address));
- else
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsAAAARecord(address));
- string ptrDomain = Zone.GetReverseZone(address, type == DnsResourceRecordType.A ? 32 : 128);
- AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
- if ((reverseZoneInfo != null) && !reverseZoneInfo.Internal && (reverseZoneInfo.Type == AuthZoneType.Primary))
- {
- IReadOnlyList<DnsResourceRecord> ptrRecords = _dnsServer.AuthZoneManager.QueryRecords(ptrDomain, DnsResourceRecordType.PTR);
- if (ptrRecords.Count > 0)
- {
- foreach (DnsResourceRecord ptrRecord in ptrRecords)
- {
- if ((ptrRecord.RDATA as DnsPTRRecord).Domain.Equals(domain, StringComparison.OrdinalIgnoreCase))
- {
- //delete PTR record and save reverse zone
- _dnsServer.AuthZoneManager.DeleteRecord(ptrDomain, DnsResourceRecordType.PTR, ptrRecord.RDATA);
- _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
- break;
- }
- }
- }
- }
- }
- break;
- case DnsResourceRecordType.MX:
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsMXRecord(0, value));
- break;
- case DnsResourceRecordType.TXT:
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsTXTRecord(value));
- break;
- case DnsResourceRecordType.NS:
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsNSRecord(value));
- break;
- case DnsResourceRecordType.ANAME:
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsANAMERecord(value));
- break;
- case DnsResourceRecordType.CNAME:
- case DnsResourceRecordType.PTR:
- case DnsResourceRecordType.APP:
- _dnsServer.AuthZoneManager.DeleteRecords(domain, type);
- break;
- case DnsResourceRecordType.SRV:
- {
- string port = request.QueryString["port"];
- if (string.IsNullOrEmpty(port))
- throw new DnsWebServiceException("Parameter 'port' missing.");
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsSRVRecord(0, 0, ushort.Parse(port), value));
- }
- break;
- case DnsResourceRecordType.CAA:
- {
- string flags = request.QueryString["flags"];
- if (string.IsNullOrEmpty(flags))
- throw new DnsWebServiceException("Parameter 'flags' missing.");
- string tag = request.QueryString["tag"];
- if (string.IsNullOrEmpty(tag))
- throw new DnsWebServiceException("Parameter 'tag' missing.");
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsCAARecord(byte.Parse(flags), tag, value));
- }
- break;
- case DnsResourceRecordType.FWD:
- {
- string strProtocol = request.QueryString["protocol"];
- if (string.IsNullOrEmpty(strProtocol))
- strProtocol = "Udp";
- _dnsServer.AuthZoneManager.DeleteRecord(domain, type, new DnsForwarderRecord((DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true), value));
- }
- break;
- default:
- throw new DnsWebServiceException("Type not supported for DeleteRecord().");
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Record was deleted from authoritative zone {domain: " + domain + "; type: " + type + "; value: " + value + ";}");
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- private void UpdateRecord(HttpListenerRequest request)
- {
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- throw new DnsWebServiceException("Parameter 'type' missing.");
- DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- throw new DnsWebServiceException("Zone '" + domain + "' was not found.");
- if (zoneInfo.Internal)
- throw new DnsWebServiceException("Access was denied to manage internal DNS Server zone.");
- string newDomain = request.QueryString["newDomain"];
- if (string.IsNullOrEmpty(newDomain))
- newDomain = domain;
- if (newDomain.EndsWith("."))
- newDomain = newDomain.Substring(0, newDomain.Length - 1);
- uint ttl;
- string strTtl = request.QueryString["ttl"];
- if (string.IsNullOrEmpty(strTtl))
- ttl = 3600;
- else
- ttl = uint.Parse(strTtl);
- string value = request.QueryString["value"];
- string newValue = request.QueryString["newValue"];
- if (string.IsNullOrEmpty(newValue))
- newValue = value;
- bool disable = false;
- string strDisable = request.QueryString["disable"];
- if (!string.IsNullOrEmpty(strDisable))
- disable = bool.Parse(strDisable);
- switch (type)
- {
- case DnsResourceRecordType.A:
- case DnsResourceRecordType.AAAA:
- {
- IPAddress oldIpAddress = IPAddress.Parse(value);
- IPAddress newIpAddress = IPAddress.Parse(newValue);
- bool ptr = false;
- string strPtr = request.QueryString["ptr"];
- if (!string.IsNullOrEmpty(strPtr))
- ptr = bool.Parse(strPtr);
- if (ptr)
- {
- string ptrDomain = Zone.GetReverseZone(newIpAddress, type == DnsResourceRecordType.A ? 32 : 128);
- AuthZoneInfo reverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(ptrDomain);
- if (reverseZoneInfo == null)
- {
- bool createPtrZone = false;
- string strCreatePtrZone = request.QueryString["createPtrZone"];
- if (!string.IsNullOrEmpty(strCreatePtrZone))
- createPtrZone = bool.Parse(strCreatePtrZone);
- if (!createPtrZone)
- throw new DnsServerException("No reverse zone available to add PTR record.");
- string ptrZone = Zone.GetReverseZone(newIpAddress, type == DnsResourceRecordType.A ? 24 : 64);
- reverseZoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(ptrZone, _dnsServer.ServerDomain, false);
- if (reverseZoneInfo == null)
- throw new DnsServerException("Failed to create reverse zone to add PTR record: " + ptrZone);
- }
- if (reverseZoneInfo.Internal)
- throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is an internal zone.");
- if (reverseZoneInfo.Type != AuthZoneType.Primary)
- throw new DnsServerException("Reverse zone '" + reverseZoneInfo.Name + "' is not a primary zone.");
- string oldPtrDomain = Zone.GetReverseZone(oldIpAddress, type == DnsResourceRecordType.A ? 32 : 128);
- AuthZoneInfo oldReverseZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(oldPtrDomain);
- if ((oldReverseZoneInfo != null) && !oldReverseZoneInfo.Internal && (oldReverseZoneInfo.Type == AuthZoneType.Primary))
- {
- //delete old PTR record if any and save old reverse zone
- _dnsServer.AuthZoneManager.DeleteRecords(oldPtrDomain, DnsResourceRecordType.PTR);
- _dnsServer.AuthZoneManager.SaveZoneFile(oldReverseZoneInfo.Name);
- }
- //add new PTR record and save reverse zone
- _dnsServer.AuthZoneManager.SetRecords(ptrDomain, DnsResourceRecordType.PTR, ttl, new DnsPTRRecord[] { new DnsPTRRecord(domain) });
- _dnsServer.AuthZoneManager.SaveZoneFile(reverseZoneInfo.Name);
- }
- DnsResourceRecord oldRecord;
- DnsResourceRecord newRecord;
- if (type == DnsResourceRecordType.A)
- {
- oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsARecord(oldIpAddress));
- newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsARecord(newIpAddress));
- }
- else
- {
- oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsAAAARecord(oldIpAddress));
- newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsAAAARecord(newIpAddress));
- }
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.MX:
- {
- string preference = request.QueryString["preference"];
- if (string.IsNullOrEmpty(preference))
- preference = "1";
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsMXRecord(0, value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsMXRecord(ushort.Parse(preference), newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.TXT:
- {
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsTXTRecord(value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsTXTRecord(newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.NS:
- {
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsNSRecord(value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsNSRecord(newValue));
- if (disable)
- newRecord.Disable();
- string glueAddresses = request.QueryString["glue"];
- if (!string.IsNullOrEmpty(glueAddresses))
- newRecord.SetGlueRecords(glueAddresses);
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.SOA:
- {
- string primaryNameServer = request.QueryString["primaryNameServer"];
- if (string.IsNullOrEmpty(primaryNameServer))
- throw new DnsWebServiceException("Parameter 'primaryNameServer' missing.");
- string responsiblePerson = request.QueryString["responsiblePerson"];
- if (string.IsNullOrEmpty(responsiblePerson))
- throw new DnsWebServiceException("Parameter 'responsiblePerson' missing.");
- string serial = request.QueryString["serial"];
- if (string.IsNullOrEmpty(serial))
- throw new DnsWebServiceException("Parameter 'serial' missing.");
- string refresh = request.QueryString["refresh"];
- if (string.IsNullOrEmpty(refresh))
- throw new DnsWebServiceException("Parameter 'refresh' missing.");
- string retry = request.QueryString["retry"];
- if (string.IsNullOrEmpty(retry))
- throw new DnsWebServiceException("Parameter 'retry' missing.");
- string expire = request.QueryString["expire"];
- if (string.IsNullOrEmpty(expire))
- throw new DnsWebServiceException("Parameter 'expire' missing.");
- string minimum = request.QueryString["minimum"];
- if (string.IsNullOrEmpty(minimum))
- throw new DnsWebServiceException("Parameter 'minimum' missing.");
- 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)));
- string primaryAddresses = request.QueryString["primaryAddresses"];
- if (!string.IsNullOrEmpty(primaryAddresses))
- soaRecord.SetGlueRecords(primaryAddresses);
- _dnsServer.AuthZoneManager.SetRecord(soaRecord);
- }
- break;
- case DnsResourceRecordType.PTR:
- {
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsPTRRecord(value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsPTRRecord(newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.CNAME:
- {
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsCNAMERecord(value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsCNAMERecord(newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.SRV:
- {
- string port = request.QueryString["port"];
- if (string.IsNullOrEmpty(port))
- throw new DnsWebServiceException("Parameter 'port' missing.");
- string priority = request.QueryString["priority"];
- if (string.IsNullOrEmpty(priority))
- throw new DnsWebServiceException("Parameter 'priority' missing.");
- string weight = request.QueryString["weight"];
- if (string.IsNullOrEmpty(weight))
- throw new DnsWebServiceException("Parameter 'weight' missing.");
- string newPort = request.QueryString["newPort"];
- if (string.IsNullOrEmpty(newPort))
- newPort = port;
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsSRVRecord(0, 0, ushort.Parse(port), value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsSRVRecord(ushort.Parse(priority), ushort.Parse(weight), ushort.Parse(newPort), newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.CAA:
- {
- string flags = request.QueryString["flags"];
- if (string.IsNullOrEmpty(flags))
- throw new DnsWebServiceException("Parameter 'flags' missing.");
- string tag = request.QueryString["tag"];
- if (string.IsNullOrEmpty(tag))
- throw new DnsWebServiceException("Parameter 'tag' missing.");
- string newFlags = request.QueryString["newFlags"];
- if (string.IsNullOrEmpty(newFlags))
- newFlags = flags;
- string newTag = request.QueryString["newTag"];
- if (string.IsNullOrEmpty(newTag))
- newTag = tag;
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsCAARecord(byte.Parse(flags), tag, value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsCAARecord(byte.Parse(newFlags), newTag, newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.ANAME:
- {
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsANAMERecord(value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsANAMERecord(newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.FWD:
- {
- string strProtocol = request.QueryString["protocol"];
- if (string.IsNullOrEmpty(strProtocol))
- strProtocol = "Udp";
- DnsTransportProtocol protocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true);
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsForwarderRecord(protocol, value));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsForwarderRecord(protocol, newValue));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- case DnsResourceRecordType.APP:
- {
- string classPath = request.QueryString["classPath"];
- if (string.IsNullOrEmpty(classPath))
- throw new DnsWebServiceException("Parameter 'classPath' missing.");
- string recordData = request.QueryString["recordData"];
- if (string.IsNullOrEmpty(recordData))
- recordData = "";
- DnsResourceRecord oldRecord = new DnsResourceRecord(domain, type, DnsClass.IN, 0, new DnsApplicationRecord(value, classPath, recordData));
- DnsResourceRecord newRecord = new DnsResourceRecord(newDomain, type, DnsClass.IN, ttl, new DnsApplicationRecord(newValue, classPath, recordData));
- if (disable)
- newRecord.Disable();
- _dnsServer.AuthZoneManager.UpdateRecord(oldRecord, newRecord);
- }
- break;
- default:
- throw new DnsWebServiceException("Type not supported for UpdateRecords().");
- }
- _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 + ";}");
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- #endregion
- #region dns apps api
- string _storeAppsJsonData;
- DateTime _storeAppsJsonDataUpdatedOn;
- const int STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS = 300;
- private async Task<string> GetStoreAppsJsonData()
- {
- if ((_storeAppsJsonData == null) || (DateTime.UtcNow > _storeAppsJsonDataUpdatedOn.AddSeconds(STORE_APPS_JSON_DATA_CACHE_TIME_SECONDS)))
- {
- SocketsHttpHandler handler = new SocketsHttpHandler();
- handler.Proxy = _dnsServer.Proxy;
- handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
- using (HttpClient http = new HttpClient(handler))
- {
- _storeAppsJsonData = await http.GetStringAsync(_appStoreUri);
- _storeAppsJsonDataUpdatedOn = DateTime.UtcNow;
- }
- }
- return _storeAppsJsonData;
- }
- private async Task ListInstalledAppsAsync(JsonTextWriter jsonWriter)
- {
- List<string> apps = new List<string>(_dnsServer.DnsApplicationManager.Applications.Keys);
- apps.Sort();
- dynamic jsonStoreAppsArray = null;
- if (apps.Count > 0)
- {
- try
- {
- string storeAppsJsonData = await GetStoreAppsJsonData().WithTimeout(5000);
- jsonStoreAppsArray = JsonConvert.DeserializeObject(storeAppsJsonData);
- }
- catch
- { }
- }
- jsonWriter.WritePropertyName("apps");
- jsonWriter.WriteStartArray();
- foreach (string app in apps)
- {
- if (_dnsServer.DnsApplicationManager.Applications.TryGetValue(app, out DnsApplication application))
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(application.AppName);
- jsonWriter.WritePropertyName("version");
- jsonWriter.WriteValue(GetCleanVersion(application.Version));
- if (jsonStoreAppsArray != null)
- {
- foreach (dynamic jsonStoreApp in jsonStoreAppsArray)
- {
- string name = jsonStoreApp.name.Value;
- if (name.Equals(application.AppName))
- {
- string version = jsonStoreApp.version.Value;
- string url = jsonStoreApp.url.Value;
- jsonWriter.WritePropertyName("updateVersion");
- jsonWriter.WriteValue(version);
- jsonWriter.WritePropertyName("updateUrl");
- jsonWriter.WriteValue(url);
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(new Version(version) > application.Version);
- break;
- }
- }
- }
- jsonWriter.WritePropertyName("details");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, IDnsApplicationRequestHandler> handler in application.DnsRequestHandlers)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("classPath");
- jsonWriter.WriteValue(handler.Key);
- jsonWriter.WritePropertyName("description");
- jsonWriter.WriteValue(handler.Value.Description);
- jsonWriter.WritePropertyName("recordDataTemplate");
- jsonWriter.WriteValue(handler.Value.ApplicationRecordDataTemplate);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- }
- }
- jsonWriter.WriteEndArray();
- }
- private async Task ListStoreApps(JsonTextWriter jsonWriter)
- {
- string storeAppsJsonData = await GetStoreAppsJsonData();
- dynamic jsonStoreAppsArray = JsonConvert.DeserializeObject(storeAppsJsonData);
- jsonWriter.WritePropertyName("storeApps");
- jsonWriter.WriteStartArray();
- foreach (dynamic jsonStoreApp in jsonStoreAppsArray)
- {
- string name = jsonStoreApp.name.Value;
- string version = jsonStoreApp.version.Value;
- string description = jsonStoreApp.description.Value;
- string url = jsonStoreApp.url.Value;
- string size = jsonStoreApp.size.Value;
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(name);
- jsonWriter.WritePropertyName("version");
- jsonWriter.WriteValue(version);
- jsonWriter.WritePropertyName("description");
- jsonWriter.WriteValue(description);
- jsonWriter.WritePropertyName("url");
- jsonWriter.WriteValue(url);
- jsonWriter.WritePropertyName("size");
- jsonWriter.WriteValue(size);
- bool installed = _dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication installedApp);
- jsonWriter.WritePropertyName("installed");
- jsonWriter.WriteValue(installed);
- if (installed)
- {
- jsonWriter.WritePropertyName("installedVersion");
- jsonWriter.WriteValue(GetCleanVersion(installedApp.Version));
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(new Version(version) > installedApp.Version);
- }
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- private async Task DownloadAndInstallAppAsync(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- string url = request.QueryString["url"];
- if (string.IsNullOrEmpty(url))
- throw new DnsWebServiceException("Parameter 'url' missing.");
- if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
- throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //download to temp file
- SocketsHttpHandler handler = new SocketsHttpHandler();
- handler.Proxy = _dnsServer.Proxy;
- handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
- using (HttpClient http = new HttpClient(handler))
- {
- using (Stream httpStream = await http.GetStreamAsync(url))
- {
- await httpStream.CopyToAsync(fS);
- }
- }
- //install app
- fS.Position = 0;
- await _dnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was installed successfully from: " + url);
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- }
- private async Task DownloadAndUpdateAppAsync(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- string url = request.QueryString["url"];
- if (string.IsNullOrEmpty(url))
- throw new DnsWebServiceException("Parameter 'url' missing.");
- if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
- throw new DnsWebServiceException("Parameter 'url' value must start with 'https://'.");
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //download to temp file
- SocketsHttpHandler handler = new SocketsHttpHandler();
- handler.Proxy = _dnsServer.Proxy;
- handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
- using (HttpClient http = new HttpClient(handler))
- {
- using (Stream httpStream = await http.GetStreamAsync(url))
- {
- await httpStream.CopyToAsync(fS);
- }
- }
- //update app
- fS.Position = 0;
- await _dnsServer.DnsApplicationManager.UpdateApplicationAsync(name, fS);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was updated successfully from: " + url);
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- }
- private async Task InstallAppAsync(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- #region skip to content
- int crlfCount = 0;
- int byteRead;
- while (crlfCount != 4)
- {
- byteRead = request.InputStream.ReadByte();
- switch (byteRead)
- {
- case -1:
- throw new EndOfStreamException();
- case 13: //CR
- case 10: //LF
- crlfCount++;
- break;
- default:
- crlfCount = 0;
- break;
- }
- }
- #endregion
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //write to temp file
- await request.InputStream.CopyToAsync(fS);
- //install app
- fS.Position = 0;
- await _dnsServer.DnsApplicationManager.InstallApplicationAsync(name, fS);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was installed successfully.");
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- }
- private async Task UpdateAppAsync(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- #region skip to content
- int crlfCount = 0;
- int byteRead;
- while (crlfCount != 4)
- {
- byteRead = request.InputStream.ReadByte();
- switch (byteRead)
- {
- case -1:
- throw new EndOfStreamException();
- case 13: //CR
- case 10: //LF
- crlfCount++;
- break;
- default:
- crlfCount = 0;
- break;
- }
- }
- #endregion
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //write to temp file
- await request.InputStream.CopyToAsync(fS);
- //update app
- fS.Position = 0;
- await _dnsServer.DnsApplicationManager.UpdateApplicationAsync(name, fS);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was updated successfully.");
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- }
- private void UninstallApp(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- _dnsServer.DnsApplicationManager.UninstallApplication(name);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS application '" + name + "' was uninstalled successfully.");
- }
- private async Task GetAppConfigAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- if (!_dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
- throw new DnsWebServiceException("DNS application was not found: " + name);
- string config = await application.GetConfigAsync();
- jsonWriter.WritePropertyName("config");
- jsonWriter.WriteValue(config);
- }
- private async Task SetAppConfigAsync(HttpListenerRequest request)
- {
- string name = request.QueryString["name"];
- if (string.IsNullOrEmpty(name))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- if (!_dnsServer.DnsApplicationManager.Applications.TryGetValue(name, out DnsApplication application))
- throw new DnsWebServiceException("DNS application was not found: " + name);
- string formRequest;
- using (StreamReader sR = new StreamReader(request.InputStream, request.ContentEncoding))
- {
- formRequest = sR.ReadToEnd();
- }
- string[] formParts = formRequest.Split('&');
- foreach (string formPart in formParts)
- {
- if (formPart.StartsWith("config="))
- {
- string config = formPart.Substring(7);
- if (config.Length == 0)
- config = null;
- await application.SetConfigAsync(config);
- break;
- }
- }
- }
- #endregion
- #region dns client api
- private async Task ResolveQuery(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string server = request.QueryString["server"];
- if (string.IsNullOrEmpty(server))
- throw new DnsWebServiceException("Parameter 'server' missing.");
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- domain = domain.Trim();
- if (domain.EndsWith("."))
- domain = domain.Substring(0, domain.Length - 1);
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- throw new DnsWebServiceException("Parameter 'type' missing.");
- DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
- string strProtocol = request.QueryString["protocol"];
- if (string.IsNullOrEmpty(strProtocol))
- strProtocol = "Udp";
- bool importRecords = false;
- string strImport = request.QueryString["import"];
- if (!string.IsNullOrEmpty(strImport))
- importRecords = bool.Parse(strImport);
- NetProxy proxy = _dnsServer.Proxy;
- bool preferIPv6 = _dnsServer.PreferIPv6;
- bool randomizeName = false;
- bool qnameMinimization = _dnsServer.QnameMinimization;
- DnsTransportProtocol protocol = (DnsTransportProtocol)Enum.Parse(typeof(DnsTransportProtocol), strProtocol, true);
- const int RETRIES = 1;
- const int TIMEOUT = 10000;
- DnsDatagram dnsResponse;
- if (server.Equals("recursive-resolver", StringComparison.OrdinalIgnoreCase))
- {
- if (type == DnsResourceRecordType.AXFR)
- throw new DnsServerException("Cannot do zone transfer (AXFR) for 'recursive-resolver'.");
- DnsQuestionRecord question;
- if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress address))
- question = new DnsQuestionRecord(address, DnsClass.IN);
- else
- question = new DnsQuestionRecord(domain, type, DnsClass.IN);
- dnsResponse = await DnsClient.RecursiveResolveAsync(question, null, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
- }
- else
- {
- if (type == DnsResourceRecordType.AXFR)
- protocol = DnsTransportProtocol.Tcp;
- NameServerAddress nameServer;
- if (server.Equals("this-server", StringComparison.OrdinalIgnoreCase))
- {
- switch (protocol)
- {
- case DnsTransportProtocol.Udp:
- nameServer = _dnsServer.ThisServer;
- break;
- case DnsTransportProtocol.Tcp:
- nameServer = new NameServerAddress(_dnsServer.ThisServer, DnsTransportProtocol.Tcp);
- break;
- case DnsTransportProtocol.Tls:
- throw new DnsServerException("Cannot use DNS-over-TLS protocol for 'this-server'. Please use the TLS certificate domain name as the server.");
- case DnsTransportProtocol.Https:
- 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.");
- case DnsTransportProtocol.HttpsJson:
- 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.");
- default:
- throw new InvalidOperationException();
- }
- proxy = null; //no proxy required for this server
- }
- else
- {
- if ((protocol == DnsTransportProtocol.Tls) && !server.Contains(":853"))
- server += ":853";
- nameServer = new NameServerAddress(server, protocol);
- if (nameServer.IPEndPoint == null)
- {
- if (proxy == null)
- {
- if (_dnsServer.AllowRecursion)
- await nameServer.ResolveIPAddressAsync(new NameServerAddress[] { _dnsServer.ThisServer }, proxy, preferIPv6, randomizeName, RETRIES, TIMEOUT);
- else
- await nameServer.RecursiveResolveIPAddressAsync(_dnsServer.DnsCache, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
- }
- }
- else if (protocol != DnsTransportProtocol.Tls)
- {
- try
- {
- if (_dnsServer.AllowRecursion)
- await nameServer.ResolveDomainNameAsync(new NameServerAddress[] { _dnsServer.ThisServer }, proxy, preferIPv6, randomizeName, RETRIES, TIMEOUT);
- else
- await nameServer.RecursiveResolveDomainNameAsync(_dnsServer.DnsCache, proxy, preferIPv6, randomizeName, qnameMinimization, RETRIES, TIMEOUT);
- }
- catch
- { }
- }
- }
- dnsResponse = await new DnsClient(nameServer) { Proxy = proxy, PreferIPv6 = preferIPv6, RandomizeName = randomizeName, Retries = RETRIES, Timeout = TIMEOUT }.ResolveAsync(domain, type);
- }
- if (importRecords)
- {
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo == null)
- {
- zoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(domain, _dnsServer.ServerDomain, false);
- if (zoneInfo == null)
- throw new DnsServerException("Cannot import records: failed to create primary zone.");
- }
- else
- {
- switch (zoneInfo.Type)
- {
- case AuthZoneType.Primary:
- case AuthZoneType.Forwarder:
- break;
- default:
- throw new DnsServerException("Cannot import records: import zone must be of primary or forwarder type.");
- }
- }
- if (type == DnsResourceRecordType.AXFR)
- {
- bool dontRemoveRecords = zoneInfo.Type == AuthZoneType.Forwarder;
- _dnsServer.AuthZoneManager.SyncRecords(domain, dnsResponse.Answer, null, dontRemoveRecords);
- }
- else
- {
- List<DnsResourceRecord> syncRecords = new List<DnsResourceRecord>();
- foreach (DnsResourceRecord record in dnsResponse.Answer)
- {
- if (record.Name.Equals(domain, StringComparison.OrdinalIgnoreCase))
- {
- record.RemoveExpiry();
- syncRecords.Add(record);
- }
- }
- _dnsServer.AuthZoneManager.SyncRecords(domain, syncRecords, null, true);
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS Client imported record(s) for authoritative zone {server: " + server + "; domain: " + domain + "; type: " + type + ";}");
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- jsonWriter.WritePropertyName("result");
- jsonWriter.WriteRawValue(JsonConvert.SerializeObject(dnsResponse, new StringEnumConverter()));
- }
- #endregion
- #region logs api
- private void ListLogs(JsonTextWriter jsonWriter)
- {
- string[] logFiles = _log.ListLogFiles();
- Array.Sort(logFiles);
- Array.Reverse(logFiles);
- jsonWriter.WritePropertyName("logFiles");
- jsonWriter.WriteStartArray();
- foreach (string logFile in logFiles)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("fileName");
- jsonWriter.WriteValue(Path.GetFileNameWithoutExtension(logFile));
- jsonWriter.WritePropertyName("size");
- jsonWriter.WriteValue(WebUtilities.GetFormattedSize(new FileInfo(logFile).Length));
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- private void DeleteLog(HttpListenerRequest request)
- {
- string log = request.QueryString["log"];
- if (string.IsNullOrEmpty(log))
- throw new DnsWebServiceException("Parameter 'log' missing.");
- _log.DeleteLog(log);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Log file was deleted: " + log);
- }
- private void DeleteAllLogs(HttpListenerRequest request)
- {
- _log.DeleteAllLogs();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] All log files were deleted.");
- }
- private void DeleteAllStats(HttpListenerRequest request)
- {
- _dnsServer.StatsManager.DeleteAllStats();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] All stats files were deleted.");
- }
- #endregion
- #region dhcp api
- private void ListDhcpLeases(JsonTextWriter jsonWriter)
- {
- IReadOnlyDictionary<string, Scope> scopes = _dhcpServer.Scopes;
- //sort by name
- List<Scope> sortedScopes = new List<Scope>(scopes.Count);
- foreach (KeyValuePair<string, Scope> entry in scopes)
- sortedScopes.Add(entry.Value);
- sortedScopes.Sort();
- jsonWriter.WritePropertyName("leases");
- jsonWriter.WriteStartArray();
- foreach (Scope scope in sortedScopes)
- {
- IReadOnlyDictionary<ClientIdentifierOption, Lease> leases = scope.Leases;
- //sort by address
- List<Lease> sortedLeases = new List<Lease>(leases.Count);
- foreach (KeyValuePair<ClientIdentifierOption, Lease> entry in leases)
- sortedLeases.Add(entry.Value);
- sortedLeases.Sort();
- foreach (Lease lease in sortedLeases)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("scope");
- jsonWriter.WriteValue(scope.Name);
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(lease.Type.ToString());
- jsonWriter.WritePropertyName("hardwareAddress");
- jsonWriter.WriteValue(BitConverter.ToString(lease.HardwareAddress));
- jsonWriter.WritePropertyName("address");
- jsonWriter.WriteValue(lease.Address.ToString());
- jsonWriter.WritePropertyName("hostName");
- jsonWriter.WriteValue(lease.HostName);
- jsonWriter.WritePropertyName("leaseObtained");
- jsonWriter.WriteValue(lease.LeaseObtained.ToLocalTime().ToString());
- jsonWriter.WritePropertyName("leaseExpires");
- jsonWriter.WriteValue(lease.LeaseExpires.ToLocalTime().ToString());
- jsonWriter.WriteEndObject();
- }
- }
- jsonWriter.WriteEndArray();
- }
- private void ListDhcpScopes(JsonTextWriter jsonWriter)
- {
- IReadOnlyDictionary<string, Scope> scopes = _dhcpServer.Scopes;
- //sort by name
- List<Scope> sortedScopes = new List<Scope>(scopes.Count);
- foreach (KeyValuePair<string, Scope> entry in scopes)
- sortedScopes.Add(entry.Value);
- sortedScopes.Sort();
- jsonWriter.WritePropertyName("scopes");
- jsonWriter.WriteStartArray();
- foreach (Scope scope in sortedScopes)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(scope.Name);
- jsonWriter.WritePropertyName("enabled");
- jsonWriter.WriteValue(scope.Enabled);
- jsonWriter.WritePropertyName("startingAddress");
- jsonWriter.WriteValue(scope.StartingAddress.ToString());
- jsonWriter.WritePropertyName("endingAddress");
- jsonWriter.WriteValue(scope.EndingAddress.ToString());
- jsonWriter.WritePropertyName("subnetMask");
- jsonWriter.WriteValue(scope.SubnetMask.ToString());
- jsonWriter.WritePropertyName("networkAddress");
- jsonWriter.WriteValue(scope.NetworkAddress.ToString());
- jsonWriter.WritePropertyName("broadcastAddress");
- jsonWriter.WriteValue(scope.BroadcastAddress.ToString());
- if (scope.InterfaceAddress != null)
- {
- jsonWriter.WritePropertyName("interfaceAddress");
- jsonWriter.WriteValue(scope.InterfaceAddress.ToString());
- }
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- private void GetDhcpScope(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- Scope scope = _dhcpServer.GetScope(scopeName);
- if (scope == null)
- throw new DnsWebServiceException("DHCP scope was not found: " + scopeName);
- jsonWriter.WritePropertyName("name");
- jsonWriter.WriteValue(scope.Name);
- jsonWriter.WritePropertyName("startingAddress");
- jsonWriter.WriteValue(scope.StartingAddress.ToString());
- jsonWriter.WritePropertyName("endingAddress");
- jsonWriter.WriteValue(scope.EndingAddress.ToString());
- jsonWriter.WritePropertyName("subnetMask");
- jsonWriter.WriteValue(scope.SubnetMask.ToString());
- jsonWriter.WritePropertyName("leaseTimeDays");
- jsonWriter.WriteValue(scope.LeaseTimeDays);
- jsonWriter.WritePropertyName("leaseTimeHours");
- jsonWriter.WriteValue(scope.LeaseTimeHours);
- jsonWriter.WritePropertyName("leaseTimeMinutes");
- jsonWriter.WriteValue(scope.LeaseTimeMinutes);
- jsonWriter.WritePropertyName("offerDelayTime");
- jsonWriter.WriteValue(scope.OfferDelayTime);
- if (!string.IsNullOrEmpty(scope.DomainName))
- {
- jsonWriter.WritePropertyName("domainName");
- jsonWriter.WriteValue(scope.DomainName);
- }
- jsonWriter.WritePropertyName("dnsTtl");
- jsonWriter.WriteValue(scope.DnsTtl);
- if (scope.ServerAddress != null)
- {
- jsonWriter.WritePropertyName("serverAddress");
- jsonWriter.WriteValue(scope.ServerAddress.ToString());
- }
- if (scope.ServerHostName != null)
- {
- jsonWriter.WritePropertyName("serverHostName");
- jsonWriter.WriteValue(scope.ServerHostName);
- }
- if (scope.BootFileName != null)
- {
- jsonWriter.WritePropertyName("bootFileName");
- jsonWriter.WriteValue(scope.BootFileName);
- }
- if (scope.RouterAddress != null)
- {
- jsonWriter.WritePropertyName("routerAddress");
- jsonWriter.WriteValue(scope.RouterAddress.ToString());
- }
- jsonWriter.WritePropertyName("useThisDnsServer");
- jsonWriter.WriteValue(scope.UseThisDnsServer);
- if (scope.DnsServers != null)
- {
- jsonWriter.WritePropertyName("dnsServers");
- jsonWriter.WriteStartArray();
- foreach (IPAddress dnsServer in scope.DnsServers)
- jsonWriter.WriteValue(dnsServer.ToString());
- jsonWriter.WriteEndArray();
- }
- if (scope.WinsServers != null)
- {
- jsonWriter.WritePropertyName("winsServers");
- jsonWriter.WriteStartArray();
- foreach (IPAddress winsServer in scope.WinsServers)
- jsonWriter.WriteValue(winsServer.ToString());
- jsonWriter.WriteEndArray();
- }
- if (scope.NtpServers != null)
- {
- jsonWriter.WritePropertyName("ntpServers");
- jsonWriter.WriteStartArray();
- foreach (IPAddress ntpServer in scope.NtpServers)
- jsonWriter.WriteValue(ntpServer.ToString());
- jsonWriter.WriteEndArray();
- }
- if (scope.StaticRoutes != null)
- {
- jsonWriter.WritePropertyName("staticRoutes");
- jsonWriter.WriteStartArray();
- foreach (ClasslessStaticRouteOption.Route route in scope.StaticRoutes)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("destination");
- jsonWriter.WriteValue(route.Destination.ToString());
- jsonWriter.WritePropertyName("subnetMask");
- jsonWriter.WriteValue(route.SubnetMask.ToString());
- jsonWriter.WritePropertyName("router");
- jsonWriter.WriteValue(route.Router.ToString());
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- if (scope.VendorInfo != null)
- {
- jsonWriter.WritePropertyName("vendorInfo");
- jsonWriter.WriteStartArray();
- foreach (KeyValuePair<string, VendorSpecificInformationOption> entry in scope.VendorInfo)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("identifier");
- jsonWriter.WriteValue(entry.Key);
- jsonWriter.WritePropertyName("information");
- jsonWriter.WriteValue(entry.Value.ToString());
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- if (scope.Exclusions != null)
- {
- jsonWriter.WritePropertyName("exclusions");
- jsonWriter.WriteStartArray();
- foreach (Exclusion exclusion in scope.Exclusions)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("startingAddress");
- jsonWriter.WriteValue(exclusion.StartingAddress.ToString());
- jsonWriter.WritePropertyName("endingAddress");
- jsonWriter.WriteValue(exclusion.EndingAddress.ToString());
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("reservedLeases");
- jsonWriter.WriteStartArray();
- foreach (Lease reservedLease in scope.ReservedLeases)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("hostName");
- jsonWriter.WriteValue(reservedLease.HostName);
- jsonWriter.WritePropertyName("hardwareAddress");
- jsonWriter.WriteValue(BitConverter.ToString(reservedLease.HardwareAddress));
- jsonWriter.WritePropertyName("address");
- jsonWriter.WriteValue(reservedLease.Address.ToString());
- jsonWriter.WritePropertyName("comments");
- jsonWriter.WriteValue(reservedLease.Comments);
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("allowOnlyReservedLeases");
- jsonWriter.WriteValue(scope.AllowOnlyReservedLeases);
- }
- private async Task SetDhcpScopeAsync(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- string newName = request.QueryString["newName"];
- if (!string.IsNullOrEmpty(newName) && !newName.Equals(scopeName))
- {
- _dhcpServer.RenameScope(scopeName, newName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was renamed successfully: '" + scopeName + "' to '" + newName + "'");
- scopeName = newName;
- }
- string strStartingAddress = request.QueryString["startingAddress"];
- if (string.IsNullOrEmpty(strStartingAddress))
- throw new DnsWebServiceException("Parameter 'startingAddress' missing.");
- string strEndingAddress = request.QueryString["endingAddress"];
- if (string.IsNullOrEmpty(strEndingAddress))
- throw new DnsWebServiceException("Parameter 'endingAddress' missing.");
- string strSubnetMask = request.QueryString["subnetMask"];
- if (string.IsNullOrEmpty(strSubnetMask))
- throw new DnsWebServiceException("Parameter 'subnetMask' missing.");
- bool scopeExists;
- Scope scope = _dhcpServer.GetScope(scopeName);
- if (scope == null)
- {
- //scope does not exists; create new scope
- scopeExists = false;
- scope = new Scope(scopeName, true, IPAddress.Parse(strStartingAddress), IPAddress.Parse(strEndingAddress), IPAddress.Parse(strSubnetMask));
- }
- else
- {
- scopeExists = true;
- IPAddress startingAddress = IPAddress.Parse(strStartingAddress);
- IPAddress endingAddress = IPAddress.Parse(strEndingAddress);
- //validate scope address
- foreach (KeyValuePair<string, Scope> entry in _dhcpServer.Scopes)
- {
- Scope existingScope = entry.Value;
- if (existingScope.Equals(scope))
- continue;
- if (existingScope.IsAddressInRange(startingAddress) || existingScope.IsAddressInRange(endingAddress))
- throw new DhcpServerException("Scope with overlapping range already exists: " + existingScope.StartingAddress.ToString() + "-" + existingScope.EndingAddress.ToString());
- }
- scope.ChangeNetwork(startingAddress, endingAddress, IPAddress.Parse(strSubnetMask));
- }
- string strLeaseTimeDays = request.QueryString["leaseTimeDays"];
- if (!string.IsNullOrEmpty(strLeaseTimeDays))
- scope.LeaseTimeDays = ushort.Parse(strLeaseTimeDays);
- string strLeaseTimeHours = request.QueryString["leaseTimeHours"];
- if (!string.IsNullOrEmpty(strLeaseTimeHours))
- scope.LeaseTimeHours = byte.Parse(strLeaseTimeHours);
- string strLeaseTimeMinutes = request.QueryString["leaseTimeMinutes"];
- if (!string.IsNullOrEmpty(strLeaseTimeMinutes))
- scope.LeaseTimeMinutes = byte.Parse(strLeaseTimeMinutes);
- string strOfferDelayTime = request.QueryString["offerDelayTime"];
- if (!string.IsNullOrEmpty(strOfferDelayTime))
- scope.OfferDelayTime = ushort.Parse(strOfferDelayTime);
- string strDomainName = request.QueryString["domainName"];
- if (strDomainName != null)
- scope.DomainName = strDomainName.Length == 0 ? null : strDomainName;
- string strDnsTtl = request.QueryString["dnsTtl"];
- if (!string.IsNullOrEmpty(strDnsTtl))
- scope.DnsTtl = uint.Parse(strDnsTtl);
- string strServerAddress = request.QueryString["serverAddress"];
- if (strServerAddress != null)
- scope.ServerAddress = strServerAddress.Length == 0 ? null : IPAddress.Parse(strServerAddress);
- string strServerHostName = request.QueryString["serverHostName"];
- if (strServerHostName != null)
- scope.ServerHostName = strServerHostName.Length == 0 ? null : strServerHostName;
- string strBootFileName = request.QueryString["bootFileName"];
- if (strBootFileName != null)
- scope.BootFileName = strBootFileName.Length == 0 ? null : strBootFileName;
- string strRouterAddress = request.QueryString["routerAddress"];
- if (strRouterAddress != null)
- scope.RouterAddress = strRouterAddress.Length == 0 ? null : IPAddress.Parse(strRouterAddress);
- string strUseThisDnsServer = request.QueryString["useThisDnsServer"];
- if (!string.IsNullOrEmpty(strUseThisDnsServer))
- scope.UseThisDnsServer = bool.Parse(strUseThisDnsServer);
- if (!scope.UseThisDnsServer)
- {
- string strDnsServers = request.QueryString["dnsServers"];
- if (strDnsServers != null)
- {
- if (strDnsServers.Length == 0)
- {
- scope.DnsServers = null;
- }
- else
- {
- string[] strDnsServerParts = strDnsServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- IPAddress[] dnsServers = new IPAddress[strDnsServerParts.Length];
- for (int i = 0; i < strDnsServerParts.Length; i++)
- dnsServers[i] = IPAddress.Parse(strDnsServerParts[i]);
- scope.DnsServers = dnsServers;
- }
- }
- }
- string strWinsServers = request.QueryString["winsServers"];
- if (strWinsServers != null)
- {
- if (strWinsServers.Length == 0)
- {
- scope.WinsServers = null;
- }
- else
- {
- string[] strWinsServerParts = strWinsServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- IPAddress[] winsServers = new IPAddress[strWinsServerParts.Length];
- for (int i = 0; i < strWinsServerParts.Length; i++)
- winsServers[i] = IPAddress.Parse(strWinsServerParts[i]);
- scope.WinsServers = winsServers;
- }
- }
- string strNtpServers = request.QueryString["ntpServers"];
- if (strNtpServers != null)
- {
- if (strNtpServers.Length == 0)
- {
- scope.NtpServers = null;
- }
- else
- {
- string[] strNtpServerParts = strNtpServers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- IPAddress[] ntpServers = new IPAddress[strNtpServerParts.Length];
- for (int i = 0; i < strNtpServerParts.Length; i++)
- ntpServers[i] = IPAddress.Parse(strNtpServerParts[i]);
- scope.NtpServers = ntpServers;
- }
- }
- string strStaticRoutes = request.QueryString["staticRoutes"];
- if (strStaticRoutes != null)
- {
- if (strStaticRoutes.Length == 0)
- {
- scope.StaticRoutes = null;
- }
- else
- {
- string[] strStaticRoutesParts = strStaticRoutes.Split('|');
- List<ClasslessStaticRouteOption.Route> staticRoutes = new List<ClasslessStaticRouteOption.Route>();
- for (int i = 0; i < strStaticRoutesParts.Length; i += 3)
- {
- staticRoutes.Add(new ClasslessStaticRouteOption.Route(IPAddress.Parse(strStaticRoutesParts[i + 0]), IPAddress.Parse(strStaticRoutesParts[i + 1]), IPAddress.Parse(strStaticRoutesParts[i + 2])));
- }
- scope.StaticRoutes = staticRoutes;
- }
- }
- string strVendorInfo = request.QueryString["vendorInfo"];
- if (strVendorInfo != null)
- {
- if (strVendorInfo.Length == 0)
- {
- scope.VendorInfo = null;
- }
- else
- {
- string[] strVendorInfoParts = strVendorInfo.Split('|');
- Dictionary<string, VendorSpecificInformationOption> vendorInfo = new Dictionary<string, VendorSpecificInformationOption>();
- for (int i = 0; i < strVendorInfoParts.Length; i += 2)
- {
- vendorInfo.Add(strVendorInfoParts[i + 0], new VendorSpecificInformationOption(strVendorInfoParts[i + 1]));
- }
- scope.VendorInfo = vendorInfo;
- }
- }
- string strExclusions = request.QueryString["exclusions"];
- if (strExclusions != null)
- {
- if (strExclusions.Length == 0)
- {
- scope.Exclusions = null;
- }
- else
- {
- string[] strExclusionsParts = strExclusions.Split('|');
- List<Exclusion> exclusions = new List<Exclusion>();
- for (int i = 0; i < strExclusionsParts.Length; i += 2)
- {
- exclusions.Add(new Exclusion(IPAddress.Parse(strExclusionsParts[i + 0]), IPAddress.Parse(strExclusionsParts[i + 1])));
- }
- scope.Exclusions = exclusions;
- }
- }
- string strReservedLeases = request.QueryString["reservedLeases"];
- if (strReservedLeases != null)
- {
- if (strReservedLeases.Length == 0)
- {
- scope.ReservedLeases = null;
- }
- else
- {
- string[] strReservedLeaseParts = strReservedLeases.Split('|');
- List<Lease> reservedLeases = new List<Lease>();
- for (int i = 0; i < strReservedLeaseParts.Length; i += 4)
- {
- reservedLeases.Add(new Lease(LeaseType.Reserved, strReservedLeaseParts[i + 0], DhcpMessageHardwareAddressType.Ethernet, strReservedLeaseParts[i + 1], IPAddress.Parse(strReservedLeaseParts[i + 2]), strReservedLeaseParts[i + 3]));
- }
- scope.ReservedLeases = reservedLeases;
- }
- }
- string strAllowOnlyReservedLeases = request.QueryString["allowOnlyReservedLeases"];
- if (!string.IsNullOrEmpty(strAllowOnlyReservedLeases))
- scope.AllowOnlyReservedLeases = bool.Parse(strAllowOnlyReservedLeases);
- if (scopeExists)
- {
- _dhcpServer.SaveScope(scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
- }
- else
- {
- await _dhcpServer.AddScopeAsync(scope);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was added successfully: " + scopeName);
- }
- }
- private async Task EnableDhcpScopeAsync(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- if (!await _dhcpServer.EnableScopeAsync(scopeName))
- throw new DnsWebServiceException("Failed to enable DHCP scope, please check logs for details: " + scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was enabled successfully: " + scopeName);
- }
- private void DisableDhcpScope(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- if (!_dhcpServer.DisableScope(scopeName))
- throw new DnsWebServiceException("Failed to disable DHCP scope, please check logs for details: " + scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was disabled successfully: " + scopeName);
- }
- private void DeleteDhcpScope(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- _dhcpServer.DeleteScope(scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was deleted successfully: " + scopeName);
- }
- private void ConvertToReservedLease(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- Scope scope = _dhcpServer.GetScope(scopeName);
- if (scope == null)
- throw new DnsWebServiceException("DHCP scope does not exists: " + scopeName);
- string strHardwareAddress = request.QueryString["hardwareAddress"];
- if (string.IsNullOrEmpty(strHardwareAddress))
- throw new DnsWebServiceException("Parameter 'hardwareAddress' missing.");
- scope.ConvertToReservedLease(strHardwareAddress);
- _dhcpServer.SaveScope(scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
- }
- private void ConvertToDynamicLease(HttpListenerRequest request)
- {
- string scopeName = request.QueryString["name"];
- if (string.IsNullOrEmpty(scopeName))
- throw new DnsWebServiceException("Parameter 'name' missing.");
- Scope scope = _dhcpServer.GetScope(scopeName);
- if (scope == null)
- throw new DnsWebServiceException("DHCP scope does not exists: " + scopeName);
- string strHardwareAddress = request.QueryString["hardwareAddress"];
- if (string.IsNullOrEmpty(strHardwareAddress))
- throw new DnsWebServiceException("Parameter 'hardwareAddress' missing.");
- scope.ConvertToDynamicLease(strHardwareAddress);
- _dhcpServer.SaveScope(scopeName);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DHCP scope was updated successfully: " + scopeName);
- }
- #endregion
- #region auth
- private void SetCredentials(string username, string password)
- {
- username = username.ToLower();
- string passwordHash = GetPasswordHash(username, password);
- _credentials[username] = passwordHash;
- }
- private void LoadCredentials(string username, string passwordHash)
- {
- username = username.ToLower();
- _credentials[username] = passwordHash;
- }
- private static string GetPasswordHash(string username, string password)
- {
- using (HMAC hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password)))
- {
- return BitConverter.ToString(hmac.ComputeHash(Encoding.UTF8.GetBytes(username))).Replace("-", "").ToLower();
- }
- }
- #endregion
- #region block list
- private void ForceUpdateBlockLists()
- {
- _blockListLastUpdatedOn = new DateTime();
- StopBlockListUpdateTimer();
- StartBlockListUpdateTimer();
- }
- private void StartBlockListUpdateTimer()
- {
- if (_blockListUpdateTimer == null)
- {
- _blockListUpdateTimer = new Timer(async delegate (object state)
- {
- try
- {
- if (DateTime.UtcNow > _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours))
- {
- if (await _dnsServer.BlockListZoneManager.UpdateBlockListsAsync())
- {
- //block lists were updated
- //save last updated on time
- _blockListLastUpdatedOn = DateTime.UtcNow;
- SaveConfigFile();
- }
- }
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating block lists.\r\n" + ex.ToString());
- }
- }, null, BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL, BLOCK_LIST_UPDATE_TIMER_INTERVAL);
- }
- }
- private void StopBlockListUpdateTimer()
- {
- if (_blockListUpdateTimer != null)
- {
- _blockListUpdateTimer.Dispose();
- _blockListUpdateTimer = null;
- }
- }
- #endregion
- #region tls
- private void StartTlsCertificateUpdateTimer()
- {
- if (_tlsCertificateUpdateTimer == null)
- {
- _tlsCertificateUpdateTimer = new Timer(delegate (object state)
- {
- if (!string.IsNullOrEmpty(_webServiceTlsCertificatePath))
- {
- try
- {
- FileInfo fileInfo = new FileInfo(_webServiceTlsCertificatePath);
- if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _webServiceTlsCertificateLastModifiedOn))
- LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating Web Service TLS Certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
- }
- }
- if (!string.IsNullOrEmpty(_dnsTlsCertificatePath))
- {
- try
- {
- FileInfo fileInfo = new FileInfo(_dnsTlsCertificatePath);
- if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _dnsTlsCertificateLastModifiedOn))
- LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating DNS Server TLS Certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
- }
- }
- }, null, TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL, TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL);
- }
- }
- private void StopTlsCertificateUpdateTimer()
- {
- if (_tlsCertificateUpdateTimer != null)
- {
- _tlsCertificateUpdateTimer.Dispose();
- _tlsCertificateUpdateTimer = null;
- }
- }
- private void LoadWebServiceTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
- {
- FileInfo fileInfo = new FileInfo(tlsCertificatePath);
- if (!fileInfo.Exists)
- throw new ArgumentException("Web Service TLS certificate file does not exists: " + tlsCertificatePath);
- if (Path.GetExtension(tlsCertificatePath) != ".pfx")
- throw new ArgumentException("Web Service TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
- X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
- _webServiceTlsCertificate = certificate;
- _webServiceTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
- _log.Write("Web Service TLS certificate was loaded: " + tlsCertificatePath);
- }
- private void LoadDnsTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
- {
- FileInfo fileInfo = new FileInfo(tlsCertificatePath);
- if (!fileInfo.Exists)
- throw new ArgumentException("DNS Server TLS certificate file does not exists: " + tlsCertificatePath);
- if (Path.GetExtension(tlsCertificatePath) != ".pfx")
- throw new ArgumentException("DNS Server TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
- X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
- _dnsServer.Certificate = certificate;
- _dnsTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
- _log.Write("DNS Server TLS certificate was loaded: " + tlsCertificatePath);
- }
- #endregion
- #region config
- private void LoadConfigFile()
- {
- string configFile = Path.Combine(_configFolder, "dns.config");
- try
- {
- bool passwordResetOption = false;
- if (!File.Exists(configFile))
- {
- string passwordResetConfigFile = Path.Combine(_configFolder, "reset.config");
- if (File.Exists(passwordResetConfigFile))
- {
- passwordResetOption = true;
- configFile = passwordResetConfigFile;
- }
- }
- byte version;
- using (FileStream fS = new FileStream(configFile, FileMode.Open, FileAccess.Read))
- {
- BinaryReader bR = new BinaryReader(fS);
- if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
- throw new InvalidDataException("DnsServer config file format is invalid.");
- version = bR.ReadByte();
- switch (version)
- {
- case 2:
- case 3:
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- case 16:
- _dnsServer.ServerDomain = bR.ReadShortString();
- _webServiceHttpPort = bR.ReadInt32();
- if (version >= 13)
- {
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPAddress[] localAddresses = new IPAddress[count];
- for (int i = 0; i < count; i++)
- localAddresses[i] = IPAddressExtension.Parse(bR);
- _webServiceLocalAddresses = localAddresses;
- }
- }
- _webServiceTlsPort = bR.ReadInt32();
- _webServiceEnableTls = bR.ReadBoolean();
- _webServiceHttpToTlsRedirect = bR.ReadBoolean();
- _webServiceTlsCertificatePath = bR.ReadShortString();
- _webServiceTlsCertificatePassword = bR.ReadShortString();
- if (_webServiceTlsCertificatePath.Length == 0)
- _webServiceTlsCertificatePath = null;
- if (_webServiceTlsCertificatePath != null)
- {
- try
- {
- LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
- }
- StartTlsCertificateUpdateTimer();
- }
- }
- _dnsServer.PreferIPv6 = bR.ReadBoolean();
- if (bR.ReadBoolean()) //logQueries
- _dnsServer.QueryLogManager = _log;
- if (version >= 14)
- _dnsServer.StatsManager.MaxStatFileDays = bR.ReadInt32();
- _dnsServer.AllowRecursion = bR.ReadBoolean();
- if (version >= 4)
- _dnsServer.AllowRecursionOnlyForPrivateNetworks = bR.ReadBoolean();
- else
- _dnsServer.AllowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
- if (version >= 12)
- _dnsServer.RandomizeName = bR.ReadBoolean();
- else
- _dnsServer.RandomizeName = true; //default true to enable security feature
- if (version >= 15)
- _dnsServer.QnameMinimization = bR.ReadBoolean();
- else
- _dnsServer.QnameMinimization = true; //default true to enable privacy feature
- if (version >= 13)
- {
- _dnsServer.ServeStale = bR.ReadBoolean();
- _dnsServer.CacheZoneManager.ServeStaleTtl = bR.ReadUInt32();
- }
- if (version >= 9)
- {
- _dnsServer.CachePrefetchEligibility = bR.ReadInt32();
- _dnsServer.CachePrefetchTrigger = bR.ReadInt32();
- _dnsServer.CachePrefetchSampleIntervalInMinutes = bR.ReadInt32();
- _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = bR.ReadInt32();
- }
- NetProxyType proxyType = (NetProxyType)bR.ReadByte();
- if (proxyType != NetProxyType.None)
- {
- string address = bR.ReadShortString();
- int port = bR.ReadInt32();
- NetworkCredential credential = null;
- if (bR.ReadBoolean()) //credential set
- credential = new NetworkCredential(bR.ReadShortString(), bR.ReadShortString());
- _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, address, port, credential);
- if (version >= 10)
- {
- int count = bR.ReadByte();
- List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(count);
- for (int i = 0; i < count; i++)
- bypassList.Add(new NetProxyBypassItem(bR.ReadShortString()));
- _dnsServer.Proxy.BypassList = bypassList;
- }
- }
- else
- {
- _dnsServer.Proxy = null;
- }
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- NameServerAddress[] forwarders = new NameServerAddress[count];
- for (int i = 0; i < count; i++)
- forwarders[i] = new NameServerAddress(bR);
- _dnsServer.Forwarders = forwarders;
- }
- }
- if (version <= 10)
- {
- DnsTransportProtocol forwarderProtocol = (DnsTransportProtocol)bR.ReadByte();
- if (_dnsServer.Forwarders != null)
- {
- List<NameServerAddress> forwarders = new List<NameServerAddress>();
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- {
- if (forwarder.Protocol == forwarderProtocol)
- forwarders.Add(forwarder);
- else
- forwarders.Add(new NameServerAddress(forwarder, forwarderProtocol));
- }
- _dnsServer.Forwarders = forwarders;
- }
- }
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- if (version > 2)
- {
- for (int i = 0; i < count; i++)
- LoadCredentials(bR.ReadShortString(), bR.ReadShortString());
- }
- else
- {
- for (int i = 0; i < count; i++)
- SetCredentials(bR.ReadShortString(), bR.ReadShortString());
- }
- }
- }
- if (version <= 6)
- {
- int count = bR.ReadInt32();
- _configDisabledZones = new List<string>(count);
- for (int i = 0; i < count; i++)
- {
- string domain = bR.ReadShortString();
- _configDisabledZones.Add(domain);
- }
- }
- if (version >= 16)
- _dnsServer.UseNxDomainForBlocking = bR.ReadBoolean();
- if (version > 4)
- {
- //read block list urls
- int count = bR.ReadByte();
- for (int i = 0; i < count; i++)
- {
- string listUrl = bR.ReadShortString();
- if (listUrl.StartsWith("!"))
- _dnsServer.BlockListZoneManager.AllowListUrls.Add(new Uri(listUrl.Substring(1)));
- else
- _dnsServer.BlockListZoneManager.BlockListUrls.Add(new Uri(listUrl));
- }
- _blockListLastUpdatedOn = bR.ReadDate();
- if (version >= 13)
- _blockListUpdateIntervalHours = bR.ReadInt32();
- }
- if (version >= 11)
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPEndPoint[] localEndPoints = new IPEndPoint[count];
- for (int i = 0; i < count; i++)
- localEndPoints[i] = (IPEndPoint)EndPointExtension.Parse(bR);
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- else if (version >= 6)
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPEndPoint[] localEndPoints = new IPEndPoint[count];
- for (int i = 0; i < count; i++)
- localEndPoints[i] = new IPEndPoint(IPAddressExtension.Parse(bR), 53);
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- if (version >= 8)
- {
- _dnsServer.EnableDnsOverHttp = bR.ReadBoolean();
- _dnsServer.EnableDnsOverTls = bR.ReadBoolean();
- _dnsServer.EnableDnsOverHttps = bR.ReadBoolean();
- _dnsTlsCertificatePath = bR.ReadShortString();
- _dnsTlsCertificatePassword = bR.ReadShortString();
- if (_dnsTlsCertificatePath.Length == 0)
- _dnsTlsCertificatePath = null;
- if (_dnsTlsCertificatePath != null)
- {
- try
- {
- LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading DNS Server TLS certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
- }
- StartTlsCertificateUpdateTimer();
- }
- }
- break;
- default:
- throw new InvalidDataException("DNS Server config version not supported.");
- }
- }
- _log.Write("DNS Server config file was loaded: " + configFile);
- if (passwordResetOption)
- {
- SetCredentials("admin", "admin");
- _log.Write("DNS Server reset password for user: admin");
- SaveConfigFile();
- try
- {
- File.Delete(configFile);
- }
- catch
- { }
- }
- if (version <= 6)
- SaveConfigFile(); //save as new config version to avoid loading old version next time
- }
- catch (FileNotFoundException)
- {
- _log.Write("DNS Server config file was not found: " + configFile);
- _log.Write("DNS Server is restoring default config file.");
- SetCredentials("admin", "admin");
- _dnsServer.AllowRecursion = true;
- _dnsServer.AllowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
- _dnsServer.RandomizeName = true; //default true to enable security feature
- _dnsServer.QnameMinimization = true; //default true to enable privacy feature
- SaveConfigFile();
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading config file: " + configFile + "\r\n" + ex.ToString());
- _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.");
- throw;
- }
- }
- private void SaveConfigFile()
- {
- string configFile = Path.Combine(_configFolder, "dns.config");
- using (MemoryStream mS = new MemoryStream())
- {
- //serialize config
- BinaryWriter bW = new BinaryWriter(mS);
- bW.Write(Encoding.ASCII.GetBytes("DS")); //format
- bW.Write((byte)16); //version
- bW.WriteShortString(_dnsServer.ServerDomain);
- bW.Write(_webServiceHttpPort);
- {
- bW.Write(Convert.ToByte(_webServiceLocalAddresses.Count));
- foreach (IPAddress localAddress in _webServiceLocalAddresses)
- localAddress.WriteTo(bW);
- }
- bW.Write(_webServiceTlsPort);
- bW.Write(_webServiceEnableTls);
- bW.Write(_webServiceHttpToTlsRedirect);
- if (_webServiceTlsCertificatePath == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_webServiceTlsCertificatePath);
- if (_webServiceTlsCertificatePassword == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_webServiceTlsCertificatePassword);
- bW.Write(_dnsServer.PreferIPv6);
- bW.Write(_dnsServer.QueryLogManager != null); //logQueries
- bW.Write(_dnsServer.StatsManager.MaxStatFileDays);
- bW.Write(_dnsServer.AllowRecursion);
- bW.Write(_dnsServer.AllowRecursionOnlyForPrivateNetworks);
- bW.Write(_dnsServer.RandomizeName);
- bW.Write(_dnsServer.QnameMinimization);
- bW.Write(_dnsServer.ServeStale);
- bW.Write(_dnsServer.CacheZoneManager.ServeStaleTtl);
- bW.Write(_dnsServer.CachePrefetchEligibility);
- bW.Write(_dnsServer.CachePrefetchTrigger);
- bW.Write(_dnsServer.CachePrefetchSampleIntervalInMinutes);
- bW.Write(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
- if (_dnsServer.Proxy == null)
- {
- bW.Write((byte)NetProxyType.None);
- }
- else
- {
- bW.Write((byte)_dnsServer.Proxy.Type);
- bW.WriteShortString(_dnsServer.Proxy.Address);
- bW.Write(_dnsServer.Proxy.Port);
- NetworkCredential credential = _dnsServer.Proxy.Credential;
- if (credential == null)
- {
- bW.Write(false);
- }
- else
- {
- bW.Write(true);
- bW.WriteShortString(credential.UserName);
- bW.WriteShortString(credential.Password);
- }
- //bypass list
- {
- bW.Write(Convert.ToByte(_dnsServer.Proxy.BypassList.Count));
- foreach (NetProxyBypassItem item in _dnsServer.Proxy.BypassList)
- bW.WriteShortString(item.Value);
- }
- }
- if (_dnsServer.Forwarders == null)
- {
- bW.Write((byte)0);
- }
- else
- {
- bW.Write(Convert.ToByte(_dnsServer.Forwarders.Count));
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- forwarder.WriteTo(bW);
- }
- {
- bW.Write(Convert.ToByte(_credentials.Count));
- foreach (KeyValuePair<string, string> credential in _credentials)
- {
- bW.WriteShortString(credential.Key);
- bW.WriteShortString(credential.Value);
- }
- }
- //block list
- bW.Write(_dnsServer.UseNxDomainForBlocking);
- {
- bW.Write(Convert.ToByte(_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count));
- foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
- bW.WriteShortString("!" + allowListUrl.AbsoluteUri);
- foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
- bW.WriteShortString(blockListUrl.AbsoluteUri);
- bW.Write(_blockListLastUpdatedOn);
- bW.Write(_blockListUpdateIntervalHours);
- }
- {
- bW.Write(Convert.ToByte(_dnsServer.LocalEndPoints.Count));
- foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
- localEP.WriteTo(bW);
- }
- bW.Write(_dnsServer.EnableDnsOverHttp);
- bW.Write(_dnsServer.EnableDnsOverTls);
- bW.Write(_dnsServer.EnableDnsOverHttps);
- if (_dnsTlsCertificatePath == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_dnsTlsCertificatePath);
- if (_dnsTlsCertificatePassword == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_dnsTlsCertificatePassword);
- //write config
- mS.Position = 0;
- using (FileStream fS = new FileStream(configFile, FileMode.Create, FileAccess.Write))
- {
- mS.CopyTo(fS);
- }
- }
- _log.Write("DNS Server config file was saved: " + configFile);
- }
- #endregion
- #region web service start stop
- private void StartDnsWebService()
- {
- int acceptTasks = Math.Max(1, Environment.ProcessorCount);
- //HTTP service
- try
- {
- string webServiceHostname = null;
- _webService = new HttpListener();
- IPAddress httpAddress = null;
- foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
- {
- string host;
- if (webServiceLocalAddress.Equals(IPAddress.Any))
- {
- host = "+";
- httpAddress = IPAddress.Loopback;
- }
- else if (webServiceLocalAddress.Equals(IPAddress.IPv6Any))
- {
- host = "+";
- if ((httpAddress == null) || !IPAddress.IsLoopback(httpAddress))
- httpAddress = IPAddress.IPv6Loopback;
- }
- else
- {
- if (webServiceLocalAddress.AddressFamily == AddressFamily.InterNetworkV6)
- host = "[" + webServiceLocalAddress.ToString() + "]";
- else
- host = webServiceLocalAddress.ToString();
- if (httpAddress == null)
- httpAddress = webServiceLocalAddress;
- if (webServiceHostname == null)
- webServiceHostname = host;
- }
- _webService.Prefixes.Add("http://" + host + ":" + _webServiceHttpPort + "/");
- }
- _webService.Start();
- if (httpAddress == null)
- httpAddress = IPAddress.Loopback;
- _webServiceHttpEP = new IPEndPoint(httpAddress, _webServiceHttpPort);
- _webServiceHostname = webServiceHostname ?? Environment.MachineName.ToLower();
- }
- catch (Exception ex)
- {
- _log.Write("Web Service failed to bind using default hostname. Attempting to bind again using 'localhost' hostname.\r\n" + ex.ToString());
- try
- {
- _webService = new HttpListener();
- _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
- _webService.Prefixes.Add("http://127.0.0.1:" + _webServiceHttpPort + "/");
- _webService.Start();
- }
- catch
- {
- _webService = new HttpListener();
- _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
- _webService.Start();
- }
- _webServiceHttpEP = new IPEndPoint(IPAddress.Loopback, _webServiceHttpPort);
- _webServiceHostname = "localhost";
- }
- _webService.IgnoreWriteExceptions = true;
- for (int i = 0; i < acceptTasks; i++)
- {
- _ = Task.Factory.StartNew(delegate ()
- {
- return AcceptWebRequestAsync();
- }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
- }
- _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "HTTP Web Service was started successfully.");
- //TLS service
- if (_webServiceEnableTls && (_webServiceTlsCertificate != null))
- {
- List<Socket> webServiceTlsListeners = new List<Socket>();
- try
- {
- foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
- {
- Socket tlsListener = new Socket(webServiceLocalAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- tlsListener.Bind(new IPEndPoint(webServiceLocalAddress, _webServiceTlsPort));
- tlsListener.Listen(10);
- webServiceTlsListeners.Add(tlsListener);
- }
- foreach (Socket tlsListener in webServiceTlsListeners)
- {
- for (int i = 0; i < acceptTasks; i++)
- {
- _ = Task.Factory.StartNew(delegate ()
- {
- return AcceptTlsWebRequestAsync(tlsListener);
- }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
- }
- }
- _webServiceTlsListeners = webServiceTlsListeners;
- _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "TLS Web Service was started successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("TLS Web Service failed to start.\r\n" + ex.ToString());
- foreach (Socket tlsListener in webServiceTlsListeners)
- tlsListener.Dispose();
- }
- }
- }
- private void StopDnsWebService()
- {
- _webService.Stop();
- if (_webServiceTlsListeners != null)
- {
- foreach (Socket tlsListener in _webServiceTlsListeners)
- tlsListener.Dispose();
- _webServiceTlsListeners = null;
- }
- }
- #endregion
- #endregion
- #region public
- public void Start()
- {
- if (_disposed)
- throw new ObjectDisposedException("WebService");
- if (_state != ServiceState.Stopped)
- throw new InvalidOperationException("Web Service is already running.");
- _state = ServiceState.Starting;
- try
- {
- //get initial server domain
- string dnsServerDomain = Environment.MachineName.ToLower();
- if (!DnsClient.IsDomainNameValid(dnsServerDomain))
- dnsServerDomain = "dns-server-1"; //use this name instead since machine name is not a valid domain name
- //init dns server
- _dnsServer = new DnsServer(dnsServerDomain, _configFolder, Path.Combine(_appFolder, "dohwww"), _log);
- //init dhcp server
- _dhcpServer = new DhcpServer(Path.Combine(_configFolder, "scopes"), _log);
- _dhcpServer.AuthZoneManager = _dnsServer.AuthZoneManager;
- //load config
- LoadConfigFile();
- //load all dns applications
- _dnsServer.DnsApplicationManager.LoadAllApplications();
- //load all zones files
- _dnsServer.AuthZoneManager.LoadAllZoneFiles();
- //disable zones from old config format
- if (_configDisabledZones != null)
- {
- foreach (string domain in _configDisabledZones)
- {
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo != null)
- {
- zoneInfo.Disabled = true;
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- }
- }
- //load allowed zone and blocked zone
- _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
- _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
- //load block list zone async
- if (_dnsServer.BlockListZoneManager.BlockListUrls.Count > 0)
- {
- ThreadPool.QueueUserWorkItem(delegate (object state)
- {
- try
- {
- _dnsServer.BlockListZoneManager.LoadBlockLists();
- StartBlockListUpdateTimer();
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- });
- }
- //start dns and dhcp
- _dnsServer.Start();
- _dhcpServer.Start();
- //start web service
- StartDnsWebService();
- _state = ServiceState.Running;
- _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was started successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to start DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
- throw;
- }
- }
- public void Stop()
- {
- if (_state != ServiceState.Running)
- return;
- _state = ServiceState.Stopping;
- try
- {
- StopDnsWebService();
- _dnsServer.Dispose();
- _dhcpServer.Dispose();
- StopBlockListUpdateTimer();
- StopTlsCertificateUpdateTimer();
- _state = ServiceState.Stopped;
- _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was stopped successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to stop DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
- throw;
- }
- }
- #endregion
- #region properties
- public string ConfigFolder
- { get { return _configFolder; } }
- public int WebServiceHttpPort
- { get { return _webServiceHttpPort; } }
- public string WebServiceHostname
- { get { return _webServiceHostname; } }
- #endregion
- }
- }
|