aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Integrations
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-02-14 17:55:58 -0600
committerGitHub <noreply@github.com>2026-02-14 17:55:58 -0600
commit7f0312a1ea28e611a126ddb07117aa1072f1c36a (patch)
treec78c5372d6bb23464480a509e3aee1789b5b78a1 /src/slskd/Integrations
parent8d30845f59d693aa6909c9fe8291493422dc10aa (diff)
parent9f3b7217dd4554482c904becc101a4cf3074544e (diff)
downloadslskd-7f0312a1ea28e611a126ddb07117aa1072f1c36a.tar.gz
Merge pull request #1632 from slskd/gluetun
Add VPN integration and gluetun client
Diffstat (limited to 'src/slskd/Integrations')
-rw-r--r--src/slskd/Integrations/VPN/Clients/Gluetun.cs149
-rw-r--r--src/slskd/Integrations/VPN/IVPNClient.cs32
-rw-r--r--src/slskd/Integrations/VPN/VPNService.cs263
-rw-r--r--src/slskd/Integrations/VPN/VPNStatus.cs28
4 files changed, 472 insertions, 0 deletions
diff --git a/src/slskd/Integrations/VPN/Clients/Gluetun.cs b/src/slskd/Integrations/VPN/Clients/Gluetun.cs
new file mode 100644
index 00000000..d22c15f7
--- /dev/null
+++ b/src/slskd/Integrations/VPN/Clients/Gluetun.cs
@@ -0,0 +1,149 @@
+// <copyright file="Gluetun.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using Microsoft.Extensions.Options;
+
+namespace slskd.Integrations.VPN;
+
+using System;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+using Serilog;
+using static slskd.Options.IntegrationOptions.VpnOptions;
+
+/// <summary>
+/// Gluetun VPN client.
+/// </summary>
+public class Gluetun : IVPNClient
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Gluetun"/> class.
+ /// </summary>
+ /// <param name="httpClientFactory"></param>
+ /// <param name="optionsMonitor"></param>
+ public Gluetun(IHttpClientFactory httpClientFactory, IOptionsMonitor<Options> optionsMonitor)
+ {
+ HttpClientFactory = httpClientFactory;
+ OptionsMonitor = optionsMonitor;
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Gluetun>();
+ private IHttpClientFactory HttpClientFactory { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private GluetunVpnOptions Options => OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun;
+
+ /// <summary>
+ /// Fetch the VPN connection status from the Gluetun control server.
+ /// </summary>
+ /// <returns>A value indicating whether the VPN is connected.</returns>
+ public async Task<VPNStatus> GetStatusAsync()
+ {
+ using var http = HttpClientFactory.CreateClient();
+
+ http.Timeout = TimeSpan.FromMilliseconds(Options.Timeout);
+
+ if (!string.IsNullOrWhiteSpace(Options.ApiKey))
+ {
+ http.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", Options.ApiKey);
+ }
+ else if (!string.IsNullOrWhiteSpace(Options.Username))
+ {
+ var creds = $"{Options.Username}:{Options.Password}".ToBase64();
+ http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {creds}");
+ }
+ else
+ {
+ // no auth
+ }
+
+ try
+ {
+ var publicIp = await MakeRequest<GluetunPublicIpResponse>(http, "/v1/publicip/ip");
+
+ // per the gluetun docs/discussions, the public ip field will be an empty string if the VPN isn't up
+ if (string.IsNullOrEmpty(publicIp.PublicIp))
+ {
+ return new VPNStatus { IsConnected = false };
+ }
+
+ int? port = null;
+
+ if (OptionsMonitor.CurrentValue.Integration.Vpn.PortForwarding)
+ {
+ port = (await MakeRequest<GluetunPortForwardResponse>(http, "/v1/portforward"))?.Port;
+
+ // port will be 0 if port forwarding isn't enabled or ready
+ if (port == 0)
+ {
+ port = null;
+ }
+ }
+
+ return new VPNStatus
+ {
+ IsConnected = true,
+ PublicIPAddress = IPAddress.Parse(publicIp.PublicIp),
+ Location = string.Join(", ", [publicIp.City, publicIp.Country]),
+ ForwardedPort = port,
+ };
+ }
+ catch (Exception ex)
+ {
+ Log.Debug("Failed to retrieve status from Gluetun: {Message}", ex.Message);
+ throw new VPNClientException(ex.Message, ex);
+ }
+ }
+
+ private async Task<T> MakeRequest<T>(HttpClient http, string url)
+ {
+ using var response = await http.GetAsync($"{Options.Url.TrimEnd('/')}{url}");
+ response.EnsureSuccessStatusCode();
+
+ var result = await response.Content.ReadFromJsonAsync<T>()
+ ?? throw new Exception($"Unexpected Gluetun response; expected: {nameof(T)}, got: {await response.Content.ReadAsStringAsync()}");
+
+ return result;
+ }
+
+ private class GluetunStatusResponse
+ {
+ public string Status { get; init; }
+ }
+
+ private class GluetunPortForwardResponse
+ {
+ public int? Port { get; init; }
+ }
+
+ private class GluetunPublicIpResponse
+ {
+ [JsonPropertyName("public_ip")]
+ public string PublicIp { get; init; }
+ public string Region { get; init; }
+ public string Country { get; init; }
+ public string City { get; init; }
+ public string Location { get; init; }
+ public string Organization { get; init; }
+
+ [JsonPropertyName("postal_code")]
+ public string PostalCode { get; init; }
+ public string Timezone { get; init; }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Integrations/VPN/IVPNClient.cs b/src/slskd/Integrations/VPN/IVPNClient.cs
new file mode 100644
index 00000000..0b4a872d
--- /dev/null
+++ b/src/slskd/Integrations/VPN/IVPNClient.cs
@@ -0,0 +1,32 @@
+// <copyright file="IVPNClient.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using System.Threading.Tasks;
+
+namespace slskd.Integrations.VPN;
+
+/// <summary>
+/// A lightweight interface for monitoring the status of a VPN provider.
+/// </summary>
+public interface IVPNClient
+{
+ /// <summary>
+ /// Fetch the VPN connection status from the provider.
+ /// </summary>
+ /// <returns>The current status.</returns>
+ public Task<VPNStatus> GetStatusAsync();
+} \ No newline at end of file
diff --git a/src/slskd/Integrations/VPN/VPNService.cs b/src/slskd/Integrations/VPN/VPNService.cs
new file mode 100644
index 00000000..bc3eb668
--- /dev/null
+++ b/src/slskd/Integrations/VPN/VPNService.cs
@@ -0,0 +1,263 @@
+// <copyright file="VPNService.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using Microsoft.Extensions.Options;
+
+namespace slskd.Integrations.VPN;
+
+using System;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+using Serilog;
+using Soulseek;
+
+/// <summary>
+/// VPN integration.
+/// </summary>
+public class VPNService : IDisposable
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VPNService"/> class.
+ /// </summary>
+ /// <param name="optionsAtStartup"></param>
+ /// <param name="optionsMonitor"></param>
+ /// <param name="stateMutator"></param>
+ /// <param name="soulseekClient"></param>
+ /// <param name="httpClientFactory"></param>
+ public VPNService(
+ OptionsAtStartup optionsAtStartup,
+ IOptionsMonitor<Options> optionsMonitor,
+ IStateMutator<State> stateMutator,
+ ISoulseekClient soulseekClient,
+ IHttpClientFactory httpClientFactory)
+ {
+ OptionsAtStartup = optionsAtStartup;
+ OptionsMonitor = optionsMonitor;
+ StateMutator = stateMutator;
+ SoulseekClient = soulseekClient;
+ HttpClientFactory = httpClientFactory;
+
+ if (OptionsAtStartup.Integration.Vpn.Enabled)
+ {
+ Timer = new System.Timers.Timer(interval: OptionsAtStartup.Integration.Vpn.PollingInterval)
+ {
+ AutoReset = true,
+ };
+
+ Timer.Elapsed += async (_, _) => await CheckConnection();
+
+ // detect VPN based on the configuration provided; this logic will determine the order
+ // we can revisit this if/when we add other options besides gluetun
+ if (!string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Integration.Vpn.Gluetun.Url))
+ {
+ Client = new Gluetun(HttpClientFactory, OptionsMonitor);
+
+ Log.Information("VPN integration enabled using {Client}", typeof(Gluetun).Name);
+ return;
+ }
+
+ Log.Error("VPN integration is enabled, but no VPN client has been configured");
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the configured VPN client is ready (connected, and if port forwarding
+ /// is configured, a port has been provided).
+ /// </summary>
+ public bool IsReady { get; private set; } = false;
+
+ /// <summary>
+ /// Gets the most recent VPN client status.
+ /// </summary>
+ public VPNStatus Status { get; private set; } = new VPNStatus();
+
+ private ISoulseekClient SoulseekClient { get; }
+ private IVPNClient Client { get; set; }
+ private System.Timers.Timer Timer { get; }
+ private IStateMutator<State> StateMutator { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<VPNService>();
+ private IHttpClientFactory HttpClientFactory { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
+ private bool Disposed { get; set; }
+ private SemaphoreSlim TimerElapsedLock { get; } = new SemaphoreSlim(1, 1);
+
+ /// <summary>
+ /// Starts polling the configured VPN client for status updates.
+ /// </summary>
+ public void StartPolling()
+ {
+ if (Timer is not null && !Timer.Enabled)
+ {
+ Timer.Start();
+ Log.Information("VPN client status polling enabled (interval: {Interval}ms)", Timer.Interval);
+ }
+ }
+
+ /// <summary>
+ /// Stops polling the configured VPN client for status updates.
+ /// </summary>
+ public void StopPolling()
+ {
+ if (Timer is not null && Timer.Enabled)
+ {
+ Timer.Stop();
+ Log.Information("VPN client status polling stopped");
+ }
+ }
+
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ /// <param name="disposing"></param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!Disposed)
+ {
+ if (disposing)
+ {
+ Timer.Dispose();
+ }
+
+ Disposed = true;
+ }
+ }
+
+ private async Task CheckConnection()
+ {
+ var options = OptionsMonitor.CurrentValue.Integration.Vpn;
+ bool isReadyNow = false;
+ VPNStatus status = new VPNStatus();
+
+ // one at a time!
+ await TimerElapsedLock.WaitAsync(0);
+
+ try
+ {
+ Log.Verbose("Checking VPN status using {Client}", Client.GetType());
+
+ try
+ {
+ status = await Client.GetStatusAsync()
+ ?? throw new VPNClientException("VPN client returned an invalid response");
+ }
+ catch (Exception ex)
+ {
+ // log, but don't throw. an exception here is treated as if the VPN is down; we have to assume it is
+ Log.Warning("Failed to fetch status from VPN client {Client}: {Message}", Client.GetType().Name, ex.Message);
+ }
+
+ if (status is not null && status.IsConnected)
+ {
+ if (options.PortForwarding)
+ {
+ if (status.ForwardedPort.HasValue)
+ {
+ isReadyNow = true;
+
+ var overlay = Program.ConfigurationOverlay ?? new OptionsOverlay();
+ overlay = overlay with { Soulseek = overlay.Soulseek ?? new OptionsOverlay.SoulseekOptionsPatch() };
+
+ // avoid incessant updates
+ if (overlay.Soulseek.ListenPort != status.ForwardedPort)
+ {
+ Program.ApplyConfigurationOverlay(overlay with
+ {
+ Soulseek = overlay.Soulseek with
+ {
+ ListenPort = status.ForwardedPort,
+ },
+ });
+ }
+ }
+ }
+ else
+ {
+ isReadyNow = true;
+ }
+ }
+
+ if (!IsReady && isReadyNow)
+ {
+ if (options.PortForwarding)
+ {
+ Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location}), Forwarded port: {Port}", status.PublicIPAddress, status.Location, status.ForwardedPort);
+ }
+ else
+ {
+ Log.Information("VPN client connected and ready. IP: {PublicIP} ({Location})", status.PublicIPAddress, status.Location);
+ }
+ }
+ else if (IsReady && !isReadyNow)
+ {
+ Log.Warning("VPN client disconnected");
+ }
+ else if (!IsReady && !isReadyNow)
+ {
+ if (!options.PortForwarding)
+ {
+ Log.Information("Waiting for VPN client; IP: ?");
+ }
+ else
+ {
+ // port could possibly come first, if the client allows the user to specify it
+ string port = status.ForwardedPort.HasValue ? status.ForwardedPort.ToString() : "?";
+ string ip = status.PublicIPAddress == default ? "?" : status.PublicIPAddress.ToString();
+ Log.Information("Waiting for VPN client; IP: {PublicIP}, Forwarded port: {Port}", ip, port);
+ }
+ }
+
+ IsReady = isReadyNow;
+ Status = status ?? new VPNStatus();
+
+ if (!IsReady)
+ {
+ SoulseekClient.Disconnect("VPN client disconnected", new VPNClientException("VPN client disconnected"));
+ }
+
+ StateMutator.SetValue(state => state with
+ {
+ Vpn = new VpnState()
+ {
+ IsReady = IsReady,
+ IsConnected = Status?.IsConnected ?? false,
+ PublicIPAddress = Status?.PublicIPAddress,
+ Location = Status?.Location,
+ ForwardedPort = Status?.ForwardedPort,
+ },
+ });
+ }
+ catch (Exception ex)
+ {
+ Log.Warning(ex, "VPN client status check failed: {Message}", ex.Message);
+ }
+ finally
+ {
+ TimerElapsedLock.Release();
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Integrations/VPN/VPNStatus.cs b/src/slskd/Integrations/VPN/VPNStatus.cs
new file mode 100644
index 00000000..c6e3d242
--- /dev/null
+++ b/src/slskd/Integrations/VPN/VPNStatus.cs
@@ -0,0 +1,28 @@
+// <copyright file="VPNStatus.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using System.Net;
+
+namespace slskd;
+
+public record VPNStatus
+{
+ public bool IsConnected { get; init; } = false;
+ public IPAddress PublicIPAddress { get; init; } = null;
+ public int? ForwardedPort { get; init; } = null;
+ public string Location { get; init; } = null;
+} \ No newline at end of file