about summary refs log tree commit diff
path: root/LibMatrix/Services
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-02-28 02:24:24 +0100
committerRory& <root@rory.gay>2025-02-28 02:24:39 +0100
commit49bb14a7f0906b6e88b7613ac1bc508d1709c06d (patch)
treee832dc149d7fc57cd649bdcec25a53fa02dd448c /LibMatrix/Services
parentHomeserverEmulator changes (diff)
downloadLibMatrix-49bb14a7f0906b6e88b7613ac1bc508d1709c06d.tar.xz
Well known resolver rewrite work
Diffstat (limited to 'LibMatrix/Services')
-rw-r--r--LibMatrix/Services/ServiceInstaller.cs7
-rw-r--r--LibMatrix/Services/WellKnownResolverService.cs173
-rw-r--r--LibMatrix/Services/WellKnownResolvers/ClientWellKnownResolver.cs53
-rw-r--r--LibMatrix/Services/WellKnownResolvers/SupportWellKnownResolver.cs54
4 files changed, 163 insertions, 124 deletions
diff --git a/LibMatrix/Services/ServiceInstaller.cs b/LibMatrix/Services/ServiceInstaller.cs

index 8b7e54b..ecc3f09 100644 --- a/LibMatrix/Services/ServiceInstaller.cs +++ b/LibMatrix/Services/ServiceInstaller.cs
@@ -1,5 +1,5 @@ +using LibMatrix.Services.WellKnownResolvers; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; namespace LibMatrix.Services; @@ -9,7 +9,10 @@ public static class ServiceInstaller { services.AddSingleton(config ?? new RoryLibMatrixConfiguration()); //Add services - services.AddSingleton<HomeserverResolverService>(sp => new HomeserverResolverService(sp.GetRequiredService<ILogger<HomeserverResolverService>>())); + services.AddSingleton<ClientWellKnownResolver>(); + services.AddSingleton<WellKnownResolverService>(); + // Legacy + services.AddSingleton<HomeserverResolverService>(); services.AddSingleton<HomeserverProviderService>(); return services; diff --git a/LibMatrix/Services/WellKnownResolverService.cs b/LibMatrix/Services/WellKnownResolverService.cs
index 0ba79b6..ab2660f 100644 --- a/LibMatrix/Services/WellKnownResolverService.cs +++ b/LibMatrix/Services/WellKnownResolverService.cs
@@ -3,6 +3,7 @@ using System.Text.Json.Serialization; using ArcaneLibs.Collections; using ArcaneLibs.Extensions; using LibMatrix.Extensions; +using LibMatrix.Services.WellKnownResolvers; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -11,11 +12,6 @@ namespace LibMatrix.Services; public class WellKnownResolverService { private readonly MatrixHttpClient _httpClient = new(); - private static readonly SemaphoreCache<ClientWellKnown> ClientWellKnownCache = new(); - private static readonly SemaphoreCache<ServerWellKnown> ServerWellKnownCache = new(); - // private static readonly SemaphoreCache<support> SupportWellKnownCache = new(); - // private static readonly SemaphoreCache<WellKnownRecords> WellKnownCache = new(); - private readonly ILogger<WellKnownResolverService> _logger; public WellKnownResolverService(ILogger<WellKnownResolverService> logger) { @@ -29,131 +25,64 @@ public class WellKnownResolverService { public async Task<WellKnownRecords> TryResolveWellKnownRecords(string homeserver) { WellKnownRecords records = new(); - records.ClientWellKnown = await ClientWellKnownCache.TryGetOrAdd(homeserver, async () => { - _logger.LogTrace($"Resolving client well-known: {homeserver}"); - ClientWellKnown? clientWellKnown = null; - // check if homeserver has a client well-known - try { - - var wk = await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client"); - } - catch { } - - // return clientWellKnown; - - _logger.LogInformation("No client well-known for {server}...", homeserver); - return null; - }); + _logger.LogDebug($"Resolving well-knowns for {homeserver}"); + return records; - } - - // public async Task<WellKnownUris> ResolveHomeserverFromWellKnown(string homeserver, bool enableClient = true, bool enableServer = true) { - // ArgumentNullException.ThrowIfNull(homeserver); - // - // return await WellKnownCache.GetOrAdd(homeserver, async () => { - // _logger.LogTrace($"Resolving homeserver well-knowns: {homeserver}"); - // var client = enableClient ? _tryResolveClientEndpoint(homeserver) : null; - // var server = enableServer ? _tryResolveServerEndpoint(homeserver) : null; - // - // var res = new WellKnownUris(); - // - // if (client != null) - // res.Client = (await client)?.TrimEnd('/') ?? throw new Exception($"Could not resolve client URL for {homeserver}."); - // - // if (server != null) - // res.Server = (await server)?.TrimEnd('/') ?? throw new Exception($"Could not resolve server URL for {homeserver}."); - // - // _logger.LogInformation("Resolved well-knowns for {hs}: {json}", homeserver, res.ToJson(indent: false)); - // return res; - // }); - // } - // - // private async Task<string?> _tryResolveClientEndpoint(string homeserver) { - // ArgumentNullException.ThrowIfNull(homeserver); - // _logger.LogTrace("Resolving client well-known: {homeserver}", homeserver); - // ClientWellKnown? clientWellKnown = null; - // // check if homeserver has a client well-known - // if (homeserver.StartsWith("https://")) { - // clientWellKnown = await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client"); - // } - // else if (homeserver.StartsWith("http://")) { - // clientWellKnown = await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client"); - // } - // else { - // clientWellKnown ??= await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"https://{homeserver}/.well-known/matrix/client"); - // clientWellKnown ??= await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"http://{homeserver}/.well-known/matrix/client"); - // - // if (clientWellKnown is null) { - // if (await _httpClient.CheckSuccessStatus($"https://{homeserver}/_matrix/client/versions")) - // return $"https://{homeserver}"; - // if (await _httpClient.CheckSuccessStatus($"http://{homeserver}/_matrix/client/versions")) - // return $"http://{homeserver}"; - // } - // } - // - // if (!string.IsNullOrWhiteSpace(clientWellKnown?.Homeserver.BaseUrl)) - // return clientWellKnown.Homeserver.BaseUrl; - // - // _logger.LogInformation("No client well-known for {server}...", homeserver); - // return null; - // } - // - // private async Task<string?> _tryResolveServerEndpoint(string homeserver) { - // // TODO: implement SRV delegation via DoH: https://developers.google.com/speed/public-dns/docs/doh/json - // ArgumentNullException.ThrowIfNull(homeserver); - // _logger.LogTrace($"Resolving server well-known: {homeserver}"); - // ServerWellKnown? serverWellKnown = null; - // // check if homeserver has a server well-known - // if (homeserver.StartsWith("https://")) { - // serverWellKnown = await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server"); - // } - // else if (homeserver.StartsWith("http://")) { - // serverWellKnown = await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server"); - // } - // else { - // serverWellKnown ??= await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"https://{homeserver}/.well-known/matrix/server"); - // serverWellKnown ??= await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"http://{homeserver}/.well-known/matrix/server"); - // } - // - // _logger.LogInformation("Server well-known for {hs}: {json}", homeserver, serverWellKnown?.ToJson() ?? "null"); - // - // if (!string.IsNullOrWhiteSpace(serverWellKnown?.Homeserver)) { - // var resolved = serverWellKnown.Homeserver; - // if (resolved.StartsWith("https://") || resolved.StartsWith("http://")) - // return resolved; - // if (await _httpClient.CheckSuccessStatus($"https://{resolved}/_matrix/federation/v1/version")) - // return $"https://{resolved}"; - // if (await _httpClient.CheckSuccessStatus($"http://{resolved}/_matrix/federation/v1/version")) - // return $"http://{resolved}"; - // _logger.LogWarning("Server well-known points to invalid server: {resolved}", resolved); - // } - // - // // fallback: most servers host C2S and S2S on the same domain - // var clientUrl = await _tryResolveClientEndpoint(homeserver); - // if (clientUrl is not null && await _httpClient.CheckSuccessStatus($"{clientUrl}/_matrix/federation/v1/version")) - // return clientUrl; - // - // _logger.LogInformation("No server well-known for {server}...", homeserver); - // return null; - // } + } - public class ClientWellKnown { - [JsonPropertyName("m.homeserver")] - public WellKnownHomeserver Homeserver { get; set; } - public class WellKnownHomeserver { - [JsonPropertyName("base_url")] - public string BaseUrl { get; set; } - } - } public class ServerWellKnown { [JsonPropertyName("m.server")] - public string Homeserver { get; set; } + public required string Homeserver { get; set; } } - + public class WellKnownRecords { - public ClientWellKnown? ClientWellKnown { get; set; } + public ClientWellKnownResolver.ClientWellKnown? ClientWellKnown { get; set; } public ServerWellKnown? ServerWellKnown { get; set; } + public SupportWellKnownResolver.SupportWellKnown? SupportWellKnown { get; set; } + + /// <summary> + /// Reports the source of the client well-known data. + /// </summary> + public WellKnownSource? ClientWellKnownSource { get; set; } + + /// <summary> + /// Reports the source of the server well-known data. + /// </summary> + public WellKnownSource? ServerWellKnownSource { get; set; } + + /// <summary> + /// Reports the source of the support well-known data. + /// </summary> + public WellKnownSource? SupportWellKnownSource { get; set; } + } + + public struct WellKnownResolutionResult<T> { + public WellKnownResolverService.WellKnownSource Source { get; set; } + public T WellKnown { get; set; } + public List<WellKnownResolverService.WellKnownResolutionWarning> Warnings { get; set; } + } + + public enum WellKnownSource { + None, + Https, + Dns, + Http, + ManualCheck, + Search + } + + public struct WellKnownResolutionWarning { + public WellKnownResolutionWarningType Type { get; set; } + public string Message { get; set; } + public Exception? Exception { get; set; } + + public enum WellKnownResolutionWarningType { + None, + Exception, + InvalidResponse, + Timeout + } } } \ No newline at end of file diff --git a/LibMatrix/Services/WellKnownResolvers/ClientWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolvers/ClientWellKnownResolver.cs new file mode 100644
index 0000000..d4d0166 --- /dev/null +++ b/LibMatrix/Services/WellKnownResolvers/ClientWellKnownResolver.cs
@@ -0,0 +1,53 @@ +using System.Text.Json.Serialization; +using ArcaneLibs.Collections; +using LibMatrix.Extensions; +using Microsoft.Extensions.Logging; + +namespace LibMatrix.Services.WellKnownResolvers; + +public class ClientWellKnownResolver(ILogger<ClientWellKnownResolver> logger) { + private static readonly SemaphoreCache<WellKnownResolutionResult> ClientWellKnownCache = new() { + StoreNulls = false + }; + private static readonly MatrixHttpClient HttpClient = new(); + + public Task<WellKnownResolutionResult> TryResolveClientWellKnown(string homeserver) { + return ClientWellKnownCache.TryGetOrAdd(homeserver, async () => { + logger.LogTrace($"Resolving client well-known: {homeserver}"); + if ((await TryGetClientWellKnownFromHttps(homeserver)) is { } clientWellKnown) + return new() { + Source = WellKnownResolverService.WellKnownSource.Https, + WellKnown = clientWellKnown + }; + + return default!; + }); + } + + private async Task<ClientWellKnown?> TryGetClientWellKnownFromHttps(string homeserver) { + try { + return await HttpClient.TryGetFromJsonAsync<ClientWellKnown>($"https://{homeserver}/.well-known/matrix/client"); + } + catch { + return null; + } + } + + + + public class ClientWellKnown { + [JsonPropertyName("m.homeserver")] + public required WellKnownHomeserver Homeserver { get; set; } + + public class WellKnownHomeserver { + [JsonPropertyName("base_url")] + public required string BaseUrl { get; set; } + } + } + + public struct WellKnownResolutionResult { + public WellKnownResolverService.WellKnownSource Source { get; set; } + public ClientWellKnown WellKnown { get; set; } + public List<WellKnownResolverService.WellKnownResolutionWarning> Warnings { get; set; } + } +} \ No newline at end of file diff --git a/LibMatrix/Services/WellKnownResolvers/SupportWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolvers/SupportWellKnownResolver.cs new file mode 100644
index 0000000..1d7567a --- /dev/null +++ b/LibMatrix/Services/WellKnownResolvers/SupportWellKnownResolver.cs
@@ -0,0 +1,54 @@ +using System.Text.Json.Serialization; +using ArcaneLibs.Collections; +using LibMatrix.Extensions; +using Microsoft.Extensions.Logging; + +namespace LibMatrix.Services.WellKnownResolvers; + +public class SupportWellKnownResolver(ILogger<SupportWellKnownResolver> logger) { + private static readonly SemaphoreCache<WellKnownResolverService.WellKnownResolutionResult<SupportWellKnown>> ClientWellKnownCache = new() { + StoreNulls = false + }; + + private static readonly MatrixHttpClient HttpClient = new(); + + public Task<WellKnownResolverService.WellKnownResolutionResult<SupportWellKnown>> TryResolveClientWellKnown(string homeserver) { + return ClientWellKnownCache.TryGetOrAdd(homeserver, async () => { + logger.LogTrace($"Resolving client well-known: {homeserver}"); + if ((await TryGetClientWellKnownFromHttps(homeserver)) is { } clientWellKnown) + return new() { + Source = WellKnownResolverService.WellKnownSource.Https, + WellKnown = clientWellKnown + }; + return default!; + }); + } + + private async Task<SupportWellKnown?> TryGetClientWellKnownFromHttps(string homeserver) { + try { + return await HttpClient.TryGetFromJsonAsync<SupportWellKnown>($"https://{homeserver}/.well-known/matrix/support"); + } + catch { + return null; + } + } + + public struct SupportWellKnown { + [JsonPropertyName("contacts")] + public List<WellKnownContact>? Contacts { get; set; } + + [JsonPropertyName("support_page")] + public Uri? SupportPage { get; set; } + + public class WellKnownContact { + [JsonPropertyName("email_address")] + public string? EmailAddress { get; set; } + + [JsonPropertyName("matrix_id")] + public string? MatrixId { get; set; } + + [JsonPropertyName("role")] + public required string Role { get; set; } + } + } +} \ No newline at end of file