Resolve() public method

public Resolve ( string host, NsType queryType, NsClass queryClass, ProtocolType protocol ) : DnsQueryResponse
host string
queryType NsType
queryClass NsClass
protocol ProtocolType
return DnsQueryResponse
 void MCPingCommand(CommandDetails command)
 {
     if (command.Arguments.Count <= 0)
     {
         Chat(command.Channel.Name, command.Pinger + ColorGeneral + "That command is written as: " + ColorHighlightMajor + Prefixes[0] + command.Name + " <Minecraft server IP address>");
         return;
     }
     IRCUser user = new IRCUser(command.Arguments[0]);
     string IP = user.Settings.ReadString("general.minecraft_server_ip", null);
     if (IP == null)
     {
         IP = command.Arguments[0];
     }
     ushort port = 0;
     if (IP.Contains(':'))
     {
         string[] dat = IP.Split(new char[] { ':' }, 2);
         IP = dat[0];
         port = Utilities.StringToUShort(dat[1]);
     }
     if (port == 0)
     {
         try
         {
             DnsQueryRequest dqr = new DnsQueryRequest();
             DnsQueryResponse resp = dqr.Resolve("_minecraft._tcp." + IP, NsType.SRV, NsClass.ANY, ProtocolType.Tcp);
             if (resp != null)
             {
                 for (int i = 0; i < resp.AdditionalRRecords.Count; i++)
                 {
                     if (resp.AdditionalRRecords[i] is SrvRecord)
                     {
                         port = (ushort)((SrvRecord)resp.AdditionalRRecords[i]).Port;
                     }
                 }
                 for (int i = 0; i < resp.Answers.Length; i++)
                 {
                     if (resp.Answers[i] is SrvRecord)
                     {
                         port = (ushort)((SrvRecord)resp.Answers[i]).Port;
                     }
                 }
             }
             else
             {
                 Logger.Output(LogType.DEBUG, "Null SRV record.");
             }
             if (port == 0)
             {
                 port = (ushort)25565;
             }
         }
         catch (Exception ex)
         {
             Logger.Output(LogType.ERROR, "Pinging a SRV record for a minecraft server: " + ex.ToString());
             port = 25565;
         }
     }
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         Stopwatch Timer = new Stopwatch();
         Timer.Reset();
         Timer.Start();
         sock.SendBufferSize = 8192;
         sock.ReceiveBufferSize = 8192 * 10;
         sock.ReceiveTimeout = 3000;
         sock.SendTimeout = 3000;
         IAsyncResult result = sock.BeginConnect(IP, port, null, null);
         bool timeout = !result.AsyncWaitHandle.WaitOne(5000, true);
         if (timeout)
         {
             throw new Exception("Connection timed out");
         }
         if (!sock.Connected)
         {
             throw new Exception("Failed to connect");
         }
         byte[] address = UTF8.GetBytes(IP);
         int packlen = 1 + 1 + 1 + address.Length + 2 + 1;
         byte[] send = new byte[1 + packlen + 1 + 1];
         byte[] portbytes = BitConverter.GetBytes(port).Reverse().ToArray();
         send[0] = (byte)packlen; // packet length
         send[1] = (byte)0x00; // Packet ID
         send[2] = (byte)0x04; // Protocol Version
         send[3] = (byte)address.Length; // Address string length
         address.CopyTo(send, 4); // Address string
         portbytes.CopyTo(send, address.Length + 4); // Port
         send[address.Length + 6] = (byte)0x01; // Next state
         send[address.Length + 7] = (byte)0x01; // Next packet length
         send[address.Length + 8] = (byte)0x00; // Empty state request packet ~ packet ID
         sock.Send(send);
         int length = 0;
         // Packet size -> packet ID -> JSON length
         for (int x = 0; x < 2; x++)
         {
             length = 0;
             int j = 0;
             while (true)
             {
                 byte[] recd = new byte[1];
                 sock.Receive(recd, 1, SocketFlags.None);
                 int k = recd[0];
                 length |= (k & 0x7F) << j++ * 7;
                 if (j > 5) throw new Exception("VarInt too big");
                 if ((k & 0x80) != 128) break;
                 if (Timer.ElapsedMilliseconds > 7000)
                     throw new Exception("Timeout while reading response");
             }
             if (x == 0)
             {
                 byte[] resp = new byte[1];
                 sock.Receive(resp, 1, SocketFlags.None);
             }
         }
         int gotten = 0;
         byte[] response = new byte[length];
         while (gotten < length)
         {
             byte[] gotbit = new byte[length - gotten];
             int newgot = sock.Receive(gotbit, length - gotten, SocketFlags.None);
             gotbit.CopyTo(response, gotten);
             gotten += newgot;
             if (Timer.ElapsedMilliseconds > 7000)
                 throw new Exception("Timeout while reading response");
         }
         string fullresponse = UTF8.GetString(response);
         int ind = fullresponse.IndexOf('{');
         if (ind < 0)
         {
             throw new Exception("Invalid response packet - is that an actual minecraft server?");
         }
         fullresponse = fullresponse.Substring(ind);
         Dictionary<string, dynamic> dict = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(fullresponse.Trim());
         string version = dict["version"]["name"].ToString();
         string versionnum = dict["version"]["protocol"].ToString();
         string players_on = dict["players"]["online"].ToString();
         string players_max = dict["players"]["max"].ToString();
         string description;
         if (dict["description"] is Dictionary<String, Object>)
         {
             description = dict["description"]["text"].ToString();
         }
         else
         {
             description = dict["description"].ToString();
         }
         Chat(command.Channel.Name, command.Pinger + ColorGeneral + "Server: " + IP + ":" + port.ToString() + ", MOTD: '"
             + Utilities.mctoirc(description) + ColorGeneral + "', players: " + players_on + "/" + players_max + ", version: " + Utilities.mctoirc(version));
     }
     catch (Exception ex)
     {
         Logger.Output(LogType.DEBUG, "Pinging minecraft server: " + ex.ToString());
         Chat(command.Channel.Name, command.Pinger + ColorGeneral + "Couldn't ping server: internal exception: " + ex.Message);
     }
     finally
     {
         sock.Close();
     }
 }
