Files
lotherk fc23161a4e dtchat: verify adapter files with SHA-256 (T4.5)
The file protocol now carries the sender's SHA-256: the adapter computes it with dc_file_sha256 for an outgoing transfer, puts it into the IBB open metadata (urn:dtchat:file:0 sha256 attribute) and into file-sent, and passes the attribute of an incoming open through in file-offer. The UI stores the offered hash, hashes the part file at file-end and only renames when it matches; a mismatch removes the part file, reports 'file rejected: checksum mismatch' in the status line and the transcript, and never exposes the bytes under the final name. The fake adapter offers the correct hash in mode files and a wrong one in mode badhash. tests/xmpp_ibb.py checks the SHA-256 in the outgoing open and in the incoming offer. Verified stand-alone under Xvfb: mode files writes the 11-byte hello world, mode badhash leaves no file and no .part; the XMPP IBB suite passes with the hash checks. In-tree build and harness follow.
2026-11-17 11:13:07 +00:00

333 lines
12 KiB
Python
Executable File

#!/usr/bin/env python3
"""tests/xmpp_ibb.py -- file transfer over IBB (T4.5).
usage: tests/xmpp_ibb.py [path-to-dtchat-xmpp]
The server speaks stream, SASL PLAIN and bind, then:
* reads an outgoing transfer (open with sid f1, data blocks, close),
checks the bytes against the file the test made and acknowledges each IQ;
* offers an incoming file (s1, 11 bytes) and waits for the explicit accept
before sending data; checks file-data and file-end;
* offers a second file (s2) and checks that a reject becomes an IQ error.
"""
import base64
import hashlib
import json
import os
import queue
import re
import socket
import subprocess
import sys
import tempfile
import threading
import time
ADAPTER = sys.argv[1] if len(sys.argv) > 1 else \
"build/mcde-host/programs/dtchat/dtchat-xmpp"
failures = []
out_data = []
accepted = []
rejected = []
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]
done = threading.Event()
fd, path = tempfile.mkstemp(prefix="dtchat-ibb-", suffix=".bin")
with os.fdopen(fd, "wb") as f:
f.write(b"hello IBB, this is a test file\x00with binary")
with open(path, "rb") as f:
payload = f.read()
def server():
conn, _ = srv.accept()
conn.settimeout(10)
buf = bytearray()
def fill_until(marker):
while marker not in buf:
chunk = conn.recv(4096)
if not chunk:
return False
buf.extend(chunk)
return True
def read_iq_with(pattern):
"""Return the IQ stanza containing a regex match, draining others."""
rx = re.compile(pattern)
deadline = time.time() + 10
while time.time() < deadline:
m = rx.search(bytes(buf))
if m is not None:
start = buf.rfind(b"<iq", 0, m.start())
if start >= 0:
tagend = buf.find(b">", start)
if tagend >= 0 and buf[tagend - 1:tagend] == b"/":
end = tagend + 1
else:
close = buf.find(b"</iq>", m.end())
end = close + 5 if close >= 0 else -1
if end >= 0:
stanza = bytes(buf[start:end])
del buf[:end]
return stanza
try:
chunk = conn.recv(4096)
except socket.timeout:
return None
if not chunk:
return None
buf.extend(chunk)
return None
def iq_id(stanza):
m = re.search(rb"id=['\"]([^'\"]+)", stanza)
return m.group(1).decode() if m else "?"
def reply(stanza, kind="result"):
conn.sendall(("<iq type='%s' id='%s'/>" %
(kind, iq_id(stanza))).encode())
if not fill_until(b"<stream:stream"):
return
buf.clear()
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
buf.clear()
conn.sendall(b"<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>")
if not fill_until(b"<stream:stream"):
return
buf.clear()
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
m = re.search(rb"<iq[^>]*id=['\"]([^'\"]+)", bytes(buf))
iqid = m.group(1).decode() if m else "1"
buf.clear()
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())
# --- outgoing: the adapter sends the file the test asked for
open_iq = read_iq_with(rb'<open[^>]*sid=["\']f1["\']')
check(open_iq is not None, "the adapter opened the outgoing stream")
if open_iq is not None:
fm = re.search(rb'<file[^>]*name=["\']([^"\']+)["\']', open_iq)
check(fm is not None and fm.group(1).decode() == "payload.bin",
"the open carries the file name")
hm = re.search(rb'<file[^>]*sha256=["\']([0-9a-f]{64})["\']',
open_iq)
check(hm is not None and
hm.group(1).decode() == hashlib.sha256(payload).hexdigest(),
"the open carries the SHA-256")
reply(open_iq)
seq = 0
while True:
iq = read_iq_with(rb'<data[^>]*sid=["\']f1["\']')
if iq is None:
check(False, "a data block arrived")
break
sm = re.search(rb'<data[^>]*seq=["\'](\d+)["\']', iq)
bm = re.search(rb'<base64>(.*?)</base64>', iq, re.S)
if sm is None or bm is None:
print("IQ:", iq[:400], flush=True)
check(False, "data block is well formed")
break
check(int(sm.group(1)) == seq, "data seq %d" % seq)
out_data.append(base64.b64decode(bm.group(1)))
seq += 1
reply(iq)
close_iq = read_iq_with(rb'<close[^>]*sid=["\']f1["\']')
if close_iq is not None:
reply(close_iq)
break
joined = b"".join(out_data)
check(joined == payload, "the outgoing bytes arrive unchanged")
# --- incoming with an explicit accept
conn.sendall(b"<iq type='set' id='in1' from='bob@example.org/laptop' "
b"to='tester@example.org/dtchat'>"
b"<open xmlns='http://jabber.org/protocol/ibb' "
b"sid='s1' block-size='4096'>"
b"<file xmlns='urn:dtchat:file:0' name='note.txt' "
b"size='11' sha256='" +
hashlib.sha256(b"hello world").hexdigest().encode() +
b"'/></open></iq>")
result = read_iq_with(rb'id=["\']in1["\']')
accepted.append(result is not None)
check(result is not None, "the adapter answered the accepted offer")
conn.sendall(b"<iq type='set' id='in2' from='bob@example.org/laptop' "
b"to='tester@example.org/dtchat'>"
b"<data xmlns='http://jabber.org/protocol/ibb' sid='s1' "
b"seq='0'><base64>aGVsbG8gd29ybGQ=</base64></data></iq>")
read_iq_with(rb'id=["\']in2["\']')
conn.sendall(b"<iq type='set' id='in3' from='bob@example.org/laptop' "
b"to='tester@example.org/dtchat'>"
b"<close xmlns='http://jabber.org/protocol/ibb' "
b"sid='s1'/></iq>")
read_iq_with(rb'id=["\']in3["\']')
# --- incoming that is rejected
conn.sendall(b"<iq type='set' id='in4' from='bob@example.org/laptop' "
b"to='tester@example.org/dtchat'>"
b"<open xmlns='http://jabber.org/protocol/ibb' "
b"sid='s2' block-size='4096'>"
b"<file xmlns='urn:dtchat:file:0' name='big.bin' "
b"size='99'/></open></iq>")
rej = read_iq_with(rb'id=["\']in4["\']')
rejected.append(rej is not None and b"error" in rej)
check(rejected[-1], "a rejected offer becomes an IQ error")
done.set()
time.sleep(0.2)
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
def wait_event(kind, pred=None, timeout=10):
deadline = time.time() + timeout
while time.time() < deadline:
try:
e = q.get(timeout=1)
except queue.Empty:
continue
if e.get("type") == kind and (pred is None or pred(e)):
return e
return None
hello = ev()
check(hello is not None and hello.get("type") == "hello", "hello arrives")
check("files" in (hello or {}).get("caps", []),
"the adapter says it does files")
send({"type": "configure", "account": "t",
"settings": {"jid": "tester@example.org", "host": "127.0.0.1",
"port": port},
"secrets": {"password": "secret"}})
send({"type": "connect"})
online = False
deadline = time.time() + 6
while time.time() < deadline:
e = ev(1.0)
if e is None:
continue
if e.get("type") == "state" and e.get("state") == "online":
online = True
break
check(online, "online")
send({"type": "file-send", "conv": "bob@example.org", "id": "f1",
"name": "payload.bin", "path": path})
sent = wait_event("file-sent", lambda e: e.get("id") == "f1")
check(sent is not None, "file-sent for the outgoing transfer")
check(sent is not None and sent.get("size") == len(payload),
"file-sent has the size")
offer = wait_event("file-offer", lambda e: e.get("id") == "s1")
check(offer is not None, "file-offer for the incoming transfer")
if offer is not None:
check(offer.get("name") == "note.txt", "the offer has the name")
check(offer.get("size") == 11, "the offer has the size")
check(offer.get("sha256") == hashlib.sha256(b"hello world").hexdigest(),
"the offer has the SHA-256")
check(offer.get("conv") == "bob@example.org",
"the offer is filed under the contact")
send({"type": "file-accept", "id": "s1"})
data = wait_event("file-data", lambda e: e.get("id") == "s1")
check(data is not None, "file-data after the accept")
if data is not None:
check(base64.b64decode(data.get("data", "")) == b"hello world",
"the data decodes to the sent bytes")
check(data.get("size") == 11, "the data size")
end = wait_event("file-end", lambda e: e.get("id") == "s1")
check(end is not None and end.get("size") == 11, "file-end with the size")
offer2 = wait_event("file-offer", lambda e: e.get("id") == "s2")
check(offer2 is not None, "second offer")
if offer2 is not None:
send({"type": "file-reject", "id": "s2", "reason": "not now"})
rej = wait_event("file-reject", lambda e: e.get("id") == "s2")
check(rej is not None, "file-reject is confirmed")
check(done.wait(6), "the server finished")
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")
os.unlink(path)
if failures:
print("test_xmpp_ibb: FAIL (%d)" % len(failures))
sys.exit(1)
print("test_xmpp_ibb: all ok")