public static void Main(string[] args) { DnsServer server = new DnsServer("8.8.8.8"); foreach(string domain in args) { Console.WriteLine("Redirecting {0} to localhost", domain); server.MasterFile.AddIPAddressResourceRecord(domain, "127.0.0.1"); } server.Responded += (request, response) => Console.WriteLine("{0} => {1}", request, response); server.Listen(); }
public static void Main(string[] args) { DnsServer server = null; (new Thread(() => { server = new DnsServer("8.8.8.8"); server.Responded += (request, response) => Console.WriteLine("{0} => {1}", request, response); server.MasterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1"); server.Listen(); })).Start(); Thread.Sleep(1000); //Client client = new Client("72.21.204.209"); //Client client = new Client("8.8.8.8"); DnsClient client = new DnsClient("127.0.0.1"); client.Reverse(IPAddress.Parse("173.194.69.100")); client.Lookup("google.com"); //client.Lookup("dr.dk"); //Console.WriteLine(client.Resolve("dnstest.managemydedi.com", RecordType.AAAA)); client.Lookup("cnn.com"); server.Close(); }
/// <summary> /// method to initialize fields utilized by the service /// </summary> private void InitializeService() { m_diagnostics.ServiceInitializing(); // load the settings from the related sections in app.config DnsServerSettings dnsServerSettings = DnsServerSettingsSection.GetSection().AsDnsServerSettings(); if (dnsServerSettings.ResolutionMode == DnsResolutionMode.AuthoritativeResolution) { AuthoritativeResolutionSettings settings = AuthoritativeResolutionSettingsSection.GetSection().AsAuthoritativeResolutionSettings(); m_store = new AuthoritativeRecordResolver(settings); } else if (dnsServerSettings.ResolutionMode == DnsResolutionMode.RecordStorageService) { ClientSettings recordRetrievalSettings = ClientSettingsSection.GetSection().AsClientSettings(); m_store = new DnsRecordStorageService(recordRetrievalSettings); } else { throw new System.Configuration.ConfigurationErrorsException("Unknown resolution mode"); } // create the DNS Server instance m_dnsServer = new DnsServer(m_store, dnsServerSettings); // // Hook up events for logging/debugging // m_diagnostics.HookEvents(m_dnsServer); m_diagnostics.ServiceInitializingComplete(dnsServerSettings); }
public TestServer(IDnsStore store, DnsServerSettings settings) { m_settings = settings; m_server = new DnsServer(store, settings); m_server.UDPResponder.Server.Error += UDPServer_Error; m_server.TCPResponder.Server.Error += TCPServer_Error; m_server.TCPResponder.Server.ConnectionAccepted += TCP_Accept; m_server.TCPResponder.Server.ConnectionClosed += TCP_Complete; }
public NewAzureVMCmdletInfo(string serviceName, PersistentVM[] vMs, string vnetName, DnsServer[] dnsSettings, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentName, string location, string affinityGroup, string rsvIPName,InternalLoadBalancerConfig internalLoadBalancerConfig, bool waitForBoot) { this.cmdletName = Utilities.NewAzureVMCmdletName; this.cmdletParams.Add(new CmdletParam("ServiceName", serviceName)); this.cmdletParams.Add(new CmdletParam("VMs", vMs)); if (!string.IsNullOrEmpty(vnetName)) { this.cmdletParams.Add(new CmdletParam("VNetName", vnetName)); } if (dnsSettings != null) { this.cmdletParams.Add(new CmdletParam("DnsSettings", dnsSettings)); } if (!string.IsNullOrEmpty(affinityGroup)) { this.cmdletParams.Add(new CmdletParam("AffinityGroup", affinityGroup)); } if (!string.IsNullOrEmpty(serviceLabel)) { this.cmdletParams.Add(new CmdletParam("ServiceLabel", serviceLabel)); } if (!string.IsNullOrEmpty(serviceDescription)) { this.cmdletParams.Add(new CmdletParam("ServiceDescription", serviceDescription)); } if (!string.IsNullOrEmpty(deploymentLabel)) { this.cmdletParams.Add(new CmdletParam("DeploymentLabel", deploymentLabel)); } if (!string.IsNullOrEmpty(deploymentName)) { this.cmdletParams.Add(new CmdletParam("DeploymentName", deploymentName)); } if (!string.IsNullOrEmpty(location)) { this.cmdletParams.Add(new CmdletParam("Location", location)); } if (!string.IsNullOrEmpty(rsvIPName)) { this.cmdletParams.Add(new CmdletParam("ReservedIPName", rsvIPName)); } if (waitForBoot) { this.cmdletParams.Add(new CmdletParam("WaitForBoot", waitForBoot)); } if (internalLoadBalancerConfig != null) { this.cmdletParams.Add(new CmdletParam("InternalLoadBalancerConfig", internalLoadBalancerConfig)); } }
public void Starting_Dns_Server_Starts_Listeners() { var mockListener = new Mocker<IDnsListener>(); var factory = new Mocker<IDnsListenerFactory>() .With(x => x.CreateListeners(), new List<IDnsListener> { mockListener.ToEntity() }) .ToEntity(); var server = new DnsServer(factory); server.StartListening(); mockListener.AssertWasCalledOnce(x => x.StartListening()); }
internal void HookEvents(DnsServer server) { server.Error += this.OnDnsError; if (server.UDPResponder != null) { server.UDPResponder.Received += this.OnUdpRequest; server.UDPResponder.Responding += this.OnUdpResponse; } if (server.TCPResponder != null) { server.TCPResponder.Received += this.OnTcpRequest; server.TCPResponder.Responding += this.OnTcpResponse; } }
public NewAzureVMCmdletInfo(string serviceName, PersistentVM[] vMs, string vnetName, DnsServer[] dnsSettings, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location, string affinityGroup) { this.cmdletName = Utilities.NewAzureVMCmdletName; this.cmdletParams.Add(new CmdletParam("ServiceName", serviceName)); this.cmdletParams.Add(new CmdletParam("VMs", vMs)); if (vnetName != null) { this.cmdletParams.Add(new CmdletParam("VNetName", vnetName)); } if (dnsSettings != null) { this.cmdletParams.Add(new CmdletParam("DnsSettings", dnsSettings)); } if (affinityGroup != null) { this.cmdletParams.Add(new CmdletParam("AffinityGroup", affinityGroup)); } if (serviceLabel != null) { this.cmdletParams.Add(new CmdletParam("ServiceLabel", serviceLabel)); } if (serviceDescription != null) { this.cmdletParams.Add(new CmdletParam("ServiceDescription", serviceDescription)); } if (deploymentLabel != null) { this.cmdletParams.Add(new CmdletParam("DeploymentLabel", deploymentLabel)); } if (deploymentDescription != null) { this.cmdletParams.Add(new CmdletParam("DeploymentDescription", deploymentDescription)); } if (location != null) { this.cmdletParams.Add(new CmdletParam("Location", location)); } }
static void Main(string[] args) { if (File.Exists("config.json")) { ReadConfig("config.json"); } Thread.Sleep(1500); Console.Clear(); Console.WriteLine(Resource.ASCII); OriginColor = Console.ForegroundColor; LocIPAddr = IPAddress.Parse(GetLocIp()); switch (ADnsSetting.TlsVersion) { case 1: SecurityProtocol = SecurityProtocolType.Tls; break; case 1.1F: SecurityProtocol = SecurityProtocolType.Tls11; break; case 1.2F: SecurityProtocol = SecurityProtocolType.Tls12; break; default: SecurityProtocol = SecurityProtocolType.Tls12; break; } if (ADnsSetting.AllowSelfSignedCert) { ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } if (Thread.CurrentThread.CurrentCulture.Name == "zh-CN") { IntIPAddr = IPAddress.Parse(new WebClient().DownloadString("http://members.3322.org/dyndns/getip").Trim()); } else { IntIPAddr = IPAddress.Parse(new WebClient().DownloadString("https://api.ipify.org").Trim()); } //Console.Clear(); if (ADnsSetting.BlackListEnable) { string[] blackListStrs = File.ReadAllLines("black.list"); BlackList = Array.ConvertAll(blackListStrs, DomainName.Parse).ToList(); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------Black List-------"); foreach (var itemName in BlackList) { Console.WriteLine(itemName.ToString()); } } } if (ADnsSetting.ChinaListEnable) { string[] chinaListStrs = File.ReadAllLines("china.list"); ChinaList = Array.ConvertAll(chinaListStrs, DomainName.Parse).ToList(); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------China List-------"); foreach (var itemName in ChinaList) { Console.WriteLine(itemName.ToString()); } } } if (ADnsSetting.WhiteListEnable) { string[] whiteListStrs; if (File.Exists("white.list")) { whiteListStrs = File.ReadAllLines("white.list"); } else { whiteListStrs = File.ReadAllLines("rewrite.list"); } WhiteList = whiteListStrs.Select( itemStr => itemStr.Split(' ', ',', '\t')).ToDictionary( whiteSplit => DomainName.Parse(whiteSplit[1]), whiteSplit => IPAddress.Parse(whiteSplit[0])); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------White List-------"); foreach (var itemName in WhiteList) { Console.WriteLine(itemName.Key + @" : " + itemName.Value); } } } using (DnsServer dnsServer = new DnsServer(ADnsSetting.ListenIp, 10, 10)) { dnsServer.QueryReceived += ServerOnQueryReceived; dnsServer.Start(); Console.WriteLine(@"-------AURORA DNS-------"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(DateTime.Now); Console.WriteLine(@"AuroraDNS Server Running"); Console.ForegroundColor = OriginColor; Console.WriteLine(@"Press any key to stop dns server"); Console.WriteLine(Resource.Line); Console.ReadKey(); } }
public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45) { //Mainland China PRC DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29"); DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/AuroraDNS/AuroraDNS.github.io/Localization/DNS-CN.list"; UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/"; } else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237) { //Taiwan ROC DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101"); DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/AuroraDNS/AuroraDNS.github.io/Localization/DNS-TW.list"; } else if (RegionInfo.CurrentRegion.GeoId == 104) { //HongKong SAR UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/AuroraDNS/AuroraDNS.github.io/Localization/DNS-HK.list"; } if (File.Exists($"{SetupBasePath}url.json")) { UrlSettings.ReadConfig($"{SetupBasePath}url.json"); } if (File.Exists($"{SetupBasePath}config.json")) { DnsSettings.ReadConfig($"{SetupBasePath}config.json"); } if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) { DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // if (false) // ServicePointManager.ServerCertificateValidationCallback += // (sender, cert, chain, sslPolicyErrors) => true; // //强烈不建议 忽略 TLS 证书安全错误 // // switch (0.0) // { // case 1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // break; // case 1.1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; // break; // case 1.2: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // break; // default: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // break; // } LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start(); MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop(); NotifyIcon = new NotifyIcon() { Text = @"AuroraDNS", Visible = false, Icon = Properties.Resources.AuroraWhite }; WinFormMenuItem showItem = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal); WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) => { MDnsSvrWorker.Dispose(); Process.Start(new ProcessStartInfo { FileName = GetType().Assembly.Location }); Environment.Exit(Environment.ExitCode); }); WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) => { if (File.Exists( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log") ) { Process.Start(new ProcessStartInfo("notepad.exe", $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")); } }); WinFormMenuItem abootItem = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().ShowDialog()); WinFormMenuItem updateItem = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location)); WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().ShowDialog()); WinFormMenuItem exitItem = new WinFormMenuItem("退出", (sender, args) => Environment.Exit(Environment.ExitCode)); NotifyIcon.ContextMenu = new WinFormContextMenu(new[] { showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem }); NotifyIcon.DoubleClick += MinimizedNormal; if (MyTools.IsNslookupLocDns()) { IsSysDns.ToolTip = "已设为系统 DNS"; } }
public void AzureIaaSBVT() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); DateTime prevTime = DateTime.Now; string diskLabel1 = "disk1"; int diskSize1 = 30; int lunSlot1 = 0; string diskLabel2 = "disk2"; int diskSize2 = 50; int lunSlot2 = 2; string ep1Name = "tcp1"; int ep1LocalPort = 60010; int ep1PublicPort = 60011; string ep1LBSetName = "lbset1"; int ep1ProbePort = 60012; string ep1ProbePath = string.Empty; int? ep1ProbeInterval = 7; int? ep1ProbeTimeout = null; NetworkAclObject ep1AclObj = vmPowershellCmdlets.NewAzureAclConfig(); bool ep1DirectServerReturn = false; string ep2Name = "tcp2"; int ep2LocalPort = 60020; int ep2PublicPort = 60021; int ep2LocalPortChanged = 60030; int ep2PublicPortChanged = 60031; string ep2LBSetName = "lbset2"; int ep2ProbePort = 60022; string ep2ProbePath = @"/"; int? ep2ProbeInterval = null; int? ep2ProbeTimeout = 32; NetworkAclObject ep2AclObj = vmPowershellCmdlets.NewAzureAclConfig(); bool ep2DirectServerReturn = false; string cerFileName = "testcert.cer"; string thumbprintAlgorithm = "sha1"; try { // Create a certificate X509Certificate2 certCreated = Utilities.CreateCertificate(password); byte[] certData2 = certCreated.Export(X509ContentType.Cert); File.WriteAllBytes(cerFileName, certData2); // Install the .cer file to local machine. StoreLocation certStoreLocation = StoreLocation.CurrentUser; StoreName certStoreName = StoreName.My; X509Certificate2 installedCert = Utilities.InstallCert(cerFileName, certStoreLocation, certStoreName); PSObject certToUpload = vmPowershellCmdlets.RunPSScript( String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0]; string certData = Convert.ToBase64String(((X509Certificate2)certToUpload.BaseObject).RawData); string newAzureVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) { imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); } RecordTimeTaken(ref prevTime); // // New-AzureService and verify with Get-AzureService // vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Assert.IsTrue(Verify.AzureService(serviceName, serviceName, locationName)); RecordTimeTaken(ref prevTime); // // Add-AzureCertificate and verify with Get-AzureCertificate // vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload); Assert.IsTrue(Verify.AzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm, certData)); RecordTimeTaken(ref prevTime); // // Remove-AzureCertificate // vmPowershellCmdlets.RemoveAzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, certCreated.Thumbprint, thumbprintAlgorithm)); RecordTimeTaken(ref prevTime); // // New-AzureVMConfig // var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName); PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(azureVMConfigInfo); RecordTimeTaken(ref prevTime); // // Add-AzureCertificate // vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload); // // New-AzureCertificateSetting // CertificateSettingList certList = new CertificateSettingList(); certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint)); RecordTimeTaken(ref prevTime); // // Add-AzureProvisioningConfig // AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password); azureProvisioningConfig.Vm = vm; vm = vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig); RecordTimeTaken(ref prevTime); // // Add-AzureDataDisk (two disks) // AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1); azureDataDiskConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo1); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2); azureDataDiskConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo2); RecordTimeTaken(ref prevTime); // // Add-AzureEndpoint (two endpoints) // AzureEndPointConfigInfo azureEndPointConfigInfo1 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep1LocalPort, ep1PublicPort, ep1Name, ep1LBSetName, ep1ProbePort, ProtocolInfo.tcp, ep1ProbePath, ep1ProbeInterval, ep1ProbeTimeout, ep1AclObj, ep1DirectServerReturn); azureEndPointConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo1); AzureEndPointConfigInfo azureEndPointConfigInfo2 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep2LocalPort, ep2PublicPort, ep2Name, ep2LBSetName, ep2ProbePort, ProtocolInfo.http, ep2ProbePath, ep2ProbeInterval, ep2ProbeTimeout, ep2AclObj, ep2DirectServerReturn); azureEndPointConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo2); RecordTimeTaken(ref prevTime); // // Set-AzureAvailabilitySet // string testAVSetName = "testAVSet1"; vm = vmPowershellCmdlets.SetAzureAvailabilitySet(testAVSetName, vm); RecordTimeTaken(ref prevTime); // // New-AzureDns // string dnsName = "OpenDns1"; string ipAddress = "208.67.222.222"; DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress); RecordTimeTaken(ref prevTime); // // New-AzureVM // vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, null, new[] { dns }, null, null, null, null); RecordTimeTaken(ref prevTime); // // Get-AzureVM without any parameter (List VMs) // var vmlist = vmPowershellCmdlets.GetAzureVM(); Console.WriteLine("The number of VMs: {0}", vmlist.Count); Assert.AreNotSame(0, vmlist.Count, "No VM exists!!!"); PersistentVMRoleListContext returnedVMlist = vmlist.First(item => item.ServiceName.Equals(serviceName) && item.Name.Equals(newAzureVMName)); Assert.IsNotNull(returnedVMlist, "Created VM does not exist!!!"); Utilities.PrintContext((PersistentVMRoleContext)returnedVMlist); // // Get-AzureVM // PersistentVMRoleContext returnedVM = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName); vm = returnedVM.VM; RecordTimeTaken(ref prevTime); // // Verify AzureDataDisk // Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.None), "Data disk is not properly added"); Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel2, diskSize2, lunSlot2, HostCaching.None), "Data disk is not properly added"); Console.WriteLine("Data disk added correctly."); RecordTimeTaken(ref prevTime); // // Verify AzureEndpoint // Assert.IsTrue(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo1, azureEndPointConfigInfo2 })); // // Verify AzureDns // Assert.IsTrue(Verify.AzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName).DnsSettings, dns)); // // Verify AzureAvailibilitySet // Assert.IsTrue(Verify.AzureAvailabilitySet(vm, testAVSetName)); // // Verify AzureOsDisk // Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadWrite)); // // Set-AzureDataDisk // SetAzureDataDiskConfig setAzureDataDiskConfigInfo = new SetAzureDataDiskConfig(HostCaching.ReadOnly, lunSlot1); setAzureDataDiskConfigInfo.Vm = vm; vm = vmPowershellCmdlets.SetAzureDataDisk(setAzureDataDiskConfigInfo); RecordTimeTaken(ref prevTime); // // Remove-AzureDataDisk // RemoveAzureDataDiskConfig removeAzureDataDiskConfig = new RemoveAzureDataDiskConfig(lunSlot2, vm); vm = vmPowershellCmdlets.RemoveAzureDataDisk(removeAzureDataDiskConfig); RecordTimeTaken(ref prevTime); // // Set-AzureEndpoint // azureEndPointConfigInfo2 = new AzureEndPointConfigInfo( AzureEndPointConfigInfo.ParameterSet.CustomProbe, ProtocolInfo.tcp, ep2LocalPortChanged, ep2PublicPortChanged, ep2Name, ep2LBSetName, ep2ProbePort, ProtocolInfo.http, ep2ProbePath, ep2ProbeInterval, ep2ProbeTimeout, ep2AclObj, ep2DirectServerReturn); azureEndPointConfigInfo2.Vm = vm; vm = vmPowershellCmdlets.SetAzureEndPoint(azureEndPointConfigInfo2); RecordTimeTaken(ref prevTime); // // Remove-AzureEndpoint // vm = vmPowershellCmdlets.RemoveAzureEndPoint(azureEndPointConfigInfo1.EndpointName, vm); RecordTimeTaken(ref prevTime); // // Set-AzureVMSize // var vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium.ToString()); vmSizeConfig.Vm = vm; vm = vmPowershellCmdlets.SetAzureVMSize(vmSizeConfig); RecordTimeTaken(ref prevTime); // // Set-AzureOSDisk // vm = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm); // // Update-AzureVM // vmPowershellCmdlets.UpdateAzureVM(newAzureVMName, serviceName, vm); RecordTimeTaken(ref prevTime); // // Get-AzureVM and Verify the VM // vm = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName).VM; // Verify setting data disk Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.ReadOnly), "Data disk is not properly added"); // Verify removing a data disk Assert.AreEqual(1, vmPowershellCmdlets.GetAzureDataDisk(vm).Count, "DataDisk is not removed."); // Verify setting an endpoint Assert.IsTrue(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo2 })); // Verify removing an endpoint Assert.IsFalse(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo1 })); // Verify os disk Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadOnly)); // // Remove-AzureVM // vmPowershellCmdlets.RemoveAzureVM(newAzureVMName, serviceName); RecordTimeTaken(ref prevTime); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName)); pass = true; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } }
private void StartDnsProxy() { this.dnsServer = new DnsServer(this.CurrentNetworkInterface.Item2, 10, 10, this.ProcessDnsQuery); this.dnsServer.Start(); }
internal VelvetService(IDnsLookup dnsLookup) { this.dnsLookup = dnsLookup; this.dnsServer = new DnsServer(IPAddress.Any, 10, 10, dnsLookup.ProcessQuery); }
private async void NotifyTimerCallback(object state) { DnsServer dnsServer = state as DnsServer; async Task NotifyZoneNameServers(List <string> existingNameServers) { string primaryNameServer = (_entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecordData).PrimaryNameServer; IReadOnlyList <DnsResourceRecord> nsRecords = GetRecords(DnsResourceRecordType.NS); //stub zone has no authority so cant use QueryRecords //notify all secondary name servers foreach (DnsResourceRecord nsRecord in nsRecords) { if (nsRecord.IsDisabled()) { continue; } string nameServerHost = (nsRecord.RDATA as DnsNSRecordData).NameServer; if (primaryNameServer.Equals(nameServerHost, StringComparison.OrdinalIgnoreCase)) { continue; //skip primary name server } existingNameServers.Add(nameServerHost); List <NameServerAddress> nameServers = new List <NameServerAddress>(2); await ResolveNameServerAddressesAsync(dnsServer, nsRecord, nameServers); if (nameServers.Count > 0) { _ = NotifyNameServerAsync(dnsServer, nameServerHost, nameServers); } else { lock (_notifyFailed) { if (!_notifyFailed.Contains(nameServerHost)) { _notifyFailed.Add(nameServerHost); } } LogManager log = dnsServer.LogManager; if (log != null) { log.Write("DNS Server failed to notify name server '" + nameServerHost + "' due to failure in resolving its IP address for zone: " + (_name == "" ? "<root>" : _name)); } } } } void NotifySpecifiedNameServers(List <string> existingNameServers) { IReadOnlyCollection <IPAddress> specifiedNameServers = _notifyNameServers; if (specifiedNameServers is not null) { foreach (IPAddress specifiedNameServer in specifiedNameServers) { string nameServerHost = specifiedNameServer.ToString(); existingNameServers.Add(nameServerHost); _ = NotifyNameServerAsync(dnsServer, nameServerHost, new NameServerAddress[] { new NameServerAddress(specifiedNameServer) }); } } } try { List <string> existingNameServers = new List <string>(); switch (_notify) { case AuthZoneNotify.ZoneNameServers: await NotifyZoneNameServers(existingNameServers); break; case AuthZoneNotify.SpecifiedNameServers: NotifySpecifiedNameServers(existingNameServers); break; case AuthZoneNotify.BothZoneAndSpecifiedNameServers: await NotifyZoneNameServers(existingNameServers); NotifySpecifiedNameServers(existingNameServers); break; } //remove non-existent name servers from notify failed list lock (_notifyFailed) { List <string> toRemove = new List <string>(); foreach (string failedNameServer in _notifyFailed) { bool found = false; foreach (string existingNameServer in existingNameServers) { if (failedNameServer.Equals(existingNameServer)) { found = true; break; } } if (!found) { toRemove.Add(failedNameServer); } } if (toRemove.Count > 0) { foreach (string failedNameServer in toRemove) { _notifyFailed.Remove(failedNameServer); } } } } catch (Exception ex) { LogManager log = dnsServer.LogManager; if (log != null) { log.Write(ex); } } finally { _notifyTimerTriggered = false; } }
public async Task <IReadOnlyList <NameServerAddress> > GetPrimaryNameServerAddressesAsync(DnsServer dnsServer) { DnsResourceRecord soaRecord = _entries[DnsResourceRecordType.SOA][0]; IReadOnlyList <NameServerAddress> primaryNameServers = soaRecord.GetPrimaryNameServers(); if (primaryNameServers.Count > 0) { List <NameServerAddress> resolvedNameServers = new List <NameServerAddress>(primaryNameServers.Count * 2); foreach (NameServerAddress nameServer in primaryNameServers) { if (nameServer.IsIPEndPointStale) { await ResolveNameServerAddressesAsync(dnsServer, nameServer.Host, nameServer.Port, nameServer.Protocol, resolvedNameServers); } else { resolvedNameServers.Add(nameServer); } } return(resolvedNameServers); } string primaryNameServer = (soaRecord.RDATA as DnsSOARecordData).PrimaryNameServer; IReadOnlyList <DnsResourceRecord> nsRecords = GetRecords(DnsResourceRecordType.NS); //stub zone has no authority so cant use QueryRecords List <NameServerAddress> nameServers = new List <NameServerAddress>(nsRecords.Count * 2); foreach (DnsResourceRecord nsRecord in nsRecords) { if (nsRecord.IsDisabled()) { continue; } if (primaryNameServer.Equals((nsRecord.RDATA as DnsNSRecordData).NameServer, StringComparison.OrdinalIgnoreCase)) { //found primary NS await ResolveNameServerAddressesAsync(dnsServer, nsRecord, nameServers); break; } } if (nameServers.Count < 1) { await ResolveNameServerAddressesAsync(dnsServer, primaryNameServer, 53, DnsTransportProtocol.Udp, nameServers); } return(nameServers); }
public void TestVirtualIPLifecycle() { try { string dnsName = Utilities.GetUniqueShortName("Dns"); string vmName = Utilities.GetUniqueShortName(vmNamePrefix); string vipName = Utilities.GetUniqueShortName("Vip"); string endpointName = Utilities.GetUniqueShortName("Endpoint"); // Create a new VM with the reserved ip. DnsServer dns = null; Utilities.ExecuteAndLog(() => { dns = vmPowershellCmdlets.NewAzureDns(dnsName, DNS_IP); }, "Create a new Azure DNS"); PersistentVM vm = null; Utilities.ExecuteAndLog(() => { vm = Utilities.CreateVMObjectWithDataDiskSubnetAndAvailibilitySet(vmName, OS.Windows, username, password, subnet); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, vnet, new[] { dns }, location: locationName); }, "Create a new windows azure vm without reserved ip."); Utilities.ExecuteAndLog(() => vmPowershellCmdlets.AddAzureVirtualIP(vipName, serviceName), "Adding Azure VirtualIP"); var deployment = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); var retrievedVip = deployment.VirtualIPs.FirstOrDefault(vip => string.Equals(vip.Name, vipName)); Assert.IsNotNull(retrievedVip); Assert.IsTrue(string.IsNullOrEmpty(retrievedVip.Address)); AzureEndPointConfigInfo endpointInfo = new AzureEndPointConfigInfo { EndpointName = endpointName, EndpointProtocol = ProtocolInfo.tcp, EndpointLocalPort = 1000, EndpointPublicPort = 444, VirtualIPName = vipName, Vm = vm }; var updatedVM = vmPowershellCmdlets.AddAzureEndPoint(endpointInfo); vmPowershellCmdlets.UpdateAzureVM(vmName, serviceName, updatedVM); deployment = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); retrievedVip = deployment.VirtualIPs.FirstOrDefault(vip => string.Equals(vip.Name, vipName)); Assert.IsNotNull(retrievedVip); Assert.IsTrue(!string.IsNullOrEmpty(retrievedVip.Address)); AzureEndPointConfigInfo removeEndpointInfo = new AzureEndPointConfigInfo { EndpointName = endpointName, EndpointProtocol = ProtocolInfo.tcp, EndpointLocalPort = 1000, EndpointPublicPort = 444, VirtualIPName = vipName, Vm = updatedVM }; updatedVM = vmPowershellCmdlets.RemoveAzureEndPoint(endpointName, updatedVM); vmPowershellCmdlets.UpdateAzureVM(vmName, serviceName, updatedVM); deployment = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); retrievedVip = deployment.VirtualIPs.FirstOrDefault(vip => string.Equals(vip.Name, vipName)); Assert.IsNotNull(retrievedVip); Assert.IsTrue(string.IsNullOrEmpty(retrievedVip.Address)); Utilities.ExecuteAndLog(() => vmPowershellCmdlets.RemoveAzureVirtualIP(vipName, serviceName), "Adding Azure VirtualIP"); deployment = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); retrievedVip = deployment.VirtualIPs.FirstOrDefault(vip => string.Equals(vip.Name, vipName)); Assert.IsNull(retrievedVip); cleanupIfPassed = false; vmPowershellCmdlets.RemoveAzureDeployment(serviceName, "Production", true); pass = true; } catch (Exception ex) { pass = false; Console.WriteLine(ex.ToString()); throw; } }
static void Main(string[] args) { var dnsServer = new DnsServer(new DummyDnsRecordProvider()); dnsServer.Start(); var data = System.IO.File.ReadAllBytes("request.dat"); for (int i = 0; i < 4; i++) { Task.Run(async() => { var udpClient = new UdpClient("127.0.0.1", 53); while (true) { try { await udpClient.SendAsync(data, data.Length); } catch (Exception e) { Console.WriteLine("BANANA: " + e.Message); } } /*while (true) * { * try * { * while (true) * { * var tcpClient = new TcpClient("127.0.0.1", 53); * var stream = tcpClient.GetStream(); * * await stream.WriteAsync(data, 0, data.Length); * await stream.FlushAsync(); * * tcpClient.Close(); * } * * } * catch { } * }*/ }); } // Stats Task.Run(() => { while (true) { Console.WriteLine("Received: " + UdpDnsRequestListener.packetsReceived); Console.WriteLine("MB recei: " + (UdpDnsRequestListener.bytesReceived / 1048576)); UdpDnsRequestListener.packetsReceived = 0; UdpDnsRequestListener.bytesReceived = 0; Thread.Sleep(1000); } }); Console.ReadLine(); }
public DnsHostedService() { _server = new DnsServer(new PSNetRequestResolver()); }
public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; if (File.Exists($"{SetupBasePath}config.json")) { DnsSettings.ReadConfig($"{SetupBasePath}config.json"); } if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) { DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; #pragma warning disable CS0162 //未实装 if (false) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } switch (1.2F) { case 1: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; break; case 1.1F: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; break; case 1.2F: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; break; default: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; break; } #pragma warning restore CS0162 LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); DnsServer myDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10); myDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; DnsSvrWorker.DoWork += (sender, args) => myDnsServer.Start(); DnsSvrWorker.Disposed += (sender, args) => myDnsServer.Stop(); NotifyIcon = new NotifyIcon() { Text = @"AuroraDNS", Visible = true, Icon = Properties.Resources.AuroraWhite }; WinFormMenuItem showItem = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal); WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) => { DnsSvrWorker.Dispose(); Process.Start(new ProcessStartInfo { FileName = GetType().Assembly.Location }); Environment.Exit(Environment.ExitCode); }); WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) => { if (File.Exists( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month}{DateTime.Today.Day}.log") ) { Process.Start(new ProcessStartInfo("notepad.exe", $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month}{DateTime.Today.Day}.log")); } }); WinFormMenuItem abootItem = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().ShowDialog()); WinFormMenuItem updateItem = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location)); WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().ShowDialog()); WinFormMenuItem exitItem = new WinFormMenuItem("退出", (sender, args) => Environment.Exit(Environment.ExitCode)); NotifyIcon.ContextMenu = new WinFormContextMenu(new[] { showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem }); NotifyIcon.DoubleClick += MinimizedNormal; if (MyTools.IsNslookupLocDns()) { IsSysDns.ToolTip = "已设为系统 DNS"; } }
public CacheZoneManager(DnsServer dnsServer) : base(FAILURE_RECORD_TTL, NEGATIVE_RECORD_TTL, MINIMUM_RECORD_TTL, SERVE_STALE_TTL) { _dnsServer = dnsServer; }
private PSVirtualNetwork CreateVirtualNetwork() { var vnet = new PSVirtualNetwork { Name = Name, ResourceGroupName = ResourceGroupName, Location = Location, AddressSpace = new PSAddressSpace { AddressPrefixes = AddressPrefix?.ToList() } }; if (this.EdgeZone != null) { vnet.ExtendedLocation = new PSExtendedLocation(EdgeZone); } if (DnsServer != null) { vnet.DhcpOptions = new PSDhcpOptions { DnsServers = DnsServer?.ToList() }; } vnet.Subnets = this.Subnet?.ToList(); vnet.EnableDdosProtection = EnableDdosProtection; if (!string.IsNullOrEmpty(DdosProtectionPlanId)) { vnet.DdosProtectionPlan = new PSResourceId { Id = DdosProtectionPlanId }; } if (!string.IsNullOrWhiteSpace(BgpCommunity)) { vnet.BgpCommunities = new PSVirtualNetworkBgpCommunities { VirtualNetworkCommunity = this.BgpCommunity }; } // Map to the sdk object var vnetModel = NetworkResourceManagerProfile.Mapper.Map <MNM.VirtualNetwork>(vnet); vnetModel.Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true); if (this.IpAllocation != null) { foreach (var ipAllocation in this.IpAllocation) { var ipAllocationReference = new MNM.SubResource(ipAllocation.Id); vnetModel.IpAllocations.Add(ipAllocationReference); } } // Execute the Create VirtualNetwork call VirtualNetworkClient.CreateOrUpdate(ResourceGroupName, Name, vnetModel); var getVirtualNetwork = GetVirtualNetwork(ResourceGroupName, Name); return(getVirtualNetwork); }
static void Main(string[] args) { Console.WriteLine( $@" __ __ __ __ __ {Environment.NewLine}" + $@" /\ | | |__) / \ |__) /\ | \ |\ | /__ {Environment.NewLine}" + $@"/ \ \__/ | \ \__/ | \ / \ |__/ | \| __/ {Environment.NewLine}" + $@" __ __ ___ ___ ___ __ __ __ ___ {Environment.NewLine}" + $@"| \ / \ | |\ | |__ | / / \ |__) |__ {Environment.NewLine}" + $@"|__/ \__/ | | \| |___ | \__ \__/ | \ |___ {Environment.NewLine}"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; if (ADnsSetting.AllowSelfSignedCert) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } OriginColor = Console.ForegroundColor; LocIPAddr = IPAddress.Parse(GetLocIp()); IntIPAddr = IPAddress.Parse(new WebClient().DownloadString("https://api.ipify.org")); Console.Clear(); if (!string.IsNullOrWhiteSpace(string.Join("", args))) { ReadConfig(args[0]); } if (File.Exists("config.json")) { ReadConfig("config.json"); } if (ADnsSetting.BlackListEnable) { string[] blackListStrs = File.ReadAllLines("black.list"); BlackList = Array.ConvertAll(blackListStrs, DomainName.Parse).ToList(); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------Black List-------"); foreach (var itemName in BlackList) { Console.WriteLine(itemName.ToString()); } } } if (ADnsSetting.WhiteListEnable) { string[] whiteListStrs; if (File.Exists("white.list")) { whiteListStrs = File.ReadAllLines("white.list"); } else { whiteListStrs = File.ReadAllLines("rewrite.list"); } WhiteList = whiteListStrs.Select( itemStr => itemStr.Split(' ', ',', '\t')).ToDictionary( whiteSplit => DomainName.Parse(whiteSplit[1]), whiteSplit => IPAddress.Parse(whiteSplit[0])); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------White List-------"); foreach (var itemName in WhiteList) { Console.WriteLine(itemName.Key + @" : " + itemName.Value); } } } if (ADnsSetting.ChinaListEnable) { string[] chinaListStrs = File.ReadAllLines("china.list"); ChinaList = Array.ConvertAll(chinaListStrs, DomainName.Parse).ToList(); if (ADnsSetting.DebugLog) { Console.WriteLine(@"-------China List-------"); foreach (var itemName in ChinaList) { Console.WriteLine(itemName.ToString()); } } } using (DnsServer dnsServer = new DnsServer(ADnsSetting.ListenIp, 10, 10)) { dnsServer.QueryReceived += ServerOnQueryReceived; dnsServer.Start(); Console.WriteLine(@"-------AURORA DNS------"); Console.WriteLine(@"-------DOTNET CORE------"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(@"AuroraDNS Server Running"); Console.ForegroundColor = OriginColor; Console.WriteLine(@"Press any key to stop dns server"); Console.WriteLine("------------------------"); Console.ReadLine(); Console.WriteLine("------------------------"); } }
public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; Grid.Effect = new BlurEffect { Radius = 5, RenderingBias = RenderingBias.Performance }; if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45) { //Mainland China PRC DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29"); DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list"; UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/"; } else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237) { //Taiwan ROC DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101"); DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list"; } else if (RegionInfo.CurrentRegion.GeoId == 104) { //HongKong SAR UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list"; } if (!File.Exists($"{SetupBasePath}config.json")) { if (MyTools.IsBadSoftExist()) { MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!"); } if (!MyTools.IsNslookupLocDns()) { MessageBoxResult msgResult = MessageBox.Show( "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?" , "Question", MessageBoxButton.OKCancel); if (msgResult == MessageBoxResult.OK) { IsSysDns_OnClick(null, null); } } } if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged")) { try { UrlReg.Reg("doh"); UrlReg.Reg("dns-over-https"); UrlReg.Reg("aurora-doh-list"); File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"); File.SetAttributes( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged", FileAttributes.Hidden); } catch (Exception e) { Console.WriteLine(e); } } try { if (File.Exists($"{SetupBasePath}url.json")) { UrlSettings.ReadConfig($"{SetupBasePath}url.json"); } if (File.Exists($"{SetupBasePath}config.json")) { DnsSettings.ReadConfig($"{SetupBasePath}config.json"); } if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) { DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); } if (DnsSettings.ChinaListEnable && File.Exists("china.list")) { DnsSettings.ReadChinaList(SetupBasePath + "china.list"); } } catch (UnauthorizedAccessException e) { MessageBoxResult msgResult = MessageBox.Show( "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" + $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel); if (msgResult == MessageBoxResult.OK) { RunAsAdmin(); } else { Close(); } } catch (Exception e) { MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; if (DnsSettings.AllowSelfSignedCert) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } // switch (0.0) // { // case 1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // break; // case 1.1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; // break; // case 1.2: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // break; // default: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // break; // } MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start(); MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop(); using (BackgroundWorker worker = new BackgroundWorker()) { worker.DoWork += (sender, args) => { LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); if (!(Equals(DnsSettings.EDnsIp, IPAddress.Any) && DnsSettings.EDnsCustomize)) { IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); var local = IpTools.GeoIpLocal(IntIPAddr.ToString()); Dispatcher?.Invoke(() => { TitleTextItem.Header = $"{IntIPAddr}{Environment.NewLine}{local}"; }); } try { if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list"); } } catch (Exception e) { MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}"); } MemoryCache.Default.Trim(100); }; worker.RunWorkerAsync(); } NotifyIcon = new NotifyIcon() { Text = @"AuroraDNS", Visible = false, Icon = Properties.Resources.AuroraWhite }; WinFormMenuItem showItem = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal); WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) => { if (MDnsSvrWorker.IsBusy) { MDnsSvrWorker.Dispose(); } Process.Start(new ProcessStartInfo { FileName = GetType().Assembly.Location }); Environment.Exit(Environment.ExitCode); }); WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) => { if (File.Exists( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")) { Process.Start(new ProcessStartInfo( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")); } else { MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。"); } }); WinFormMenuItem abootItem = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().Show()); WinFormMenuItem updateItem = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location)); WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().Show()); WinFormMenuItem exitItem = new WinFormMenuItem("退出", (sender, args) => { try { UrlReg.UnReg("doh"); UrlReg.UnReg("dns-over-https"); UrlReg.UnReg("aurora-doh-list"); File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"); if (!DnsSettings.AutoCleanLogEnable) { return; } foreach (var item in Directory.GetFiles($"{SetupBasePath}Log")) { if (item != $"{SetupBasePath}Log" + $"\\{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log") { File.Delete(item); } } if (File.Exists(Path.GetTempPath() + "setdns.cmd")) { File.Delete(Path.GetTempPath() + "setdns.cmd"); } } catch (Exception e) { Console.WriteLine(e); } Close(); Environment.Exit(Environment.ExitCode); }); NotifyIcon.ContextMenu = new WinFormContextMenu(new[] { showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem }); NotifyIcon.DoubleClick += MinimizedNormal; IsSysDns.IsChecked = MyTools.IsNslookupLocDns(); }
internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] vms, string vnetName, DnsServer[] dnsSettings, string affinityGroup, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location) { NewAzureVMCmdletInfo newAzureVMCmdletInfo = new NewAzureVMCmdletInfo(serviceName, vms, vnetName, dnsSettings, affinityGroup, serviceLabel, serviceDescription, deploymentLabel, deploymentDescription, location); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureVMCmdletInfo); Collection<ManagementOperationContext> newAzureVMs = new Collection<ManagementOperationContext>(); foreach (PSObject result in azurePowershellCmdlet.Run()) { newAzureVMs.Add((ManagementOperationContext)result.BaseObject); } return newAzureVMs; }
protected void InitNotify(DnsServer dnsServer) { _notifyTimer = new Timer(NotifyTimerCallback, dnsServer, Timeout.Infinite, Timeout.Infinite); _notifyList = new List <string>(); _notifyFailed = new List <string>(); }
public Service1() { InitializeComponent(); _server = new DnsServer(GetMasterFile(), "114.114.114.114"); }
private async Task NotifyNameServerAsync(DnsServer dnsServer, string nameServerHost, IReadOnlyList <NameServerAddress> nameServers) { //use notify list to prevent multiple threads from notifying the same name server lock (_notifyList) { if (_notifyList.Contains(nameServerHost)) { return; //already notifying the name server in another thread } _notifyList.Add(nameServerHost); } try { DnsClient client = new DnsClient(nameServers); client.Proxy = dnsServer.Proxy; client.Timeout = NOTIFY_TIMEOUT; client.Retries = NOTIFY_RETRIES; DnsDatagram notifyRequest = new DnsDatagram(0, false, DnsOpcode.Notify, true, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN) }, _entries[DnsResourceRecordType.SOA]); DnsDatagram response = await client.ResolveAsync(notifyRequest); switch (response.RCODE) { case DnsResponseCode.NoError: case DnsResponseCode.NotImplemented: { //transaction complete lock (_notifyFailed) { _notifyFailed.Remove(nameServerHost); } LogManager log = dnsServer.LogManager; if (log is not null) { log.Write("DNS Server successfully notified name server '" + nameServerHost + "' for zone: " + (_name == "" ? "<root>" : _name)); } } break; default: { //transaction failed lock (_notifyFailed) { if (!_notifyFailed.Contains(nameServerHost)) { _notifyFailed.Add(nameServerHost); } } LogManager log = dnsServer.LogManager; if (log is not null) { log.Write("DNS Server failed to notify name server '" + nameServerHost + "' (RCODE=" + response.RCODE.ToString() + ") for zone : " + (_name == "" ? "<root>" : _name)); } } break; } } catch (Exception ex) { lock (_notifyFailed) { if (!_notifyFailed.Contains(nameServerHost)) { _notifyFailed.Add(nameServerHost); } } LogManager log = dnsServer.LogManager; if (log is not null) { log.Write("DNS Server failed to notify name server '" + nameServerHost + "' for zone: " + (_name == "" ? "<root>" : _name)); log.Write(ex); } } finally { lock (_notifyList) { _notifyList.Remove(nameServerHost); } } }
public NewAzureQuickVMCmdletInfo( OS os, string userName, string affinityGroup, string availabilitySetName, CertificateSettingList certificates, DnsServer[] dnsSettings, string hostCaching, string imageName, InstanceSize? instanceSize, string location, string mediaLocation, string name, string password, string serviceName, LinuxProvisioningConfigurationSet.SSHKeyPairList sshKeyPairs, LinuxProvisioningConfigurationSet.SSHPublicKeyList sshPublicKeys, string[] subnetNames, string vnetName ) : this(os, name, serviceName, imageName, userName, password, location, instanceSize) { if (!string.IsNullOrEmpty(affinityGroup)) { cmdletParams.Add(new CmdletParam("AffinityGroup", affinityGroup)); } if (!string.IsNullOrEmpty(availabilitySetName)) { cmdletParams.Add(new CmdletParam("AvailabilitySetName", availabilitySetName)); } if (certificates != null) { cmdletParams.Add(new CmdletParam("Certificates", certificates)); } if (dnsSettings != null) { cmdletParams.Add(new CmdletParam("DnsSettings", dnsSettings)); } if (!string.IsNullOrEmpty(hostCaching)) { cmdletParams.Add(new CmdletParam("HostCaching", hostCaching)); } if (!string.IsNullOrEmpty(mediaLocation)) { cmdletParams.Add(new CmdletParam("MediaLocation", mediaLocation)); } if (sshKeyPairs != null) { cmdletParams.Add(new CmdletParam("SSHKeyPairs", sshKeyPairs)); } if (sshPublicKeys != null) { cmdletParams.Add(new CmdletParam("SSHPublicKeys", sshPublicKeys)); } if (subnetNames != null) { cmdletParams.Add(new CmdletParam("SubnetNames", subnetNames)); } if (!string.IsNullOrEmpty(vnetName)) { cmdletParams.Add(new CmdletParam("VNetName", vnetName)); } }
public async Task <IReadOnlyList <NameServerAddress> > GetSecondaryNameServerAddressesAsync(DnsServer dnsServer) { string primaryNameServer = (_entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecordData).PrimaryNameServer; IReadOnlyList <DnsResourceRecord> nsRecords = GetRecords(DnsResourceRecordType.NS); //stub zone has no authority so cant use QueryRecords List <NameServerAddress> nameServers = new List <NameServerAddress>(nsRecords.Count * 2); foreach (DnsResourceRecord nsRecord in nsRecords) { if (nsRecord.IsDisabled()) { continue; } if (primaryNameServer.Equals((nsRecord.RDATA as DnsNSRecordData).NameServer, StringComparison.OrdinalIgnoreCase)) { continue; //skip primary name server } await ResolveNameServerAddressesAsync(dnsServer, nsRecord, nameServers); } return(nameServers); }
/// <summary> /// /// </summary> /// <param name="resultSettings"></param> /// <param name="expDns"></param> /// <returns></returns> internal static bool AzureDns(DnsSettings resultSettings, DnsServer expDns) { try { DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(resultSettings); foreach (DnsServer dnsServer in dnsList) { Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address); if (MatchDns(expDns, dnsServer)) { Console.WriteLine("Matched Dns found!"); return true; } } return false; } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } }
public DnsServerInternal(DnsServer dnsServer, string applicationName, string applicationFolder) { _dnsServer = dnsServer; _applicationName = applicationName; _applicationFolder = applicationFolder; }
public Task <IReadOnlyList <NameServerAddress> > GetPrimaryNameServerAddressesAsync(DnsServer dnsServer) { if (_apexZone is null) { throw new InvalidOperationException(); } return(_apexZone.GetPrimaryNameServerAddressesAsync(dnsServer)); }
public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; Grid.Effect = new BlurEffect { Radius = 5, RenderingBias = RenderingBias.Performance }; if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45) { //Mainland China PRC DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29"); DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve"; UrlSettings.MDnsList = "https://gh.mili.one/github.com/mili-tan/AuroraDNS.GUI/blob/master/List/L10N/DNS-CN.list"; UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/"; } else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237) { //Taiwan ROC DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101"); DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list"; } else if (RegionInfo.CurrentRegion.GeoId == 104) { //HongKong SAR UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list"; } if (!File.Exists($"{SetupBasePath}config.json")) { if (MyTools.IsBadSoftExist()) { MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!"); } if (!MyTools.IsNslookupLocDns()) { var msgResult = MessageBox.Show( "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?" , "Question", MessageBoxButton.OKCancel); if (msgResult == MessageBoxResult.OK) { IsSysDns_OnClick(null, null); } } } if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged")) { try { UrlReg.Reg("doh"); UrlReg.Reg("dns-over-https"); UrlReg.Reg("aurora-doh-list"); File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"); File.SetAttributes( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged", FileAttributes.Hidden); } catch (Exception e) { Console.WriteLine(e); } } try { if (File.Exists($"{SetupBasePath}url.json")) { UrlSettings.ReadConfig($"{SetupBasePath}url.json"); } if (File.Exists($"{SetupBasePath}config.json")) { DnsSettings.ReadConfig($"{SetupBasePath}config.json"); } if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) { DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); } if (DnsSettings.ChinaListEnable && File.Exists("china.list")) { DnsSettings.ReadChinaList(SetupBasePath + "china.list"); } } catch (UnauthorizedAccessException e) { MessageBoxResult msgResult = MessageBox.Show( "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" + $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel); if (msgResult == MessageBoxResult.OK) { RunAsAdmin(); } else { Close(); } } catch (Exception e) { MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; if (DnsSettings.AllowSelfSignedCert) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } // switch (0.0) // { // case 1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // break; // case 1.1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; // break; // case 1.2: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // break; // default: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // break; // } MDnsServer = new DnsServer(DnsSettings.ListenIp, 8, 8); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; //MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start(); //MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop(); using (BackgroundWorker worker = new BackgroundWorker()) { worker.DoWork += (a, s) => { LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); if (!(Equals(DnsSettings.EDnsIp, IPAddress.Any) && DnsSettings.EDnsCustomize)) { IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); var local = IpTools.GeoIpLocal(IntIPAddr.ToString()); Dispatcher?.Invoke(() => { TitleTextItem.Header = $"{IntIPAddr}{Environment.NewLine}{local}"; }); } try { if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list"); } } catch (Exception e) { MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}"); } MemoryCache.Default.Trim(100); }; worker.RunWorkerAsync(); } IsSysDns.IsChecked = MyTools.IsNslookupLocDns(); }
public async Task <IReadOnlyList <NameServerAddress> > GetSecondaryNameServerAddressesAsync(DnsServer dnsServer) { List <NameServerAddress> nameServers = new List <NameServerAddress>(); DnsSOARecord soa = _entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecord; IReadOnlyList <DnsResourceRecord> nsRecords = GetRecords(DnsResourceRecordType.NS); //stub zone has no authority so cant use QueryRecords foreach (DnsResourceRecord nsRecord in nsRecords) { if (nsRecord.IsDisabled()) { continue; } string nsDomain = (nsRecord.RDATA as DnsNSRecord).NameServer; if (soa.PrimaryNameServer.Equals(nsDomain, StringComparison.OrdinalIgnoreCase)) { continue; //skip primary name server } nameServers.AddRange(await GetNameServerAddressesAsync(dnsServer, nsRecord)); } return(nameServers); }
public Task <IReadOnlyList <NameServerAddress> > GetSecondaryNameServerAddressesAsync(DnsServer dnsServer) { if (_zone == null) { throw new InvalidOperationException(); } return(_zone.GetSecondaryNameServerAddressesAsync(dnsServer)); }
public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; Grid.Effect = new BlurEffect { Radius = 5, RenderingBias = RenderingBias.Performance }; if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45) { //Mainland China PRC DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29"); DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list"; UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/"; } else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237) { //Taiwan ROC DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101"); DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list"; } else if (RegionInfo.CurrentRegion.GeoId == 104) { //HongKong SAR UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list"; } try { if (File.Exists($"{SetupBasePath}url.json")) { UrlSettings.ReadConfig($"{SetupBasePath}url.json"); } if (File.Exists($"{SetupBasePath}config.json")) { DnsSettings.ReadConfig($"{SetupBasePath}config.json"); } if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) { DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) { DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); } if (DnsSettings.ChinaListEnable && File.Exists("china.list")) { DnsSettings.ReadChinaList(SetupBasePath + "china.list"); } } catch (Exception e) { MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // if (false) // ServicePointManager.ServerCertificateValidationCallback += // (sender, cert, chain, sslPolicyErrors) => true; // //强烈不建议 忽略 TLS 证书安全错误 // // switch (0.0) // { // case 1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // break; // case 1.1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; // break; // case 1.2: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // break; // default: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // break; // } MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start(); MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop(); using (BackgroundWorker worker = new BackgroundWorker()) { worker.DoWork += (sender, args) => { LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); try { if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list"); } if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list")) { DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list"); } } catch (Exception e) { MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}"); } MemoryCache.Default.Trim(100); }; worker.RunWorkerAsync(); } NotifyIcon = new NotifyIcon() { Text = @"AuroraDNS", Visible = false, Icon = Properties.Resources.AuroraWhite }; WinFormMenuItem showItem = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal); WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) => { if (MDnsSvrWorker.IsBusy) { MDnsSvrWorker.Dispose(); } Process.Start(new ProcessStartInfo { FileName = GetType().Assembly.Location }); Environment.Exit(Environment.ExitCode); }); WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) => { if (File.Exists( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")) { Process.Start(new ProcessStartInfo( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")); } else { MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。"); } }); WinFormMenuItem abootItem = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().Show()); WinFormMenuItem updateItem = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location)); WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().Show()); WinFormMenuItem exitItem = new WinFormMenuItem("退出", (sender, args) => { Close(); Environment.Exit(Environment.ExitCode); }); NotifyIcon.ContextMenu = new WinFormContextMenu(new[] { showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem }); NotifyIcon.DoubleClick += MinimizedNormal; if (MyTools.IsNslookupLocDns()) { IsSysDns.ToolTip = "已设为系统 DNS"; } }
public StartHandler(DnsServer server) { _server = server; }
public AuthZoneManager(DnsServer dnsServer) { _dnsServer = dnsServer; _serverDomain = _dnsServer.ServerDomain; }
public static void Main(string[] args) => DnsServer.StartServer(UIDataParser.GetInputData(args).OriginDnsServerName, new DnsLocalCache(CacheFileName));
private static async Task <IReadOnlyList <NameServerAddress> > GetNameServerAddressesAsync(DnsServer dnsServer, DnsResourceRecord record) { string nsDomain; switch (record.Type) { case DnsResourceRecordType.NS: nsDomain = (record.RDATA as DnsNSRecord).NameServer; break; case DnsResourceRecordType.SOA: nsDomain = (record.RDATA as DnsSOARecord).PrimaryNameServer; break; default: throw new InvalidOperationException(); } List <NameServerAddress> nameServers = new List <NameServerAddress>(2); IReadOnlyList <DnsResourceRecord> glueRecords = record.GetGlueRecords(); if (glueRecords.Count > 0) { foreach (DnsResourceRecord glueRecord in glueRecords) { switch (glueRecord.Type) { case DnsResourceRecordType.A: nameServers.Add(new NameServerAddress(nsDomain, (glueRecord.RDATA as DnsARecord).Address)); break; case DnsResourceRecordType.AAAA: if (dnsServer.PreferIPv6) { nameServers.Add(new NameServerAddress(nsDomain, (glueRecord.RDATA as DnsAAAARecord).Address)); } break; } } } else { //resolve addresses try { DnsDatagram response = await dnsServer.DirectQueryAsync(new DnsQuestionRecord(nsDomain, DnsResourceRecordType.A, DnsClass.IN)); if ((response != null) && (response.Answer.Count > 0)) { IReadOnlyList <IPAddress> addresses = DnsClient.ParseResponseA(response); foreach (IPAddress address in addresses) { nameServers.Add(new NameServerAddress(nsDomain, address)); } } } catch { } if (dnsServer.PreferIPv6) { try { DnsDatagram response = await dnsServer.DirectQueryAsync(new DnsQuestionRecord(nsDomain, DnsResourceRecordType.AAAA, DnsClass.IN)); if ((response != null) && (response.Answer.Count > 0)) { IReadOnlyList <IPAddress> addresses = DnsClient.ParseResponseAAAA(response); foreach (IPAddress address in addresses) { nameServers.Add(new NameServerAddress(nsDomain, address)); } } } catch { } } } return(nameServers); }
private static bool MatchDns(DnsServer expDns, DnsServer actualDns) { try { Assert.AreEqual(expDns.Name, actualDns.Name); Assert.AreEqual(expDns.Address, actualDns.Address); return true; } catch (Exception e) { Console.WriteLine(e.ToString()); if (e is AssertFailedException) { return false; } else { throw; } } }
public void NewAzureVMProcess() { NewAzureVMCommand.NewAzureVMCommand variable = null; int num; List <PersistentVMRole> persistentVMRoles = new List <PersistentVMRole>(); NewAzureVMCommand persistentVMRoles1 = this; var persistentVMs = new List <PersistentVMRole>(); SubscriptionData currentSubscription = CmdletSubscriptionExtensions.GetCurrentSubscription(this); PersistentVM[] vMs = this.VMs; for (int i = 0; i < (int)vMs.Length; i++) { PersistentVM uri = vMs[i]; if (uri.OSVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(uri.OSVirtualHardDisk.DiskName)) { CloudStorageAccount currentStorageAccount = null; try { currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel); } catch (EndpointNotFoundException endpointNotFoundException) { throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service."); } if (currentStorageAccount != null) { DateTime now = DateTime.Now; string roleName = uri.RoleName; if (uri.OSVirtualHardDisk.DiskLabel != null) { roleName = string.Concat(roleName, "-", uri.OSVirtualHardDisk.DiskLabel); } object[] serviceName = new object[6]; serviceName[0] = this.ServiceName; serviceName[1] = roleName; serviceName[2] = now.Year; serviceName[3] = now.Month; serviceName[4] = now.Day; serviceName[5] = now.Millisecond; string str = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", serviceName); string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri; if (!absoluteUri.EndsWith("/")) { absoluteUri = string.Concat(absoluteUri, "/"); } uri.OSVirtualHardDisk.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str)); } else { throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storage account to set it."); } } foreach (DataVirtualHardDisk dataVirtualHardDisk in uri.DataVirtualHardDisks) { if (dataVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(dataVirtualHardDisk.DiskName)) { CloudStorageAccount cloudStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel); if (cloudStorageAccount != null) { DateTime dateTime = DateTime.Now; string roleName1 = uri.RoleName; if (dataVirtualHardDisk.DiskLabel != null) { roleName1 = string.Concat(roleName1, "-", dataVirtualHardDisk.DiskLabel); } object[] year = new object[6]; year[0] = this.ServiceName; year[1] = roleName1; year[2] = dateTime.Year; year[3] = dateTime.Month; year[4] = dateTime.Day; year[5] = dateTime.Millisecond; string str1 = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", year); string absoluteUri1 = cloudStorageAccount.BlobEndpoint.AbsoluteUri; if (!absoluteUri1.EndsWith("/")) { absoluteUri1 = string.Concat(absoluteUri1, "/"); } dataVirtualHardDisk.MediaLink = new Uri(string.Concat(absoluteUri1, "vhds/", str1)); } else { throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it."); } } if (uri.DataVirtualHardDisks.Count <DataVirtualHardDisk>() <= 1) { continue; } Thread.Sleep(1); } PersistentVMRole persistentVMRole = new PersistentVMRole(); persistentVMRole.AvailabilitySetName = uri.AvailabilitySetName; persistentVMRole.ConfigurationSets = uri.ConfigurationSets; persistentVMRole.DataVirtualHardDisks = uri.DataVirtualHardDisks; persistentVMRole.OSVirtualHardDisk = uri.OSVirtualHardDisk; persistentVMRole.RoleName = uri.RoleName; persistentVMRole.RoleSize = uri.RoleSize; persistentVMRole.RoleType = uri.RoleType; persistentVMRole.Label = uri.Label; PersistentVMRole persistentVMRole1 = persistentVMRole; persistentVMRoles1.persistentVMs.Add(persistentVMRole1); } new List <string>(); Operation operation = null; using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel)) { try { if (base.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase)) { CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput(); createHostedServiceInput.AffinityGroup = this.AffinityGroup; createHostedServiceInput.Location = this.Location; createHostedServiceInput.ServiceName = this.ServiceName; if (this.ServiceDescription != null) { createHostedServiceInput.Description = this.ServiceDescription; } else { DateTime now1 = DateTime.Now; DateTime universalTime = now1.ToUniversalTime(); string str2 = string.Format("Implicitly created hosted service{0}", universalTime.ToString("yyyy-MM-dd HH:mm")); createHostedServiceInput.Description = str2; } if (this.ServiceLabel != null) { createHostedServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceLabel); } else { createHostedServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName); } CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput); base.RetryCall((string s) => base.Channel.CreateHostedService(s, createHostedServiceInput)); Operation operation1 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service")); ManagementOperationContext managementOperationContext = new ManagementOperationContext(); managementOperationContext.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service")); managementOperationContext.set_OperationId(operation1.OperationTrackingId); managementOperationContext.set_OperationStatus(operation1.Status); ManagementOperationContext managementOperationContext1 = managementOperationContext; base.WriteObject(managementOperationContext1, true); } } catch (CommunicationException communicationException1) { CommunicationException communicationException = communicationException1; this.WriteErrorDetails(communicationException); return; } } if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0) { if (base.CurrentDeployment != null) { if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName)) { base.WriteWarning("VNetName, DnsSettings, DeploymentLabel or DeploymentName Name can only be specified on new deployments."); } } else { using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel)) { try { if (string.IsNullOrEmpty(this.DeploymentName)) { this.DeploymentName = this.ServiceName; } if (string.IsNullOrEmpty(this.DeploymentLabel)) { this.DeploymentLabel = this.ServiceName; } Deployment deployment = new Deployment(); deployment.DeploymentSlot = "Production"; deployment.Name = this.DeploymentName; deployment.Label = this.DeploymentLabel; List <Role> roles = new List <Role>(); roles.Add(persistentVMRoles1.persistentVMs[0]); deployment.RoleList = new RoleList(roles); deployment.VirtualNetworkName = this.VNetName; Deployment dnsSetting = deployment; if (this.DnsSettings != null) { dnsSetting.Dns = new DnsSettings(); dnsSetting.Dns.DnsServers = new DnsServerList(); DnsServer[] dnsSettings = this.DnsSettings; for (int j = 0; j < (int)dnsSettings.Length; j++) { DnsServer dnsServer = dnsSettings[j]; dnsSetting.Dns.DnsServers.Add(dnsServer); } } CmdletExtensions.WriteVerboseOutputForObject(this, dnsSetting); base.RetryCall((string s) => base.Channel.CreateDeployment(s, this.ServiceName, dnsSetting)); Operation operation2 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", persistentVMRoles1.persistentVMs[0].RoleName)); ManagementOperationContext managementOperationContext2 = new ManagementOperationContext(); managementOperationContext2.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", persistentVMRoles1.persistentVMs[0].RoleName)); managementOperationContext2.set_OperationId(operation2.OperationTrackingId); managementOperationContext2.set_OperationStatus(operation2.Status); ManagementOperationContext managementOperationContext3 = managementOperationContext2; base.WriteObject(managementOperationContext3, true); } catch (CommunicationException communicationException3) { CommunicationException communicationException2 = communicationException3; if (communicationException2 as EndpointNotFoundException == null) { this.WriteErrorDetails(communicationException2); return; } else { throw new Exception("Cloud Service does not exist. Specify -Location or -AffinityGroup to create one."); } } this.createdDeployment = true; } } if (!this.createdDeployment && base.CurrentDeployment != null) { this.DeploymentName = base.CurrentDeployment.Name; } if (this.createdDeployment) { num = 1; } else { num = 0; } int num1 = num; Action <string> action = null; while (num1 < persistentVMRoles1.persistentVMs.Count) { if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0) { using (OperationContextScope operationContextScope2 = new OperationContextScope((IContextChannel)base.Channel)) { try { CmdletExtensions.WriteVerboseOutputForObject(this, persistentVMRoles1.persistentVMs[num1]); NewAzureVMCommand newAzureVMCommand = this; if (action == null) { action = (string s) => base.Channel.AddRole(s, this.ServiceName, this.DeploymentName, persistentVMRoles[num1]); } ((CmdletBase <IServiceManagement>)newAzureVMCommand).RetryCall(action); Operation operation3 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", persistentVMRoles1.persistentVMs[num1].RoleName)); ManagementOperationContext managementOperationContext4 = new ManagementOperationContext(); managementOperationContext4.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", persistentVMRoles1.persistentVMs[num1].RoleName)); managementOperationContext4.set_OperationId(operation3.OperationTrackingId); managementOperationContext4.set_OperationStatus(operation3.Status); ManagementOperationContext managementOperationContext5 = managementOperationContext4; base.WriteObject(managementOperationContext5, true); } catch (CommunicationException communicationException5) { CommunicationException communicationException4 = communicationException5; this.WriteErrorDetails(communicationException4); return; } } NewAzureVMCommand.NewAzureVMCommand variable1 = variable; variable1.i = variable1.i + 1; } else { return; } } return; } }