예제 #1
0
    public static bool ArpPing(string host)
    {
        try {
            IPAddress[] ips = System.Net.Dns.GetHostAddresses(host);
            if (ips.Length == 0)
            {
                return(false);
            }

            IPAddress ip = ips.First(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
            if (!IpTools.OnSameNetwork(ips[0]))
            {
                return(false);
            }

            int    len     = 6;
            byte[] mac     = new byte[len];
            byte[] byte_ip = ips[0].GetAddressBytes();
            uint   long_ip = (uint)(byte_ip[3] * 16777216 + byte_ip[2] * 65536 + byte_ip[1] * 256 + byte_ip[0]);
            SendARP(long_ip, 0, mac, ref len);

            return(true);
        } catch {
            return(false);
        }
    }
    /* Handler for clicking of ConnectNow button */
    private void ConnectNow_MouseUp(object sender, MouseButtonEventArgs e)
    {
        string     InputHost      = IPInput.Text;
        int        InputPort      = int.Parse(PortInput.Text);
        IPEndPoint InputIPEndpoit = IpTools.GetIPEndPointFromHostName(InputHost, InputPort);

        backgroundConnect.RunWorkerAsync(InputIPEndpoit);                                                               //This one is executed correctly when button is clicked
    }
예제 #3
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var bgWorker = new BackgroundWorker {
                WorkerReportsProgress = true
            };
            List <SpeedList> mItems = SpeedListView.Items.Cast <SpeedList>().ToList();

            IsEnabled = false;
            SpeedListView.Items.Clear();

            bgWorker.DoWork += (o, args) =>
            {
                int i = 0;
                foreach (SpeedList item in mItems)
                {
                    double delayTime;
                    if (item.Server.Contains("google.com") && !DnsSettings.ProxyEnable &&
                        IpTools.GeoIpLocal(MainWindow.IntIPAddr.ToString(), true).Contains("CN"))
                    {
                        bgWorker.ReportProgress(i++,
                                                new SpeedList
                        {
                            Server = item.Server, Name = item.Name, DelayTime = "PASS",
                            Asn    = IpTools.GeoIpLocal(item.Server)
                        });
                        continue;
                    }

                    if (TypeDNS)
                    {
                        delayTime = Ping.MPing(item.Server).Average();
                        if (delayTime == 0)
                        {
                            delayTime = Ping.Tcping(item.Server, 53).Average();
                        }
                    }
                    else
                    {
                        delayTime = Ping.Curl(ListStrings[i], "auroradns.github.io").Average();
                    }

                    bgWorker.ReportProgress(i++,
                                            new SpeedList
                    {
                        Server    = item.Server, Name = item.Name,
                        DelayTime = delayTime.ToString("0ms"),
                        Asn       = IpTools.GeoIpLocal(item.Server)
                    });
                }
            };
            bgWorker.ProgressChanged    += (o, args) => { SpeedListView.Items.Add((SpeedList)args.UserState); };
            bgWorker.RunWorkerCompleted += (o, args) => { IsEnabled = true; };

            bgWorker.RunWorkerAsync();
        }
    private void ReconnectTimer_Tick(object sender, EventArgs e)
    {
        /*IPInput and PortInput are names of corresponding textboxes*/
        string     InputHost      = IPInput.Text;
        int        InputPort      = int.Parse(PortInput.Text);
        IPEndPoint InputIPEndpoit = IpTools.GetIPEndPointFromHostName(InputHost, InputPort);            //That's working OK when tested separately

        backgroundConnect.DoWork             += BackgroundConnect_DoWork;
        backgroundConnect.RunWorkerCompleted += BackgroundConnect_RunWorkerCompleted;
        if (backgroundConnect.IsBusy == false)                     //In order not to call async twice, or it will throw an exception
        {
            backgroundConnect.RunWorkerAsync(InputIPEndpoit);
        }
    }
