rsipstack 0.8.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Transaction state transition tests
//!
//! This module contains comprehensive tests for transaction state transitions
//! according to RFC 3261 Section 17.

use super::create_test_endpoint;
use crate::sip::headers::*;
use crate::transaction::{
    key::{TransactionKey, TransactionRole},
    transaction::Transaction,
    TransactionState, TransactionTimer, TransactionType,
};
use crate::transport::udp::UdpConnection;
use crate::transport::SipConnection;

/// Test helper to create a mock request
fn create_test_request(method: crate::sip::Method, branch: &str) -> crate::sip::Request {
    let cseq_header = CSeq::new(format!("1 {}", method)).into();
    crate::sip::Request {
        method,
        uri: crate::sip::Uri::try_from("sip:test.example.com:5060").unwrap(),
        headers: vec![
            Via::new(format!(
                "SIP/2.0/UDP test.example.com:5060;branch={}",
                branch
            ))
            .into(),
            cseq_header,
            From::new("Alice <sip:alice@example.com>;tag=1928301774").into(),
            To::new("Bob <sip:bob@example.com>").into(),
            CallId::new("a84b4c76e66710@pc33.atlanta.com").into(),
            MaxForwards::new("70").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: Default::default(),
    }
}

#[tokio::test]
async fn test_client_invite_transaction_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;

    // Create INVITE request
    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Client)?;

    let tx = Transaction::new_client(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        None, // No connection needed for basic tests
    );

    // Initial state should be Calling
    assert_eq!(tx.state, TransactionState::Nothing);
    assert_eq!(tx.transaction_type, TransactionType::ClientInvite);

    Ok(())
}

#[tokio::test]
async fn test_client_non_invite_transaction_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;

    // Create REGISTER request (non-INVITE)
    let register_req = create_test_request(crate::sip::Method::Register, "z9hG4bKnashds");
    let key = TransactionKey::from_request(&register_req, TransactionRole::Client)?;

    let tx = Transaction::new_client(
        key.clone(),
        register_req.clone(),
        endpoint.inner.clone(),
        None,
    );

    // Initial state should be Calling
    assert_eq!(tx.state, TransactionState::Nothing);
    assert_eq!(tx.transaction_type, TransactionType::ClientNonInvite);

    Ok(())
}

#[tokio::test]
async fn test_server_invite_transaction_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;

    // Create INVITE request for server
    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        None,
    );

    // Initial state should be Trying
    assert_eq!(tx.state, TransactionState::Trying);
    assert_eq!(tx.transaction_type, TransactionType::ServerInvite);

    Ok(())
}

#[tokio::test]
async fn test_server_non_invite_transaction_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;

    // Create REGISTER request for server
    let register_req = create_test_request(crate::sip::Method::Register, "z9hG4bKnashds");
    let key = TransactionKey::from_request(&register_req, TransactionRole::Server)?;

    let tx = Transaction::new_server(
        key.clone(),
        register_req.clone(),
        endpoint.inner.clone(),
        None,
    );

    // Initial state should be Trying
    assert_eq!(tx.state, TransactionState::Trying);
    assert_eq!(tx.transaction_type, TransactionType::ServerNonInvite);

    Ok(())
}

#[tokio::test]
async fn test_transaction_key_generation() -> crate::Result<()> {
    // Test transaction key generation for different roles
    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bKnashds");

    let client_key = TransactionKey::from_request(&invite_req, TransactionRole::Client)?;
    let server_key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    // Keys should be different for different roles
    assert_ne!(client_key, server_key);

    // Same request and role should generate same key
    let client_key2 = TransactionKey::from_request(&invite_req, TransactionRole::Client)?;
    assert_eq!(client_key, client_key2);

    Ok(())
}

#[tokio::test]
async fn test_transaction_types() -> crate::Result<()> {
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;

    // Test INVITE transaction type
    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bKnashds");
    let invite_key = TransactionKey::from_request(&invite_req, TransactionRole::Client)?;
    let invite_tx = Transaction::new_client(invite_key, invite_req, endpoint.inner.clone(), None);
    assert_eq!(invite_tx.transaction_type, TransactionType::ClientInvite);

    // Test non-INVITE transaction type
    let register_req = create_test_request(crate::sip::Method::Register, "z9hG4bKnashds2");
    let register_key = TransactionKey::from_request(&register_req, TransactionRole::Client)?;
    let register_tx =
        Transaction::new_client(register_key, register_req, endpoint.inner.clone(), None);
    assert_eq!(
        register_tx.transaction_type,
        TransactionType::ClientNonInvite
    );

    Ok(())
}

