private Mapping CreatePortMap(Mapping mapping, bool create) { List <byte> package = new List <byte> (); package.Add(PmpConstants.Version); package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp); package.Add((byte)0); //reserved package.Add((byte)0); //reserved package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)mapping.PrivatePort))); package.AddRange(BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0)); package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime))); CreatePortMapAsyncState state = new CreatePortMapAsyncState(); state.Buffer = package.ToArray(); state.Mapping = mapping; ThreadPool.QueueUserWorkItem(new WaitCallback(CreatePortMapAsync), state); #if SSHARP state.ResetEvent.Wait(); #else WaitHandle.WaitAll(new WaitHandle[] { state.ResetEvent }); #endif if (!state.Success) { string type = create ? "create" : "delete"; throw new MappingException(String.Format("Failed to {0} portmap (protocol={1}, private port={2}", type, mapping.Protocol, mapping.PrivatePort)); } return(state.Mapping); }
internal UpnpNatDevice(IPAddress localAddress, string deviceDetails, string serviceType) { this.LastSeen = DateTime.Now; this.localAddress = localAddress; // Split the string at the "location" section so i can extract the ipaddress and service description url string locationDetails = deviceDetails.Substring(deviceDetails.IndexOf("Location", StringComparison.InvariantCultureIgnoreCase) + 9).Split('\r')[0]; this.serviceType = serviceType; // Make sure we have no excess whitespace locationDetails = locationDetails.Trim(); // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address // Are we going to get addresses with the "http://" attached? if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { NatUtility.Log("Found device at: {0}", locationDetails); // This bit strings out the "http://" from the string locationDetails = locationDetails.Substring(7); // We then split off the end of the string to get something like: 192.168.0.3:241 in our string string hostAddressAndPort = locationDetails.Remove(locationDetails.IndexOf('/')); // From this we parse out the IP address and Port if (hostAddressAndPort.IndexOf(':') > 0) { this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort.Remove(hostAddressAndPort.IndexOf(':'))), Convert.ToUInt16(hostAddressAndPort.Substring(hostAddressAndPort.IndexOf(':') + 1), System.Globalization.CultureInfo.InvariantCulture)); } else { // there is no port specified, use default port (80) this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort), 80); } NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString()); // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip // and port information this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/')); } else { Trace.WriteLine("Couldn't decode address. Please send following string to the developer: "); Trace.WriteLine(deviceDetails); } }
internal PmpNatDevice(IPAddress localAddress, IPAddress publicAddress) { this.localAddress = localAddress; this.publicAddress = publicAddress; }
private void CreatePortMapListen(object obj) { CreatePortMapListenState state = obj as CreatePortMapListenState; UdpClient udpClient = state.UdpClient; state.UdpClientReady.WaitOne(); // Evidently UdpClient has some lazy-init Send/Receive race? IPEndPoint endPoint = new IPEndPoint(localAddress, PmpConstants.ServerPort); while (!state.Success) { byte[] data; try { data = udpClient.Receive(ref endPoint); } catch (SocketException) { state.Success = false; return; } if (data.Length < 16) { continue; } if (data[0] != PmpConstants.Version) { continue; } byte opCode = (byte)(data[1] & (byte)127); Protocol protocol = Protocol.Tcp; if (opCode == PmpConstants.OperationCodeUdp) { protocol = Protocol.Udp; } short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2)); uint epoch = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4)); int privatePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8)); int publicPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10)); uint lifetime = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12)); if (resultCode != PmpConstants.ResultCodeSuccess) { state.Success = false; return; } if (lifetime == 0) { //mapping was deleted state.Success = true; state.Mapping = null; return; } else { //mapping was created //TODO: verify that the private port+protocol are a match Mapping mapping = state.Mapping; mapping.PublicPort = publicPort; mapping.Protocol = protocol; mapping.Expiration = DateTime.Now.AddSeconds(lifetime); state.Success = true; } } }
public GetExternalIPAddressResponseMessage(string ip) : base(null) { this.externalIPAddress = IPAddress.Parse(ip); }
private void ServicesReceived(IAsyncResult result) { HttpWebResponse response = null; try { int abortCount = 0; int bytesRead = 0; byte[] buffer = new byte[10240]; StringBuilder servicesXml = new StringBuilder(); XmlDocument xmldoc = new XmlDocument(); HttpWebRequest request = result.AsyncState as HttpWebRequest; response = request.EndGetResponse(result) as HttpWebResponse; Stream s = response.GetResponseStream(); if (response.StatusCode != HttpStatusCode.OK) { NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); return; // FIXME: This the best thing to do?? } while (true) { bytesRead = s.Read(buffer, 0, buffer.Length); servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); try { xmldoc.LoadXml(servicesXml.ToString()); response.Close(); break; } catch (XmlException) { // If we can't receive the entire XML within 500ms, then drop the connection // Unfortunately not all routers supply a valid ContentLength (mine doesn't) // so this hack is needed to keep testing our recieved data until it gets successfully // parsed by the xmldoc. Without this, the code will never pick up my router. if (abortCount++ > 50) { response.Close(); return; } NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint); #if SSHARP CrestronEnvironment.Sleep(10); #else System.Threading.Thread.Sleep(10); #endif } } NatUtility.Log("{0}: Parsed services list", HostEndPoint); XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns); foreach (XmlNode node in nodes) { //Go through each service there foreach (XmlNode service in node.ChildNodes) { //If the service is a WANIPConnection, then we have what we want string type = service["serviceType"].InnerText; NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type); StringComparison c = StringComparison.OrdinalIgnoreCase; if (type.Equals(this.serviceType, c)) { this.controlUrl = service["controlURL"].InnerText; NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); try { Uri u = new Uri(controlUrl); if (u.IsAbsoluteUri) { IPEndPoint old = hostEndPoint; this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port); NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length); NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl); } } catch { NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); } NatUtility.Log("{0}: Handshake Complete", HostEndPoint); this.callback(this); return; } } } //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding //So we don't invoke the callback, so this device is never added to our lists } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex); } finally { if (response != null) { response.Close(); } } }