ExternalPortForwarding.cs 7.0 KB

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