2
0

ExternalPortForwarding.cs 9.9 KB

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