ExternalPortForwarding.cs 7.8 KB

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