Esempio n. 1
0
        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())
                {
                    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, 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 += (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();
        }
Esempio n. 2
0
        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.Loopback))
                    {
                        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) =>
            {
                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();
            if (IsSysDns.IsChecked == true)
            {
                IsSysDns.ToolTip = "已设为系统 DNS";
            }
        }
        private void ButtonSave_OnClick(object sender, RoutedEventArgs e)
        {
            DnsSettings.DebugLog           = Convert.ToBoolean(Log.IsChecked);
            DnsSettings.EDnsCustomize      = Convert.ToBoolean(EDNSCustomize.IsChecked);
            DnsSettings.DnsCacheEnable     = Convert.ToBoolean(DNSCache.IsChecked);
            DnsSettings.WhiteListEnable    = Convert.ToBoolean(WhiteList.IsChecked);
            DnsSettings.ProxyEnable        = Convert.ToBoolean(Proxy.IsChecked);
            DnsSettings.AutoCleanLogEnable = Convert.ToBoolean(AutoClean.IsChecked);
            DnsSettings.DnsMsgEnable       = Convert.ToBoolean(DNSMsg.IsChecked);
            DnsSettings.Http2Enable        = Convert.ToBoolean(HTTP2Client.IsChecked);

            if (!string.IsNullOrWhiteSpace(DoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(SecondDoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(SecondDNS.Text) &&
                !string.IsNullOrWhiteSpace(EDNSClientIP.Text) &&
                !string.IsNullOrWhiteSpace(ListenIP.Text))
            {
                DnsSettings.HttpsDnsUrl       = DoHUrlText.Text.Trim();
                DnsSettings.SecondHttpsDnsUrl = SecondDoHUrlText.Text.Trim();
                DnsSettings.SecondDnsIp       = IPAddress.Parse(SecondDNS.Text);
                DnsSettings.EDnsIp            = IPAddress.Parse(EDNSClientIP.Text);
                DnsSettings.ListenIp          = IPAddress.Parse(ListenIP.Text);

                if (Proxy.IsChecked == true)
                {
                    DnsSettings.WProxy = new WebProxy(ProxyServer.Text + ":" + ProxyServerPort.Text);
                }
                else
                {
                    DnsSettings.WProxy = new WebProxy("127.0.0.1:80");
                }

                if (DnsSettings.BlackListEnable && File.Exists("black.list"))
                {
                    DnsSettings.ReadBlackList(MainWindow.SetupBasePath + "black.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(MainWindow.SetupBasePath + "china.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("white.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("rewrite.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "rewrite.list");
                }

                File.WriteAllText($"{MainWindow.SetupBasePath}config.json",
                                  "{\n" +
                                  $"\"Listen\" : \"{DnsSettings.ListenIp}\",\n" +
                                  $"\"SecondDns\" : \"{DnsSettings.SecondDnsIp}\",\n" +
                                  $"\"BlackList\" : {DnsSettings.BlackListEnable.ToString().ToLower()},\n" +
                                  $"\"ChinaList\" : {DnsSettings.ChinaListEnable.ToString().ToLower()},\n" +
                                  $"\"RewriteList\" : {DnsSettings.WhiteListEnable.ToString().ToLower()},\n" +
                                  $"\"DebugLog\" : {DnsSettings.DebugLog.ToString().ToLower()},\n" +
                                  $"\"EDnsCustomize\" : {DnsSettings.EDnsCustomize.ToString().ToLower()},\n" +
                                  $"\"EDnsClientIp\" : \"{DnsSettings.EDnsIp}\",\n" +
                                  $"\"ProxyEnable\" : {DnsSettings.ProxyEnable.ToString().ToLower()},\n" +
                                  $"\"HttpsDns\" : \"{DnsSettings.HttpsDnsUrl.Trim()}\",\n" +
                                  $"\"SecondHttpsDns\" : \"{DnsSettings.SecondHttpsDnsUrl}\",\n" +
                                  $"\"Proxy\" : \"{ProxyServer.Text + ":" + ProxyServerPort.Text}\",\n" +
                                  $"\"EnableDnsCache\" : {DnsSettings.DnsCacheEnable.ToString().ToLower()},\n" +
                                  $"\"EnableDnsMessage\" : {DnsSettings.DnsMsgEnable.ToString().ToLower()},\n" +
                                  $"\"EnableAutoCleanLog\" : {DnsSettings.AutoCleanLogEnable.ToString().ToLower()},\n" +
                                  $"\"EnableHttp2\" : {DnsSettings.Http2Enable.ToString().ToLower()} \n" +
                                  "}");
                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"设置已保存!"
                });
            }
            else
            {
                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"不应为空,请填写完全。"
                });
            }
        }
        public void ButtonSave_OnClick(object sender, RoutedEventArgs e)
        {
            DnsSettings.DebugLog           = Convert.ToBoolean(Log.IsChecked);
            DnsSettings.EDnsCustomize      = Convert.ToBoolean(EDNSCustomize.IsChecked);
            DnsSettings.DnsCacheEnable     = Convert.ToBoolean(DNSCache.IsChecked);
            DnsSettings.WhiteListEnable    = Convert.ToBoolean(WhiteList.IsChecked);
            DnsSettings.ProxyEnable        = Convert.ToBoolean(Proxy.IsChecked);
            DnsSettings.AutoCleanLogEnable = Convert.ToBoolean(AutoClean.IsChecked);
            DnsSettings.DnsMsgEnable       = Convert.ToBoolean(DNSMsg.IsChecked);
            DnsSettings.Http2Enable        = Convert.ToBoolean(HTTP2Client.IsChecked);
            DnsSettings.TtlRewrite         = Convert.ToBoolean(MinimumTTL.IsChecked);

            if (!string.IsNullOrWhiteSpace(DoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(SecondDoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(EDNSClientIP.Text) &&
                !string.IsNullOrWhiteSpace(ListenIP.Text))
            {
                if (string.IsNullOrWhiteSpace(SecondDNS.Text))
                {
                    DnsSettings.StartupOverDoH = true;
                    DnsSettings.SecondDnsIp    = IPAddress.Any;
                }
                else
                {
                    DnsSettings.SecondDnsIp = IPAddress.Parse(SecondDNS.Text);
                }

                DnsSettings.HttpsDnsUrl       = DoHUrlText.Text.Trim();
                DnsSettings.SecondHttpsDnsUrl = SecondDoHUrlText.Text.Trim();
                DnsSettings.EDnsIp            = IPAddress.Parse(EDNSClientIP.Text);
                DnsSettings.ListenIp          = IPAddress.Parse(ListenIP.Text);

                DnsSettings.WProxy = Proxy.IsChecked == true
                    ? new WebProxy(ProxyServer.Text + ":" + ProxyServerPort.Text)
                    : new WebProxy("127.0.0.1:1080");

                if (DnsSettings.BlackListEnable && File.Exists("black.list"))
                {
                    DnsSettings.ReadBlackList(MainWindow.SetupBasePath + "black.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(MainWindow.SetupBasePath + "china.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("white.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("rewrite.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "rewrite.list");
                }

                try
                {
                    File.WriteAllText($"{MainWindow.SetupBasePath}config.json",
                                      "{\n" +
                                      $"\"Listen\" : \"{DnsSettings.ListenIp}\",\n" +
                                      $"\"SecondDns\" : \"{DnsSettings.SecondDnsIp}\",\n" +
                                      $"\"BlackList\" : {DnsSettings.BlackListEnable.ToString().ToLower()},\n" +
                                      $"\"ChinaList\" : {DnsSettings.ChinaListEnable.ToString().ToLower()},\n" +
                                      $"\"RewriteList\" : {DnsSettings.WhiteListEnable.ToString().ToLower()},\n" +
                                      $"\"DebugLog\" : {DnsSettings.DebugLog.ToString().ToLower()},\n" +
                                      $"\"EDnsCustomize\" : {DnsSettings.EDnsCustomize.ToString().ToLower()},\n" +
                                      $"\"EDnsClientIp\" : \"{DnsSettings.EDnsIp}\",\n" +
                                      $"\"ProxyEnable\" : {DnsSettings.ProxyEnable.ToString().ToLower()},\n" +
                                      $"\"HttpsDns\" : \"{DnsSettings.HttpsDnsUrl.Trim()}\",\n" +
                                      $"\"SecondHttpsDns\" : \"{DnsSettings.SecondHttpsDnsUrl}\",\n" +
                                      $"\"Proxy\" : \"{ProxyServer.Text + ":" + ProxyServerPort.Text}\",\n" +
                                      $"\"EnableDnsCache\" : {DnsSettings.DnsCacheEnable.ToString().ToLower()},\n" +
                                      $"\"EnableDnsMessage\" : {DnsSettings.DnsMsgEnable.ToString().ToLower()},\n" +
                                      $"\"EnableAutoCleanLog\" : {DnsSettings.AutoCleanLogEnable.ToString().ToLower()},\n" +
                                      $"\"Ipv6Disable\" : {DnsSettings.Ipv6Disable.ToString().ToLower()},\n" +
                                      $"\"Ipv4Disable\" : {DnsSettings.Ipv4Disable.ToString().ToLower()},\n" +
                                      $"\"StartupOverDoH\" : {DnsSettings.StartupOverDoH.ToString().ToLower()},\n" +
                                      $"\"AllowSelfSignedCert\" : {DnsSettings.AllowSelfSignedCert.ToString().ToLower()},\n" +
                                      $"\"AllowAutoRedirect\" : {DnsSettings.AllowAutoRedirect.ToString().ToLower()},\n" +
                                      $"\"HTTPStatusNotify\" : {DnsSettings.HTTPStatusNotify.ToString().ToLower()},\n" +
                                      $"\"TTLRewrite\" : {DnsSettings.TtlRewrite.ToString().ToLower()},\n" +
                                      $"\"TTLMinTime\" : {DnsSettings.TtlMinTime.ToString().ToLower()},\n" +
                                      $"\"EnableHttp2\" : {DnsSettings.Http2Enable.ToString().ToLower()} \n" +
                                      "}");
                }
                catch (UnauthorizedAccessException exp)
                {
                    MessageBoxResult msgResult =
                        MessageBox.Show(
                            "Error: 尝试写入配置文权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                            $"{Environment.NewLine}Original error: {exp}");
                    if (msgResult == MessageBoxResult.OK)
                    {
                        new MainWindow().RunAsAdmin();
                    }
                    else
                    {
                        Close();
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show($"Error: 尝试写入配置文件错误{Environment.NewLine}Original error: {exp}");
                }

                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"设置已保存!"
                });
            }
            else
            {
                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"不应为空,请填写完全。"
                });
            }
        }
Esempio n. 5
0
        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";
            }
        }