ExternalPortForwarding.cs 8.8 KB

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