Esempio n. 2
0
        private DnsLookup(string address)
        {
            NameList.Add (address);

            #if OLD
            IPAddress[] ipList = Dns.GetHostAddresses (address);
            foreach (IPAddress ip in ipList) {
            if (ip.AddressFamily == AddressFamily.InterNetworkV6 && Proxy.IPv6 == false)
                continue;
                AList.Add (ip);
            }

            if (AList.Count == 0)
                throw new HeaderException ("Lookup of " + address + " failed", HttpStatusCode.BadGateway);
            #else

            //localhost
            if (address.ToLowerInvariant () == "localhost") {
                AList.Add (IPAddress.Loopback);
                return;
            }

            //Raw IP addresses
            IPAddress ipa;
            if (IPAddress.TryParse (address, out ipa)) {
                AList.Add (ipa);
                return;
            }

            //New method below
            DnsQueryRequest request = new DnsQueryRequest ();

            //TODO also do AAAA lookup if Proxy.ipv6 is enabled

            DnsQueryResponse dr;
            try {
                // UDP request
                dr = request.Resolve (address, NsType.A, NsClass.INET, ProtocolType.Udp);
                if (ParseDnsResponse (dr))
                    return;

                // TCP request
                dr = request.Resolve (address, NsType.A, NsClass.INET, ProtocolType.Tcp);
                if (ParseDnsResponse (dr))
                    return;
            } catch (Exception e) {
                throw new HeaderException ("DNS lookup failed", HttpStatusCode.NotFound, e);
            }
            throw new HeaderException ("Lookup of " + address + " failed: " + dr.RCode, HttpStatusCode.BadGateway);
            #endif
        }
