msm-modem-uim-selection, sxmo_modem: fix incoming SMS TPDU decoding and delivery

This commit is contained in:
Luxferre committed 2026-10-29 18:45:18 +02:00
1 parent a4dbf71af9
commit 5da053d8a5
3 files changed
+514 -308

No files matched your search

@@ -1705,21 +1705,38 @@ def encode_da(number):
bcd.append((hi << 4) | lo)
return bytes([len(digits), ton_npi]) + bytes(bcd)
def build_pdus(number, msg):
da = encode_da(number)
try:
raw_ascii = msg.encode("ascii")
is_ascii = all((32 <= b < 127) or b in (10, 13) for b in raw_ascii)
except UnicodeEncodeError:
is_ascii = False
GSM7_BASIC = (
"@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5"
"\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\x1b\u00c6\u00e6\u00df\u00c9"
" !\"#\u00a4%&'()*+,-./0123456789:;<=>?"
"\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
"\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0"
)
GSM7_EXT_ENC = {
"\f": 0x0A, "^": 0x14, "{": 0x28, "}": 0x29, "\\": 0x2F,
"[": 0x3C, "~": 0x3D, "]": 0x3E, "|": 0x40, "\u20ac": 0x65
}
GSM7_BASIC_ENC = {ch: idx for idx, ch in enumerate(GSM7_BASIC) if ch != "\x1b"}
if is_ascii and len(msg) <= 160:
septets = [ord(c) & 0x7F for c in msg]
def encode_gsm7_septets(msg):
septets = []
for ch in msg:
if ch in GSM7_BASIC_ENC:
septets.append(GSM7_BASIC_ENC[ch])
elif ch in GSM7_EXT_ENC:
septets.append(0x1B)
septets.append(GSM7_EXT_ENC[ch])
else:
return None
return septets
def pack_gsm7(septets, udh=b""):
if not udh:
packed = bytearray()
shift = 0
cur = 0
for s_val in septets:
cur |= (s_val << shift)
cur |= (s_val & 0x7F) << shift
shift += 7
while shift >= 8:
packed.append(cur & 0xFF)
@@ -1727,8 +1744,47 @@ def build_pdus(number, msg):
shift -= 8
if shift > 0:
packed.append(cur & 0xFF)
# 0x00 (default SMSC), 0x01 (SMS-SUBMIT), 0x00 (MR), DA, 0x00 (PID), 0x00 (DCS 7-bit), UDL, UD
return [b"\x00\x01\x00" + da + b"\x00\x00" + bytes([len(septets)]) + bytes(packed)]
return len(septets), bytes(packed)
udh_bits = len(udh) * 8
fill_bits = (7 - (udh_bits % 7)) % 7
packed = bytearray()
shift = fill_bits
cur = 0
for s_val in septets:
cur |= (s_val & 0x7F) << shift
shift += 7
while shift >= 8:
packed.append(cur & 0xFF)
cur >>= 8
shift -= 8
if shift > 0:
packed.append(cur & 0xFF)
total_septets = ((udh_bits + fill_bits) // 7) + len(septets)
return total_septets, bytes(udh) + bytes(packed)
def build_pdus(number, msg):
da = encode_da(number)
septets = encode_gsm7_septets(msg)
if septets is not None:
if len(septets) <= 160:
udl, ud = pack_gsm7(septets)
return [b"\x00\x01\x00" + da + b"\x00\x00" + bytes([udl]) + ud]
chunks = []
pos = 0
while pos < len(septets):
chunk = septets[pos:pos+153]
if chunk and chunk[-1] == 0x1B and (pos + len(chunk)) < len(septets):
chunk = chunk[:-1]
chunks.append(chunk)
pos += len(chunk)
ref = random.randint(1, 254)
total = len(chunks)
pdus = []
for idx, chunk in enumerate(chunks, 1):
udh = bytes([0x05, 0x00, 0x03, ref, total, idx])
udl, ud = pack_gsm7(chunk, udh)
pdus.append(b"\x00\x41\x00" + da + b"\x00\x00" + bytes([udl]) + ud)
return pdus
u16 = msg.encode("utf-16-be")
if len(u16) <= 140:
@@ -2093,6 +2149,8 @@ def parse_tlvs(resp):
pos += tl
return res
pending_inds = []
def qmi_req(s, addr, txn, msg_id, tlvs=b"", timeout=1.0):
s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, addr)
deadline = time.time() + timeout
@@ -2101,20 +2159,26 @@ def qmi_req(s, addr, txn, msg_id, tlvs=b"", timeout=1.0):
if not r:
return {}
resp, _ = s.recvfrom(4096)
if len(resp) >= 7 and resp[0] == 0x04:
pending_inds.append((s, resp))
continue
if len(resp) >= 7 and resp[0] == 0x02:
r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
if r_txn == txn and r_msg == msg_id:
return parse_tlvs(resp)
return {}
def run_user_cmd(cmd_str):
def run_user_cmd(cmd_str, extra_env=None):
env = os.environ.copy()
env["DISPLAY"] = ":0"
env["XDG_RUNTIME_DIR"] = "/run/user/10000"
env["HOME"] = "/home/user"
env["PATH"] = "/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin"
if extra_env:
env.update(extra_env)
subprocess.Popen(
["su", "user", "-c", f"export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/10000 HOME=/home/user PATH=/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin; {cmd_str}"],
["su", "-m", "user", "-c", f"export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/10000 HOME=/home/user PATH=/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin; {cmd_str}"],
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
@@ -2131,7 +2195,7 @@ def send_fifo(fifo_path, line):
GSM7_BASIC = (
"@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5"
"\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\x1b\u00c6\u00e6\u00df\u00c9"
" !\"#$%&'()*+,-./0123456789:;<=>?"
" !\"#\u00a4%&'()*+,-./0123456789:;<=>?"
"\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
"\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0"
)
@@ -2146,6 +2210,7 @@ def decode_bcd_addr(data, num_digits, ton_npi):
# Alphanumeric 7-bit GSM address
total_septets = (num_digits * 4) // 7
septets = []
esc = False
for i in range(total_septets):
bit_off = i * 7
byte_idx = bit_off // 8
@@ -2155,7 +2220,13 @@ def decode_bcd_addr(data, num_digits, ton_npi):
val = (data[byte_idx] >> shift) & 0x7F
if shift > 1 and (byte_idx + 1) < len(data):
val |= (data[byte_idx + 1] << (8 - shift)) & 0x7F
septets.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "")
if esc:
septets.append(GSM7_EXT.get(val, ""))
esc = False
elif val == 0x1B:
esc = True
else:
septets.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "")
return "".join(septets).strip("@ ")
prefix = "+" if ton == 1 else ""
digits = []
@@ -2168,47 +2239,49 @@ def decode_bcd_addr(data, num_digits, ton_npi):
digits.append(str(hi))
return prefix + "".join(digits[:num_digits])
def decode_sms_deliver(pdu):
def _parse_deliver_tpdu(pdu, pos):
try:
if len(pdu) < 10:
return None
smsc_len = pdu[0]
pos = 1 + smsc_len
if pos >= len(pdu):
if pos < 0 or pos + 12 > len(pdu):
return None
first_octet = pdu[pos]
mti = first_octet & 0x03
if mti not in (0, 2):
if mti != 0:
return None
udhi = (first_octet & 0x40) != 0
pos += 1
oa_digits = pdu[pos]
oa_ton_npi = pdu[pos + 1]
if oa_digits > 20 or (oa_ton_npi & 0x80) == 0:
return None
oa_byte_len = (oa_digits + 1) // 2
if pos + 2 + oa_byte_len + 10 > len(pdu):
return None
oa_bytes = pdu[pos + 2 : pos + 2 + oa_byte_len]
sender = decode_bcd_addr(oa_bytes, oa_digits, oa_ton_npi)
pos += 2 + oa_byte_len
if pos + 9 > len(pdu):
return None
pid = pdu[pos]
dcs = pdu[pos + 1]
scts = pdu[pos + 2 : pos + 9]
udl = pdu[pos + 9]
ud = pdu[pos + 10 :]
# Decode SCTS (YY MM DD HH MM SS TZ)
# Validate and decode SCTS (YY MM DD HH MM SS TZ)
def unbcd(b):
return ((b & 0x0F) * 10) + ((b >> 4) & 0x0F)
try:
yr = 2000 + unbcd(scts[0])
mo = unbcd(scts[1])
dy = unbcd(scts[2])
hr = unbcd(scts[3])
mi = unbcd(scts[4])
sc = unbcd(scts[5])
iso_ts = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mi:02d}:{sc:02d}"
except Exception:
iso_ts = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
lo = b & 0x0F
hi = (b >> 4) & 0x0F
if lo > 9 or hi > 9:
raise ValueError("invalid BCD")
return (lo * 10) + hi
yr = 2000 + unbcd(scts[0])
mo = unbcd(scts[1])
dy = unbcd(scts[2])
hr = unbcd(scts[3])
mi = unbcd(scts[4])
sc = unbcd(scts[5])
if not (1 <= mo <= 12 and 1 <= dy <= 31 and 0 <= hr <= 23 and 0 <= mi <= 59 and 0 <= sc <= 59):
return None
iso_ts = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mi:02d}:{sc:02d}"
csms_ref = None
csms_total = 1
@@ -2217,6 +2290,8 @@ def decode_sms_deliver(pdu):
if udhi and len(ud) >= 1:
udh_len = ud[0]
udh_bytes = 1 + udh_len
if udh_bytes > len(ud):
return None
upos = 1
while upos + 2 <= udh_bytes and upos + 2 <= len(ud):
iei = ud[upos]
@@ -2229,19 +2304,29 @@ def decode_sms_deliver(pdu):
csms_ref = (iedata[0] << 8) | iedata[1]
csms_total, csms_seq = iedata[2], iedata[3]
# Determine alphabet from DCS
if (dcs & 0xC0) == 0x00:
# Determine alphabet from 3GPP TS 23.038 DCS
if (dcs & 0xC0) in (0x00, 0x40):
alphabet = (dcs >> 2) & 0x03
if alphabet == 3:
alphabet = 0
elif (dcs & 0xF0) == 0xE0:
alphabet = 2
elif (dcs & 0xF0) in (0xC0, 0xD0):
alphabet = 0
elif (dcs & 0xF0) == 0xF0:
alphabet = 1 if (dcs & 0x04) else 0
else:
alphabet = 0
if alphabet == 2:
payload = ud[udh_bytes : udl]
end_byte = min(udl, len(ud))
payload = ud[udh_bytes : end_byte]
if len(payload) % 2 == 1:
payload = payload[:-1]
text = payload.decode("utf-16-be", errors="replace")
elif alphabet == 1:
payload = ud[udh_bytes : udl]
end_byte = min(udl, len(ud))
payload = ud[udh_bytes : end_byte]
text = payload.decode("utf-8", errors="replace")
else:
fill_bits = (7 - ((udh_bytes * 8) % 7)) % 7 if udh_bytes > 0 else 0
@@ -2266,8 +2351,13 @@ def decode_sms_deliver(pdu):
chars.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "?")
text = "".join(chars)
clean_sender = "".join(
c for c in (sender or "Unknown")
if c not in "/\x00\r\n\t" and ord(c) >= 32
).strip() or "Unknown"
return {
"sender": sender or "Unknown",
"sender": clean_sender,
"time": iso_ts,
"text": text,
"ref": csms_ref,
@@ -2277,30 +2367,100 @@ def decode_sms_deliver(pdu):
except Exception:
return None
def decode_sms_deliver(pdu, only_tpdu=False):
if not pdu or len(pdu) < 12:
return None
if only_tpdu:
res = _parse_deliver_tpdu(pdu, 0)
if res is not None:
return res
smsc_len = pdu[0]
if 0 <= smsc_len <= 12 and (smsc_len == 0 or (pdu[1] & 0x80) != 0):
return _parse_deliver_tpdu(pdu, 1 + smsc_len)
return None
smsc_len = pdu[0]
if 0 <= smsc_len <= 12 and (smsc_len == 0 or (len(pdu) > 1 and (pdu[1] & 0x80) != 0)):
res = _parse_deliver_tpdu(pdu, 1 + smsc_len)
if res is not None:
return res
return _parse_deliver_tpdu(pdu, 0)
multipart_buf = {}
BLOCK_FILE = "/home/user/.config/sxmo/block.tsv"
BLOCK_DIR = "/home/user/.local/share/sxmo/block"
def is_sender_blocked(sender):
try:
if not os.path.isfile(BLOCK_FILE):
return False
norm = "".join(c for c in sender if c.isdigit() or c == "+")
if not norm:
norm = sender.strip()
sfx = norm[-7:] if len(norm) >= 7 else ""
with open(BLOCK_FILE, "r", encoding="utf-8", errors="ignore") as bf:
for line in bf:
raw = line.split("\t", 1)[0].strip()
if not raw:
continue
r_norm = "".join(c for c in raw if c.isdigit() or c in "+*")
if not r_norm:
continue
if r_norm.endswith("*") and len(r_norm) > 1:
if norm.startswith(r_norm[:-1]):
return True
elif r_norm == norm or (sfx and len(r_norm) >= 7 and r_norm[-7:] == sfx):
return True
except Exception:
pass
return False
def deliver_sms_to_sxmo(sender, iso_ts, text, sim_slot):
now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
tsv_text = text.replace("\t", " ").replace("\r", " ").replace("\n", " ")
if is_sender_blocked(sender):
num_dir = os.path.join(BLOCK_DIR, sender)
ensure_user_dir(num_dir, "/home/user")
sms_file = os.path.join(num_dir, "sms.txt")
header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
with open(sms_file, "a", encoding="utf-8") as f:
f.write(header)
chown_user(sms_file)
blk_log = os.path.join(BLOCK_DIR, "modemlog.tsv")
try:
with open(blk_log, "a", encoding="utf-8") as f:
f.write(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
chown_user(blk_log)
except Exception:
pass
send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
return
num_dir = os.path.join(LOG_DIR, sender)
ensure_user_dir(num_dir, "/home/user")
sms_file = os.path.join(num_dir, "sms.txt")
now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
with open(sms_file, "a", encoding="utf-8") as f:
f.write(header)
tsv_text = text.replace("\t", " ").replace("\r", " ").replace("\n", " ")
append_modemlog(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
chown_user(sms_file)
send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
safe_sender = sender.replace("'", "")
safe_text = text.replace("'", "")
run_user_cmd(f"sxmo_hook_sms.sh '{safe_sender}' '{safe_text}'")
run_user_cmd(
'CONTACTNAME="$(sxmo_contacts.sh --name-or-number "$SXMO_SMS_SENDER" 2>/dev/null || printf "%s" "$SXMO_SMS_SENDER")"; '
'sxmo_notifs.sh new -g "incoming-message-$SXMO_SMS_SENDER" "xsms tailtextlog \'$SXMO_SMS_SENDER\'" "$CONTACTNAME: $SXMO_SMS_TEXT" >/dev/null 2>&1 || true; '
'sxmo_hook_sms.sh "$CONTACTNAME" "$SXMO_SMS_TEXT"',
extra_env={"SXMO_SMS_SENDER": sender, "SXMO_SMS_TEXT": text}
)
def handle_decoded_sms(info, sim_slot):
if not info:
return
if info["ref"] is not None and info["total"] > 1:
key = (info["sender"], info["ref"], info["total"])
parts = multipart_buf.setdefault(key, {"ts": time.time(), "segs": {}})
parts = multipart_buf.setdefault(key, {"ts": time.time(), "time": info["time"], "slot": sim_slot, "segs": {}})
parts["ts"] = time.time()
parts["time"] = info["time"]
parts["slot"] = sim_slot
parts["segs"][info["seq"]] = info["text"]
if len(parts["segs"]) >= info["total"]:
full_text = "".join(parts["segs"].get(i, "") for i in range(1, info["total"] + 1))
@@ -2309,6 +2469,16 @@ def handle_decoded_sms(info, sim_slot):
else:
deliver_sms_to_sxmo(info["sender"], info["time"], info["text"], sim_slot)
def flush_stale_multipart():
now = time.time()
for key, parts in list(multipart_buf.items()):
if now - parts["ts"] >= 30.0:
sender, _, total = key
full_text = "".join(parts["segs"].get(i, "") for i in range(1, total + 1))
del multipart_buf[key]
if full_text:
deliver_sms_to_sxmo(sender, parts.get("time", ""), full_text, parts.get("slot", 2))
def poll_stored_sms(wms_sock, wms_addr, txn, sim_slot):
for stype in (0, 1):
# WMSListMessages (0x0031): TLV 0x01 = storage_type, TLV 0x11 = message_mode (1 = GW)
@@ -2332,7 +2502,7 @@ def poll_stored_sms(wms_sock, wms_addr, txn, sim_slot):
if len(raw_msg) >= 4:
dlen = struct.unpack("<H", raw_msg[2:4])[0]
pdu = raw_msg[4:4+dlen]
info = decode_sms_deliver(pdu)
info = decode_sms_deliver(pdu, only_tpdu=False)
if info:
handle_decoded_sms(info, sim_slot)
qmi_req(wms_sock, wms_addr, txn, 0x0024, struct.pack("<BHB", 0x01, 1, stype) + struct.pack("<BHI", 0x10, 4, idx) + struct.pack("<BHB", 0x12, 1, 1))
@@ -2564,23 +2734,42 @@ while True:
try:
while True:
poll_timeout = 1.0 if (active_calls or has_sub1_call_files()) else 10.0
if active_calls or has_sub1_call_files():
poll_timeout = 1.0
elif multipart_buf:
poll_timeout = 2.0
else:
poll_timeout = 60.0
r, _, _ = select.select([ws, vs], [], [], poll_timeout)
got_voice_ind = False
events = []
while pending_inds:
events.append(pending_inds.pop(0))
for sock in r:
pkt, _ = sock.recvfrom(4096)
events.append((sock, pkt))
for sock, pkt in events:
if len(pkt) < 7:
continue
flags, txn, mid, _ = struct.unpack("<BHHH", pkt[:7])
if flags != 0x04:
continue
tlvs = parse_tlvs(pkt)
if sock is ws and mid == 0x0001:
# WMSEventReport indication
if 0x11 in tlvs and len(tlvs[0x11]) >= 8:
# Transfer-route MT message: [ack_ind(1), txn_id(4), format(1), len(2), data...]
tr = tlvs[0x11]
ack_ind = tr[0]
mt_txn_id = struct.unpack("<I", tr[1:5])[0]
dlen = struct.unpack("<H", tr[6:8])[0]
pdu = tr[8:8+dlen]
info = decode_sms_deliver(pdu)
if ack_ind == 0:
# Send QMI_WMS_SEND_ACK (0x0026): TLV 0x01 = [txn_id(4), protocol=1(WCDMA), success=1]
ack_tlv = struct.pack("<BHIBB", 0x01, 6, mt_txn_id, 1, 1)
ws.sendto(struct.pack("<BHHH", 0x00, w_txn, 0x0026, len(ack_tlv)) + ack_tlv, wms_addr)
w_txn = (w_txn % 60000) + 1
info = decode_sms_deliver(pdu, only_tpdu=True)
if info:
handle_decoded_sms(info, sec_slot)
if 0x10 in tlvs:
@@ -2598,12 +2787,15 @@ while True:
calls[cid]["num"] = fc["num"]
sync_sub1_calls(calls, sec_slot)
if multipart_buf:
flush_stale_multipart()
if not got_voice_ind and (active_calls or has_sub1_call_files()):
full_tlvs = qmi_req(vs, voice_addr, v_txn, 0x002F)
v_txn = (v_txn % 60000) + 1
sync_sub1_calls(parse_call_info(full_tlvs), sec_slot)
if time.time() - last_poll >= 15.0:
if time.time() - last_poll >= 120.0:
w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
last_poll = time.time()
except Exception: