From 5f27e0fe10b75440864057f1006cb93ba9eb01cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:08:29 -0600 Subject: add vpn stuff --- src/slskd/Common/Exceptions/VPNClientException.cs | 60 +++++++++++++++++++++++ src/slskd/Integrations/VPN/IVPNClient.cs | 38 ++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 src/slskd/Common/Exceptions/VPNClientException.cs create mode 100644 src/slskd/Integrations/VPN/IVPNClient.cs (limited to 'src') 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 (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/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// + /// Represents errors that originate from slskd logic. + /// + [ExcludeFromCodeCoverage] + public class VPNClientException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public VPNClientException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public VPNClientException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public VPNClientException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} \ 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..5a111ccd --- /dev/null +++ b/src/slskd/Integrations/VPN/IVPNClient.cs @@ -0,0 +1,38 @@ +// +// 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/. +// + +using System.Threading.Tasks; + +namespace slskd.Integrations.VPN; + +/// +/// A lightweight interface for monitoring the status of a VPN provider. +/// +public interface IVPNClient +{ + /// + /// Fetch the VPN connection status from the provider. + /// + /// A value indicating whether the VPN is connected. + public Task GetConnectionStatusAsync(); + + /// + /// Fetch the forwarded port configured with the provider, if enabled. + /// + /// The forwarded port. + public Task GetForwardedPortAsync(); +} \ No newline at end of file -- cgit v1.2.3 From 6e97421cd7d56d04efe37f7793ec77dd5b8b1d5a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:11:00 -0600 Subject: add VPN options --- src/slskd/Core/Options.cs | 88 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 200b0ee8..545dedac 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; @@ -2274,6 +2275,12 @@ namespace slskd /// public class IntegrationOptions { + /// + /// Gets VPN options. + /// + [Validate] + public VpnOptions Vpn { get; init; } = new(); + /// /// Gets webhook configuration. /// @@ -2298,6 +2305,87 @@ namespace slskd [Validate] public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); + /// + /// VPN options. + /// + public class VpnOptions + { + /// + /// Gets a value indicating whether the VPN integration is enabled. + /// + public bool Enabled { get; init; } = false; + + /// + /// Gets Gluetun options. + /// + public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions(); + + /// + /// Gluetun options. + /// + public class GluetunVpnOptions : IValidatableObject + { + /// + /// Gets the Gluetun integration version. + /// + /// + /// Only v1 of the Gluetun API exists right now; this is to ease a transition if there's ever a v2. + /// + [Range(1, 1)] + public int Version { get; init; } = 1; + + /// + /// Gets the fully qualified root URL for the Gluetun control server. + /// + [NotNullOrWhiteSpace] + public string Url { get; init; } + + /// + /// Gets the Gluetun control server authentication method. + /// + [Enum(typeof(GluetunClientAuthOptions), ignoreCase: true)] + public string Auth { get; init; } + + /// + /// Gets the username used for basic auth. + /// + public string Username { get; init; } + + /// + /// Gets the password used for basic auth. + /// + public string Password { get; init; } + + /// + /// Gets the API key used for API key auth. + /// + public string ApiKey { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (string.Equals(Auth, GluetunClientAuthOptions.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password)) + { + results.Add(new ValidationResult("Username and Password are required when using Basic auth")); + } + } + + if (string.Equals(Auth, GluetunClientAuthOptions.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(ApiKey)) + { + results.Add(new ValidationResult("ApiKey is required when using ApiKey auth")); + } + } + + return results; + } + } + } + /// /// Webhook configuration. /// -- cgit v1.2.3 From 2b3e6f30420128940c6c626b78028386e6c5a54b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:11:10 -0600 Subject: make OptionsOverlay a record --- src/slskd/Core/OptionsOverlay.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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. /// /// - public class OptionsOverlay + public record OptionsOverlay { /// /// Gets options for the Soulseek client. @@ -48,7 +48,7 @@ namespace slskd /// /// Soulseek client options. /// - public class SoulseekOptionsPatch + public record SoulseekOptionsPatch { /// /// Gets the local IP address on which to listen for incoming connections. -- cgit v1.2.3 From a3e880e813d97e917ba2f41b756e2430efd7d60e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:11:40 -0600 Subject: add events for client connect and disconnect --- src/slskd/Application.cs | 15 ++++++++++++++- src/slskd/Events/Types/Events.cs | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index bed8aab2..93db9073 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, - IHubContext logHub) + IHubContext 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 { get; set; } private IHubContext 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) @@ -960,6 +967,12 @@ namespace slskd 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/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; -- cgit v1.2.3 From f5365181c88885eaba3ad69511a5a2748f3481ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:11:53 -0600 Subject: add a non-async subscribe overload --- src/slskd/Events/EventBus.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') 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 @@ -111,6 +111,24 @@ public class EventBus } } + /// + /// Subscribes a 's to an event. + /// + /// The unique name of the subscriber. + /// The callback function to execute when an event is raised. + /// The Type of the event. + /// Thrown if the specified is null or whitespace. + /// Thrown if the specified is null. + public virtual void Subscribe(string subscriber, Action callback) + where T : Event + { + Subscribe(subscriber, e => + { + callback(e); + return Task.CompletedTask; + }); + } + /// /// Subscribes a 's to an event. /// -- cgit v1.2.3 From eb53ab89dde320acc10cd31efd863a5277cd23fa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 14:12:05 -0600 Subject: stub vpn service and gluetun client --- src/slskd/Integrations/VPN/GluetunClient.cs | 116 +++++++++++++++++++++++++++ src/slskd/Integrations/VPN/VPNService.cs | 119 ++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 src/slskd/Integrations/VPN/GluetunClient.cs create mode 100644 src/slskd/Integrations/VPN/VPNService.cs (limited to 'src') diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs new file mode 100644 index 00000000..16713963 --- /dev/null +++ b/src/slskd/Integrations/VPN/GluetunClient.cs @@ -0,0 +1,116 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.VPN; + +using System; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +using Serilog; +using static slskd.Options.IntegrationOptions.VpnOptions; + +public enum GluetunClientAuthOptions +{ + Basic, + ApiKey, +} + +public class GluetunClient : IVPNClient +{ + public GluetunClient(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) + { + HttpClientFactory = httpClientFactory; + OptionsMonitor = optionsMonitor; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor OptionsMonitor { get; } + private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; + + public async Task GetConnectionStatusAsync() + { + using var http = HttpClientFactory.CreateClient(); + http.Timeout = TimeSpan.FromMilliseconds(1000); + ConfigureAuth(http); + + try + { + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}/v1/vpn/status"); + response.EnsureSuccessStatusCode(); + + var status = await response.Content.ReadFromJsonAsync() + ?? throw new Exception($"Failed to deserialize Gluetun status response; got: {await response.Content.ReadAsStringAsync()}"); + + return status.Status.Equals("running", StringComparison.OrdinalIgnoreCase); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to retrieve status from Gluetun: {Message}", ex.Message); + throw new VPNClientException($"Failed to retrieve status from Gluetun: {ex.Message}", ex); + } + } + + public async Task GetForwardedPortAsync() + { + using var http = HttpClientFactory.CreateClient(); + http.Timeout = TimeSpan.FromMilliseconds(1000); + ConfigureAuth(http); + + try + { + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}/v1/portforward"); + response.EnsureSuccessStatusCode(); + + var port = await response.Content.ReadFromJsonAsync() + ?? throw new Exception($"Failed to deserialize Gluetun port forward response; got: {await response.Content.ReadAsStringAsync()}"); + + return port.Port; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to retrieve status from Gluetun: {Message}", ex.Message); + throw new VPNClientException($"Failed to retrieve status from Gluetun: {ex.Message}", ex); + } + } + + private void ConfigureAuth(HttpClient client) + { + if (Options.Auth.Equals(GluetunClientAuthOptions.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + { + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); + } + else + { + client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + } + } + + private class GluetunStatusResponse + { + public string Status { get; init; } + } + + private class GluetunPortForwardResponse + { + public int Port { get; init; } + } +} \ 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..1b636d62 --- /dev/null +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -0,0 +1,119 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.VPN; + +using System; +using System.Net.Http; +using System.Threading; +using Serilog; +using slskd.Events; +using static slskd.Options.IntegrationOptions; + +public class VPNService : IDisposable +{ + public VPNService( + IOptionsMonitor optionsMonitor, + EventBus eventBus, + IHttpClientFactory httpClientFactory) + { + OptionsMonitor = optionsMonitor; + HttpClientFactory = httpClientFactory; + + Timer = new System.Timers.Timer(interval: 1000) + { + AutoReset = true, + }; + + Timer.Elapsed += Timer_Elapsed; + + EventBus = eventBus; + EventBus.Subscribe(nameof(VPNService), e => + { + Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds; + }); + + if (Options.Enabled) + { + if (!string.IsNullOrEmpty(Options.Gluetun.Url)) + { + Client = new GluetunClient(HttpClientFactory, OptionsMonitor); + Timer.Start(); + return; + } + + Log.Error("VPN integration is enabled, but no VPN client has been configured"); + } + } + + private EventBus EventBus { get; } + private IVPNClient Client { get; set; } + private System.Timers.Timer Timer { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor OptionsMonitor { get; } + private VpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn; + private bool Disposed { get; set; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Timer.Dispose(); + } + + Disposed = true; + } + } + + private async void Timer_Elapsed(object sender, EventArgs args) + { + try + { + var isConnected = await Client.GetConnectionStatusAsync(); + + if (isConnected) + { + var port = await Client.GetForwardedPortAsync(); + + Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with + { + Soulseek = Program.ConfigurationOverlay.Soulseek with + { + ListenPort = 123, + }, + }); + + Timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds; + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to communicate with VPN client: {Message}", ex.Message); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 1f7799fd5b1d75ce4648de7e025793038539c1c7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 22:25:44 -0600 Subject: add required and portforwarding vpn options --- src/slskd/Core/Options.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 545dedac..10aaed3d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2315,6 +2315,16 @@ namespace slskd /// public bool Enabled { get; init; } = false; + /// + /// Gets a value indicating whether a VPN connection is required before connecting to the Soulseek network. + /// + public bool Required { get; init; } = false; + + /// + /// Gets a value indicating whether the configured VPN supports port forwarding. + /// + public bool PortForwarding { get; init; } = false; + /// /// Gets Gluetun options. /// @@ -2343,8 +2353,8 @@ namespace slskd /// /// Gets the Gluetun control server authentication method. /// - [Enum(typeof(GluetunClientAuthOptions), ignoreCase: true)] - public string Auth { get; init; } + [Enum(typeof(GluetunClientAuthenticationMethod), ignoreCase: true)] + public string Auth { get; init; } = GluetunClientAuthenticationMethod.None.ToString(); /// /// Gets the username used for basic auth. @@ -2365,7 +2375,7 @@ namespace slskd { var results = new List(); - if (string.Equals(Auth, GluetunClientAuthOptions.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + if (string.Equals(Auth, GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password)) { @@ -2373,7 +2383,7 @@ namespace slskd } } - if (string.Equals(Auth, GluetunClientAuthOptions.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) + if (string.Equals(Auth, GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(ApiKey)) { -- cgit v1.2.3 From c0ab76e7a199b71431e73b2cf70cbf616feaf026 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 22:26:00 -0600 Subject: add none auth method --- src/slskd/Integrations/VPN/GluetunClient.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs index 16713963..81757c5c 100644 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ b/src/slskd/Integrations/VPN/GluetunClient.cs @@ -26,8 +26,9 @@ using System.Threading.Tasks; using Serilog; using static slskd.Options.IntegrationOptions.VpnOptions; -public enum GluetunClientAuthOptions +public enum GluetunClientAuthenticationMethod { + None, Basic, ApiKey, } @@ -93,7 +94,7 @@ public class GluetunClient : IVPNClient private void ConfigureAuth(HttpClient client) { - if (Options.Auth.Equals(GluetunClientAuthOptions.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) { var creds = $"{Options.Username}:{Options.Password}".ToBase64(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); -- cgit v1.2.3 From a5da4702b441644b3ffab3993347b6c476de417a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Feb 2026 22:31:55 -0600 Subject: rough in vpn service --- src/slskd/Integrations/VPN/VPNService.cs | 71 +++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 1b636d62..270f748c 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -22,8 +22,10 @@ namespace slskd.Integrations.VPN; using System; using System.Net.Http; using System.Threading; +using System.Threading.Tasks; using Serilog; using slskd.Events; +using Soulseek; using static slskd.Options.IntegrationOptions; public class VPNService : IDisposable @@ -41,12 +43,25 @@ public class VPNService : IDisposable AutoReset = true, }; - Timer.Elapsed += Timer_Elapsed; + Timer.Elapsed += async (_, _) => await CheckConnection(); EventBus = eventBus; - EventBus.Subscribe(nameof(VPNService), e => + EventBus.Subscribe(nameof(VPNService), async e => { - Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds; + await SyncRoot.WaitAsync(); + + try + { + var cts = ConnectedTaskCompletionSource; + ConnectedTaskCompletionSource = new(); + cts.TrySetException(new SoulseekClientException("Client disconnected")); + + Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds; + } + finally + { + SyncRoot.Release(); + } }); if (Options.Enabled) @@ -70,6 +85,28 @@ public class VPNService : IDisposable private IOptionsMonitor OptionsMonitor { get; } private VpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn; private bool Disposed { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); + private TaskCompletionSource ConnectedTaskCompletionSource { get; set; } = new(); + + public async Task WaitForConnectionAsync() + { + await SyncRoot.WaitAsync(); + + Task task = default; + + try + { + task = ConnectedTaskCompletionSource.Task; + } + finally + { + SyncRoot.Release(); + } + + _ = CheckConnection(); + await task; + } public void Dispose() { @@ -90,23 +127,31 @@ public class VPNService : IDisposable } } - private async void Timer_Elapsed(object sender, EventArgs args) + private async Task CheckConnection() { + // only one connection process at a time + await TimerElapsedLock.WaitAsync(0); + try { var isConnected = await Client.GetConnectionStatusAsync(); if (isConnected) { - var port = await Client.GetForwardedPortAsync(); - - Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with + if (Options.PortForwarding) { - Soulseek = Program.ConfigurationOverlay.Soulseek with + var port = await Client.GetForwardedPortAsync(); + + Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with { - ListenPort = 123, - }, - }); + Soulseek = Program.ConfigurationOverlay.Soulseek with + { + ListenPort = port, + }, + }); + } + + ConnectedTaskCompletionSource.TrySetResult(); Timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds; } @@ -115,5 +160,9 @@ public class VPNService : IDisposable { Log.Error(ex, "Failed to communicate with VPN client: {Message}", ex.Message); } + finally + { + TimerElapsedLock.Release(); + } } } \ No newline at end of file -- cgit v1.2.3 From 2fa649934b70edc40350343eb583574dce8c7617 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Feb 2026 19:07:56 -0600 Subject: tweak attributes for vpn options --- src/slskd/Core/Options.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 10aaed3d..85d1491c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2313,11 +2313,13 @@ namespace slskd /// /// Gets a value indicating whether the VPN integration is enabled. /// + [RequiresRestart] public bool Enabled { get; init; } = false; /// /// Gets a value indicating whether a VPN connection is required before connecting to the Soulseek network. /// + [RequiresRestart] public bool Required { get; init; } = false; /// @@ -2328,6 +2330,7 @@ namespace slskd /// /// Gets Gluetun options. /// + [Validate] public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions(); /// -- cgit v1.2.3 From 0a8c9afbc2d435b230f745c7ed6f2e142668c65f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Feb 2026 19:08:13 -0600 Subject: docs and interface renames --- src/slskd/Integrations/VPN/GluetunClient.cs | 23 ++++++++++++++++++----- src/slskd/Integrations/VPN/IVPNClient.cs | 6 +++--- 2 files changed, 21 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs index 81757c5c..0d2d7fd0 100644 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ b/src/slskd/Integrations/VPN/GluetunClient.cs @@ -46,7 +46,11 @@ public class GluetunClient : IVPNClient private IOptionsMonitor OptionsMonitor { get; } private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; - public async Task GetConnectionStatusAsync() + /// + /// Fetch the VPN connection status from the Gluetun control server. + /// + /// A value indicating whether the VPN is connected. + public async Task GetIsConnectedAsync() { using var http = HttpClientFactory.CreateClient(); http.Timeout = TimeSpan.FromMilliseconds(1000); @@ -69,7 +73,11 @@ public class GluetunClient : IVPNClient } } - public async Task GetForwardedPortAsync() + /// + /// Fetch the forwarded port from the Gluetun control server. + /// + /// The forwarded port, or null if one hasn't been provided yet. + public async Task GetForwardedPortAsync() { using var http = HttpClientFactory.CreateClient(); http.Timeout = TimeSpan.FromMilliseconds(1000); @@ -83,7 +91,8 @@ public class GluetunClient : IVPNClient var port = await response.Content.ReadFromJsonAsync() ?? throw new Exception($"Failed to deserialize Gluetun port forward response; got: {await response.Content.ReadAsStringAsync()}"); - return port.Port; + // Gluetun will return 0 if the port hasn't been retrieved yet, or if port forwarding is turned off + return port.Port == 0 ? null : port.Port; } catch (Exception ex) { @@ -99,10 +108,14 @@ public class GluetunClient : IVPNClient var creds = $"{Options.Username}:{Options.Password}".ToBase64(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); } - else + else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) { client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); } + else + { + // no auth + } } private class GluetunStatusResponse @@ -112,6 +125,6 @@ public class GluetunClient : IVPNClient private class GluetunPortForwardResponse { - public int Port { get; init; } + public int? Port { get; init; } } } \ No newline at end of file diff --git a/src/slskd/Integrations/VPN/IVPNClient.cs b/src/slskd/Integrations/VPN/IVPNClient.cs index 5a111ccd..7c6c5022 100644 --- a/src/slskd/Integrations/VPN/IVPNClient.cs +++ b/src/slskd/Integrations/VPN/IVPNClient.cs @@ -28,11 +28,11 @@ public interface IVPNClient /// Fetch the VPN connection status from the provider. /// /// A value indicating whether the VPN is connected. - public Task GetConnectionStatusAsync(); + public Task GetIsConnectedAsync(); /// /// Fetch the forwarded port configured with the provider, if enabled. /// - /// The forwarded port. - public Task GetForwardedPortAsync(); + /// The forwarded port, or null if one hasn't been provided yet. + public Task GetForwardedPortAsync(); } \ No newline at end of file -- cgit v1.2.3 From d4f2f5b3d7041e339e37727dddfa1c63064a051a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 Feb 2026 20:36:51 -0600 Subject: add VpnState --- src/slskd/Core/State.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 4f7876de..7730e0eb 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(); @@ -93,6 +94,13 @@ namespace slskd public DateTime? NextAttemptAt { get; init; } } + public record VpnState + { + public bool IsConnected { get; init; } = false; + public int? ForwardedPort { get; init; } = null; + public bool IsReady { get; init; } = false; + } + public record RelayState { public RelayMode Mode { get; init; } -- cgit v1.2.3 From 1709f1aaa22f32904236616fcb4b41b0cc3cca4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 Feb 2026 20:37:14 -0600 Subject: finish VPNService implementation --- src/slskd/Integrations/VPN/VPNService.cs | 167 +++++++++++++++++++++++-------- 1 file changed, 123 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 270f748c..9eece537 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -25,48 +25,36 @@ using System.Threading; using System.Threading.Tasks; using Serilog; using slskd.Events; -using Soulseek; -using static slskd.Options.IntegrationOptions; public class VPNService : IDisposable { public VPNService( + OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, EventBus eventBus, + IStateMonitor stateMonitor, + IStateMutator stateMutator, IHttpClientFactory httpClientFactory) { + OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + EventBus = eventBus; + StateMutator = stateMutator; + StateMonitor = stateMonitor; HttpClientFactory = httpClientFactory; - Timer = new System.Timers.Timer(interval: 1000) - { - AutoReset = true, - }; - - Timer.Elapsed += async (_, _) => await CheckConnection(); - - EventBus = eventBus; - EventBus.Subscribe(nameof(VPNService), async e => + if (OptionsAtStartup.Integration.Vpn.Enabled) { - await SyncRoot.WaitAsync(); - - try + Timer = new System.Timers.Timer(interval: 2500) { - var cts = ConnectedTaskCompletionSource; - ConnectedTaskCompletionSource = new(); - cts.TrySetException(new SoulseekClientException("Client disconnected")); + AutoReset = true, + }; - Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds; - } - finally - { - SyncRoot.Release(); - } - }); + Timer.Elapsed += async (_, _) => await CheckConnection(); - if (Options.Enabled) - { - if (!string.IsNullOrEmpty(Options.Gluetun.Url)) + // 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 GluetunClient(HttpClientFactory, OptionsMonitor); Timer.Start(); @@ -77,19 +65,25 @@ public class VPNService : IDisposable } } - private EventBus EventBus { get; } + public bool IsConnected { get; private set; } + public int? ForwardedPort { get; private set; } + public bool IsReady { get; private set; } + private IVPNClient Client { get; set; } private System.Timers.Timer Timer { get; } + private EventBus EventBus { get; } + private IStateMutator StateMutator { get; } + private IStateMonitor StateMonitor { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IHttpClientFactory HttpClientFactory { get; } private IOptionsMonitor OptionsMonitor { get; } - private VpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn; + private OptionsAtStartup OptionsAtStartup { get; } private bool Disposed { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); - private TaskCompletionSource ConnectedTaskCompletionSource { get; set; } = new(); + private TaskCompletionSource ReadyTaskCompletionSource { get; set; } = new(); - public async Task WaitForConnectionAsync() + public async Task WaitForReadyAsync() { await SyncRoot.WaitAsync(); @@ -97,7 +91,7 @@ public class VPNService : IDisposable try { - task = ConnectedTaskCompletionSource.Task; + task = ReadyTaskCompletionSource.Task; } finally { @@ -129,31 +123,116 @@ public class VPNService : IDisposable private async Task CheckConnection() { - // only one connection process at a time + var initialIsReady = IsReady; + bool isConnected = false; + int? port = null; + + // one at a time! await TimerElapsedLock.WaitAsync(0); try { - var isConnected = await Client.GetConnectionStatusAsync(); + /* + step one: fetch status from the VPN client + + this step performs I/O with the VPN client, so do it before obtaining the SyncRoot to avoid + unnecessary lock contention + */ + Log.Debug("Checking VPN status using {Client}", Client.GetType()); + + isConnected = await Client.GetIsConnectedAsync(); + + if (isConnected && OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) + { + Log.Debug("Fetching forwarded port from {Client}", Client.GetType()); + + port = await Client.GetForwardedPortAsync(); - if (isConnected) + if (port.HasValue && (port < 1024 || port > 65535)) + { + Log.Warning("VPN client provided a forwarded port outside of the supported range of 1024-65535 (given: {Port})", ForwardedPort); + port = null; + } + } + + // synchronize access to the TaskCompletionSource so we don't swap it out while something is trying to access it + await SyncRoot.WaitAsync(); + + try { - if (Options.PortForwarding) + /* + step two: + * update VPNService state + * apply a configuration overlay to set the forwarded port (if there is one) + * update application state (via StateMutator) + * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource + */ + if (!isConnected) + { + IsConnected = false; + IsReady = false; + ForwardedPort = null; + } + else { - var port = await Client.GetForwardedPortAsync(); + IsConnected = true; - Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with + if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) { - Soulseek = Program.ConfigurationOverlay.Soulseek with + if (port.HasValue) { - ListenPort = port, - }, - }); + ForwardedPort = port; + IsReady = true; + + // always apply the provided port, as it may change while the app is running + Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with + { + Soulseek = Program.ConfigurationOverlay.Soulseek with + { + ListenPort = ForwardedPort, + }, + }); + } + } + else + { + IsReady = true; + } } - ConnectedTaskCompletionSource.TrySetResult(); + // if we weren't ready before and now we are, signal to anyone waiting that we're good to go + if (!initialIsReady && IsReady) + { + // complete the TCS so anything waiting for ready can progress. don't replace it; VPN should be assumed + // to stay ready until we check and find that it is no longer ready + ReadyTaskCompletionSource.SetResult(); + } - Timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds; + // if we were previously ready and now we aren't, the VPN has disconnected or stopped providing a port + if (initialIsReady && !IsReady) + { + var tcs = ReadyTaskCompletionSource; + + // replace the TCS with a new one; anything that waits on it needs to wait for a new transition to ready + ReadyTaskCompletionSource = new TaskCompletionSource(); + + // throw the existing TCS so anything waiting for it dies (otherwise risk of waiting forever) + tcs.SetException(new VPNClientException("VPN client is no longer ready")); + } + } + finally + { + StateMutator.SetValue(state => state with + { + Vpn = new VpnState() + { + IsConnected = IsConnected, + ForwardedPort = ForwardedPort, + IsReady = IsReady, + }, + }); + + SyncRoot.Release(); } } catch (Exception ex) -- cgit v1.2.3 From b2c321c401d305e7c8f9edcd60c3d9e03ddfa359 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 09:14:06 -0600 Subject: consolidate calls into one --- src/slskd/Integrations/VPN/GluetunClient.cs | 112 ++++++++++++++++------------ src/slskd/Integrations/VPN/IVPNClient.cs | 10 +-- 2 files changed, 67 insertions(+), 55 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs index 0d2d7fd0..28fef202 100644 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ b/src/slskd/Integrations/VPN/GluetunClient.cs @@ -20,8 +20,10 @@ 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; @@ -50,72 +52,73 @@ public class GluetunClient : IVPNClient /// Fetch the VPN connection status from the Gluetun control server. /// /// A value indicating whether the VPN is connected. - public async Task GetIsConnectedAsync() + public async Task GetStatusAsync() { using var http = HttpClientFactory.CreateClient(); + http.Timeout = TimeSpan.FromMilliseconds(1000); - ConfigureAuth(http); - try + if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) { - using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}/v1/vpn/status"); - response.EnsureSuccessStatusCode(); - - var status = await response.Content.ReadFromJsonAsync() - ?? throw new Exception($"Failed to deserialize Gluetun status response; got: {await response.Content.ReadAsStringAsync()}"); - - return status.Status.Equals("running", StringComparison.OrdinalIgnoreCase); + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); } - catch (Exception ex) + else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) { - Log.Warning(ex, "Failed to retrieve status from Gluetun: {Message}", ex.Message); - throw new VPNClientException($"Failed to retrieve status from Gluetun: {ex.Message}", ex); + http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + } + else + { + // no auth } - } - - /// - /// Fetch the forwarded port from the Gluetun control server. - /// - /// The forwarded port, or null if one hasn't been provided yet. - public async Task GetForwardedPortAsync() - { - using var http = HttpClientFactory.CreateClient(); - http.Timeout = TimeSpan.FromMilliseconds(1000); - ConfigureAuth(http); try { - using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}/v1/portforward"); - response.EnsureSuccessStatusCode(); - - var port = await response.Content.ReadFromJsonAsync() - ?? throw new Exception($"Failed to deserialize Gluetun port forward response; got: {await response.Content.ReadAsStringAsync()}"); - - // Gluetun will return 0 if the port hasn't been retrieved yet, or if port forwarding is turned off - return port.Port == 0 ? null : port.Port; + var publicIp = await MakeRequest(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(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.Warning(ex, "Failed to retrieve status from Gluetun: {Message}", ex.Message); + Log.Warning("Failed to retrieve status from Gluetun: {Message}", ex.Message); throw new VPNClientException($"Failed to retrieve status from Gluetun: {ex.Message}", ex); } } - private void ConfigureAuth(HttpClient client) + private async Task MakeRequest(HttpClient http, string url) { - if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) - { - var creds = $"{Options.Username}:{Options.Password}".ToBase64(); - client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); - } - else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) - { - client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); - } - else - { - // no auth - } + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync() + ?? throw new Exception($"Failed to deserialize Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); + + return result; } private class GluetunStatusResponse @@ -127,4 +130,19 @@ public class GluetunClient : IVPNClient { 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 index 7c6c5022..0b4a872d 100644 --- a/src/slskd/Integrations/VPN/IVPNClient.cs +++ b/src/slskd/Integrations/VPN/IVPNClient.cs @@ -27,12 +27,6 @@ public interface IVPNClient /// /// Fetch the VPN connection status from the provider. /// - /// A value indicating whether the VPN is connected. - public Task GetIsConnectedAsync(); - - /// - /// Fetch the forwarded port configured with the provider, if enabled. - /// - /// The forwarded port, or null if one hasn't been provided yet. - public Task GetForwardedPortAsync(); + /// The current status. + public Task GetStatusAsync(); } \ No newline at end of file -- cgit v1.2.3 From 4d6bf6d6c038c7b5ccdca003cca09a18ce1ea285 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 09:22:37 -0600 Subject: add ip and location to vpn state --- src/slskd/Core/State.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 7730e0eb..f9a3bf97 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -96,9 +96,11 @@ namespace slskd 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 bool IsReady { get; init; } = false; } public record RelayState -- cgit v1.2.3 From 91a16e7d1864edcbc4d1c946038c83830fb750e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 09:22:57 -0600 Subject: wire up the VPN service --- src/slskd/Program.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') 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(); _ = app.Services.GetService(); + _ = app.Services.GetService(); app.ConfigureAspDotNetPipeline(); @@ -731,6 +733,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From f10a4aa2cad193a01b14fe52e1bb6350f41a474b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 09:23:28 -0600 Subject: abort connection attempts if the VPN is required and not ready --- src/slskd/Core/ConnectionWatchdog.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index b7a4fa34..0cf30484 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; /// @@ -41,15 +42,21 @@ namespace slskd /// Initializes a new instance of the class. /// /// + /// /// + /// /// public ConnectionWatchdog( ISoulseekClient soulseekClient, + VPNService vpnService, IOptionsMonitor optionsMonitor, + OptionsAtStartup optionsAtStartup, IManagedState applicationState) { Client = soulseekClient; + VPN = vpnService; OptionsMonitor = optionsMonitor; + OptionsAtStartup = optionsAtStartup; ApplicationState = applicationState; WatchdogTimer = new System.Timers.Timer() @@ -77,9 +84,11 @@ namespace slskd public bool IsAttemptingConnection => SyncRoot.CurrentCount == 0; private ISoulseekClient Client { get; } + private VPNService VPN { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } private IManagedState ApplicationState { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private object StateLock { get; } = new object(); @@ -232,6 +241,12 @@ namespace slskd return; } + if (OptionsAtStartup.Integration.Vpn.Required && !VPN.IsReady) + { + Log.Debug("AttemptConnection aborted; VPN is not yet ready (status: {Status})", VPN.Status); + return; + } + CancellationTokenSource = new CancellationTokenSource(); if (attempts > 0) -- cgit v1.2.3 From 4906d0b377a5b2eb45c95d3a40b01f5b2f9ef2cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 09:23:38 -0600 Subject: add VPNStatus --- src/slskd/Integrations/VPN/VPNStatus.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/slskd/Integrations/VPN/VPNStatus.cs (limited to 'src') 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 (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/. +// + +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 -- cgit v1.2.3 From 8134803e8047942e9beb962996e3a4db01593c71 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 18:36:33 -0600 Subject: remove wait method --- src/slskd/Integrations/VPN/VPNService.cs | 130 +++++++++++++------------------ 1 file changed, 54 insertions(+), 76 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 9eece537..d57a3122 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -24,23 +24,21 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Serilog; -using slskd.Events; +using Soulseek; public class VPNService : IDisposable { public VPNService( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, - EventBus eventBus, - IStateMonitor stateMonitor, IStateMutator stateMutator, + ISoulseekClient soulseekClient, IHttpClientFactory httpClientFactory) { OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; - EventBus = eventBus; StateMutator = stateMutator; - StateMonitor = stateMonitor; + SoulseekClient = soulseekClient; HttpClientFactory = httpClientFactory; if (OptionsAtStartup.Integration.Vpn.Enabled) @@ -58,6 +56,8 @@ public class VPNService : IDisposable { Client = new GluetunClient(HttpClientFactory, OptionsMonitor); Timer.Start(); + + Log.Information("VPN integration enabled using {Client}", typeof(GluetunClient).Name); return; } @@ -65,15 +65,13 @@ public class VPNService : IDisposable } } - public bool IsConnected { get; private set; } - public int? ForwardedPort { get; private set; } - public bool IsReady { get; private set; } + public bool IsReady { get; private set; } = false; + public VPNStatus Status { get; private set; } = new VPNStatus(); + private ISoulseekClient SoulseekClient { get; } private IVPNClient Client { get; set; } private System.Timers.Timer Timer { get; } - private EventBus EventBus { get; } private IStateMutator StateMutator { get; } - private IStateMonitor StateMonitor { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IHttpClientFactory HttpClientFactory { get; } private IOptionsMonitor OptionsMonitor { get; } @@ -81,26 +79,6 @@ public class VPNService : IDisposable private bool Disposed { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); - private TaskCompletionSource ReadyTaskCompletionSource { get; set; } = new(); - - public async Task WaitForReadyAsync() - { - await SyncRoot.WaitAsync(); - - Task task = default; - - try - { - task = ReadyTaskCompletionSource.Task; - } - finally - { - SyncRoot.Release(); - } - - _ = CheckConnection(); - await task; - } public void Dispose() { @@ -123,9 +101,8 @@ public class VPNService : IDisposable private async Task CheckConnection() { - var initialIsReady = IsReady; - bool isConnected = false; - int? port = null; + bool isReadyNow = false; + VPNStatus status = default; // one at a time! await TimerElapsedLock.WaitAsync(0); @@ -138,22 +115,9 @@ public class VPNService : IDisposable this step performs I/O with the VPN client, so do it before obtaining the SyncRoot to avoid unnecessary lock contention */ - Log.Debug("Checking VPN status using {Client}", Client.GetType()); - - isConnected = await Client.GetIsConnectedAsync(); - - if (isConnected && OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) - { - Log.Debug("Fetching forwarded port from {Client}", Client.GetType()); + Log.Verbose("Checking VPN status using {Client}", Client.GetType()); - port = await Client.GetForwardedPortAsync(); - - if (port.HasValue && (port < 1024 || port > 65535)) - { - Log.Warning("VPN client provided a forwarded port outside of the supported range of 1024-65535 (given: {Port})", ForwardedPort); - port = null; - } - } + status = await Client.GetStatusAsync(); // synchronize access to the TaskCompletionSource so we don't swap it out while something is trying to access it await SyncRoot.WaitAsync(); @@ -167,57 +131,69 @@ public class VPNService : IDisposable * update application state (via StateMutator) * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource */ - if (!isConnected) + if (!status.IsConnected) { - IsConnected = false; - IsReady = false; - ForwardedPort = null; + isReadyNow = false; } else { - IsConnected = true; - if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) { - if (port.HasValue) + if (status.ForwardedPort.HasValue) { - ForwardedPort = port; - IsReady = true; + isReadyNow = true; + + var overlay = Program.ConfigurationOverlay ?? new OptionsOverlay(); + overlay = overlay with { Soulseek = overlay.Soulseek ?? new OptionsOverlay.SoulseekOptionsPatch() }; - // always apply the provided port, as it may change while the app is running - Program.ApplyConfigurationOverlay(Program.ConfigurationOverlay with + // avoid incessant updates + if (overlay.Soulseek.ListenPort != status.ForwardedPort) { - Soulseek = Program.ConfigurationOverlay.Soulseek with + Program.ApplyConfigurationOverlay(overlay with { - ListenPort = ForwardedPort, - }, - }); + Soulseek = overlay.Soulseek with + { + ListenPort = status.ForwardedPort, + }, + }); + } } } else { - IsReady = true; + isReadyNow = true; } } + Status = status; + // if we weren't ready before and now we are, signal to anyone waiting that we're good to go - if (!initialIsReady && IsReady) + if (!IsReady && isReadyNow) { // complete the TCS so anything waiting for ready can progress. don't replace it; VPN should be assumed // to stay ready until we check and find that it is no longer ready - ReadyTaskCompletionSource.SetResult(); + if (status.ForwardedPort.HasValue) + { + Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location}); forwarding port {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort); + } + else + { + Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location})", status.PublicIPAddress, status.Location); + } + + IsReady = isReadyNow; } // if we were previously ready and now we aren't, the VPN has disconnected or stopped providing a port - if (initialIsReady && !IsReady) + if (IsReady && !isReadyNow) { - var tcs = ReadyTaskCompletionSource; - - // replace the TCS with a new one; anything that waits on it needs to wait for a new transition to ready - ReadyTaskCompletionSource = new TaskCompletionSource(); + IsReady = isReadyNow; + Log.Warning("VPN client disconnected"); - // throw the existing TCS so anything waiting for it dies (otherwise risk of waiting forever) - tcs.SetException(new VPNClientException("VPN client is no longer ready")); + if (OptionsAtStartup.Integration.Vpn.Required) + { + SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); + } } } finally @@ -226,9 +202,11 @@ public class VPNService : IDisposable { Vpn = new VpnState() { - IsConnected = IsConnected, - ForwardedPort = ForwardedPort, IsReady = IsReady, + IsConnected = status.IsConnected, + PublicIPAddress = status.PublicIPAddress, + Location = status.Location, + ForwardedPort = status.ForwardedPort, }, }); @@ -237,7 +215,7 @@ public class VPNService : IDisposable } catch (Exception ex) { - Log.Error(ex, "Failed to communicate with VPN client: {Message}", ex.Message); + Log.Warning("Failed to communicate with VPN client: {Message}", ex.Message); } finally { -- cgit v1.2.3 From a29a2fddedc0deb670e14256df4ca13466e05b71 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 Feb 2026 18:49:19 -0600 Subject: simplify check logic --- src/slskd/Integrations/VPN/VPNService.cs | 139 ++++++++++++++----------------- 1 file changed, 61 insertions(+), 78 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index d57a3122..179c5436 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -77,7 +77,6 @@ public class VPNService : IDisposable private IOptionsMonitor OptionsMonitor { get; } private OptionsAtStartup OptionsAtStartup { get; } private bool Disposed { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); public void Dispose() @@ -117,105 +116,89 @@ public class VPNService : IDisposable */ Log.Verbose("Checking VPN status using {Client}", Client.GetType()); - status = await Client.GetStatusAsync(); - - // synchronize access to the TaskCompletionSource so we don't swap it out while something is trying to access it - await SyncRoot.WaitAsync(); - try { - /* - step two: - * update VPNService state - * apply a configuration overlay to set the forwarded port (if there is one) - * update application state (via StateMutator) - * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource - */ - if (!status.IsConnected) - { - isReadyNow = false; - } - else + status = await Client.GetStatusAsync(); + } + 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: {Message}", ex.Message); + } + + /* + step two: + * update VPNService state + * apply a configuration overlay to set the forwarded port (if there is one) + * update application state (via StateMutator) + * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource + */ + if (!status.IsConnected) + { + isReadyNow = false; + } + else + { + if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) { - if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) + if (status.ForwardedPort.HasValue) { - if (status.ForwardedPort.HasValue) - { - isReadyNow = true; + isReadyNow = true; - var overlay = Program.ConfigurationOverlay ?? new OptionsOverlay(); - overlay = overlay with { Soulseek = overlay.Soulseek ?? new OptionsOverlay.SoulseekOptionsPatch() }; + var overlay = Program.ConfigurationOverlay ?? new OptionsOverlay(); + overlay = overlay with { Soulseek = overlay.Soulseek ?? new OptionsOverlay.SoulseekOptionsPatch() }; - // avoid incessant updates - if (overlay.Soulseek.ListenPort != status.ForwardedPort) + // avoid incessant updates + if (overlay.Soulseek.ListenPort != status.ForwardedPort) + { + Program.ApplyConfigurationOverlay(overlay with { - Program.ApplyConfigurationOverlay(overlay with + Soulseek = overlay.Soulseek with { - Soulseek = overlay.Soulseek with - { - ListenPort = status.ForwardedPort, - }, - }); - } + ListenPort = status.ForwardedPort, + }, + }); } } - else - { - isReadyNow = true; - } } - - Status = status; - - // if we weren't ready before and now we are, signal to anyone waiting that we're good to go - if (!IsReady && isReadyNow) + else { - // complete the TCS so anything waiting for ready can progress. don't replace it; VPN should be assumed - // to stay ready until we check and find that it is no longer ready - if (status.ForwardedPort.HasValue) - { - Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location}); forwarding port {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort); - } - else - { - Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location})", status.PublicIPAddress, status.Location); - } - - IsReady = isReadyNow; + isReadyNow = true; } + } - // if we were previously ready and now we aren't, the VPN has disconnected or stopped providing a port - if (IsReady && !isReadyNow) - { - IsReady = isReadyNow; - Log.Warning("VPN client disconnected"); + if (!IsReady && isReadyNow) + { + Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort.ToString() ?? "N/A"); + } + else if (IsReady && !isReadyNow) + { + Log.Warning("VPN client disconnected"); - if (OptionsAtStartup.Integration.Vpn.Required) - { - SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); - } + if (OptionsAtStartup.Integration.Vpn.Required) + { + SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); } } - finally + + IsReady = isReadyNow; + Status = status; + + StateMutator.SetValue(state => state with { - StateMutator.SetValue(state => state with + Vpn = new VpnState() { - Vpn = new VpnState() - { - IsReady = IsReady, - IsConnected = status.IsConnected, - PublicIPAddress = status.PublicIPAddress, - Location = status.Location, - ForwardedPort = status.ForwardedPort, - }, - }); - - SyncRoot.Release(); - } + IsReady = IsReady, + IsConnected = status.IsConnected, + PublicIPAddress = status.PublicIPAddress, + Location = status.Location, + ForwardedPort = status.ForwardedPort, + }, + }); } catch (Exception ex) { - Log.Warning("Failed to communicate with VPN client: {Message}", ex.Message); + Log.Warning("VPN client status check failed: {Message}", ex.Message); } finally { -- cgit v1.2.3 From 96c5e799a576d063e541f0c4ee0cd76847d75290 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:44:08 -0600 Subject: add vpn exception to disconnect handling --- src/slskd/Application.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 93db9073..daed5d3f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -962,6 +962,11 @@ 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); -- cgit v1.2.3 From fb757c4d789390ae3c838be46c356cb70fdb6aa1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:44:27 -0600 Subject: add a flag to the watchdog state to indicate that it is awaiting vpn --- src/slskd/Core/State.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index f9a3bf97..cd742348 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -91,7 +91,8 @@ 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 -- cgit v1.2.3 From 6d9101e57714e67d0e628f4e03c1a87b9b336f33 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:45:06 -0600 Subject: add flag to indicate when watchdog is awaiting vpn --- src/slskd/Core/ConnectionWatchdog.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 0cf30484..6250a0ba 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -83,6 +83,11 @@ namespace slskd /// public bool IsAttemptingConnection => SyncRoot.CurrentCount == 0; + /// + /// Gets a value indicating whether the watchdog is waiting for the VPN client to connect. + /// + public bool IsAwaitingVpn { get; private set; } + private ISoulseekClient Client { get; } private VPNService VPN { get; } private bool Disposed { get; set; } @@ -193,6 +198,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 }, }); @@ -218,8 +224,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 @@ -243,10 +247,12 @@ namespace slskd if (OptionsAtStartup.Integration.Vpn.Required && !VPN.IsReady) { - Log.Debug("AttemptConnection aborted; VPN is not yet ready (status: {Status})", VPN.Status); + IsAwaitingVpn = true; return; } + IsAwaitingVpn = false; + CancellationTokenSource = new CancellationTokenSource(); if (attempts > 0) -- cgit v1.2.3 From 02a3a82cb2d14bc43102aea56437bab4a5d588b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:45:19 -0600 Subject: start and stop vpn polling --- src/slskd/Core/ConnectionWatchdog.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 6250a0ba..2dd2f791 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -115,6 +115,11 @@ namespace slskd /// This should be called at application startup. public virtual void Start() { + if (OptionsAtStartup.Integration.Vpn.Enabled) + { + VPN.StartPolling(); + } + WatchdogTimer.Enabled = true; UpdateApplicationState(); @@ -147,6 +152,13 @@ namespace slskd /// This should be called when the application is reasonably certain that the connection is connected. public virtual void Stop(bool abortReconnect = false) { + // if the VPN is required, we have to keep polling in the background so we can disconnect if it drops + // this is a belt-and-suspenders effort to ensure maximum protection in case someone doesn't have a kill switch + if (OptionsAtStartup.Integration.Vpn.Required) + { + VPN.StopPolling(); + } + // stop the timer first to avoid having it start the connection process again when the cts is cancelled WatchdogTimer.Enabled = false; UpdateApplicationState(); -- cgit v1.2.3 From 0f14c33d3d1682e235b6fe29a8bfe555e48a339f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:46:11 -0600 Subject: add polling interval --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 7 +++++++ 2 files changed, 8 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 25fb4760..4f8cd157 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -235,6 +235,7 @@ # enabled: false # required: false # wait for the VPN to connect before connecting to Soulseek # port_forwarding: false +# polling_interval: 2500 # gluetun: # url: http://localhost:8000 # auth: apikey diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 85d1491c..565cbd4d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2327,6 +2327,13 @@ namespace slskd /// public bool PortForwarding { get; init; } = false; + /// + /// Gets the rate at which to poll the configured VPN client for status updates, in milliseconds. + /// + [Range(500, int.MaxValue)] + [RequiresRestart] + public int PollingInterval { get; init; } = 2500; + /// /// Gets Gluetun options. /// -- cgit v1.2.3 From 1aff04b696f30ffbca057a20f68fbd71246d6fbb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:55:33 -0600 Subject: simplify logs --- src/slskd/Integrations/VPN/GluetunClient.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs index 28fef202..2d1588dd 100644 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ b/src/slskd/Integrations/VPN/GluetunClient.cs @@ -105,8 +105,8 @@ public class GluetunClient : IVPNClient } catch (Exception ex) { - Log.Warning("Failed to retrieve status from Gluetun: {Message}", ex.Message); - throw new VPNClientException($"Failed to retrieve status from Gluetun: {ex.Message}", ex); + Log.Debug("Failed to retrieve status from Gluetun: {Message}", ex.Message); + throw new VPNClientException(ex.Message, ex); } } @@ -116,7 +116,7 @@ public class GluetunClient : IVPNClient response.EnsureSuccessStatusCode(); var result = await response.Content.ReadFromJsonAsync() - ?? throw new Exception($"Failed to deserialize Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); + ?? throw new Exception($"Unexpected Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}"); return result; } -- cgit v1.2.3 From 102046851d3233c791b069cbe75ddbfbafe675cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 18:55:51 -0600 Subject: tweaking of status updates and logs --- src/slskd/Integrations/VPN/VPNService.cs | 41 ++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 179c5436..4938e817 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -43,7 +43,7 @@ public class VPNService : IDisposable if (OptionsAtStartup.Integration.Vpn.Enabled) { - Timer = new System.Timers.Timer(interval: 2500) + Timer = new System.Timers.Timer(interval: OptionsAtStartup.Integration.Vpn.PollingInterval) { AutoReset = true, }; @@ -55,7 +55,6 @@ public class VPNService : IDisposable if (!string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun.Url)) { Client = new GluetunClient(HttpClientFactory, OptionsMonitor); - Timer.Start(); Log.Information("VPN integration enabled using {Client}", typeof(GluetunClient).Name); return; @@ -79,6 +78,9 @@ public class VPNService : IDisposable private bool Disposed { get; set; } private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); + public void StartPolling() => Timer?.Start(); + public void StopPolling() => Timer?.Stop(); + public void Dispose() { Dispose(disposing: true); @@ -101,7 +103,7 @@ public class VPNService : IDisposable private async Task CheckConnection() { bool isReadyNow = false; - VPNStatus status = default; + VPNStatus status = new VPNStatus(); // one at a time! await TimerElapsedLock.WaitAsync(0); @@ -123,7 +125,7 @@ public class VPNService : IDisposable 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: {Message}", ex.Message); + Log.Warning("Failed to fetch status from VPN client {Client}: {Message}", Client.GetType().Name, ex.Message); } /* @@ -133,7 +135,7 @@ public class VPNService : IDisposable * update application state (via StateMutator) * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource */ - if (!status.IsConnected) + if (status is null || !status.IsConnected) { isReadyNow = false; } @@ -169,36 +171,45 @@ public class VPNService : IDisposable if (!IsReady && isReadyNow) { - Log.Information("VPN client connected and ready! IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort.ToString() ?? "N/A"); + string port = OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding ? status.ForwardedPort.ToString() : "N/A"; + Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort.ToString() ?? "N/A"); } else if (IsReady && !isReadyNow) { Log.Warning("VPN client disconnected"); + } + else if (!IsReady && !isReadyNow) + { + string port = OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding ? status.ForwardedPort.ToString() : "N/A"; + port = string.IsNullOrEmpty(port) ? "?" : port; - if (OptionsAtStartup.Integration.Vpn.Required) - { - SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); - } + 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; + if (OptionsAtStartup.Integration.Vpn.Required && !IsReady) + { + SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); + } + StateMutator.SetValue(state => state with { Vpn = new VpnState() { IsReady = IsReady, - IsConnected = status.IsConnected, - PublicIPAddress = status.PublicIPAddress, - Location = status.Location, - ForwardedPort = status.ForwardedPort, + IsConnected = Status?.IsConnected ?? false, + PublicIPAddress = status?.PublicIPAddress, + Location = status?.Location, + ForwardedPort = status?.ForwardedPort, }, }); } catch (Exception ex) { - Log.Warning("VPN client status check failed: {Message}", ex.Message); + Log.Warning(ex, "VPN client status check failed: {Message}", ex.Message); } finally { -- cgit v1.2.3 From 55376314db7972da453bbded6037f1e1db169a1f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 19:00:24 -0600 Subject: oops --- src/slskd/Core/ConnectionWatchdog.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 2dd2f791..7e0710a6 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -154,7 +154,7 @@ namespace slskd { // if the VPN is required, we have to keep polling in the background so we can disconnect if it drops // this is a belt-and-suspenders effort to ensure maximum protection in case someone doesn't have a kill switch - if (OptionsAtStartup.Integration.Vpn.Required) + if (!OptionsAtStartup.Integration.Vpn.Required) { VPN.StopPolling(); } -- cgit v1.2.3 From 2a9c370eed0b94f7773d2d4eca4887155b0835a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Feb 2026 19:00:39 -0600 Subject: log when vpn client polling starts and stops --- src/slskd/Integrations/VPN/VPNService.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 4938e817..dbe7d2c1 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -78,8 +78,23 @@ public class VPNService : IDisposable private bool Disposed { get; set; } private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); - public void StartPolling() => Timer?.Start(); - public void StopPolling() => Timer?.Stop(); + public void StartPolling() + { + if (Timer is not null && !Timer.Enabled) + { + Timer.Start(); + Log.Information("VPN client status polling enabled (interval: {Interval}ms)", Timer.Interval); + } + } + + public void StopPolling() + { + if (Timer is not null && Timer.Enabled) + { + Timer.Stop(); + Log.Information("VPN client status polling stopped"); + } + } public void Dispose() { -- cgit v1.2.3 From 09b42a04b36e324c0c1f1f20bd1c66e95217f19f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Feb 2026 11:34:14 -0600 Subject: docs --- config/slskd.example.yml | 4 +- src/slskd/Integrations/VPN/Clients/Gluetun.cs | 148 ++++++++++++++++++++++++++ src/slskd/Integrations/VPN/GluetunClient.cs | 148 -------------------------- src/slskd/Integrations/VPN/VPNService.cs | 37 ++++++- 4 files changed, 184 insertions(+), 153 deletions(-) create mode 100644 src/slskd/Integrations/VPN/Clients/Gluetun.cs delete mode 100644 src/slskd/Integrations/VPN/GluetunClient.cs (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 4f8cd157..9be02b85 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -238,10 +238,10 @@ # polling_interval: 2500 # gluetun: # url: http://localhost:8000 -# auth: apikey +# auth: apikey # or basic or none # api_key: # username: -# password: # +# password: # webhooks: # my_webhook: # on: diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs new file mode 100644 index 00000000..e9be123f --- /dev/null +++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs @@ -0,0 +1,148 @@ +// +// 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/. +// + +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; + +public enum GluetunClientAuthenticationMethod +{ + None, + Basic, + ApiKey, +} + +public class Gluetun : IVPNClient +{ + public Gluetun(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) + { + HttpClientFactory = httpClientFactory; + OptionsMonitor = optionsMonitor; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IHttpClientFactory HttpClientFactory { get; } + private IOptionsMonitor OptionsMonitor { get; } + private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; + + /// + /// Fetch the VPN connection status from the Gluetun control server. + /// + /// A value indicating whether the VPN is connected. + public async Task GetStatusAsync() + { + using var http = HttpClientFactory.CreateClient(); + + http.Timeout = TimeSpan.FromMilliseconds(1000); + + if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + { + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); + } + else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) + { + http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + } + else + { + // no auth + } + + try + { + var publicIp = await MakeRequest(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(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 MakeRequest(HttpClient http, string url) + { + using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync() + ?? 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/GluetunClient.cs b/src/slskd/Integrations/VPN/GluetunClient.cs deleted file mode 100644 index 2d1588dd..00000000 --- a/src/slskd/Integrations/VPN/GluetunClient.cs +++ /dev/null @@ -1,148 +0,0 @@ -// -// 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/. -// - -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; - -public enum GluetunClientAuthenticationMethod -{ - None, - Basic, - ApiKey, -} - -public class GluetunClient : IVPNClient -{ - public GluetunClient(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) - { - HttpClientFactory = httpClientFactory; - OptionsMonitor = optionsMonitor; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private IHttpClientFactory HttpClientFactory { get; } - private IOptionsMonitor OptionsMonitor { get; } - private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun; - - /// - /// Fetch the VPN connection status from the Gluetun control server. - /// - /// A value indicating whether the VPN is connected. - public async Task GetStatusAsync() - { - using var http = HttpClientFactory.CreateClient(); - - http.Timeout = TimeSpan.FromMilliseconds(1000); - - if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) - { - var creds = $"{Options.Username}:{Options.Password}".ToBase64(); - http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); - } - else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) - { - http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); - } - else - { - // no auth - } - - try - { - var publicIp = await MakeRequest(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(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 MakeRequest(HttpClient http, string url) - { - using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}"); - response.EnsureSuccessStatusCode(); - - var result = await response.Content.ReadFromJsonAsync() - ?? 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/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index dbe7d2c1..18003341 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -26,8 +26,19 @@ using System.Threading.Tasks; using Serilog; using Soulseek; +/// +/// VPN integration. +/// public class VPNService : IDisposable { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// public VPNService( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -54,9 +65,9 @@ public class VPNService : IDisposable // we can revisit this if/when we add other options besides gluetun if (!string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun.Url)) { - Client = new GluetunClient(HttpClientFactory, OptionsMonitor); + Client = new Gluetun(HttpClientFactory, OptionsMonitor); - Log.Information("VPN integration enabled using {Client}", typeof(GluetunClient).Name); + Log.Information("VPN integration enabled using {Client}", typeof(Gluetun).Name); return; } @@ -64,7 +75,15 @@ public class VPNService : IDisposable } } + /// + /// Gets a value indicating whether the configured VPN client is ready (connected, and if port forwarding + /// is configured, a port has been provided). + /// public bool IsReady { get; private set; } = false; + + /// + /// Gets the most recent VPN client status. + /// public VPNStatus Status { get; private set; } = new VPNStatus(); private ISoulseekClient SoulseekClient { get; } @@ -78,6 +97,9 @@ public class VPNService : IDisposable private bool Disposed { get; set; } private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1); + /// + /// Starts polling the configured VPN client for status updates. + /// public void StartPolling() { if (Timer is not null && !Timer.Enabled) @@ -87,6 +109,9 @@ public class VPNService : IDisposable } } + /// + /// Stops polling the configured VPN client for status updates. + /// public void StopPolling() { if (Timer is not null && Timer.Enabled) @@ -96,12 +121,19 @@ public class VPNService : IDisposable } } + /// + /// Disposes this instance. + /// public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } + /// + /// Disposes this instance. + /// + /// protected virtual void Dispose(bool disposing) { if (!Disposed) @@ -148,7 +180,6 @@ public class VPNService : IDisposable * update VPNService state * apply a configuration overlay to set the forwarded port (if there is one) * update application state (via StateMutator) - * if IsReady changed during this invocation, disposition the ReadyTaskCompletionSource */ if (status is null || !status.IsConnected) { -- cgit v1.2.3 From 357a49a8012ad9b8377103a51d4e939138f3ce01 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Feb 2026 12:07:50 -0600 Subject: simplify some things --- src/slskd/Integrations/VPN/VPNService.cs | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 18003341..2c42ff97 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -157,17 +157,12 @@ public class VPNService : IDisposable try { - /* - step one: fetch status from the VPN client - - this step performs I/O with the VPN client, so do it before obtaining the SyncRoot to avoid - unnecessary lock contention - */ Log.Verbose("Checking VPN status using {Client}", Client.GetType()); try { - status = await Client.GetStatusAsync(); + status = await Client.GetStatusAsync() + ?? throw new VPNClientException("VPN client returned an invalid response"); } catch (Exception ex) { @@ -175,17 +170,7 @@ public class VPNService : IDisposable Log.Warning("Failed to fetch status from VPN client {Client}: {Message}", Client.GetType().Name, ex.Message); } - /* - step two: - * update VPNService state - * apply a configuration overlay to set the forwarded port (if there is one) - * update application state (via StateMutator) - */ - if (status is null || !status.IsConnected) - { - isReadyNow = false; - } - else + if (status is not null && status.IsConnected) { if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) { @@ -234,7 +219,7 @@ public class VPNService : IDisposable } IsReady = isReadyNow; - Status = status; + Status = status ?? new VPNStatus(); if (OptionsAtStartup.Integration.Vpn.Required && !IsReady) { @@ -247,9 +232,9 @@ public class VPNService : IDisposable { IsReady = IsReady, IsConnected = Status?.IsConnected ?? false, - PublicIPAddress = status?.PublicIPAddress, - Location = status?.Location, - ForwardedPort = status?.ForwardedPort, + PublicIPAddress = Status?.PublicIPAddress, + Location = Status?.Location, + ForwardedPort = Status?.ForwardedPort, }, }); } -- cgit v1.2.3 From 29d7927982da0cc26484410ead30758f242b3dfc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Feb 2026 12:14:07 -0600 Subject: add Timeout option for gluetun --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 6 ++++++ src/slskd/Integrations/VPN/Clients/Gluetun.cs | 26 ++++++++++++++++++++++++-- 3 files changed, 31 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 9be02b85..dcf419c6 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -238,6 +238,7 @@ # polling_interval: 2500 # gluetun: # url: http://localhost:8000 +# timeout: 1000 # auth: apikey # or basic or none # api_key: # username: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 565cbd4d..08fb1166 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2360,6 +2360,12 @@ namespace slskd [NotNullOrWhiteSpace] public string Url { get; init; } + /// + /// Gets the timeout for HTTP requests to the Gluetun control server, in milliseconds. + /// + [Range(500, 10_000)] + public int Timeout { get; init; } = 1000; + /// /// Gets the Gluetun control server authentication method. /// diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs index e9be123f..8c134599 100644 --- a/src/slskd/Integrations/VPN/Clients/Gluetun.cs +++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -28,15 +28,37 @@ using System.Threading.Tasks; using Serilog; using static slskd.Options.IntegrationOptions.VpnOptions; +/// +/// Gluetun VPN client authentication methods. +/// public enum GluetunClientAuthenticationMethod { + /// + /// The Gluetun control server allows unauthenticated requests. + /// None, + + /// + /// The Glueton control server is configured to use HTTP Basic authentication; username and password are required. + /// Basic, + + /// + /// The Gluetun control server is configured to use API key authentication; apiKey is required. + /// ApiKey, } +/// +/// Gluetun VPN client. +/// public class Gluetun : IVPNClient { + /// + /// Initializes a new instance of the class. + /// + /// + /// public Gluetun(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor) { HttpClientFactory = httpClientFactory; @@ -56,7 +78,7 @@ public class Gluetun : IVPNClient { using var http = HttpClientFactory.CreateClient(); - http.Timeout = TimeSpan.FromMilliseconds(1000); + http.Timeout = TimeSpan.FromMilliseconds(Options.Timeout); if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) { -- cgit v1.2.3 From c3d69a12a52d2ca550aa2f7345fd6e0cc6c8a41d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Feb 2026 13:08:39 -0600 Subject: remove required option; if vpn is enabled it is required --- config/slskd.example.yml | 1 - src/slskd/Core/ConnectionWatchdog.cs | 9 +-------- src/slskd/Core/Options.cs | 6 ------ src/slskd/Integrations/VPN/VPNService.cs | 31 ++++++++++++++++++++++--------- 4 files changed, 23 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index dcf419c6..7e820d9f 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -233,7 +233,6 @@ # integration: # vpn: # enabled: false -# required: false # wait for the VPN to connect before connecting to Soulseek # port_forwarding: false # polling_interval: 2500 # gluetun: diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 7e0710a6..d2f7caa8 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -152,13 +152,6 @@ namespace slskd /// This should be called when the application is reasonably certain that the connection is connected. public virtual void Stop(bool abortReconnect = false) { - // if the VPN is required, we have to keep polling in the background so we can disconnect if it drops - // this is a belt-and-suspenders effort to ensure maximum protection in case someone doesn't have a kill switch - if (!OptionsAtStartup.Integration.Vpn.Required) - { - VPN.StopPolling(); - } - // stop the timer first to avoid having it start the connection process again when the cts is cancelled WatchdogTimer.Enabled = false; UpdateApplicationState(); @@ -257,7 +250,7 @@ namespace slskd return; } - if (OptionsAtStartup.Integration.Vpn.Required && !VPN.IsReady) + if (OptionsAtStartup.Integration.Vpn.Enabled && !VPN.IsReady) { IsAwaitingVpn = true; return; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 08fb1166..a0b5f954 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2316,12 +2316,6 @@ namespace slskd [RequiresRestart] public bool Enabled { get; init; } = false; - /// - /// Gets a value indicating whether a VPN connection is required before connecting to the Soulseek network. - /// - [RequiresRestart] - public bool Required { get; init; } = false; - /// /// Gets a value indicating whether the configured VPN supports port forwarding. /// diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs index 2c42ff97..bc3eb668 100644 --- a/src/slskd/Integrations/VPN/VPNService.cs +++ b/src/slskd/Integrations/VPN/VPNService.cs @@ -149,6 +149,7 @@ public class VPNService : IDisposable private async Task CheckConnection() { + var options = OptionsMonitor.CurrentValue.Integration.Vpn; bool isReadyNow = false; VPNStatus status = new VPNStatus(); @@ -172,7 +173,7 @@ public class VPNService : IDisposable if (status is not null && status.IsConnected) { - if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding) + if (options.PortForwarding) { if (status.ForwardedPort.HasValue) { @@ -202,8 +203,14 @@ public class VPNService : IDisposable if (!IsReady && isReadyNow) { - string port = OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding ? status.ForwardedPort.ToString() : "N/A"; - Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort.ToString() ?? "N/A"); + 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) { @@ -211,17 +218,23 @@ public class VPNService : IDisposable } else if (!IsReady && !isReadyNow) { - string port = OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding ? status.ForwardedPort.ToString() : "N/A"; - port = string.IsNullOrEmpty(port) ? "?" : port; - - string ip = status.PublicIPAddress == default ? "?" : status.PublicIPAddress.ToString(); - Log.Information("Waiting for VPN client; IP: {PublicIP}, Forwarded port: {Port}", ip, port); + 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 (OptionsAtStartup.Integration.Vpn.Required && !IsReady) + if (!IsReady) { SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected")); } -- cgit v1.2.3 From e187c78dbc9587cf70a4fdd51bc6056eac65d0c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Feb 2026 16:02:49 -0600 Subject: require gluetun url if enabled, auto negotiate auth --- src/slskd/Core/Options.cs | 68 +++++++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a0b5f954..cc4c367a 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2308,22 +2308,31 @@ namespace slskd /// /// VPN options. /// - public class VpnOptions + public class VpnOptions : IValidatableObject { /// /// Gets a value indicating whether the VPN integration is enabled. /// + [Argument(default, "vpn")] + [EnvironmentVariable("VPN")] + [Description("enable VPN integration")] [RequiresRestart] public bool Enabled { get; init; } = false; /// - /// Gets a value indicating whether the configured VPN supports port forwarding. + /// Gets a value indicating whether the configured VPN supports dynamic port forwarding. /// + [Argument(default, "vpn-port-forwarding")] + [EnvironmentVariable("VPN_PORT_FORWARDING")] + [Description("VPN supports dynamic port forwarding")] public bool PortForwarding { get; init; } = false; /// /// Gets the rate at which to poll the configured VPN client for status updates, in milliseconds. /// + [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; @@ -2334,10 +2343,19 @@ namespace slskd [Validate] public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions(); + public IEnumerable Validate(ValidationContext validationContext) + { + // as/if more VPN clients are added, update this logic to ensure that exactly one is configured + if (Enabled && string.IsNullOrWhiteSpace(Gluetun?.Url)) + { + yield return new ValidationResult("VPN is enabled but no client is configured"); + } + } + /// /// Gluetun options. /// - public class GluetunVpnOptions : IValidatableObject + public class GluetunVpnOptions { /// /// Gets the Gluetun integration version. @@ -2351,58 +2369,44 @@ namespace slskd /// /// Gets the fully qualified root URL for the Gluetun control server. /// + [Argument(default, "vpn-gluetun-url")] + [EnvironmentVariable("VPN_GLUETUN_URL")] + [Description("URL for gluetun control server")] [NotNullOrWhiteSpace] public string Url { get; init; } /// /// Gets the timeout for HTTP requests to the Gluetun control server, in milliseconds. /// + [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; - /// - /// Gets the Gluetun control server authentication method. - /// - [Enum(typeof(GluetunClientAuthenticationMethod), ignoreCase: true)] - public string Auth { get; init; } = GluetunClientAuthenticationMethod.None.ToString(); - /// /// Gets the username used for basic auth. /// + [Argument(default, "vpn-gluetun-username")] + [EnvironmentVariable("VPN_GLUETUN_USERNAME")] + [Description("username for gluetun control server")] public string Username { get; init; } /// /// Gets the password used for basic auth. /// + [Argument(default, "vpn-gluetun-password")] + [EnvironmentVariable("VPN_GLUETUN_PASSWORD")] + [Description("password for gluetun control server")] public string Password { get; init; } /// /// Gets the API key used for API key auth. /// + [Argument(default, "vpn-gluetun-api-key")] + [EnvironmentVariable("VPN_GLUETUN_API_KEY")] + [Description("API key for gluetun control server")] public string ApiKey { get; init; } - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (string.Equals(Auth, GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) - { - if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password)) - { - results.Add(new ValidationResult("Username and Password are required when using Basic auth")); - } - } - - if (string.Equals(Auth, GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) - { - if (string.IsNullOrWhiteSpace(ApiKey)) - { - results.Add(new ValidationResult("ApiKey is required when using ApiKey auth")); - } - } - - return results; - } } } -- cgit v1.2.3 From b11904bb36d0ae868b69773ac5efe44646da4116 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Feb 2026 16:03:15 -0600 Subject: negotiate gluetun auth from config --- src/slskd/Integrations/VPN/Clients/Gluetun.cs | 31 +++++---------------------- 1 file changed, 5 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs index 8c134599..d22c15f7 100644 --- a/src/slskd/Integrations/VPN/Clients/Gluetun.cs +++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs @@ -28,27 +28,6 @@ using System.Threading.Tasks; using Serilog; using static slskd.Options.IntegrationOptions.VpnOptions; -/// -/// Gluetun VPN client authentication methods. -/// -public enum GluetunClientAuthenticationMethod -{ - /// - /// The Gluetun control server allows unauthenticated requests. - /// - None, - - /// - /// The Glueton control server is configured to use HTTP Basic authentication; username and password are required. - /// - Basic, - - /// - /// The Gluetun control server is configured to use API key authentication; apiKey is required. - /// - ApiKey, -} - /// /// Gluetun VPN client. /// @@ -80,14 +59,14 @@ public class Gluetun : IVPNClient http.Timeout = TimeSpan.FromMilliseconds(Options.Timeout); - if (Options.Auth.Equals(GluetunClientAuthenticationMethod.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrWhiteSpace(Options.ApiKey)) { - var creds = $"{Options.Username}:{Options.Password}".ToBase64(); - http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); + http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); } - else if (Options.Auth.Equals(GluetunClientAuthenticationMethod.ApiKey.ToString(), StringComparison.OrdinalIgnoreCase)) + else if (!string.IsNullOrWhiteSpace(Options.Username)) { - http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey); + var creds = $"{Options.Username}:{Options.Password}".ToBase64(); + http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}"); } else { -- cgit v1.2.3 From 022461e8bc1acce57b338da1ce7f74da183d143a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Feb 2026 17:47:17 -0600 Subject: validate gluetun url --- src/slskd/Core/Options.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cc4c367a..644fb885 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2345,10 +2345,19 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { - // as/if more VPN clients are added, update this logic to ensure that exactly one is configured - if (Enabled && string.IsNullOrWhiteSpace(Gluetun?.Url)) + if (Enabled) { - yield return new ValidationResult("VPN is enabled but no client is configured"); + // 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'"); + } } } @@ -2372,7 +2381,6 @@ namespace slskd [Argument(default, "vpn-gluetun-url")] [EnvironmentVariable("VPN_GLUETUN_URL")] [Description("URL for gluetun control server")] - [NotNullOrWhiteSpace] public string Url { get; init; } /// -- cgit v1.2.3