Esempio n. 3
0
 public XmppHost[] GetXmppHosts(IPAddress[] dnsServers, string domain, ILog log)
 {
     var dnsQueryRequest = new DnsQueryRequest();
     string record = "_xmpp-server._tcp." + domain;
     bool dnsServerWasReached = false;
     foreach (IPAddress address in dnsServers) {
         DnsQueryResponse queryResponse = null;
         try {
             queryResponse = dnsQueryRequest.Resolve(address.ToString(), record, NsType.SRV, NsClass.INET, ProtocolType.Udp);
         }
         catch(SocketException ex) {
             log.Error("Dns server unreachable. " + ex);
             continue;
         }
         dnsServerWasReached = true;
         if (queryResponse == null || queryResponse.Answers == null || queryResponse.Answers.Length <= 0) continue;
         var hosts = new List<XmppHost>();
         foreach (IDnsRecord answer in queryResponse.Answers) {
             var srvRecord = (SrvRecord) answer;
             try {
                 IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(srvRecord.HostName);
                 foreach (IPAddress ipAddress in ipHostEntry.AddressList) {
                     hosts.Add(new XmppHost(ipHostEntry.HostName, ipAddress, srvRecord.Port));
                 }
             }
             catch (SocketException ex) {
                 if (ex.SocketErrorCode == SocketError.HostNotFound) {
                     log.Warn(ex);
                 }
                 else {
                     throw;
                 }
             }
             catch (Exception ex) {
                 log.Error(ex);
                 throw;
             }
         }
         if(hosts.Count == 0) {
             throw new SocketException(11001); //Host not found
         }
         return hosts.ToArray();
     }
     if (!dnsServerWasReached) {
         throw new SocketException(10060);
     }
     //couldn't locate the service via dns, assume the domain is the host.
     try {
         IPHostEntry defaultHostEntry = System.Net.Dns.GetHostEntry(domain);
         var hosts = new List<XmppHost>();
         foreach (IPAddress ipAddress in defaultHostEntry.AddressList) {
             hosts.Add(new XmppHost(defaultHostEntry.HostName, ipAddress, 5222)); //5222 default XmppPort
         }
         return hosts.ToArray();
     }
     catch(SocketException ex) {
         log.Error(ex);
         throw;
     }
 }
Esempio n. 4
0
        static void Main(string[] args)
        {
            // Test TCP request
            DnsQueryRequest request = new DnsQueryRequest();
            DnsQueryResponse response = request.Resolve("www.google.com", NsType.A, NsClass.INET, ProtocolType.Tcp);

            OutputResults(response);

            // Test UDP request
            DnsQueryRequest request2 = new DnsQueryRequest();
            DnsQueryResponse response2 = request.Resolve("www.google.com", NsType.A, NsClass.INET, ProtocolType.Udp);

            OutputResults(response2);

            // Example usage of security provider.
            // DnsQueryRequest request3 = new DnsQueryRequest();
            // DnsQueryResponse response3 = request3.Resolve("a.tsig.secured.server", "a.server.to.lookup", NsType.A, NsClass.INET, ProtocolType.Udp, new TsigMessageSecurityProvider("sharedkeyname", "shared key as base 64 string", 300));

            Console.ReadLine();
        }
Esempio n. 5
0
        protected void ResolveHostName()
        {
            try
            {
                var request = new DnsQueryRequest();
                var response = request.Resolve
                    (
                        String.Format("{0}.{1}", XmppCodes.XmppSrvRecordPrefix, ConnectionString.HostName),
                        NsType.SRV,
                        NsClass.INET,
                        ProtocolType.Tcp
                    );

                foreach (var record in response.Answers.OfType<SrvRecord>())
                {
                    HostName = record.HostName;
                }
            }
            catch // TODO: logging of exceptions?
            {
            }
        }
