rsipstack 0.5.6

SIP Stack Rust library for building SIP applications
Documentation
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
use super::{sip_addr::SipAddr, stream::StreamConnection, tcp::TcpConnection, udp::UdpConnection};
use crate::sip::headers::untyped::Via;
use crate::sip::{
    prelude::{HeadersExt, ToTypedHeader},
    HostWithPort, Param, SipMessage, Transport,
};
use crate::transport::channel::ChannelConnection;
use crate::transport::websocket::{WebSocketConnection, WebSocketListenerConnection};
use crate::transport::{
    tcp_listener::TcpListenerConnection,
    tls::{TlsConnection, TlsListenerConnection},
};
use crate::Result;
use get_if_addrs::IfAddr;
use std::net::{IpAddr, Ipv4Addr};
use std::{fmt, net::SocketAddr};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio_util::sync::CancellationToken;
use tracing::debug;

/// Transport Layer Events
///
/// `TransportEvent` represents events that occur at the transport layer,
/// such as incoming messages, new connections, and connection closures.
/// These events are used to coordinate between the transport layer and
/// higher protocol layers.
///
/// # Events
///
/// * `Incoming` - A SIP message was received from the network
/// * `New` - A new connection has been established
/// * `Closed` - An existing connection has been closed
///
/// # Examples
///
/// ```rust,no_run
/// use rsipstack::transport::connection::TransportEvent;
///
/// # fn handle_event(event: TransportEvent) {
/// match event {
///     TransportEvent::Incoming(message, connection, source) => {
///         // Process incoming SIP message
///         println!("Received message from {}", source);
///     },
///     TransportEvent::New(connection) => {
///         // Handle new connection
///         println!("New connection established");
///     },
///     TransportEvent::Closed(connection) => {
///         // Handle connection closure
///         println!("Connection closed");
///     }
/// }
/// # }
/// ```
#[derive(Debug)]
pub enum TransportEvent {
    Incoming(SipMessage, SipConnection, SipAddr),
    New(SipConnection),
    Closed(SipConnection),
}

pub type TransportReceiver = UnboundedReceiver<TransportEvent>;
pub type TransportSender = UnboundedSender<TransportEvent>;

pub const KEEPALIVE_REQUEST: &[u8] = b"\r\n\r\n";
pub const KEEPALIVE_RESPONSE: &[u8] = b"\r\n";
pub const MAX_UDP_BUF_SIZE: usize = 8192;

/// SIP Connection
///
/// `SipConnection` is an enum that abstracts different transport protocols
/// used for SIP communication. It provides a unified interface for sending
/// SIP messages regardless of the underlying transport mechanism.
///
/// # Supported Transports
///
/// * `Udp` - UDP transport for connectionless communication
/// * `Channel` - In-memory channel for testing and local communication
/// * `Tcp` - TCP transport for reliable connection-oriented communication
/// * `Tls` - TLS transport for secure communication over TCP
/// * `WebSocket` - WebSocket transport for web-based SIP clients
///
/// # Key Features
///
/// * Transport abstraction - uniform interface across protocols
/// * Reliability detection - distinguishes reliable vs unreliable transports
/// * Address management - tracks local and remote addresses
/// * Message sending - handles protocol-specific message transmission
/// * Via header processing - automatic received parameter handling
///
/// # Examples
///
/// ```rust,no_run
/// use rsipstack::transport::{SipConnection, SipAddr};
/// use rsipstack::sip::SipMessage;
///
/// // Send a message through any connection type
/// async fn send_message(
///     connection: &SipConnection,
///     message: SipMessage,
///     destination: Option<&SipAddr>
/// ) -> rsipstack::Result<()> {
///     connection.send(message, destination).await?;
///     Ok(())
/// }
///
/// # fn example(connection: &SipConnection) {
/// // Check if transport is reliable
/// let is_reliable = connection.is_reliable();
/// if is_reliable {
///     println!("Using reliable transport");
/// } else {
///     println!("Using unreliable transport - retransmissions may be needed");
/// }
/// # }
/// ```
///
/// # Transport Characteristics
///
/// ## UDP
/// * Connectionless and unreliable
/// * Requires retransmission handling
/// * Lower overhead
/// * Default SIP transport
///
/// ## TCP
/// * Connection-oriented and reliable
/// * No retransmission needed
/// * Higher overhead
/// * Better for large messages
///
/// ## TLS
/// * Secure TCP with encryption
/// * Reliable transport
/// * Certificate-based authentication
/// * Used for SIPS URIs
///
/// ## WebSocket
/// * Web-friendly transport
/// * Reliable connection
/// * Firewall and NAT friendly
/// * Used in web applications
///
/// # Via Header Processing
///
/// SipConnection automatically handles Via header processing for incoming
/// messages, adding 'received' and 'rport' parameters as needed per RFC 3261.
#[derive(Clone, Debug)]
pub enum SipConnection {
    Channel(ChannelConnection),
    Udp(UdpConnection),
    Tcp(TcpConnection),
    TcpListener(TcpListenerConnection),
    #[cfg(feature = "rustls")]
    Tls(TlsConnection),
    #[cfg(feature = "rustls")]
    TlsListener(TlsListenerConnection),
    #[cfg(feature = "websocket")]
    WebSocket(WebSocketConnection),
    #[cfg(feature = "websocket")]
    WebSocketListener(WebSocketListenerConnection),
}

