public void MessageBytesTest()
        {
            var message = new DnsMessage();

            message.Header = new DnsHeader()
            {
                ID      = 1234,
                QR      = 0,
                QDCOUNT = 1,
                ANCOUNT = 1,
            };
            message.Question = new DnsQuestion()
            {
                QClass = 1,
                QType  = 1,
                Name   = "f00.test",
            };
            message.Answer.Add(new ARecord("f00.test", "127.0.0.2")
            {
                RClass = 1,
                Ttl    = 10,
            });
            Console.WriteLine(message.ToMultiString());

            Console.WriteLine($"Header is {message.Header.ToBytes().Length} bytes.");
            Console.WriteLine($"Question is {message.Question.ToBytes().Length} bytes.");

            var messageBytes = DnsUtils.DnsMessageToBytes(message);

            Console.WriteLine($"Message is {messageBytes.Length} bytes");

            var message2 = DnsUtils.ReadDnsMessage(messageBytes);

            Console.WriteLine(message2.ToMultiString());
        }
Exemple #2
0
        /// <summary>
        ///     Resolve <see cref="ProcessingContext.ServerEndPoint" /> based on <see cref="ProcessingContext.RequestHeader" />,
        ///     establish connection to destination server and open <see cref="ProcessingContext.ServerStream" />.
        ///     <see cref="ProcessingContext.RequestHeader" /> should be defined.
        /// </summary>
        /// <param name="context">current request context</param>
        protected virtual void ConnectToServer(ProcessingContext context)
        {
            Contract.Requires <ArgumentNullException>(context != null, "context");
            Contract.Requires <InvalidContextException>(context.RequestHeader != null, "RequestHeader");

            context.ServerEndPoint = DnsUtils.ResolveRequestEndpoint(context.RequestHeader, _defaultPort);

            context.ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                ReceiveTimeout = (Int32)ServerReadTimeout.TotalMilliseconds,
                SendTimeout    = (Int32)ServerWriteTimeout.TotalMilliseconds
            };

            context.ServerSocket.Connect(context.ServerEndPoint.Host, context.ServerEndPoint.Port);

            context.ServerStream = new NetworkStream(context.ServerSocket, true);

            if (Logger.IsDebugEnabled)
            {
                Logger.DebugFormat("Connection Established: {0}:{1}",
                                   context.ServerEndPoint.Host,
                                   context.ServerEndPoint.Port
                                   );
            }
        }
        public void Response2Test()
        {
            byte[] messageBytes = File.ReadAllBytes(Path.Combine("Files", "dns-02-response.dat"));
            var    message      = DnsUtils.ReadDnsMessage(messageBytes);

            Console.WriteLine(message.ToMultiString());
        }
Exemple #4
0
        public void TestParseLocalDomainName()
        {
            var domainName = DnsUtils.GetDomainName();

            Log.Info("domain is '{0}'", domainName);

            domainName.ShouldNotBeEmpty();
        }
Exemple #5
0
        /// <summary>
        /// Create new header from ByteReader.
        /// </summary>
        public static DnsQuestion FromByteReader(ByteReader byteReader)
        {
            var question = new DnsQuestion();

            question.Name   = DnsUtils.ReadName(byteReader);
            question.QType  = byteReader.GetUshort();
            question.QClass = byteReader.GetUshort();

            return(question);
        }
    public static async Task <NatTypeTestResult> DiscoveryNatTypeAsync(Socks5Server socks5, CancellationToken ctx = default)
    {
        var stunServer = Global.Settings.STUN_Server;
        var port       = (ushort)Global.Settings.STUN_Server_Port;
        var local      = new IPEndPoint(IPAddress.Any, 0);

        var socks5Option = new Socks5CreateOption
        {
            Address          = await DnsUtils.LookupAsync(socks5.Hostname),
            Port             = socks5.Port,
            UsernamePassword = new UsernamePassword
            {
                UserName = socks5.Username,
                Password = socks5.Password
            }
        };

        var ip = await DnsUtils.LookupAsync(stunServer);

        if (ip == null)
        {
            return(new NatTypeTestResult {
                Result = "Wrong STUN Server!"
            });
        }

        using IUdpProxy proxy = ProxyFactory.CreateProxy(ProxyType.Socks5, new IPEndPoint(IPAddress.Loopback, 0), socks5Option);
        using var client      = new StunClient5389UDP(new IPEndPoint(ip, port), local, proxy);

        await client.ConnectProxyAsync(ctx);

        try
        {
            await client.QueryAsync(ctx);
        }
        finally
        {
            await client.CloseProxyAsync(ctx);
        }

        var res    = client.State;
        var result = GetSimpleResult(res);

        return(new NatTypeTestResult
        {
            Result = result,
            LocalEnd = res.LocalEndPoint?.ToString(),
            PublicEnd = res.PublicEndPoint?.ToString()
        });
    }
