//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ 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;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Serilog;
using static slskd.Options.IntegrationsOptions.VpnOptions;
///
/// Gluetun VPN client.
///
public class Gluetun : IVPNClient
{
///
/// Initializes a new instance of the class.
///
///
///
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.Integrations.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(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(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.Integrations.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; }
}
}