ExternalPortForwarding.cs 11 KB

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