dtchat: add XMPP MUC rooms (T4.4)

join sends a presence to room/nick with the http://jabber.org/protocol/muc <x/>; the room's self-presence is answered with a conversation event (kind group, title room), other occupants are reported as presence events with buddy=room/nick, groupchat messages are filed under the room with the sender's nick in from, and part sends an unavailable presence. The nick is the JID's local part. The hello caps gain muc. tests/xmpp_muc.py drives a minimal server through stream, SASL PLAIN, bind, join (checks the MUC element), self-presence, alice's presence, a groupchat message and the part; all 17 checks pass, exit 0, no stderr. UI wiring for adapter accounts is still open, as is the live test.
This commit is contained in:
lotherk committed 2026-11-17 10:02:33 +00:00
1 parent a2c4a0e4c4
commit f0e8c668d6
2 files changed
+413 -1

No files matched your search

+173 -1
View File
@@ -49,6 +49,21 @@ typedef struct {
static Contact contacts[MAX_CONTACTS];
static int ncontacts;
/* the MUC rooms we joined, so a self-presence can be answered with the
* conversation event once */
#define MAX_ROOMS 16
typedef struct {
char room[256];
int announced;
} Room;
static Room rooms[MAX_ROOMS];
static int nrooms;
static void muc_nick(char *out, size_t outlen);
static Room *room_find(const char *room);
static void send_conversation(const char *conv, const char *kind,
const char *title);
static void
send_json(DcJson *json)
{
@@ -107,7 +122,7 @@ send_hello(void)
DcJson *caps = dc_json_new_array();
DcJson *settings = dc_json_new_array();
static const char *const capnames[] = { "text", "roster", "presence",
"typing" };
"typing", "muc" };
for (size_t i = 0; i < sizeof(capnames) / sizeof(capnames[0]); i++)
(void)dc_json_array_append(caps,
@@ -248,6 +263,32 @@ presence_cb(xmpp_conn_t *c, xmpp_stanza_t *stanza, void *userdata)
if (from == NULL)
return 1;
bare_jid(from, conv, sizeof(conv));
/* a room's presence: our own announces the conversation, occupants
* are shown as room/nick */
if (strchr(from, '/') != NULL) {
Room *room = room_find(conv);
if (room != NULL) {
const char *res = strchr(from, '/') + 1;
char nick[64];
muc_nick(nick, sizeof(nick));
if (type == NULL) {
if (!room->announced &&
strcmp(res, nick) == 0) {
room->announced = 1;
send_conversation(conv, "group", conv);
} else if (strcmp(res, nick) != 0) {
send_presence_event(from, "online", NULL,
NULL);
}
} else if (strcmp(type, "unavailable") == 0 &&
strcmp(res, nick) != 0) {
send_presence_event(from, "offline", NULL, NULL);
}
return 1;
}
}
contact = contact_get(conv);
if (type == NULL) {
child_text(stanza, "show", show, sizeof(show));
@@ -352,6 +393,91 @@ enable_carbons(void)
xmpp_stanza_release(iq);
}
/* the nickname in a room: the local part of the JID */
static void
muc_nick(char *out, size_t outlen)
{
size_t i = 0;
while (jid[i] != '\0' && jid[i] != '@' && i + 1 < outlen) {
out[i] = jid[i];
i++;
}
out[i] = '\0';
if (i == 0)
snprintf(out, outlen, "dtchat");
}
static Room *
room_find(const char *room)
{
int i;
for (i = 0; i < nrooms; i++)
if (strcmp(rooms[i].room, room) == 0)
return &rooms[i];
return NULL;
}
static Room *
room_add(const char *room)
{
Room *r = room_find(room);
if (r != NULL || nrooms == MAX_ROOMS)
return r;
r = &rooms[nrooms++];
memset(r, 0, sizeof(*r));
snprintf(r->room, sizeof(r->room), "%s", room);
return r;
}
static void
send_conversation(const char *conv, const char *kind, const char *title)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("conversation"));
(void)dc_json_object_set(json, "conv", dc_json_new_string(conv));
(void)dc_json_object_set(json, "kind", dc_json_new_string(kind));
(void)dc_json_object_set(json, "title",
dc_json_new_string(title != NULL ? title : conv));
send_json(json);
}
static void
room_presence(const char *room, const char *type)
{
xmpp_stanza_t *presence;
char nick[64];
char full[512];
if (ctx == NULL || conn == NULL || room == NULL)
return;
muc_nick(nick, sizeof(nick));
snprintf(full, sizeof(full), "%s/%s", room, nick);
presence = xmpp_stanza_new(ctx);
if (presence == NULL)
return;
xmpp_stanza_set_name(presence, "presence");
xmpp_stanza_set_attribute(presence, "to", full);
if (type != NULL)
xmpp_stanza_set_attribute(presence, "type", type);
if (type == NULL) {
xmpp_stanza_t *x = xmpp_stanza_new(ctx);
if (x != NULL) {
xmpp_stanza_set_name(x, "x");
xmpp_stanza_set_ns(x, "http://jabber.org/protocol/muc");
xmpp_stanza_add_child(presence, x);
xmpp_stanza_release(x);
}
}
xmpp_send(conn, presence);
xmpp_stanza_release(presence);
}
static void
send_presence_available(void)
{
@@ -413,6 +539,37 @@ message_cb(xmpp_conn_t *c, xmpp_stanza_t *stanza, void *userdata)
to = xmpp_stanza_get_attribute(stanza, "to");
if (from == NULL)
return 1;
if (xmpp_stanza_get_attribute(stanza, "type") != NULL &&
strcmp(xmpp_stanza_get_attribute(stanza, "type"), "groupchat") == 0) {
xmpp_stanza_t *gbody;
char room[256];
const char *sender = "?";
char *gtext;
bare_jid(from, room, sizeof(room));
if (strchr(from, '/') != NULL)
sender = strchr(from, '/') + 1;
gbody = xmpp_stanza_get_child_by_name(stanza, "body");
if (gbody == NULL)
return 1;
gtext = xmpp_stanza_get_text(gbody);
if (gtext == NULL)
return 1;
json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("message"));
(void)dc_json_object_set(json, "conv",
dc_json_new_string(room));
(void)dc_json_object_set(json, "from",
dc_json_new_string(sender));
(void)dc_json_object_set(json, "kind",
dc_json_new_string("text"));
(void)dc_json_object_set(json, "text",
dc_json_new_string(gtext));
send_json(json);
xmpp_free(ctx, gtext);
return 1;
}
/* XEP-0085: a message with a chat state instead of a body */
state = xmpp_stanza_get_child_by_name_and_ns(stanza, "composing",
chatstate_ns);
@@ -598,6 +755,21 @@ handle_command(DcJson *cmd)
return;
}
(void)connect_account();
} else if (strcmp(type, "join") == 0) {
const char *conv = dc_json_string(dc_json_get(cmd, "conv"));
if (conn == NULL || !online || conv == NULL)
return;
if (room_add(conv) != NULL)
room_presence(conv, NULL);
} else if (strcmp(type, "part") == 0) {
const char *conv = dc_json_string(dc_json_get(cmd, "conv"));
Room *room = conv != NULL ? room_find(conv) : NULL;
if (conn == NULL || conv == NULL || room == NULL)
return;
room_presence(conv, "unavailable");
room->announced = 0;
} 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"));
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""tests/xmpp_muc.py -- the XMPP adapter in a MUC room (T4.4).
usage: tests/xmpp_muc.py [path-to-dtchat-xmpp]
A minimal XMPP server (no TLS, DTCHAT_XMPP_NO_TLS) answers the stream, SASL
PLAIN and the resource bind, then expects the join presence for
room@conference.example.org/<nick> with the MUC <x/> element. It sends the
self-presence back (the adapter must answer with a conversation event), the
presence of alice and a groupchat message from her, and afterwards waits for
the unavailable presence of a part.
"""
import base64
import json
import queue
import re
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-xmpp"
ROOM = "room@conference.example.org"
failures = []
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]
join_seen = []
part_seen = []
done = threading.Event()
def server():
conn, _ = srv.accept()
conn.settimeout(8)
buf = b""
def fill_until(marker):
nonlocal buf
while marker not in buf:
chunk = conn.recv(4096)
if not chunk:
return False
buf += chunk
return True
def take(marker):
nonlocal buf
i = buf.index(marker) + len(marker)
out, buf = buf[:i], buf[i:]
return out
if not fill_until(b"<stream:stream"):
return
take(b"<stream:stream")
conn.sendall(b"<?xml version='1.0'?><stream:stream "
b"xmlns='jabber:client' "
b"xmlns:stream='http://etherx.jabber.org/streams' "
b"id='s1' from='example.org' version='1.0'>")
conn.sendall(b"<stream:features><mechanisms "
b"xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"
b"<mechanism>PLAIN</mechanism></mechanisms>"
b"</stream:features>")
if not fill_until(b"</auth>"):
return
take(b"</auth>")
conn.sendall(b"<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>")
buf = b""
if not fill_until(b"<stream:stream"):
return
take(b"<stream:stream")
conn.sendall(b"<?xml version='1.0'?><stream:stream "
b"xmlns='jabber:client' "
b"xmlns:stream='http://etherx.jabber.org/streams' "
b"id='s2' from='example.org' version='1.0'>")
conn.sendall(b"<stream:features><bind "
b"xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>"
b"</stream:features>")
if not fill_until(b"</bind></iq>"):
return
iq = take(b"</bind></iq>")
m = re.search(rb"<iq[^>]*id=['\"]([^'\"]+)", iq)
iqid = m.group(1).decode() if m else "1"
conn.sendall(("<iq type='result' id='%s'><bind "
"xmlns='urn:ietf:params:xml:ns:xmpp-bind'>"
"<jid>tester@example.org/dtchat</jid></bind></iq>" %
iqid).encode())
# the join: <presence to='room@conference.example.org/tester'> with <x/>
data = buf
deadline = time.time() + 5
want = ROOM.encode() + b"/tester"
while (want not in data or
b"http://jabber.org/protocol/muc" not in data) and \
time.time() < deadline:
chunk = conn.recv(4096)
if not chunk:
break
data += chunk
join_seen.append(want in data and
b"http://jabber.org/protocol/muc" in data)
buf = b""
conn.sendall(("<presence from='%s/tester'><x "
"xmlns='http://jabber.org/protocol/muc#user'>"
"<item affiliation='member' role='participant'/>"
"</x></presence>" % ROOM).encode())
conn.sendall(("<presence from='%s/alice'><show>away</show>"
"</presence>" % ROOM).encode())
conn.sendall(("<message from='%s/alice' to='tester@example.org/dtchat' "
"type='groupchat'><body>hello room</body></message>" %
ROOM).encode())
# the part: an unavailable presence to the same room/nick
try:
deadline = time.time() + 5
data = buf
while want not in data and time.time() < deadline:
chunk = conn.recv(4096)
if not chunk:
break
data += chunk
part_seen.append(b"type='unavailable'" in data or
b'type="unavailable"' in data)
except socket.timeout:
pass
done.set()
time.sleep(0.3)
try:
conn.sendall(b"</stream:stream>")
conn.close()
except OSError:
pass
threading.Thread(target=server, daemon=True).start()
proc = subprocess.Popen([ADAPTER, "--stdio"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, env={"PATH": "/usr/bin:/bin",
"DTCHAT_XMPP_NO_TLS": "1"})
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 and hello.get("type") == "hello", "hello arrives")
check("muc" in (hello or {}).get("caps", []), "the adapter says it does MUC")
send({"type": "configure", "account": "t",
"settings": {"jid": "tester@example.org", "resource": "dtchat",
"host": "127.0.0.1", "port": port},
"secrets": {"password": "secret"}})
send({"type": "connect"})
online = False
conversation = None
message = None
alice_seen = False
deadline = time.time() + 10
while time.time() < deadline:
e = ev(1.0)
if e is None:
if conversation and message and alice_seen:
break
continue
t = e.get("type")
if t == "state" and e.get("state") == "online":
online = True
send({"type": "join", "conv": ROOM})
elif t == "conversation":
conversation = e
elif t == "message":
message = e
elif t == "presence" and e.get("buddy") == ROOM + "/alice":
alice_seen = True
check(online, "online")
check(join_seen and join_seen[0], "the join presence reached the room")
check(conversation is not None, "conversation event for the room")
check(conversation and conversation.get("conv") == ROOM,
"conversation is the room")
check(conversation and conversation.get("kind") == "group",
"the room is a group")
check(alice_seen, "alice's presence in the room")
check(message is not None, "group message event")
if message is not None:
check(message.get("conv") == ROOM, "group message is filed under the room")
check(message.get("from") == "alice", "group message names the sender")
check(message.get("text") == "hello room", "group message text")
send({"type": "part", "conv": ROOM})
check(done.wait(6), "the server saw the part")
check(part_seen and part_seen[0], "the part presence reached the room")
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")
check(proc.wait(timeout=3) == 0, "exit 0")
check(proc.stderr.read().strip() == "", "no stderr output")
if failures:
print("test_xmpp_muc: FAIL (%d)" % len(failures))
sys.exit(1)
print("test_xmpp_muc: all ok")