Files
lotherk f0e8c668d6 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.
2026-11-17 10:02:33 +00:00

241 lines
7.6 KiB
Python
Executable File

#!/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")