NatUtility.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.Pmp
  62. };
  63. searching = new ManualResetEvent(false);
  64. controllers = new List<ISearcher>();
  65. controllers.Add(PmpSearcher.Instance);
  66. controllers.ForEach(searcher =>
  67. {
  68. searcher.DeviceFound += (sender, args) =>
  69. {
  70. if (DeviceFound != null)
  71. DeviceFound(sender, args);
  72. };
  73. searcher.DeviceLost += (sender, args) =>
  74. {
  75. if (DeviceLost != null)
  76. DeviceLost(sender, args);
  77. };
  78. });
  79. Thread t = new Thread(SearchAndListen);
  80. t.IsBackground = true;
  81. t.Start();
  82. }
  83. internal static void Log(string format, params object[] args)
  84. {
  85. var logger = Logger;
  86. if (logger != null)
  87. logger.Debug(format, args);
  88. }
  89. private static void SearchAndListen()
  90. {
  91. while (true)
  92. {
  93. searching.WaitOne();
  94. try
  95. {
  96. var enabledProtocols = EnabledProtocols.ToList();
  97. if (enabledProtocols.Contains(PmpSearcher.Instance.Protocol))
  98. {
  99. Receive(PmpSearcher.Instance, PmpSearcher.sockets);
  100. }
  101. foreach (ISearcher s in controllers)
  102. if (s.NextSearch < DateTime.Now && enabledProtocols.Contains(s.Protocol))
  103. {
  104. Log("Searching for: {0}", s.GetType().Name);
  105. s.Search();
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. if (UnhandledException != null)
  111. UnhandledException(typeof(NatUtility), new UnhandledExceptionEventArgs(e, false));
  112. }
  113. Thread.Sleep(10);
  114. }
  115. }
  116. static void Receive (ISearcher searcher, List<UdpClient> clients)
  117. {
  118. IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
  119. foreach (UdpClient client in clients)
  120. {
  121. if (client.Available > 0)
  122. {
  123. IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
  124. byte[] data = client.Receive(ref received);
  125. searcher.Handle(localAddress, data, received);
  126. }
  127. }
  128. }
  129. public static void StartDiscovery ()
  130. {
  131. searching.Set();
  132. }
  133. public static void StopDiscovery ()
  134. {
  135. searching.Reset();
  136. }
  137. //This is for when you know the Gateway IP and want to skip the costly search...
  138. public static void DirectMap(IPAddress gatewayAddress, MapperType type)
  139. {
  140. IMapper mapper;
  141. switch (type)
  142. {
  143. case MapperType.Pmp:
  144. mapper = new PmpMapper();
  145. break;
  146. case MapperType.Upnp:
  147. mapper = new UpnpMapper(Logger);
  148. mapper.DeviceFound += (sender, args) =>
  149. {
  150. if (DeviceFound != null)
  151. DeviceFound(sender, args);
  152. };
  153. mapper.Map(gatewayAddress);
  154. break;
  155. default:
  156. throw new InvalidOperationException("Unsuported type given");
  157. }
  158. searching.Reset();
  159. }
  160. //checks if an IP address is a private address space as defined by RFC 1918
  161. public static bool IsPrivateAddressSpace (IPAddress address)
  162. {
  163. byte[] ba = address.GetAddressBytes ();
  164. switch ((int)ba[0]) {
  165. case 10:
  166. return true; //10.x.x.x
  167. case 172:
  168. return ((int)ba[1] & 16) != 0; //172.16-31.x.x
  169. case 192:
  170. return (int)ba[1] == 168; //192.168.x.x
  171. default:
  172. return false;
  173. }
  174. }
  175. public static void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint, NatProtocol protocol)
  176. {
  177. switch (protocol)
  178. {
  179. case NatProtocol.Upnp:
  180. //UpnpSearcher.Instance.Handle(localAddress, response, endpoint);
  181. break;
  182. case NatProtocol.Pmp:
  183. PmpSearcher.Instance.Handle(localAddress, response, endpoint);
  184. break;
  185. default:
  186. throw new ArgumentException("Unexpected protocol: " + protocol);
  187. }
  188. }
  189. public static void Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint, NatProtocol protocol)
  190. {
  191. switch (protocol)
  192. {
  193. case NatProtocol.Upnp:
  194. new UpnpSearcher(Logger).Handle(localAddress, deviceInfo, endpoint);
  195. break;
  196. default:
  197. throw new ArgumentException("Unexpected protocol: " + protocol);
  198. }
  199. }
  200. }
  201. }