Use IHostedService for UPnP port forwarding

This commit is contained in:
Patrick Barron 2024-02-06 14:45:44 -05:00
parent 143ef71528
commit 99ea6059c7
2 changed files with 35 additions and 37 deletions

View File

@ -125,6 +125,7 @@ namespace Jellyfin.Server
services.AddLiveTvServices(); services.AddLiveTvServices();
services.AddHostedService<AutoDiscoveryHost>(); services.AddHostedService<AutoDiscoveryHost>();
services.AddHostedService<PortForwardingHost>();
} }
/// <summary> /// <summary>

View File

@ -1,7 +1,3 @@
#nullable disable
#pragma warning disable CS1591
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@ -12,36 +8,34 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Mono.Nat; using Mono.Nat;
namespace Jellyfin.Networking; namespace Jellyfin.Networking;
/// <summary> /// <summary>
/// Server entrypoint handling external port forwarding. /// <see cref="IHostedService"/> responsible for UPnP port forwarding.
/// </summary> /// </summary>
public sealed class ExternalPortForwarding : IServerEntryPoint public sealed class PortForwardingHost : IHostedService, IDisposable
{ {
private readonly IServerApplicationHost _appHost; private readonly IServerApplicationHost _appHost;
private readonly ILogger<ExternalPortForwarding> _logger; private readonly ILogger<PortForwardingHost> _logger;
private readonly IServerConfigurationManager _config; private readonly IServerConfigurationManager _config;
private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new();
private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>(); private Timer? _timer;
private string? _configIdentifier;
private Timer _timer;
private string _configIdentifier;
private bool _disposed; private bool _disposed;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ExternalPortForwarding"/> class. /// Initializes a new instance of the <see cref="PortForwardingHost"/> class.
/// </summary> /// </summary>
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="appHost">The application host.</param> /// <param name="appHost">The application host.</param>
/// <param name="config">The configuration manager.</param> /// <param name="config">The configuration manager.</param>
public ExternalPortForwarding( public PortForwardingHost(
ILogger<ExternalPortForwarding> logger, ILogger<PortForwardingHost> logger,
IServerApplicationHost appHost, IServerApplicationHost appHost,
IServerConfigurationManager config) IServerConfigurationManager config)
{ {
@ -66,7 +60,7 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
.ToString(); .ToString();
} }
private void OnConfigurationUpdated(object sender, EventArgs e) private void OnConfigurationUpdated(object? sender, EventArgs e)
{ {
var oldConfigIdentifier = _configIdentifier; var oldConfigIdentifier = _configIdentifier;
_configIdentifier = GetConfigIdentifier(); _configIdentifier = GetConfigIdentifier();
@ -79,7 +73,7 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
} }
/// <inheritdoc /> /// <inheritdoc />
public Task RunAsync() public Task StartAsync(CancellationToken cancellationToken)
{ {
Start(); Start();
@ -88,6 +82,14 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
return Task.CompletedTask; return Task.CompletedTask;
} }
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
Stop();
return Task.CompletedTask;
}
private void Start() private void Start()
{ {
var config = _config.GetNetworkConfiguration(); var config = _config.GetNetworkConfiguration();
@ -101,7 +103,8 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
NatUtility.DeviceFound += OnNatUtilityDeviceFound; NatUtility.DeviceFound += OnNatUtilityDeviceFound;
NatUtility.StartDiscovery(); NatUtility.StartDiscovery();
_timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); _timer?.Dispose();
_timer = new Timer(_ => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
} }
private void Stop() private void Stop()
@ -112,13 +115,23 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
NatUtility.DeviceFound -= OnNatUtilityDeviceFound; NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
_timer?.Dispose(); _timer?.Dispose();
_timer = null;
} }
private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e) private async void OnNatUtilityDeviceFound(object? sender, DeviceEventArgs e)
{ {
ObjectDisposedException.ThrowIf(_disposed, this);
try try
{ {
await CreateRules(e.Device).ConfigureAwait(false); // On some systems the device discovered event seems to fire repeatedly
// This check will help ensure we're not trying to port map the same device over and over
if (!_createdRules.TryAdd(e.Device.DeviceEndpoint, 0))
{
return;
}
await Task.WhenAll(CreatePortMaps(e.Device)).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -126,20 +139,6 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
} }
} }
private Task CreateRules(INatDevice device)
{
ObjectDisposedException.ThrowIf(_disposed, this);
// On some systems the device discovered event seems to fire repeatedly
// This check will help ensure we're not trying to port map the same device over and over
if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
{
return Task.CompletedTask;
}
return Task.WhenAll(CreatePortMaps(device));
}
private IEnumerable<Task> CreatePortMaps(INatDevice device) private IEnumerable<Task> CreatePortMaps(INatDevice device)
{ {
var config = _config.GetNetworkConfiguration(); var config = _config.GetNetworkConfiguration();
@ -185,8 +184,6 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
_config.ConfigurationUpdated -= OnConfigurationUpdated; _config.ConfigurationUpdated -= OnConfigurationUpdated;
Stop();
_timer?.Dispose(); _timer?.Dispose();
_timer = null; _timer = null;