Skip to main content

smpp_codec/
common.rs

1//! # Common Definitions
2//!
3//! This module contains common constants, error types, and helper functions used throughout the library.
4
5// --- Command IDs ---
6// These constants define the Command ID for each SMPP PDU.
7
8/// Command ID for Bind Receiver.
9pub const CMD_BIND_RECEIVER: u32 = 0x00000001;
10/// Command ID for Bind Receiver Response.
11pub const CMD_BIND_RECEIVER_RESP: u32 = 0x80000001;
12
13/// Command ID for Bind Transmitter.
14pub const CMD_BIND_TRANSMITTER: u32 = 0x00000002;
15/// Command ID for Bind Transmitter Response.
16pub const CMD_BIND_TRANSMITTER_RESP: u32 = 0x80000002;
17
18/// Command ID for Bind Transceiver.
19pub const CMD_BIND_TRANSCEIVER: u32 = 0x00000009;
20/// Command ID for Bind Transceiver Response.
21pub const CMD_BIND_TRANSCEIVER_RESP: u32 = 0x80000009;
22
23/// Command ID for Outbind.
24pub const CMD_OUTBIND: u32 = 0x0000000B;
25
26/// Command ID for Enquire Link.
27pub const CMD_ENQUIRE_LINK: u32 = 0x00000015;
28/// Command ID for Enquire Link Response.
29pub const CMD_ENQUIRE_LINK_RESP: u32 = 0x80000015;
30
31/// Command ID for Submit SM.
32pub const CMD_SUBMIT_SM: u32 = 0x00000004;
33/// Command ID for Submit SM Response.
34pub const CMD_SUBMIT_SM_RESP: u32 = 0x80000004;
35
36/// Command ID for Deliver SM.
37pub const CMD_DELIVER_SM: u32 = 0x00000005;
38/// Command ID for Deliver SM Response.
39pub const CMD_DELIVER_SM_RESP: u32 = 0x80000005;
40
41/// Command ID for Unbind.
42pub const CMD_UNBIND: u32 = 0x00000006;
43/// Command ID for Unbind Response.
44pub const CMD_UNBIND_RESP: u32 = 0x80000006;
45
46/// Command ID for Submit Multi SM.
47pub const CMD_SUBMIT_MULTI_SM: u32 = 0x00000021;
48/// Command ID for Submit Multi SM Response.
49pub const CMD_SUBMIT_MULTI_SM_RESP: u32 = 0x80000021;
50
51/// Command ID for Query SM.
52pub const CMD_QUERY_SM: u32 = 0x00000003;
53/// Command ID for Query SM Response.
54pub const CMD_QUERY_SM_RESP: u32 = 0x80000003;
55
56/// Command ID for Cancel SM.
57pub const CMD_CANCEL_SM: u32 = 0x00000008;
58/// Command ID for Cancel SM Response.
59pub const CMD_CANCEL_SM_RESP: u32 = 0x80000008;
60
61/// Command ID for Replace SM.
62pub const CMD_REPLACE_SM: u32 = 0x00000007;
63/// Command ID for Replace SM Response.
64pub const CMD_REPLACE_SM_RESP: u32 = 0x80000007;
65
66/// Command ID for Data SM.
67pub const CMD_DATA_SM: u32 = 0x00000103;
68/// Command ID for Data SM Response.
69pub const CMD_DATA_SM_RESP: u32 = 0x80000103;
70
71/// Command ID for Alert Notification.
72pub const CMD_ALERT_NOTIFICATION: u32 = 0x00000102;
73/// Command ID for Alert Notification Response (Note: Alert Notification does not have a standard response, but some implementations might use one).
74pub const CMD_ALERT_NOTIFICATION_RESP: u32 = 0x80000102;
75
76/// Generic NACK.
77pub const GENERIC_NACK: u32 = 0x80000000;
78
79/// Command ID for Broadcast SM.
80pub const CMD_BROADCAST_SM: u32 = 0x00000111;
81/// Command ID for Broadcast SM Response.
82pub const CMD_BROADCAST_SM_RESP: u32 = 0x80000112;
83
84/// Command ID for Query Broadcast SM.
85pub const CMD_QUERY_BROADCAST_SM: u32 = 0x00000112;
86/// Command ID for Query Broadcast SM Response.
87pub const CMD_QUERY_BROADCAST_SM_RESP: u32 = 0x80000112;
88
89/// Command ID for Cancel Broadcast SM.
90pub const CMD_CANCEL_BROADCAST_SM: u32 = 0x00000113;
91/// Command ID for Cancel Broadcast SM Response.
92pub const CMD_CANCEL_BROADCAST_SM_RESP: u32 = 0x80000113;
93
94/// Standard Header Length
95pub const HEADER_LEN: usize = 16;
96
97/// SMPP Interface Version
98pub const SMPP_INTERFACE_VERSION_34: u8 = 0x34;
99/// SMPP Interface Version 5.0
100pub const SMPP_INTERFACE_VERSION_50: u8 = 0x50;
101
102/// Address Type of Number (TON)
103#[derive(Debug, Clone, Copy, PartialEq)]
104#[repr(u8)]
105pub enum Ton {
106    /// Unknown
107    Unknown = 0x00,
108    /// International
109    International = 0x01,
110    /// National
111    National = 0x02,
112    /// Network Specific
113    NetworkSpecific = 0x03,
114    /// Subscriber Number
115    SubscriberNumber = 0x04,
116    /// Alphanumeric
117    Alphanumeric = 0x05,
118    /// Abbreviated
119    Abbreviated = 0x06,
120}
121
122impl From<u8> for Ton {
123    fn from(value: u8) -> Self {
124        match value {
125            0x01 => Ton::International,
126            0x02 => Ton::National,
127            0x03 => Ton::NetworkSpecific,
128            0x04 => Ton::SubscriberNumber,
129            0x05 => Ton::Alphanumeric,
130            0x06 => Ton::Abbreviated,
131            _ => Ton::Unknown,
132        }
133    }
134}
135
136/// Address Numbering Plan Indicator (NPI)
137#[derive(Debug, Clone, Copy, PartialEq)]
138#[repr(u8)]
139pub enum Npi {
140    /// Unknown
141    Unknown = 0x00,
142    /// ISDN
143    Isdn = 0x01,
144    /// Data
145    Data = 0x03,
146    /// Telex
147    Telex = 0x04,
148    /// Land Mobile
149    LandMobile = 0x06,
150    /// National
151    National = 0x08,
152    /// Private
153    Private = 0x09,
154    /// ERMES
155    Ermes = 0x0A,
156    /// Internet
157    Internet = 0x0E,
158    /// WAP
159    Wap = 0x12,
160}
161
162impl From<u8> for Npi {
163    fn from(value: u8) -> Self {
164        match value {
165            0x01 => Npi::Isdn,
166            0x03 => Npi::Data,
167            0x04 => Npi::Telex,
168            0x06 => Npi::LandMobile,
169            0x08 => Npi::National,
170            0x09 => Npi::Private,
171            0x0A => Npi::Ermes,
172            0x0E => Npi::Internet,
173            0x12 => Npi::Wap,
174            _ => Npi::Unknown,
175        }
176    }
177}
178
179/// Command Status
180pub const COMMAND_STATUS_OK: u32 = 0x00000000;
181
182/// Helper function to get error description from status code
183pub fn get_status_description(status: u32) -> String {
184    match status {
185        0x00000000 => "ESME_ROK".to_string(),
186        0x00000001 => "ESME_RINVMSGLEN".to_string(),
187        0x00000002 => "ESME_RINVCMDLEN".to_string(),
188        0x00000003 => "ESME_RINVCMDID".to_string(),
189        0x00000004 => "ESME_RINVBNDSTS".to_string(),
190        0x00000005 => "ESME_RALYBND".to_string(),
191        0x00000006 => "ESME_RINVPRTFLG".to_string(),
192        0x00000007 => "ESME_RINVREGDLVFLG".to_string(),
193        0x00000008 => "ESME_RSYSERR".to_string(),
194        0x0000000A => "ESME_RINVSRCADR".to_string(),
195        0x0000000B => "ESME_RINVDSTADR".to_string(),
196        0x0000000C => "ESME_RINVMSGID".to_string(),
197        0x0000000D => "ESME_RBINDFAIL".to_string(),
198        0x0000000E => "ESME_RINVPASWD".to_string(),
199        0x0000000F => "ESME_RINVSYSID".to_string(),
200        0x00000011 => "ESME_RCANCELFAIL".to_string(),
201        0x00000013 => "ESME_RREPLACEFAIL".to_string(),
202        0x00000014 => "ESME_RMSGQFUL".to_string(),
203        0x00000015 => "ESME_RINVSERVICETYPE".to_string(),
204        0x00000033 => "ESME_RINVNUMDESTS".to_string(),
205        0x00000034 => "ESME_RINVDLNAME".to_string(),
206        0x00000040 => "ESME_RINVDESTFLAG".to_string(),
207        0x00000042 => "ESME_RINVSUBREP".to_string(),
208        0x00000043 => "ESME_RINVESMCLASS".to_string(),
209        0x00000044 => "ESME_RCNTSUBDL".to_string(),
210        0x00000045 => "ESME_RSUBMITFAIL".to_string(),
211        0x00000048 => "ESME_RINVSRCTON".to_string(),
212        0x00000049 => "ESME_RINVSRCNPI".to_string(),
213        0x00000050 => "ESME_RINVDSTTON".to_string(),
214        0x00000051 => "ESME_RINVDSTNPI".to_string(),
215        0x00000053 => "ESME_RINVSYSTYP".to_string(),
216        0x00000054 => "ESME_RINVREPFLAG".to_string(),
217        0x00000055 => "ESME_RINVNUMMSGS".to_string(),
218        0x00000058 => "ESME_RTHROTTLED".to_string(),
219        0x00000061 => "ESME_RINVSCHED".to_string(),
220        0x00000062 => "ESME_RINVEXPIRY".to_string(),
221        0x00000063 => "ESME_RINVDFTMSGID".to_string(),
222        0x00000064 => "ESME_RX_T_APPN".to_string(),
223        0x00000065 => "ESME_RX_P_APPN".to_string(),
224        0x00000066 => "ESME_RX_R_APPN".to_string(),
225        0x00000067 => "ESME_RQUERYFAIL".to_string(),
226        0x000000C0 => "ESME_RINVOPTPARSTREAM".to_string(),
227        0x000000C1 => "ESME_ROPTPARNOTALLWD".to_string(),
228        0x000000C2 => "ESME_RINVPARLEN".to_string(),
229        0x000000C3 => "ESME_RMISSINGOPTPARAM".to_string(),
230        0x000000C4 => "ESME_RINVOPTPARAMVAL".to_string(),
231        0x000000FE => "ESME_RDELIVERYFAILURE".to_string(),
232        0x000000FF => "ESME_RUNKNOWNERR".to_string(),
233        _ => format!("Unknown Error: 0x{:08X}", status),
234    }
235}
236
237/// Helper function to get status code from description (Reverse lookup)
238pub fn get_status_code(name: &str) -> u32 {
239    match name {
240        "ESME_ROK" => 0x00000000,
241        "ESME_RINVMSGLEN" => 0x00000001,
242        "ESME_RINVCMDLEN" => 0x00000002,
243        "ESME_RINVCMDID" => 0x00000003,
244        "ESME_RINVBNDSTS" => 0x00000004,
245        "ESME_RALYBND" => 0x00000005,
246        "ESME_RINVPRTFLG" => 0x00000006,
247        "ESME_RINVREGDLVFLG" => 0x00000007,
248        "ESME_RSYSERR" => 0x00000008,
249        "ESME_RINVSRCADR" => 0x0000000A,
250        "ESME_RINVDSTADR" => 0x0000000B,
251        "ESME_RINVMSGID" => 0x0000000C,
252        "ESME_RBINDFAIL" => 0x0000000D,
253        "ESME_RINVPASWD" => 0x0000000E,
254        "ESME_RINVSYSID" => 0x0000000F,
255        "ESME_RCANCELFAIL" => 0x00000011,
256        "ESME_RREPLACEFAIL" => 0x00000013,
257        "ESME_RMSGQFUL" => 0x00000014,
258        "ESME_RINVSERVICETYPE" => 0x00000015,
259        "ESME_RINVNUMDESTS" => 0x00000033,
260        "ESME_RINVDLNAME" => 0x00000034,
261        "ESME_RINVDESTFLAG" => 0x00000040,
262        "ESME_RINVSUBREP" => 0x00000042,
263        "ESME_RINVESMCLASS" => 0x00000043,
264        "ESME_RCNTSUBDL" => 0x00000044,
265        "ESME_RSUBMITFAIL" => 0x00000045,
266        "ESME_RINVSRCTON" => 0x00000048,
267        "ESME_RINVSRCNPI" => 0x00000049,
268        "ESME_RINVDSTTON" => 0x00000050,
269        "ESME_RINVDSTNPI" => 0x00000051,
270        "ESME_RINVSYSTYP" => 0x00000053,
271        "ESME_RINVREPFLAG" => 0x00000054,
272        "ESME_RINVNUMMSGS" => 0x00000055,
273        "ESME_RTHROTTLED" => 0x00000058,
274        "ESME_RINVSCHED" => 0x00000061,
275        "ESME_RINVEXPIRY" => 0x00000062,
276        "ESME_RINVDFTMSGID" => 0x00000063,
277        "ESME_RX_T_APPN" => 0x00000064,
278        "ESME_RX_P_APPN" => 0x00000065,
279        "ESME_RX_R_APPN" => 0x00000066,
280        "ESME_RQUERYFAIL" => 0x00000067,
281        "ESME_RINVOPTPARSTREAM" => 0x000000C0,
282        "ESME_ROPTPARNOTALLWD" => 0x000000C1,
283        "ESME_RINVPARLEN" => 0x000000C2,
284        "ESME_RMISSINGOPTPARAM" => 0x000000C3,
285        "ESME_RINVOPTPARAMVAL" => 0x000000C4,
286        "ESME_RDELIVERYFAILURE" => 0x000000FE,
287        "ESME_RUNKNOWNERR" => 0x000000FF,
288        _ => 0x000000FF, // Default to Unknown Error if string not found
289    }
290}
291
292/// Bind Mode (Receiver, Transmitter, Transceiver)
293#[derive(Debug, Clone, Copy, PartialEq)]
294pub enum BindMode {
295    /// Receiver Mode
296    Receiver,
297    /// Transmitter Mode
298    Transmitter,
299    /// Transceiver Mode
300    Transceiver,
301}
302
303impl BindMode {
304    /// Returns the Command ID corresponding to the Bind Mode
305    pub fn command_id(&self) -> u32 {
306        match self {
307            BindMode::Receiver => CMD_BIND_RECEIVER,
308            BindMode::Transmitter => CMD_BIND_TRANSMITTER,
309            BindMode::Transceiver => CMD_BIND_TRANSCEIVER,
310        }
311    }
312}
313
314// Custom Error for PDU operations
315/// Error type for PDU operations
316#[derive(Debug)]
317pub enum PduError {
318    /// IO Error
319    Io(std::io::Error),
320    /// UTF-8 Conversion Error
321    Utf8(std::string::FromUtf8Error),
322    /// Buffer is too short to contain expected data
323    BufferTooShort,
324    /// Invalid Command ID encountered
325    InvalidCommandId(u32),
326    /// String exceeds maximum allowed length
327    StringTooLong(String, usize), // Field name, Max len
328    /// Invalid Length for a field
329    InvalidLength,
330}
331
332// Convert IO errors to PduError
333impl From<std::io::Error> for PduError {
334    fn from(err: std::io::Error) -> Self {
335        PduError::Io(err)
336    }
337}
338
339impl std::fmt::Display for PduError {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        match self {
342            PduError::Io(err) => write!(f, "IO Error: {}", err),
343            PduError::Utf8(err) => write!(f, "UTF8 Error: {}", err),
344            PduError::BufferTooShort => write!(f, "Buffer contains insufficient data"),
345            PduError::InvalidCommandId(id) => write!(f, "Invalid Command ID: 0x{:08X}", id),
346            PduError::StringTooLong(field, max) => {
347                write!(f, "String too long for field '{}' (max: {})", field, max)
348            }
349            PduError::InvalidLength => write!(f, "Invalid length for field"),
350        }
351    }
352}
353
354impl std::error::Error for PduError {
355    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
356        match self {
357            PduError::Io(err) => Some(err),
358            PduError::Utf8(err) => Some(err),
359            _ => None,
360        }
361    }
362}
363
364/// optimized helper to read a C-Style string from a Cursor<&[u8]>
365pub fn read_c_string(cursor: &mut std::io::Cursor<&[u8]>) -> Result<String, PduError> {
366    let current_pos = cursor.position() as usize;
367    let inner = cursor.get_ref();
368
369    if current_pos >= inner.len() {
370        return Err(PduError::Io(std::io::Error::from(
371            std::io::ErrorKind::UnexpectedEof,
372        )));
373    }
374
375    let remaining = &inner[current_pos..];
376
377    // Find null byte efficiently using slice iter
378    match remaining.iter().position(|&b| b == 0) {
379        Some(null_idx) => {
380            let s_bytes = &remaining[..null_idx];
381            let s = String::from_utf8(s_bytes.to_vec()).map_err(PduError::Utf8)?;
382            cursor.set_position((current_pos + null_idx + 1) as u64);
383            Ok(s)
384        }
385        None => Err(PduError::Io(std::io::Error::from(
386            std::io::ErrorKind::UnexpectedEof,
387        ))),
388    }
389}
390
391/// Helper to write a C-Style string (null terminated)
392pub fn write_c_string(w: &mut impl std::io::Write, s: &str) -> std::io::Result<()> {
393    w.write_all(s.as_bytes())?;
394    w.write_all(&[0])
395}