private bool CheckAvailability()
        {
                        #if DOTNETCORE
            return(false);
                        #endif
            switch (m_status)
            {
            case UPnPStatus.NotAvailable:
                return(false);

            case UPnPStatus.Available:
                return(true);

            case UPnPStatus.Discovering:
                if (m_discoveryComplete.WaitOne(c_discoveryTimeOutMillis))
                {
                    return(true);
                }
                if (NetTime.Now > m_discoveryResponseDeadline)
                {
                    m_status = UPnPStatus.NotAvailable;
                }
                return(false);
            }
            return(false);
        }
Esempio n. 2
0
        internal void Discover(NetPeer peer)
        {
            string content =
                "M-SEARCH * HTTP/1.1\r\n" +
                "HOST: 239.255.255.250:1900\r\n" +
                "ST:upnp:rootdevice\r\n" +
                "MAN:\"ssdp:discover\"\r\n" +
                "MX:3\r\n\r\n";

            m_discoveryResponseDeadline = NetTime.Now + 6.0; // arbitrarily chosen number, router gets 6 seconds to respond
            m_status = UPnPStatus.Discovering;

            byte[] raw = System.Text.Encoding.UTF8.GetBytes(content);

            m_peer.LogDebug("Attempting UPnP discovery");
            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

            if (peer.Configuration.BroadcastAddress.Equals(IPAddress.Broadcast))
            {
                foreach (IPAddress address in NetUtility.GetBroadcastAddresses())
                {
                    peer.RawSend(raw, 0, raw.Length, new NetEndPoint(address, 1900));
                }
            }
            else
            {
                peer.RawSend(raw, 0, raw.Length, new NetEndPoint(peer.Configuration.BroadcastAddress, 1900));
            }

            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
        }
