ExternalPortForwarding.cs 7.2 KB

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