Esempio n. 6
0
        protected void ResolveHostName()
        {
            try
            {
                DnsQueryRequest     request     = new DnsQueryRequest();
                DnsQueryResponse    response    = request.Resolve
                (
                    String.Format("{0}.{1}", XmppCodes.XmppSrvRecordPrefix, this.ConnectionString.HostName),
                    NsType.SRV,
                    NsClass.INET,
                    ProtocolType.Tcp
                );

                foreach (SrvRecord record in response.Answers.OfType<SrvRecord>())
                {
                    this.HostName = record.HostName;
                }
            }
            catch
            {
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Gets the domain controllers associated with a specific Active Directory site from the Active Directory's DNS SRV records.
 /// </summary>
 /// <param name="domainName">The DNS domain name of the Active Directory to retrieve the domain controllers for.</param>
 /// <param name="siteName">The name of the site to retrieve the domain controllers for.</param>
 /// <returns>A list containg the FQDNs of the domain controllers in the specified site, or an empty list if they could not be retrieved.</returns>
 public static List<String> GetSiteDomainControllers(string domainName, string siteName)
 {
     if (!string.IsNullOrWhiteSpace(domainName) && !string.IsNullOrWhiteSpace(siteName))
     {
         try
         {
             DnsQueryRequest request = new DnsQueryRequest();
             DnsQueryResponse response = request.Resolve("_ldap._tcp." + siteName + "._sites.dc._msdcs." + domainName, NsType.SRV, NsClass.INET, System.Net.Sockets.ProtocolType.Tcp);
             IDnsRecord[] records = response.Answers;
             List<string> domainControllers = new List<string>();
             foreach (IDnsRecord record in records)
             {
                 domainControllers.Add((record as SrvRecord).HostName);
             }
             return domainControllers;
         }
         catch
         {
             // There was an error contacting or retrieving data from the DNS server.
             return new List<string>();
         }
     }
     else
     {
         // Invalid parameters were supplied.
         return new List<string>();
     }
 }
Esempio n. 8
0
		private void RegisterTrunk(Trunk trunk)
		{
			trunk.State = Trunk.States.WaitingDns;

			var match = Regex.Match(trunk.OutgoingProxy, "(?<url>[^:]+)(:(?<port>[0-9]*))?");
			if (match.Success == false)
			{
				trunk.ErrorMessage = @"Invalid outgouing proxy URL";
			}
			else
			{
				var hostname = match.Groups["url"].Value;
				int? port = null;
				if (match.Groups["port"].Success)
					port = int.Parse(match.Groups["port"].Value);

				IPAddress address;
				if (IPAddress.TryParse(hostname, out address))
				{
					trunk.SetServerEndPoint(address, port ?? 5060);
					trunk.State = Trunk.States.Waiting200or401;
					SendRegister(trunk, trunk.RegisterDuration);
				}
				else
				{
					try
					{
						var prefixes = new string[] { @"_sip._tcp.", @"_sip._udp." };

						Transports transport = Transports.None;
						SrvRecord record = null;
						foreach (var prefix in prefixes)
						{
							var request = new DnsQueryRequest();
							var response = request.Resolve(prefix + hostname, NsType.SRV, NsClass.INET, ProtocolType.Udp);

							if (response.Answers.Length > 0)
								record = response.Answers[0] as SrvRecord;

							if (record != null)
							{
								if (prefix.Contains(@"tcp"))
									transport = Transports.Tcp;
								if (prefix.Contains(@"udp"))
									transport = Transports.Udp;
								break;
							}
						}

						if (record == null)
							trunk.ErrorMessage = @"Failed to get SRV record";
						else
						{
							var addresses = Dns.GetHostAddresses(record.HostName);
							if (addresses.Length < 0)
								trunk.ErrorMessage = @"Failed to get DNS A record for " + record.HostName;
							else
							{
								trunk.SetServerEndPoint(transport, addresses[0], port ?? record.Port);
								trunk.State = Trunk.States.Waiting200or401;
								SendRegister(trunk, trunk.RegisterDuration);
							}
						}
					}
					catch (Exception ex)
					{
						trunk.ErrorMessage = ex.Message;
					}
				}
			}
		}
Esempio n. 9
0
    public string ResolveNaptr(string e164_Number) {
      /* Need to know about DNS servers available */
      try {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Resolving NAPTR for {0}", e164_Number));

        string e164_NumberNaptr = "";

        for (int i = e164_Number.Length - 1; i > 0; i--) {
          if (e164_Number[i] == ' ' || e164_Number[i] == '+')
            continue;
          e164_NumberNaptr += e164_Number[i];
          e164_NumberNaptr += ".";
        }
        e164_NumberNaptr += "e164.arpa";


        List<string> s_dnsServerAddrList = new List<string>();

        if (!s_dnsServerAddrList.Contains(ReloadGlobals.DNS_Address))
          s_dnsServerAddrList.Add(ReloadGlobals.DNS_Address);

        foreach (string s_dnsServerAddr in s_dnsServerAddrList) {
          DnsQueryRequest dnsQuery = new DnsQueryRequest();

          //string e164_NumberNaptr = "2.2.2.2.2.2.2.1.7.1.9.4.e164.arpa";
          //answer: ...d.u.E2U+sip$!^.*$!sip:[email protected]!.

          DnsQueryResponse dnsResponse = dnsQuery.Resolve(s_dnsServerAddr, e164_NumberNaptr, DnDns.Enums.NsType.MAPTR, DnDns.Enums.NsClass.INET, ProtocolType.Udp);

          if (dnsResponse != null)
            foreach (IDnsRecord record in dnsResponse.Answers) {
              string[] lines = System.Text.RegularExpressions.Regex.Split(record.Answer, "!");

              if (lines != null && lines.Length > 2)
                m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("DNS NAPTR for {0} returned: {1}", e164_Number, lines[2]));

              return lines[2];
            }
        }
      }
      catch (Exception ex) {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("DNS NAPTR for {0} failed: {1}", e164_Number, ex.Message));
      }
      return null;

    }