Exemple #7
0
        /// <summary>
        ///     Resolve <see cref="ProcessingContext.ServerEndPoint" /> based on <see cref="ProcessingContext.RequestHeader" />,
        ///     establish connection to destination server and open <see cref="ProcessingContext.ServerStream" />.
        ///     <see cref="ProcessingContext.RequestHeader" /> should be defined.
        /// </summary>
        /// <param name="context">current request context</param>
        protected virtual void ConnectToServer(ProcessingContext context)
        {
            ContractUtils.Requires <ArgumentNullException>(context != null, "context");
            ContractUtils.Requires <InvalidContextException>(context.RequestHeader != null, "RequestHeader");

            context.ServerEndPoint = DnsUtils.ResolveRequestEndpoint(context.RequestHeader, _defaultPort);

            bool requiresNewSocket = true;

            if (EnableKeepAlive && activeSockets.ContainsKey(context.ServerEndPoint))
            {
                context.ServerSocket = activeSockets[context.ServerEndPoint];
                if (context.ServerSocket.IsConnected())
                {
                    requiresNewSocket = false;
                }
                else
                {
                    context.ServerSocket.Close();
                    activeSockets.Remove(context.ServerEndPoint);
                    OnLog(LogLevel.Debug, "Server socket appears disconnected. Requiring new socket.");
                }
            }

            if (requiresNewSocket)
            {
                context.ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveTimeout = (int)ServerReadTimeout.TotalMilliseconds,
                    SendTimeout    = (int)ServerWriteTimeout.TotalMilliseconds
                };

                context.ServerSocket.Connect(context.ServerEndPoint.Host, context.ServerEndPoint.Port);
                if (EnableKeepAlive)
                {
                    activeSockets[context.ServerEndPoint] = context.ServerSocket;
                }
            }

            context.ServerStream = new NetworkStream(context.ServerSocket, !EnableKeepAlive);

            OnLog(LogLevel.Debug,
                  "Connection Established: {0}:{1}",
                  context.ServerEndPoint.Host,
                  context.ServerEndPoint.Port
                  );
        }
Exemple #8
0
 /// <summary>
 /// Parses a specified DNS stamp string (<seealso cref="dnsStampStr"/>)
 /// </summary>
 /// <param name="dnsStampStr">DNS stamp string</param>
 /// <returns>DNS stamp as a <see cref="DnsStamp"/> instance</returns>
 public DnsStamp ParseDnsStamp(string dnsStampStr)
 {
     lock (SYNC_ROOT)
     {
         try
         {
             LOG.InfoFormat("Parsing DNS stamp");
             DnsStamp dnsStamp = DnsUtils.ParseDnsStamp(dnsStampStr);
             LOG.InfoFormat("Parsing DNS stamp has been successfully completed");
             return(dnsStamp);
         }
         catch (Exception ex)
         {
             LOG.ErrorFormat("Parsing DNS stamp failed with an error", ex);
             return(null);
         }
     }
 }
Exemple #9
0
 /// <summary>
 /// Checks if upstream is valid and available
 /// </summary>
 /// <param name="upstreamOptions">Upstream options
 /// (<seealso cref="UpstreamOptions"/>)</param>
 /// <exception cref="InvalidOperationException"></exception>
 /// <returns>True, if test has completed successfully,
 /// otherwise false</returns>
 public bool TestUpstream(UpstreamOptions upstreamOptions)
 {
     lock (SYNC_ROOT)
     {
         try
         {
             LOG.InfoFormat("Testing upstream");
             bool result = DnsUtils.TestUpstream(upstreamOptions);
             LOG.InfoFormat("Testing upstream has been successfully completed");
             return(result);
         }
         catch (Exception ex)
         {
             LOG.ErrorFormat("Testing upstream failed with an error", ex);
             return(false);
         }
     }
 }
Exemple #10
0
        /// <summary>
        ///     测试延迟
        /// </summary>
        /// <returns>延迟</returns>
        public async Task <int> PingAsync()
        {
            try
            {
                var destination = await DnsUtils.LookupAsync(Hostname);

                if (destination == null)
                {
                    return(Delay = -2);
                }

                var list = new Task <int> [3];
                for (var i = 0; i < 3; i++)
                {
                    async Task <int> PingCoreAsync()
                    {
                        try
                        {
                            return(Global.Settings.ServerTCPing
                                ? await Utils.Utils.TCPingAsync(destination, Port)
                                : await Utils.Utils.ICMPingAsync(destination));
                        }
                        catch (Exception)
                        {
                            return(-4);
                        }
                    }

                    list[i] = PingCoreAsync();
                }

                var resTask = await Task.WhenAny(list[0], list[1], list[2]);

                return(Delay = await resTask);
            }
            catch (Exception)
            {
                return(Delay = -4);
            }
        }
