ExternalPortForwarding.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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<ExternalPortForwarding> _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 _configIdentifier;
  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(config.PublicHttpsPort).Append(Separator)
  57. .Append(_appHost.HttpPort).Append(Separator)
  58. .Append(_appHost.HttpsPort).Append(Separator)
  59. .Append(_appHost.ListenWithHttps).Append(Separator)
  60. .Append(config.EnableRemoteAccess).Append(Separator)
  61. .ToString();
  62. }
  63. private void OnConfigurationUpdated(object sender, EventArgs e)
  64. {
  65. var oldConfigIdentifier = _configIdentifier;
  66. _configIdentifier = GetConfigIdentifier();
  67. if (!string.Equals(_configIdentifier, oldConfigIdentifier, StringComparison.OrdinalIgnoreCase))
  68. {
  69. Stop();
  70. Start();
  71. }
  72. }
  73. /// <inheritdoc />
  74. public Task RunAsync()
  75. {
  76. Start();
  77. _config.ConfigurationUpdated += OnConfigurationUpdated;
  78. return Task.CompletedTask;
  79. }
  80. private void Start()
  81. {
  82. if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess)
  83. {
  84. return;
  85. }
  86. _logger.LogInformation("Starting NAT discovery");
  87. NatUtility.DeviceFound += OnNatUtilityDeviceFound;
  88. NatUtility.StartDiscovery();
  89. _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
  90. _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered;
  91. }
  92. private void Stop()
  93. {
  94. _logger.LogInformation("Stopping NAT discovery");
  95. NatUtility.StopDiscovery();
  96. NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
  97. _timer?.Dispose();
  98. _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered;
  99. }
  100. private void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  101. {
  102. NatUtility.Search(e.Argument.LocalIpAddress, NatProtocol.Upnp);
  103. }
  104. private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
  105. {
  106. try
  107. {
  108. await CreateRules(e.Device).ConfigureAwait(false);
  109. }
  110. catch (Exception ex)
  111. {
  112. _logger.LogError(ex, "Error creating port forwarding rules");
  113. }
  114. }
  115. private Task CreateRules(INatDevice device)
  116. {
  117. if (_disposed)
  118. {
  119. throw new ObjectDisposedException(GetType().Name);
  120. }
  121. // On some systems the device discovered event seems to fire repeatedly
  122. // This check will help ensure we're not trying to port map the same device over and over
  123. if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
  124. {
  125. return Task.CompletedTask;
  126. }
  127. return Task.WhenAll(CreatePortMaps(device));
  128. }
  129. private IEnumerable<Task> CreatePortMaps(INatDevice device)
  130. {
  131. yield return CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  132. if (_appHost.ListenWithHttps)
  133. {
  134. yield return CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  135. }
  136. }
  137. private async Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
  138. {
  139. _logger.LogDebug(
  140. "Creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}",
  141. privatePort,
  142. publicPort,
  143. device.DeviceEndpoint);
  144. try
  145. {
  146. var mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name);
  147. await device.CreatePortMapAsync(mapping).ConfigureAwait(false);
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.LogError(
  152. ex,
  153. "Error creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}.",
  154. privatePort,
  155. publicPort,
  156. device.DeviceEndpoint);
  157. }
  158. }
  159. /// <inheritdoc />
  160. public void Dispose()
  161. {
  162. Dispose(true);
  163. GC.SuppressFinalize(this);
  164. }
  165. /// <summary>
  166. /// Releases unmanaged and - optionally - managed resources.
  167. /// </summary>
  168. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  169. protected virtual void Dispose(bool dispose)
  170. {
  171. if (_disposed)
  172. {
  173. return;
  174. }
  175. _config.ConfigurationUpdated -= OnConfigurationUpdated;
  176. Stop();
  177. _timer = null;
  178. _disposed = true;
  179. }
  180. }
  181. }