ExternalPortForwarding.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered;
  94. }
  95. private void Stop()
  96. {
  97. _logger.LogInformation("Stopping NAT discovery");
  98. NatUtility.StopDiscovery();
  99. NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
  100. _timer?.Dispose();
  101. _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered;
  102. }
  103. private void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  104. {
  105. NatUtility.Search(e.Argument.LocalIpAddress, NatProtocol.Upnp);
  106. }
  107. private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
  108. {
  109. try
  110. {
  111. await CreateRules(e.Device).ConfigureAwait(false);
  112. }
  113. catch (Exception ex)
  114. {
  115. _logger.LogError(ex, "Error creating port forwarding rules");
  116. }
  117. }
  118. private Task CreateRules(INatDevice device)
  119. {
  120. if (_disposed)
  121. {
  122. throw new ObjectDisposedException(GetType().Name);
  123. }
  124. // On some systems the device discovered event seems to fire repeatedly
  125. // This check will help ensure we're not trying to port map the same device over and over
  126. if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
  127. {
  128. return Task.CompletedTask;
  129. }
  130. return Task.WhenAll(CreatePortMaps(device));
  131. }
  132. private IEnumerable<Task> CreatePortMaps(INatDevice device)
  133. {
  134. var config = _config.GetNetworkConfiguration();
  135. yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort);
  136. if (_appHost.ListenWithHttps)
  137. {
  138. yield return CreatePortMap(device, _appHost.HttpsPort, config.PublicHttpsPort);
  139. }
  140. }
  141. private async Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
  142. {
  143. _logger.LogDebug(
  144. "Creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}",
  145. privatePort,
  146. publicPort,
  147. device.DeviceEndpoint);
  148. try
  149. {
  150. var mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name);
  151. await device.CreatePortMapAsync(mapping).ConfigureAwait(false);
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.LogError(
  156. ex,
  157. "Error creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}.",
  158. privatePort,
  159. publicPort,
  160. device.DeviceEndpoint);
  161. }
  162. }
  163. /// <inheritdoc />
  164. public void Dispose()
  165. {
  166. Dispose(true);
  167. GC.SuppressFinalize(this);
  168. }
  169. /// <summary>
  170. /// Releases unmanaged and - optionally - managed resources.
  171. /// </summary>
  172. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  173. protected virtual void Dispose(bool dispose)
  174. {
  175. if (_disposed)
  176. {
  177. return;
  178. }
  179. _config.ConfigurationUpdated -= OnConfigurationUpdated;
  180. Stop();
  181. _timer = null;
  182. _disposed = true;
  183. }
  184. }
  185. }