ExternalPortForwarding.cs 11 KB

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