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