ExternalPortForwarding.cs 8.6 KB

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