ExternalPortForwarding.cs 11 KB

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