예제 #5
0
    public static string ArpRequest(IPAddress ip)
    {
        try {
            if (!IpTools.OnSameNetwork(ip))
            {
                return("");
            }

            int    len     = 6;
            byte[] mac     = new byte[len];
            byte[] byte_ip = ip.GetAddressBytes();
            uint   long_ip = (uint)(byte_ip[3] * 16777216 + byte_ip[2] * 65536 + byte_ip[1] * 256 + byte_ip[0]);
            SendARP(long_ip, 0, mac, ref len);

            return(BitConverter.ToString(mac, 0, len).Replace("-", ":"));
        } catch {
            return("");
        }
    }
예제 #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 += (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();
        }
예제 #7
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ProgressBar.Visibility = Visibility.Visible;
            var bgWorker = new BackgroundWorker {
                WorkerReportsProgress = true
            };
            List <SpeedList> mItems = SpeedListView.Items.Cast <SpeedList>().ToList();

            StratButton.IsEnabled = false;
            SpeedListView.Items.Clear();

            bgWorker.DoWork += (o, args) =>
            {
                int i = 1;
                foreach (SpeedList item in mItems)
                {
                    double delayTime;
                    if (item.Server.Contains("google.com") && !DnsSettings.ProxyEnable &&
                        IpTools.GeoIpLocal(MainWindow.IntIPAddr.ToString(), true).Contains("CN"))
                    {
                        bgWorker.ReportProgress(i++,
                                                new SpeedList
                        {
                            Server = item.Server, Name = item.Name, DelayTime = 0,
                            Asn    = IpTools.GeoIpLocal(item.Server)
                        });
                        continue;
                    }

                    if (TypeDNS)
                    {
                        delayTime = Ping.MPing(item.Server).Average();
                        if (delayTime == 0)
                        {
                            delayTime = Ping.Tcping(item.Server, 53).Average();
                        }
                    }
                    else
                    {
                        delayTime = Ping.Curl(ListStrings[i].Split('*', ',')[0].Trim(), "github.io").Average();
                    }

                    bgWorker.ReportProgress(i++,
                                            new SpeedList
                    {
                        Server    = item.Server, Name = item.Name,
                        DelayTime = Convert.ToInt32(delayTime),
                        Asn       = IpTools.GeoIpLocal(item.Server)
                    });
                }
            };
            bgWorker.ProgressChanged += (o, args) =>
            {
                SpeedListView.Items.Add((SpeedList)args.UserState);
                ProgressBar.Value = args.ProgressPercentage;
            };
            bgWorker.RunWorkerCompleted += (o, args) =>
            {
                StratButton.IsEnabled  = true;
                ProgressBar.Value      = 0;
                ProgressBar.Visibility = Visibility.Hidden;
            };

            bgWorker.RunWorkerAsync();
        }
예제 #8
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ProgressBar.Visibility = Visibility.Visible;
            var bgWorker = new BackgroundWorker {
                WorkerReportsProgress = true
            };
            List <SpeedList> mItems = SpeedListView.Items.Cast <SpeedList>().ToList();

            StratButton.IsEnabled = false;
            SpeedListView.Items.Clear();

            bgWorker.DoWork += (o, args) =>
            {
                int i = 1;
                foreach (SpeedList item in mItems)
                {
                    double delayTime;
                    if (item.Server.Contains("google.com") && !DnsSettings.ProxyEnable &&
                        IpTools.GeoIpLocal(MainWindow.IntIPAddr.ToString(), true).Contains("CN"))
                    {
                        bgWorker.ReportProgress(i++,
                                                new SpeedList
                        {
                            Server = item.Server, Name = item.Name, DelayTime = 0,
                            Asn    = IpTools.GeoIpLocal(item.Server).Trim()
                        });
                        continue;
                    }

                    try
                    {
                        if (TypeDNS)
                        {
                            //delayTime = Ping.MPing(item.Server).Average();
                            //if (delayTime == 0)
                            //    delayTime = Ping.Tcping(item.Server, 53).Average();
                            //var dnsDelayTime = Ping.DnsTest(item.Server).Average();
                            //if (dnsDelayTime > delayTime) delayTime = dnsDelayTime;
                            delayTime = Math.Round(Ping.DnsTest(item.Server).Average(), 2);
                        }
                        else
                        {
                            delayTime = Math.Round(Ping.Tcping(item.Server, 443).Average(), 2);
                        }

                        bgWorker.ReportProgress(i++,
                                                new SpeedList
                        {
                            Server    = item.Server,
                            Name      = item.Name,
                            DelayTime = delayTime,
                            Asn       = IpTools.GeoIpLocal(item.Server).Trim()
                        });
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                }
            };
            bgWorker.ProgressChanged += (o, args) =>
            {
                SpeedListView.Items.Add((SpeedList)args.UserState);
                ProgressBar.Value = args.ProgressPercentage;
            };
            bgWorker.RunWorkerCompleted += (o, args) =>
            {
                StratButton.IsEnabled  = true;
                ProgressBar.Value      = 0;
                ProgressBar.Visibility = Visibility.Hidden;
            };

            bgWorker.RunWorkerAsync();
        }
