IRC parsing, tokenization, and state handling in C#
1using System.Collections.Generic;
2using System.Linq;
3using System.Text.RegularExpressions;
4
5namespace IRCRobots
6{
7 public class ConnectionParams
8 {
9 public string Nickname { get; set; }
10 public string Host { get; set; }
11 public int Port { get; set; }
12 public bool UseTLS { get; set; }
13 public string? Username { get; set; } = null;
14 public string? Realname { get; set; } = null;
15 public string? Bindhost { get; set; } = null;
16 public string? Password { get; set; } = null;
17 public bool VerifyTLS { get; set; } = true;
18 public SASLParams? SASL { get; set; } = null;
19 public STSPolicy? STS { get; set; } = null;
20 public ResumePolicy? Resume { get; set; } = null;
21 public int Reconnect { get; set; } = 10; // seconds
22 public IEnumerable<string> AltNicknames { get; set; } = new List<string>();
23 public IEnumerable<string> Autojoin { get; set; } = new List<string>();
24
25 public static ConnectionParams FromHostString(string nickName, string hostString)
26 {
27 var result = new ConnectionParams {Nickname = nickName};
28 var ipv6host = Regex.Matches(hostString, @"\[([a-fA-F0-9:]+)\]").SingleOrDefault();
29 var portString = "";
30 if (ipv6host is { Index: 0 })
31 {
32 result.Host = ipv6host.Groups[0].Value;
33 portString = hostString[(ipv6host.Index + ipv6host.Length)..];
34 }
35 else
36 {
37 var s = hostString.Split(':', 2);
38 result.Host = s[0];
39 portString = s[1];
40 }
41
42 if (string.IsNullOrWhiteSpace(portString))
43 {
44 portString = "6667";
45 result.UseTLS = false;
46 }
47 else
48 {
49 result.UseTLS = portString.StartsWith('+') || portString.StartsWith('~');
50 result.VerifyTLS = portString.StartsWith('~');
51 portString = portString[1..];
52 }
53
54 result.Port = int.Parse(portString);
55
56 return result;
57 }
58 }
59}