Esempio n. 3
0
        private bool CheckAvailability()
        {
            switch (Status)
            {
            case UPnPStatus.NotAvailable:
                return(false);

            case UPnPStatus.Available:
                return(true);

            case UPnPStatus.Discovering:
                while (!discoveryComplete.WaitOne(DiscoveryTimeOutMs))
                {
                    if (DateTime.UtcNow > discoveryResponseDeadline)
                    {
                        Status = UPnPStatus.NotAvailable;
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
Esempio n. 4
0
 public NetUPnPDiscoveryEventArgs(
     NetUPnP upnp, UPnPStatus status, TimeSpan discoveryStartTime, TimeSpan discoveryEndTime)
 {
     UPnP               = upnp ?? throw new ArgumentNullException(nameof(upnp));
     Status             = status;
     DiscoveryStartTime = discoveryStartTime;
     DiscoveryEndTime   = discoveryEndTime;
 }
Esempio n. 5
0
 internal void Invalidate(TimeSpan endTime)
 {
     _discoveryStartTime = default;
     _serviceName        = "";
     _serviceUri         = null;
     Status = UPnPStatus.NotAvailable;
     StatusChanged?.Invoke(this, new NetUPnPDiscoveryEventArgs(this, Status, _discoveryStartTime, endTime));
 }
Esempio n. 6
0
 internal void CheckForDiscoveryTimeout()
 {
     if ((m_status != UPnPStatus.Discovering) || (NetTime.Now < m_discoveryResponseDeadline))
     {
         return;
     }
     m_peer.LogDebug("UPnP discovery timed out");
     m_status = UPnPStatus.NotAvailable;
 }
Esempio n. 7
0
        internal void ExtractServiceUri(Uri location)
        {
            TimeSpan discoveryEndTime = NetTime.Now;

            try
            {
                var desc = new XmlDocument();
                using (WebResponse rep = WebRequest.Create(location).GetResponse())
                    using (Stream stream = rep.GetResponseStream())
                        desc.Load(stream);

                var nsMgr = new XmlNamespaceManager(desc.NameTable);
                nsMgr.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0");
                XmlNode?typen = desc.SelectSingleNode("//tns:device/tns:deviceType/text()", nsMgr);
                if (typen?.Value == null || !typen.Value.Contains("InternetGatewayDevice", StringComparison.Ordinal))
                {
                    Invalidate(discoveryEndTime);
                    return;
                }

                _serviceName = "WANIPConnection";

                XmlNode?node = desc.SelectSingleNode(
                    "//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" +
                    _serviceName + ":1\"]/tns:controlURL/text()", nsMgr);

                if (node == null)
                {
                    //try another service name
                    _serviceName = "WANPPPConnection";

                    node = desc.SelectSingleNode(
                        "//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" +
                        _serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
                }

                if (node?.Value == null)
                {
                    Invalidate(discoveryEndTime);
                    return;
                }

                Uri controlUri = new(node.Value, UriKind.RelativeOrAbsolute);
                _serviceUri = controlUri.IsAbsoluteUri
                    ? controlUri
                    : new Uri(new Uri(location.GetLeftPart(UriPartial.Authority)), controlUri);

                Status = UPnPStatus.Available;
                StatusChanged?.Invoke(this, new NetUPnPDiscoveryEventArgs(this, Status, _discoveryStartTime, discoveryEndTime));
            }
            catch
            {
                Invalidate(discoveryEndTime);
                throw;
            }
        }
Esempio n. 8
0
        internal void CheckForDiscoveryTimeout()
        {
            if (NetTime.Now < m_discoveryResponseDeadline)
            {
                return;
            }

            lock (DiscoveryResults)
                m_status = DiscoveryResults.Count > 0 ? UPnPStatus.Available : UPnPStatus.NotAvailable;

            m_discoveryComplete.Set();
            m_peer.LogDebug("UPnP service ready");
        }
Esempio n. 9
0
        internal void CheckForDiscoveryTimeout()
        {
            if (m_status == UPnPStatus.NotAvailable || NetTime.Now < m_discoveryResponseDeadline)
            {
                return;
            }

            lock (m_discoveryResults) {
                m_status = (m_discoveryResults.Count > 0 ? UPnPStatus.Available : UPnPStatus.NotAvailable);
            }

            m_discoveryComplete.Set();
            m_peer.LogDebug("UPnP discovery timed out");
        }
Esempio n. 10
0
        internal void ExtractServiceUrl(string resp)
        {
#if !DOTNETCORE
#if !DEBUG
            try
            {
#endif
            XmlDocument desc = new XmlDocument();
            using (var response = await WebRequest.Create(resp).GetResponseAsync())
                desc.Load(response.GetResponseStream());

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(desc.NameTable);
            nsMgr.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0");
            //XmlNode typen = desc.SelectSingleNode("//tns:device/tns:deviceType/text()", nsMgr);
            //var a = desc.DocumentElement;
            a.
            if (!typen.Value.Contains("InternetGatewayDevice"))
            {
                return;
            }

            m_serviceName = "WANIPConnection";
            XmlNode node = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + m_serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
            if (node == null)
            {
                //try another service name
                m_serviceName = "WANPPPConnection";
                node          = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + m_serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
                if (node == null)
                {
                    return;
                }
            }

            m_serviceUrl = CombineUrls(resp, node.Value);
            m_peer.LogDebug("UPnP service ready");
            m_status = UPnPStatus.Available;
            m_discoveryComplete.Set();
#if !DEBUG
        }

        catch
        {
            m_peer.LogVerbose("Exception ignored trying to parse UPnP XML response");
            return;
        }
#endif
#endif // !DOTNETCORE
        }
Esempio n. 11
0
        internal void Discover()
        {
            string str =
                "M-SEARCH * HTTP/1.1\r\n" +
                "HOST: 239.255.255.250:1900\r\n" +
                "ST:upnp:rootdevice\r\n" +
                "MAN:\"ssdp:discover\"\r\n" +
                "MX:3\r\n\r\n";

            discoveryResponseDeadline = DateTime.UtcNow.AddSeconds(6);
            Status = UPnPStatus.Discovering;

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);

            this.logger.WriteInfo("Attempting UPnP discovery");

            socket.SendTo(buffer, new IPEndPoint(NetUtility.GetBroadcastAddress(), 1900));
        }
Esempio n. 12
0
        internal void Discover(NetPeer peer)
        {
            string str =
                "M-SEARCH * HTTP/1.1\r\n" +
                "HOST: 239.255.255.250:1900\r\n" +
                "ST:upnp:rootdevice\r\n" +
                "MAN:\"ssdp:discover\"\r\n" +
                "MX:3\r\n\r\n";

            m_discoveryResponseDeadline = NetTime.Now + 6.0;             // arbitrarily chosen number, router gets 6 seconds to respond
            m_status = UPnPStatus.Discovering;

            byte[] arr = System.Text.Encoding.UTF8.GetBytes(str);

            m_peer.LogDebug("Attempting UPnP discovery");
            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            peer.RawSend(arr, 0, arr.Length, new NetEndPoint(NetUtility.GetBroadcastAddress(), 1900));
            peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
        }
Esempio n. 13
0
        internal bool ExtractServiceUrl(string resp)
        {
            try
            {
                XmlDocument desc = new XmlDocument();
                using (WebResponse response = WebRequest.Create(resp).GetResponse())
                {
                    desc.Load(response.GetResponseStream());
                }

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(desc.NameTable);
                nsMgr.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0");
                XmlNode typen = desc.SelectSingleNode("//tns:device/tns:deviceType/text()", nsMgr);
                if (!typen.Value.Contains("InternetGatewayDevice"))
                {
                    return(false);
                }

                serviceName = "WANIPConnection";
                XmlNode node = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
                if (node == null)
                {
                    //try another service name
                    serviceName = "WANPPPConnection";
                    node        = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
                    if (node == null)
                    {
                        return(false);
                    }
                }

                serviceUrl = CombineUrls(resp, node.Value);
                this.logger.WriteInfo("UPnP service ready");
                Status = UPnPStatus.Available;
                discoveryComplete.Set();
                return(true);
            }
            catch (Exception e)
            {
                this.logger.WriteError("Exception while parsing UPnP Service URL: " + e.Message);
                return(false);
            }
        }
Esempio n. 14
0
		internal void Discover(NetPeer peer)
		{
			string str =
"M-SEARCH * HTTP/1.1\r\n" +
"HOST: 239.255.255.250:1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"MAN:\"ssdp:discover\"\r\n" +
"MX:3\r\n\r\n";

			m_discoveryResponseDeadline = NetTime.Now + 6.0; // arbitrarily chosen number, router gets 6 seconds to respond
			m_status = UPnPStatus.Discovering;

			byte[] arr = System.Text.Encoding.UTF8.GetBytes(str);

			m_peer.LogDebug("Attempting UPnP discovery");
			peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
			peer.RawSend(arr, 0, arr.Length, new NetEndPoint(NetUtility.GetBroadcastAddress(), 1900));
			peer.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
		}
Esempio n. 15
0
        private bool CheckAvailability()
        {
            if (m_status == UPnPStatus.Discovering)
            {
                m_discoveryComplete.WaitOne(c_discoveryTimeOutMillis);

                lock (m_discoveryResults) {
                    if (m_discoveryResults.Count > 0)
                    {
                        m_status = UPnPStatus.Available;
                    }
                    else if (NetTime.Now > m_discoveryResponseDeadline)
                    {
                        m_status = UPnPStatus.NotAvailable;
                    }
                }
            }

            return(m_status == UPnPStatus.Available);
        }
Esempio n. 16
0
        public void Discover()
        {
            if (Peer.Socket == null)
            {
                throw new InvalidOperationException("The associated peer has no socket.");
            }

            string str =
                "M-SEARCH * HTTP/1.1\r\n" +
                "HOST: 239.255.255.250:1900\r\n" +
                "ST:upnp:rootdevice\r\n" +
                "MAN:\"ssdp:discover\"\r\n" +
                "MX:3\r\n\r\n";

            byte[] arr = _encoding.GetBytes(str);

            _discoveryStartTime = NetTime.Now;
            Status = UPnPStatus.Discovering;

            Peer.Socket.EnableBroadcast = true;
            Peer.RawSend(arr, 0, arr.Length, new IPEndPoint(IPAddress.Broadcast, 1900));
            Peer.Socket.EnableBroadcast = false;
        }
Esempio n. 17
0
		internal void ExtractServiceUrl(string resp)
		{
#if !DEBUG
			try
			{
#endif
			XmlDocument desc = new XmlDocument();
			desc.Load(WebRequest.Create(resp).GetResponse().GetResponseStream());
			XmlNamespaceManager nsMgr = new XmlNamespaceManager(desc.NameTable);
			nsMgr.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0");
			XmlNode typen = desc.SelectSingleNode("//tns:device/tns:deviceType/text()", nsMgr);
			if (!typen.Value.Contains("InternetGatewayDevice"))
				return;

			m_serviceName = "WANIPConnection";
			XmlNode node = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + m_serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
			if (node == null)
			{
				//try another service name
				m_serviceName = "WANPPPConnection";
				node = desc.SelectSingleNode("//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:" + m_serviceName + ":1\"]/tns:controlURL/text()", nsMgr);
				if (node == null)
					return;
			}

			m_serviceUrl = CombineUrls(resp, node.Value);
			m_peer.LogDebug("UPnP service ready");
			m_status = UPnPStatus.Available;
			m_discoveryComplete.Set();
#if !DEBUG
			}
			catch
			{
				m_peer.LogVerbose("Exception ignored trying to parse UPnP XML response");
				return;
			}
#endif
		}
Esempio n. 18
0
		private bool CheckAvailability()
		{
			switch (m_status)
			{
				case UPnPStatus.NotAvailable:
					return false;
				case UPnPStatus.Available:
					return true;
				case UPnPStatus.Discovering:
					if (m_discoveryComplete.WaitOne(c_discoveryTimeOutMillis))
						return true;
					if (NetTime.Now > m_discoveryResponseDeadline)
						m_status = UPnPStatus.NotAvailable;
					return false;
			}
			return false;
		}
Esempio n. 19
0
 internal void CheckForDiscoveryTimeout()
 {
     if ((m_status != UPnPStatus.Discovering) || (NetTime.Now < m_discoveryResponseDeadline))
         return;
     m_peer.LogDebug("UPnP discovery timed out");
     m_status = UPnPStatus.NotAvailable;
 }
Esempio n. 20
0
        private void UPnPTimerCallback(object state)
        {
            try
            {
                DefaultNetworkInfo defaultNetworkInfo = NetUtilities.GetDefaultNetworkInfo();
                if (defaultNetworkInfo == null)
                {
                    //no internet available;
                    _upnpStatus = UPnPStatus.NoInternetConnection;
                    return;
                }

                if (defaultNetworkInfo.IsPublicIP)
                {
                    //public ip so no need to do port forwarding
                    _upnpStatus = UPnPStatus.PortForwardingNotRequired;
                    return;
                }

                IPEndPoint LocalNetworkEP = new IPEndPoint(defaultNetworkInfo.LocalIP, ((IPEndPoint)_tcpListener.LocalEndpoint).Port);

                try
                {
                    if ((_upnp == null) || (!_upnp.NetworkBroadcastAddress.Equals(defaultNetworkInfo.BroadcastIP)))
                    {
                        _upnp = InternetGatewayDevice.Discover(defaultNetworkInfo.BroadcastIP, 30000);
                    }
                }
                catch
                {
                    _upnpStatus = UPnPStatus.UPnPDeviceNotFound;
                    throw;
                }

                //find external ip from router
                try
                {
                    IPAddress externalIP = _upnp.GetExternalIPAddress();

                    if (!_externalSelfEP.Address.Equals(externalIP))
                    {
                        _externalSelfEP = new IPEndPoint(externalIP, _externalSelfEP.Port);
                    }
                }
                catch
                { }

                int  externalPort = LocalNetworkEP.Port;
                bool isTCPMapped  = false;

                try
                {
                    int loopCount = 0;

                    while (true)
                    {
                        PortMappingEntry portMap = _upnp.GetSpecificPortMappingEntry(ProtocolType.Tcp, externalPort);

                        if (portMap == null)
                        {
                            break; //port available
                        }
                        if (portMap.InternalEP.Equals(LocalNetworkEP))
                        {
                            //port already mapped with us
                            isTCPMapped = true;
                            _upnpStatus = UPnPStatus.PortForwarded;
                            break;
                        }

                        //find new port for mapping
                        if (externalPort < ushort.MaxValue)
                        {
                            externalPort++;
                        }
                        else
                        {
                            externalPort = 1024;
                        }

                        if (loopCount > ushort.MaxValue)
                        {
                            return;
                        }

                        loopCount++;
                    }
                }
                catch { }

                if (!isTCPMapped)
                {
                    try
                    {
                        _upnp.AddPortMapping(ProtocolType.Tcp, externalPort, LocalNetworkEP, "BitChat - TCP");

                        if (_externalSelfEP.Port != externalPort)
                        {
                            _externalSelfEP = new IPEndPoint(_externalSelfEP.Address, externalPort);
                        }

                        _upnpStatus = UPnPStatus.PortForwarded;

                        Debug.Write("BitChatClient.UPnPTimerCallback", "tcp port mapped " + externalPort);
                    }
                    catch
                    {
                        try
                        {
                            _upnp.DeletePortMapping(ProtocolType.Tcp, externalPort);
                            _upnp.AddPortMapping(ProtocolType.Tcp, externalPort, LocalNetworkEP, "BitChat - TCP");

                            if (_externalSelfEP.Port != externalPort)
                            {
                                _externalSelfEP = new IPEndPoint(_externalSelfEP.Address, externalPort);
                            }

                            _upnpStatus = UPnPStatus.PortForwarded;

                            Debug.Write("BitChat.UPnPTimerCallback", "tcp port mapped " + externalPort);
                        }
                        catch { }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Write("BitChat.UPnPTimerCallback", ex);
            }
            finally
            {
                if (_upnpTimer != null)
                {
                    switch (_upnpStatus)
                    {
                    case Connections.UPnPStatus.UPnPDeviceNotFound:
                        _upnpTimer.Change(10000, Timeout.Infinite);
                        break;

                    default:
                        _upnpTimer.Change(UPNP_TIMER_INTERVAL, Timeout.Infinite);
                        break;
                    }
                }
            }
        }
        private void UPnPTimerCallback(object state)
        {
            try
            {
                DefaultNetworkInfo defaultNetworkInfo = NetUtilities.GetDefaultNetworkInfo();
                if (defaultNetworkInfo == null)
                {
                    //no internet available;
                    _upnpStatus = UPnPStatus.NoInternetConnection;
                    return;
                }

                if (defaultNetworkInfo.IsPublicIP)
                {
                    //public ip so no need to do port forwarding
                    _upnpStatus = UPnPStatus.PortForwardingNotRequired;
                    return;
                }

                IPEndPoint LocalNetworkEP = new IPEndPoint(defaultNetworkInfo.LocalIP, ((IPEndPoint)_tcpListener.LocalEndpoint).Port);

                try
                {
                    if ((_upnp == null) || (!_upnp.NetworkBroadcastAddress.Equals(defaultNetworkInfo.BroadcastIP)))
                        _upnp = InternetGatewayDevice.Discover(defaultNetworkInfo.BroadcastIP, 30000);
                }
                catch
                {
                    _upnpStatus = UPnPStatus.UPnPDeviceNotFound;
                    throw;
                }

                //find external ip from router
                try
                {
                    IPAddress externalIP = _upnp.GetExternalIPAddress();

                    if (!_externalSelfEP.Address.Equals(externalIP))
                        _externalSelfEP = new IPEndPoint(externalIP, _externalSelfEP.Port);
                }
                catch
                { }

                int externalPort = LocalNetworkEP.Port;
                bool isTCPMapped = false;

                try
                {
                    int loopCount = 0;

                    while (true)
                    {
                        PortMappingEntry portMap = _upnp.GetSpecificPortMappingEntry(ProtocolType.Tcp, externalPort);

                        if (portMap == null)
                            break; //port available

                        if (portMap.InternalEP.Equals(LocalNetworkEP))
                        {
                            //port already mapped with us
                            isTCPMapped = true;
                            _upnpStatus = UPnPStatus.PortForwarded;
                            break;
                        }

                        //find new port for mapping
                        if (externalPort < ushort.MaxValue)
                            externalPort++;
                        else
                            externalPort = 1024;

                        if (loopCount > ushort.MaxValue)
                            return;

                        loopCount++;
                    }
                }
                catch { }

                if (!isTCPMapped)
                {
                    try
                    {
                        _upnp.AddPortMapping(ProtocolType.Tcp, externalPort, LocalNetworkEP, "BitChat - TCP");

                        if (_externalSelfEP.Port != externalPort)
                            _externalSelfEP = new IPEndPoint(_externalSelfEP.Address, externalPort);

                        _upnpStatus = UPnPStatus.PortForwarded;

                        Debug.Write("BitChatClient.UPnPTimerCallback", "tcp port mapped " + externalPort);
                    }
                    catch
                    {
                        try
                        {
                            _upnp.DeletePortMapping(ProtocolType.Tcp, externalPort);
                            _upnp.AddPortMapping(ProtocolType.Tcp, externalPort, LocalNetworkEP, "BitChat - TCP");

                            if (_externalSelfEP.Port != externalPort)
                                _externalSelfEP = new IPEndPoint(_externalSelfEP.Address, externalPort);

                            _upnpStatus = UPnPStatus.PortForwarded;

                            Debug.Write("BitChat.UPnPTimerCallback", "tcp port mapped " + externalPort);
                        }
                        catch { }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Write("BitChat.UPnPTimerCallback", ex);
            }
            finally
            {
                if (_upnpTimer != null)
                {
                    switch (_upnpStatus)
                    {
                        case Connections.UPnPStatus.UPnPDeviceNotFound:
                            _upnpTimer.Change(10000, Timeout.Infinite);
                            break;

                        default:
                            _upnpTimer.Change(UPNP_TIMER_INTERVAL, Timeout.Infinite);
                            break;
                    }
                }
            }
        }