NatUtility.cs 6.7 KB

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