// ===========================================================================
// RFC 6026 conformance tests
//
// Validate the Accepted state and Timer L / Timer M behaviour required by
// RFC 6026 §7.1 (server INVITE) + §7.2 (client INVITE).
//
// Test design notes:
// - Display-impl tests are pure unit tests — no async setup required.
// - State-machine tests use a mock UDP connection bound to 127.0.0.1:0
//   so respond() can issue a real UDP send into the void; UDP is
//   connectionless so the send succeeds even with no peer listener,
//   letting the state transition fire without a full peer orchestration.
// - Timer L / Timer M actually firing (transitioning Accepted → Terminated
//   after 64*T1 ≈ 32s) is NOT exercised here because waiting 32s per test
//   would balloon the suite runtime; instead these tests verify
//   timer_l.is_some() / timer_m.is_some() to confirm the timers are armed.
//   The transition logic itself is exercised by the unit-level state
//   machine in transaction.rs on_timer dispatch.
// ===========================================================================

/// Helper: mock UDP connection on localhost for tests that exercise respond().
/// The connection sends UDP packets to a bogus loopback port — UDP is
/// connectionless so the send succeeds (packets are dropped at the OS).
async fn mock_udp_connection() -> crate::Result<SipConnection> {
    let conn = UdpConnection::create_connection("127.0.0.1:0".parse()?, None, None).await?;
    Ok(conn.into())
}

#[test]
fn test_rfc6026_accepted_state_display() {
    // RFC 6026 §7.1/§7.2 exposes the Accepted state via the public
    // TransactionState Display impl. Lock the rendering so external
    // observers (logs, metrics, debug dumps) see "Accepted".
    assert_eq!(
        format!("{}", TransactionState::Accepted),
        "Accepted",
        "TransactionState::Accepted must Display as `Accepted` (RFC 6026 §7.1/§7.2)",
    );
}