예제 #9
0
        public static async Task ServerOnQueryReceived(object sender, QueryReceivedEventArgs e)
        {
            try
            {
                if (!(e.Query is DnsMessage query))
                {
                    return;
                }

                IPAddress clientAddress = e.RemoteEndpoint.Address;
                if (DnsSettings.EDnsCustomize)
                {
                    clientAddress = Equals(DnsSettings.EDnsIp, IPAddress.Parse("0.0.0.1"))
                        ? IPAddress.Parse(MainWindow.IntIPAddr.ToString().Substring(
                                              0, MainWindow.IntIPAddr.ToString().LastIndexOf(".", StringComparison.Ordinal)) + ".1") : DnsSettings.EDnsIp;
                }
                else if (Equals(clientAddress, IPAddress.Loopback) || IpTools.InSameLaNet(clientAddress, MainWindow.LocIPAddr))
                {
                    clientAddress = MainWindow.IntIPAddr;
                }

                DnsMessage response = query.CreateResponseInstance();

                if (query.Questions.Count <= 0)
                {
                    response.ReturnCode = ReturnCode.ServerFailure;
                }
                else
                {
                    foreach (DnsQuestion dnsQuestion in query.Questions)
                    {
                        response.ReturnCode = ReturnCode.NoError;

                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog($@"| {DateTime.Now} {e.RemoteEndpoint.Address} : {dnsQuestion.Name} | {dnsQuestion.RecordType.ToString().ToUpper()}");
                        }

                        if (DomainName.Parse(new Uri(DnsSettings.HttpsDnsUrl).DnsSafeHost) == dnsQuestion.Name ||
                            DomainName.Parse(new Uri(DnsSettings.SecondHttpsDnsUrl).DnsSafeHost) == dnsQuestion.Name ||
                            DomainName.Parse(new Uri(UrlSettings.WhatMyIpApi).DnsSafeHost) == dnsQuestion.Name)
                        {
                            if (!DnsSettings.StartupOverDoH)
                            {
                                response.AnswerRecords.AddRange((await new DnsClient(DnsSettings.SecondDnsIp, 5000)
                                                                 .ResolveAsync(dnsQuestion.Name, dnsQuestion.RecordType)).AnswerRecords);
                                if (DnsSettings.DebugLog)
                                {
                                    BackgroundLog($"| -- Startup SecondDns : {DnsSettings.SecondDnsIp}");
                                }
                            }
                            else
                            {
                                response.AnswerRecords.AddRange(ResolveOverHttpsByDnsJson(clientAddress.ToString(),
                                                                                          dnsQuestion.Name.ToString(), "https://1.0.0.1/dns-query", DnsSettings.ProxyEnable,
                                                                                          DnsSettings.WProxy, dnsQuestion.RecordType).list);
                                if (DnsSettings.DebugLog)
                                {
                                    BackgroundLog("| -- Startup DoH : https://1.0.0.1/dns-query");
                                }
                            }
                        }
                        else if (DnsSettings.DnsCacheEnable && DnsCache.Contains(query))
                        {
                            response.AnswerRecords.AddRange(DnsCache.Get(query).AnswerRecords);
                            //response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("cache.auroradns.mili.one"), 0,
                            //    "AuroraDNSC Cached"));
                            if (DnsSettings.DebugLog)
                            {
                                BackgroundLog(
                                    $@"|- CacheContains : {dnsQuestion.Name} | Count : {MemoryCache.Default.Count()}");
                            }
                        }
                        else if (DnsSettings.BlackListEnable && DnsSettings.BlackList.Contains(dnsQuestion.Name))
                        {
                            response.AnswerRecords.Add(new ARecord(dnsQuestion.Name, 10, IPAddress.Any));
                            response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("blacklist.auroradns.mili.one"), 0,
                                                                     "AuroraDNSC Blocked"));

                            if (DnsSettings.DebugLog)
                            {
                                BackgroundLog(@"|- BlackList");
                            }
                        }
                        else if (DnsSettings.WhiteListEnable && DnsSettings.WhiteList.ContainsKey(dnsQuestion.Name))
                        {
                            List <DnsRecordBase> whiteRecords = new List <DnsRecordBase>();
                            if (!IpTools.IsIp(DnsSettings.WhiteList[dnsQuestion.Name]))
                            {
                                whiteRecords.AddRange((await new DnsClient(DnsSettings.SecondDnsIp, 5000)
                                                       .ResolveAsync(dnsQuestion.Name, dnsQuestion.RecordType)).AnswerRecords);
                            }
                            else
                            {
                                whiteRecords.Add(new ARecord(dnsQuestion.Name, 10,
                                                             IPAddress.Parse(DnsSettings.WhiteList[dnsQuestion.Name])));
                            }

                            response.AnswerRecords.AddRange(whiteRecords);
                            response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("whitelist.auroradns.mili.one"), 0,
                                                                     "AuroraDNSC Rewrote"));

                            if (DnsSettings.DebugLog)
                            {
                                BackgroundLog(@"|- WhiteList");
                            }
                        }
                        else if (DnsSettings.ChinaListEnable && DomainNameInChinaList(dnsQuestion.Name))
                        {
                            try
                            {
                                var resolvedDnsList = ResolveOverHttpByDPlus(dnsQuestion.Name.ToString());
                                if (resolvedDnsList != null && resolvedDnsList != new List <DnsRecordBase>())
                                {
                                    resolvedDnsList.Add(new TxtRecord(DomainName.Parse("chinalist.auroradns.mili.one"),
                                                                      0, "AuroraDNSC ChinaList - DNSPod D+"));
                                    foreach (var item in resolvedDnsList)
                                    {
                                        response.AnswerRecords.Add(item);
                                    }

                                    if (DnsSettings.DebugLog)
                                    {
                                        BackgroundLog(@"|- ChinaList - DNSPOD D+");
                                    }

                                    if (DnsSettings.DnsCacheEnable && response.ReturnCode == ReturnCode.NoError)
                                    {
                                        BackgroundWriteCache(response);
                                    }
                                }
                            }
                            catch (Exception exception)
                            {
                                BackgroundLog(exception.ToString());
                            }
                        }
                        else
                        {
                            //Resolve
                            try
                            {
                                (List <DnsRecordBase> resolvedDnsList, ReturnCode statusCode) = DnsSettings.DnsMsgEnable
                                    ? ResolveOverHttpsByDnsMsg(clientAddress.ToString(),
                                                               dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                               DnsSettings.WProxy, dnsQuestion.RecordType)
                                    : ResolveOverHttpsByDnsJson(clientAddress.ToString(),
                                                                dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                                DnsSettings.WProxy, dnsQuestion.RecordType);

                                if (resolvedDnsList != null && resolvedDnsList.Count != 0 && statusCode == ReturnCode.NoError)
                                {
                                    response.AnswerRecords.AddRange(resolvedDnsList);
                                    if (DnsSettings.DnsCacheEnable)
                                    {
                                        BackgroundWriteCache(response);
                                    }
                                }
                                else if (statusCode == ReturnCode.ServerFailure)
                                {
                                    response.AnswerRecords = (await new DnsClient(DnsSettings.SecondDnsIp, 1000)
                                                              .ResolveAsync(dnsQuestion.Name, dnsQuestion.RecordType)).AnswerRecords;
                                    BackgroundLog($"| -- SecondDns : {DnsSettings.SecondDnsIp}");
                                }
                                else
                                {
                                    response.ReturnCode = statusCode;
                                }
                            }
                            catch (Exception ex)
                            {
                                response.ReturnCode = ReturnCode.ServerFailure;
                                BackgroundLog(@"| " + ex);
                            }
                        }
                    }
                }

                if (DnsSettings.TtlRewrite &&
                    response.AnswerRecords.All(item => item.Name != DomainName.Parse("cache.auroradns.mili.one")))
                {
                    var list = response.AnswerRecords.Where(item =>
                                                            item.TimeToLive < DnsSettings.TtlMinTime - DateTime.Now.Second).ToList();
                    foreach (var item in list)
                    {
                        switch (item)
                        {
                        case ARecord aRecord:
                            response.AnswerRecords.Add(
                                new ARecord(aRecord.Name, DnsSettings.TtlMinTime, aRecord.Address));
                            response.AnswerRecords.Remove(item);
                            break;

                        case AaaaRecord aaaaRecord:
                            response.AnswerRecords.Add(
                                new ARecord(aaaaRecord.Name, DnsSettings.TtlMinTime, aaaaRecord.Address));
                            response.AnswerRecords.Remove(item);
                            break;

                        case CNameRecord cNameRecord:
                            response.AnswerRecords.Add(new CNameRecord(cNameRecord.Name, DnsSettings.TtlMinTime,
                                                                       cNameRecord.CanonicalName));
                            response.AnswerRecords.Remove(item);
                            break;
                        }
                    }

                    if (list.Count > 0)
                    {
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("ttl.auroradns.mili.one"), 600,
                                                                 $"Rewrite TTL to {DnsSettings.TtlMinTime}"));
                    }
                }

                e.Response = response;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                BackgroundLog(exception.ToString());
            }
        }
