ExternalPortForwarding.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. _createdRules = new List<string>();
  155. lock (_usnsHandled)
  156. {
  157. _usnsHandled.Clear();
  158. }
  159. }
  160. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  161. {
  162. if (_disposed)
  163. {
  164. return;
  165. }
  166. try
  167. {
  168. var device = e.Device;
  169. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  170. CreateRules(device);
  171. }
  172. catch
  173. {
  174. // I think it could be a good idea to log the exception because
  175. // you are using permanent portmapping here (never expire) and that means that next time
  176. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  177. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  178. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  179. // and those errors (upnp errors) could be useful for diagnosting.
  180. // Commenting out because users are reporting problems out of our control
  181. //_logger.ErrorException("Error creating port forwarding rules", ex);
  182. }
  183. }
  184. private List<string> _createdRules = new List<string>();
  185. private List<string> _usnsHandled = new List<string>();
  186. private async void CreateRules(INatDevice device)
  187. {
  188. if (_disposed)
  189. {
  190. throw new ObjectDisposedException("PortMapper");
  191. }
  192. // On some systems the device discovered event seems to fire repeatedly
  193. // This check will help ensure we're not trying to port map the same device over and over
  194. var address = device.LocalAddress.ToString();
  195. if (!_createdRules.Contains(address))
  196. {
  197. _createdRules.Add(address);
  198. var success = await CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort).ConfigureAwait(false);
  199. if (success)
  200. {
  201. await CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort).ConfigureAwait(false);
  202. }
  203. }
  204. }
  205. private async Task<bool> CreatePortMap(INatDevice device, int privatePort, int publicPort)
  206. {
  207. _logger.Debug("Creating port map on port {0}", privatePort);
  208. try
  209. {
  210. await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  211. {
  212. Description = _appHost.Name
  213. }).ConfigureAwait(false);
  214. return true;
  215. }
  216. catch (Exception ex)
  217. {
  218. _logger.Error("Error creating port map: " + ex.Message);
  219. return false;
  220. }
  221. }
  222. // As I said before, this method will be never invoked. You can remove it.
  223. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  224. {
  225. var device = e.Device;
  226. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  227. }
  228. private bool _disposed = false;
  229. public void Dispose()
  230. {
  231. _disposed = true;
  232. DisposeNat();
  233. }
  234. private void DisposeNat()
  235. {
  236. _logger.Debug("Stopping NAT discovery");
  237. if (_timer != null)
  238. {
  239. _timer.Dispose();
  240. _timer = null;
  241. }
  242. _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
  243. try
  244. {
  245. // This is not a significant improvement
  246. NatUtility.StopDiscovery();
  247. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  248. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  249. }
  250. // Statements in try-block will no fail because StopDiscovery is a one-line
  251. // method that was no chances to fail.
  252. // public static void StopDiscovery ()
  253. // {
  254. // searching.Reset();
  255. // }
  256. // IMO you could remove the catch-block
  257. catch (Exception ex)
  258. {
  259. _logger.ErrorException("Error stopping NAT Discovery", ex);
  260. }
  261. finally
  262. {
  263. _isStarted = false;
  264. }
  265. }
  266. }
  267. }