#[test]
fn test_rfc6026_timer_l_display() {
    // RFC 6026 §7.1 server INVITE Accepted-state timer.
    let request = crate::sip::Request {
        method: crate::sip::Method::Invite,
        uri: crate::sip::Uri::try_from("sip:bob@example.com").unwrap(),
        headers: vec![
            Via::new("SIP/2.0/UDP example.com:5060;branch=z9hG4bKtimerL").into(),
            CSeq::new("1 INVITE").into(),
            From::new("Alice <sip:alice@example.com>;tag=t1").into(),
            CallId::new("call-l@example.com").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: Default::default(),
    };
    let key = TransactionKey::from_request(&request, TransactionRole::Server).unwrap();
    let timer = TransactionTimer::TimerL(key.clone());
    assert_eq!(format!("{}", timer), format!("TimerL: {}", key));
}

#[test]
fn test_rfc6026_timer_m_display() {
    // RFC 6026 §7.2 client INVITE Accepted-state timer.
    let request = crate::sip::Request {
        method: crate::sip::Method::Invite,
        uri: crate::sip::Uri::try_from("sip:bob@example.com").unwrap(),
        headers: vec![
            Via::new("SIP/2.0/UDP example.com:5060;branch=z9hG4bKtimerM").into(),
            CSeq::new("1 INVITE").into(),
            From::new("Alice <sip:alice@example.com>;tag=t1").into(),
            CallId::new("call-m@example.com").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: Default::default(),
    };
    let key = TransactionKey::from_request(&request, TransactionRole::Client).unwrap();
    let timer = TransactionTimer::TimerM(key.clone());
    assert_eq!(format!("{}", timer), format!("TimerM: {}", key));
}

#[tokio::test]
async fn test_rfc6026_server_invite_2xx_routes_to_accepted_with_timer_l() -> crate::Result<()> {
    // RFC 6026 §7.1: server INVITE 2xx final response transitions
    // Proceeding/Trying → Accepted (NOT Completed), and arms Timer L.
    // Timer G IS armed as a documented deviation (see lib.rs): strict §7.1
    // leaves 2xx retransmission to the TU, but the rsipstack dialog layer
    // does not retransmit, so the transaction keeps the RFC 3261
    // §13.3.1.4 wire behavior (2xx retransmitted until ACK or Timer L).
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srv2xx");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    tx.reply(crate::sip::StatusCode::OK).await?;

    assert_eq!(
        tx.state,
        TransactionState::Accepted,
        "server INVITE 2xx must route to Accepted per RFC 6026 §7.1, not Completed",
    );
    assert!(
        tx.timer_l.is_some(),
        "Accepted state must arm Timer L (= 64*T1) per RFC 6026 §7.1",
    );
    assert!(
        tx.timer_g.is_some(),
        "Accepted state arms Timer G (documented deviation): the dialog layer does not retransmit 2xx, so the transaction keeps the RFC 3261 §13.3.1.4 retransmission",
    );
    Ok(())
}

#[tokio::test]
async fn test_rfc6026_server_invite_4xx_still_routes_to_completed() -> crate::Result<()> {
    // RFC 3261 §17.2.1 regression: non-2xx final responses (3xx-6xx) must
    // continue to route to Completed (not Accepted) so the existing Timer G
    // retransmit + Timer K + Timer D semantics for ACK matching are preserved.
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srv404");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    tx.reply(crate::sip::StatusCode::NotFound).await?;

    assert_eq!(
        tx.state,
        TransactionState::Completed,
        "server INVITE 4xx must continue to route to Completed (RFC 3261 §17.2.1 retained)",
    );
    Ok(())
}

#[tokio::test]
async fn test_rfc6026_server_invite_accepted_registers_waiting_ack() -> crate::Result<()> {
    // RFC 6026 §7.1: when a server INVITE transaction enters Accepted, it
    // MUST register itself in the dialog-layer ACK routing map so the
    // forthcoming ACK (sent by the UAC outside this transaction per
    // §17.1.1.3) lands at this transaction key. The waiting_ack map keyed
    // by DialogId is rsipstack's canonical routing primitive.
    use crate::dialog::DialogId;

    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srvack");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    tx.reply(crate::sip::StatusCode::OK).await?;

    // The 200 OK has been stored as last_response; derive the dialog_id
    // (server role) and check that the waiting_ack map points back to us.
    let last_response = tx
        .last_response
        .as_ref()
        .expect("respond() must store the 2xx in last_response");
    let dialog_id = DialogId::try_from((last_response, TransactionRole::Server))?;
    let registered = endpoint.inner.waiting_ack.get(&dialog_id);
    assert!(
        registered.is_some(),
        "Accepted-state entry must register the dialog in waiting_ack for ACK routing per RFC 6026 §7.1",
    );
    assert_eq!(
        registered.expect("registered"),
        key,
        "waiting_ack entry must point back to this transaction key",
    );
    Ok(())
}

#[tokio::test]
async fn test_rfc6026_server_invite_3xx_still_arms_timer_g() -> crate::Result<()> {
    // RFC 6026 §7.1 retains Timer G for non-2xx final responses
    // (the §7.1 prohibition is "MUST NOT generate 2xx retransmissions",
    // explicitly NOT a blanket ban). This regression test ensures the
    // server-side 3xx-6xx Timer G retransmit path remains live.
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srvtimerg");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    tx.reply(crate::sip::StatusCode::ServerInternalError)
        .await?;

    assert_eq!(tx.state, TransactionState::Completed);
    assert!(
        tx.timer_g.is_some(),
        "non-2xx final must continue to arm Timer G (RFC 3261 §17.2.1 retained; RFC 6026 §7.1 only prohibits 2xx retransmits)",
    );
    Ok(())
}

#[tokio::test]
async fn test_rfc6026_server_invite_accepted_absorbs_duplicate_2xx() -> crate::Result<()> {
    // RFC 6026 §7.1: 'absorb retransmissions of the INVITE after a 2xx
    // response has been sent' implies the server transaction MUST tolerate
    // a TU-retransmitted 2xx in the Accepted state — the response is
    // re-sent through the transport but no state error is raised. The
    // can_transition() (Accepted, Accepted) self-loop edge enables this.
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srvdup");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    let response_1 = tx.reply(crate::sip::StatusCode::OK).await;
    response_1?;
    assert_eq!(tx.state, TransactionState::Accepted);

    // Second TU-driven 2xx (e.g. retransmit per §7.1 forwarding rule):
    // must succeed without state-machine error; transaction stays in
    // Accepted (the (Accepted, Accepted) edge in can_transition).
    tx.reply(crate::sip::StatusCode::OK).await?;
    assert_eq!(
        tx.state,
        TransactionState::Accepted,
        "duplicate 2xx in Accepted must keep the transaction in Accepted, not raise a transition error",
    );
    Ok(())
}

#[tokio::test]
async fn test_rfc6026_server_invite_accepted_rejects_3xx_transition() -> crate::Result<()> {
    // can_transition matrix: once a server INVITE has entered Accepted (2xx
    // already sent), a subsequent 3xx-6xx attempt must be rejected. The
    // matrix has no (Accepted, Completed) edge so respond() should error.
    let endpoint = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let conn = mock_udp_connection().await?;

    let invite_req = create_test_request(crate::sip::Method::Invite, "z9hG4bK6026srvreject");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

    let mut tx = Transaction::new_server(
        key.clone(),
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(conn),
    );
    tx.destination = Some(crate::transport::SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));

    tx.reply(crate::sip::StatusCode::OK).await?;
    assert_eq!(tx.state, TransactionState::Accepted);

    // Now try sending a 4xx — this is illegal per the can_transition matrix
    // (Accepted has no edge to Completed). reply() should return an Err.
    let err = tx.reply(crate::sip::StatusCode::BusyHere).await;
    assert!(
        err.is_err(),
        "reply() must reject Accepted → Completed (no such edge in can_transition matrix)",
    );
    Ok(())
}

#[tokio::test]
async fn test_server_non_invite_timer_j_is_zero_on_reliable_transport() -> crate::Result<()> {
    // RFC 3261 §17.2.2: When the server non-INVITE transaction enters the
    // "Completed" state, it MUST set Timer J to fire in 64*T1 seconds for
    // unreliable transports, and zero seconds for reliable transports.
    use crate::transport::{channel::ChannelConnection, SipAddr};
    use tokio::sync::mpsc::unbounded_channel;

    // Reliable transport (ChannelConnection has is_reliable() == true).
    let endpoint_tcp = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let (to_net_tx, _to_net_rx) = unbounded_channel();
    let (_from_net_tx, from_net_rx) = unbounded_channel();
    let tcp_conn: SipConnection = ChannelConnection::create_connection(
        from_net_rx,
        to_net_tx,
        SipAddr {
            r#type: Some(crate::sip::Transport::Tcp),
            addr: "127.0.0.1:5060".try_into()?,
        },
        None,
    )
    .await?
    .into();
    assert!(tcp_conn.is_reliable());

    let register_req = create_test_request(crate::sip::Method::Register, "z9hG4bKtimerjtcp");
    let key_tcp = TransactionKey::from_request(&register_req, TransactionRole::Server)?;
    let mut tx_tcp = Transaction::new_server(
        key_tcp,
        register_req.clone(),
        endpoint_tcp.inner.clone(),
        Some(tcp_conn),
    );
    tx_tcp.reply(crate::sip::StatusCode::OK).await?;
    assert_eq!(tx_tcp.state, TransactionState::Terminated);
    assert_eq!(
        endpoint_tcp.inner.get_stats().finished_transactions,
        0,
        "Timer J must be 0 on reliable transports (RFC 3261 §17.2.2)"
    );

    // Unreliable transport (UDP has is_reliable() == false).
    let endpoint_udp = create_test_endpoint(Some("127.0.0.1:0")).await?;
    let udp_conn = mock_udp_connection().await?;
    assert!(!udp_conn.is_reliable());

    let key_udp = TransactionKey::from_request(&register_req, TransactionRole::Server)?;
    let mut tx_udp = Transaction::new_server(
        key_udp,
        register_req,
        endpoint_udp.inner.clone(),
        Some(udp_conn),
    );
    tx_udp.destination = Some(SipAddr::from(
        "127.0.0.1:1".parse::<std::net::SocketAddr>()?,
    ));
    tx_udp.reply(crate::sip::StatusCode::OK).await?;
    assert_eq!(tx_udp.state, TransactionState::Terminated);
    assert_eq!(
        endpoint_udp.inner.get_stats().finished_transactions,
        1,
        "Timer J must retain the final response for 64*T1 on UDP (RFC 3261 §17.2.2)"
    );

    Ok(())
}