ExternalPortForwarding.cs 8.7 KB

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