imsd/interfaces/Imsd-Sms.cppm

1071 lines
50 KiB
Text
Raw Normal View History

sms: the short message codecs of TS 23.038, 23.040 and 24.011, and EF_SMSP SMS over IP (TS 24.341) carries the bytes a 2G/3G phone puts in an RP-DATA inside a SIP MESSAGE body of type application/vnd.3gpp.sms, so imsd needs the whole stack below SIP once it owns SMS on a carrier whose modem IMS is off: the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 for everything else (TS 23.038); SMS-SUBMIT built per segment with the concatenation header, SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed, the SMS-DELIVER-REPORT that acknowledges a delivery, the user-data header and the reassembly of a concatenated message (TS 23.040); RP-DATA, RP-ACK and RP-ERROR in both directions with their causes (TS 24.011); and EF_SMSP, where the (U)SIM names the service centre the RP-DATA is addressed to (TS 31.102 4.2.27, the KPN SIM's record read on the dev phone on 2026-10-16: +31653131313). A new partition, Imsd:Sms, pure std with no SIP, clock or I/O; tests/Sms checks it against the classic public PDU vectors ("hellohello", the "How are you?" SMS-DELIVER) and vectors cross-generated by an independent Python reference. A concatenated set with one alphabet throughout is decoded from its segments' joined units — the septets, or the UTF-16BE octets — not from the segments' texts, so a surrogate pair or an escape pair a sender cut at a segment boundary comes out whole; a U+0000 in UCS-2 decodes as U+FFFD, since no text means it and a D-Bus string cannot carry it. A status report's TP-ST is read as TS 23.040 9.2.3.15 has the MS read it: a reserved value, any with bit 7 set among them, as "Service Rejected" — a temporary error after which the SC is not making any more transfer attempts (StatusAsRead, pinned over all 256 values; StatusText has the clause's four classes in words). Three more readings follow their clauses the same way, each pinned: a time stamp semi-octet that is no digit reads as 0 (9.2.3.11); `1111` before an address's last semi-octet is skipped, not taken for its end (9.1.2.3); an SMS-SUBMIT-REPORT for RP-ERROR with an unused bit of its first octet set gives TP-FCS 0xFF, unspecified, with nothing else examined (9.2.2.2a).
2026-10-16 23:11:24 +02:00
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Imsd:Sms — the short message codecs SMS over IP rides on (TS 24.341 carries
the same bytes a 2G/3G phone puts in an RP-DATA, inside a SIP MESSAGE body of
type application/vnd.3gpp.sms):
- TS 23.038: the GSM 7-bit default alphabet with its extension table, the
septet packing, and UCS-2 (UTF-16BE on the wire) for everything else;
- TS 23.040: the SM-TL PDUs — SMS-SUBMIT built (one per segment, with the
concatenation header when the text needs more than one), SMS-DELIVER,
SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed, the SMS-DELIVER-REPORT
that acknowledges a delivery, the user-data header (concatenation, the
application ports) and the reassembly of a concatenated message;
- TS 24.011: the SM-RL messages — RP-DATA, RP-ACK, RP-ERROR — in both
directions, and their cause values;
- TS 31.102 §4.2.27: EF_SMSP, where the (U)SIM names the service centre the
RP-DATA is addressed to.
Byte-level only: no SIP, no clock, no I/O. tests/Sms checks it
against the classic public PDU vectors ("hellohello", the "How are you?"
SMS-DELIVER) and vectors cross-generated by an independent reference.
*/
export module Imsd:Sms;
import std;
namespace imsd::sms {
using Bytes = std::vector<std::uint8_t>;
// TS 23.038 6.2.1, the GSM 7-bit default alphabet; 0x1B is the escape
// to the extension table (its own entry is a placeholder — the ESC
// character itself is not encodable).
constexpr std::array<char16_t, 128> Gsm7Table = {
u'@', u'£', u'$', u'¥', u'è', u'é', u'ù', u'ì', u'ò', u'Ç', u'\n', u'Ø', u'ø', u'\r', u'Å', u'å',
u'Δ', u'_', u'Φ', u'Γ', u'Λ', u'Ω', u'Π', u'Ψ', u'Σ', u'Θ', u'Ξ', u'\u001B', u'Æ', u'æ', u'ß', u'É',
u' ', u'!', u'"', u'#', u'¤', u'%', u'&', u'\'', u'(', u')', u'*', u'+', u',', u'-', u'.', u'/',
u'0', u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9', u':', u';', u'<', u'=', u'>', u'?',
u'¡', u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'I', u'J', u'K', u'L', u'M', u'N', u'O',
u'P', u'Q', u'R', u'S', u'T', u'U', u'V', u'W', u'X', u'Y', u'Z', u'Ä', u'Ö', u'Ñ', u'Ü', u'§',
u'¿', u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'o',
u'p', u'q', u'r', u's', u't', u'u', u'v', u'w', u'x', u'y', u'z', u'ä', u'ö', u'ñ', u'ü', u'à',
};
constexpr std::uint8_t Gsm7Escape = 0x1B;
// TS 23.038 6.2.1.1, the extension table: <ESC><code> pairs.
constexpr std::array<std::pair<std::uint8_t, char16_t>, 10> Gsm7Ext = {{
{0x0A, u'\u000C'}, {0x14, u'^'}, {0x28, u'{'}, {0x29, u'}'}, {0x2F, u'\\'},
{0x3C, u'['}, {0x3D, u'~'}, {0x3E, u']'}, {0x40, u'|'}, {0x65, u'€'},
}};
// UTF-8 → code points; a byte that starts no sequence, or starts one cut
// short or with a byte that does not continue it, yields U+FFFD and is
// passed over alone. The value is not checked: an overlong form, a
// surrogate or one past U+10FFFF is taken as it is.
std::vector<char32_t> Utf8Decode(std::string_view s) {
std::vector<char32_t> out;
std::size_t i = 0;
while (i < s.size()) {
const std::uint8_t b = static_cast<std::uint8_t>(s[i]);
std::size_t n = 0;
char32_t cp = 0;
if (b < 0x80) { cp = b; n = 1; }
else if ((b & 0xE0) == 0xC0) { cp = b & 0x1F; n = 2; }
else if ((b & 0xF0) == 0xE0) { cp = b & 0x0F; n = 3; }
else if ((b & 0xF8) == 0xF0) { cp = b & 0x07; n = 4; }
else { out.push_back(0xFFFD); i++; continue; }
if (i + n > s.size()) { out.push_back(0xFFFD); i++; continue; }
bool ok = true;
for (std::size_t k = 1; k < n; k++) {
const std::uint8_t c = static_cast<std::uint8_t>(s[i + k]);
if ((c & 0xC0) != 0x80) { ok = false; break; }
cp = (cp << 6) | (c & 0x3F);
}
if (!ok) { out.push_back(0xFFFD); i++; continue; }
out.push_back(cp);
i += n;
}
return out;
}
void Utf8Append(std::string& s, char32_t cp) {
if (cp < 0x80) { s.push_back(static_cast<char>(cp)); return; }
if (cp < 0x800) {
s.push_back(static_cast<char>(0xC0 | (cp >> 6)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
return;
}
if (cp < 0x10000) {
s.push_back(static_cast<char>(0xE0 | (cp >> 12)));
s.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
return;
}
s.push_back(static_cast<char>(0xF0 | (cp >> 18)));
s.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
s.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
// Called Party BCD digits (TS 24.008 10.5.4.7): 0-9, then * # a b c as
// 0xA..0xE; 0xF ends an odd-length value.
constexpr std::string_view BcdDigits = "0123456789*#abc";
std::optional<std::uint8_t> BcdOf(char c) {
const std::size_t i = BcdDigits.find(c);
if (i == std::string_view::npos) return std::nullopt;
return static_cast<std::uint8_t>(i);
}
std::uint8_t Byte(std::span<const std::uint8_t> b, std::size_t i) { return i < b.size() ? b[i] : 0; }
}
export namespace imsd::sms {
using Bytes = std::vector<std::uint8_t>;
// ---- TS 23.038: alphabets -------------------------------------------
enum class Alphabet { Gsm7, Octet, Ucs2 };
// The text as GSM 7-bit septets (an extension character as the ESC
// pair); nullopt when a character is outside the alphabet and its
// extension — the caller then sends UCS-2.
std::optional<Bytes> Gsm7Septets(std::string_view utf8) {
Bytes out;
for (char32_t cp : Utf8Decode(utf8)) {
bool found = false;
for (std::size_t i = 0; i < Gsm7Table.size(); i++)
if (i != Gsm7Escape && static_cast<char32_t>(Gsm7Table[i]) == cp) { out.push_back(static_cast<std::uint8_t>(i)); found = true; break; }
if (found) continue;
for (const auto& [code, u] : Gsm7Ext)
if (static_cast<char32_t>(u) == cp) { out.push_back(Gsm7Escape); out.push_back(code); found = true; break; }
if (!found) return std::nullopt;
}
return out;
}
// Septets → UTF-8. An escape to a code the extension table does not
// define shows the main table's character (TS 23.038 6.2.1.1); an escape
// to another extension table (ESC ESC) a space (6.2.1.1 NOTE 1), and so
// does a trailing escape.
std::string Gsm7Text(std::span<const std::uint8_t> septets) {
std::string s;
for (std::size_t i = 0; i < septets.size(); i++) {
const std::uint8_t c = septets[i] & 0x7F;
if (c != Gsm7Escape) { Utf8Append(s, Gsm7Table[c]); continue; }
if (i + 1 >= septets.size()) { s.push_back(' '); break; }
const std::uint8_t n = septets[++i] & 0x7F;
if (n == Gsm7Escape) { s.push_back(' '); continue; }
bool hit = false;
for (const auto& [code, u] : Gsm7Ext)
if (code == n) { Utf8Append(s, u); hit = true; break; }
if (!hit) Utf8Append(s, Gsm7Table[n]);
}
return s;
}
// TS 23.038 6.1.2.1.1: septets packed LSB first into octets, `fill`
// zero bits before the first septet (the padding that brings a
// user-data header to a septet boundary, TS 23.040 9.2.3.24).
Bytes PackSeptets(std::span<const std::uint8_t> septets, int fill = 0) {
const std::size_t bits = static_cast<std::size_t>(fill) + septets.size() * 7;
Bytes out((bits + 7) / 8, 0);
std::size_t p = static_cast<std::size_t>(fill);
for (std::uint8_t s : septets) {
for (int i = 0; i < 7; i++, p++)
if ((s >> i) & 1) out[p / 8] |= static_cast<std::uint8_t>(1u << (p % 8));
}
return out;
}
// `count` septets out of `octets`, skipping `fill` bits first; stops
// short when the octets run out.
Bytes UnpackSeptets(std::span<const std::uint8_t> octets, std::size_t count, int fill = 0) {
Bytes out;
const std::size_t total = octets.size() * 8;
std::size_t p = static_cast<std::size_t>(fill);
for (std::size_t n = 0; n < count && p + 7 <= total; n++) {
std::uint8_t v = 0;
for (int i = 0; i < 7; i++, p++)
if ((octets[p / 8] >> (p % 8)) & 1) v |= static_cast<std::uint8_t>(1u << i);
out.push_back(v);
}
return out;
}
// UTF-8 → UTF-16BE units (a code point beyond the BMP as a surrogate
// pair).
std::vector<char16_t> Utf16Units(std::string_view utf8) {
std::vector<char16_t> out;
for (char32_t cp : Utf8Decode(utf8)) {
if (cp < 0x10000) { out.push_back(static_cast<char16_t>(cp)); continue; }
cp -= 0x10000;
out.push_back(static_cast<char16_t>(0xD800 + (cp >> 10)));
out.push_back(static_cast<char16_t>(0xDC00 + (cp & 0x3FF)));
}
return out;
}
Bytes Ucs2Bytes(std::span<const char16_t> units) {
Bytes out;
for (char16_t u : units) {
out.push_back(static_cast<std::uint8_t>(u >> 8));
out.push_back(static_cast<std::uint8_t>(u & 0xFF));
}
return out;
}
Bytes Ucs2Encode(std::string_view utf8) { return Ucs2Bytes(Utf16Units(utf8)); }
// UTF-16BE bytes → UTF-8; a lone surrogate, a trailing odd byte or a
// U+0000 (no text means it, and a D-Bus string cannot carry it) yields
// U+FFFD.
std::string Ucs2Decode(std::span<const std::uint8_t> b) {
std::string s;
for (std::size_t i = 0; i + 1 < b.size(); i += 2) {
char32_t u = static_cast<char32_t>((b[i] << 8) | b[i + 1]);
if (u >= 0xD800 && u < 0xDC00 && i + 3 < b.size()) {
const char32_t lo = static_cast<char32_t>((b[i + 2] << 8) | b[i + 3]);
if (lo >= 0xDC00 && lo < 0xE000) { u = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00); i += 2; }
else u = 0xFFFD;
} else if (u >= 0xD800 && u < 0xE000) u = 0xFFFD;
if (u == 0) u = 0xFFFD;
Utf8Append(s, u);
}
if (b.size() % 2) Utf8Append(s, 0xFFFD);
return s;
}
// ---- TS 23.040 9.1.2.5 / TS 24.011 8.2.5: addresses ------------------
// Type-of-address octets: bit 7 set, type of number in bits 6-4,
// numbering plan in bits 3-0.
constexpr std::uint8_t ToaInternational = 0x91; // E.164, international
constexpr std::uint8_t ToaUnknown = 0x81; // E.164, as dialled (a short code, a national number)
constexpr std::uint8_t ToaAlphanumeric = 0xD0; // GSM 7-bit text, no numbering plan
struct Address {
std::uint8_t toa = ToaUnknown;
std::string digits; // the digits (0-9 * # a b c), or the text of an alphanumeric sender
bool International() const { return (toa & 0x70) == 0x10; }
bool Alphanumeric() const { return (toa & 0x70) == 0x50; }
// "+<digits>" for an international number, the digits or the text otherwise.
std::string Number() const { return International() ? "+" + digits : digits; }
// A number as a user types it: "+…" is international; anything else
// (a short code, a national number) goes as dialled with the type
// "unknown", which the network reads by its own dialling plan.
// Spaces, dashes and dots are dropped. Digits, `*` and `#` only: the
// BCD table's a, b and c are decoded, never dialled. At most 20
// digits, what an address field holds (9.1.2.5) — so a number this
// accepts is one the encoders accept.
static std::optional<Address> ForNumber(std::string_view number) {
Address a;
std::string n;
for (char c : number)
if (c != ' ' && c != '-' && c != '.') n.push_back(c);
if (n.starts_with('+')) { a.toa = ToaInternational; n.erase(0, 1); }
if (n.empty() || n.size() > 20) return std::nullopt;
for (char c : n)
if (!(std::isdigit(static_cast<unsigned char>(c)) || c == '*' || c == '#')) return std::nullopt;
a.digits = n;
return a;
}
};
// Semi-octet digits, the first digit in the low nibble, 0xF closing an
// odd count; nullopt for a character that is no BCD digit.
std::optional<Bytes> EncodeBcd(std::string_view digits) {
Bytes out;
for (std::size_t i = 0; i < digits.size(); i += 2) {
auto lo = BcdOf(digits[i]);
if (!lo) return std::nullopt;
std::uint8_t hi = 0xF;
if (i + 1 < digits.size()) {
auto h = BcdOf(digits[i + 1]);
if (!h) return std::nullopt;
hi = *h;
}
out.push_back(static_cast<std::uint8_t>(*lo | (hi << 4)));
}
return out;
}
// Up to `nDigits` digits out of semi-octets. A 0xF is fill and is
// skipped wherever it stands: one before the last semi-octet does not
// end the value (9.1.2.3).
std::string DecodeBcd(std::span<const std::uint8_t> b, std::size_t nDigits) {
std::string s;
for (std::size_t i = 0; i < nDigits; i++) {
const std::uint8_t n = i % 2 ? Byte(b, i / 2) >> 4 : Byte(b, i / 2) & 0xF;
if (n == 0xF) continue;
s.push_back(BcdDigits[n]);
}
return s;
}
// The SM-TL address field: [digits][type-of-address][value] — the length
// counts semi-octets (TS 23.040 9.1.2.5); an alphanumeric value is 7-bit
// packed text and its length the useful semi-octets, ceil(7n/4).
std::optional<Bytes> EncodeTpAddress(const Address& a) {
Bytes out;
if (a.Alphanumeric()) {
auto sep = Gsm7Septets(a.digits);
if (!sep) return std::nullopt;
Bytes packed = PackSeptets(*sep);
out.push_back(static_cast<std::uint8_t>((sep->size() * 7 + 3) / 4));
out.push_back(a.toa);
out.insert(out.end(), packed.begin(), packed.end());
return out;
}
auto bcd = EncodeBcd(a.digits);
if (!bcd || a.digits.empty() || a.digits.size() > 20) return std::nullopt;
out.push_back(static_cast<std::uint8_t>(a.digits.size()));
out.push_back(a.toa);
out.insert(out.end(), bcd->begin(), bcd->end());
return out;
}
// Reads an SM-TL address field at `pos`, advancing it; nullopt when the
// bytes run out.
std::optional<Address> DecodeTpAddress(std::span<const std::uint8_t> b, std::size_t& pos) {
if (pos + 2 > b.size()) return std::nullopt;
const std::size_t len = b[pos];
const std::size_t octets = (len + 1) / 2;
if (pos + 2 + octets > b.size()) return std::nullopt;
Address a;
a.toa = b[pos + 1];
auto value = b.subspan(pos + 2, octets);
if (a.Alphanumeric()) a.digits = Gsm7Text(UnpackSeptets(value, len * 4 / 7));
else a.digits = DecodeBcd(value, len);
pos += 2 + octets;
return a;
}
// The SM-RL address (TS 24.011 8.2.5.1/8.2.5.2) as the LV it travels
// as: [octets][type-of-address][digits] — the length counts octets.
std::optional<Bytes> EncodeRpAddress(const Address& a) {
auto bcd = EncodeBcd(a.digits);
if (!bcd || a.digits.empty() || a.digits.size() > 20) return std::nullopt;
Bytes out;
out.push_back(static_cast<std::uint8_t>(1 + bcd->size()));
out.push_back(a.toa);
out.insert(out.end(), bcd->begin(), bcd->end());
return out;
}
// The value of an SM-RL address (what follows its length): the
// type-of-address octet and the digits.
std::optional<Address> DecodeRpAddressValue(std::span<const std::uint8_t> v) {
if (v.empty()) return std::nullopt;
Address a;
a.toa = v[0];
a.digits = DecodeBcd(v.subspan(1), (v.size() - 1) * 2);
return a;
}
// ---- TS 23.040 9.2.3.11: TP-Service-Centre-Time-Stamp -----------------
// Seven semi-octet pairs (year, month, day, hour, minute, second, zone
// in quarter hours with its sign in bit 3 of the first semi-octet) as
// "2026-10-16T22:50:00+02:00", with the sender's offset.
// A semi-octet that is no digit reads as 0 (9.2.3.11).
std::string ScTimeStamp(std::span<const std::uint8_t> b) {
if (b.size() < 7) return {};
auto semi = [](int v) { return v > 9 ? 0 : v; };
auto digit = [&](std::size_t i) { return semi(Byte(b, i) & 0xF) * 10 + semi(Byte(b, i) >> 4); };
const int tzOctet = Byte(b, 6);
const int quarters = (tzOctet & 0x7) * 10 + semi(tzOctet >> 4);
const char sign = (tzOctet & 0x08) ? '-' : '+';
return std::format("20{:02}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}",
digit(0), digit(1), digit(2), digit(3), digit(4), digit(5), sign, quarters / 4, (quarters % 4) * 15);
}
// ---- TS 23.040 9.2.3.10 / TS 23.038 4: TP-Data-Coding-Scheme ----------
struct Coding {
Alphabet alphabet = Alphabet::Gsm7;
std::optional<int> msgClass; // 0-3 when the scheme carries a class
bool compressed = false; // TS 23.042 compression (not decoded)
bool messageWaiting = false; // a message-waiting indication group (the text, if any, is still shown)
};
Coding DecodeDcs(std::uint8_t dcs) {
Coding c;
const std::uint8_t group = dcs >> 4;
if (group <= 0x7) { // general data coding (00xx), marked for automatic deletion (01xx)
c.compressed = dcs & 0x20;
if (dcs & 0x10) c.msgClass = dcs & 0x03;
switch ((dcs >> 2) & 0x3) {
case 1: c.alphabet = Alphabet::Octet; break;
case 2: c.alphabet = Alphabet::Ucs2; break;
default: c.alphabet = Alphabet::Gsm7; break; // 0, and the reserved 3 (TS 23.038 4: as 00000000)
}
} else if (group >= 0xC && group <= 0xE) { // message waiting indication: discard / store 7-bit / store UCS-2
c.messageWaiting = true;
c.alphabet = group == 0xE ? Alphabet::Ucs2 : Alphabet::Gsm7;
} else if (group == 0xF) { // data coding / message class
c.alphabet = (dcs & 0x04) ? Alphabet::Octet : Alphabet::Gsm7;
c.msgClass = dcs & 0x03;
}
return c; // 1000..1011 reserved: as 00000000
}
constexpr std::uint8_t DcsGsm7 = 0x00;
constexpr std::uint8_t DcsUcs2 = 0x08;
// ---- TS 23.040 9.2.3.24: the user-data header -------------------------
struct Concat {
std::uint16_t ref = 0;
std::uint8_t total = 0;
std::uint8_t seq = 0;
};
struct UserDataHeader {
std::optional<Concat> concat; // IE 00 (8-bit reference) or 08 (16-bit)
std::optional<std::uint16_t> portDst; // IE 04/05: application port addressing
std::optional<std::uint16_t> portSrc;
bool valid = true; // false: an element overran the header (the whole header is ignored, 9.2.3.24)
};
// The elements of a header (its contents after the UDHL octet). A later
// occurrence of a non-repeatable element wins (9.2.3.24); a
// concatenation element with a zero total, a zero sequence or one past
// the total is ignored (9.2.3.24.1).
UserDataHeader ParseUserDataHeader(std::span<const std::uint8_t> h) {
UserDataHeader out;
std::size_t p = 0;
while (p < h.size()) {
if (p + 2 > h.size()) { out.valid = false; break; }
const std::uint8_t iei = h[p];
const std::size_t len = h[p + 1];
if (p + 2 + len > h.size()) { out.valid = false; break; }
auto d = h.subspan(p + 2, len);
if (iei == 0x00 && len == 3) {
if (d[1] != 0 && d[2] != 0 && d[2] <= d[1]) out.concat = Concat{d[0], d[1], d[2]};
} else if (iei == 0x08 && len == 4) {
if (d[2] != 0 && d[3] != 0 && d[3] <= d[2]) out.concat = Concat{static_cast<std::uint16_t>((d[0] << 8) | d[1]), d[2], d[3]};
} else if (iei == 0x04 && len == 2) {
out.portDst = d[0]; out.portSrc = d[1];
} else if (iei == 0x05 && len == 4) {
out.portDst = static_cast<std::uint16_t>((d[0] << 8) | d[1]);
out.portSrc = static_cast<std::uint16_t>((d[2] << 8) | d[3]);
}
p += 2 + len;
}
if (!out.valid) out = UserDataHeader{std::nullopt, std::nullopt, std::nullopt, false};
return out;
}
// The concatenation element with an 8-bit reference, as the header's
// contents (UDHL excluded): 00 03 <ref> <total> <seq>.
Bytes ConcatHeader(std::uint8_t ref, std::uint8_t total, std::uint8_t seq) { return {0x00, 0x03, ref, total, seq}; }
// ---- TS 23.040 9.2.2: the TPDUs ---------------------------------------
// The user data as the TPDU carries it: the header (if any), then the
// text or the octets.
struct UserData {
Alphabet alphabet = Alphabet::Gsm7;
UserDataHeader header;
bool hasHeader = false;
std::string text; // GSM 7-bit or UCS-2 decoded to UTF-8; empty for 8-bit data
Bytes units; // the text's undecoded units — septets for GSM 7-bit, UTF-16BE octets for UCS-2 — so a set's segments decode as one stream (Reassembler)
Bytes data; // 8-bit data after the header
};
// Decodes TP-UD given TP-UDL and TP-UDHI (9.2.3.16, 9.2.3.24): with a
// header and the 7-bit alphabet the text starts at the next septet
// boundary after it and the length counts the header's septets too;
// with UCS-2 or 8-bit data the length counts octets, header included.
// Short user data decodes as far as it goes.
UserData DecodeUserData(std::span<const std::uint8_t> ud, std::size_t udl, bool udhi, Alphabet alphabet) {
UserData out;
out.alphabet = alphabet;
std::size_t headerOctets = 0;
if (udhi && !ud.empty()) {
const std::size_t udhl = ud[0];
headerOctets = std::min(ud.size(), 1 + udhl);
out.hasHeader = true;
out.header = ParseUserDataHeader(ud.subspan(1, headerOctets - 1));
}
if (alphabet == Alphabet::Gsm7) {
const std::size_t headerSeptets = (headerOctets * 8 + 6) / 7;
const int fill = static_cast<int>(headerSeptets * 7 - headerOctets * 8);
const std::size_t count = udl > headerSeptets ? udl - headerSeptets : 0;
out.units = UnpackSeptets(ud.subspan(headerOctets), count, fill);
out.text = Gsm7Text(out.units);
return out;
}
const std::size_t count = udl > headerOctets ? std::min(udl - headerOctets, ud.size() - headerOctets) : 0;
auto payload = ud.subspan(headerOctets, count);
if (alphabet == Alphabet::Ucs2) { out.units.assign(payload.begin(), payload.end()); out.text = Ucs2Decode(payload); }
else out.data.assign(payload.begin(), payload.end());
return out;
}
// What a TPDU from the service centre is (9.2.3.1, the SC → MS reading
// of TP-MTI).
enum class TpduKind { Deliver, SubmitReport, StatusReport, Reserved };
TpduKind KindOfTpdu(std::span<const std::uint8_t> tpdu) {
switch (Byte(tpdu, 0) & 0x3) {
case 0: return TpduKind::Deliver;
case 1: return TpduKind::SubmitReport;
case 2: return TpduKind::StatusReport;
default: return TpduKind::Reserved; // processed as an SMS-DELIVER (9.2.3.1)
}
}
struct Deliver {
Address from;
std::uint8_t pid = 0;
std::uint8_t dcs = 0;
Coding coding;
std::string scts; // the service centre's time stamp (ScTimeStamp's text)
bool moreMessages = false; // TP-MMS: more are waiting at the SC
bool statusReportIndication = false;
bool replyPath = false;
UserData ud;
};
// An SMS-DELIVER (9.2.2.1). nullopt when the mandatory fields run out;
// a TP-MTI of reserved value is read as a DELIVER (9.2.3.1).
std::optional<Deliver> ParseDeliver(std::span<const std::uint8_t> b) {
if (b.empty()) return std::nullopt;
Deliver d;
const std::uint8_t first = b[0];
d.moreMessages = !(first & 0x04);
d.statusReportIndication = first & 0x20;
d.replyPath = first & 0x80;
const bool udhi = first & 0x40;
std::size_t pos = 1;
auto from = DecodeTpAddress(b, pos);
if (!from) return std::nullopt;
d.from = *from;
if (pos + 2 + 7 + 1 > b.size()) return std::nullopt;
d.pid = b[pos++];
d.dcs = b[pos++];
d.coding = DecodeDcs(d.dcs);
d.scts = ScTimeStamp(b.subspan(pos, 7));
pos += 7;
const std::size_t udl = b[pos++];
d.ud = DecodeUserData(b.subspan(pos), udl, udhi, d.coding.alphabet);
return d;
}
struct StatusReport {
std::uint8_t mr = 0; // the TP-MR of the SMS-SUBMIT it reports on
Address recipient;
std::string scts; // when the SC took the SMS-SUBMIT
std::string dischargeTime; // when the outcome happened
std::uint8_t status = 0; // TP-ST (9.2.3.15)
bool moreMessages = false;
};
// An SMS-STATUS-REPORT (9.2.2.3); the optional tail (TP-PI onwards) is
// not read.
std::optional<StatusReport> ParseStatusReport(std::span<const std::uint8_t> b) {
if (b.size() < 2) return std::nullopt;
StatusReport r;
r.moreMessages = !(b[0] & 0x04);
r.mr = b[1];
std::size_t pos = 2;
auto ra = DecodeTpAddress(b, pos);
if (!ra) return std::nullopt;
r.recipient = *ra;
if (pos + 15 > b.size()) return std::nullopt;
r.scts = ScTimeStamp(b.subspan(pos, 7));
r.dischargeTime = ScTimeStamp(b.subspan(pos + 7, 7));
r.status = b[pos + 14];
return r;
}
// TP-ST (9.2.3.15) as the MS is to read it. The octet's low seven bits
// make four classes of 32 values: the transaction completed (from
// 0x00), a temporary error with the SC still trying (0x20), and a
// permanent (0x40) and a temporary (0x60) error with the SC not making
// any more transfer attempts. Each names its first values, reserves the
// rest of its first sixteen and leaves the other sixteen to each SC. A
// reserved value — any with bit 7 set among them — is read as "Service
// Rejected" (0x63), as the clause has it.
constexpr std::uint8_t StatusAsRead(std::uint8_t st) {
constexpr std::uint8_t lastNamed[] = {0x02, 0x05, 0x09, 0x05}; // of each class, counted from its first value
if (st & 0x80) return 0x63;
const std::uint8_t within = st & 0x1F;
return (within >= 0x10 || within <= lastNamed[st >> 5]) ? st : 0x63;
}
// The same in words: a named value by its name, an SC's own by its
// class and number, a reserved one as the rejection it is read as,
// with the number that came.
std::string StatusText(std::uint8_t st) {
const std::uint8_t read = StatusAsRead(st);
if (read != st) return std::format("service rejected, the SC has stopped trying (reserved status 0x{:02x})", st);
switch (read) {
case 0x00: return "delivered";
case 0x01: return "forwarded, delivery unconfirmed";
case 0x02: return "replaced by the SC";
case 0x20: return "congestion, the SC is retrying";
case 0x21: return "recipient busy, the SC is retrying";
case 0x22: return "no response from the recipient, the SC is retrying";
case 0x23: return "service rejected, the SC is retrying";
case 0x24: return "quality of service not available, the SC is retrying";
case 0x25: return "error in the recipient, the SC is retrying";
case 0x40: return "remote procedure error";
case 0x41: return "incompatible destination";
case 0x42: return "connection rejected by the recipient";
case 0x43: return "not obtainable";
case 0x44: return "quality of service not available";
case 0x45: return "no interworking available";
case 0x46: return "validity period expired";
case 0x47: return "deleted by the originator";
case 0x48: return "deleted by the SC";
case 0x49: return "no longer exists";
case 0x60: return "congestion, the SC has stopped trying";
case 0x61: return "recipient busy, the SC has stopped trying";
case 0x62: return "no response from the recipient, the SC has stopped trying";
case 0x63: return "service rejected, the SC has stopped trying";
case 0x64: return "quality of service not available, the SC has stopped trying";
case 0x65: return "error in the recipient, the SC has stopped trying";
default: break;
}
if (read < 0x20) return std::format("completed, status 0x{:02x}", st);
if (read < 0x40) return std::format("temporary error 0x{:02x}, the SC is retrying", st);
if (read < 0x60) return std::format("permanent error 0x{:02x}", st);
return std::format("temporary error 0x{:02x}, the SC has stopped trying", st);
}
struct SubmitReport {
std::optional<std::uint8_t> failureCause; // TP-FCS, in the RP-ERROR shape only
std::string scts;
};
// An SMS-SUBMIT-REPORT (9.2.2.2a) — in an RP-ACK (the SC's time stamp)
// or an RP-ERROR (`ofError`: the failure cause first).
std::optional<SubmitReport> ParseSubmitReport(std::span<const std::uint8_t> b, bool ofError) {
SubmitReport r;
std::size_t pos = 1;
if (ofError) {
// bits 7 and 5-2 of the first octet are unused: with one of them set
// nothing else is examined and the cause is "unspecified" (9.2.2.2a)
if (!b.empty() && (b[0] & 0xBC)) { r.failureCause = 0xFF; return r; }
if (b.size() < 2) return std::nullopt;
r.failureCause = b[1]; pos = 2;
}
if (pos + 1 + 7 > b.size()) return std::nullopt;
r.scts = ScTimeStamp(b.subspan(pos + 1, 7));
return r;
}
// TP-FCS (9.2.3.22) in words.
std::string FailureCauseText(std::uint8_t fcs) {
switch (fcs) {
case 0x80: return "telematic interworking not supported";
case 0x81: return "short message type 0 not supported";
case 0x82: return "cannot replace short message";
case 0x8F: return "unspecified TP-PID error";
case 0x90: return "data coding scheme not supported";
case 0x91: return "message class not supported";
case 0x9F: return "unspecified TP-DCS error";
case 0xB0: return "TPDU not supported";
case 0xC0: return "SC busy";
case 0xC1: return "no SC subscription";
case 0xC2: return "SC system failure";
case 0xC3: return "invalid SME address";
case 0xC4: return "destination SME barred";
case 0xC5: return "duplicate short message rejected";
case 0xC6: return "TP-VPF not supported";
case 0xC7: return "TP-VP not supported";
case 0xD0: return "(U)SIM SMS storage full";
case 0xD1: return "no SMS storage capability in (U)SIM";
case 0xD2: return "error in MS";
case 0xD3: return "memory capacity exceeded";
case 0xFF: return "unspecified error";
default: return std::format("failure cause 0x{:02x}", fcs);
}
}
// The SMS-DELIVER-REPORT a delivery is acknowledged with (9.2.2.1a):
// for the RP-ACK the type octet and an empty parameter indicator; for
// the RP-ERROR the failure cause between them.
Bytes DeliverReportAck() { return {0x00, 0x00}; }
Bytes DeliverReportError(std::uint8_t fcs) { return {0x00, fcs, 0x00}; }
constexpr std::uint8_t FcsUnspecified = 0xFF;
constexpr std::uint8_t FcsTpduNotSupported = 0xB0;
// Segment capacities (9.2.3.24.1): a lone message, and one with the
// 8-bit-reference concatenation header (six octets: UDHL + 00 03 r t s).
constexpr std::size_t Gsm7Max = 160;
constexpr std::size_t Gsm7SegmentMax = 153;
constexpr std::size_t Ucs2Max = 70; // UTF-16 units
constexpr std::size_t Ucs2SegmentMax = 67;
constexpr std::size_t SegmentsMax = 255;
struct Submit {
std::string to;
std::uint8_t mr = 0; // TP-MR of the first segment; each further one takes the next (9.2.3.24.1)
std::optional<std::uint8_t> validity; // TP-VP, relative format (9.2.3.12.1); none: no TP-VP
bool statusReport = false; // TP-SRR
bool rejectDuplicates = false; // TP-RD
std::uint8_t pid = 0;
};
// The text split into segments of septets (7-bit) or UTF-16 units
// (UCS-2): one when it fits a lone message, else as many as the
// concatenated capacity needs; an escape pair or a surrogate pair is
// never split (9.2.3.24.1). nullopt when more than SegmentsMax would
// be needed.
std::optional<std::vector<std::vector<std::uint16_t>>> SplitText(std::string_view text, Alphabet& alphabet) {
std::vector<std::vector<std::uint16_t>> segments;
std::vector<std::uint16_t> units;
std::size_t lone = 0;
std::size_t per = 0;
auto isPairLead = [&](std::uint16_t u) {
return alphabet == Alphabet::Gsm7 ? u == Gsm7Escape : (u >= 0xD800 && u < 0xDC00);
};
if (auto sep = Gsm7Septets(text)) {
alphabet = Alphabet::Gsm7;
units.assign(sep->begin(), sep->end());
lone = Gsm7Max; per = Gsm7SegmentMax;
} else {
alphabet = Alphabet::Ucs2;
for (char16_t u : Utf16Units(text)) units.push_back(u);
lone = Ucs2Max; per = Ucs2SegmentMax;
}
if (units.size() <= lone) { segments.push_back(units); return segments; }
std::size_t i = 0;
while (i < units.size()) {
std::size_t n = std::min(per, units.size() - i);
if (n > 1 && i + n < units.size() && isPairLead(units[i + n - 1])) n--;
segments.emplace_back(units.begin() + static_cast<std::ptrdiff_t>(i), units.begin() + static_cast<std::ptrdiff_t>(i + n));
i += n;
if (segments.size() > SegmentsMax) return std::nullopt;
}
return segments;
}
// The SMS-SUBMIT TPDUs (9.2.2.2) for `text`: one per segment, the
// concatenation header on each when there are several (`concatRef`
// names the set), TP-MR counting up from `s.mr`. Empty when the
// destination is no number or the text needs too many segments.
std::vector<Bytes> BuildSubmits(const Submit& s, std::string_view text, std::uint8_t concatRef) {
std::vector<Bytes> out;
auto to = Address::ForNumber(s.to);
if (!to) return out;
auto da = EncodeTpAddress(*to);
if (!da) return out;
Alphabet alphabet = Alphabet::Gsm7;
auto segments = SplitText(text, alphabet);
if (!segments) return out;
const bool concat = segments->size() > 1;
for (std::size_t i = 0; i < segments->size(); i++) {
const auto& units = (*segments)[i];
std::uint8_t first = 0x01; // SMS-SUBMIT
if (s.rejectDuplicates) first |= 0x04;
if (s.validity) first |= 0x10; // TP-VPF relative
if (s.statusReport) first |= 0x20;
if (concat) first |= 0x40;
Bytes tpdu = {first, static_cast<std::uint8_t>((s.mr + i) & 0xFF)};
tpdu.insert(tpdu.end(), da->begin(), da->end());
tpdu.push_back(s.pid);
tpdu.push_back(alphabet == Alphabet::Gsm7 ? DcsGsm7 : DcsUcs2);
if (s.validity) tpdu.push_back(*s.validity);
Bytes header;
if (concat) {
Bytes ie = ConcatHeader(concatRef, static_cast<std::uint8_t>(segments->size()), static_cast<std::uint8_t>(i + 1));
header.push_back(static_cast<std::uint8_t>(ie.size()));
header.insert(header.end(), ie.begin(), ie.end());
}
if (alphabet == Alphabet::Gsm7) {
Bytes septets(units.begin(), units.end());
const std::size_t headerSeptets = (header.size() * 8 + 6) / 7;
const int fill = static_cast<int>(headerSeptets * 7 - header.size() * 8);
Bytes packed = PackSeptets(septets, header.empty() ? 0 : fill);
tpdu.push_back(static_cast<std::uint8_t>(headerSeptets + septets.size()));
tpdu.insert(tpdu.end(), header.begin(), header.end());
tpdu.insert(tpdu.end(), packed.begin(), packed.end());
} else {
std::vector<char16_t> u16(units.begin(), units.end());
Bytes body = Ucs2Bytes(u16);
tpdu.push_back(static_cast<std::uint8_t>(header.size() + body.size()));
tpdu.insert(tpdu.end(), header.begin(), header.end());
tpdu.insert(tpdu.end(), body.begin(), body.end());
}
out.push_back(std::move(tpdu));
}
return out;
}
// ---- TS 24.011 7.3 / 8.2: the SM-RL messages --------------------------
enum class RpType : std::uint8_t {
DataMo = 0, // RP-DATA, MS → network
DataMt = 1, // RP-DATA, network → MS
AckMo = 2, // RP-ACK, MS → network
AckMt = 3, // RP-ACK, network → MS
ErrorMo = 4, // RP-ERROR, MS → network
ErrorMt = 5, // RP-ERROR, network → MS
Smma = 6, // RP-SMMA, MS → network
};
constexpr std::uint8_t RpUserDataIei = 0x41;
struct Rp {
RpType type = RpType::DataMt;
std::uint8_t mr = 0; // RP-Message Reference: links an ACK/ERROR to its DATA
std::optional<Address> sc; // RP-Originator (MT) or RP-Destination (MO): the service centre
Bytes tpdu; // RP-User Data
std::optional<std::uint8_t> cause; // RP-ERROR
std::optional<std::uint8_t> diagnostic;
};
// RP-DATA MS → network (7.3.1.2): an empty originator, the service
// centre as destination — `scAddress` as EF_SMSP holds it and
// EncodeRpAddress builds it: [octets][toa][digits] —, the TPDU.
Bytes BuildRpData(std::uint8_t mr, std::span<const std::uint8_t> scAddress, std::span<const std::uint8_t> tpdu) {
Bytes out = {static_cast<std::uint8_t>(RpType::DataMo), mr, 0x00};
out.insert(out.end(), scAddress.begin(), scAddress.end());
out.push_back(static_cast<std::uint8_t>(tpdu.size()));
out.insert(out.end(), tpdu.begin(), tpdu.end());
return out;
}
// RP-ACK MS → network (7.3.3), the SMS-DELIVER-REPORT as its user data
// when given.
Bytes BuildRpAck(std::uint8_t mr, std::span<const std::uint8_t> tpdu = {}) {
Bytes out = {static_cast<std::uint8_t>(RpType::AckMo), mr};
if (!tpdu.empty()) {
out.push_back(RpUserDataIei);
out.push_back(static_cast<std::uint8_t>(tpdu.size()));
out.insert(out.end(), tpdu.begin(), tpdu.end());
}
return out;
}
// RP-ERROR MS → network (7.3.4): the cause (8.2.5.4, no diagnostic),
// the SMS-DELIVER-REPORT as its user data when given.
Bytes BuildRpError(std::uint8_t mr, std::uint8_t cause, std::span<const std::uint8_t> tpdu = {}) {
Bytes out = {static_cast<std::uint8_t>(RpType::ErrorMo), mr, 0x01, static_cast<std::uint8_t>(cause & 0x7F)};
if (!tpdu.empty()) {
out.push_back(RpUserDataIei);
out.push_back(static_cast<std::uint8_t>(tpdu.size()));
out.insert(out.end(), tpdu.begin(), tpdu.end());
}
return out;
}
// RP-Cause values (table 8.4) in words — the MO ones a submission may
// be refused with and the MT ones we send.
std::string RpCauseText(std::uint8_t cause) {
switch (cause & 0x7F) {
case 1: return "unassigned number";
case 8: return "operator determined barring";
case 10: return "call barred";
case 21: return "short message transfer rejected";
case 22: return "memory capacity exceeded";
case 27: return "destination out of order";
case 28: return "unidentified subscriber";
case 29: return "facility rejected";
case 30: return "unknown subscriber";
case 38: return "network out of order";
case 41: return "temporary failure";
case 42: return "congestion";
case 47: return "resources unavailable";
case 50: return "requested facility not subscribed";
case 69: return "requested facility not implemented";
case 81: return "invalid short message transfer reference value";
case 95: return "semantically incorrect message";
case 96: return "invalid mandatory information";
case 97: return "message type non-existent or not implemented";
case 98: return "message not compatible with the short message protocol state";
case 99: return "information element non-existent or not implemented";
case 111: return "protocol error, unspecified";
case 127: return "interworking, unspecified";
default: return std::format("cause {}", cause & 0x7F);
}
}
constexpr std::uint8_t RpCauseMemoryCapacityExceeded = 22;
constexpr std::uint8_t RpCauseInvalidMandatoryInformation = 96;
constexpr std::uint8_t RpCauseProtocolError = 111;
// An RP message as received — from the network (the MT types) or, for
// a round trip of our own, from a mobile. nullopt when the type does
// not fit the direction or a mandatory element runs out; the optional
// RP-User Data of an ACK or ERROR is read when its IEI is there.
std::optional<Rp> ParseRp(std::span<const std::uint8_t> b, bool fromNetwork = true) {
if (b.size() < 2) return std::nullopt;
Rp rp;
const std::uint8_t mti = b[0] & 0x07;
if (mti > 6 || (fromNetwork ? mti % 2 == 0 : mti % 2 == 1)) return std::nullopt;
rp.type = static_cast<RpType>(mti);
rp.mr = b[1];
std::size_t pos = 2;
auto lv = [&](Bytes& out) -> bool {
if (pos >= b.size()) return false;
const std::size_t len = b[pos++];
if (pos + len > b.size()) return false;
out.assign(b.begin() + static_cast<std::ptrdiff_t>(pos), b.begin() + static_cast<std::ptrdiff_t>(pos + len));
pos += len;
return true;
};
auto userDataTlv = [&]() {
if (pos < b.size() && b[pos] == RpUserDataIei) { pos++; lv(rp.tpdu); }
};
switch (rp.type) {
case RpType::DataMo:
case RpType::DataMt: {
Bytes oa, da;
if (!lv(oa) || !lv(da) || !lv(rp.tpdu)) return std::nullopt;
const Bytes& scv = rp.type == RpType::DataMt ? oa : da;
if (!scv.empty()) rp.sc = DecodeRpAddressValue(scv);
return rp;
}
case RpType::AckMo:
case RpType::AckMt:
userDataTlv();
return rp;
case RpType::ErrorMo:
case RpType::ErrorMt: {
Bytes cause;
if (!lv(cause) || cause.empty()) return std::nullopt;
rp.cause = cause[0] & 0x7F;
if (cause.size() > 1) rp.diagnostic = cause[1];
userDataTlv();
return rp;
}
case RpType::Smma:
return rp;
}
return std::nullopt;
}
// ---- TS 31.102 4.2.27: EF_SMSP ----------------------------------------
struct SmsParameters {
std::string alpha; // the parameter set's name
Bytes scAddress; // TS-Service-Centre-Address as the RP-DATA destination takes it: [octets][toa][digits]
std::string scNumber; // the same as a number
std::optional<std::uint8_t> validity; // TP-Validity-Period, relative format
};
// One record of EF_SMSP: the alpha identifier (the record's length less
// the 28 fixed octets), the parameter indicators (a 0 bit = present),
// TP-Destination-Address (12), TP-Service-Centre-Address (12 — the first
// octet counts the octets that follow, 0xFF when unused), TP-PID,
// TP-DCS, TP-Validity-Period. nullopt for a record too short or without
// a service centre.
std::optional<SmsParameters> ParseSmsp(std::span<const std::uint8_t> record) {
if (record.size() < 28) return std::nullopt;
const std::size_t base = record.size() - 28;
SmsParameters p;
for (std::size_t i = 0; i < base; i++) {
if (record[i] == 0xFF) break;
Utf8Append(p.alpha, Gsm7Table[record[i] & 0x7F]);
}
const std::uint8_t pi = record[base];
if (pi & 0x02) return std::nullopt; // TP-SCA absent
auto sca = record.subspan(base + 13, 12);
const std::size_t len = sca[0];
if (len == 0 || len > 11 || len == 0xFF) return std::nullopt;
p.scAddress.assign(sca.begin(), sca.begin() + static_cast<std::ptrdiff_t>(1 + len));
auto addr = DecodeRpAddressValue(std::span<const std::uint8_t>(p.scAddress).subspan(1));
if (!addr || addr->digits.empty()) return std::nullopt;
p.scNumber = addr->Number();
if (!(pi & 0x10)) p.validity = record[base + 27];
return p;
}
// The bytes `qmicli --uim-read-record` / `--uim-read-transparent`
// print under "Read result:" — colon-separated hex pairs, wrapped over
// lines. Empty when the marker is missing.
Bytes ParseQmicliReadResult(std::string_view text) {
Bytes out;
const std::size_t at = text.find("Read result:");
if (at == std::string_view::npos) return out;
std::string_view rest = text.substr(at + 12);
std::size_t i = 0;
auto hex = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
while (i < rest.size()) {
const char c = rest[i];
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ':') { i++; continue; }
if (i + 1 >= rest.size()) break;
const int hi = hex(c);
const int lo = hex(rest[i + 1]);
if (hi < 0 || lo < 0) break;
out.push_back(static_cast<std::uint8_t>(hi * 16 + lo));
i += 2;
}
return out;
}
// ---- reassembly of a concatenated message ------------------------------
// Collects the segments of concatenated SMS-DELIVERs — keyed by the
// sender, the reference and the total (9.2.3.24.1) — and hands the
// whole message back once every segment is in, in sequence order. A
// set to which no segment comes for `maxAge` seconds on the caller's
// clock is dropped by Purge, and named to the caller: its segments go
// nowhere.
class Reassembler {
public:
struct Dropped { std::string from; std::uint16_t ref = 0; std::uint8_t total = 0; std::uint8_t held = 0; };
// A segment in; the complete message when it was the last one
// missing: the highest-numbered segment's fields; the text decoded from the
// segments' units joined in order when one alphabet runs through
// the set, so a surrogate pair or an escape pair a sender cut at a
// segment boundary comes out whole (the segments' texts joined
// otherwise); the data joined. A DELIVER without a concatenation
// header is complete as it is.
std::optional<Deliver> Add(Deliver part, double now) {
if (!part.ud.header.concat) return part;
const Concat c = *part.ud.header.concat;
Key key{part.from.Number(), c.ref, c.total};
Set& set = sets_[key];
set.at = now;
set.parts[c.seq] = std::move(part);
if (set.parts.size() < c.total) return std::nullopt;
Deliver whole = set.parts.rbegin()->second;
whole.ud.text.clear();
whole.ud.units.clear();
whole.ud.data.clear();
bool oneAlphabet = true;
for (auto& [seq, p] : set.parts) {
if (p.ud.alphabet != whole.ud.alphabet) oneAlphabet = false;
whole.ud.text += p.ud.text;
whole.ud.units.insert(whole.ud.units.end(), p.ud.units.begin(), p.ud.units.end());
whole.ud.data.insert(whole.ud.data.end(), p.ud.data.begin(), p.ud.data.end());
}
if (oneAlphabet && whole.ud.alphabet == Alphabet::Gsm7) whole.ud.text = Gsm7Text(whole.ud.units);
else if (oneAlphabet && whole.ud.alphabet == Alphabet::Ucs2) whole.ud.text = Ucs2Decode(whole.ud.units);
sets_.erase(key);
return whole;
}
std::vector<Dropped> Purge(double now, double maxAge) {
std::vector<Dropped> dropped;
for (auto it = sets_.begin(); it != sets_.end();) {
if (now - it->second.at > maxAge) {
dropped.push_back({it->first.from, it->first.ref, it->first.total, static_cast<std::uint8_t>(it->second.parts.size())});
it = sets_.erase(it);
} else ++it;
}
return dropped;
}
std::size_t Pending() const { return sets_.size(); }
private:
struct Key {
std::string from;
std::uint16_t ref;
std::uint8_t total;
auto operator<=>(const Key&) const = default;
};
struct Set {
std::map<std::uint8_t, Deliver> parts;
double at = 0;
};
std::map<Key, Set> sets_;
};
}