ExternalPortForwarding.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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.Data.Events;
  11. using Jellyfin.Networking.Configuration;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Model.Dlna;
  16. using Microsoft.Extensions.Logging;
  17. using Mono.Nat;
  18. namespace Emby.Server.Implementations.EntryPoints
  19. {
  20. /// <summary>
  21. /// Server entrypoint handling external port forwarding.
  22. /// </summary>
  23. public class ExternalPortForwarding : IServerEntryPoint
  24. {
  25. private readonly IServerApplicationHost _appHost;
  26. private readonly ILogger<ExternalPortForwarding> _logger;
  27. private readonly IServerConfigurationManager _config;
  28. private readonly IDeviceDiscovery _deviceDiscovery;
  29. private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>();
  30. private Timer _timer;
  31. private string _configIdentifier;
  32. private bool _disposed = false;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="ExternalPortForwarding"/> class.
  35. /// </summary>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="appHost">The application host.</param>
  38. /// <param name="config">The configuration manager.</param>
  39. /// <param name="deviceDiscovery">The device discovery.</param>
  40. public ExternalPortForwarding(
  41. ILogger<ExternalPortForwarding> logger,
  42. IServerApplicationHost appHost,
  43. IServerConfigurationManager config,
  44. IDeviceDiscovery deviceDiscovery)
  45. {
  46. _logger = logger;
  47. _appHost = appHost;
  48. _config = config;
  49. _deviceDiscovery = deviceDiscovery;
  50. }
  51. private string GetConfigIdentifier()
  52. {
  53. const char Separator = '|';
  54. var config = _config.GetNetworkConfiguration();
  55. return new StringBuilder(32)
  56. .Append(config.EnableUPnP).Append(Separator)
  57. .Append(config.PublicPort).Append(Separator)
  58. .Append(config.PublicHttpsPort).Append(Separator)
  59. .Append(_appHost.HttpPort).Append(Separator)
  60. .Append(_appHost.HttpsPort).Append(Separator)
  61. .Append(_appHost.ListenWithHttps).Append(Separator)
  62. .Append(config.EnableRemoteAccess).Append(Separator)
  63. .ToString();
  64. }
  65. private void OnConfigurationUpdated(object sender, EventArgs e)
  66. {
  67. var oldConfigIdentifier = _configIdentifier;
  68. _configIdentifier = GetConfigIdentifier();
  69. if (!string.Equals(_configIdentifier, oldConfigIdentifier, StringComparison.OrdinalIgnoreCase))
  70. {
  71. Stop();
  72. Start();
  73. }
  74. }
  75. /// <inheritdoc />
  76. public Task RunAsync()
  77. {
  78. Start();
  79. _config.ConfigurationUpdated += OnConfigurationUpdated;
  80. return Task.CompletedTask;
  81. }
  82. private void Start()
  83. {
  84. var config = _config.GetNetworkConfiguration();
  85. if (!config.EnableUPnP || !config.EnableRemoteAccess)
  86. {
  87. return;
  88. }
  89. _logger.LogInformation("Starting NAT discovery");
  90. NatUtility.DeviceFound += OnNatUtilityDeviceFound;
  91. NatUtility.StartDiscovery();
  92. _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
  93. }
  94. private void Stop()
  95. {
  96. _logger.LogInformation("Stopping NAT discovery");
  97. NatUtility.StopDiscovery();
  98. NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
  99. _timer?.Dispose();
  100. }
  101. private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
  102. {
  103. try
  104. {
  105. await CreateRules(e.Device).ConfigureAwait(false);
  106. }
  107. catch (Exception ex)
  108. {
  109. _logger.LogError(ex, "Error creating port forwarding rules");
  110. }
  111. }
  112. private Task CreateRules(INatDevice device)
  113. {
  114. if (_disposed)
  115. {
  116. throw new ObjectDisposedException(GetType().Name);
  117. }
  118. // On some systems the device discovered event seems to fire repeatedly
  119. // This check will help ensure we're not trying to port map the same device over and over
  120. if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
  121. {
  122. return Task.CompletedTask;
  123. }
  124. return Task.WhenAll(CreatePortMaps(device));
  125. }
  126. private IEnumerable<Task> CreatePortMaps(INatDevice device)
  127. {
  128. var config = _config.GetNetworkConfiguration();
  129. yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort);
  130. if (_appHost.ListenWithHttps)
  131. {
  132. yield return CreatePortMap(device, _appHost.HttpsPort, config.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. }