191 lines
9.1 KiB
C#
191 lines
9.1 KiB
C#
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal sealed class VpnApiClient : IDisposable
|
|
{
|
|
internal const string BaseAddress = "https://vpn.example.invalid/";
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
};
|
|
private HttpClient _httpClient;
|
|
|
|
internal VpnApiClient()
|
|
{ _httpClient = CreateTransport(); }
|
|
|
|
internal void ResetTransport() => Interlocked.Exchange(ref _httpClient, CreateTransport()).Dispose();
|
|
|
|
private static HttpClient CreateTransport()
|
|
{
|
|
// The management API is domestic infrastructure and must remain
|
|
// reachable before a VPN node is started. Do not inherit a stale
|
|
// Clash/system proxy (for example 127.0.0.1:7890), otherwise login,
|
|
// profile loading and update checks can all fail before connection.
|
|
var handler = PlatformBootstrapTransport.CreateHandler();
|
|
var client = new HttpClient(handler)
|
|
{
|
|
BaseAddress = new Uri(BaseAddress),
|
|
Timeout = TimeSpan.FromSeconds(20),
|
|
};
|
|
client.DefaultRequestHeaders.UserAgent.ParseAdd($"UCVL-VPNPlus/{Application.ProductVersion} Windows-x64");
|
|
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
return client;
|
|
}
|
|
|
|
internal async Task<LoginResponse> LoginAsync(string login, string password, CancellationToken cancellationToken)
|
|
{
|
|
var body = new LoginRequest
|
|
{
|
|
Login = login,
|
|
Password = password,
|
|
DeviceId = AppPaths.GetOrCreateDeviceId(),
|
|
DeviceName = Environment.MachineName,
|
|
AppVersion = Application.ProductVersion,
|
|
};
|
|
using var request = new HttpRequestMessage(HttpMethod.Post, "api/v1/client/login/")
|
|
{
|
|
Content = JsonContent(body),
|
|
};
|
|
return await SendAsync<LoginResponse>(request, cancellationToken);
|
|
}
|
|
|
|
internal async Task<Profile> GetProfileAsync(string token, CancellationToken cancellationToken)
|
|
{
|
|
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/profile/", token);
|
|
var envelope = await SendAsync<ProfileEnvelope>(request, cancellationToken);
|
|
return envelope.Profile;
|
|
}
|
|
|
|
internal async Task<ClientUpdateInfo> GetUpdateAsync(CancellationToken cancellationToken)
|
|
{
|
|
return await GitReleaseUpdater.GetLatestAsync(cancellationToken);
|
|
}
|
|
|
|
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken)
|
|
{
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(3));
|
|
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/node-traffic/", token);
|
|
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 32 * 1024);
|
|
}
|
|
|
|
internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null)
|
|
{
|
|
var url = $"api/v1/client/config/?node={Uri.EscapeDataString(nodeSlug)}&route={Uri.EscapeDataString(routeMode)}";
|
|
if (nodeSlug == "auto") url += "&new_connection=1";
|
|
if (excluded is not null) url += "&exclude=" + Uri.EscapeDataString(string.Join(",", excluded));
|
|
using var request = AuthorizedRequest(HttpMethod.Get, url, token);
|
|
return await SendAsync<ConfigResponse>(request, cancellationToken);
|
|
}
|
|
|
|
internal async Task LogoutAsync(string token, CancellationToken cancellationToken)
|
|
{
|
|
using var request = AuthorizedRequest(HttpMethod.Post, "api/v1/client/logout/", token);
|
|
request.Content = new ByteArrayContent([]);
|
|
await SendAsync<JsonElement>(request, cancellationToken);
|
|
}
|
|
|
|
internal async Task<ConfigResponse> GetPrivateAuxiliaryConfigAsync(string token, PrivateAuxiliaryNode node,
|
|
string routeMode, CancellationToken cancellationToken)
|
|
{
|
|
var url = $"api/v1/client/private-auxiliary/config/?node={Uri.EscapeDataString(node.Slug)}&route={Uri.EscapeDataString(routeMode)}&endpoint={Uri.EscapeDataString(node.EndpointHost)}";
|
|
using var request = AuthorizedRequest(HttpMethod.Get, url, token);
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(5));
|
|
ConfigResponse response;
|
|
try { response = await SendAsync<ConfigResponse>(request, deadline.Token); }
|
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
|
{ throw new TimeoutException("私有辅助节点配置请求超时。"); }
|
|
PrivateAuxiliaryRouting.ValidateConfig(node, response, routeMode);
|
|
return response;
|
|
}
|
|
|
|
internal async Task ReportObservationAsync(string token, LearningObservation observation, CancellationToken cancellationToken)
|
|
{
|
|
using var request = AuthorizedRequest(HttpMethod.Post, "api/v1/client/observations/", token);
|
|
request.Content = JsonContent(new ObservationEnvelope { Observations = [observation] });
|
|
await SendAsync<JsonElement>(request, cancellationToken);
|
|
}
|
|
|
|
internal async Task<RoutingManifest> GetRoutingRulesAsync(string token, CancellationToken cancellationToken)
|
|
{
|
|
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/routing-rules/", token);
|
|
return await SendAsync<RoutingManifest>(request, cancellationToken);
|
|
}
|
|
|
|
internal async Task AcknowledgeRoutingAsync(string token, string revision, bool cached, CancellationToken cancellationToken)
|
|
{
|
|
using var request = AuthorizedRequest(HttpMethod.Post, "api/v1/client/routing-rules/", token);
|
|
request.Content = JsonContent(new { revision, status = cached ? "cached" : "failed", client_version = Application.ProductVersion });
|
|
await SendAsync<JsonElement>(request, cancellationToken);
|
|
}
|
|
|
|
private static StringContent JsonContent<T>(T value) =>
|
|
new(JsonSerializer.Serialize(value, JsonOptions), Encoding.UTF8, "application/json");
|
|
|
|
private static HttpRequestMessage AuthorizedRequest(HttpMethod method, string url, string token)
|
|
{
|
|
var request = new HttpRequestMessage(method, url);
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
|
return request;
|
|
}
|
|
|
|
private async Task<T> SendAsync<T>(HttpRequestMessage request, CancellationToken cancellationToken, int? maximumBodyBytes = null)
|
|
{
|
|
var uri = request.RequestUri ?? throw new InvalidOperationException("管理接口地址为空。");
|
|
PlatformBootstrapTransport.ValidateRequest(uri.IsAbsoluteUri ? uri : new Uri(new Uri(BaseAddress), uri), request.Headers.Host);
|
|
// ResponseHeadersRead otherwise leaves the response body outside the
|
|
// HttpClient timeout. One deadline covers connect, TLS and body reads.
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(20));
|
|
cancellationToken = deadline.Token;
|
|
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
|
string payload;
|
|
if (maximumBodyBytes is { } maximum)
|
|
{
|
|
if (response.Content.Headers.ContentLength > maximum) throw new IOException("监控响应过大。");
|
|
using var body = new MemoryStream();
|
|
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
|
var buffer = new byte[4096];
|
|
int read;
|
|
while ((read = await stream.ReadAsync(buffer, cancellationToken)) != 0)
|
|
{
|
|
if (body.Length + read > maximum) throw new IOException("监控响应过大。");
|
|
body.Write(buffer, 0, read);
|
|
}
|
|
payload = new UTF8Encoding(false, true).GetString(body.ToArray());
|
|
}
|
|
else payload = await response.Content.ReadAsStringAsync(cancellationToken);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
string message;
|
|
try
|
|
{
|
|
message = JsonSerializer.Deserialize<ErrorResponse>(payload, JsonOptions)?.Error ?? "服务暂时不可用。";
|
|
}
|
|
catch
|
|
{
|
|
message = response.StatusCode == System.Net.HttpStatusCode.TooManyRequests
|
|
? "登录尝试过多,请稍后再试。"
|
|
: "服务暂时不可用。";
|
|
}
|
|
throw new ApiException((int)response.StatusCode, message);
|
|
}
|
|
try
|
|
{
|
|
return JsonSerializer.Deserialize<T>(payload, JsonOptions)
|
|
?? throw new JsonException("响应内容为空");
|
|
}
|
|
catch (JsonException exception)
|
|
{
|
|
throw new ApiException((int)response.StatusCode, $"服务返回了无法识别的数据:{exception.Message}");
|
|
}
|
|
}
|
|
|
|
public void Dispose() => _httpClient.Dispose();
|
|
}
|