ExternalPortForwarding.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Net;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Plugins;
  9. using MediaBrowser.Model.Dlna;
  10. using MediaBrowser.Model.Events;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Threading;
  13. using Mono.Nat;
  14. namespace Emby.Server.Core.EntryPoints
  15. {
  16. public class ExternalPortForwarding : IServerEntryPoint
  17. {
  18. private readonly IServerApplicationHost _appHost;
  19. private readonly ILogger _logger;
  20. private readonly IHttpClient _httpClient;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly IDeviceDiscovery _deviceDiscovery;
  23. private ITimer _timer;
  24. private bool _isStarted;
  25. private readonly ITimerFactory _timerFactory;
  26. public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory)
  27. {
  28. _logger = logmanager.GetLogger("PortMapper");
  29. _appHost = appHost;
  30. _config = config;
  31. _deviceDiscovery = deviceDiscovery;
  32. _httpClient = httpClient;
  33. _timerFactory = timerFactory;
  34. }
  35. private string _lastConfigIdentifier;
  36. private string GetConfigIdentifier()
  37. {
  38. var values = new List<string>();
  39. var config = _config.Configuration;
  40. values.Add(config.EnableUPnP.ToString());
  41. values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture));
  42. values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture));
  43. values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture));
  44. values.Add(config.EnableHttps.ToString());
  45. values.Add(_appHost.EnableHttps.ToString());
  46. return string.Join("|", values.ToArray());
  47. }
  48. void _config_ConfigurationUpdated(object sender, EventArgs e)
  49. {
  50. if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
  51. {
  52. if (_isStarted)
  53. {
  54. DisposeNat();
  55. }
  56. Run();
  57. }
  58. }
  59. public void Run()
  60. {
  61. NatUtility.Logger = _logger;
  62. NatUtility.HttpClient = _httpClient;
  63. if (_config.Configuration.EnableUPnP)
  64. {
  65. Start();
  66. }
  67. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  68. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  69. }
  70. private void Start()
  71. {
  72. _logger.Debug("Starting NAT discovery");
  73. NatUtility.EnabledProtocols = new List<NatProtocol>
  74. {
  75. NatProtocol.Pmp
  76. };
  77. NatUtility.DeviceFound += NatUtility_DeviceFound;
  78. // Mono.Nat does never rise this event. The event is there however it is useless.
  79. // You could remove it with no risk.
  80. NatUtility.DeviceLost += NatUtility_DeviceLost;
  81. NatUtility.StartDiscovery();
  82. _timer = _timerFactory.Create(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
  83. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  84. _lastConfigIdentifier = GetConfigIdentifier();
  85. _isStarted = true;
  86. }
  87. private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  88. {
  89. var info = e.Argument;
  90. string usn;
  91. if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
  92. string nt;
  93. if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
  94. // Filter device type
  95. if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  96. nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  97. usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  98. nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
  99. {
  100. return;
  101. }
  102. var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
  103. if (info.Location == null)
  104. {
  105. return;
  106. }
  107. lock (_usnsHandled)
  108. {
  109. if (_usnsHandled.Contains(identifier))
  110. {
  111. return;
  112. }
  113. _usnsHandled.Add(identifier);
  114. }
  115. _logger.Debug("Found NAT device: " + identifier);
  116. IPAddress address;
  117. if (IPAddress.TryParse(info.Location.Host, out address))
  118. {
  119. // The Handle method doesn't need the port
  120. var endpoint = new IPEndPoint(address, info.Location.Port);
  121. IPAddress localAddress = null;
  122. try
  123. {
  124. var localAddressString = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  125. Uri uri;
  126. if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri))
  127. {
  128. localAddressString = uri.Host;
  129. if (!IPAddress.TryParse(localAddressString, out localAddress))
  130. {
  131. return;
  132. }
  133. }
  134. }
  135. catch (Exception ex)
  136. {
  137. return;
  138. }
  139. _logger.Debug("Calling Nat.Handle on " + identifier);
  140. NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
  141. }
  142. }
  143. private void ClearCreatedRules(object state)
  144. {
  145. _createdRules = new List<string>();
  146. lock (_usnsHandled)
  147. {
  148. _usnsHandled.Clear();
  149. }
  150. }
  151. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  152. {
  153. try
  154. {
  155. var device = e.Device;
  156. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  157. CreateRules(device);
  158. }
  159. catch
  160. {
  161. // I think it could be a good idea to log the exception because
  162. // you are using permanent portmapping here (never expire) and that means that next time
  163. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  164. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  165. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  166. // and those errors (upnp errors) could be useful for diagnosting.
  167. // Commenting out because users are reporting problems out of our control
  168. //_logger.ErrorException("Error creating port forwarding rules", ex);
  169. }
  170. }
  171. private List<string> _createdRules = new List<string>();
  172. private List<string> _usnsHandled = new List<string>();
  173. private void CreateRules(INatDevice device)
  174. {
  175. // On some systems the device discovered event seems to fire repeatedly
  176. // This check will help ensure we're not trying to port map the same device over and over
  177. var address = device.LocalAddress.ToString();
  178. if (!_createdRules.Contains(address))
  179. {
  180. _createdRules.Add(address);
  181. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  182. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  183. }
  184. }
  185. private async void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  186. {
  187. _logger.Debug("Creating port map on port {0}", privatePort);
  188. try
  189. {
  190. await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  191. {
  192. Description = _appHost.Name
  193. }).ConfigureAwait(false);
  194. }
  195. catch (Exception ex)
  196. {
  197. _logger.Error("Error creating port map: " + ex.Message);
  198. }
  199. }
  200. // As I said before, this method will be never invoked. You can remove it.
  201. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  202. {
  203. var device = e.Device;
  204. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  205. }
  206. public void Dispose()
  207. {
  208. DisposeNat();
  209. }
  210. private void DisposeNat()
  211. {
  212. _logger.Debug("Stopping NAT discovery");
  213. if (_timer != null)
  214. {
  215. _timer.Dispose();
  216. _timer = null;
  217. }
  218. _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
  219. try
  220. {
  221. // This is not a significant improvement
  222. NatUtility.StopDiscovery();
  223. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  224. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  225. }
  226. // Statements in try-block will no fail because StopDiscovery is a one-line
  227. // method that was no chances to fail.
  228. // public static void StopDiscovery ()
  229. // {
  230. // searching.Reset();
  231. // }
  232. // IMO you could remove the catch-block
  233. catch (Exception ex)
  234. {
  235. _logger.ErrorException("Error stopping NAT Discovery", ex);
  236. }
  237. finally
  238. {
  239. _isStarted = false;
  240. }
  241. }
  242. }
  243. }