#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
"""fake-imsd.py — net.catcrafts.IMS1's Messaging interface on the session bus,
with the answers chosen on the command line, for benching imsd-messages
without a phone: a registered daemon that accepts sends, a store to list
and delete, texts injected while the app runs, and the refusals.
fake-imsd.py [--unregistered] [--disabled] [--deny] [--fail-sends] [--ppi TEL]
[--operator ID] [--inject FROM TEXT [FROM TEXT ...]]
[--inject-after SECONDS] [--subscribe-delay SECONDS]
Run imsd-messages with --session against it. --deny answers Subscribe, List,
Delete and Send with AccessDenied (polkit's refusal); --fail-sends makes every
Send end in `failed`. Texts given with --inject are stored at start, or
delivered as Received after --inject-after seconds when that is given.
--subscribe-delay answers Subscribe that many seconds late: the app before
imsd's status is in.
"""
import argparse, datetime, random, sys, time
import gi
gi.require_version('Gio', '2.0'); gi.require_version('GLib', '2.0')
from gi.repository import Gio, GLib
BUS = 'net.catcrafts.IMS1'; PATH = '/net/catcrafts/IMS1'; IFACE = 'net.catcrafts.IMS1.Messaging'; BASE = 'net.catcrafts.IMS1'
XML = f"""
"""
def log(*a): print('fake-imsd:', *a, flush=True)
class Fake:
def __init__(self, args):
self.args = args; self.store = {}; self.subscribers = set(); self.sent = 0; self.n = 0; self.started = int(time.time()); self.run = f'{random.getrandbits(32):08x}'; self.conn = None # the run token, imsd's first id field
def message(self, sender, text, received):
d = {'operator': GLib.Variant('s', self.args.operator)} if self.args.operator else {} # the SIM a text arrived under, as imsd records it
return d | {'from': GLib.Variant('s', sender), 'text': GLib.Variant('s', text),
'timestamp': GLib.Variant('s', datetime.datetime.fromtimestamp(received).astimezone().isoformat(timespec='seconds')), # imsd's form: ISO 8601 with the offset
'received': GLib.Variant('x', received), 'sc': GLib.Variant('s', '+31624000000'), 'class': GLib.Variant('i', -1),
'pid': GLib.Variant('y', 0), 'dcs': GLib.Variant('y', 0), 'segments': GLib.Variant('i', 1), 'message-waiting': GLib.Variant('b', False),
'pdu': GLib.Variant('ay', b'')}
def inject(self, sender, text):
self.n += 1; now = int(time.time()); mid = f'ims-sms-in-{self.run}-{now}-{self.n}'
self.store[mid] = self.message(sender, text, now)
log('stored', mid, 'from', sender)
for name in list(self.subscribers):
self.conn.emit_signal(name, PATH, IFACE, 'Received', GLib.Variant('(sa{sv})', (mid, self.store[mid])))
log('Received ->', name, mid)
return False
def status(self):
d = {'enabled': GLib.Variant('b', not self.args.disabled), 'smsc': GLib.Variant('s', '+31653131313'),
'registered': GLib.Variant('b', not self.args.unregistered), 'subscribers': GLib.Variant('u', len(self.subscribers))}
if self.args.ppi: d['ppi'] = GLib.Variant('s', self.args.ppi) # in both GetStatus answers, as imsd gives it
if self.args.operator: d['operator'] = GLib.Variant('s', self.args.operator) # the Messaging answer's alone
return d
def on_call(self, conn, sender, path, iface, method, params, inv):
gated = method in ('Send', 'Subscribe', 'List', 'Delete')
if gated and self.args.deny:
log(method, 'refused for', sender); inv.return_dbus_error('org.freedesktop.DBus.Error.AccessDenied', f'{sender} is not authorized for net.catcrafts.IMS1.Messaging'); return
if method == 'GetStatus' and iface == BASE:
# the frozen interface's status: the subscriber's own number as a tel: URI (--ppi '' for a network that gives none)
d = {'registered': GLib.Variant('b', not self.args.unregistered)}
if self.args.ppi: d['ppi'] = GLib.Variant('s', self.args.ppi)
inv.return_value(GLib.Variant('(a{sv})', (d,)))
elif method == 'GetStatus':
inv.return_value(GLib.Variant('(a{sv})', (self.status(),)))
elif method == 'Subscribe':
def subscribed():
self.subscribers.add(sender); log(sender, 'subscribed', f'({len(self.subscribers)})')
Gio.bus_watch_name_on_connection(conn, sender, Gio.BusNameWatcherFlags.NONE, None, lambda c, n: (self.subscribers.discard(n), log(n, 'unsubscribed')))
inv.return_value(None)
if self.args.subscribe_delay > 0: GLib.timeout_add(int(self.args.subscribe_delay * 1000), subscribed)
else: subscribed()
elif method == 'List':
items = sorted(self.store.items(), key=lambda kv: kv[1]['received'].get_int64())
inv.return_value(GLib.Variant('(a(sa{sv}))', ([(k, v) for k, v in items],)))
log('List ->', len(items))
elif method == 'Delete':
mid = params.unpack()[0]
if mid not in self.store: inv.return_dbus_error('org.freedesktop.DBus.Error.FileNotFound', f'no stored message {mid}'); return
del self.store[mid]; log('deleted', mid); inv.return_value(None)
elif method == 'Send':
if self.args.disabled: inv.return_dbus_error('org.freedesktop.DBus.Error.NotSupported', 'SMS over IP is off'); return
number, text, options = params.unpack(); self.sent += 1; mid = f'ims-sms-{self.run}-{self.started}-{self.sent}' # imsd's form: the run token, its start second and a counter
log('Send', mid, 'to', number, repr(text), 'status-report' if options.get('status-report') else '')
inv.return_value(GLib.Variant('(s)', (mid,)))
targets = set(self.subscribers) | {sender}
def state(st, reason):
for name in list(targets):
conn.emit_signal(name, PATH, IFACE, 'StateChanged', GLib.Variant('(sss)', (mid, st, reason)))
log('StateChanged ->', st, reason or ''); return False
if self.args.unregistered: GLib.timeout_add(100, state, 'failed', 'imsd is not registered')
elif self.args.fail_sends: GLib.timeout_add(800, state, 'failed', 'RP-ERROR cause 38 (network out of order)')
else:
GLib.timeout_add(800, state, 'sent', datetime.datetime.now().astimezone().isoformat(timespec='seconds')) # a stamp for imsd's reason ("n segment(s) accepted by the SC at "), which the app logs as it comes
if options.get('status-report'): GLib.timeout_add(2500, state, 'delivered', '')
else:
inv.return_dbus_error('org.freedesktop.DBus.Error.UnknownMethod', 'no such method')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--unregistered', action='store_true'); ap.add_argument('--disabled', action='store_true')
ap.add_argument('--ppi', default='tel:+31612345678', help="the ppi of both GetStatus answers, the subscriber's own number; '' for none")
ap.add_argument('--operator', default='20408', metavar='ID', help="the SIM's operator in the Messaging GetStatus and in each text: MCC then MNC; '' for none")
ap.add_argument('--deny', action='store_true'); ap.add_argument('--fail-sends', action='store_true')
ap.add_argument('--subscribe-delay', type=float, default=0.0, metavar='SECONDS', help='answer Subscribe this many seconds late: the app before the status is in')
ap.add_argument('--inject', nargs='+', default=[], metavar='FROM TEXT'); ap.add_argument('--inject-after', type=float, default=None)
args = ap.parse_args()
if len(args.inject) % 2: ap.error('--inject takes FROM TEXT pairs')
fake = Fake(args)
info = Gio.DBusNodeInfo.new_for_xml(XML)
def on_bus(conn, name):
fake.conn = conn
for i in info.interfaces: conn.register_object(PATH, i, fake.on_call, None, None)
log('owning', BUS, 'on the session bus')
pairs = list(zip(args.inject[::2], args.inject[1::2]))
if args.inject_after is None:
for s, t in pairs: fake.inject(s, t)
else:
for k, (s, t) in enumerate(pairs): GLib.timeout_add(int(args.inject_after * 1000) + 300 * k, fake.inject, s, t)
Gio.bus_own_name(Gio.BusType.SESSION, BUS, Gio.BusNameOwnerFlags.NONE, on_bus, None, lambda c, n: (log('lost the name', n), sys.exit(1)))
GLib.MainLoop().run()
if __name__ == '__main__': main()