impl SipConnection {
    pub fn is_reliable(&self) -> bool {
        match self {
            SipConnection::Udp(_) => false,
            _ => true,
        }
    }

    pub fn cancel_token(&self) -> Option<CancellationToken> {
        match self {
            SipConnection::Channel(transport) => transport.cancel_token(),
            SipConnection::Udp(transport) => transport.cancel_token(),
            SipConnection::Tcp(transport) => transport.cancel_token(),
            #[cfg(feature = "rustls")]
            SipConnection::Tls(transport) => transport.cancel_token(),
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(transport) => transport.cancel_token(),
            _ => None,
        }
    }
    pub fn get_addr(&self) -> &SipAddr {
        match self {
            SipConnection::Channel(transport) => transport.get_addr(),
            SipConnection::Udp(transport) => transport.get_addr(),
            SipConnection::Tcp(transport) => transport.get_addr(),
            SipConnection::TcpListener(transport) => transport.get_addr(),
            #[cfg(feature = "rustls")]
            SipConnection::Tls(transport) => transport.get_addr(),
            #[cfg(feature = "rustls")]
            SipConnection::TlsListener(transport) => transport.get_addr(),
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(transport) => transport.get_addr(),
            #[cfg(feature = "websocket")]
            SipConnection::WebSocketListener(transport) => transport.get_addr(),
        }
    }
    pub async fn send(&self, msg: SipMessage, destination: Option<&SipAddr>) -> Result<()> {
        match self {
            SipConnection::Channel(transport) => transport.send(msg).await,
            SipConnection::Udp(transport) => transport.send(msg, destination).await,
            SipConnection::Tcp(transport) => transport.send_message(msg).await,
            SipConnection::TcpListener(_) => {
                debug!("SipConnection::send: TcpListener cannot send messages");
                Ok(())
            }
            #[cfg(feature = "rustls")]
            SipConnection::Tls(transport) => transport.send_message(msg).await,
            #[cfg(feature = "rustls")]
            SipConnection::TlsListener(_) => {
                debug!("SipConnection::send: TlsListener cannot send messages");
                Ok(())
            }
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(transport) => transport.send_message(msg).await,
            #[cfg(feature = "websocket")]
            SipConnection::WebSocketListener(_) => {
                debug!("SipConnection::send: WebSocketListener cannot send messages");
                Ok(())
            }
        }
    }
    pub async fn serve_loop(&self, sender: TransportSender) -> Result<()> {
        match self {
            SipConnection::Channel(transport) => transport.serve_loop(sender).await,
            SipConnection::Udp(transport) => transport.serve_loop(sender).await,
            SipConnection::Tcp(transport) => transport.serve_loop(sender).await,
            SipConnection::TcpListener(_) => {
                debug!("SipConnection::serve_loop: TcpListener does not have serve_loop");
                Ok(())
            }
            #[cfg(feature = "rustls")]
            SipConnection::Tls(transport) => transport.serve_loop(sender).await,
            #[cfg(feature = "rustls")]
            SipConnection::TlsListener(_) => {
                debug!("SipConnection::serve_loop: TlsListener does not have serve_loop");
                Ok(())
            }
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(transport) => transport.serve_loop(sender).await,
            #[cfg(feature = "websocket")]
            SipConnection::WebSocketListener(_) => {
                debug!("SipConnection::serve_loop: WebSocketListener does not have serve_loop");
                Ok(())
            }
        }
    }

    pub async fn close(&self) -> Result<()> {
        match self {
            SipConnection::Channel(transport) => transport.close().await,
            SipConnection::Udp(_) => Ok(()), // UDP has no connection state
            SipConnection::Tcp(transport) => transport.close().await,
            SipConnection::TcpListener(transport) => transport.close().await,
            #[cfg(feature = "rustls")]
            SipConnection::Tls(transport) => transport.close().await,
            #[cfg(feature = "rustls")]
            SipConnection::TlsListener(transport) => transport.close().await,
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(transport) => transport.close().await,
            #[cfg(feature = "websocket")]
            SipConnection::WebSocketListener(transport) => transport.close().await,
        }
    }
}

impl SipConnection {
    pub fn update_msg_received(
        msg: SipMessage,
        addr: SocketAddr,
        transport: Transport,
    ) -> Result<SipMessage> {
        match msg {
            SipMessage::Request(mut req) => {
                let via = req.via_header_mut()?;
                Self::build_via_received(via, addr, transport)?;
                Ok(req.into())
            }
            SipMessage::Response(_) => Ok(msg),
        }
    }

