Skip to main content

sms_pdu/gsm_encoding/
mod.rs

1//! Utilities for dealing with the (annoying) GSM 7-bit encoding (GSM 03.38), and decoding/encoding message
2//! data.
3//!
4//! "The annoying GSM 7-bit encoding" is otherwise known as [GSM
5//! 03.38](https://en.wikipedia.org/wiki/GSM_03.38), and that Wikipedia article is pretty
6//! informative.
7//!
8//! **NB:** SMS messages that are longer than the per-message character limit are sent & received
9//! as [concatenated SMS](https://en.wikipedia.org/wiki/Concatenated_SMS) messages. The various
10//! functions in this module will attempt to warn you about this.
11
12use crate::pdu::MessageEncoding;
13use std::convert::TryFrom;
14use crate::{PDUError, PDUResult};
15
16mod lookup_tables;
17pub mod udh;
18
19use self::udh::{UserDataHeader, UdhComponent};
20use self::lookup_tables::*;
21
22/// Decode a GSM 7-bit-encoded buffer into a string.
23///
24/// **Warning:** You need to unpack the string first; this method operates on unpacked septets, not
25/// packed septets. See the `pdu` module for more.
26///
27/// This method is lossy, and doesn't complain about crap that it can't decode.
28pub fn gsm_decode_string(input: &[u8]) -> String {
29    let mut ret = String::new();
30    let mut skip = false;
31    for (i, b) in input.iter().enumerate() {
32        if skip {
33            skip = false;
34            continue;
35        }
36        match *b {
37            b'A' ..= b'Z' | b'a' ..= b'z' | b'0' ..= b'9' => {
38                ret.push(*b as char);
39            },
40            0x1B => {
41                if let Some(b) = input.get(i+1) {
42                    for &(ch, val) in GSM_EXTENDED_ENCODING_TABLE.iter() {
43                        if val == *b {
44                            ret.push(ch);
45                            skip = true;
46                        }
47                    }
48                }
49            },
50            b => {
51                for &(ch, val) in GSM_ENCODING_TABLE.iter() {
52                    if val == b {
53                        ret.push(ch);
54                    }
55                }
56            }
57        }
58    }
59    ret
60}
61/// Tries to encode a character into the given destination buffer, returning `true` if the
62/// character was successfully encoded, and `false` if the character cannot be represented in the
63/// GSM 7-bit encoding.
64pub fn try_gsm_encode_char(b: char, dest: &mut Vec<u8>) -> bool {
65    match b {
66        'A' ..= 'Z' | 'a' ..= 'z' | '0' ..= '9' => {
67            dest.push(b as u8);
68            return true;
69        },
70        b => {
71            for &(ch, val) in GSM_ENCODING_TABLE.iter() {
72                if b == ch {
73                    dest.push(val);
74                    return true;
75                }
76            }
77            for &(ch, val) in GSM_EXTENDED_ENCODING_TABLE.iter() {
78                if b == ch {
79                    dest.push(0x1B);
80                    dest.push(val);
81                    return true;
82                }
83            }
84        }
85    }
86    false
87}
88/// Tries to encode a string as GSM 7-bit, returning a buffer of **unpacked** septets iff all of
89/// the data in `input` was representable in the 7-bit encoding.
90///
91/// **Warning:** The output of this function is unsuitable for transmission across the network;
92/// you need to pack the septets first! See the `pdu` module for more.
93pub fn try_gsm_encode_string(input: &str) -> Option<Vec<u8>> {
94    let mut ret = vec![];
95    for c in input.chars() {
96        if !try_gsm_encode_char(c, &mut ret) {
97            return None;
98        }
99    }
100    Some(ret)
101}
102fn split_buffers(buf: Vec<u8>, max_len: usize) -> Vec<Vec<u8>> {
103    let mut ret = vec![];
104    let mut cbuf = buf;
105    while max_len < cbuf.len() {
106        let split = cbuf.split_off(max_len);
107        let old = ::std::mem::replace(&mut cbuf, split);
108        ret.push(old);
109    }
110    ret.push(cbuf);
111    ret
112}
113/// The 'data' portion of an SMS message - i.e. the text, for a simple message.
114#[derive(Debug, Clone)]
115pub struct GsmMessageData {
116    pub encoding: MessageEncoding,
117    pub udh: bool,
118    pub bytes: Vec<u8>,
119    pub user_data_len: u8
120}
121/// A decoded text mesasge, with optional user data header.
122#[derive(Debug, Clone, Default)]
123pub struct DecodedMessage {
124    /// Decoded text.
125    pub text: String,
126    /// User data header. You'll want this to check if the message is concatenated, i.e. is part of
127    /// a multi-part series.
128    pub udh: Option<UserDataHeader>
129}
130impl GsmMessageData {
131    /// Get the message encoding.
132    pub fn encoding(&self) -> &MessageEncoding {
133        &self.encoding
134    }
135    /// Get the underlying bytes.
136    pub fn as_bytes(&self) -> &[u8] {
137        &self.bytes
138    }
139    /// Get the user data length.
140    pub fn user_data_len(&self) -> u8 {
141        self.user_data_len
142    }
143    /// Attempt to decode this message.
144    pub fn decode_message(&self) -> PDUResult<DecodedMessage> {
145        use encoding::{Encoding, DecoderTrap};
146        use encoding::all::UTF_16BE;
147        let mut padding = 0;
148        let mut start = 0;
149        let mut udh = None;
150        if self.udh {
151            if self.bytes.len() < 1 {
152                Err(PDUError::InvalidPdu("UDHI specified, but no data"))?
153            }
154            let udhl = self.bytes[0] as usize;
155            padding = 7 - (((udhl + 1) * 8) % 7);
156            start = udhl + 1;
157            if self.bytes.len() < start {
158                Err(PDUError::InvalidPdu("UDHL goes past end of data"))?
159            }
160            udh = Some(UserDataHeader::try_from(&self.bytes[1..start])?);
161        }
162        if self.bytes.get(start).is_none() {
163            return Ok(DecodedMessage {
164                text: String::new(),
165                udh
166            });
167        }
168        match self.encoding {
169            MessageEncoding::Gsm7Bit => {
170                let buf = decode_sms_7bit(&self.bytes[start..], padding, self.user_data_len as _);
171                Ok(DecodedMessage {
172                    text: gsm_decode_string(&buf),
173                    udh
174                })
175            },
176            MessageEncoding::Ucs2 => {
177                Ok(DecodedMessage {
178                    text: UTF_16BE.decode(&self.bytes[start..], DecoderTrap::Replace).unwrap(),
179                    udh
180                })
181            },
182            x => Err(PDUError::UnsupportedEncoding(x, self.bytes.clone()))
183        }
184    }
185    /// Encode an arbitrary string of text into one, or multiple, GSM message data segments.
186    ///
187    /// If this function returns more than one bit of data, it means it's been split into multiple
188    /// concatenated parts for you, and you'll need to send each part individually in order, as
189    /// part of a new `Pdu` to your desired recipient.
190    pub fn encode_message(msg: &str) -> Vec<GsmMessageData> {
191        use encoding::{Encoding, EncoderTrap};
192        use encoding::all::UTF_16BE;
193        use rand;
194
195        if let Some(buf) = try_gsm_encode_string(msg) {
196            let user_data_len = buf.len();
197            if user_data_len > 160 {
198                // time to make a Concatenated SMS
199                let bufs = split_buffers(buf, 153);
200                let csms_ref = rand::random::<u8>();
201                let num_parts = bufs.len() as u8;
202                bufs.into_iter()
203                    .enumerate()
204                    .map(|(i, buf)| {
205                        let udh = UserDataHeader {
206                            components: vec![UdhComponent {
207                                id: 0,
208                                data: vec![csms_ref, num_parts, i as u8 + 1]
209                            }]
210                        };
211                        let mut ret = udh.as_bytes();
212                        let padding = 7 - ((ret.len() * 8) % 7);
213                        let len = ((ret.len() * 8) + padding + (buf.len() * 7)) / 7;
214                        let enc = encode_sms_7bit(&buf, padding);
215                        ret.extend(enc);
216                        GsmMessageData {
217                            encoding: MessageEncoding::Gsm7Bit,
218                            bytes: ret,
219                            udh: true,
220                            user_data_len: len as u8
221                        }
222                    })
223                    .collect()
224            }
225            else {
226                let buf = encode_sms_7bit(&buf, 0);
227                vec![GsmMessageData {
228                    encoding: MessageEncoding::Gsm7Bit,
229                    bytes: buf,
230                    udh: false,
231                    user_data_len: user_data_len as u8
232                }]
233            }
234        }
235        else {
236            let buf = UTF_16BE.encode(msg, EncoderTrap::Replace).unwrap();
237            let user_data_len = buf.len();
238            if user_data_len > 140 {
239                // time to make a Concatenated SMS
240                let bufs = split_buffers(buf, 134);
241                let csms_ref = rand::random::<u8>();
242                let num_parts = bufs.len() as u8;
243                bufs.into_iter()
244                    .enumerate()
245                    .map(|(i, buf)| {
246                        let udh = UserDataHeader {
247                            components: vec![UdhComponent {
248                                id: 0,
249                                data: vec![csms_ref, num_parts, i as u8 + 1]
250                            }]
251                        };
252                        let mut ret = udh.as_bytes();
253                        ret.extend(buf);
254                        let len = ret.len();
255                        GsmMessageData {
256                            encoding: MessageEncoding::Ucs2,
257                            bytes: ret,
258                            udh: true,
259                            user_data_len: len as u8
260                        }
261                    })
262                    .collect()
263            }
264            else {
265                vec![GsmMessageData {
266                    encoding: MessageEncoding::Ucs2,
267                    bytes: buf,
268                    udh: false,
269                    user_data_len: user_data_len as u8
270                }]
271            }
272        }
273    }
274}
275// This function wins the "I spent a *goddamn hour* debugging this crap" award.
276// The best part? The bug wasn't even in this function...!
277pub(crate) fn decode_sms_7bit(orig: &[u8], padding: usize, len: usize) -> Vec<u8> {
278    let mut ret = vec![0];
279    // Number of bits in the current octet that come from the current septet.
280    let mut chars_cur = 7;
281    let mut i = 0;
282    if padding > 0 && orig.len() > 0 {
283        chars_cur = padding;
284    }
285    for (j, data) in orig.iter().enumerate() {
286        if chars_cur == 0 {
287            chars_cur = 7;
288            ret.push(0);
289            i += 1;
290        }
291        let next = data >> chars_cur;
292        let cur = ((data << (8 - chars_cur)) >> (8 - chars_cur)) << (7 - chars_cur);
293        ret[i] |= cur;
294        if j+1 < orig.len() || ret.len() < len {
295            ret.push(next);
296        }
297        chars_cur -= 1;
298        i += 1;
299    }
300    if padding > 0 && ret.len() > 0 {
301        ret.remove(0);
302    }
303    ret
304}
305pub(crate) fn encode_sms_7bit(orig: &[u8], padding: usize) -> Vec<u8> {
306    let mut ret = vec![];
307    // Number of bits in the current octet that come from the current septet.
308    let mut chars_cur = 7;
309    if padding > 0 && orig.len() > 0 {
310        chars_cur = padding;
311        let cur = orig[0] << padding;
312        ret.push(cur);
313        chars_cur -= 1;
314    }
315    for (i, data) in orig.iter().enumerate() {
316        if chars_cur == 0 {
317            chars_cur = 7;
318            continue;
319        }
320        let mut cur = (*data & 0b01111111) >> (7 - chars_cur);
321        let next = if let Some(n) = orig.get(i+1) {
322            *n << chars_cur
323        }
324        else {
325            0
326        };
327        cur |= next;
328        ret.push(cur);
329        chars_cur -= 1;
330    }
331    ret
332}