NatUtility.cs 7.8 KB

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