diff --git a/programs/dtchat/irc_adapter.c b/programs/dtchat/irc_adapter.c index 264b6f8a..1f7f6b44 100644 --- a/programs/dtchat/irc_adapter.c +++ b/programs/dtchat/irc_adapter.c @@ -45,10 +45,50 @@ static int cap_done; static int sasl_offered; static int sasl_requested; static int sasl_done; +static int tags_offered; +static int tags_requested; +static int have_message_tags; static char capbuf[1024]; static long long now_ms(void); +/* is NAME a token in a space separated CAP list? */ +static int +cap_has(const char *list, const char *name) +{ + size_t n = strlen(name); + const char *p = list; + + while (p != NULL && *p != '\0') { + while (*p == ' ') + p++; + if (strncmp(p, name, n) == 0 && + (p[n] == '\0' || p[n] == ' ')) + return 1; + p = strchr(p, ' '); + } + return 0; +} + +/* the value of KEY in an IRCv3 tag string ("a=b;+typing=active") */ +static const char * +tag_value(const char *tags, const char *key) +{ + size_t n = strlen(key); + const char *p = tags; + + if (p == NULL) + return NULL; + while (p != NULL && *p != '\0') { + while (*p == ';') + p++; + if (strncmp(p, key, n) == 0 && p[n] == '=') + return p + n + 1; + p = strchr(p, ';'); + } + return NULL; +} + #ifdef HAVE_LIBTLS static struct tls *tls_ctx; #endif @@ -519,6 +559,9 @@ handshake(int fd) sasl_offered = 0; sasl_requested = 0; sasl_done = 0; + tags_offered = 0; + tags_requested = 0; + have_message_tags = 0; capbuf[0] = '\0'; (void)send_all(fd, "CAP LS 302\r\n"); if (password[0] != '\0') { @@ -1024,9 +1067,37 @@ handle_line(int fd, const char *line) handle_mode(ch, &msg); } - } else if (strcmp(msg.command, "PRIVMSG") == 0 || + } else if (strcmp(msg.command, "TAGMSG") == 0 || + strcmp(msg.command, "PRIVMSG") == 0 || strcmp(msg.command, "NOTICE") == 0) { const char *target = msg.nparams > 0 ? msg.params[0] : NULL; + const char *typing = tag_value(msg.tags, "+typing"); + + if (typing != NULL) { + char who[64]; + char conv[128]; + DcJson *json; + + prefix_nick(msg.prefix, who, sizeof(who)); + if (target != NULL && *target == '#') + snprintf(conv, sizeof(conv), "%s", target); + else + snprintf(conv, sizeof(conv), "%s", who); + json = dc_json_new_object(); + (void)dc_json_object_set(json, "type", + dc_json_new_string("typing")); + (void)dc_json_object_set(json, "conv", + dc_json_new_string(conv)); + (void)dc_json_object_set(json, "on", + dc_json_new_bool(strcmp(typing, "active") == 0)); + (void)dc_json_object_set(json, "who", + dc_json_new_string(who)); + send_json(json); + } + if (strcmp(msg.command, "TAGMSG") == 0) { + dc_irc_message_free(&msg); + return; + } const char *text = msg.trailing != NULL ? msg.trailing : ""; char from[64]; char conv[128]; @@ -1096,11 +1167,31 @@ handle_line(int fd, const char *line) } if (!(msg.nparams > 2 && strcmp(msg.params[2], "*") == 0)) { - sasl_offered = strstr(capbuf, "sasl") != NULL; + char req[128] = "CAP REQ :"; + size_t used = strlen(req); + int any = 0; + + sasl_offered = cap_has(capbuf, "sasl"); + tags_offered = cap_has(capbuf, + "message-tags"); if (password[0] != '\0' && sasl_offered) { - (void)send_all(fd, - "CAP REQ :sasl\r\n"); + snprintf(req + used, + sizeof(req) - used, "sasl"); + used = strlen(req); sasl_requested = 1; + any = 1; + } + if (tags_offered) { + snprintf(req + used, + sizeof(req) - used, + "%smessage-tags", + any ? " " : ""); + tags_requested = 1; + any = 1; + } + if (any) { + (void)send_all(fd, req); + (void)send_all(fd, "\r\n"); } else { (void)send_all(fd, "CAP END\r\n"); @@ -1108,10 +1199,18 @@ handle_line(int fd, const char *line) } } } else if (strcmp(sub, "ACK") == 0) { + if (msg.trailing != NULL && + strstr(msg.trailing, "message-tags") != NULL) + have_message_tags = 1; if (sasl_requested && msg.trailing != NULL && - strstr(msg.trailing, "sasl") != NULL) + strstr(msg.trailing, "sasl") != NULL) { (void)send_all(fd, "AUTHENTICATE PLAIN\r\n"); + } else if (!sasl_requested) { + (void)send_all(fd, "CAP END\r\n"); + cap_done = 1; + } } else if (strcmp(sub, "NAK") == 0) { + have_message_tags = 0; (void)send_all(fd, "CAP END\r\n"); cap_done = 1; } @@ -1267,6 +1366,20 @@ read_stdin(DcFrameBuf *frame, int *sockp) } (void)n; } + } else if (strcmp(type, "typing") == 0) { + const char *conv = dc_json_string( + dc_json_get(cmd, "conv")); + int on = dc_json_bool(dc_json_get(cmd, "on")); + + if (*sockp >= 0 && have_message_tags && + conv != NULL && *conv != '\0') { + char line[300]; + + snprintf(line, sizeof(line), + "@+typing=%s TAGMSG %s\r\n", + on ? "active" : "paused", conv); + queue_line(line); + } } dc_json_free(cmd); } diff --git a/tests/irc_typing.py b/tests/irc_typing.py new file mode 100755 index 00000000..f0ba7d38 --- /dev/null +++ b/tests/irc_typing.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""tests/irc_typing.py -- IRCv3 typing tags (T3.4/T4.3). + +usage: tests/irc_typing.py [path-to-dtchat-irc] + +The server offers message-tags, acknowledges the request, sends two TAGMSG +lines with +typing from alice, and records the adapter's own TAGMSG lines +for a typing command. +""" +import json +import queue +import socket +import subprocess +import sys +import threading +import time + +ADAPTER = sys.argv[1] if len(sys.argv) > 1 else \ + "build/mcde-host/programs/dtchat/dtchat-irc" +failures = [] +outgoing = [] +cap_req = [] + + +def check(cond, what): + print(("ok " if cond else "FAIL ") + what, flush=True) + if not cond: + failures.append(what) + + +srv = socket.socket() +srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +srv.bind(("127.0.0.1", 0)) +srv.listen(1) +port = srv.getsockname()[1] +online_sent = threading.Event() +done = threading.Event() + + +def server(): + conn, _ = srv.accept() + conn.settimeout(0.2) + buf = b"" + + def wait_line(marker=None, timeout=6): + nonlocal buf + deadline = time.time() + timeout + while time.time() < deadline: + if marker is None and b"\r\n" in buf: + line, buf = buf.split(b"\r\n", 1) + return line.decode("utf-8", "replace") + if marker is not None and marker in buf: + return marker.decode() + try: + chunk = conn.recv(4096) + except socket.timeout: + continue + if not chunk: + return None + buf += chunk + return None + + wait_line() + conn.sendall(b":srv CAP * LS :sasl message-tags\r\n") + line = wait_line(b"CAP REQ") + # wait_line returns the marker only; look at the whole line around it + cap_req.append(buf is not None and + b"message-tags" in buf.split(b"CAP REQ", 1)[1][:80]) + conn.sendall(b":srv CAP tester ACK :message-tags\r\n") + wait_line(b"CAP END") + wait_line(b"USER ") + conn.sendall(b":srv 001 tester :Welcome\r\n") + # the channel join may follow; answer the JOIN + line = wait_line() + if line is not None and "JOIN" in line: + conn.sendall(b":tester!t@h JOIN #cde\r\n") + conn.sendall(b"@+typing=active :alice!a@h TAGMSG #cde\r\n") + conn.sendall(b"@+typing=paused :alice!a@h TAGMSG #cde\r\n") + online_sent.set() + + deadline = time.time() + 6 + while time.time() < deadline: + try: + chunk = conn.recv(4096) + except socket.timeout: + continue + if not chunk: + break + buf += chunk + while b"\r\n" in buf: + line, buf = buf.split(b"\r\n", 1) + text = line.decode("utf-8", "replace") + if "TAGMSG" in text: + outgoing.append(text) + if len(outgoing) >= 2: + done.set() + conn.close() + + +threading.Thread(target=server, daemon=True).start() +proc = subprocess.Popen([ADAPTER, "--stdio"], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True) +q = queue.Queue() + + +def reader(): + for line in proc.stdout: + line = line.strip() + if line: + q.put(json.loads(line)) + + +threading.Thread(target=reader, daemon=True).start() + + +def send(o): + proc.stdin.write(json.dumps(o) + "\n") + proc.stdin.flush() + + +def ev(t=5.0): + try: + return q.get(timeout=t) + except queue.Empty: + return None + + +hello = ev() +check(hello is not None and hello.get("type") == "hello", "hello arrives") +send({"type": "configure", "account": "t", + "settings": {"host": "127.0.0.1", "port": port, "tls": False, + "nick": "tester", "channels": "#cde"}, + "secrets": {}}) +send({"type": "connect"}) + +online = False +typing = [] +deadline = time.time() + 8 +while time.time() < deadline: + e = ev(1.0) + if e is None: + if online and len(typing) >= 2: + break + continue + if e.get("type") == "state" and e.get("state") == "online": + online = True + elif e.get("type") == "typing": + typing.append(e) + if len(typing) >= 2: + break +check(online, "online") +check(cap_req and cap_req[0], "the adapter asked for message-tags") +check(any(t.get("on") is True and t.get("who") == "alice" for t in typing), + "incoming typing active from alice") +check(any(t.get("on") is False and t.get("who") == "alice" for t in typing), + "incoming typing paused from alice") +check(any(t.get("conv") == "#cde" for t in typing), + "typing is filed under the channel") + +send({"type": "typing", "conv": "#cde", "on": True}) +send({"type": "typing", "conv": "#cde", "on": False}) +check(done.wait(6), "the adapter sent both TAGMSG lines") +check(any(l.startswith("@+typing=active TAGMSG #cde") for l in outgoing), + "outgoing +typing=active") +check(any(l.startswith("@+typing=paused TAGMSG #cde") for l in outgoing), + "outgoing +typing=paused") + +send({"type": "disconnect"}) +bye = None +deadline = time.time() + 3 +while time.time() < deadline: + e = ev(1.0) + if e and e.get("type") == "bye": + bye = e + break +check(bye is not None, "bye on disconnect") +try: + check(proc.wait(timeout=3) == 0, "exit 0") +except subprocess.TimeoutExpired: + proc.kill() + check(False, "exit 0") +check(proc.stderr.read().strip() == "", "no stderr output") + +if failures: + print("test_irc_typing: FAIL (%d)" % len(failures)) + sys.exit(1) +print("test_irc_typing: all ok")