ExternalPortForwarding.cs 9.1 KB

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