//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
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;
///
/// VPN integration.
///
public class VPNService : IDisposable
{
///
/// Initializes a new instance of the class.
///
///
///
///
///
///
public VPNService(
OptionsAtStartup optionsAtStartup,
IOptionsMonitor optionsMonitor,
IStateMutator stateMutator,
ISoulseekClient soulseekClient,
IHttpClientFactory httpClientFactory)
{
OptionsAtStartup = optionsAtStartup;
OptionsMonitor = optionsMonitor;
StateMutator = stateMutator;
SoulseekClient = soulseekClient;
HttpClientFactory = httpClientFactory;
if (OptionsAtStartup.Integrations.Vpn.Enabled)
{
Timer = new System.Timers.Timer(interval: OptionsAtStartup.Integrations.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.Integrations.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");
}
}
///
/// 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; }
private IVPNClient Client { get; set; }
private System.Timers.Timer Timer { get; }
private IStateMutator StateMutator { get; }
private ILogger Log { get; } = Serilog.Log.ForContext();
private IHttpClientFactory HttpClientFactory { get; }
private IOptionsMonitor OptionsMonitor { get; }
private OptionsAtStartup OptionsAtStartup { get; }
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)
{
Timer.Start();
Log.Information("VPN client status polling enabled (interval: {Interval}ms)", Timer.Interval);
}
}
///
/// Stops polling the configured VPN client for status updates.
///
public void StopPolling()
{
if (Timer is not null && Timer.Enabled)
{
Timer.Stop();
Log.Information("VPN client status polling stopped");
}
}
///
/// Disposes this instance.
///
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
/// Disposes this instance.
///
///
protected virtual void Dispose(bool disposing)
{
if (!Disposed)
{
if (disposing)
{
Timer?.Dispose();
}
Disposed = true;
}
}
private async Task CheckConnection()
{
if (Client is null)
{
throw new VPNClientException("VPN client not properly initialized; something went seriously wrong! Please report to GitHub.");
}
var options = OptionsMonitor.CurrentValue.Integrations.Vpn;
bool isReadyNow = false;
VPNStatus status = new VPNStatus();
// one at a time!
if (!await TimerElapsedLock.WaitAsync(0))
{
return;
}
try
{
Log.Verbose("Checking VPN status using {Client}", Client.GetType());
try
{
status = await Client.GetStatusAsync();
if (status is null)
{
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 the VPN client returned null, swap it for a default instance to prevent null refs
status ??= new VPNStatus();
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();
}
}
}