imsd/tests/Sms/main.cpp
Jorijn van der Graaf 23892e8e81
sms, engine, imsd: a segment that gets no answer, or an RP-ERROR with cause 41, is sent once more with TP-RD set
A submission whose submit report did not come in time ended as
`failed`, and nothing was sent again. The service centre may have the
text all the same, and a user who then sends it again delivers it
twice: the second submission has a new TP-MR, and the service centre
cannot tell that it is a repeat (issue #3, the second of its three
cases).

TS 23.040 9.2.3.6 has the MS "automatically repeat the SMS-SUBMIT", one
to three times, with the same TP-MR and TP-RD set, when no response or
an RP-ERROR with an appropriate cause comes, so that the service centre
can discard a duplicate. SmsOutbound now sends a segment once more: when
either wait runs out, on a final of 408 or 504 (RFC 3261 21.4.9: the
server "could not produce a response within a suitable amount of time";
21.5.5: it "did not receive a timely response from an external server")
and on an RP-ERROR with cause 41, temporary failure, or with a value TS
24.011 table 8.4's part 1 does not list, which it has "treated as cause
number 41". Of the causes part 1 lists, Annex E-2 says of 41 alone that
the MS "may wish to try another short message transfer attempt almost
immediately". The repeat is a MESSAGE of its own, under its own Call-ID
and the next RP-MR — the shell's counter now goes on after the last
RP-MR a message used, one per MESSAGE built — with the same SMS-SUBMIT,
TP-RD set by the codec's flag, which nothing set until now.

The two waits are longer, so that a repeat does not overtake an answer
that is only late: 128 s for the final and 130 s from the final for the
report. TS 24.229 table 7.7.1 recommends a UE whose requests name one
of the accesses clause 7.7 lists in P-Access-Network-Info a T1 of 2 s
and a timer F of 64*T1, and TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP
sender's TR1M set to a value greater than timer F (Jorijn, 2026-11-21).

The segment is accepted by an RP-ACK to either attempt — the first
attempt's is taken when it comes after the repeat went out — and by the
RP-ERROR whose TP-FCS is the duplicate rejection (0xC5) when it answers
the repeat and no RP-ERROR has answered the first attempt by then: the
service centre is taken to have the first. An RP-ERROR to the first
attempt that comes after the repeat went out leaves the segment to the
repeat's answer. Any other end of the repeat fails the message, with
both attempts' ends in the reason. A final refused with another status
and an RP-ERROR with another cause fail the message at once, as before.

What the duplicate rejection does not say is which SMS-SUBMIT the
service centre holds: one of this subscription's that reached it
another way under the same TP-MR can draw the rejection too, and with
imsd's first attempt lost the message is then `sent` for a text that
never arrived (Jorijn, 2026-11-21: taken as the clause has it).

Not done of the clause's repeat: it cannot be switched off, and a failed
message is not kept for a user's retransmission under its TP-MR.

No member of the Messaging interface changes: `sent` and `failed` come
as before, a `failed` later by the waits — with nothing answering, 256 s
after the MESSAGE where 1.2.0 said it after 32 s — and texts queued
behind the message wait as long.

Tested by tests/Engine and tests/Sms (RpCauseIsTemporary over all 128
values; a cross-generated SMS-SUBMIT with TP-RD), and on the dev phone
against KPN with the binary of this range's last commit (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6, repeat-bench.log):
with the phone deaf on its protected server port a text to the own
number got its 202 and no submit report, went out again 130 s after the
final under the next RP-MR, with the same TP-MR and TP-RD set, and ended
`sent`; the message after it took the RP-MR after the repeat's.

KPN's service centre did not discard the repeat in that bench, nor in
the six before it (one of them with a build that waited 40 s): the
repeat got an RP-ACK under a time stamp of its own, and once the port
was open again the text came twice, under the two attempts' time
stamps: the recipient got the text twice without the user sending it
again, and the message was `sent`. 1.2.0 ends a submission whose report
does not come as `failed` and sends nothing again.

The repeat is sent all the same, on Jorijn's decision of 2026-11-20 with
the first of those benches before him: the clause has the MS repeat
("shall") and the service centre discard ("should"), and Android's
framework sends its own retries so (AOSP's ImsSmsDispatcher and
GsmSMSDispatcher set TP-RD and the earlier TP-MR; the capture's
repeat-research).
2026-11-22 17:35:12 +01:00

