NatUtility.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //
  2. // Authors:
  3. // Ben Motmans <ben.motmans@gmail.com>
  4. // Nicholas Terry <nick.i.terry@gmail.com>
  5. //
  6. // Copyright (C) 2007 Ben Motmans
  7. // Copyright (C) 2014 Nicholas Terry
  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.Net.Sockets;
  31. using System.Threading;
  32. using System.Linq;
  33. using System.Collections.Generic;
  34. using System.IO;
  35. using System.Net.NetworkInformation;
  36. using MediaBrowser.Controller.Dlna;
  37. using MediaBrowser.Model.Logging;
  38. using Mono.Nat.Pmp.Mappers;
  39. using Mono.Nat.Upnp.Mappers;
  40. namespace Mono.Nat
  41. {
  42. public static class NatUtility
  43. {
  44. private static ManualResetEvent searching;
  45. public static event EventHandler<DeviceEventArgs> DeviceFound;
  46. public static event EventHandler<DeviceEventArgs> DeviceLost;
  47. public static event EventHandler<UnhandledExceptionEventArgs> UnhandledException;
  48. private static List<ISearcher> controllers;
  49. private static bool verbose;
  50. public static List<NatProtocol> EnabledProtocols { get; set; }
  51. public static ILogger Logger { get; set; }
  52. public static bool Verbose
  53. {
  54. get { return verbose; }
  55. set { verbose = value; }
  56. }
  57. static NatUtility()
  58. {
  59. EnabledProtocols = new List<NatProtocol>
  60. {
  61. NatProtocol.Upnp,
  62. NatProtocol.Pmp
  63. };
  64. searching = new ManualResetEvent(false);
  65. controllers = new List<ISearcher>();
  66. controllers.Add(UpnpSearcher.Instance);
  67. controllers.Add(PmpSearcher.Instance);
  68. controllers.ForEach(searcher =>
  69. {
  70. searcher.DeviceFound += (sender, args) =>
  71. {
  72. if (DeviceFound != null)
  73. DeviceFound(sender, args);
  74. };
  75. searcher.DeviceLost += (sender, args) =>
  76. {
  77. if (DeviceLost != null)
  78. DeviceLost(sender, args);
  79. };
  80. });
  81. Thread t = new Thread(SearchAndListen);
  82. t.IsBackground = true;
  83. t.Start();
  84. }
  85. internal static void Log(string format, params object[] args)
  86. {
  87. var logger = Logger;
  88. if (logger != null)
  89. logger.Debug(format, args);
  90. }
  91. private static void SearchAndListen()
  92. {
  93. while (true)
  94. {
  95. searching.WaitOne();
  96. try
  97. {
  98. var enabledProtocols = EnabledProtocols.ToList();
  99. if (enabledProtocols.Contains(UpnpSearcher.Instance.Protocol))
  100. {
  101. Receive(UpnpSearcher.Instance, UpnpSearcher.sockets);
  102. }
  103. if (enabledProtocols.Contains(PmpSearcher.Instance.Protocol))
  104. {
  105. Receive(PmpSearcher.Instance, PmpSearcher.sockets);
  106. }
  107. foreach (ISearcher s in controllers)
  108. if (s.NextSearch < DateTime.Now && enabledProtocols.Contains(s.Protocol))
  109. {
  110. Log("Searching for: {0}", s.GetType().Name);
  111. s.Search();
  112. }
  113. }
  114. catch (Exception e)
  115. {
  116. if (UnhandledException != null)
  117. UnhandledException(typeof(NatUtility), new UnhandledExceptionEventArgs(e, false));
  118. }
  119. Thread.Sleep(10);
  120. }
  121. }
  122. static void Receive (ISearcher searcher, List<UdpClient> clients)
  123. {
  124. IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
  125. foreach (UdpClient client in clients)
  126. {
  127. if (client.Available > 0)
  128. {
  129. IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
  130. byte[] data = client.Receive(ref received);
  131. searcher.Handle(localAddress, data, received);
  132. }
  133. }
  134. }
  135. static void Receive(IMapper mapper, List<UdpClient> clients)
  136. {
  137. IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
  138. foreach (UdpClient client in clients)
  139. {
  140. if (client.Available > 0)
  141. {
  142. IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
  143. byte[] data = client.Receive(ref received);
  144. mapper.Handle(localAddress, data);
  145. }
  146. }
  147. }
  148. public static void StartDiscovery ()
  149. {
  150. searching.Set();
  151. }
  152. public static void StopDiscovery ()
  153. {
  154. searching.Reset();
  155. }
  156. //This is for when you know the Gateway IP and want to skip the costly search...
  157. public static void DirectMap(IPAddress gatewayAddress, MapperType type)
  158. {
  159. IMapper mapper;
  160. switch (type)
  161. {
  162. case MapperType.Pmp:
  163. mapper = new PmpMapper();
  164. break;
  165. case MapperType.Upnp:
  166. mapper = new UpnpMapper();
  167. mapper.DeviceFound += (sender, args) =>
  168. {
  169. if (DeviceFound != null)
  170. DeviceFound(sender, args);
  171. };
  172. mapper.Map(gatewayAddress);
  173. break;
  174. default:
  175. throw new InvalidOperationException("Unsuported type given");
  176. }
  177. searching.Reset();
  178. }
  179. //So then why is it here? -Nick
  180. [Obsolete ("This method serves no purpose and shouldn't be used")]
  181. public static IPAddress[] GetLocalAddresses (bool includeIPv6)
  182. {
  183. List<IPAddress> addresses = new List<IPAddress> ();
  184. IPHostEntry hostInfo = Dns.GetHostEntry (Dns.GetHostName ());
  185. foreach (IPAddress address in hostInfo.AddressList) {
  186. if (address.AddressFamily == AddressFamily.InterNetwork ||
  187. (includeIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) {
  188. addresses.Add (address);
  189. }
  190. }
  191. return addresses.ToArray ();
  192. }
  193. //checks if an IP address is a private address space as defined by RFC 1918
  194. public static bool IsPrivateAddressSpace (IPAddress address)
  195. {
  196. byte[] ba = address.GetAddressBytes ();
  197. switch ((int)ba[0]) {
  198. case 10:
  199. return true; //10.x.x.x
  200. case 172:
  201. return ((int)ba[1] & 16) != 0; //172.16-31.x.x
  202. case 192:
  203. return (int)ba[1] == 168; //192.168.x.x
  204. default:
  205. return false;
  206. }
  207. }
  208. public static void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint, NatProtocol protocol)
  209. {
  210. switch (protocol)
  211. {
  212. case NatProtocol.Upnp:
  213. UpnpSearcher.Instance.Handle(localAddress, response, endpoint);
  214. break;
  215. case NatProtocol.Pmp:
  216. PmpSearcher.Instance.Handle(localAddress, response, endpoint);
  217. break;
  218. default:
  219. throw new ArgumentException("Unexpected protocol: " + protocol);
  220. }
  221. }
  222. public static void Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint, NatProtocol protocol)
  223. {
  224. switch (protocol)
  225. {
  226. case NatProtocol.Upnp:
  227. UpnpSearcher.Instance.Handle(localAddress, deviceInfo, endpoint);
  228. break;
  229. default:
  230. throw new ArgumentException("Unexpected protocol: " + protocol);
  231. }
  232. }
  233. }
  234. }