Exemple #11
0
        public static string MakeDefaultTransport()
        {
            var env = Environment.GetEnvironmentVariable("LOG4NET_SMTP_CONFIG");

            if (!string.IsNullOrEmpty(env))
            {
                LogLog.Debug(typeof(SmtpClientFactory), string.Format("Using environment based configuration '{0}", env));
                return(env);
            }
            else
            {
                var domain = DnsUtils.GetDomainName();
                if (!string.IsNullOrEmpty(domain))
                {
                    var mxs      = DnsQuery.QueryMx(domain);
                    var mxRecord = mxs.OrderBy(mx => mx.Preference).FirstOrDefault();
                    if (mxRecord != null && !string.IsNullOrEmpty(mxRecord.Name))
                    {
                        return(string.Format("smtp://smtp.{0}", mxRecord.Name));
                    }
                    else
                    {
                        LogLog.Debug(
                            typeof(SmtpClientFactory),
                            string.Format(
                                "The domain '{0}' has no MX record, using localhost as the SMTP smart host", domain));
                        return("smtp://localhost");
                    }
                }
                else
                {
                    LogLog.Debug(
                        typeof(SmtpClientFactory),
                        "The machine has no domain name (primary DNS suffix), using localhost as the SMTP smart host");
                    return("smtp://localhost");
                }
            }
        }
        /// <summary>
        ///     Attempt to make a default SMTP transport URI. The URI is defaulted in the following
        ///     order:
        ///     <list type="bullet">
        ///         <item>From the environment variable 'NLOG_SMTP_CONFIG'</item>
        ///         <item>By querying if the host has a domain MX record</item>
        ///         <item>A local SMTP start host on port 25 with no authentication (e.g. IIS SMTP mailer)</item>
        ///     </list>
        /// </summary>
        public static string MakeDefaultTransport()
        {
            var env = Environment.GetEnvironmentVariable("NLOG_SMTP_CONFIG");

            if (!string.IsNullOrEmpty(env))
            {
                InternalLogger.Debug("Using environment based configuration '{0}", env);
                return(env);
            }
            else
            {
                var domain = DnsUtils.GetDomainName();
                if (!string.IsNullOrEmpty(domain))
                {
                    var mxs      = DnsQuery.QueryMx(domain);
                    var mxRecord = mxs
                                   .OrderBy(mx => mx.Preference)
                                   .FirstOrDefault();
                    if (!string.IsNullOrEmpty(mxRecord?.Name))
                    {
                        return($"smtp://{mxRecord.Name}");
                    }
                    else
                    {
                        InternalLogger.Debug(
                            "The domain '{0}' has no MX record, using localhost as the SMTP smart host", domain);
                        return("smtp://localhost");
                    }
                }
                else
                {
                    InternalLogger.Debug(
                        "The machine has no domain name (primary DNS suffix), using localhost as the SMTP smart host");
                    return("smtp://localhost");
                }
            }
        }
Exemple #13
0
 public static async Task <string> AutoResolveHostnameAsync(this Server server, AddressFamily inet = AddressFamily.Unspecified)
 {
     // ! MainController cached
     return((await DnsUtils.LookupAsync(server.Hostname, inet)) !.ToString());
 }
Exemple #14
0
        /// <summary>
        /// Gets current DNS proxy version
        /// </summary>
        /// <returns></returns>
        public string GetDnsProxyVersion()
        {
            string dnsProxyVersion = DnsUtils.GetDnsProxyVersion();

            return(dnsProxyVersion);
        }
