1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use std::{net::SocketAddr, time::Duration};
use futures::Stream;
use rusmpp::tokio_codec::CommandCodec;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpStream,
};
use tokio_util::codec::Framed;
use crate::{Client, Event, MaybeTlsStream, delay::TokioDelay, error::Error};
/// Builder for creating a new `SMPP` connection.
#[derive(Debug)]
pub struct ConnectionBuilder {
pub(crate) max_command_length: usize,
pub(crate) enquire_link_interval: Option<Duration>,
/// Timeout for waiting for a an enquire link response from the server.
pub(crate) enquire_link_response_timeout: Duration,
/// Whether to automatically respond to enquire link requests from the server.
pub(crate) auto_enquire_link_response: bool,
/// Timeout for waiting for a response from the server.
pub(crate) response_timeout: Option<Duration>,
pub(crate) check_interface_version: bool,
/// TLS configurations provided by the user. If None, default configurations will be used.
#[cfg(feature = "rustls")]
rustls_config: Option<rustls::ClientConfig>,
/// Native TLS connector provided by the user. If None, default connector will be used.
#[cfg(feature = "native-tls")]
native_tls_connector: Option<native_tls::TlsConnector>,
}
impl Default for ConnectionBuilder {
fn default() -> Self {
Self::new()
}
}
impl ConnectionBuilder {
/// Creates a new [`ConnectionBuilder`] with default configurations.
///
/// # Defaults
/// - `max_command_length`: 4096 bytes
/// - `enquire_link_interval`: 30 seconds
/// - `enquire_link_response_timeout`: 5 seconds
/// - `auto_enquire_link_response`: true
/// - `response_timeout`: 5 seconds
/// - `check_interface_version`: true
/// - `rustls_config`: default configuration will be used if TLS is enabled. See [`rustls_config`](Self::rustls_config) for more details.
/// - `native_tls_connector`: default connector will be used if TLS is enabled. See [`native_tls_connector`](Self::native_tls_connector) for more details.
pub fn new() -> Self {
Self {
max_command_length: 4096,
enquire_link_interval: Some(Duration::from_secs(30)),
enquire_link_response_timeout: Duration::from_secs(5),
auto_enquire_link_response: true,
response_timeout: Some(Duration::from_secs(5)),
check_interface_version: true,
#[cfg(feature = "rustls")]
rustls_config: None,
#[cfg(feature = "native-tls")]
native_tls_connector: None,
}
}
/// Does not spawn the connection in the background.
///
/// It is your responsibility to run the connection to completion.
pub fn no_spawn(self) -> NoSpawnConnectionBuilder {
NoSpawnConnectionBuilder { builder: self }
}
/// Connects to the `SMPP` server.
///
/// Opens and manages a connection in the background and returns a client and an event stream.
///
/// - The client is used as a handle to communicate with the server through the managed connection.
/// - The event stream is used to receive events from the server, such as incoming messages or errors.
///
/// # Example
///
/// Connect to an `SMPP` server running on localhost at port 2775.
///
/// ```
/// # use rusmppc::ConnectionBuilder;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let (client, events) = ConnectionBuilder::new()
/// .connect("smpp://localhost:2775")
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// Connect to an `SMPP` server running on localhost at port 2775 using TLS.
///
/// ```
/// # use rusmppc::ConnectionBuilder;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let (client, events) = ConnectionBuilder::new()
/// .connect("smpps://localhost:2775")
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Supported URL schemes
/// - `smpp`: Connect using plain TCP.
/// - `ssmpp` or `smpps`: Connect using TLS. Requires the `rustls` or `native-tls` features to be enabled.
///
/// # Notes
/// - If no port is specified in the URL, the default port `2775` will be used.
/// - Path and query parameters in the URL are ignored silently.
///
/// # Errors
///
/// This function will return an error in the following cases:
///
/// - If the URL is invalid. See [`url::Url::parse`] for more details.
/// - If the URL scheme is not supported. Supported schemes are `smpp`, `ssmpp`, and `smpps`.
/// - If the URL does not have a host.
/// - If DNS resolution fails.
/// - If the connection to the server fails.
/// - If TLS is enabled (when using `ssmpp` or `smpps` schemes) but the `rustls` or `native-tls` features are not enabled.
/// - If TLS handshake fails.
pub async fn connect(
self,
url: impl AsRef<str>,
) -> Result<(Client, impl Stream<Item = Event> + Unpin + 'static), Error> {
let (client, events, connection) = self.no_spawn().connect(url).await?;
tokio::spawn(connection);
Ok((client, events))
}
/// Creates a client from an existing connection.
///
/// Manages a connection in the background and returns a client and an event stream.
///
/// - The client is used as a handle to communicate with the server through the managed connection.
/// - The event stream is used to receive events from the server, such as incoming messages or errors.
pub fn connected<S>(self, stream: S) -> (Client, impl Stream<Item = Event> + Unpin + 'static)
where
S: AsyncRead + AsyncWrite + Send + 'static,
{
let (client, events, connection) = self.no_spawn().connected(stream);
tokio::spawn(connection);
(client, events)
}
}
impl ConnectionBuilder {
/// Sets the maximum command length for incoming commands.
pub const fn max_command_length(mut self, max_command_length: usize) -> Self {
self.max_command_length = max_command_length;
self
}
/// Sets the enquire link interval.
///
/// Used to determine how often an enquire link command should be sent to the server.
pub fn enquire_link_interval(mut self, enquire_link_interval: Duration) -> Self {
self.enquire_link_interval = Some(enquire_link_interval);
self
}
/// Disables the enquire link interval.
///
/// When disabled, no enquire link commands will be sent to the server.
pub fn no_enquire_link_interval(mut self) -> Self {
self.enquire_link_interval = None;
self
}
/// Sets the enquire link interval.
///
/// If set to `None`, no enquire link commands will be sent to the server.
pub fn with_enquire_link_interval(mut self, enquire_link_interval: Option<Duration>) -> Self {
self.enquire_link_interval = enquire_link_interval;
self
}
/// Sets the enquire link response timeout.
///
/// This timeout is used to determine how long the connection should wait for an enquire link response from the server.
pub fn enquire_link_response_timeout(
mut self,
enquire_link_response_timeout: Duration,
) -> Self {
self.enquire_link_response_timeout = enquire_link_response_timeout;
self
}
/// Enables automatic responses to enquire link requests from the server.
///
/// See [`with_auto_enquire_link_response`](Self::with_auto_enquire_link_response) for more details.
pub fn enable_auto_enquire_link_response(mut self) -> Self {
self.auto_enquire_link_response = true;
self
}
/// Disables automatic responses to enquire link requests from the server.
///
/// See [`with_auto_enquire_link_response`](Self::with_auto_enquire_link_response) for more details.
pub fn disable_auto_enquire_link_response(mut self) -> Self {
self.auto_enquire_link_response = false;
self
}
/// Sets whether to automatically respond to enquire link requests from the server.
///
/// By default, this is set to `true`.
///
/// When enabled, the connection will automatically respond to any enquire link requests received from the server.
///
/// When disabled, the client will need to handle enquire link requests manually. The [`EnquireLink`](rusmpp::Pdu::EnquireLink) command will be received as an event in the event stream.
pub fn with_auto_enquire_link_response(mut self, auto: bool) -> Self {
self.auto_enquire_link_response = auto;
self
}
/// Sets the response timeout.
///
/// This timeout is used to determine how long the client should wait for a response from the server.
///
/// The timer is started after the command has been sent to the server.
pub fn response_timeout(mut self, response_timeout: Duration) -> Self {
self.response_timeout = Some(response_timeout);
self
}
/// Disables the response timeout.
///
/// When disabled, the client will wait indefinitely for a response from the server.
pub fn no_response_timeout(mut self) -> Self {
self.response_timeout = None;
self
}
/// Sets the response timeout.
///
/// If set to `None`, no timeout will be used and the client will wait indefinitely for a response from the server.
pub fn with_response_timeout(mut self, response_timeout: Option<Duration>) -> Self {
self.response_timeout = response_timeout;
self
}
/// Enables the interface version check.
///
/// See [`with_interface_version_check`](Self::with_interface_version_check) for more details.
pub fn enable_interface_version_check(mut self) -> Self {
self.check_interface_version = true;
self
}
/// Disables the interface version check.
///
/// See [`with_interface_version_check`](Self::with_interface_version_check) for more details.
pub fn disable_interface_version_check(mut self) -> Self {
self.check_interface_version = false;
self
}
/// Enables or disables the interface version check.
///
/// By default, the interface version check is enabled.
///
/// This library uses `SMPP v5` implementation to encode and decode commands.
///
/// Binding to a server with another `SMPP` version may cause issues encoding and decoding commands.
/// Disable interface version check to allow binding to servers with any `SMPP` version.
pub fn with_interface_version_check(mut self, check: bool) -> Self {
self.check_interface_version = check;
self
}
/// Sets a custom `rustls` client configuration.
///
/// If not set, a default configuration will be used.
/// - If the `rustls-tls-native-roots` feature is enabled, native root certificates are used.
/// - If the `rustls-tls-webpki-roots` feature is enabled, webpki root certificates are used.
#[cfg(feature = "rustls")]
pub fn rustls_config(mut self, config: rustls::ClientConfig) -> Self {
self.rustls_config = Some(config);
self
}
/// Sets a custom `native-tls` connector.
///
/// If not set, a default connector will be used.
#[cfg(feature = "native-tls")]
pub fn native_tls_connector(mut self, connector: native_tls::TlsConnector) -> Self {
self.native_tls_connector = Some(connector);
self
}
}
/// Builder for creating a new `SMPP` connection without spawning it in the background.
#[derive(Debug)]
pub struct NoSpawnConnectionBuilder {
pub(crate) builder: ConnectionBuilder,
}
impl NoSpawnConnectionBuilder {
/// Connects to the `SMPP` server without spawning the connection in the background.
///
/// # Errors
///
/// This function will return an error in the following cases:
///
/// - If the URL is invalid. See [`url::Url::parse`] for more details.
/// - If the URL scheme is not supported. Supported schemes are `smpp`, `ssmpp`, and `smpps`.
/// - If the URL does not have a host.
/// - If DNS resolution fails.
/// - If the connection to the server fails.
/// - If TLS is enabled (when using `ssmpp` or `smpps` schemes) but the `rustls` or `native-tls` features are not enabled.
/// - If TLS handshake fails.
#[allow(unused_mut)]
pub async fn connect(
mut self,
url: impl AsRef<str>,
) -> Result<
(
Client,
impl Stream<Item = Event> + Unpin + 'static,
impl Future<Output = ()> + 'static,
),
Error,
> {
enum Scheme {
Smpp,
Ssmpp,
}
let url = url::Url::parse(url.as_ref()).map_err(|err| {
Error::Connect(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Invalid URL: {err}"),
))
})?;
let scheme = match url.scheme() {
"smpp" => Scheme::Smpp,
"ssmpp" | "smpps" => Scheme::Ssmpp,
scheme => {
return Err(Error::Connect(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"Unsupported URL scheme: {scheme}, supported schemes are smpp and ssmpp/smpps"
),
)));
}
};
let domain = url.host_str().ok_or_else(|| {
Error::Connect(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"URL must have a host",
))
})?;
let port = url.port().unwrap_or(2775);
tracing::debug!(target: "rusmppc::connection::dns", domain, "Resolving domain");
let resolver = hickory_resolver::TokioResolver::builder_tokio()
.map_err(|err| {
Error::Connect(std::io::Error::other(format!(
"Failed to create DNS resolver: {err}"
)))
})?
.build();
let ip_addr = resolver
.lookup_ip(domain)
.await
.map_err(|err| {
Error::Connect(std::io::Error::other(format!("Failed to lookup IP: {err}")))
})?
.into_iter()
.next()
.ok_or_else(|| {
Error::Connect(std::io::Error::new(
std::io::ErrorKind::NotFound,
"No addresses found for the given host",
))
})?;
let socket_addr = SocketAddr::new(ip_addr, port);
tracing::debug!(target: "rusmppc::connection::tcp", %socket_addr, "Connecting");
let stream = TcpStream::connect(socket_addr)
.await
.map_err(Error::Connect)?;
tracing::debug!(target: "rusmppc::connection::tcp", %socket_addr, "Connected");
let stream = match scheme {
Scheme::Smpp => MaybeTlsStream::plain(stream),
Scheme::Ssmpp => {
#[cfg(all(feature = "rustls", not(feature = "native-tls")))]
{
MaybeTlsStream::rustls(stream, domain, self.builder.rustls_config.take())
.await?
}
// If both features are enabled, prefer rustls.
#[cfg(all(feature = "rustls", feature = "native-tls"))]
{
tracing::warn!(target: "rusmppc::connection::tls", "Both `rustls` and `native-tls` features are enabled, preferring `rustls` for TLS connections");
MaybeTlsStream::rustls(stream, domain, self.builder.rustls_config.take())
.await?
}
#[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
{
MaybeTlsStream::native_tls(
stream,
domain,
self.builder.native_tls_connector.take(),
)
.await?
}
#[cfg(not(any(feature = "rustls", feature = "native-tls")))]
{
return Err(Error::Connect(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"TLS support is not enabled, enable the `rustls` or `native-tls` feature to use ssmpp/smpps",
)));
}
}
};
Ok(self.connected(stream))
}
/// Creates a client from an existing connection without spawning the connection in the background.
pub fn connected<S>(
self,
stream: S,
) -> (
Client,
impl Stream<Item = Event> + Unpin + 'static,
impl Future<Output = ()>,
)
where
S: AsyncRead + AsyncWrite + Send + 'static,
{
let framed = Framed::new(
stream,
CommandCodec::new().with_max_length(self.builder.max_command_length),
);
self.raw(framed, TokioDelay::new(), TokioDelay::new())
}
}