Esempio n. 10
0
    public string ResolveConfigurationServer(string OverlayName) {
      if (ReloadGlobals.ForceLocalConfig)
        return null;

      /* Need to know about DNS servers available */
      try {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, "Resolving Configuration server...");

#if WINDOWS_PHONE
                // HACK: Windows Phone doesn't support DNS lookups, so fake it

				string enrollment_url = String.Format("enroll.{0}.org", OverlayName);
				m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_TOPO, String.Format("DNS SRV lookup faked: http://{0}", enrollment_url));

				// Be sure to use HTTP instead of HTTPS

#if IETF83_ENROLL
				return String.Format("http://{0}/.well-known/p2psip-enroll", enrollment_url);
#else
				return String.Format("http://{0}/p2psip/enroll/", enrollment_url);
#endif

#else

        List<string> s_dnsServerAddrList = new List<string>();

        if (ReloadGlobals.DNS_Address != null && ReloadGlobals.DNS_Address.Length != 0)
          if (!s_dnsServerAddrList.Contains(ReloadGlobals.DNS_Address))
            s_dnsServerAddrList.Add(ReloadGlobals.DNS_Address);

        foreach (string s_dnsServerAddr in s_dnsServerAddrList) {

          DnsQueryRequest dnsQuery = new DnsQueryRequest();

          DnsQueryResponse dnsResponse = dnsQuery.Resolve(s_dnsServerAddr, String.Format("_reload-config._tcp.{0}", OverlayName), DnDns.Enums.NsType.SRV, DnDns.Enums.NsClass.INET, ProtocolType.Udp);  //--joscha

          if (dnsResponse != null)
            foreach (IDnsRecord record in dnsResponse.Answers) {
              string[] lines = System.Text.RegularExpressions.Regex.Split(record.Answer, "\r\n");
              //m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("DNS SRV lookup returned {0}", record.Answer));

              foreach (string line in lines) {
                if (line.StartsWith("HostName")) {
                  string[] lines2 = System.Text.RegularExpressions.Regex.Split(line, " ");
                  string enrollment_url = lines2[1].TrimEnd('.');

                  m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_TOPO, String.Format("DNS SRV lookup returned: https://{0}", enrollment_url));

                  return String.Format("https://{0}/.well-known/reload-config", enrollment_url);

                }
              }
            }
        }
#endif
      }
      catch (Exception ex) {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("DNS SRV for p2psip_enroll failed: {0}", ex.Message));
      }
      return null;
    }