about summary refs log tree commit diff
path: root/LibMatrix/Services/HomeserverResolverService.cs
blob: 4d3bc462e8e0a4068a5a6539b9dd1ec867b0ef93 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System.Text.Json;
using LibMatrix.Extensions;
using Microsoft.Extensions.Logging;

namespace LibMatrix.Services;

public class HomeserverResolverService {
    private readonly MatrixHttpClient _httpClient = new();
    private readonly ILogger<HomeserverResolverService> _logger;

    private static readonly Dictionary<string, string> _wellKnownCache = new();
    private static readonly Dictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();

    public HomeserverResolverService(ILogger<HomeserverResolverService> logger) {
        _logger = logger;
    }

    public async Task<string> ResolveHomeserverFromWellKnown(string homeserver) {
        var res = await _resolveHomeserverFromWellKnown(homeserver);
        if (!res.StartsWith("http")) res = "https://" + res;
        if (res.EndsWith(":443")) res = res.Substring(0, res.Length - 4);
        return res;
    }

    private async Task<string> _resolveHomeserverFromWellKnown(string homeserver) {
        if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
        SemaphoreSlim sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1));
        await sem.WaitAsync();
        if (_wellKnownCache.ContainsKey(homeserver)) {
            sem.Release();
            return _wellKnownCache[homeserver];
        }

        string? result = null;
        _logger.LogInformation($"Attempting to resolve homeserver: {homeserver}");
        result ??= await _tryResolveFromClientWellknown(homeserver);
        result ??= await _tryResolveFromServerWellknown(homeserver);
        result ??= await _tryCheckIfDomainHasHomeserver(homeserver);

        if (result is not null) {
            _logger.LogInformation($"Resolved homeserver: {homeserver} -> {result}");
            _wellKnownCache[homeserver] = result;
            sem.Release();
            return result;
        }

        throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?");
    }

    private async Task<string?> _tryResolveFromClientWellknown(string homeserver) {
        if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/client")) {
            var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/client");
            var hs = resp.GetProperty("m.homeserver").GetProperty("base_url").GetString();
            return hs;
        }

        _logger.LogInformation("No client well-known...");
        return null;
    }

    private async Task<string?> _tryResolveFromServerWellknown(string homeserver) {
        if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/server")) {
            var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
            var hs = resp.GetProperty("m.server").GetString();
            return hs;
        }

        _logger.LogInformation("No server well-known...");
        return null;
    }

    private async Task<string?> _tryCheckIfDomainHasHomeserver(string homeserver) {
        _logger.LogInformation($"Checking if {homeserver} hosts a homeserver...");
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
            return homeserver;
        _logger.LogInformation("No homeserver on shortname...");
        return null;
    }

    private async Task<string?> _tryCheckIfSubDomainHasHomeserver(string homeserver, string subdomain) {
        homeserver = homeserver.Replace("https://", $"https://{subdomain}.");
        return await _tryCheckIfDomainHasHomeserver(homeserver);
    }
}