ExternalPortForwarding.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Plugins;
  12. using MediaBrowser.Model.Dlna;
  13. using MediaBrowser.Model.Events;
  14. using Microsoft.Extensions.Logging;
  15. using Mono.Nat;
  16. namespace Emby.Server.Implementations.EntryPoints
  17. {
  18. /// <summary>
  19. /// Server entrypoint handling external port forwarding.
  20. /// </summary>
  21. public class ExternalPortForwarding : IServerEntryPoint
  22. {
  23. private readonly IServerApplicationHost _appHost;
  24. private readonly ILogger _logger;
  25. private readonly IServerConfigurationManager _config;
  26. private readonly IDeviceDiscovery _deviceDiscovery;
  27. private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>();
  28. private Timer _timer;
  29. private string _lastConfigIdentifier;
  30. private bool _disposed = false;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="ExternalPortForwarding"/> class.
  33. /// </summary>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="appHost">The application host.</param>
  36. /// <param name="config">The configuration manager.</param>
  37. /// <param name="deviceDiscovery">The device discovery.</param>
  38. public ExternalPortForwarding(
  39. ILogger<ExternalPortForwarding> logger,
  40. IServerApplicationHost appHost,
  41. IServerConfigurationManager config,
  42. IDeviceDiscovery deviceDiscovery)
  43. {
  44. _logger = logger;
  45. _appHost = appHost;
  46. _config = config;
  47. _deviceDiscovery = deviceDiscovery;
  48. }
  49. private string GetConfigIdentifier()
  50. {
  51. const char Separator = '|';
  52. var config = _config.Configuration;
  53. return new StringBuilder(32)
  54. .Append(config.EnableUPnP).Append(Separator)
  55. .Append(config.PublicPort).Append(Separator)
  56. .Append(_appHost.HttpPort).Append(Separator)
  57. .Append(_appHost.HttpsPort).Append(Separator)
  58. .Append(_appHost.EnableHttps).Append(Separator)
  59. .Append(config.EnableRemoteAccess).Append(Separator)
  60. .ToString();
  61. }
  62. private void OnConfigurationUpdated(object sender, EventArgs e)
  63. {
  64. if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
  65. {
  66. Stop();
  67. Start();
  68. }
  69. }
  70. /// <inheritdoc />
  71. public Task RunAsync()
  72. {
  73. Start();
  74. _config.ConfigurationUpdated += OnConfigurationUpdated;
  75. return Task.CompletedTask;
  76. }
  77. private void Start()
  78. {
  79. if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess)
  80. {
  81. return;
  82. }
  83. _logger.LogDebug("Starting NAT discovery");
  84. NatUtility.DeviceFound += OnNatUtilityDeviceFound;
  85. NatUtility.StartDiscovery();
  86. _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
  87. _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered;
  88. _lastConfigIdentifier = GetConfigIdentifier();
  89. }
  90. private void Stop()
  91. {
  92. _logger.LogDebug("Stopping NAT discovery");
  93. NatUtility.StopDiscovery();
  94. NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
  95. _timer?.Dispose();
  96. _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered;
  97. }
  98. private void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  99. {
  100. NatUtility.Search(e.Argument.LocalIpAddress, NatProtocol.Upnp);
  101. }
  102. private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
  103. {
  104. try
  105. {
  106. await CreateRules(e.Device).ConfigureAwait(false);
  107. }
  108. catch (Exception ex)
  109. {
  110. _logger.LogError(ex, "Error creating port forwarding rules");
  111. }
  112. }
  113. private Task CreateRules(INatDevice device)
  114. {
  115. if (_disposed)
  116. {
  117. throw new ObjectDisposedException(GetType().Name);
  118. }
  119. // On some systems the device discovered event seems to fire repeatedly
  120. // This check will help ensure we're not trying to port map the same device over and over
  121. if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
  122. {
  123. return Task.CompletedTask;
  124. }
  125. return Task.WhenAll(CreatePortMaps(device));
  126. }
  127. private IEnumerable<Task> CreatePortMaps(INatDevice device)
  128. {
  129. yield return CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  130. if (_appHost.EnableHttps)
  131. {
  132. yield return CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  133. }
  134. }
  135. private async Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
  136. {
  137. _logger.LogDebug(
  138. "Creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}",
  139. privatePort,
  140. publicPort,
  141. device.DeviceEndpoint);
  142. try
  143. {
  144. var mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name);
  145. await device.CreatePortMapAsync(mapping).ConfigureAwait(false);
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.LogError(
  150. ex,
  151. "Error creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}.",
  152. privatePort,
  153. publicPort,
  154. device.DeviceEndpoint);
  155. }
  156. }
  157. /// <inheritdoc />
  158. public void Dispose()
  159. {
  160. Dispose(true);
  161. GC.SuppressFinalize(this);
  162. }
  163. /// <summary>
  164. /// Releases unmanaged and - optionally - managed resources.
  165. /// </summary>
  166. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  167. protected virtual void Dispose(bool dispose)
  168. {
  169. if (_disposed)
  170. {
  171. return;
  172. }
  173. _config.ConfigurationUpdated -= OnConfigurationUpdated;
  174. Stop();
  175. _timer = null;
  176. _disposed = true;
  177. }
  178. }
  179. }