summaryrefslogtreecommitdiffstats
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientHandshake.cs
blob: 7fef628c793aa97a8eed6a01e62ac4cd34c4b7d3 (plain)
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
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;

namespace GodotTools.IdeMessaging
{
    public class ClientHandshake : IHandshake
    {
        private static readonly string ClientHandshakeBase = $"{Peer.ClientHandshakeName},Version={Peer.ProtocolVersionMajor}.{Peer.ProtocolVersionMinor}.{Peer.ProtocolVersionRevision}";
        private static readonly string ServerHandshakePattern = $@"{Regex.Escape(Peer.ServerHandshakeName)},Version=([0-9]+)\.([0-9]+)\.([0-9]+),([_a-zA-Z][_a-zA-Z0-9]{{0,63}})";

        public string GetHandshakeLine(string identity) => $"{ClientHandshakeBase},{identity}";

        public bool IsValidPeerHandshake(string handshake, [NotNullWhen(true)] out string? identity, ILogger logger)
        {
            identity = null;

            var match = Regex.Match(handshake, ServerHandshakePattern);

            if (!match.Success)
                return false;

            if (!uint.TryParse(match.Groups[1].Value, out uint serverMajor) || Peer.ProtocolVersionMajor != serverMajor)
            {
                logger.LogDebug("Incompatible major version: " + match.Groups[1].Value);
                return false;
            }

            if (!uint.TryParse(match.Groups[2].Value, out uint serverMinor) || Peer.ProtocolVersionMinor < serverMinor)
            {
                logger.LogDebug("Incompatible minor version: " + match.Groups[2].Value);
                return false;
            }

            if (!uint.TryParse(match.Groups[3].Value, out uint _)) // Revision
            {
                logger.LogDebug("Incompatible revision build: " + match.Groups[3].Value);
                return false;
            }

            identity = match.Groups[4].Value;

            return true;
        }
    }
}