private void IsSysDns_Checked(object sender, RoutedEventArgs e)
 {
     if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
     {
         SysDnsSet.SetDns("127.0.0.1", DnsSettings.SecondDnsIp.ToString());
         Snackbar.MessageQueue.Enqueue(new TextBlock()
         {
             Text = "主DNS:" + IPAddress.Loopback +
                    Environment.NewLine +
                    "辅DNS:" + DnsSettings.SecondDnsIp
         });
         IsSysDns.ToolTip = "已设为系统 DNS";
     }
     else
     {
         var snackbarMsg = new SnackbarMessage()
         {
             Content       = "权限不足",
             ActionContent = "Administrator权限运行",
         };
         snackbarMsg.ActionClick += RunAsAdmin_OnActionClick;
         Snackbar.MessageQueue.Enqueue(snackbarMsg);
         IsSysDns.IsChecked = false;
     }
 }
        private void IsSysDns_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MyTools.IsNslookupLocDns())
                {
                    if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        SysDnsSet.ResetDns();
                        Snackbar.MessageQueue.Enqueue(new TextBlock {
                            Text = "已将 DNS 重置为自动获取"
                        });
                    }
                    else
                    {
                        SysDnsSet.ResetDnsCmd();
                        Snackbar.MessageQueue.Enqueue(new TextBlock {
                            Text = "已通过 Netsh 将 DNS 重置为自动获取"
                        });
                    }

                    IsSysDns.ToolTip   = "设为系统 DNS";
                    IsSysDns.IsChecked = false;
                }
                else
                {
                    if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(
                            WindowsBuiltInRole.Administrator))
                    {
                        SysDnsSet.SetDns(IPAddress.Loopback.ToString(), DnsSettings.SecondDnsIp.ToString());
                        IsSysDns.ToolTip = "已设为系统 DNS";
                    }
                    else
                    {
                        SysDnsSet.SetDnsCmd(IPAddress.Loopback.ToString(), DnsSettings.SecondDnsIp.ToString());
                        Snackbar.MessageQueue.Enqueue(new TextBlock {
                            Text = "已通过 Netsh 设为系统 DNS"
                        });
                    }

                    Snackbar.MessageQueue.Enqueue(new TextBlock
                    {
                        Text = "主DNS:" + IPAddress.Loopback +
                               Environment.NewLine +
                               "辅DNS:" + DnsSettings.SecondDnsIp
                    });

                    IsSysDns.ToolTip   = "已设为系统 DNS";
                    IsSysDns.IsChecked = true;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
        }
 private void IsSysDns_Unchecked(object sender, RoutedEventArgs e)
 {
     if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
     {
         SysDnsSet.ResetDns();
         Snackbar.MessageQueue.Enqueue(new TextBlock()
         {
             Text = "已将 DNS 重置为自动获取"
         });
         IsSysDns.ToolTip = "设为系统 DNS";
     }
 }
示例#4
0
        private void ExitResetItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (new WindowsPrincipal(WindowsIdentity.GetCurrent())
                    .IsInRole(WindowsBuiltInRole.Administrator))
                {
                    SysDnsSet.ResetDns();
                }
                else
                {
                    SysDnsSet.ResetDnsCmd();
                }
                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)
                {
                    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 exception)
            {
                Console.WriteLine(exception);
            }

            try
            {
                Close();
                Environment.Exit(0);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
            }
        }
示例#5
0
        private void IsSysDns_Checked(object sender, RoutedEventArgs e)
        {
            if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
            {
                SysDnsSet.SetDns("127.0.0.1", DnsSettings.SecondDnsIp.ToString());
            }
            else
            {
                SysDnsSet.SetDnsCmd("127.0.0.1", DnsSettings.SecondDnsIp.ToString());
                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = "已通过 Netsh 设置"
                });
            }

            IsSysDns.ToolTip = "已设为系统 DNS";
            Snackbar.MessageQueue.Enqueue(new TextBlock()
            {
                Text = "主DNS:" + IPAddress.Loopback +
                       Environment.NewLine +
                       "辅DNS:" + DnsSettings.SecondDnsIp
            });
        }
示例#6
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 += (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 (!MDnsSvrTask.IsCompleted)
                {
                    MDnsServer.Stop();
                }
                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 exitResetItem = new WinFormMenuItem("退出并重置系统 DNS", (sender, args) =>
            {
                try
                {
                    if (new WindowsPrincipal(WindowsIdentity.GetCurrent())
                        .IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        SysDnsSet.ResetDns();
                    }
                    else
                    {
                        SysDnsSet.ResetDnsCmd();
                    }
                    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)
                    {
                        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);
                }

                try
                {
                    Close();
                    Environment.Exit(0);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
            });
            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)
                    {
                        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);
                }

                try
                {
                    Close();
                    Environment.Exit(0);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
            });

            NotifyIcon.ContextMenu =
                new WinFormContextMenu(new[]
            {
                showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem,
                new WinFormMenuItem("-"), restartItem, exitResetItem, exitItem
            });

            NotifyIcon.DoubleClick += MinimizedNormal;

            IsSysDns.IsChecked = MyTools.IsNslookupLocDns();
        }