ExternalPortForwarding.cs 6.6 KB

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