NatUtility.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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.Collections.Generic;
  33. using System.IO;
  34. using System.Net.NetworkInformation;
  35. using System.Threading.Tasks;
  36. using MediaBrowser.Common.Net;
  37. using MediaBrowser.Model.Dlna;
  38. using MediaBrowser.Model.Logging;
  39. namespace Mono.Nat
  40. {
  41. public static class NatUtility
  42. {
  43. public static event EventHandler<DeviceEventArgs> DeviceFound;
  44. public static event EventHandler<DeviceEventArgs> DeviceLost;
  45. private static List<ISearcher> controllers;
  46. private static bool verbose;
  47. public static List<NatProtocol> EnabledProtocols { get; set; }
  48. public static ILogger Logger { get; set; }
  49. public static IHttpClient HttpClient { get; set; }
  50. public static bool Verbose
  51. {
  52. get { return verbose; }
  53. set { verbose = value; }
  54. }
  55. static NatUtility()
  56. {
  57. EnabledProtocols = new List<NatProtocol>
  58. {
  59. NatProtocol.Pmp
  60. };
  61. controllers = new List<ISearcher>();
  62. controllers.Add(PmpSearcher.Instance);
  63. controllers.ForEach(searcher =>
  64. {
  65. searcher.DeviceFound += (sender, args) =>
  66. {
  67. if (DeviceFound != null)
  68. DeviceFound(sender, args);
  69. };
  70. searcher.DeviceLost += (sender, args) =>
  71. {
  72. if (DeviceLost != null)
  73. DeviceLost(sender, args);
  74. };
  75. });
  76. }
  77. internal static void Log(string format, params object[] args)
  78. {
  79. var logger = Logger;
  80. if (logger != null)
  81. logger.Debug(format, args);
  82. }
  83. private static async Task SearchAndListen(CancellationToken cancellationToken)
  84. {
  85. while (!cancellationToken.IsCancellationRequested)
  86. {
  87. try
  88. {
  89. if (EnabledProtocols.Contains(PmpSearcher.Instance.Protocol))
  90. {
  91. await Receive(PmpSearcher.Instance, PmpSearcher.sockets).ConfigureAwait(false);
  92. }
  93. foreach (ISearcher s in controllers)
  94. {
  95. if (s.NextSearch < DateTime.Now && EnabledProtocols.Contains(s.Protocol))
  96. {
  97. Log("Searching for: {0}", s.GetType().Name);
  98. s.Search();
  99. }
  100. }
  101. }
  102. catch (Exception e)
  103. {
  104. }
  105. await Task.Delay(100).ConfigureAwait(false);
  106. }
  107. }
  108. static async Task Receive(ISearcher searcher, List<UdpClient> clients)
  109. {
  110. foreach (UdpClient client in clients)
  111. {
  112. if (client.Available > 0)
  113. {
  114. IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
  115. var result = await client.ReceiveAsync().ConfigureAwait(false);
  116. var data = result.Buffer;
  117. var received = result.RemoteEndPoint;
  118. searcher.Handle(localAddress, data, received);
  119. }
  120. }
  121. }
  122. private static CancellationTokenSource _currentCancellationTokenSource;
  123. private static object _runSyncLock = new object();
  124. public static void StartDiscovery()
  125. {
  126. lock (_runSyncLock)
  127. {
  128. if (_currentCancellationTokenSource == null)
  129. {
  130. return;
  131. }
  132. var tokenSource = new CancellationTokenSource();
  133. _currentCancellationTokenSource = tokenSource;
  134. //Task.Factory.StartNew(() => SearchAndListen(tokenSource.Token), tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  135. }
  136. }
  137. public static void StopDiscovery()
  138. {
  139. lock (_runSyncLock)
  140. {
  141. var tokenSource = _currentCancellationTokenSource;
  142. if (tokenSource != null)
  143. {
  144. try
  145. {
  146. tokenSource.Cancel();
  147. tokenSource.Dispose();
  148. }
  149. catch
  150. {
  151. }
  152. _currentCancellationTokenSource = null;
  153. }
  154. }
  155. }
  156. //checks if an IP address is a private address space as defined by RFC 1918
  157. public static bool IsPrivateAddressSpace(IPAddress address)
  158. {
  159. byte[] ba = address.GetAddressBytes();
  160. switch ((int)ba[0])
  161. {
  162. case 10:
  163. return true; //10.x.x.x
  164. case 172:
  165. return ((int)ba[1] & 16) != 0; //172.16-31.x.x
  166. case 192:
  167. return (int)ba[1] == 168; //192.168.x.x
  168. default:
  169. return false;
  170. }
  171. }
  172. public static void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint, NatProtocol protocol)
  173. {
  174. switch (protocol)
  175. {
  176. case NatProtocol.Upnp:
  177. //UpnpSearcher.Instance.Handle(localAddress, response, endpoint);
  178. break;
  179. case NatProtocol.Pmp:
  180. PmpSearcher.Instance.Handle(localAddress, response, endpoint);
  181. break;
  182. default:
  183. throw new ArgumentException("Unexpected protocol: " + protocol);
  184. }
  185. }
  186. public static void Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint, NatProtocol protocol)
  187. {
  188. switch (protocol)
  189. {
  190. case NatProtocol.Upnp:
  191. var searcher = new UpnpSearcher(Logger, HttpClient);
  192. searcher.DeviceFound += Searcher_DeviceFound;
  193. searcher.Handle(localAddress, deviceInfo, endpoint);
  194. break;
  195. default:
  196. throw new ArgumentException("Unexpected protocol: " + protocol);
  197. }
  198. }
  199. private static void Searcher_DeviceFound(object sender, DeviceEventArgs e)
  200. {
  201. if (DeviceFound != null)
  202. {
  203. DeviceFound(sender, e);
  204. }
  205. }
  206. }
  207. }