예제 #10
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";
            }
        }
예제 #11
0
        public static async Task ServerOnQueryReceived(object sender, QueryReceivedEventArgs e)
        {
            if (!(e.Query is DnsMessage query))
            {
                return;
            }

            IPAddress clientAddress = e.RemoteEndpoint.Address;

            if (DnsSettings.EDnsCustomize)
            {
                clientAddress = Equals(DnsSettings.EDnsIp, IPAddress.Parse("0.0.0.1"))
                    ? IPAddress.Parse(MainWindow.IntIPAddr.ToString().Substring(
                                          0, MainWindow.IntIPAddr.ToString().LastIndexOf(".", StringComparison.Ordinal)) + ".0") : DnsSettings.EDnsIp;
            }
            else if (Equals(clientAddress, IPAddress.Loopback) || IpTools.InSameLaNet(clientAddress, MainWindow.LocIPAddr))
            {
                clientAddress = MainWindow.IntIPAddr;
            }

            DnsMessage response = query.CreateResponseInstance();

            if (query.Questions.Count <= 0)
            {
                response.ReturnCode = ReturnCode.ServerFailure;
            }

            else
            {
                foreach (DnsQuestion dnsQuestion in query.Questions)
                {
                    response.ReturnCode = ReturnCode.NoError;

                    if (DnsSettings.DebugLog)
                    {
                        BgwLog($@"| {DateTime.Now} {e.RemoteEndpoint.Address} : {dnsQuestion.Name} | {dnsQuestion.RecordType.ToString().ToUpper()}");
                    }

                    if (DnsSettings.BlackListEnable && BlackList.Contains(dnsQuestion.Name) && dnsQuestion.RecordType == RecordType.A)
                    {
                        //BlackList
                        ARecord blackRecord = new ARecord(dnsQuestion.Name, 10, IPAddress.Any);
                        response.AnswerRecords.Add(blackRecord);
                        if (DnsSettings.DebugLog)
                        {
                            BgwLog(@"|- BlackList");
                        }
                    }
                    else if (DnsSettings.WhiteListEnable && WhiteList.ContainsKey(dnsQuestion.Name) && dnsQuestion.RecordType == RecordType.A)
                    {
                        //WhiteList
                        ARecord blackRecord = new ARecord(dnsQuestion.Name, 10, WhiteList[dnsQuestion.Name]);
                        response.AnswerRecords.Add(blackRecord);
                        if (DnsSettings.DebugLog)
                        {
                            BgwLog(@"|- WhiteList");
                        }
                    }
                    else
                    {
                        //Resolve
                        try
                        {
                            var(resolvedDnsList, statusCode) = ResolveOverHttps(clientAddress.ToString(),
                                                                                dnsQuestion.Name.ToString(), DnsSettings.ProxyEnable, DnsSettings.WProxy, dnsQuestion.RecordType);
                            if (resolvedDnsList != null && resolvedDnsList != new List <dynamic>() && statusCode == ReturnCode.NoError)
                            {
                                foreach (var item in resolvedDnsList)
                                {
                                    response.AnswerRecords.Add(item);
                                }
                            }
                            else if (statusCode == ReturnCode.ServerFailure)
                            {
                                response.AnswerRecords = new DnsClient(DnsSettings.SecondDnsIp, 1000)
                                                         .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords;
                                BgwLog($"| -- SecondDns {DnsSettings.SecondDnsIp}");
                            }
                            else
                            {
                                response.ReturnCode = statusCode;
                            }
                        }
                        catch (Exception ex)
                        {
                            response.ReturnCode = ReturnCode.ServerFailure;
                            BgwLog(@"| " + ex);
                        }
                    }
                }
            }

            e.Response = response;
        }
