UpnpNatDevice.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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.IO;
  30. using System.Net;
  31. using System.Xml;
  32. using System.Text;
  33. using System.Diagnostics;
  34. using MediaBrowser.Controller.Dlna;
  35. namespace Mono.Nat.Upnp
  36. {
  37. public sealed class UpnpNatDevice : AbstractNatDevice, IEquatable<UpnpNatDevice>
  38. {
  39. private EndPoint hostEndPoint;
  40. private IPAddress localAddress;
  41. private string serviceDescriptionUrl;
  42. private string controlUrl;
  43. private string serviceType;
  44. public override IPAddress LocalAddress
  45. {
  46. get { return localAddress; }
  47. }
  48. /// <summary>
  49. /// The callback to invoke when we are finished setting up the device
  50. /// </summary>
  51. private NatDeviceCallback callback;
  52. internal UpnpNatDevice(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint hostEndPoint, string serviceType)
  53. {
  54. this.LastSeen = DateTime.Now;
  55. this.localAddress = localAddress;
  56. // Split the string at the "location" section so i can extract the ipaddress and service description url
  57. string locationDetails = deviceInfo.Location.ToString();
  58. this.serviceType = serviceType;
  59. // Make sure we have no excess whitespace
  60. locationDetails = locationDetails.Trim();
  61. // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
  62. // Are we going to get addresses with the "http://" attached?
  63. if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
  64. {
  65. NatUtility.Log("Found device at: {0}", locationDetails);
  66. // This bit strings out the "http://" from the string
  67. locationDetails = locationDetails.Substring(7);
  68. this.hostEndPoint = hostEndPoint;
  69. NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString());
  70. // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
  71. // and port information
  72. this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
  73. }
  74. else
  75. {
  76. NatUtility.Log("Couldn't decode address. Please send following string to the developer: ");
  77. }
  78. }
  79. internal UpnpNatDevice (IPAddress localAddress, string deviceDetails, string serviceType)
  80. {
  81. this.LastSeen = DateTime.Now;
  82. this.localAddress = localAddress;
  83. // Split the string at the "location" section so i can extract the ipaddress and service description url
  84. string locationDetails = deviceDetails.Substring(deviceDetails.IndexOf("Location", StringComparison.InvariantCultureIgnoreCase) + 9).Split('\r')[0];
  85. this.serviceType = serviceType;
  86. // Make sure we have no excess whitespace
  87. locationDetails = locationDetails.Trim();
  88. // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
  89. // Are we going to get addresses with the "http://" attached?
  90. if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
  91. {
  92. NatUtility.Log("Found device at: {0}", locationDetails);
  93. // This bit strings out the "http://" from the string
  94. locationDetails = locationDetails.Substring(7);
  95. // We then split off the end of the string to get something like: 192.168.0.3:241 in our string
  96. string hostAddressAndPort = locationDetails.Remove(locationDetails.IndexOf('/'));
  97. // From this we parse out the IP address and Port
  98. if (hostAddressAndPort.IndexOf(':') > 0)
  99. {
  100. this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort.Remove(hostAddressAndPort.IndexOf(':'))),
  101. Convert.ToUInt16(hostAddressAndPort.Substring(hostAddressAndPort.IndexOf(':') + 1), System.Globalization.CultureInfo.InvariantCulture));
  102. }
  103. else
  104. {
  105. // there is no port specified, use default port (80)
  106. this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort), 80);
  107. }
  108. NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString());
  109. // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
  110. // and port information
  111. this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
  112. }
  113. else
  114. {
  115. Trace.WriteLine("Couldn't decode address. Please send following string to the developer: ");
  116. Trace.WriteLine(deviceDetails);
  117. }
  118. }
  119. /// <summary>
  120. /// The EndPoint that the device is at
  121. /// </summary>
  122. internal EndPoint HostEndPoint
  123. {
  124. get { return this.hostEndPoint; }
  125. }
  126. /// <summary>
  127. /// The relative url of the xml file that describes the list of services is at
  128. /// </summary>
  129. internal string ServiceDescriptionUrl
  130. {
  131. get { return this.serviceDescriptionUrl; }
  132. }
  133. /// <summary>
  134. /// The relative url that we can use to control the port forwarding
  135. /// </summary>
  136. internal string ControlUrl
  137. {
  138. get { return this.controlUrl; }
  139. }
  140. /// <summary>
  141. /// The service type we're using on the device
  142. /// </summary>
  143. public string ServiceType
  144. {
  145. get { return serviceType; }
  146. }
  147. /// <summary>
  148. /// Begins an async call to get the external ip address of the router
  149. /// </summary>
  150. public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState)
  151. {
  152. // Create the port map message
  153. GetExternalIPAddressMessage message = new GetExternalIPAddressMessage(this);
  154. return BeginMessageInternal(message, callback, asyncState, EndGetExternalIPInternal);
  155. }
  156. /// <summary>
  157. /// Maps the specified port to this computer
  158. /// </summary>
  159. public override IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
  160. {
  161. CreatePortMappingMessage message = new CreatePortMappingMessage(mapping, localAddress, this);
  162. return BeginMessageInternal(message, callback, asyncState, EndCreatePortMapInternal);
  163. }
  164. /// <summary>
  165. /// Removes a port mapping from this computer
  166. /// </summary>
  167. public override IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
  168. {
  169. DeletePortMappingMessage message = new DeletePortMappingMessage(mapping, this);
  170. return BeginMessageInternal(message, callback, asyncState, EndDeletePortMapInternal);
  171. }
  172. public override IAsyncResult BeginGetAllMappings(AsyncCallback callback, object asyncState)
  173. {
  174. GetGenericPortMappingEntry message = new GetGenericPortMappingEntry(0, this);
  175. return BeginMessageInternal(message, callback, asyncState, EndGetAllMappingsInternal);
  176. }
  177. public override IAsyncResult BeginGetSpecificMapping (Protocol protocol, int port, AsyncCallback callback, object asyncState)
  178. {
  179. GetSpecificPortMappingEntryMessage message = new GetSpecificPortMappingEntryMessage(protocol, port, this);
  180. return this.BeginMessageInternal(message, callback, asyncState, new AsyncCallback(this.EndGetSpecificMappingInternal));
  181. }
  182. /// <summary>
  183. ///
  184. /// </summary>
  185. /// <param name="result"></param>
  186. public override void EndCreatePortMap(IAsyncResult result)
  187. {
  188. if (result == null) throw new ArgumentNullException("result");
  189. PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
  190. if (mappingResult == null)
  191. throw new ArgumentException("Invalid AsyncResult", "result");
  192. // Check if we need to wait for the operation to finish
  193. if (!result.IsCompleted)
  194. result.AsyncWaitHandle.WaitOne();
  195. // If we have a saved exception, it means something went wrong during the mapping
  196. // so we just rethrow the exception and let the user figure out what they should do.
  197. if (mappingResult.SavedMessage is ErrorMessage)
  198. {
  199. ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
  200. throw new MappingException(msg.ErrorCode, msg.Description);
  201. }
  202. //return result.AsyncState as Mapping;
  203. }
  204. /// <summary>
  205. ///
  206. /// </summary>
  207. /// <param name="result"></param>
  208. public override void EndDeletePortMap(IAsyncResult result)
  209. {
  210. if (result == null)
  211. throw new ArgumentNullException("result");
  212. PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
  213. if (mappingResult == null)
  214. throw new ArgumentException("Invalid AsyncResult", "result");
  215. // Check if we need to wait for the operation to finish
  216. if (!mappingResult.IsCompleted)
  217. mappingResult.AsyncWaitHandle.WaitOne();
  218. // If we have a saved exception, it means something went wrong during the mapping
  219. // so we just rethrow the exception and let the user figure out what they should do.
  220. if (mappingResult.SavedMessage is ErrorMessage)
  221. {
  222. ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
  223. throw new MappingException(msg.ErrorCode, msg.Description);
  224. }
  225. // If all goes well, we just return
  226. //return true;
  227. }
  228. public override Mapping[] EndGetAllMappings(IAsyncResult result)
  229. {
  230. if (result == null)
  231. throw new ArgumentNullException("result");
  232. GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;
  233. if (mappingResult == null)
  234. throw new ArgumentException("Invalid AsyncResult", "result");
  235. if (!mappingResult.IsCompleted)
  236. mappingResult.AsyncWaitHandle.WaitOne();
  237. if (mappingResult.SavedMessage is ErrorMessage)
  238. {
  239. ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
  240. if (msg.ErrorCode != 713)
  241. throw new MappingException(msg.ErrorCode, msg.Description);
  242. }
  243. return mappingResult.Mappings.ToArray();
  244. }
  245. /// <summary>
  246. /// Ends an async request to get the external ip address of the router
  247. /// </summary>
  248. public override IPAddress EndGetExternalIP(IAsyncResult result)
  249. {
  250. if (result == null) throw new ArgumentNullException("result");
  251. PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
  252. if (mappingResult == null)
  253. throw new ArgumentException("Invalid AsyncResult", "result");
  254. if (!result.IsCompleted)
  255. result.AsyncWaitHandle.WaitOne();
  256. if (mappingResult.SavedMessage is ErrorMessage)
  257. {
  258. ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
  259. throw new MappingException(msg.ErrorCode, msg.Description);
  260. }
  261. if (mappingResult.SavedMessage == null)
  262. return null;
  263. else
  264. return ((GetExternalIPAddressResponseMessage)mappingResult.SavedMessage).ExternalIPAddress;
  265. }
  266. public override Mapping EndGetSpecificMapping(IAsyncResult result)
  267. {
  268. if (result == null)
  269. throw new ArgumentNullException("result");
  270. GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;
  271. if (mappingResult == null)
  272. throw new ArgumentException("Invalid AsyncResult", "result");
  273. if (!mappingResult.IsCompleted)
  274. mappingResult.AsyncWaitHandle.WaitOne();
  275. if (mappingResult.SavedMessage is ErrorMessage)
  276. {
  277. ErrorMessage message = mappingResult.SavedMessage as ErrorMessage;
  278. if (message.ErrorCode != 0x2ca)
  279. {
  280. throw new MappingException(message.ErrorCode, message.Description);
  281. }
  282. }
  283. if (mappingResult.Mappings.Count == 0)
  284. return new Mapping (Protocol.Tcp, -1, -1);
  285. return mappingResult.Mappings[0];
  286. }
  287. public override bool Equals(object obj)
  288. {
  289. UpnpNatDevice device = obj as UpnpNatDevice;
  290. return (device == null) ? false : this.Equals((device));
  291. }
  292. public bool Equals(UpnpNatDevice other)
  293. {
  294. return (other == null) ? false : (this.hostEndPoint.Equals(other.hostEndPoint)
  295. //&& this.controlUrl == other.controlUrl
  296. && this.serviceDescriptionUrl == other.serviceDescriptionUrl);
  297. }
  298. public override int GetHashCode()
  299. {
  300. return (this.hostEndPoint.GetHashCode() ^ this.controlUrl.GetHashCode() ^ this.serviceDescriptionUrl.GetHashCode());
  301. }
  302. private IAsyncResult BeginMessageInternal(MessageBase message, AsyncCallback storedCallback, object asyncState, AsyncCallback callback)
  303. {
  304. byte[] body;
  305. WebRequest request = message.Encode(out body);
  306. PortMapAsyncResult mappingResult = PortMapAsyncResult.Create(message, request, storedCallback, asyncState);
  307. if (body.Length > 0)
  308. {
  309. request.ContentLength = body.Length;
  310. request.BeginGetRequestStream(delegate(IAsyncResult result) {
  311. try
  312. {
  313. Stream s = request.EndGetRequestStream(result);
  314. s.Write(body, 0, body.Length);
  315. request.BeginGetResponse(callback, mappingResult);
  316. }
  317. catch (Exception ex)
  318. {
  319. mappingResult.Complete(ex);
  320. }
  321. }, null);
  322. }
  323. else
  324. {
  325. request.BeginGetResponse(callback, mappingResult);
  326. }
  327. return mappingResult;
  328. }
  329. private void CompleteMessage(IAsyncResult result)
  330. {
  331. PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;
  332. mappingResult.CompletedSynchronously = result.CompletedSynchronously;
  333. mappingResult.Complete();
  334. }
  335. private MessageBase DecodeMessageFromResponse(Stream s, long length)
  336. {
  337. StringBuilder data = new StringBuilder();
  338. int bytesRead = 0;
  339. int totalBytesRead = 0;
  340. byte[] buffer = new byte[10240];
  341. // Read out the content of the message, hopefully picking everything up in the case where we have no contentlength
  342. if (length != -1)
  343. {
  344. while (totalBytesRead < length)
  345. {
  346. bytesRead = s.Read(buffer, 0, buffer.Length);
  347. data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  348. totalBytesRead += bytesRead;
  349. }
  350. }
  351. else
  352. {
  353. while ((bytesRead = s.Read(buffer, 0, buffer.Length)) != 0)
  354. data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  355. }
  356. // Once we have our content, we need to see what kind of message it is. It'll either a an error
  357. // or a response based on the action we performed.
  358. return MessageBase.Decode(this, data.ToString());
  359. }
  360. private void EndCreatePortMapInternal(IAsyncResult result)
  361. {
  362. EndMessageInternal(result);
  363. CompleteMessage(result);
  364. }
  365. private void EndMessageInternal(IAsyncResult result)
  366. {
  367. HttpWebResponse response = null;
  368. PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;
  369. try
  370. {
  371. try
  372. {
  373. response = (HttpWebResponse)mappingResult.Request.EndGetResponse(result);
  374. }
  375. catch (WebException ex)
  376. {
  377. // Even if the request "failed" i want to continue on to read out the response from the router
  378. response = ex.Response as HttpWebResponse;
  379. if (response == null)
  380. mappingResult.SavedMessage = new ErrorMessage((int)ex.Status, ex.Message);
  381. }
  382. if (response != null)
  383. mappingResult.SavedMessage = DecodeMessageFromResponse(response.GetResponseStream(), response.ContentLength);
  384. }
  385. finally
  386. {
  387. if (response != null)
  388. response.Close();
  389. }
  390. }
  391. private void EndDeletePortMapInternal(IAsyncResult result)
  392. {
  393. EndMessageInternal(result);
  394. CompleteMessage(result);
  395. }
  396. private void EndGetAllMappingsInternal(IAsyncResult result)
  397. {
  398. EndMessageInternal(result);
  399. GetAllMappingsAsyncResult mappingResult = result.AsyncState as GetAllMappingsAsyncResult;
  400. GetGenericPortMappingEntryResponseMessage message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage;
  401. if (message != null)
  402. {
  403. Mapping mapping = new Mapping (message.Protocol, message.InternalPort, message.ExternalPort, message.LeaseDuration);
  404. mapping.Description = message.PortMappingDescription;
  405. mappingResult.Mappings.Add(mapping);
  406. GetGenericPortMappingEntry next = new GetGenericPortMappingEntry(mappingResult.Mappings.Count, this);
  407. // It's ok to do this synchronously because we should already be on anther thread
  408. // and this won't block the user.
  409. byte[] body;
  410. WebRequest request = next.Encode(out body);
  411. if (body.Length > 0)
  412. {
  413. request.ContentLength = body.Length;
  414. request.GetRequestStream().Write(body, 0, body.Length);
  415. }
  416. mappingResult.Request = request;
  417. request.BeginGetResponse(EndGetAllMappingsInternal, mappingResult);
  418. return;
  419. }
  420. CompleteMessage(result);
  421. }
  422. private void EndGetExternalIPInternal(IAsyncResult result)
  423. {
  424. EndMessageInternal(result);
  425. CompleteMessage(result);
  426. }
  427. private void EndGetSpecificMappingInternal(IAsyncResult result)
  428. {
  429. EndMessageInternal(result);
  430. GetAllMappingsAsyncResult mappingResult = result.AsyncState as GetAllMappingsAsyncResult;
  431. GetGenericPortMappingEntryResponseMessage message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage;
  432. if (message != null) {
  433. Mapping mapping = new Mapping(mappingResult.SpecificMapping.Protocol, message.InternalPort, mappingResult.SpecificMapping.PublicPort, message.LeaseDuration);
  434. mapping.Description = mappingResult.SpecificMapping.Description;
  435. mappingResult.Mappings.Add(mapping);
  436. }
  437. CompleteMessage(result);
  438. }
  439. internal void GetServicesList(NatDeviceCallback callback)
  440. {
  441. // Save the callback so i can use it again later when i've finished parsing the services available
  442. this.callback = callback;
  443. // Create a HTTPWebRequest to download the list of services the device offers
  444. byte[] body;
  445. WebRequest request = new GetServicesMessage(this.serviceDescriptionUrl, this.hostEndPoint).Encode(out body);
  446. if (body.Length > 0)
  447. NatUtility.Log("Error: Services Message contained a body");
  448. request.BeginGetResponse(this.ServicesReceived, request);
  449. }
  450. private void ServicesReceived(IAsyncResult result)
  451. {
  452. HttpWebResponse response = null;
  453. try
  454. {
  455. int abortCount = 0;
  456. int bytesRead = 0;
  457. byte[] buffer = new byte[10240];
  458. StringBuilder servicesXml = new StringBuilder();
  459. XmlDocument xmldoc = new XmlDocument();
  460. HttpWebRequest request = result.AsyncState as HttpWebRequest;
  461. response = request.EndGetResponse(result) as HttpWebResponse;
  462. Stream s = response.GetResponseStream();
  463. if (response.StatusCode != HttpStatusCode.OK) {
  464. NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
  465. return; // FIXME: This the best thing to do??
  466. }
  467. while (true)
  468. {
  469. bytesRead = s.Read(buffer, 0, buffer.Length);
  470. servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  471. try
  472. {
  473. xmldoc.LoadXml(servicesXml.ToString());
  474. response.Close();
  475. break;
  476. }
  477. catch (XmlException)
  478. {
  479. // If we can't receive the entire XML within 500ms, then drop the connection
  480. // Unfortunately not all routers supply a valid ContentLength (mine doesn't)
  481. // so this hack is needed to keep testing our recieved data until it gets successfully
  482. // parsed by the xmldoc. Without this, the code will never pick up my router.
  483. if (abortCount++ > 50)
  484. {
  485. response.Close();
  486. return;
  487. }
  488. NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint);
  489. System.Threading.Thread.Sleep(10);
  490. }
  491. }
  492. NatUtility.Log("{0}: Parsed services list", HostEndPoint);
  493. XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
  494. ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
  495. XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns);
  496. foreach (XmlNode node in nodes)
  497. {
  498. //Go through each service there
  499. foreach (XmlNode service in node.ChildNodes)
  500. {
  501. //If the service is a WANIPConnection, then we have what we want
  502. string type = service["serviceType"].InnerText;
  503. NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type);
  504. StringComparison c = StringComparison.OrdinalIgnoreCase;
  505. // TODO: Add support for version 2 of UPnP.
  506. if (type.Equals("urn:schemas-upnp-org:service:WANPPPConnection:1", c) ||
  507. type.Equals("urn:schemas-upnp-org:service:WANIPConnection:1", c))
  508. {
  509. this.controlUrl = service["controlURL"].InnerText;
  510. NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
  511. try
  512. {
  513. Uri u = new Uri(controlUrl);
  514. if (u.IsAbsoluteUri)
  515. {
  516. EndPoint old = hostEndPoint;
  517. this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port);
  518. NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
  519. this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
  520. NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl);
  521. }
  522. }
  523. catch
  524. {
  525. NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
  526. }
  527. NatUtility.Log("{0}: Handshake Complete", HostEndPoint);
  528. this.callback(this);
  529. return;
  530. }
  531. }
  532. }
  533. //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding
  534. //So we don't invoke the callback, so this device is never added to our lists
  535. }
  536. catch (WebException ex)
  537. {
  538. // Just drop the connection, FIXME: Should i retry?
  539. NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex);
  540. }
  541. finally
  542. {
  543. if (response != null)
  544. response.Close();
  545. }
  546. }
  547. /// <summary>
  548. /// Overridden.
  549. /// </summary>
  550. /// <returns></returns>
  551. public override string ToString( )
  552. {
  553. //GetExternalIP is blocking and can throw exceptions, can't use it here.
  554. return String.Format(
  555. "UpnpNatDevice - EndPoint: {0}, External IP: {1}, Control Url: {2}, Service Description Url: {3}, Service Type: {4}, Last Seen: {5}",
  556. this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen);
  557. }
  558. }
  559. }