Exemple #15
0
        private async void ButtonAddFriend_Click(object sender, RoutedEventArgs e)
        {
            string id      = TextBoxFriendId.Text.Trim();
            string message = TextBoxMessage.Text.Trim();

            if (string.IsNullOrEmpty(id))
            {
                ShowError("The Tox ID field is empty.");
                return;
            }

            if (string.IsNullOrEmpty(message))
            {
                message = (string)TextBoxMessage.Tag;
            }

            if (Config.Instance.EnableToxDns && id.Contains("@"))
            {
                //try resolving 3 times
                for (int tries = 0; tries < 3; tries++)
                {
                    try
                    {
                        string toxId = DnsUtils.DiscoverToxID(id, Config.Instance.NameServices, !Config.Instance.AllowPublicKeyLookups, !Config.Instance.AllowTox1Lookups);
                        if (!string.IsNullOrEmpty(toxId))
                        {
                            //show the tox id to the user before actually adding it to the friend list
                            TextBoxFriendId.Text = toxId;
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debugging.Write(string.Format("Could not resolve {0}: {1}", id, ex.Message));
                    }
                }

                //if we got this far the discovery must have failed
                ShowError("Could not resolve tox username.");
                return;
            }

            if (!ToxId.IsValid(id))
            {
                ShowError("The entered Tox ID is invalid.");
                return;
            }

            var error        = ToxErrorFriendAdd.Ok;
            int friendNumber = ProfileManager.Instance.Tox.AddFriend(new ToxId(id), message, out error);

            if (error != ToxErrorFriendAdd.Ok)
            {
                ShowError(error.ToString());
                return;
            }

            var model = new FriendControlViewModel(MainWindow.Instance.ViewModel.CurrentFriendListView);

            model.ChatNumber    = friendNumber;
            model.Name          = id;
            model.StatusMessage = "Friend request sent";

            MainWindow.Instance.ViewModel.CurrentFriendListView.AddObject(model);
            MainWindow.Instance.ViewModel.CurrentFriendListView.SortObject(model);
            MainWindow.Instance.ViewModel.CurrentFriendListView.SelectObject(model);

            await ProfileManager.Instance.SaveAsync();
        }
 public void TestParseDomainNameHostNameWithTrailingDot()
 {
     Assert.AreEqual("", DnsUtils.GetDomainName("bart."));
 }
 public void TestParseDomainNameHostNameOnly()
 {
     Assert.AreEqual("", DnsUtils.GetDomainName("bob"));
 }
Exemple #18
0
 public void TestParseLocalName()
 {
     "local".ShouldEqual(DnsUtils.GetDomainName("host.local"));
 }
 public void TestParseDomainNameFullyQualifiedDomainName()
 {
     Assert.AreEqual("simpson.com", DnsUtils.GetDomainName("homer.simpson.com"));
 }
Exemple #20
0
 public void TestParseDomainNameHostNameWithTrailingDot()
 {
     "".ShouldEqual(DnsUtils.GetDomainName("bart."));
 }
Exemple #21
0
 public void TestParseDomainNameFullyQualifiedDomainName()
 {
     "simpson.com".ShouldEqual(DnsUtils.GetDomainName("homer.simpson.com"));
 }
 public void TestParseLocalName()
 {
     Assert.AreEqual("local", DnsUtils.GetDomainName("host.local"));
 }
Exemple #23
0
 public void TestParseDomainNameHostNameOnly()
 {
     "".ShouldEqual(DnsUtils.GetDomainName("bob"));
 }
 public void TestParseLocalDomainName()
 {
     Log.InfoFormat("domain is '{0}'", DnsUtils.GetDomainName());
     Assert.IsNotEmpty(DnsUtils.GetDomainName());
 }
Exemple #25
0
        public static async Task <UpdateResult> Update()
        {
            Log.Write("Hashing local hosts...");
            string localHash = string.Empty;

            try
            {
                localHash = MD5.HashFile(HostsPath);
            }
            catch (UnauthorizedAccessException)
            {
                Log.Write("Insufficient permission to read hosts, please run the program as administrator!");

                return(UpdateResult.InsufficientPermission);
            }
            Log.Write($"Local hash => {localHash}");

            Log.Write("Downloading remote hosts...");
            byte[] remoteData = Array.Empty <byte>();
            try
            {
                remoteData = await WebClient.DownloadDataTaskAsync(HostsUrl);
            }
            catch (System.Net.WebException)
            {
                Log.Write("WebException! Remote host is down or no internet connection?");

                return(UpdateResult.NoInternet);
            }
            Log.Write("Hashing remote hosts...");
            string remoteHash = MD5.HashData(remoteData);

            Log.Write($"Remote hash => {remoteHash}");

            if (localHash == remoteHash)
            {
                Log.Write("Hosts is up to date, returning.");

                return(UpdateResult.AlreadyUpdated);
            }

            Log.Write("Remote hosts hash doesn't match local, updating...");

            try
            {
                File.Replace(HostsPath, remoteData);
            }
            catch (UnauthorizedAccessException)
            {
                Log.Write("Insufficient permission to replace hosts, please run the program as administrator!");

                return(UpdateResult.InsufficientPermission);
            }

            Log.Write("Flushing dns cache...");
            DnsUtils.FlushCache();

            Log.Write("Updated hosts file.");

            return(UpdateResult.Updated);
        }
Exemple #26
0
 public static string AutoResolveHostname(this Server server)
 {
     return(Global.Settings.ResolveServerHostname ? DnsUtils.Lookup(server.Hostname) !.ToString() : server.Hostname);
 }
Exemple #27
0
 public static async Task <string> AutoResolveHostnameAsync(this Server server, AddressFamily inet = AddressFamily.Unspecified)
 {
     return(Global.Settings.ResolveServerHostname ? (await DnsUtils.LookupAsync(server.Hostname, inet)) !.ToString() : server.Hostname);
 }
Exemple #28
0
        /// <summary>
        /// Gets the SDNS-based string representation
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string dnsStampString = DnsUtils.GetDnsStampString(this);

            return(dnsStampString);
        }