ExternalPortForwarding.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. if (_disposed)
  90. {
  91. return;
  92. }
  93. var info = e.Argument;
  94. string usn;
  95. if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
  96. string nt;
  97. if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
  98. // Filter device type
  99. if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  100. nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  101. usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  102. nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
  103. {
  104. return;
  105. }
  106. var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
  107. if (info.Location == null)
  108. {
  109. return;
  110. }
  111. lock (_usnsHandled)
  112. {
  113. if (_usnsHandled.Contains(identifier))
  114. {
  115. return;
  116. }
  117. _usnsHandled.Add(identifier);
  118. }
  119. _logger.Debug("Found NAT device: " + identifier);
  120. IPAddress address;
  121. if (IPAddress.TryParse(info.Location.Host, out address))
  122. {
  123. // The Handle method doesn't need the port
  124. var endpoint = new IPEndPoint(address, info.Location.Port);
  125. IPAddress localAddress = null;
  126. try
  127. {
  128. var localAddressString = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  129. Uri uri;
  130. if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri))
  131. {
  132. localAddressString = uri.Host;
  133. if (!IPAddress.TryParse(localAddressString, out localAddress))
  134. {
  135. return;
  136. }
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. return;
  142. }
  143. if (_disposed)
  144. {
  145. return;
  146. }
  147. _logger.Debug("Calling Nat.Handle on " + identifier);
  148. NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
  149. }
  150. }
  151. private void ClearCreatedRules(object state)
  152. {
  153. _createdRules = new List<string>();
  154. lock (_usnsHandled)
  155. {
  156. _usnsHandled.Clear();
  157. }
  158. }
  159. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  160. {
  161. if (_disposed)
  162. {
  163. return;
  164. }
  165. try
  166. {
  167. var device = e.Device;
  168. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  169. CreateRules(device);
  170. }
  171. catch
  172. {
  173. // I think it could be a good idea to log the exception because
  174. // you are using permanent portmapping here (never expire) and that means that next time
  175. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  176. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  177. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  178. // and those errors (upnp errors) could be useful for diagnosting.
  179. // Commenting out because users are reporting problems out of our control
  180. //_logger.ErrorException("Error creating port forwarding rules", ex);
  181. }
  182. }
  183. private List<string> _createdRules = new List<string>();
  184. private List<string> _usnsHandled = new List<string>();
  185. private void CreateRules(INatDevice device)
  186. {
  187. if (_disposed)
  188. {
  189. throw new ObjectDisposedException("PortMapper");
  190. }
  191. // On some systems the device discovered event seems to fire repeatedly
  192. // This check will help ensure we're not trying to port map the same device over and over
  193. var address = device.LocalAddress.ToString();
  194. if (!_createdRules.Contains(address))
  195. {
  196. _createdRules.Add(address);
  197. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  198. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  199. }
  200. }
  201. private async void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  202. {
  203. _logger.Debug("Creating port map on port {0}", privatePort);
  204. try
  205. {
  206. await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  207. {
  208. Description = _appHost.Name
  209. }).ConfigureAwait(false);
  210. }
  211. catch (Exception ex)
  212. {
  213. _logger.Error("Error creating port map: " + ex.Message);
  214. }
  215. }
  216. // As I said before, this method will be never invoked. You can remove it.
  217. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  218. {
  219. var device = e.Device;
  220. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  221. }
  222. private bool _disposed = false;
  223. public void Dispose()
  224. {
  225. _disposed = true;
  226. DisposeNat();
  227. }
  228. private void DisposeNat()
  229. {
  230. _logger.Debug("Stopping NAT discovery");
  231. if (_timer != null)
  232. {
  233. _timer.Dispose();
  234. _timer = null;
  235. }
  236. _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
  237. try
  238. {
  239. // This is not a significant improvement
  240. NatUtility.StopDiscovery();
  241. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  242. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  243. }
  244. // Statements in try-block will no fail because StopDiscovery is a one-line
  245. // method that was no chances to fail.
  246. // public static void StopDiscovery ()
  247. // {
  248. // searching.Reset();
  249. // }
  250. // IMO you could remove the catch-block
  251. catch (Exception ex)
  252. {
  253. _logger.ErrorException("Error stopping NAT Discovery", ex);
  254. }
  255. finally
  256. {
  257. _isStarted = false;
  258. }
  259. }
  260. }
  261. }