ExternalPortForwarding.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Dlna;
  4. using MediaBrowser.Controller.Plugins;
  5. using MediaBrowser.Model.Logging;
  6. using Mono.Nat;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Net;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Model.Events;
  13. using MediaBrowser.Server.Implementations.Threading;
  14. namespace MediaBrowser.Server.Implementations.EntryPoints
  15. {
  16. public class ExternalPortForwarding : IServerEntryPoint
  17. {
  18. private readonly IServerApplicationHost _appHost;
  19. private readonly ILogger _logger;
  20. private readonly IHttpClient _httpClient;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly IDeviceDiscovery _deviceDiscovery;
  23. private PeriodicTimer _timer;
  24. private bool _isStarted;
  25. public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient)
  26. {
  27. _logger = logmanager.GetLogger("PortMapper");
  28. _appHost = appHost;
  29. _config = config;
  30. _deviceDiscovery = deviceDiscovery;
  31. _httpClient = httpClient;
  32. }
  33. private string _lastConfigIdentifier;
  34. private string GetConfigIdentifier()
  35. {
  36. var values = new List<string>();
  37. var config = _config.Configuration;
  38. values.Add(config.EnableUPnP.ToString());
  39. values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture));
  40. values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture));
  41. values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture));
  42. values.Add(config.EnableHttps.ToString());
  43. values.Add(_appHost.EnableHttps.ToString());
  44. return string.Join("|", values.ToArray());
  45. }
  46. void _config_ConfigurationUpdated(object sender, EventArgs e)
  47. {
  48. if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
  49. {
  50. if (_isStarted)
  51. {
  52. DisposeNat();
  53. }
  54. Run();
  55. }
  56. }
  57. public void Run()
  58. {
  59. NatUtility.Logger = _logger;
  60. NatUtility.HttpClient = _httpClient;
  61. if (_config.Configuration.EnableUPnP)
  62. {
  63. Start();
  64. }
  65. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  66. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  67. }
  68. private void Start()
  69. {
  70. _logger.Debug("Starting NAT discovery");
  71. NatUtility.EnabledProtocols = new List<NatProtocol>
  72. {
  73. NatProtocol.Pmp
  74. };
  75. NatUtility.DeviceFound += NatUtility_DeviceFound;
  76. // Mono.Nat does never rise this event. The event is there however it is useless.
  77. // You could remove it with no risk.
  78. NatUtility.DeviceLost += NatUtility_DeviceLost;
  79. // it is hard to say what one should do when an unhandled exception is raised
  80. // because there isn't anything one can do about it. Probably save a log or ignored it.
  81. NatUtility.UnhandledException += NatUtility_UnhandledException;
  82. NatUtility.StartDiscovery();
  83. _timer = new PeriodicTimer(ClearCreatedRules, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  84. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  85. _lastConfigIdentifier = GetConfigIdentifier();
  86. _isStarted = true;
  87. }
  88. private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  89. {
  90. var info = e.Argument;
  91. string usn;
  92. if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
  93. string nt;
  94. if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
  95. // Filter device type
  96. if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  97. nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  98. usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  99. nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
  100. {
  101. return;
  102. }
  103. var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
  104. if (info.Location == null)
  105. {
  106. return;
  107. }
  108. lock (_usnsHandled)
  109. {
  110. if (_usnsHandled.Contains(identifier))
  111. {
  112. return;
  113. }
  114. _usnsHandled.Add(identifier);
  115. }
  116. _logger.Debug("Found NAT device: " + identifier);
  117. IPAddress address;
  118. if (IPAddress.TryParse(info.Location.Host, out address))
  119. {
  120. // The Handle method doesn't need the port
  121. var endpoint = new IPEndPoint(address, info.Location.Port);
  122. IPAddress localAddress = null;
  123. try
  124. {
  125. var localAddressString = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  126. Uri uri;
  127. if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri))
  128. {
  129. localAddressString = uri.Host;
  130. if (!IPAddress.TryParse(localAddressString, out localAddress))
  131. {
  132. return;
  133. }
  134. }
  135. }
  136. catch (Exception ex)
  137. {
  138. return;
  139. }
  140. _logger.Debug("Calling Nat.Handle on " + identifier);
  141. NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
  142. }
  143. }
  144. private void ClearCreatedRules(object state)
  145. {
  146. _createdRules = new List<string>();
  147. lock (_usnsHandled)
  148. {
  149. _usnsHandled.Clear();
  150. }
  151. }
  152. void NatUtility_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  153. {
  154. var ex = e.ExceptionObject as Exception;
  155. if (ex == null)
  156. {
  157. //_logger.Error("Unidentified error reported by Mono.Nat");
  158. }
  159. else
  160. {
  161. // Seeing some blank exceptions coming through here
  162. //_logger.ErrorException("Error reported by Mono.Nat: ", ex);
  163. }
  164. }
  165. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  166. {
  167. try
  168. {
  169. var device = e.Device;
  170. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  171. CreateRules(device);
  172. }
  173. catch
  174. {
  175. // I think it could be a good idea to log the exception because
  176. // you are using permanent portmapping here (never expire) and that means that next time
  177. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  178. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  179. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  180. // and those errors (upnp errors) could be useful for diagnosting.
  181. // Commenting out because users are reporting problems out of our control
  182. //_logger.ErrorException("Error creating port forwarding rules", ex);
  183. }
  184. }
  185. private List<string> _createdRules = new List<string>();
  186. private List<string> _usnsHandled = new List<string>();
  187. private void CreateRules(INatDevice device)
  188. {
  189. // On some systems the device discovered event seems to fire repeatedly
  190. // This check will help ensure we're not trying to port map the same device over and over
  191. var address = device.LocalAddress.ToString();
  192. if (!_createdRules.Contains(address))
  193. {
  194. _createdRules.Add(address);
  195. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  196. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  197. }
  198. }
  199. private async void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  200. {
  201. _logger.Debug("Creating port map on port {0}", privatePort);
  202. try
  203. {
  204. await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  205. {
  206. Description = _appHost.Name
  207. }).ConfigureAwait(false);
  208. }
  209. catch (Exception ex)
  210. {
  211. _logger.ErrorException("Error creating port map", ex);
  212. }
  213. }
  214. // As I said before, this method will be never invoked. You can remove it.
  215. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  216. {
  217. var device = e.Device;
  218. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  219. }
  220. public void Dispose()
  221. {
  222. DisposeNat();
  223. }
  224. private void DisposeNat()
  225. {
  226. _logger.Debug("Stopping NAT discovery");
  227. if (_timer != null)
  228. {
  229. _timer.Dispose();
  230. _timer = null;
  231. }
  232. _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
  233. try
  234. {
  235. // This is not a significant improvement
  236. NatUtility.StopDiscovery();
  237. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  238. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  239. NatUtility.UnhandledException -= NatUtility_UnhandledException;
  240. }
  241. // Statements in try-block will no fail because StopDiscovery is a one-line
  242. // method that was no chances to fail.
  243. // public static void StopDiscovery ()
  244. // {
  245. // searching.Reset();
  246. // }
  247. // IMO you could remove the catch-block
  248. catch (Exception ex)
  249. {
  250. _logger.ErrorException("Error stopping NAT Discovery", ex);
  251. }
  252. finally
  253. {
  254. _isStarted = false;
  255. }
  256. }
  257. }
  258. }