ExternalPortForwarding.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 MediaBrowser.Common.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 PeriodicTimer _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. if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
  47. {
  48. if (_isStarted)
  49. {
  50. DisposeNat();
  51. }
  52. Run();
  53. }
  54. }
  55. public void Run()
  56. {
  57. //NatUtility.Logger = new LogWriter(_logger);
  58. if (_config.Configuration.EnableUPnP)
  59. {
  60. Start();
  61. }
  62. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  63. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  64. }
  65. private void Start()
  66. {
  67. _logger.Debug("Starting NAT discovery");
  68. NatUtility.EnabledProtocols = new List<NatProtocol>
  69. {
  70. NatProtocol.Pmp
  71. };
  72. NatUtility.DeviceFound += NatUtility_DeviceFound;
  73. // Mono.Nat does never rise this event. The event is there however it is useless.
  74. // You could remove it with no risk.
  75. NatUtility.DeviceLost += NatUtility_DeviceLost;
  76. // it is hard to say what one should do when an unhandled exception is raised
  77. // because there isn't anything one can do about it. Probably save a log or ignored it.
  78. NatUtility.UnhandledException += NatUtility_UnhandledException;
  79. NatUtility.StartDiscovery();
  80. _timer = new PeriodicTimer(ClearCreatedRules, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  81. _ssdp.MessageReceived += _ssdp_MessageReceived;
  82. _lastConfigIdentifier = GetConfigIdentifier();
  83. _isStarted = true;
  84. }
  85. private void ClearCreatedRules(object state)
  86. {
  87. _createdRules = new List<string>();
  88. _usnsHandled = new List<string>();
  89. }
  90. void _ssdp_MessageReceived(object sender, SsdpMessageEventArgs e)
  91. {
  92. var endpoint = e.EndPoint as IPEndPoint;
  93. if (endpoint == null || e.LocalEndPoint == null)
  94. {
  95. return;
  96. }
  97. string usn;
  98. if (!e.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
  99. string nt;
  100. if (!e.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
  101. // Filter device type
  102. if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  103. nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  104. usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  105. nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
  106. {
  107. return;
  108. }
  109. var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
  110. if (!_usnsHandled.Contains(identifier))
  111. {
  112. _usnsHandled.Add(identifier);
  113. _logger.Debug("Calling Nat.Handle on " + identifier);
  114. NatUtility.Handle(e.LocalEndPoint.Address, e.Message, endpoint, NatProtocol.Upnp);
  115. }
  116. }
  117. void NatUtility_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  118. {
  119. var ex = e.ExceptionObject as Exception;
  120. if (ex == null)
  121. {
  122. //_logger.Error("Unidentified error reported by Mono.Nat");
  123. }
  124. else
  125. {
  126. // Seeing some blank exceptions coming through here
  127. //_logger.ErrorException("Error reported by Mono.Nat: ", ex);
  128. }
  129. }
  130. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  131. {
  132. try
  133. {
  134. var device = e.Device;
  135. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  136. CreateRules(device);
  137. }
  138. catch (Exception ex)
  139. {
  140. // I think it could be a good idea to log the exception because
  141. // you are using permanent portmapping here (never expire) and that means that next time
  142. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  143. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  144. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  145. // and those errors (upnp errors) could be useful for diagnosting.
  146. // Commenting out because users are reporting problems out of our control
  147. //_logger.ErrorException("Error creating port forwarding rules", ex);
  148. }
  149. }
  150. private List<string> _createdRules = new List<string>();
  151. private List<string> _usnsHandled = new List<string>();
  152. private void CreateRules(INatDevice device)
  153. {
  154. // On some systems the device discovered event seems to fire repeatedly
  155. // This check will help ensure we're not trying to port map the same device over and over
  156. var address = device.LocalAddress.ToString();
  157. if (!_createdRules.Contains(address))
  158. {
  159. _createdRules.Add(address);
  160. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  161. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  162. }
  163. }
  164. private void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  165. {
  166. _logger.Debug("Creating port map on port {0}", privatePort);
  167. device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  168. {
  169. Description = _appHost.Name
  170. });
  171. }
  172. // As I said before, this method will be never invoked. You can remove it.
  173. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  174. {
  175. var device = e.Device;
  176. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  177. }
  178. public void Dispose()
  179. {
  180. DisposeNat();
  181. }
  182. private void DisposeNat()
  183. {
  184. _logger.Debug("Stopping NAT discovery");
  185. if (_timer != null)
  186. {
  187. _timer.Dispose();
  188. _timer = null;
  189. }
  190. _ssdp.MessageReceived -= _ssdp_MessageReceived;
  191. try
  192. {
  193. // This is not a significant improvement
  194. NatUtility.StopDiscovery();
  195. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  196. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  197. NatUtility.UnhandledException -= NatUtility_UnhandledException;
  198. }
  199. // Statements in try-block will no fail because StopDiscovery is a one-line
  200. // method that was no chances to fail.
  201. // public static void StopDiscovery ()
  202. // {
  203. // searching.Reset();
  204. // }
  205. // IMO you could remove the catch-block
  206. catch (Exception ex)
  207. {
  208. _logger.ErrorException("Error stopping NAT Discovery", ex);
  209. }
  210. finally
  211. {
  212. _isStarted = false;
  213. }
  214. }
  215. }
  216. }