UpnpNatDevice.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //
  2. // Authors:
  3. // Alan McGovern alan.mcgovern@gmail.com
  4. // Ben Motmans <ben.motmans@gmail.com>
  5. //
  6. // Copyright (C) 2006 Alan McGovern
  7. // Copyright (C) 2007 Ben Motmans
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Net;
  30. using System.Xml;
  31. using System.Text;
  32. using System.Threading.Tasks;
  33. using MediaBrowser.Common.Net;
  34. using Microsoft.Extensions.Logging;
  35. using MediaBrowser.Model.Dlna;
  36. namespace Mono.Nat.Upnp
  37. {
  38. public sealed class UpnpNatDevice : AbstractNatDevice, IEquatable<UpnpNatDevice>
  39. {
  40. private EndPoint hostEndPoint;
  41. private IPAddress localAddress;
  42. private string serviceDescriptionUrl;
  43. private string controlUrl;
  44. private string serviceType;
  45. private readonly ILogger _logger;
  46. private readonly IHttpClient _httpClient;
  47. public override IPAddress LocalAddress
  48. {
  49. get { return localAddress; }
  50. }
  51. internal UpnpNatDevice(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint hostEndPoint, string serviceType, ILogger logger, IHttpClient httpClient)
  52. {
  53. if (localAddress == null)
  54. {
  55. throw new ArgumentNullException(nameof(localAddress));
  56. }
  57. this.LastSeen = DateTime.Now;
  58. this.localAddress = localAddress;
  59. // Split the string at the "location" section so i can extract the ipaddress and service description url
  60. string locationDetails = deviceInfo.Location.ToString();
  61. this.serviceType = serviceType;
  62. _logger = logger;
  63. _httpClient = httpClient;
  64. // Make sure we have no excess whitespace
  65. locationDetails = locationDetails.Trim();
  66. // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
  67. // Are we going to get addresses with the "http://" attached?
  68. if (locationDetails.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
  69. {
  70. _logger.LogDebug("Found device at: {0}", locationDetails);
  71. // This bit strings out the "http://" from the string
  72. locationDetails = locationDetails.Substring(7);
  73. this.hostEndPoint = hostEndPoint;
  74. // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
  75. // and port information
  76. this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
  77. }
  78. else
  79. {
  80. _logger.LogDebug("Couldn't decode address. Please send following string to the developer: ");
  81. }
  82. }
  83. public async Task GetServicesList()
  84. {
  85. // Create a HTTPWebRequest to download the list of services the device offers
  86. var message = new GetServicesMessage(this.serviceDescriptionUrl, this.hostEndPoint);
  87. using (var response = await _httpClient.SendAsync(message.Encode(), message.Method).ConfigureAwait(false))
  88. {
  89. OnServicesReceived(response);
  90. }
  91. }
  92. private void OnServicesReceived(HttpResponseInfo response)
  93. {
  94. int abortCount = 0;
  95. int bytesRead = 0;
  96. byte[] buffer = new byte[10240];
  97. var servicesXml = new StringBuilder();
  98. var xmldoc = new XmlDocument();
  99. using (var s = response.Content)
  100. {
  101. if (response.StatusCode != HttpStatusCode.OK)
  102. {
  103. _logger.LogDebug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
  104. return; // FIXME: This the best thing to do??
  105. }
  106. while (true)
  107. {
  108. bytesRead = s.Read(buffer, 0, buffer.Length);
  109. servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  110. try
  111. {
  112. xmldoc.LoadXml(servicesXml.ToString());
  113. break;
  114. }
  115. catch (XmlException)
  116. {
  117. // If we can't receive the entire XML within 500ms, then drop the connection
  118. // Unfortunately not all routers supply a valid ContentLength (mine doesn't)
  119. // so this hack is needed to keep testing our recieved data until it gets successfully
  120. // parsed by the xmldoc. Without this, the code will never pick up my router.
  121. if (abortCount++ > 50)
  122. {
  123. return;
  124. }
  125. _logger.LogDebug("{0}: Couldn't parse services list", HostEndPoint);
  126. System.Threading.Thread.Sleep(10);
  127. }
  128. }
  129. var ns = new XmlNamespaceManager(xmldoc.NameTable);
  130. ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
  131. XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns);
  132. foreach (XmlNode node in nodes)
  133. {
  134. //Go through each service there
  135. foreach (XmlNode service in node.ChildNodes)
  136. {
  137. //If the service is a WANIPConnection, then we have what we want
  138. string type = service["serviceType"].InnerText;
  139. _logger.LogDebug("{0}: Found service: {1}", HostEndPoint, type);
  140. // TODO: Add support for version 2 of UPnP.
  141. if (string.Equals(type, "urn:schemas-upnp-org:service:WANPPPConnection:1", StringComparison.OrdinalIgnoreCase) ||
  142. string.Equals(type, "urn:schemas-upnp-org:service:WANIPConnection:1", StringComparison.OrdinalIgnoreCase))
  143. {
  144. this.controlUrl = service["controlURL"].InnerText;
  145. _logger.LogDebug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
  146. Uri u;
  147. if (Uri.TryCreate(controlUrl, UriKind.RelativeOrAbsolute, out u))
  148. {
  149. if (u.IsAbsoluteUri)
  150. {
  151. var old = hostEndPoint;
  152. IPAddress parsedHostIpAddress;
  153. if (IPAddress.TryParse(u.Host, out parsedHostIpAddress))
  154. {
  155. this.hostEndPoint = new IPEndPoint(parsedHostIpAddress, u.Port);
  156. //_logger.LogDebug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
  157. this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
  158. //_logger.LogDebug("{0}: New control url: {1}", HostEndPoint, controlUrl);
  159. }
  160. }
  161. }
  162. else
  163. {
  164. _logger.LogDebug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
  165. }
  166. return;
  167. }
  168. }
  169. }
  170. //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding
  171. //So we don't invoke the callback, so this device is never added to our lists
  172. }
  173. }
  174. /// <summary>
  175. /// The EndPoint that the device is at
  176. /// </summary>
  177. internal EndPoint HostEndPoint
  178. {
  179. get { return this.hostEndPoint; }
  180. }
  181. /// <summary>
  182. /// The relative url of the xml file that describes the list of services is at
  183. /// </summary>
  184. internal string ServiceDescriptionUrl
  185. {
  186. get { return this.serviceDescriptionUrl; }
  187. }
  188. /// <summary>
  189. /// The relative url that we can use to control the port forwarding
  190. /// </summary>
  191. internal string ControlUrl
  192. {
  193. get { return this.controlUrl; }
  194. }
  195. /// <summary>
  196. /// The service type we're using on the device
  197. /// </summary>
  198. public string ServiceType
  199. {
  200. get { return serviceType; }
  201. }
  202. public override async Task CreatePortMap(Mapping mapping)
  203. {
  204. var message = new CreatePortMappingMessage(mapping, localAddress, this);
  205. using (await _httpClient.SendAsync(message.Encode(), message.Method).ConfigureAwait(false))
  206. {
  207. }
  208. }
  209. public override bool Equals(object obj)
  210. {
  211. var device = obj as UpnpNatDevice;
  212. return (device == null) ? false : this.Equals((device));
  213. }
  214. public bool Equals(UpnpNatDevice other)
  215. {
  216. return (other == null) ? false : (this.hostEndPoint.Equals(other.hostEndPoint)
  217. //&& this.controlUrl == other.controlUrl
  218. && this.serviceDescriptionUrl == other.serviceDescriptionUrl);
  219. }
  220. public override int GetHashCode()
  221. {
  222. return (this.hostEndPoint.GetHashCode() ^ this.controlUrl.GetHashCode() ^ this.serviceDescriptionUrl.GetHashCode());
  223. }
  224. /// <summary>
  225. /// Overridden.
  226. /// </summary>
  227. /// <returns></returns>
  228. public override string ToString()
  229. {
  230. //GetExternalIP is blocking and can throw exceptions, can't use it here.
  231. return String.Format(
  232. "UpnpNatDevice - EndPoint: {0}, External IP: {1}, Control Url: {2}, Service Description Url: {3}, Service Type: {4}, Last Seen: {5}",
  233. this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen);
  234. }
  235. }
  236. }