99 lines
4.5 KiB
C#
99 lines
4.5 KiB
C#
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Net.Sockets;
|
|
|
|
namespace Ads.Desktop;
|
|
|
|
public sealed record RelayOptions(Uri BaseUri, string Origin, string Token)
|
|
{
|
|
public const string DefaultServer = "wss://ttstd.com/ads";
|
|
public const string DefaultOrigin = "175.178.213.60:443";
|
|
public override string ToString() => $"RelayOptions {{ BaseUri = {BaseUri}, Origin = {Origin}, Token = [REDACTED] }}";
|
|
|
|
public static Uri ParseBaseUri(string server)
|
|
{
|
|
if (!Uri.TryCreate(server.Trim(), UriKind.Absolute, out var uri) ||
|
|
uri.Scheme != "wss" || string.IsNullOrEmpty(uri.Host) ||
|
|
uri.Query.Length != 0 || uri.Fragment.Length != 0 || uri.UserInfo.Length != 0)
|
|
throw new InvalidOperationException("请输入有效的 WSS 中继地址,可以包含 /ads 路径。");
|
|
return uri;
|
|
}
|
|
|
|
public static RelayOptions Parse(string server, string origin, string token)
|
|
{
|
|
var uri = ParseBaseUri(server);
|
|
if (token.Length < 32 || token.Contains('\r') || token.Contains('\n'))
|
|
throw new InvalidOperationException("请导入有效的客户端令牌(至少 32 个字符)。");
|
|
origin = origin.Trim();
|
|
if (origin.Length > 0) ParseOrigin(origin);
|
|
return new RelayOptions(uri, origin, token);
|
|
}
|
|
|
|
public static DnsEndPoint ParseOrigin(string origin)
|
|
{
|
|
if (!Uri.TryCreate("tcp://" + origin, UriKind.Absolute, out var uri) ||
|
|
uri.Port is < 1 or > 65535 || string.IsNullOrEmpty(uri.Host) ||
|
|
uri.UserInfo.Length != 0 || uri.AbsolutePath != "/" ||
|
|
uri.Query.Length != 0 || uri.Fragment.Length != 0)
|
|
throw new InvalidOperationException("直连服务器请填写 IP或主机名:端口,例如 175.178.213.60:443;也可以留空。");
|
|
return new DnsEndPoint(uri.IdnHost.Trim('[', ']'), uri.Port);
|
|
}
|
|
|
|
public Uri DevicesUri => new UriBuilder(BaseUri)
|
|
{
|
|
Scheme = "https",
|
|
Port = BaseUri.Port > 0 ? BaseUri.Port : 443,
|
|
Path = BaseUri.AbsolutePath.TrimEnd('/') + "/v1/devices"
|
|
}.Uri;
|
|
}
|
|
|
|
public sealed record RelayDevice(string Id, bool Busy);
|
|
|
|
public static class RelayApi
|
|
{
|
|
public static HttpClient CreateClient(RelayOptions options)
|
|
{
|
|
var handler = new SocketsHttpHandler
|
|
{
|
|
AllowAutoRedirect = false,
|
|
UseProxy = false,
|
|
ConnectTimeout = TimeSpan.FromSeconds(8)
|
|
};
|
|
if (!string.IsNullOrWhiteSpace(options.Origin))
|
|
{
|
|
var origin = RelayOptions.ParseOrigin(options.Origin);
|
|
handler.ConnectCallback = async (_, cancellation) =>
|
|
{
|
|
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
|
|
try
|
|
{
|
|
await socket.ConnectAsync(origin, cancellation);
|
|
return new NetworkStream(socket, ownsSocket: true);
|
|
}
|
|
catch { socket.Dispose(); throw; }
|
|
};
|
|
}
|
|
// Only TCP resolution is overridden. HttpClient still supplies the URL's
|
|
// hostname for TLS SNI and normal certificate/hostname validation.
|
|
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(12) };
|
|
}
|
|
|
|
public static async Task<RelayDevice[]> GetDevicesAsync(RelayOptions options, CancellationToken cancellation = default)
|
|
{
|
|
using var http = CreateClient(options);
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, options.DevicesUri);
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.Token);
|
|
using var response = await http.SendAsync(request, cancellation);
|
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
|
throw new InvalidOperationException("客户端令牌无效,请导入 client.env,而不是 agent.env。");
|
|
if (!response.IsSuccessStatusCode)
|
|
throw new InvalidOperationException($"中继返回 HTTP {(int)response.StatusCode},请检查地址与服务状态。");
|
|
var devices = await response.Content.ReadFromJsonAsync<RelayDevice[]>(cancellationToken: cancellation) ?? [];
|
|
if (devices.Any(d => string.IsNullOrWhiteSpace(d.Id) || d.Id.Length > 128 ||
|
|
d.Id.Any(c => !char.IsAsciiLetterOrDigit(c) && c != '-' && c != '_' && c != '.')))
|
|
throw new InvalidOperationException("中继返回了无效的设备 ID。");
|
|
return devices.OrderBy(d => d.Id, StringComparer.Ordinal).ToArray();
|
|
}
|
|
}
|