Skip to main content

sms_pdu/
pdu.rs

1//! Utilities for dealing with GSM 03.40 Protocol Data Units (PDUs).
2//!
3//! See [this Wikipedia article](https://en.wikipedia.org/wiki/GSM_03.40) for more genreal
4//! information on the format of PDUs.
5//!
6//! As of the time of writing, this library's implementation of PDUs can be classed as "passable" -
7//! in that it currently supports 2 out of the 6 specified PDU types (SMS-DELIVER and SMS-SUBMIT),
8//! and straight up refuses to parse anything else. Luckily, these two are the only ones you really
9//! need (and if they aren't, feel free to file an issue!).
10use std::fmt;
11use std::str::FromStr;
12use std::convert::{Infallible, TryFrom};
13use num_derive::FromPrimitive;
14use num_traits::FromPrimitive;
15use crate::gsm_encoding::{GsmMessageData, gsm_decode_string, decode_sms_7bit};
16use crate::{check_offset, PDUError, PDUResult};
17
18/// Type of number value - used as part of phone numbers to indicate whether the number is
19/// international, alphanumeric, etc.
20#[repr(u8)]
21#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive, Hash)]
22pub enum TypeOfNumber {
23    /// Unknown number type ('let the network handle it please').
24    Unknown = 0b0_000_0000,
25    /// International (i.e. starting with +). This is probably what you want when sending messages.
26    International = 0b0_001_0000,
27    /// National number - no prefix or suffix added.
28    National = 0b0_010_0000,
29    /// Special number - you can't send messages with this type.
30    Special = 0b0_011_0000,
31    /// Alphanumeric number - i.e. this isn't a phone number, it's actually some text that
32    /// indicates who the sender is (e.g. when banks/other companies send you SMSes).
33    ///
34    /// You can't send messages with this type.
35    Gsm = 0b0_101_0000,
36    /// Short number (not in use).
37    Short = 0b0_110_0000,
38    /// Reserved (not in use).
39    Reserved = 0b0_111_0000
40}
41/// Numbering plan idnficiation value.
42///
43/// I think this is mostly vestigial, and you'll want to set this to `IsdnTelephone`.
44#[repr(u8)]
45#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive, Hash)]
46pub enum NumberingPlanIdentification {
47    NetworkDetermined = 0b0_000_0000,
48    IsdnTelephone = 0b0_000_0001,
49    Data = 0b0_000_0011,
50    Telex = 0b0_000_0100,
51    National = 0b0_000_1000,
52    Private = 0b0_000_1001,
53    Ermes = 0b0_000_1010
54}
55/// Address type, comprised of a `TypeOfNumber` and `NumberingPlanIdentification` value.
56///
57/// It is **highly** recommended that you just use the `Default` value of this `struct`, unless you
58/// know what you're doing, and that your phone numbers are in international format (i.e. starting
59/// with `+`).
60#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
61pub struct AddressType {
62    pub type_of_number: TypeOfNumber,
63    pub numbering_plan_identification: NumberingPlanIdentification
64}
65impl Default for AddressType {
66    fn default() -> Self {
67        AddressType {
68            type_of_number: TypeOfNumber::International,
69            numbering_plan_identification: NumberingPlanIdentification::IsdnTelephone
70        }
71    }
72}
73impl TryFrom<u8> for AddressType {
74    type Error = PDUError;
75    fn try_from(b: u8) -> PDUResult<Self>  {
76        let ton = b & 0b0_111_0000;
77        let ton = TypeOfNumber::from_u8(ton)
78            .ok_or(PDUError::InvalidPdu("invalid type_of_number"))?;
79        let npi = b & 0b0_000_1111;
80        let npi = NumberingPlanIdentification::from_u8(npi)
81            .ok_or(PDUError::InvalidPdu("invalid numbering_plan_identification"))?;
82        Ok(Self {
83            type_of_number: ton,
84            numbering_plan_identification: npi
85        })
86    }
87}
88impl Into<u8> for AddressType {
89    fn into(self) -> u8 {
90        let mut ret: u8 = 0b1_000_0000;
91        ret |= self.type_of_number as u8;
92        ret |= self.numbering_plan_identification as u8;
93        ret
94    }
95}
96/// A GSM phone number, encoded using their weird half-octet encoding.
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct PhoneNumber(pub Vec<u8>);
99/// Make a phone number from some ordinary bytes.
100///
101/// Note that **only the least significant 4 bytes** are used in this conversion, due to the way
102/// GSM phone numbers work. The top 4 bytes are discarded!
103impl<'a> From<&'a [u8]> for PhoneNumber {
104    fn from(b: &[u8]) -> Self {
105        let mut ret = vec![];
106        for b in b.iter() {
107            let first = b & 0b0000_1111;
108            let second = (b & 0b1111_0000) >> 4;
109            ret.push(first);
110            if second != 0b0000_1111 {
111                ret.push(second);
112            }
113        }
114        PhoneNumber(ret)
115    }
116}
117impl PhoneNumber {
118    /// Make a `PhoneNumber` for an alphanumeric GSM sender address.
119    pub fn from_gsm(b: &[u8], len: usize) -> Self {
120        PhoneNumber(decode_sms_7bit(b, 0, len))
121    }
122    /// Represent this phone number as normal bytes, instead of their weird as hell encoding.
123    pub fn as_bytes(&self) -> Vec<u8> {
124        let mut ret = vec![];
125        let mut cur = 0b0000_0000;
126        for (i, b) in self.0.iter().enumerate() {
127            let mut b = *b;
128            if i % 2 == 0 {
129                cur |= b;
130            }
131            else {
132                b = b << 4;
133                cur |= b;
134                ret.push(cur);
135                cur = 0b0000_0000;
136            }
137        }
138        if self.0.len() % 2 != 0 {
139            cur |= 0b1111_0000;
140            ret.push(cur);
141        }
142        ret
143    }
144}
145/// A PDU address (i.e. phone number, and number type). This is what you want to use for
146/// representing phone numbers, most likely.
147///
148/// Use the `FromStr` implementation here to convert regular string phone numbers into weird PDU
149/// format. Note that alphanumeric numbers are not supported at this time (only normal phone
150/// numbers).
151#[derive(Debug, Clone, PartialEq, Eq, Hash)]
152pub struct PduAddress {
153    pub type_addr: AddressType,
154    pub number: PhoneNumber
155}
156impl fmt::Display for PduAddress {
157    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158
159        let prefix = match self.type_addr.type_of_number {
160            TypeOfNumber::International => "+",
161            _ => ""
162        };
163        write!(f, "{}", prefix)?;
164        if self.type_addr.type_of_number == TypeOfNumber::Gsm {
165            write!(f, "{}", gsm_decode_string(&self.number.0))?;
166        }
167        else {
168            for b in self.number.0.iter() {
169                write!(f, "{}", b)?;
170            }
171        }
172        Ok(())
173    }
174}
175impl FromStr for PduAddress {
176    type Err = Infallible;
177    fn from_str(st: &str) -> Result<Self, Infallible> {
178        let mut int = false;
179        let buf = st.chars()
180            .filter_map(|x| {
181                match x {
182                    '0'..='9' => Some(x as u8 - 48),
183                    '+' => {
184                        int = true;
185                        None
186                    },
187                    _ => None
188                }
189            }).collect::<Vec<_>>();
190        let ton = if int {
191            TypeOfNumber::International
192        }
193        else {
194            TypeOfNumber::Unknown
195        };
196        Ok(PduAddress {
197            type_addr: AddressType {
198                type_of_number: ton,
199                numbering_plan_identification: NumberingPlanIdentification::IsdnTelephone
200            },
201            number: PhoneNumber(buf)
202        })
203    }
204}
205impl<'a> TryFrom<&'a [u8]> for PduAddress {
206    type Error = PDUError;
207    fn try_from(b: &[u8]) -> PDUResult<Self> {
208        if b.len() < 3 {
209            Err(PDUError::InvalidPdu("tried to make a PduAddress from less than 3 bytes"))?
210        }
211        let len = b[0] as usize;
212        let type_addr = AddressType::try_from(b[1])?;
213        let number = if type_addr.type_of_number == TypeOfNumber::Gsm {
214            let len = (len * 4) / 7;
215            PhoneNumber::from_gsm(&b[2..], len)
216        }
217        else {
218            PhoneNumber::from(&b[2..])
219        };
220        Ok(PduAddress { type_addr, number })
221    }
222}
223impl PduAddress {
224    /// Convert this address into bytes, as represented in the actual PDU.
225    ///
226    /// The `broken_len` flag controls whether to represent the length as the length in bytes of
227    /// the whole PduAddress (false), or just the length of the phone number contained within (true).
228    ///
229    /// In testing, it seems as if it should pretty much always be `true`, which is weird. A future
230    /// version of the crate may well just remove the parameter and default to true.
231    pub fn as_bytes(&self, broken_len: bool) -> Vec<u8> {
232        let mut ret = vec![];
233        ret.push(self.type_addr.into());
234        ret.extend(self.number.as_bytes());
235        let len = if broken_len {
236            self.number.0.len()
237        } else {
238            ret.len()
239        };
240        ret.insert(0, len as u8);
241        ret
242    }
243}
244/// SMS PDU message type.
245#[repr(u8)]
246#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
247pub enum MessageType {
248    /// SMS-DELIVER (SC to MT) or SMS-DELIVER-REPORT (MT to SC)
249    SmsDeliver = 0b000000_00,
250    /// SMS-STATUS-REPORT (SC to MT) or SMS-COMMAND (MT to SC)
251    SmsCommand = 0b000000_10,
252    /// SMS-SUBMIT-REPORT (SC to MT) or SMS-SUBMIT (MT to SC)
253    SmsSubmit = 0b000000_01,
254    /// Reserved for future use.
255    Reserved = 0b000000_11
256}
257/// Validity of the VP field.
258#[repr(u8)]
259#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
260pub enum VpFieldValidity {
261    /// Invalid.
262    Invalid = 0b00,
263    /// Valid, in relative format.
264    Relative = 0b10,
265    /// Valid, in enhanced format.
266    Enhanced = 0b01,
267    /// Valid, in absolute format.
268    Absolute = 0b11,
269}
270/// The first octet of a SMS-SUBMIT PDU.
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub struct PduFirstOctet {
273    /// Message type.
274    pub mti: MessageType,
275    /// Reject duplicates (?).
276    pub rd: bool,
277    /// Validity and format of the VP field.
278    pub vpf: VpFieldValidity,
279    /// Whether to request a status report when the message is sent succesfully.
280    pub srr: bool,
281    /// Does the user data segment contain a data header?
282    pub udhi: bool,
283    /// Do replies to this message use the same settings as this message?
284    pub rp: bool
285}
286impl From<u8> for PduFirstOctet {
287    fn from(b: u8) -> Self {
288        let rd = (b & 0b0000_0100) > 0;
289        let srr = (b & 0b0010_0000) > 0;
290        let udhi = (b & 0b0100_0000) > 0;
291        let rp = (b & 0b1000_0000) > 0;
292        let mti = MessageType::from_u8(b & 0b0000_0011)
293            .expect("MessageType conversions should be exhaustive!");
294        let vpf = VpFieldValidity::from_u8((b & 0b0001_1000) >> 3)
295            .expect("VpFieldValidity conversions should be exhaustive!");
296        PduFirstOctet { rd, srr, udhi, rp, mti, vpf }
297    }
298}
299impl Into<u8> for PduFirstOctet {
300    fn into(self) -> u8 {
301        let mut ret = 0b0000_0000;
302        ret |= self.mti as u8;
303        ret |= (self.vpf as u8) << 3;
304        if self.rd {
305            ret |= 0b0000_0100;
306        }
307        if self.srr {
308            ret |= 0b0010_0000;
309        }
310        if self.udhi {
311            ret |= 0b0100_0000;
312        }
313        if self.rp {
314            ret |= 0b1000_0000;
315        }
316        ret
317    }
318}
319/// The data coding scheme of the message.
320///
321/// Basically, this `enum` is a decoded 8-bit field that has a bunch of different cases, which is
322/// why there are so many options here.
323///
324/// The meanings explained in the Huawei spec are very confusing and sometimes overlapping.
325/// Use the `encoding` method to figure out what encoding to use, which is probably the only real
326/// use you're going to have for this `struct` anyway.
327#[derive(Debug, Copy, Clone, PartialEq, Eq)]
328pub enum DataCodingScheme {
329    /// Standard coding scheme.
330    Standard {
331        /// Whether or not the message is compressed, but this isn't actually supported.
332        compressed: bool,
333        /// The message class (flash SMS, stored to SIM only, etc.)
334        class: Option<MessageClass>,
335        /// The message encoding (7-bit, UCS-2, 8-bit)
336        encoding: MessageEncoding
337    },
338    /// Reserved value.
339    Reserved,
340    /// Discard the message content, but display the message waiting indication to the user.
341    MessageWaitingDiscard {
342        /// Enables or disables message waiting indication.
343        waiting: bool,
344        /// Type of message waiting.
345        type_indication: MessageWaitingType,
346    },
347    /// Store the message content, and display the message waiting indication to the user.
348    MessageWaiting {
349        /// Enables or disables message waiting indication.
350        waiting: bool,
351        /// Type of message waiting.
352        type_indication: MessageWaitingType,
353        /// Whether or not the message is encoded in UCS-2 format.
354        ucs2: bool
355    }
356}
357impl DataCodingScheme {
358    /// Determine which character encoding the message uses (i.e. GSM 7-bit, UCS-2, ...)
359    ///
360    /// (Some of these answers might be guesses.)
361    pub fn encoding(&self) -> MessageEncoding {
362        use self::DataCodingScheme::*;
363        match *self {
364            Standard { encoding, .. } => encoding,
365            Reserved => MessageEncoding::Gsm7Bit,
366            MessageWaitingDiscard { .. } => MessageEncoding::Gsm7Bit,
367            MessageWaiting { ucs2, .. } => if ucs2 {
368                MessageEncoding::Ucs2
369            }
370            else {
371                MessageEncoding::Gsm7Bit
372            }
373        }
374    }
375}
376impl From<u8> for DataCodingScheme {
377    fn from(b: u8) -> Self {
378        if (b & 0b1100_0000) == 0b0000_0000 {
379            let compressed = (b & 0b0010_0000) > 0;
380            let reserved = (b & 0b0001_0000) > 0;
381            let class = Some(if reserved {
382                // XXX: No default is actually specified in the Huawei spec; I just chose
383                // StoreToNv, because that's what we send by default.
384                MessageClass::StoreToNv
385            }
386            else {
387                MessageClass::from_u8(b & 0b0000_0011)
388                    .expect("MessageClass conversions should be exhaustive!")
389            });
390            let encoding = MessageEncoding::from_u8(b & 0b0000_1100)
391                .expect("MessageEncoding conversions should be exhaustive!");
392            DataCodingScheme::Standard { compressed, class, encoding }
393        }
394        else if (b & 0b1111_0000) == 0b1111_0000 {
395            let compressed = false;
396            let class = Some(MessageClass::from_u8(b & 0b0000_0011)
397                .expect("MessageClass conversions should be exhaustive!"));
398            let encoding = if (b & 0b0000_0100) > 0 {
399                MessageEncoding::Gsm7Bit
400            }
401            else {
402                MessageEncoding::EightBit
403            };
404            DataCodingScheme::Standard { compressed, class, encoding }
405        }
406        else if (b & 0b1111_0000) == 0b1100_0000 {
407            let waiting = (b & 0b0000_1000) > 0;
408            let type_indication = MessageWaitingType::from_u8(b & 0b0000_0011)
409                .expect("MessageWaitingType conversions should be exhaustive!");
410            DataCodingScheme::MessageWaitingDiscard { waiting, type_indication }
411        }
412        else if (b & 0b1111_0000) == 0b1101_0000 || (b & 0b1111_0000) == 0b1110_0000 {
413            let ucs2 = (b & 0b1111_0000) == 0b1110_0000;
414            let waiting = (b & 0b0000_1000) > 0;
415            let type_indication = MessageWaitingType::from_u8(b & 0b0000_0011)
416                .expect("MessageWaitingType conversions should be exhaustive!");
417            DataCodingScheme::MessageWaiting { ucs2, waiting, type_indication }
418        }
419        else {
420            DataCodingScheme::Reserved
421        }
422    }
423}
424impl Into<u8> for DataCodingScheme {
425    fn into(self) -> u8 {
426        use self::DataCodingScheme::*;
427        match self {
428            Standard { compressed, class, encoding } => {
429                let mut ret = 0u8;
430                if compressed {
431                    ret |= 0b0010_0000;
432                }
433                if let Some(class) = class {
434                    ret |= 0b0001_0000;
435                    ret |= class as u8;
436                }
437                ret |= encoding as u8;
438                ret
439            },
440            Reserved => 0b0100_0101,
441            MessageWaiting { waiting, type_indication, ucs2 } => {
442                let mut ret = if ucs2 {
443                    0b1110_0000
444                }
445                else {
446                    0b1101_0000
447                };
448                if waiting {
449                    ret |= 0b0000_1000;
450                }
451                ret |= type_indication as u8;
452                ret
453            },
454            MessageWaitingDiscard { waiting, type_indication } => {
455                let mut ret = 0b1100_0000;
456                if waiting {
457                    ret |= 0b0000_1000;
458                }
459                ret |= type_indication as u8;
460                ret
461            }
462        }
463    }
464}
465/// Type of message waiting.
466#[repr(u8)]
467#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
468pub enum MessageWaitingType {
469    Voice = 0b000000_00,
470    Fax = 0b000000_01,
471    Email = 0b000000_10,
472    Unknown = 0b000000_11
473}
474/// Class of message received.
475#[repr(u8)]
476#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
477pub enum MessageClass {
478    /// Silent (class 0)  - display on the phone's UI, but don't store in memory.
479    Silent = 0b000000_00,
480    /// Store to the NV (class 1), or SIM card if the NV is full.
481    StoreToNv = 0b000000_01,
482    /// Store to the SIM card only (class 2).
483    StoreToSim = 0b000000_10,
484    /// Store to the TE (class 3).
485    StoreToTe = 0b000000_11
486}
487/// SMS message data encoding.
488#[repr(u8)]
489#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
490pub enum MessageEncoding {
491    /// GSM packed 7-bit encoding.
492    Gsm7Bit = 0b0000_00_00,
493    /// Binary 8-bit encoding.
494    EightBit = 0b0000_01_00,
495    /// UCS-2 (i.e. UTF-16) encoding.
496    Ucs2 = 0b0000_10_00,
497    /// Reserved for future use.
498    Reserved = 0b0000_11_00,
499}
500/// The first octet of a SMS-DELIVER PDU.
501#[derive(Debug, Clone, PartialEq, Eq)]
502pub struct DeliverPduFirstOctet {
503    /// Message type.
504    mti: MessageType,
505    /// Indicates whetehr a status report was requested.
506    sri: bool,
507    /// Does the user data segment contain a data header?
508    udhi: bool,
509    /// Do replies to this message use the same settings as this message?
510    rp: bool
511}
512impl From<u8> for DeliverPduFirstOctet {
513    fn from(b: u8) -> Self {
514        let mti = MessageType::from_u8(b & 0b000000_11)
515            .expect("MessageType conversions should be exhaustive!");
516        let sri = (b & 0b00100000) > 0;
517        let udhi = (b & 0b01000000) > 0;
518        let rp = (b & 0b01000000) > 0;
519        DeliverPduFirstOctet { mti, sri, udhi, rp }
520    }
521}
522/// Service centre timestamp.
523#[derive(Debug, Clone, PartialEq, Eq)]
524pub struct SmscTimestamp {
525    pub year: u8,
526    pub month: u8,
527    pub day: u8,
528    pub hour: u8,
529    pub minute: u8,
530    pub second: u8,
531    /// Hours' difference between local time and GMT.
532    pub timezone: u8
533}
534pub(crate) fn reverse_byte(b: u8) -> u8 {
535    let units = b >> 4;
536    let tens = b & 0b0000_1111;
537    (tens * 10) + units
538}
539impl<'a> TryFrom<&'a [u8]> for SmscTimestamp {
540    type Error = PDUError;
541    fn try_from(b: &[u8]) -> PDUResult<Self> {
542        if b.len() != 7 {
543            Err(PDUError::InvalidPdu("SmscTimestamp must be 7 bytes long"))?
544        }
545        Ok(SmscTimestamp {
546            year: reverse_byte(b[0]),
547            month: reverse_byte(b[1]),
548            day: reverse_byte(b[2]),
549            hour: reverse_byte(b[3]),
550            minute: reverse_byte(b[4]),
551            second: reverse_byte(b[5]),
552            timezone: reverse_byte(b[6]),
553        })
554    }
555}
556/// An SMS-DELIVER PDU.
557///
558/// **NB:** For simple usage, you'll only need to care about the `originating_address` field and
559/// the `get_message_data` method!
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub struct DeliverPdu {
562    /// Service centre address, if provided here.
563    pub sca: Option<PduAddress>,
564    /// First octet (contains some extra fields).
565    pub first_octet: DeliverPduFirstOctet,
566    /// Originating address (i.e. message sender).
567    pub originating_address: PduAddress,
568    /// Message data coding scheme.
569    pub dcs: DataCodingScheme,
570    /// Message timestamp, from the service centre.
571    pub scts: SmscTimestamp,
572    /// User data.
573    pub user_data: Vec<u8>,
574    /// User data length.
575    pub user_data_len: u8
576}
577impl DeliverPdu {
578    /// Get the actual data (i.e. text or binary content) of the message.
579    ///
580    /// Methods on `GsmMessageData` let you convert this into actual text.
581    pub fn get_message_data(&self) -> GsmMessageData {
582        GsmMessageData {
583            bytes: self.user_data.clone(),
584            user_data_len: self.user_data_len,
585            encoding: self.dcs.encoding(),
586            udh: self.first_octet.udhi
587        }
588    }
589}
590impl<'a> TryFrom<&'a [u8]> for DeliverPdu {
591    type Error = PDUError;
592    fn try_from(b: &[u8]) -> PDUResult<Self> {
593        if b.len() == 0 {
594            return Err(PDUError::InvalidPdu("zero-length input"));
595        }
596        let scalen = b[0];
597        let mut offset: usize = scalen as usize + 1;
598        let sca = if scalen > 0 {
599            let o = offset - 1;
600            check_offset!(b, o, "SCA");
601            Some(PduAddress::try_from(&b[0..offset])?)
602        }
603        else {
604            None
605        };
606        check_offset!(b, offset, "first octet");
607        let first_octet = DeliverPduFirstOctet::from(b[offset]);
608        offset += 1;
609        check_offset!(b, offset, "originating address len");
610        let destination_len_nybbles = b[offset];
611        // destination_len_nybbles represents the length of the address, in nybbles (half-octets).
612        // Therefore, we divide by 2, rounding up, to get the number of full octets.
613        let destination_len_octets = (destination_len_nybbles / 2) + destination_len_nybbles % 2;
614        // destination_offset = what we're going to add to the offset to get the new offset
615        // This is the destination length, in octets, plus one byte for the address length field,
616        // and another because range syntax is non-inclusive.
617        let destination_offset = (destination_len_octets as usize) + 2;
618        let destination_end = offset + destination_offset;
619        let de = destination_end - 1;
620        check_offset!(b, de, "originating address");
621        let originating_address = PduAddress::try_from(&b[offset..destination_end])?;
622        offset += destination_offset;
623        check_offset!(b, offset, "protocol identifier");
624        let _pid = b[offset];
625        offset += 1;
626        check_offset!(b, offset, "data coding scheme");
627        let dcs = DataCodingScheme::from(b[offset]);
628        offset += 1;
629        let scts_end = offset + 7;
630        let ss = offset + 6;
631        check_offset!(b, ss, "service center timestamp");
632        let scts = SmscTimestamp::try_from(&b[offset..scts_end])?;
633        offset += 7;
634        check_offset!(b, offset, "user data len");
635        let user_data_len = b[offset];
636        offset += 1;
637        let user_data = if b.get(offset).is_some() {
638            b[offset..].to_owned()
639        }
640        else {
641            vec![]
642        };
643        Ok(DeliverPdu {
644            sca,
645            first_octet,
646            originating_address,
647            dcs,
648            scts,
649            user_data,
650            user_data_len
651        })
652
653    }
654}
655
656/// SMS delivery status codes for STATUS-REPORT PDUs.
657#[repr(u8)]
658#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, FromPrimitive)]
659pub enum MessageStatus {
660    // Short message transaction completed
661    /// Short message received by the SME
662    ReceivedBySme = 0x00,
663    /// Short message forwarded by the SC to the SME but the SC is unable to confirm delivery
664    ForwardedUnconfirmed = 0x01,
665    /// Short message replaced by the SC
666    ReplacedBySc = 0x02,
667
668    // Temporary error, SC still trying to transfer SM
669    /// Congestion
670    Congestion = 0x20,
671    /// SME busy
672    SmeBusy = 0x21,
673    /// No response from SME
674    NoResponseFromSme = 0x22,
675    /// Service rejected
676    ServiceRejected = 0x23,
677    /// Quality of service not available
678    QualityOfServiceNotAvailable = 0x24,
679    /// Error in SME
680    ErrorInSme = 0x25,
681
682    // Permanent error, SC is not making any more transfer attempts
683    /// Remote procedure error
684    RemoteProcedureError = 0x40,
685    /// Incompatible destination
686    IncompatibleDestination = 0x41,
687    /// Connection rejected by SME
688    ConnectionRejectedBySme = 0x42,
689    /// Not obtainable
690    NotObtainable = 0x43,
691    /// Quality of service not available
692    QualityOfServiceNotAvailablePermanent = 0x44,
693    /// No interworking available
694    NoInterworkingAvailable = 0x45,
695    /// SM Validity Period Expired
696    SmValidityPeriodExpired = 0x46,
697    /// SM Deleted by originating SME
698    SmDeletedByOriginatingSme = 0x47,
699    /// SM Deleted by SC Administration
700    SmDeletedByScAdministration = 0x48,
701    /// SM does not exist
702    SmDoesNotExist = 0x49,
703
704    // Temporary error, SC is not making any more transfer attempts
705    /// Congestion
706    CongestionNoMoreAttempts = 0x60,
707    /// SME busy
708    SmeBusyNoMoreAttempts = 0x61,
709    /// No response from SME
710    NoResponseFromSmeNoMoreAttempts = 0x62,
711    /// Service rejected
712    ServiceRejectedNoMoreAttempts = 0x63,
713    /// Quality of service not available
714    QualityOfServiceNotAvailableNoMoreAttempts = 0x64,
715    /// Error in SME
716    ErrorInSmeNoMoreAttempts = 0x65,
717}
718
719impl MessageStatus {
720    /// Returns true if this status indicates successful delivery
721    pub fn is_success(&self) -> bool {
722        matches!(self, MessageStatus::ReceivedBySme | MessageStatus::ForwardedUnconfirmed | MessageStatus::ReplacedBySc)
723    }
724
725    /// Returns true if this is a temporary error (SC still trying)
726    pub fn is_temporary_error(&self) -> bool {
727        let status_code = *self as u8;
728        (0x20..=0x3F).contains(&status_code)
729    }
730
731    /// Returns true if this is a permanent error (SC gave up).
732    /// More delivery reports will not be received for the message.
733    pub fn is_permanent_error(&self) -> bool {
734        let status_code = *self as u8;
735        (0x40..=0x6F).contains(&status_code)
736    }
737}
738
739/// The first octet of a SMS-STATUS-REPORT PDU.
740#[derive(Debug, Clone, PartialEq, Eq)]
741pub struct StatusReportPduFirstOctet {
742    /// Message type.
743    pub mti: MessageType,
744    /// More messages to send flag
745    pub mms: bool,
746    /// Loop prevention flag
747    pub lp: bool,
748    /// Status report qualifier (0 = result of SMS-SUBMIT, 1 = result of SMS-COMMAND)
749    pub srq: bool,
750    /// Does the user data segment contain a data header?
751    pub udhi: bool,
752}
753
754impl From<u8> for StatusReportPduFirstOctet {
755    fn from(b: u8) -> Self {
756        let mti = MessageType::from_u8(b & 0b00000011)
757            .expect("MessageType conversions should be exhaustive!");
758        let mms = (b & 0b00000100) > 0;
759        let lp = (b & 0b00001000) > 0;
760        let srq = (b & 0b00100000) > 0;
761        let udhi = (b & 0b01000000) > 0;
762
763        StatusReportPduFirstOctet { mti, mms, lp, srq, udhi }
764    }
765}
766
767/// An SMS-STATUS-REPORT PDU.
768///
769/// This PDU type is sent by the SMS Center to inform about the delivery status
770/// of a previously submitted message.
771#[derive(Debug, Clone, PartialEq, Eq)]
772pub struct StatusReportPdu {
773    /// Service centre address, if provided here.
774    pub sca: Option<PduAddress>,
775    /// First octet (contains some extra fields).
776    pub first_octet: StatusReportPduFirstOctet,
777    /// Message reference (matches the reference from the original SMS-SUBMIT)
778    pub message_reference: u8,
779    /// Recipient address (destination of the original message)
780    pub recipient_address: PduAddress,
781    /// Service centre timestamp when the original message was received
782    pub scts: SmscTimestamp,
783    /// Discharge time - when the message was delivered or failed
784    pub discharge_time: SmscTimestamp,
785    /// Status of the message delivery attempt
786    pub status: MessageStatus,
787    /// Parameter indicating (optional) - only present if first_octet.udhi is true
788    pub parameter_indicating: Option<u8>,
789    /// User data (optional)
790    pub user_data: Vec<u8>,
791    /// User data length
792    pub user_data_len: u8
793}
794impl StatusReportPdu {
795    /// Get the actual data (i.e. text or binary content) of the optional user data.
796    ///
797    /// Methods on `GsmMessageData` let you convert this into actual text.
798    /// Returns None if there's no user data.
799    pub fn get_message_data(&self) -> Option<GsmMessageData> {
800        if self.user_data.is_empty() {
801            None
802        } else {
803            Some(GsmMessageData {
804                bytes: self.user_data.clone(),
805                user_data_len: self.user_data_len,
806                encoding: MessageEncoding::Gsm7Bit, // Default encoding for status reports
807                udh: self.first_octet.udhi
808            })
809        }
810    }
811}
812impl<'a> TryFrom<&'a [u8]> for StatusReportPdu {
813    type Error = PDUError;
814
815    fn try_from(b: &[u8]) -> PDUResult<Self> {
816        if b.is_empty() {
817            return Err(PDUError::InvalidPdu("zero-length input"));
818        }
819
820        let scalen = b[0];
821        let mut offset: usize = scalen as usize + 1;
822
823        // Parse SCA if present
824        let sca = if scalen > 0 {
825            let o = offset - 1;
826            check_offset!(b, o, "SCA");
827            Some(PduAddress::try_from(&b[0..offset])?)
828        } else {
829            None
830        };
831
832        // Parse first octet
833        check_offset!(b, offset, "first octet");
834        let first_octet = StatusReportPduFirstOctet::from(b[offset]);
835        offset += 1;
836
837        // Parse message reference
838        check_offset!(b, offset, "message reference");
839        let message_reference = b[offset];
840        offset += 1;
841
842        // Parse recipient address
843        check_offset!(b, offset, "recipient address len");
844        let recipient_len_nybbles = b[offset];
845        let recipient_len_octets = (recipient_len_nybbles / 2) + (recipient_len_nybbles % 2);
846        let recipient_offset = (recipient_len_octets as usize) + 2;
847        let recipient_end = offset + recipient_offset;
848        let re = recipient_end - 1;
849        check_offset!(b, re, "recipient address");
850        let recipient_address = PduAddress::try_from(&b[offset..recipient_end])?;
851        offset += recipient_offset;
852
853        // Parse service centre timestamp (7 bytes)
854        let scts_end = offset + 7;
855        let ss = offset + 6;
856        check_offset!(b, ss, "service center timestamp");
857        let scts = SmscTimestamp::try_from(&b[offset..scts_end])?;
858        offset += 7;
859
860        // Parse discharge time (7 bytes)
861        let discharge_end = offset + 7;
862        let ds = offset + 6;
863        check_offset!(b, ds, "discharge time");
864        let discharge_time = SmscTimestamp::try_from(&b[offset..discharge_end])?;
865        offset += 7;
866
867        // Parse status
868        check_offset!(b, offset, "status");
869        let status = MessageStatus::from_u8(b[offset])
870            .unwrap_or(MessageStatus::ErrorInSme); // Default to a reasonable error if unknown status
871        offset += 1;
872
873        // Parse optional parameter indicating (only if UDHI is set)
874        let parameter_indicating = if first_octet.udhi && offset < b.len() {
875            let pi = b[offset];
876            offset += 1;
877            Some(pi)
878        } else {
879            None
880        };
881
882        // Parse optional user data length and user data
883        let (user_data_len, user_data) = if offset < b.len() {
884            check_offset!(b, offset, "user data len");
885            let udl = b[offset];
886            offset += 1;
887
888            let ud = if offset < b.len() {
889                b[offset..].to_owned()
890            } else {
891                vec![]
892            };
893
894            (udl, ud)
895        } else {
896            (0, vec![])
897        };
898
899        Ok(StatusReportPdu {
900            sca,
901            first_octet,
902            message_reference,
903            recipient_address,
904            scts,
905            discharge_time,
906            status,
907            parameter_indicating,
908            user_data,
909            user_data_len,
910        })
911    }
912}
913
914/// An SMS-SUBMIT PDU.
915///
916/// **NB:** For simple usage, ignore 99% of the stuff in this module and just use
917/// `Pdu::make_simple_message`!
918#[derive(Debug, Clone, PartialEq, Eq)]
919pub struct SubmitPdu {
920    /// Service centre address, if provided here.
921    ///
922    /// If you haven't set the service center address for all messages (see the `set_smsc_addr`
923    /// function in `cmd::sms`), you'll need to provide it in SMS-SUBMIT PDUs using the `set_sca`
924    /// method.
925    pub sca: Option<PduAddress>,
926    /// First octet (contains some extra fields).
927    pub first_octet: PduFirstOctet,
928    /// Message ID.
929    ///
930    /// This is set to 0 in `make_simple_message`. Presumably, you might ostensibly be able to use
931    /// it to store outgoing messages in modem memory and then address them later?
932    pub message_id: u8,
933    /// Destination address (i.e. mesage recipient).
934    pub destination: PduAddress,
935    /// Message data coding scheme.
936    pub dcs: DataCodingScheme,
937    /// Validity period (used for message expiry).
938    ///
939    /// FIXME: as yet undocumented.
940    pub validity_period: u8,
941    /// User data.
942    pub user_data: Vec<u8>,
943    /// User data length.
944    pub user_data_len: u8
945}
946impl SubmitPdu {
947    /// Set the SMS service centre address.
948    pub fn set_sca(&mut self, sca: PduAddress) {
949        self.sca = Some(sca);
950    }
951
952    pub fn make_simple_message(recipient: PduAddress, msg: GsmMessageData) -> Self {
953        SubmitPdu {
954            sca: None,
955            first_octet: PduFirstOctet {
956                mti: MessageType::SmsSubmit,
957                rd: false,
958                vpf: VpFieldValidity::Invalid,
959                rp: false,
960                udhi: msg.udh,
961                srr: false
962            },
963            message_id: 0,
964            destination: recipient,
965            dcs: DataCodingScheme::Standard {
966                compressed: false,
967                class: Some(MessageClass::StoreToNv),
968                encoding: msg.encoding
969            },
970            validity_period: 0,
971            user_data: msg.bytes,
972            user_data_len: msg.user_data_len as u8
973        }
974    }
975}
976impl SubmitPdu {
977
978    /// Convert to wire-format bytes, with a TPDU length value.
979    pub fn as_bytes(&self) -> (Vec<u8>, usize) {
980        let mut ret = vec![];
981
982        // Handle SCA (Service Center Address)
983        let sca_field_len = if let Some(ref sca) = self.sca {
984            let sca_bytes = sca.as_bytes(false);
985            ret.extend(&sca_bytes);
986            sca_bytes.len()
987        } else {
988            ret.push(0); // SCA length = 0
989            1
990        };
991
992        ret.push(self.first_octet.into());
993        ret.push(self.message_id);
994        ret.extend(self.destination.as_bytes(true));
995        ret.push(0); // Protocol ID
996        let dcs_byte = self.dcs.into();
997        ret.push(dcs_byte);
998
999        if self.first_octet.vpf != VpFieldValidity::Invalid {
1000            ret.push(self.validity_period);
1001        }
1002
1003        ret.push(self.user_data_len);
1004        ret.extend(self.user_data.clone());
1005
1006        // TPDU length excludes the entire SCA field (length byte + SCA data)
1007        let tpdu_len = ret.len() - sca_field_len;
1008        (ret, tpdu_len)
1009    }
1010}