ExternalPortForwarding.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. _logger.ErrorException("Error creating port forwarding rules", ex);
  124. }
  125. }
  126. private List<string> _createdRules = new List<string>();
  127. private void CreateRules(INatDevice device)
  128. {
  129. // On some systems the device discovered event seems to fire repeatedly
  130. // This check will help ensure we're not trying to port map the same device over and over
  131. var address = device.LocalAddress.ToString();
  132. if (!_createdRules.Contains(address))
  133. {
  134. _createdRules.Add(address);
  135. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  136. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  137. }
  138. }
  139. private void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  140. {
  141. _logger.Debug("Creating port map on port {0}", privatePort);
  142. device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  143. {
  144. Description = _appHost.Name
  145. });
  146. }
  147. // As I said before, this method will be never invoked. You can remove it.
  148. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  149. {
  150. var device = e.Device;
  151. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  152. }
  153. public void Dispose()
  154. {
  155. DisposeNat();
  156. }
  157. private void DisposeNat()
  158. {
  159. _logger.Debug("Stopping NAT discovery");
  160. if (_timer != null)
  161. {
  162. _timer.Dispose();
  163. _timer = null;
  164. }
  165. _ssdp.MessageReceived -= _ssdp_MessageReceived;
  166. try
  167. {
  168. // This is not a significant improvement
  169. NatUtility.StopDiscovery();
  170. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  171. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  172. NatUtility.UnhandledException -= NatUtility_UnhandledException;
  173. }
  174. // Statements in try-block will no fail because StopDiscovery is a one-line
  175. // method that was no chances to fail.
  176. // public static void StopDiscovery ()
  177. // {
  178. // searching.Reset();
  179. // }
  180. // IMO you could remove the catch-block
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error stopping NAT Discovery", ex);
  184. }
  185. finally
  186. {
  187. _isStarted = false;
  188. }
  189. }
  190. private class LogWriter : TextWriter
  191. {
  192. private readonly ILogger _logger;
  193. public LogWriter(ILogger logger)
  194. {
  195. _logger = logger;
  196. }
  197. public override Encoding Encoding
  198. {
  199. get { return Encoding.UTF8; }
  200. }
  201. public override void WriteLine(string format, params object[] arg)
  202. {
  203. _logger.Debug(format, arg);
  204. }
  205. public override void WriteLine(string value)
  206. {
  207. _logger.Debug(value);
  208. }
  209. }
  210. }
  211. }