    pub fn resolve_bind_address(addr: SocketAddr) -> SocketAddr {
        let ip = addr.ip();
        if ip.is_unspecified() {
            // 0.0.0.0 or ::
            let interfaces = match get_if_addrs::get_if_addrs() {
                Ok(interfaces) => interfaces,
                Err(_) => return addr,
            };
            for interface in interfaces {
                if interface.is_loopback() {
                    continue;
                }
                match interface.addr {
                    IfAddr::V4(v4addr) => {
                        return SocketAddr::new(IpAddr::V4(v4addr.ip), addr.port());
                    }
                    //TODO: don't support ipv6 for now
                    _ => continue,
                }
            }
            // fallback to loopback
            return SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), addr.port());
        }
        addr
    }
    pub fn build_via_received(via: &mut Via, addr: SocketAddr, transport: Transport) -> Result<()> {
        let received = addr.into();
        let mut typed_via = via.typed()?;

        typed_via.params.retain(|param| match param {
            Param::Rport(_) | Param::Received(_) => false,
            _ => true,
        });

        // Only add received parameter if the source address differs from Via header
        if typed_via.uri.host_with_port == received {
            return Ok(());
        }

        // For reliable transports (TCP/TLS/WS), we need to be more careful about received parameter
        let should_add_received = match transport {
            Transport::Udp => true,
            _ => {
                // For connection-oriented protocols, only add if explicitly different
                typed_via.uri.host_with_port.host != received.host
            }
        };

        if !should_add_received {
            return Ok(());
        }

        if transport != Transport::Udp && typed_via.transport != transport {
            typed_via.params.push(Param::Transport(transport));
        }

        let received_str = match addr {
            SocketAddr::V6(_) => format!("[{}]", received.host),
            _ => received.host.to_string(),
        };
        typed_via
            .params
            .push(Param::Received(crate::sip::param::Received::new(
                received_str,
            )));
        typed_via.params.push(Param::Rport(Some(addr.port())));
        *via = typed_via.into();
        Ok(())
    }

    pub fn parse_target_from_via(via: &Via) -> Result<(Transport, HostWithPort)> {
        let typed_via = via.typed()?;
        let mut host_with_port = typed_via.uri.host_with_port.clone();
        let mut transport = typed_via.transport.clone();
        for param in &typed_via.params {
            match param {
                Param::Received(v) => {
                    if let Ok(addr) = v.parse() {
                        host_with_port.host = addr.into();
                    }
                }
                Param::Transport(t) => {
                    transport = t.clone();
                }
                Param::Rport(Some(port)) => {
                    host_with_port.port = Some((*port).into());
                }
                _ => {}
            }
        }
        Ok((transport, host_with_port))
    }

    pub fn get_destination(msg: &SipMessage) -> Result<SocketAddr> {
        let host_with_port = match msg {
            SipMessage::Request(req) => req.uri().host_with_port.clone(),
            SipMessage::Response(res) => Self::parse_target_from_via(res.via_header()?)?.1,
        };
        host_with_port.try_into().map_err(Into::into)
    }
}

impl fmt::Display for SipConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SipConnection::Channel(t) => write!(f, "{}", t),
            SipConnection::Udp(t) => write!(f, "UDP {}", t),
            SipConnection::Tcp(t) => write!(f, "TCP {}", t),
            SipConnection::TcpListener(t) => write!(f, "TCP LISTEN {}", t),
            #[cfg(feature = "rustls")]
            SipConnection::Tls(t) => write!(f, "{}", t),
            #[cfg(feature = "rustls")]
            SipConnection::TlsListener(t) => write!(f, "TLS LISTEN {}", t),
            #[cfg(feature = "websocket")]
            SipConnection::WebSocket(t) => write!(f, "{}", t),
            #[cfg(feature = "websocket")]
            SipConnection::WebSocketListener(t) => write!(f, "WS LISTEN {}", t),
        }
    }
}

impl From<ChannelConnection> for SipConnection {
    fn from(connection: ChannelConnection) -> Self {
        SipConnection::Channel(connection)
    }
}

impl From<UdpConnection> for SipConnection {
    fn from(connection: UdpConnection) -> Self {
        SipConnection::Udp(connection)
    }
}

impl From<TcpConnection> for SipConnection {
    fn from(connection: TcpConnection) -> Self {
        SipConnection::Tcp(connection)
    }
}

impl From<TcpListenerConnection> for SipConnection {
    fn from(connection: TcpListenerConnection) -> Self {
        SipConnection::TcpListener(connection)
    }
}

impl From<TlsConnection> for SipConnection {
    fn from(connection: TlsConnection) -> Self {
        SipConnection::Tls(connection)
    }
}

#[cfg(feature = "rustls")]
impl From<TlsListenerConnection> for SipConnection {
    fn from(connection: TlsListenerConnection) -> Self {
        SipConnection::TlsListener(connection)
    }
}

impl From<WebSocketConnection> for SipConnection {
    fn from(connection: WebSocketConnection) -> Self {
        SipConnection::WebSocket(connection)
    }
}

#[cfg(feature = "websocket")]
impl From<WebSocketListenerConnection> for SipConnection {
    fn from(connection: WebSocketListenerConnection) -> Self {
        SipConnection::WebSocketListener(connection)
    }
}