예제 #12
0
        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";
            }
        }
예제 #13
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";
            }
        }
예제 #14
0
        public static async Task ServerOnQueryReceived(object sender, QueryReceivedEventArgs e)
        {
            if (!(e.Query is DnsMessage query))
            {
                return;
            }

            IPAddress clientAddress = e.RemoteEndpoint.Address;

            if (DnsSettings.EDnsCustomize)
            {
                clientAddress = Equals(DnsSettings.EDnsIp, IPAddress.Parse("0.0.0.1"))
                    ? IPAddress.Parse(MainWindow.IntIPAddr.ToString().Substring(
                                          0, MainWindow.IntIPAddr.ToString().LastIndexOf(".", StringComparison.Ordinal)) + ".1") : DnsSettings.EDnsIp;
            }
            else if (Equals(clientAddress, IPAddress.Loopback) || IpTools.InSameLaNet(clientAddress, MainWindow.LocIPAddr))
            {
                clientAddress = MainWindow.IntIPAddr;
            }

            DnsMessage response = query.CreateResponseInstance();

            if (query.Questions.Count <= 0)
            {
                response.ReturnCode = ReturnCode.ServerFailure;
            }

            else
            {
                foreach (DnsQuestion dnsQuestion in query.Questions)
                {
                    response.ReturnCode = ReturnCode.NoError;

                    if (DnsSettings.DebugLog)
                    {
                        BackgroundLog($@"| {DateTime.Now} {e.RemoteEndpoint.Address} : {dnsQuestion.Name} | {dnsQuestion.RecordType.ToString().ToUpper()}");
                    }

                    if (DnsSettings.DnsCacheEnable && MemoryCache.Default.Contains($"{dnsQuestion.Name}{dnsQuestion.RecordType}"))
                    {
                        response.AnswerRecords.AddRange(
                            (List <DnsRecordBase>)MemoryCache.Default.Get($"{dnsQuestion.Name}{dnsQuestion.RecordType}"));
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("cache.auroradns.mili.one"), 0, "AuroraDNSC Cached"));
                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog($@"|- CacheContains : {dnsQuestion.Name} | Count : {MemoryCache.Default.Count()}");
                        }
                    }
                    else if (DnsSettings.BlackListEnable && DnsSettings.BlackList.Contains(dnsQuestion.Name) && dnsQuestion.RecordType == RecordType.A)
                    {
                        response.AnswerRecords.Add(new ARecord(dnsQuestion.Name, 10, IPAddress.Any));
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("blacklist.auroradns.mili.one"), 0, "AuroraDNSC Blocked"));
                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog(@"|- BlackList");
                        }
                    }
                    else if (DnsSettings.WhiteListEnable && DnsSettings.WhiteList.ContainsKey(dnsQuestion.Name) && dnsQuestion.RecordType == RecordType.A)
                    {
                        List <DnsRecordBase> whiteRecords = new List <DnsRecordBase>();
                        if (!IpTools.IsIp(DnsSettings.WhiteList[dnsQuestion.Name]))
                        {
                            whiteRecords.AddRange(new DnsClient(DnsSettings.SecondDnsIp, 1000)
                                                  .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords);
                        }
                        else
                        {
                            whiteRecords.Add(new ARecord(dnsQuestion.Name, 10,
                                                         IPAddress.Parse(DnsSettings.WhiteList[dnsQuestion.Name])));
                        }

                        response.AnswerRecords.AddRange(whiteRecords);
                        response.AnswerRecords.Add(new TxtRecord(DomainName.Parse("whitelist.auroradns.mili.one"), 0, "AuroraDNSC Rewrote"));
                        if (DnsSettings.DebugLog)
                        {
                            BackgroundLog(@"|- WhiteList");
                        }
                    }
                    else
                    {
                        //Resolve
                        try
                        {
                            (List <DnsRecordBase> resolvedDnsList, ReturnCode statusCode) = DnsSettings.DnsMsgEnable
                                ? ResolveOverHttpsByDnsMsg(clientAddress.ToString(),
                                                           dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                           DnsSettings.WProxy, dnsQuestion.RecordType)
                                : ResolveOverHttpsByDnsJson(clientAddress.ToString(),
                                                            dnsQuestion.Name.ToString(), DnsSettings.HttpsDnsUrl, DnsSettings.ProxyEnable,
                                                            DnsSettings.WProxy, dnsQuestion.RecordType);

                            if (resolvedDnsList != null && resolvedDnsList.Count != 0 && statusCode == ReturnCode.NoError)
                            {
                                response.AnswerRecords.AddRange(resolvedDnsList);

                                if (DnsSettings.DnsCacheEnable)
                                {
                                    BackgroundWriteCache(
                                        new CacheItem($"{dnsQuestion.Name}{dnsQuestion.RecordType}", resolvedDnsList),
                                        resolvedDnsList[0].TimeToLive);
                                }
                            }
                            else if (statusCode == ReturnCode.ServerFailure)
                            {
                                response.AnswerRecords = new DnsClient(DnsSettings.SecondDnsIp, 1000)
                                                         .Resolve(dnsQuestion.Name, dnsQuestion.RecordType).AnswerRecords;
                                BackgroundLog($"| -- SecondDns : {DnsSettings.SecondDnsIp}");
                            }
                            else
                            {
                                response.ReturnCode = statusCode;
                            }
                        }
                        catch (Exception ex)
                        {
                            response.ReturnCode = ReturnCode.ServerFailure;
                            BackgroundLog(@"| " + ex);
                        }
                    }
                }
            }
            e.Response = response;
        }
예제 #15
0
        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";
            }
        }