diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-02-14 17:55:58 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-02-14 17:55:58 -0600 |
| commit | 7f0312a1ea28e611a126ddb07117aa1072f1c36a (patch) | |
| tree | c78c5372d6bb23464480a509e3aee1789b5b78a1 /src | |
| parent | 8d30845f59d693aa6909c9fe8291493422dc10aa (diff) | |
| parent | 9f3b7217dd4554482c904becc101a4cf3074544e (diff) | |
| download | slskd-7f0312a1ea28e611a126ddb07117aa1072f1c36a.tar.gz | |
Merge pull request #1632 from slskd/gluetun
Add VPN integration and gluetun client
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/VPNClientException.cs | 60 | ||||
| -rw-r--r-- | src/slskd/Core/ConnectionWatchdog.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 120 | ||||
| -rw-r--r-- | src/slskd/Core/OptionsOverlay.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Core/State.cs | 13 | ||||
| -rw-r--r-- | src/slskd/Events/EventBus.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Events/Types/Events.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Integrations/VPN/Clients/Gluetun.cs | 149 | ||||
| -rw-r--r-- | src/slskd/Integrations/VPN/IVPNClient.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Integrations/VPN/VPNService.cs | 263 | ||||
| -rw-r--r-- | src/slskd/Integrations/VPN/VPNStatus.cs | 28 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 3 |
13 files changed, 752 insertions, 6 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index bed8aab2..daed5d3f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -40,6 +40,7 @@ namespace slskd using Serilog.Events; using slskd.Configuration; using slskd.Core.API; + using slskd.Events; using slskd.Files; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -105,7 +106,8 @@ namespace slskd IPushbulletService pushbulletService, IRelayService relayService, IHubContext<ApplicationHub> applicationHub, - IHubContext<LogsHub> logHub) + IHubContext<LogsHub> logHub, + EventBus eventBus) { Console.CancelKeyPress += (_, args) => { @@ -130,6 +132,8 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + EventBus = eventBus; + IncomingSearchRequestSemaphore = new SemaphoreSlim( initialCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency, maxCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency); @@ -240,6 +244,7 @@ namespace slskd private ITransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } + private EventBus EventBus { get; } private IUserService Users { get; set; } private IShareService Shares { get; set; } private ISearchService Search { get; set; } @@ -900,6 +905,8 @@ namespace slskd { ConnectionWatchdog.Stop(); Log.Information("Connected to the Soulseek server"); + + EventBus.Raise(new SoulseekClientConnectedEvent()); } private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) @@ -955,11 +962,22 @@ namespace slskd { Log.Error("Disconnected from the Soulseek server: another client logged in using the same username"); } + else if (args.Exception is VPNClientException) + { + Log.Error("Disconnected from the Soulseek server; VPN is required and the VPN client has gone down"); + ConnectionWatchdog.Start(); + } else { Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); ConnectionWatchdog.Start(); } + + EventBus.Raise(new SoulseekClientDisconnectedEvent() + { + Message = args.Message, + Exception = args.Exception, + }); } private async Task RefreshUserStatistics(bool force = false) diff --git a/src/slskd/Common/Exceptions/VPNClientException.cs b/src/slskd/Common/Exceptions/VPNClientException.cs new file mode 100644 index 00000000..d7e505d7 --- /dev/null +++ b/src/slskd/Common/Exceptions/VPNClientException.cs @@ -0,0 +1,60 @@ +// <copyright file="VPNClientException.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// <summary> + /// Represents errors that originate from slskd logic. + /// </summary> + [ExcludeFromCodeCoverage] + public class VPNClientException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="VPNClientException"/> class. + /// </summary> + public VPNClientException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="VPNClientException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public VPNClientException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="VPNClientException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public VPNClientException(string message, Exception innerException) + : base(message, innerException) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index b7a4fa34..d2f7caa8 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -23,6 +23,7 @@ namespace slskd using System.Threading; using System.Threading.Tasks; using Serilog; + using slskd.Integrations.VPN; using Soulseek; /// <summary> @@ -41,15 +42,21 @@ namespace slskd /// Initializes a new instance of the <see cref="ConnectionWatchdog"/> class. /// </summary> /// <param name="soulseekClient"></param> + /// <param name="vpnService"></param> /// <param name="optionsMonitor"></param> + /// <param name="optionsAtStartup"></param> /// <param name="applicationState"></param> public ConnectionWatchdog( ISoulseekClient soulseekClient, + VPNService vpnService, IOptionsMonitor<Options> optionsMonitor, + OptionsAtStartup optionsAtStartup, IManagedState<State> applicationState) { Client = soulseekClient; + VPN = vpnService; OptionsMonitor = optionsMonitor; + OptionsAtStartup = optionsAtStartup; ApplicationState = applicationState; WatchdogTimer = new System.Timers.Timer() @@ -76,10 +83,17 @@ namespace slskd /// </summary> public bool IsAttemptingConnection => SyncRoot.CurrentCount == 0; + /// <summary> + /// Gets a value indicating whether the watchdog is waiting for the VPN client to connect. + /// </summary> + public bool IsAwaitingVpn { get; private set; } + private ISoulseekClient Client { get; } + private VPNService VPN { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<Application>(); private IOptionsMonitor<Options> OptionsMonitor { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } private IManagedState<State> ApplicationState { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private object StateLock { get; } = new object(); @@ -101,6 +115,11 @@ namespace slskd /// <remarks>This should be called at application startup.</remarks> public virtual void Start() { + if (OptionsAtStartup.Integration.Vpn.Enabled) + { + VPN.StartPolling(); + } + WatchdogTimer.Enabled = true; UpdateApplicationState(); @@ -184,6 +203,7 @@ namespace slskd { IsEnabled = IsEnabled, IsAttemptingConnection = IsAttemptingConnection, + IsAwaitingVpn = IsAwaitingVpn, NextAttemptAt = IsAttemptingConnection ? nextAttemptAt ?? state.ConnectionWatchdog.NextAttemptAt : null, // only null this if we're not attempting, otherwise it sticks }, }); @@ -209,8 +229,6 @@ namespace slskd { try { - Log.Debug("AttemptConnection initiated by {Source}", source); - /* go until we connect and break, or something stops the watchdog. why don't we just use the timer here? good question. we could, but a loop gives us more control and precision. at the expensive of needing to @@ -232,6 +250,14 @@ namespace slskd return; } + if (OptionsAtStartup.Integration.Vpn.Enabled && !VPN.IsReady) + { + IsAwaitingVpn = true; + return; + } + + IsAwaitingVpn = false; + CancellationTokenSource = new CancellationTokenSource(); if (attempts > 0) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 200b0ee8..644fb885 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -33,6 +33,7 @@ namespace slskd using slskd.Authentication; using slskd.Configuration; using slskd.Events; + using slskd.Integrations.VPN; using slskd.Relay; using slskd.Shares; using slskd.Validation; @@ -2275,6 +2276,12 @@ namespace slskd public class IntegrationOptions { /// <summary> + /// Gets VPN options. + /// </summary> + [Validate] + public VpnOptions Vpn { get; init; } = new(); + + /// <summary> /// Gets webhook configuration. /// </summary> [Validate] @@ -2299,6 +2306,119 @@ namespace slskd public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); /// <summary> + /// VPN options. + /// </summary> + public class VpnOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the VPN integration is enabled. + /// </summary> + [Argument(default, "vpn")] + [EnvironmentVariable("VPN")] + [Description("enable VPN integration")] + [RequiresRestart] + public bool Enabled { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the configured VPN supports dynamic port forwarding. + /// </summary> + [Argument(default, "vpn-port-forwarding")] + [EnvironmentVariable("VPN_PORT_FORWARDING")] + [Description("VPN supports dynamic port forwarding")] + public bool PortForwarding { get; init; } = false; + + /// <summary> + /// Gets the rate at which to poll the configured VPN client for status updates, in milliseconds. + /// </summary> + [Argument(default, "vpn-polling-interval")] + [EnvironmentVariable("VPN_POLLING_INTERVAL")] + [Description("VPN client status polling interval")] + [Range(500, int.MaxValue)] + [RequiresRestart] + public int PollingInterval { get; init; } = 2500; + + /// <summary> + /// Gets Gluetun options. + /// </summary> + [Validate] + public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions(); + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + if (Enabled) + { + // as/if more VPN clients are added, update this logic to ensure that exactly one is configured + if (string.IsNullOrWhiteSpace(Gluetun?.Url)) + { + yield return new ValidationResult("VPN is enabled but no client is configured"); + yield break; + } + + if (!Uri.TryCreate(Gluetun.Url, UriKind.Absolute, out _)) + { + yield return new ValidationResult("The gluetun URL must be absolute, e.g. 'http://127.0.0.1:8000'"); + } + } + } + + /// <summary> + /// Gluetun options. + /// </summary> + public class GluetunVpnOptions + { + /// <summary> + /// Gets the Gluetun integration version. + /// </summary> + /// <remarks> + /// Only v1 of the Gluetun API exists right now; this is to ease a transition if there's ever a v2. + /// </remarks> + [Range(1, 1)] + public int Version { get; init; } = 1; + + /// <summary> + /// Gets the fully qualified root URL for the Gluetun control server. + /// </summary> + [Argument(default, "vpn-gluetun-url")] + [EnvironmentVariable("VPN_GLUETUN_URL")] + [Description("URL for gluetun control server")] + public string Url { get; init; } + + /// <summary> + /// Gets the timeout for HTTP requests to the Gluetun control server, in milliseconds. + /// </summary> + [Argument(default, "vpn-gluetun-timeout")] + [EnvironmentVariable("VPN_GLUETUN_TIMEOUT")] + [Description("timeout for HTTP requests to gluetun control server")] + [Range(500, 10_000)] + public int Timeout { get; init; } = 1000; + + /// <summary> + /// Gets the username used for basic auth. + /// </summary> + [Argument(default, "vpn-gluetun-username")] + [EnvironmentVariable("VPN_GLUETUN_USERNAME")] + [Description("username for gluetun control server")] + public string Username { get; init; } + + /// <summary> + /// Gets the password used for basic auth. + /// </summary> + [Argument(default, "vpn-gluetun-password")] + [EnvironmentVariable("VPN_GLUETUN_PASSWORD")] + [Description("password for gluetun control server")] + public string Password { get; init; } + + /// <summary> + /// Gets the API key used for API key auth. + /// </summary> + [Argument(default, "vpn-gluetun-api-key")] + [EnvironmentVariable("VPN_GLUETUN_API_KEY")] + [Description("API key for gluetun control server")] + public string ApiKey { get; init; } + } + } + + /// <summary> /// Webhook configuration. /// </summary> public class WebhookOptions diff --git a/src/slskd/Core/OptionsOverlay.cs b/src/slskd/Core/OptionsOverlay.cs index 11167da5..4edd3b02 100644 --- a/src/slskd/Core/OptionsOverlay.cs +++ b/src/slskd/Core/OptionsOverlay.cs @@ -37,7 +37,7 @@ namespace slskd /// selectively applies the patch overlay only to information that is explicitly supplied. /// </para> /// </remarks> - public class OptionsOverlay + public record OptionsOverlay { /// <summary> /// Gets options for the Soulseek client. @@ -48,7 +48,7 @@ namespace slskd /// <summary> /// Soulseek client options. /// </summary> - public class SoulseekOptionsPatch + public record SoulseekOptionsPatch { /// <summary> /// Gets the local IP address on which to listen for incoming connections. diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 4f7876de..cd742348 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -36,6 +36,7 @@ namespace slskd public bool PendingRestart { get; init; } public ServerState Server { get; init; } = new ServerState(); public ServerConnectionWatchdogState ConnectionWatchdog { get; init; } = new ServerConnectionWatchdogState(); + public VpnState Vpn { get; init; } = new VpnState(); public RelayState Relay { get; init; } = new RelayState(); public HealthState Health { get; init; } = new HealthState(); public UserState User { get; init; } = new UserState(); @@ -90,7 +91,17 @@ namespace slskd { public bool IsEnabled { get; init; } = false; public bool IsAttemptingConnection { get; init; } = false; - public DateTime? NextAttemptAt { get; init; } + public bool IsAwaitingVpn { get; init; } = false; + public DateTime? NextAttemptAt { get; init; } = null; + } + + public record VpnState + { + public bool IsReady { get; init; } = false; + public bool IsConnected { get; init; } = false; + public IPAddress PublicIPAddress { get; init; } = null; + public string Location { get; init; } = null; + public int? ForwardedPort { get; init; } = null; } public record RelayState diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index ae3350f0..2ddf9b1f 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -119,6 +119,24 @@ public class EventBus /// <typeparam name="T">The Type of the event.</typeparam> /// <exception cref="ArgumentException">Thrown if the specified <paramref name="subscriber"/> is null or whitespace.</exception> /// <exception cref="ArgumentNullException">Thrown if the specified <paramref name="callback"/> is null.</exception> + public virtual void Subscribe<T>(string subscriber, Action<T> callback) + where T : Event + { + Subscribe<T>(subscriber, e => + { + callback(e); + return Task.CompletedTask; + }); + } + + /// <summary> + /// Subscribes a <paramref name="subscriber"/>'s <paramref name="callback"/> to an event. + /// </summary> + /// <param name="subscriber">The unique name of the subscriber.</param> + /// <param name="callback">The callback function to execute when an event is raised.</param> + /// <typeparam name="T">The Type of the event.</typeparam> + /// <exception cref="ArgumentException">Thrown if the specified <paramref name="subscriber"/> is null or whitespace.</exception> + /// <exception cref="ArgumentNullException">Thrown if the specified <paramref name="callback"/> is null.</exception> public virtual void Subscribe<T>(string subscriber, Func<T, Task> callback) where T : Event { diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 577e41e3..d67396dc 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -32,6 +32,10 @@ public enum EventType // UploadDirectoryComplete = 5, PrivateMessageReceived = 6, RoomMessageReceived = 7, + + SoulseekClientConnected = 50, + SoulseekClientDisconnected = 51, + Noop = int.MaxValue, } @@ -43,6 +47,20 @@ public abstract record Event public abstract int Version { get; } } +public sealed record SoulseekClientConnectedEvent : Event +{ + public override EventType Type => EventType.SoulseekClientConnected; + public override int Version { get; } = 0; +} + +public sealed record SoulseekClientDisconnectedEvent : Event +{ + public override EventType Type => EventType.SoulseekClientDisconnected; + public override int Version { get; } = 0; + public required string Message { get; init; } + public required Exception Exception { get; init; } +} + public sealed record DownloadFileCompleteEvent : Event { public override EventType Type => EventType.DownloadFileComplete; diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs new file mode 100644 index 00000000..d22c15f7 --- /dev/null +++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs @@ -0,0 +1,149 @@ +// <copyright file="Gluetun.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.VPN; + +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Serilog; +using static slskd.Options.IntegrationOptions.VpnOptions; + +/// <summary> +/// Gluetun VPN client. +/// </summary> +public class Gluetun : IVPNClient +{ + /// <summary> + /// Initializes a new instance of the <see cref="Gluetun"/> class. + /// </summary> + /// <param name="httpClientFactory"></param> + /// <param name="optionsMonitor"></param> + public Gluetun(IHttpClientFactory httpClientFactory, IOptionsMonitor<Options> optionsMonitor) + { + HttpClientFactory = httpClientFactory; + OptionsMonitor = optionsMonitor; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<Gluetun>(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; + + /// <summary> + /// Fetch the VPN connection status from the Gluetun control server. + /// </summary> + /// <returns>A value indicating whether the VPN is connected.</returns> + public async Task<VPNStatus> GetStatusAsync() + { + using var http = HttpClientFactory.CreateClient(); + + http.Timeout = TimeSpan.FromMilliseconds(Options.Timeout); + + if (!string.IsNullOrWhiteSpace(Options.ApiKey)) + { + http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + } + else if (!string.IsNullOrWhiteSpace(Options.Username)) + { + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); + } + else + { + // no auth + } + + try + { + var publicIp = await MakeRequest<GluetunPublicIpResponse>(http, "/v1/publicip/ip"); + + // per the gluetun docs/discussions, the public ip field will be an empty string if the VPN isn't up + if (string.IsNullOrEmpty(publicIp.PublicIp)) + { + return new VPNStatus { IsConnected = false }; + } + + int? port = null; + + if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) + { + port = (await MakeRequest<GluetunPortForwardResponse>(http, "/v1/portforward"))?.Port; + + // port will be 0 if port forwarding isn't enabled or ready + if (port == 0) + { + port = null; + } + } + + return new VPNStatus + { + IsConnected = true, + PublicIPAddress = IPAddress.Parse(publicIp.PublicIp), + Location = string.Join(", ", [publicIp.City, publicIp.Country]), + ForwardedPort = port, + }; + } + catch (Exception ex) + { + Log.Debug("Failed to retrieve status from Gluetun: {Message}", ex.Message); + throw new VPNClientException(ex.Message, ex); + } + } + + private async Task<T> MakeRequest<T>(HttpClient http, string url) + { + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync<T>() + ?? throw new Exception($"Unexpected Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); + + return result; + } + + private class GluetunStatusResponse + { + public string Status { get; init; } + } + + private class GluetunPortForwardResponse + { + public int? Port { get; init; } + } + + private class GluetunPublicIpResponse + { + [JsonPropertyName("public_ip")] + public string PublicIp { get; init; } + public string Region { get; init; } + public string Country { get; init; } + public string City { get; init; } + public string Location { get; init; } + public string Organization { get; init; } + + [JsonPropertyName("postal_code")] + public string PostalCode { get; init; } + public string Timezone { get; init; } + } +}
\ No newline at end of file diff --git a/src/slskd/Integrations/VPN/IVPNClient.cs b/src/slskd/Integrations/VPN/IVPNClient.cs new file mode 100644 index 00000000..0b4a872d --- /dev/null +++ b/src/slskd/Integrations/VPN/IVPNClient.cs @@ -0,0 +1,32 @@ +// <copyright file="IVPNClient.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using System.Threading.Tasks; + +namespace slskd.Integrations.VPN; + +/// <summary> +/// A lightweight interface for monitoring the status of a VPN provider. +/// </summary> +public interface IVPNClient +{ + /// <summary> + /// Fetch the VPN connection status from the provider. + /// </summary> + /// <returns>The current status.</returns> + public Task<VPNStatus> GetStatusAsync(); +}
\ No newline at end of file diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs new file mode 100644 index 00000000..bc3eb668 --- /dev/null +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -0,0 +1,263 @@ +// <copyright file="VPNService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.VPN; + +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Serilog; +using Soulseek; + +/// <summary> +/// VPN integration. +/// </summary> +public class VPNService : IDisposable +{ + /// <summary> + /// Initializes a new instance of the <see cref="VPNService"/> class. + /// </summary> + /// <param name="optionsAtStartup"></param> + /// <param name="optionsMonitor"></param> + /// <param name="stateMutator"></param> + /// <param name="soulseekClient"></param> + /// <param name="httpClientFactory"></param> + public VPNService( + OptionsAtStartup optionsAtStartup, + IOptionsMonitor<Options> optionsMonitor, + IStateMutator<State> stateMutator, + ISoulseekClient soulseekClient, + IHttpClientFactory httpClientFactory) + { + OptionsAtStartup = optionsAtStartup; + OptionsMonitor = optionsMonitor; + StateMutator = stateMutator; + SoulseekClient = soulseekClient; + HttpClientFactory = httpClientFactory; + + if (OptionsAtStartup.Integration.Vpn.Enabled) + { + Timer = new System.Timers.Timer(interval: OptionsAtStartup.Integration.Vpn.PollingInterval) + { + AutoReset = true, + }; + + Timer.Elapsed += async (_, _) => await CheckConnection(); + + // detect VPN based on the configuration provided; this logic will determine the order + // we can revisit this if/when we add other options besides gluetun + if (!string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun.Url)) + { + Client = new Gluetun(HttpClientFactory, OptionsMonitor); + + Log.Information("VPN integration enabled using {Client}", typeof(Gluetun).Name); + return; + } + + Log.Error("VPN integration is enabled, but no VPN client has been configured"); + } + } + + /// <summary> + /// Gets a value indicating whether the configured VPN client is ready (connected, and if port forwarding + /// is configured, a port has been provided). + /// </summary> + public bool IsReady { get; private set; } = false; + + /// <summary> + /// Gets the most recent VPN client status. + /// </summary> + public VPNStatus Status { get; private set; } = new VPNStatus(); + + private ISoulseekClient SoulseekClient { get; } + private IVPNClient Client { get; set; } + private System.Timers.Timer Timer { get; } + private IStateMutator<State> StateMutator { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<VPNService>(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private bool Disposed { get; set; } + private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); + + /// <summary> + /// Starts polling the configured VPN client for status updates. + /// </summary> + public void StartPolling() + { + if (Timer is not null && !Timer.Enabled) + { + Timer.Start(); + Log.Information("VPN client status polling enabled (interval: {Interval}ms)", Timer.Interval); + } + } + + /// <summary> + /// Stops polling the configured VPN client for status updates. + /// </summary> + public void StopPolling() + { + if (Timer is not null && Timer.Enabled) + { + Timer.Stop(); + Log.Information("VPN client status polling stopped"); + } + } + + /// <summary> + /// Disposes this instance. + /// </summary> + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// <summary> + /// Disposes this instance. + /// </summary> + /// <param name="disposing"></param> + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Timer.Dispose(); + } + + Disposed = true; + } + } + + private async Task CheckConnection() + { + var options = OptionsMonitor.CurrentValue.Integration.Vpn; + bool isReadyNow = false; + VPNStatus status = new VPNStatus(); + + // one at a time! + await TimerElapsedLock.WaitAsync(0); + + try + { + Log.Verbose("Checking VPN status using {Client}", Client.GetType()); + + try + { + status = await Client.GetStatusAsync() + ?? throw new VPNClientException("VPN client returned an invalid response"); + } + catch (Exception ex) + { + // log, but don't throw. an exception here is treated as if the VPN is down; we have to assume it is + Log.Warning("Failed to fetch status from VPN client {Client}: {Message}", Client.GetType().Name, ex.Message); + } + + if (status is not null && status.IsConnected) + { + if (options.PortForwarding) + { + if (status.ForwardedPort.HasValue) + { + isReadyNow = true; + + var overlay = Program.ConfigurationOverlay ?? new OptionsOverlay(); + overlay = overlay with { Soulseek = overlay.Soulseek ?? new OptionsOverlay.SoulseekOptionsPatch() }; + + // avoid incessant updates + if (overlay.Soulseek.ListenPort != status.ForwardedPort) + { + Program.ApplyConfigurationOverlay(overlay with + { + Soulseek = overlay.Soulseek with + { + ListenPort = status.ForwardedPort, + }, + }); + } + } + } + else + { + isReadyNow = true; + } + } + + if (!IsReady && isReadyNow) + { + if (options.PortForwarding) + { + Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort); + } + else + { + Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location})", status.PublicIPAddress, status.Location); + } + } + else if (IsReady && !isReadyNow) + { + Log.Warning("VPN client disconnected"); + } + else if (!IsReady && !isReadyNow) + { + if (!options.PortForwarding) + { + Log.Information("Waiting for VPN client; IP: ?"); + } + else + { + // port could possibly come first, if the client allows the user to specify it + string port = status.ForwardedPort.HasValue ? status.ForwardedPort.ToString() : "?"; + string ip = status.PublicIPAddress == default ? "?" : status.PublicIPAddress.ToString(); + Log.Information("Waiting for VPN client; IP: {PublicIP}, Forwarded port: {Port}", ip, port); + } + } + + IsReady = isReadyNow; + Status = status ?? new VPNStatus(); + + if (!IsReady) + { + SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); + } + + StateMutator.SetValue(state => state with + { + Vpn = new VpnState() + { + IsReady = IsReady, + IsConnected = Status?.IsConnected ?? false, + PublicIPAddress = Status?.PublicIPAddress, + Location = Status?.Location, + ForwardedPort = Status?.ForwardedPort, + }, + }); + } + catch (Exception ex) + { + Log.Warning(ex, "VPN client status check failed: {Message}", ex.Message); + } + finally + { + TimerElapsedLock.Release(); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Integrations/VPN/VPNStatus.cs b/src/slskd/Integrations/VPN/VPNStatus.cs new file mode 100644 index 00000000..c6e3d242 --- /dev/null +++ b/src/slskd/Integrations/VPN/VPNStatus.cs @@ -0,0 +1,28 @@ +// <copyright file="VPNStatus.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using System.Net; + +namespace slskd; + +public record VPNStatus +{ + public bool IsConnected { get; init; } = false; + public IPAddress PublicIPAddress { get; init; } = null; + public int? ForwardedPort { get; init; } = null; + public string Location { get; init; } = null; +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 75c51355..948bb9a6 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -63,6 +63,7 @@ namespace slskd using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Integrations.Scripts; + using slskd.Integrations.VPN; using slskd.Integrations.Webhooks; using slskd.Messaging; using slskd.Relay; @@ -601,6 +602,7 @@ namespace slskd // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService<ScriptService>(); _ = app.Services.GetService<WebhookService>(); + _ = app.Services.GetService<VPNService>(); app.ConfigureAspDotNetPipeline(); @@ -731,6 +733,7 @@ namespace slskd services.AddSingleton<ReportsService>(); services.AddSingleton<TelemetryService>(); + services.AddSingleton<VPNService>(); services.AddSingleton<ScriptService>(); services.AddSingleton<WebhookService>(); |