393 lines
29 KiB
C++
Raw Permalink Blame History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Imsd:Sms unit tests — the short message codecs byte for byte: the GSM
// 7-bit alphabet, its extension table and the septet packing (the classic
// "hellohello" vector), UCS-2, the address fields, SMS-SUBMIT (the classic
// tutorial PDU, UCS-2, the concatenated pair, the escape and surrogate pairs
// kept whole at a segment boundary), SMS-DELIVER (the classic "How are
// you?" PDU and vectors cross-generated by the fp6 journal's Python
// reference: a header with fill bits, a 16-bit concatenation reference, a
// class-0 message, port-addressed 8-bit data, an alphanumeric sender, a
// negative time zone), SMS-STATUS-REPORT and SMS-SUBMIT-REPORT (the
// duplicate rejection's TP-FCS among its causes), the
// RP-DATA / RP-ACK / RP-ERROR messages both ways, which RP causes of a
// submission invite a repeat, EF_SMSP with the KPN
// SIM's record, qmicli's hex dump, and the reassembly of a concatenated
// message.
import std;
import Imsd;
using namespace imsd::sms;
namespace {
int Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
Bytes Hex(std::string_view hex) {
auto b = imsd::util::FromHex(hex);
return b ? *b : Bytes{};
}
std::string Hex(std::span<const std::uint8_t> b) {
std::string s = imsd::util::ToHex(b);
for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return s;
}
void Eq(std::span<const std::uint8_t> got, std::string_view wantHex, std::string_view msg) {
if (Hex(got) != wantHex) {
std::println(std::cerr, "FAIL: {}\n--- got ---\n{}\n--- want ---\n{}", msg, Hex(got), wantHex);
++Failures;
}
}
std::string Rep(std::string_view s, std::size_t n) {
std::string out;
for (std::size_t i = 0; i < n; i++) out += s;
return out;
}
void EqS(std::string_view got, std::string_view want, std::string_view msg) {
if (got != want) {
std::println(std::cerr, "FAIL: {}\n--- got ---\n{}\n--- want ---\n{}", msg, got, want);
++Failures;
}
}
// the KPN SIM's service centre, as EF_SMSP holds it (dev phone, 2026-10-16)
constexpr std::string_view KpnSc = "07911356131313F3";
void TestAlphabet() {
auto hello = Gsm7Septets("hellohello");
Check(hello.has_value() && hello->size() == 10, "hellohello: 10 septets");
Eq(PackSeptets(*hello), "E8329BFD4697D9EC37", "hellohello packed (the classic vector)");
EqS(Gsm7Text(UnpackSeptets(Hex("E8329BFD4697D9EC37"), 10)), "hellohello", "hellohello unpacked");
Eq(PackSeptets(*Gsm7Septets("AAAAAAA"), 1), "82C16030180C02", "seven septets after one fill bit");
EqS(Gsm7Text(UnpackSeptets(Hex("82C16030180C02"), 7, 1)), "AAAAAAA", "unpacked after one fill bit");
Eq(PackSeptets(*Gsm7Septets("Test")), "D4F29C0E", "Test packed");
auto ext = Gsm7Septets("€[x]{~}\\|^\f");
Check(ext.has_value() && ext->size() == 21, "extension characters: ESC pairs");
EqS(Gsm7Text(*ext), "€[x]{~}\\|^\f", "extension characters round trip");
EqS(Gsm7Text(Bytes{0x00, 0x01, 0x10, 0x1B, 0x1B, 0x1B, 0x41, 0x1B}), "@£Δ A ", "ESC ESC and a trailing ESC show a space, an undefined extension code the main table's character");
Check(!Gsm7Septets("❤"), "a character outside the alphabet: no septets");
Check(!Gsm7Septets("a\x1b" "b"), "the ESC character itself is not encodable");
Check(Gsm7Septets("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà")->size() == 127, "the whole default table encodes");
Eq(Ucs2Encode("Grüße ❤"), "0047007200FC00DF006500202764", "UCS-2 encode");
EqS(Ucs2Decode(Hex("0047007200FC00DF006500202764")), "Grüße ❤", "UCS-2 decode");
Eq(Ucs2Encode("😀"), "D83DDE00", "beyond the BMP: a surrogate pair");
EqS(Ucs2Decode(Hex("D83DDE00")), "😀", "a surrogate pair decodes");
EqS(Ucs2Decode(Hex("D83D0041")), "<EFBFBD>" "A", "a lone high surrogate: U+FFFD");
EqS(Ucs2Decode(Hex("004100")), "A<EFBFBD>", "an odd trailing byte: U+FFFD");
EqS(Ucs2Decode(Hex("0048006900000021")), "Hi<EFBFBD>!", "U+0000: U+FFFD (no text means it; a D-Bus string cannot carry it)");
}
void TestAddresses() {
auto a = Address::ForNumber("+31 6-1234.5678");
Check(a && a->International() && a->digits == "31612345678", "ForNumber: international, separators dropped");
EqS(a->Number(), "+31612345678", "Number() restores the +");
Eq(*EncodeTpAddress(*a), "0B911316325476F8", "TP address, 11 digits");
auto s = Address::ForNumber("112");
Check(s && !s->International() && s->toa == ToaUnknown, "a short code: type unknown");
Eq(*EncodeTpAddress(*s), "038111F2", "TP address, 3 digits");
Eq(*EncodeRpAddress(*Address::ForNumber("+3161234567")), "06911316325476", "RP address, 10 digits: the length counts octets");
Eq(*EncodeRpAddress(Address{ToaInternational, "31653131313"}), KpnSc, "RP address of KPN's SC = the EF_SMSP bytes");
Check(!Address::ForNumber("+31x"), "a letter that is no BCD digit: no address");
Check(!Address::ForNumber("+"), "no digits: no address");
Check(Address::ForNumber("*21#")->digits == "*21#", "* and # are digits");
Check(!Address::ForNumber("abc") && !Address::ForNumber("+31c"), "ForNumber: the BCD table's a, b, c are not dialled digits");
Check(!Address::ForNumber(std::string(21, '1')) && Address::ForNumber(std::string(20, '1')), "ForNumber: at most 20 digits, the address field's cap");
Eq(*EncodeTpAddress(*Address::ForNumber("*21#")), "04812AB1", "TP address with * and #");
std::size_t pos = 0;
auto d = DecodeTpAddress(Hex("0B911316325476F8FF"), pos);
Check(d && d->Number() == "+31612345678" && pos == 8, "DecodeTpAddress: 11 digits, 8 octets consumed");
pos = 0;
Check(!DecodeTpAddress(Hex("0B9113"), pos), "DecodeTpAddress: short");
pos = 0;
auto inner = DecodeTpAddress(Hex("0481F132"), pos);
Check(inner && inner->Number() == "123" && pos == 4, "DecodeTpAddress: 1111 before the last semi-octet is skipped, not the value's end (9.1.2.3)");
auto rp = DecodeRpAddressValue(Hex("911356131313F3"));
Check(rp && rp->Number() == "+31653131313", "DecodeRpAddressValue: KPN's SC");
pos = 0;
auto alnum = DecodeTpAddress(Hex("06D04BA813"), pos);
Check(alnum && alnum->Alphanumeric() && alnum->Number() == "KPN", "an alphanumeric sender decodes as text");
Eq(*EncodeTpAddress(Address{ToaAlphanumeric, "KPN"}), "06D04BA813", "an alphanumeric address encodes 7-bit");
}
void TestSubmit() {
Submit s{"+46708251358", 0, 0xAA};
auto t = BuildSubmits(s, "hellohello", 0);
Check(t.size() == 1, "classic SUBMIT: one segment");
if (!t.empty()) Eq(t[0], "11000B916407281553F80000AA0AE8329BFD4697D9EC37", "the classic tutorial SMS-SUBMIT");
Submit u{"+31612345678", 7};
auto tu = BuildSubmits(u, "Grüße ❤", 0);
Check(tu.size() == 1, "UCS-2 SUBMIT: one segment");
if (!tu.empty()) Eq(tu[0], "01070B911316325476F800080E0047007200FC00DF006500202764", "SMS-SUBMIT in UCS-2, no TP-VP");
Submit e{"112", 3};
auto te = BuildSubmits(e, "€[x]{~}", 0);
Check(te.size() == 1, "SUBMIT with extension characters: one segment");
if (!te.empty()) Eq(te[0], "0103038111F200000D9BF28687DFF836A84D6F9302", "SMS-SUBMIT with extension characters: 13 septets for 7 characters");
Submit o{"+3161234567", 1, 0xA9, true};
auto to = BuildSubmits(o, "Hi", 0);
Check(to.size() == 1, "SUBMIT with a status report requested: one segment");
if (!to.empty()) Eq(to[0], "31010A9113163254760000A902C834", "SMS-SUBMIT: status report requested, TP-VP A9, an even number of digits");
Submit r = o;
r.rejectDuplicates = true;
auto tr = BuildSubmits(r, "Hi", 0);
Check(tr.size() == 1, "SUBMIT with TP-RD: one segment");
if (!tr.empty()) Eq(tr[0], "35010A9113163254760000A902C834", "SMS-SUBMIT with TP-RD: bit 2 of the first octet set, the rest as without it");
Submit c{"+31612345678", 10};
std::string longText(153, 'A');
longText += std::string(8, 'B');
auto tc = BuildSubmits(c, longText, 0x2A);
Check(tc.size() == 2, "161 characters: two segments");
if (tc.size() == 2) {
Eq(tc[0], "410A0B911316325476F80000A00500032A020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683", "segment 1/2: UDHI, the concatenation header, 153 septets after one fill bit, TP-MR 10");
Eq(tc[1], "410B0B911316325476F800000F0500032A02028442A15028140A01", "segment 2/2: TP-MR 11, 8 septets");
}
auto tw = BuildSubmits(c, Rep("ü", 70) + "❤", 0x2A);
Check(tw.size() == 2, "71 UCS-2 characters: two segments");
if (tw.size() == 2) {
Eq(tw[0], "410A0B911316325476F800088C0500032A0201" + Rep("00FC", 67), "UCS-2 segment 1/2: TP-MR 10, the header and 67 characters in 140 octets");
Eq(tw[1], "410B0B911316325476F800080E0500032A020200FC00FC00FC2764", "UCS-2 segment 2/2: TP-MR 11, the header and four characters");
}
Check(BuildSubmits(c, std::string(160, 'A'), 1).size() == 1, "160 characters fit one message");
Check(BuildSubmits(c, std::string(161, 'A'), 1).size() == 2, "161 characters need two");
Check(BuildSubmits(c, Rep("ü", 70) + "❤", 1).size() == 2, "71 UCS-2 characters need two");
Check(BuildSubmits(c, std::string(69, 'x') + "❤", 1).size() == 1, "70 UCS-2 characters fit one");
Check(BuildSubmits(c, "", 1).size() == 1 && BuildSubmits(c, "", 1)[0].back() == 0, "an empty text: one TPDU with TP-UDL 0");
Check(BuildSubmits(Submit{"+31x", 1}, "a", 1).empty(), "no number: no TPDU");
Check(BuildSubmits(c, std::string(153 * 255 + 1, 'A'), 1).empty(), "more than 255 segments: refused");
Alphabet alphabet;
auto seg = SplitText(std::string(152, 'A') + "€" + std::string(10, 'B'), alphabet);
Check(seg && seg->size() == 2 && (*seg)[0].size() == 152 && (*seg)[1].size() == 12 && (*seg)[1][0] == 0x1B, "an escape pair is not split at the segment boundary");
seg = SplitText(Rep("ü", 66) + "😀xxxx", alphabet);
Check(seg && alphabet == Alphabet::Ucs2 && seg->size() == 2 && (*seg)[0].size() == 66 && (*seg)[1].size() == 6, "a surrogate pair is not split at the segment boundary");
seg = SplitText(std::string(306, 'A'), alphabet);
Check(seg && seg->size() == 2 && (*seg)[1].size() == 153, "306 characters: two full segments");
}
void TestDeliver() {
auto classic = ParseDeliver(Hex("040B911346610089F60000208062917314080CC8F71D14969741F977FD07"));
Check(classic.has_value(), "the classic SMS-DELIVER parses");
if (classic) {
EqS(classic->from.Number(), "+31641600986", "classic: sender");
EqS(classic->ud.text, "How are you?", "classic: text");
EqS(classic->scts, "2002-08-26T19:37:41-00:00", "classic: time stamp as the bytes say (its zone octet 08 reads as a negative zero)");
Check(!classic->moreMessages && !classic->ud.hasHeader && classic->coding.alphabet == Alphabet::Gsm7 && !classic->coding.msgClass, "classic: flags");
}
auto t = ParseDeliver(Hex("040B911316325476F800006201612205008004D4F29C0E"));
Check(t && t->ud.text == "Test" && t->scts == "2026-10-16T22:50:00+02:00" && t->from.Number() == "+31612345678", "DELIVER 'Test' at +02:00");
auto u = ParseDeliver(Hex("040B911316325476F80008620161220500800E0047007200FC00DF006500202764"));
Check(u && u->coding.alphabet == Alphabet::Ucs2 && u->ud.text == "Grüße ❤", "DELIVER in UCS-2");
auto k = ParseDeliver(Hex("440B911316325476F80000620161220500800D060804123403029576F91C06"));
Check(k && k->ud.hasHeader && k->ud.header.concat && k->ud.header.concat->ref == 0x1234 && k->ud.header.concat->total == 3 && k->ud.header.concat->seq == 2 && k->ud.text == "Ωmega", "DELIVER with a 16-bit concatenation reference: header of eight septets, no fill");
auto f = ParseDeliver(Hex("04048121430010620161220500800546767" "88E06"));
Check(f && f->coding.msgClass == 0 && f->ud.text == "Flash" && f->from.Number() == "1234", "DELIVER class 0 from a short code");
auto p = ParseDeliver(Hex("440B911316325476F8000462016122050080090605040B8423F0DEAD"));
Check(p && p->coding.alphabet == Alphabet::Octet && p->ud.header.portDst == 0x0B84 && p->ud.header.portSrc == 0x23F0 && p->ud.text.empty() && Hex(p->ud.data) == "DEAD", "DELIVER of 8-bit data to an application port");
auto a = ParseDeliver(Hex("0406D04BA81300006201612205008002C834"));
Check(a && a->from.Alphanumeric() && a->from.Number() == "KPN" && a->ud.text == "Hi", "DELIVER from an alphanumeric sender");
auto n = ParseDeliver(Hex("04049121430000621020304050890178"));
Check(n && n->scts == "2026-01-02T03:04:05-04:30" && n->ud.text == "x", "DELIVER with a negative zone");
Check(!ParseDeliver(Hex("040B91")), "a truncated DELIVER: nullopt");
auto shortUd = ParseDeliver(Hex("040B911316325476F8000062016122050080" "0AD4F29C0E"));
Check(shortUd && shortUd->ud.text == "Test", "user data shorter than TP-UDL decodes as far as it goes");
auto mms = ParseDeliver(Hex("000B911316325476F800006201612205008004D4F29C0E"));
Check(mms && mms->moreMessages, "TP-MMS 0: more messages waiting");
}
void TestReassembly() {
Reassembler r;
auto p1 = ParseDeliver(Hex("440B911316325476F8000062016122050080A00500037B020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683"));
auto p2 = ParseDeliver(Hex("440B911316325476F80000620161220500800C0500037B02028442A15008"));
Check(p1 && p2 && p1->ud.header.concat && p2->ud.header.concat, "both segments parse with their headers");
if (!p1 || !p2) return;
Check(p1->ud.text == std::string(153, 'A') && p2->ud.text == "BBBBB", "the segments' texts");
Check(!r.Add(*p2, 10.0) && r.Pending() == 1, "the second segment first: nothing yet");
auto whole = r.Add(*p1, 11.0);
Check(whole && whole->ud.text == std::string(153, 'A') + "BBBBB" && r.Pending() == 0, "the first segment completes the message in order");
auto lone = ParseDeliver(Hex("040B911316325476F800006201612205008004D4F29C0E"));
Check(r.Add(*lone, 12.0).has_value() && r.Pending() == 0, "a message without a header is complete as it is");
auto k = ParseDeliver(Hex("440B911316325476F80000620161220500800D060804123403029576F91C06"));
Check(!r.Add(*k, 100.0) && r.Pending() == 1, "one of three: pending");
auto dropped = r.Purge(701.0, 600.0);
Check(r.Pending() == 0 && dropped.size() == 1 && dropped[0].from == "+31612345678" && dropped[0].ref == 0x1234 && dropped[0].total == 3 && dropped[0].held == 1, "a set older than maxAge is dropped and named: sender, reference, total, segments held");
// a UCS-2 surrogate pair a sender split at the segment boundary (cut at 67 units blindly): whole again, in either arrival order
auto s1 = ParseDeliver(Hex("440B911316325476F80008620161220500808C0500032A0201" + Rep("00FC", 66) + "D83D"));
auto s2 = ParseDeliver(Hex("440B911316325476F8000862016122050080100500032A0202DE00" + Rep("0078", 4)));
Check(s1 && s2 && s1->ud.text == Rep("ü", 66) + "<EFBFBD>" && s2->ud.text == "<EFBFBD>xxxx", "the split pair: each segment alone decodes its half as U+FFFD");
if (!s1 || !s2) return;
Check(!r.Add(*s1, 20.0) && r.Pending() == 1, "the split pair: segment 1 alone, nothing yet");
auto w12 = r.Add(*s2, 21.0);
Check(w12 && w12->ud.text == Rep("ü", 66) + "😀xxxx" && r.Pending() == 0, "the split pair: whole again from the joined units (1 then 2)");
Check(!r.Add(*s2, 22.0), "the split pair: segment 2 alone, nothing yet");
auto w21 = r.Add(*s1, 23.0);
Check(w21 && w21->ud.text == Rep("ü", 66) + "😀xxxx" && r.Pending() == 0, "the split pair: whole again (2 then 1)");
// a GSM 7-bit escape pair split the same way: ESC ends segment 1, the extension code starts segment 2
auto g1 = ParseDeliver(Hex("440B911316325476F8000062016122050080090500032B0201" + Hex(PackSeptets(Bytes{0x41, 0x1B}, 1))));
auto g2 = ParseDeliver(Hex("440B911316325476F8000062016122050080090500032B0202" + Hex(PackSeptets(Bytes{0x65, 0x42}, 1))));
Check(g1 && g2 && g1->ud.text == "A " && g2->ud.text == "eB", "the split escape pair: a space and a stray e, segment by segment");
if (!g1 || !g2) return;
Check(!r.Add(*g1, 30.0), "the split escape pair: segment 1 alone, nothing yet");
auto wg = r.Add(*g2, 31.0);
Check(wg && wg->ud.text == "A€B" && r.Pending() == 0, "the split escape pair: whole again from the joined septets");
}
void TestHeaderAndDcs() {
auto h = ParseUserDataHeader(Hex("0003010201"));
Check(h.valid && h.concat && h.concat->ref == 1 && h.concat->total == 2 && h.concat->seq == 1, "concatenation IE");
Check(!ParseUserDataHeader(Hex("0003010001")).concat, "a zero total is ignored");
Check(!ParseUserDataHeader(Hex("0003010203")).concat, "a sequence past the total is ignored");
Check(!ParseUserDataHeader(Hex("00030102")).valid, "an element overrunning the header: the whole header is ignored");
Check(ParseUserDataHeader(Hex("7F02AABB0003050201")).concat.has_value(), "an unknown element is skipped");
Check(DecodeDcs(0x00).alphabet == Alphabet::Gsm7 && !DecodeDcs(0x00).msgClass, "DCS 00");
Check(DecodeDcs(0x08).alphabet == Alphabet::Ucs2, "DCS 08: UCS-2");
Check(DecodeDcs(0x11).alphabet == Alphabet::Gsm7 && DecodeDcs(0x11).msgClass == 1, "DCS 11: class 1");
Check(DecodeDcs(0xF6).alphabet == Alphabet::Octet && DecodeDcs(0xF6).msgClass == 2, "DCS F6: 8-bit class 2");
Check(DecodeDcs(0xD8).messageWaiting && DecodeDcs(0xD8).alphabet == Alphabet::Gsm7, "DCS D8: message waiting, 7-bit");
Check(DecodeDcs(0xE0).messageWaiting && DecodeDcs(0xE0).alphabet == Alphabet::Ucs2, "DCS E0: message waiting, UCS-2");
Check(DecodeDcs(0x24).compressed && DecodeDcs(0x24).alphabet == Alphabet::Octet, "DCS 24: compressed 8-bit");
Check(DecodeDcs(0x0C).alphabet == Alphabet::Gsm7 && DecodeDcs(0x9F).alphabet == Alphabet::Gsm7, "reserved codings read as the default alphabet");
Check(DecodeDcs(0x48).alphabet == Alphabet::Ucs2 && DecodeDcs(0x51).msgClass == 1 && !DecodeDcs(0x48).messageWaiting && DecodeDcs(0x74).compressed && DecodeDcs(0x74).alphabet == Alphabet::Octet, "DCS 48, 51, 74: the group marked for automatic deletion, read as the general one");
Check(DecodeDcs(0xC8).messageWaiting && DecodeDcs(0xC8).alphabet == Alphabet::Gsm7 && !DecodeDcs(0xC8).msgClass, "DCS C8: message waiting, discard");
Check(DecodeDcs(0x84).alphabet == Alphabet::Gsm7 && DecodeDcs(0xB4).alphabet == Alphabet::Gsm7 && !DecodeDcs(0xB4).compressed && !DecodeDcs(0xB4).msgClass && !DecodeDcs(0xB0).messageWaiting, "DCS 84, B0, B4: the reserved groups read as 00000000");
}
void TestReports() {
auto sr = ParseStatusReport(Hex("062A0B911316325476F8620161220500806201612205708000"));
Check(sr && sr->mr == 0x2A && sr->recipient.Number() == "+31612345678" && sr->scts == "2026-10-16T22:50:00+02:00" && sr->dischargeTime == "2026-10-16T22:50:07+02:00" && sr->status == 0, "SMS-STATUS-REPORT");
Check(!ParseStatusReport(Hex("062A0B9113")), "a truncated status report");
EqS(StatusText(0x00), "delivered", "TP-ST 0");
EqS(StatusText(0x46), "validity period expired", "TP-ST 46");
EqS(StatusText(0x30), "temporary error 0x30, the SC is retrying", "TP-ST 30: an SC-specific temporary value");
EqS(StatusText(0x50), "permanent error 0x50", "TP-ST 50: an SC-specific permanent value");
EqS(StatusText(0x62), "no response from the recipient, the SC has stopped trying", "TP-ST 62: a temporary error, the SC not trying any more");
EqS(StatusText(0x70), "temporary error 0x70, the SC has stopped trying", "TP-ST 70: an SC-specific value of that class");
EqS(StatusText(0x03), "service rejected, the SC has stopped trying (reserved status 0x03)", "TP-ST 03: a reserved value, in words");
EqS(StatusText(0x80), "service rejected, the SC has stopped trying (reserved status 0x80)", "TP-ST 80: bit 7 set, in words");
bool asRead = true;
for (int v = 0; v < 256; v++) {
const bool reserved = (v >= 0x03 && v <= 0x0F) || (v >= 0x26 && v <= 0x2F) || (v >= 0x4A && v <= 0x4F) || (v >= 0x66 && v <= 0x6F) || v >= 0x80;
if (StatusAsRead(static_cast<std::uint8_t>(v)) != (reserved ? 0x63 : v)) asRead = false;
}
Check(asRead, "TP-ST: 9.2.3.15's reserved values (0x03-0x0F, 0x26-0x2F, 0x4A-0x4F, 0x66-0x6F, and bit 7 set) are read as Service Rejected (0x63), every other value as it is");
Check(KindOfTpdu(Hex("062A")) == TpduKind::StatusReport && KindOfTpdu(Hex("04")) == TpduKind::Deliver && KindOfTpdu(Hex("01")) == TpduKind::SubmitReport && KindOfTpdu(Hex("03")) == TpduKind::Reserved, "TP-MTI, SC to MS");
auto ack = ParseSubmitReport(Hex("010062016122050080"), false);
Check(ack && !ack->failureCause && ack->scts == "2026-10-16T22:50:00+02:00", "SMS-SUBMIT-REPORT for RP-ACK");
auto err = ParseSubmitReport(Hex("01C30062016122050080"), true);
Check(err && err->failureCause == 0xC3 && err->scts == "2026-10-16T22:50:00+02:00", "SMS-SUBMIT-REPORT for RP-ERROR");
bool unusedBits = true;
for (int bit : {7, 5, 4, 3, 2}) {
auto unused = ParseSubmitReport(Hex(std::format("{:02X}C30062016122050080", 0x01 | (1 << bit))), true);
if (!unused || unused->failureCause != 0xFF || !unused->scts.empty()) unusedBits = false;
}
Check(unusedBits, "SMS-SUBMIT-REPORT for RP-ERROR with one of the unused bits of its first octet set (7, 5, 4, 3, 2): the cause is unspecified, nothing else examined (9.2.2.2a)");
auto alone = ParseSubmitReport(Hex("81"), true);
Check(alone && alone->failureCause == 0xFF, "the same for such a first octet with nothing after it");
auto udhi = ParseSubmitReport(Hex("41C30062016122050080"), true);
Check(udhi && udhi->failureCause == 0xC3, "TP-UDHI (bit 6) is no unused bit: the cause as sent");
EqS(ScTimeStamp(Hex("621AF12205A0A0")), "2026-01-10T22:50:00+00:00", "SCTS: a semi-octet that is no digit reads as 0, in the zone too (9.2.3.11)");
EqS(FailureCauseText(0xC3), "invalid SME address", "TP-FCS C3");
Check(FcsDuplicateRejected == 0xC5, "TP-FCS C5 is the duplicate rejection (9.2.3.22)");
EqS(FailureCauseText(FcsDuplicateRejected), "duplicate short message rejected", "TP-FCS C5 in words");
Eq(DeliverReportAck(), "0000", "SMS-DELIVER-REPORT for RP-ACK");
Eq(DeliverReportError(0xFF), "00FF00", "SMS-DELIVER-REPORT for RP-ERROR");
}
void TestRp() {
const Bytes classic = Hex("11000B916407281553F80000AA0AE8329BFD4697D9EC37");
Eq(BuildRpData(0x2A, Hex(KpnSc), classic), "002A00" + std::string(KpnSc) + "1711000B916407281553F80000AA0AE8329BFD4697D9EC37", "RP-DATA MS to network");
Eq(BuildRpAck(5, DeliverReportAck()), "020541020000", "RP-ACK MS to network with the delivery report");
Eq(BuildRpAck(5), "0205", "RP-ACK MS to network, bare");
Eq(BuildRpError(5, 111, DeliverReportError(0xFF)), "0405016F410300FF00", "RP-ERROR MS to network");
auto mo = ParseRp(BuildRpData(0x2A, Hex(KpnSc), classic), false);
Check(mo && mo->type == RpType::DataMo && mo->mr == 0x2A && mo->sc && mo->sc->Number() == "+31653131313" && mo->tpdu == classic, "our RP-DATA round-trips");
Check(!ParseRp(BuildRpData(0x2A, Hex(KpnSc), classic), true), "an MS-to-network type read as the network's: refused");
auto mt = ParseRp(Hex("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"));
Check(mt && mt->type == RpType::DataMt && mt->mr == 0x11 && mt->sc && mt->sc->Number() == "+31653131313" && mt->tpdu.size() == 30 && KindOfTpdu(mt->tpdu) == TpduKind::Deliver, "RP-DATA network to MS");
Check(!ParseRp(Hex("011107911356131313F3001E040B91")), "a truncated RP-DATA");
auto ackMt = ParseRp(Hex("032A4109010062016122050080"));
Check(ackMt && ackMt->type == RpType::AckMt && ackMt->mr == 0x2A && ackMt->tpdu.size() == 9 && KindOfTpdu(ackMt->tpdu) == TpduKind::SubmitReport, "RP-ACK network to MS with a submit report");
auto bare = ParseRp(Hex("032A"));
Check(bare && bare->type == RpType::AckMt && bare->tpdu.empty(), "a bare RP-ACK");
auto errMt = ParseRp(Hex("052A011C410A01C30062016122050080"));
Check(errMt && errMt->type == RpType::ErrorMt && errMt->cause == 28 && !errMt->diagnostic && errMt->tpdu.size() == 10, "RP-ERROR network to MS with a submit report");
EqS(RpCauseText(28), "unidentified subscriber", "RP cause 28");
// a submission's RP-ERROR invites another attempt at once for cause 41 (TS 24.011 Annex E-2) and for a value table 8.4's part 1 does not list (treated as 41)
{
const std::set<int> listed{1, 8, 10, 11, 21, 27, 28, 29, 30, 38, 41, 42, 47, 50, 69, 81, 95, 96, 97, 98, 99, 111, 127};
bool asTabled = true;
for (int cause = 0; cause < 128; cause++)
if (RpCauseIsTemporary(static_cast<std::uint8_t>(cause)) != (cause == 41 || !listed.contains(cause))) asTabled = false;
Check(asTabled && listed.size() == 23, "RpCauseIsTemporary over the 128 cause values: 41, and whatever part 1's 23 do not list");
Check(RpCauseIsTemporary(41) && RpCauseIsTemporary(0x80 | 41) && !RpCauseIsTemporary(28) && !RpCauseIsTemporary(0x80 | 28) && RpCauseIsTemporary(2) && !RpCauseIsTemporary(11), "RpCauseIsTemporary: the extension bit is no part of the value; an unlisted 2 invites a repeat, the reserved 11 is listed");
}
auto diag = ParseRp(Hex("0507022611"));
Check(diag && diag->cause == 38 && diag->diagnostic == 0x11 && diag->tpdu.empty(), "RP-ERROR with a diagnostic octet");
Check(!ParseRp(Hex("05")), "one byte: nothing");
auto sr = ParseRp(Hex("011207911356131313F30019062A0B911316325476F8620161220500806201612205708000"));
Check(sr && KindOfTpdu(sr->tpdu) == TpduKind::StatusReport, "RP-DATA carrying a status report");
}
void TestSmsp() {
const std::string record = std::string(30, 'F') + "ED" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFA9";
auto p = ParseSmsp(Hex(record));
Check(p.has_value(), "the KPN SIM's EF_SMSP record parses");
if (p) {
EqS(p->scNumber, "+31653131313", "EF_SMSP: the service centre");
Eq(p->scAddress, KpnSc, "EF_SMSP: the RP-DA bytes");
Check(p->validity == 0xA9 && p->alpha.empty(), "EF_SMSP: validity A9, no alpha identifier");
}
const std::string named = "4B504EFF" + std::string(22, 'F') + "ED" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFFF";
auto n = ParseSmsp(Hex(named));
Check(n && n->alpha == "KPN" && n->validity == 0xFF, "EF_SMSP with an alpha identifier");
Check(!ParseSmsp(Hex("FFFF")), "a short record");
Check(!ParseSmsp(Hex(std::string(30, 'F') + "EF" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFA9")), "TP-SCA marked absent");
Check(!ParseSmsp(Hex(std::string(30, 'F') + "ED" + std::string(24, 'F') + "FF911356131313F3" + std::string(8, 'F') + "FFFFA9")), "an unused TP-SCA");
const std::string qmicli =
"[qrtr://0] Successfully read information from the UIM:\n"
"Card result:\n\tSW1: '0x90'\n\tSW2: '0x00'\n"
"Read result:\n\tFF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:ED:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:\n"
"\tFF:FF:07:91:13:56:13:13:13:F3:FF:FF:FF:FF:FF:FF:A9\n";
auto b = ParseQmicliReadResult(qmicli);
Check(b.size() == 43, "qmicli's hex dump: 43 bytes");
auto q = ParseSmsp(b);
Check(q && q->scNumber == "+31653131313", "EF_SMSP straight from qmicli's output");
Check(ParseQmicliReadResult("error: couldn't read").empty(), "no marker: no bytes");
}
}
int main() {
TestAlphabet();
TestAddresses();
TestSubmit();
TestDeliver();
TestReassembly();
TestHeaderAndDcs();
TestReports();
TestRp();
TestSmsp();
if (Failures == 0) std::println("Sms: all tests passed");
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that
}