rsipstack 0.5.10

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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Dialog layer tests
//!
//! This module contains tests for dialog management and lifecycle

use crate::dialog::{dialog_layer::DialogLayer, DialogId};
use crate::sip::{headers::*, prelude::HeadersExt, HostWithPort, Param, Request, Transport};
use crate::transaction::{
    endpoint::EndpointBuilder,
    key::{TransactionKey, TransactionRole},
    transaction::Transaction,
};
use crate::transport::{
    tcp_listener::TcpListenerConnection, udp::UdpConnection, SipAddr, TransportLayer,
};
use tokio::sync::mpsc::unbounded_channel;
use tokio_util::sync::CancellationToken;

/// Test helper to create a test endpoint
async fn create_test_endpoint() -> crate::Result<crate::transaction::endpoint::Endpoint> {
    let token = CancellationToken::new();
    let tl = TransportLayer::new(token.child_token());
    let endpoint = EndpointBuilder::new()
        .with_user_agent("rsipstack-test")
        .with_transport_layer(tl)
        .build();
    Ok(endpoint)
}

/// Test helper to create mock INVITE request
fn create_invite_request(from_tag: &str, to_tag: &str, call_id: &str, branch: &str) -> Request {
    Request {
        method: crate::sip::Method::Invite,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060").unwrap(),
        headers: vec![
            Via::new(&format!(
                "SIP/2.0/UDP alice.example.com:5060;branch={}",
                branch
            ))
            .into(),
            CSeq::new("1 INVITE").into(),
            From::new(&format!("Alice <sip:alice@example.com>;tag={}", from_tag)).into(),
            To::new(&format!("Bob <sip:bob@example.com>;tag={}", to_tag)).into(),
            CallId::new(call_id).into(),
            Contact::new("<sip:alice@alice.example.com:5060>").into(),
            MaxForwards::new("70").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: b"v=0\r\no=alice 2890844526 2890844527 IN IP4 host.atlanta.com\r\n".to_vec(),
    }
}

/// Test helper to create mock connection
async fn create_mock_connection() -> crate::Result<crate::transport::SipConnection> {
    let udp_conn = UdpConnection::create_connection("127.0.0.1:0".parse()?, None, None).await?;
    Ok(udp_conn.into())
}

#[tokio::test]
async fn test_dialog_layer_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());

    // Initial state should be empty
    assert_eq!(dialog_layer.len(), 0);

    // Test sequence number increment
    let seq1 = dialog_layer.increment_last_seq();
    let seq2 = dialog_layer.increment_last_seq();
    assert_eq!(seq2, seq1 + 1);

    Ok(())
}

#[tokio::test]
async fn test_server_invite_dialog_creation() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // Create INVITE request without to-tag (new dialog)
    let invite_req = create_invite_request("alice-tag-123", "", "call-id-456", "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;

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

    let (state_sender, _state_receiver) = unbounded_channel();

    // Create server invite dialog
    let dialog = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    // Dialog should be created and stored
    assert_eq!(dialog_layer.len(), 1);

    // Dialog ID should have generated to-tag
    let dialog_id = dialog.id();
    assert_eq!(dialog_id.call_id, "call-id-456");
    assert_eq!(dialog_id.remote_tag, "alice-tag-123");
    assert!(!dialog_id.local_tag.is_empty());

    Ok(())
}

#[tokio::test]
async fn test_existing_server_invite_dialog_retrieval() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // First request creates dialog
    let invite_req1 = create_invite_request("alice-tag-123", "", "call-id-456", "z9hG4bKnashds1");
    let key1 = TransactionKey::from_request(&invite_req1, TransactionRole::Server)?;
    let tx1 = Transaction::new_server(
        key1,
        invite_req1,
        endpoint.inner.clone(),
        Some(mock_conn.clone()),
    );

    let (state_sender, _) = unbounded_channel();

    let dialog1 = dialog_layer.get_or_create_server_invite(
        &tx1,
        state_sender.clone(),
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    let dialog_id = dialog1.id();

    // Second request with same dialog identifiers should retrieve existing dialog
    let invite_req2 = create_invite_request(
        "alice-tag-123",
        &dialog_id.local_tag,
        "call-id-456",
        "z9hG4bKnashds2",
    );
    let key2 = TransactionKey::from_request(&invite_req2, TransactionRole::Server)?;
    let tx2 = Transaction::new_server(key2, invite_req2, endpoint.inner.clone(), Some(mock_conn));

    let dialog2 = dialog_layer.get_or_create_server_invite(
        &tx2,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    // Should be the same dialog
    assert_eq!(dialog1.id(), dialog2.id());
    assert_eq!(dialog_layer.len(), 1);

    Ok(())
}

#[tokio::test]
async fn test_dialog_retrieval_and_matching() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // Create a dialog
    let invite_req = create_invite_request("alice-tag-123", "", "call-id-456", "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
    let tx = Transaction::new_server(
        key,
        invite_req.clone(),
        endpoint.inner.clone(),
        Some(mock_conn.clone()),
    );

    let (state_sender, _) = unbounded_channel();

    let dialog = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    let dialog_id = dialog.id();

    // Test direct retrieval
    let retrieved_dialog = dialog_layer.get_dialog(&dialog_id);
    assert!(retrieved_dialog.is_some());

    // Test request matching
    let bye_req = Request {
        method: crate::sip::Method::Bye,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060")?,
        headers: vec![
            Via::new("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKbye").into(),
            CSeq::new("2 BYE").into(),
            From::new(&format!(
                "Alice <sip:alice@example.com>;tag={}",
                dialog_id.remote_tag
            ))
            .into(),
            To::new(&format!(
                "Bob <sip:bob@example.com>;tag={}",
                dialog_id.local_tag
            ))
            .into(),
            CallId::new(&dialog_id.call_id).into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: vec![],
    };

    let bye_key = TransactionKey::from_request(&bye_req, TransactionRole::Server)?;
    let bye_tx = Transaction::new_server(bye_key, bye_req, endpoint.inner.clone(), Some(mock_conn));
    let matched_dialog = dialog_layer.match_dialog(&bye_tx);
    assert!(matched_dialog.is_some());

    Ok(())
}

#[tokio::test]
async fn test_dialog_removal() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // Create a dialog
    let invite_req = create_invite_request("alice-tag-123", "", "call-id-456", "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
    let tx = Transaction::new_server(key, invite_req, endpoint.inner.clone(), Some(mock_conn));

    let (state_sender, _) = unbounded_channel();

    let dialog = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    let dialog_id = dialog.id();

    // Verify dialog exists
    assert_eq!(dialog_layer.len(), 1);
    assert!(dialog_layer.get_dialog(&dialog_id).is_some());

    // Remove dialog
    dialog_layer.remove_dialog(&dialog_id);

    // Verify dialog is removed
    assert_eq!(dialog_layer.len(), 0);
    assert!(dialog_layer.get_dialog(&dialog_id).is_none());

    Ok(())
}

#[tokio::test]
async fn test_dialog_layer_with_swapped_tags() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // Create a dialog
    let invite_req = create_invite_request("alice-tag-123", "", "call-id-456", "z9hG4bKnashds");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
    let tx = Transaction::new_server(key, invite_req, endpoint.inner.clone(), Some(mock_conn));

    let (state_sender, _) = unbounded_channel();

    let dialog = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    let dialog_id = dialog.id();

    // Create a swapped dialog ID (as if from the other perspective)
    let swapped_id = DialogId {
        call_id: dialog_id.call_id.clone(),
        local_tag: dialog_id.remote_tag.clone(),
        remote_tag: dialog_id.local_tag.clone(),
    };

    // Swapped tags should NOT match the server-side dialog ID
    let found_dialog = dialog_layer.get_dialog(&swapped_id);
    assert!(found_dialog.is_none());

    Ok(())
}

#[tokio::test]
async fn test_multiple_dialogs_management() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    let (state_sender, _) = unbounded_channel();

    // Create multiple dialogs
    for i in 0..5 {
        let call_id = format!("call-id-{}", i);
        let from_tag = format!("alice-tag-{}", i);
        let branch = format!("z9hG4bKnashds{}", i);

        let invite_req = create_invite_request(&from_tag, "", &call_id, &branch);
        let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
        let tx = Transaction::new_server(
            key,
            invite_req,
            endpoint.inner.clone(),
            Some(mock_conn.clone()),
        );

        dialog_layer.get_or_create_server_invite(
            &tx,
            state_sender.clone(),
            None,
            Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
        )?;
    }

    // Should have 5 dialogs
    assert_eq!(dialog_layer.len(), 5);

    // Remove one dialog
    let _test_id = DialogId {
        call_id: "test-call-2".to_string(),
        local_tag: "".to_string(),
        remote_tag: "alice-tag-2".to_string(), // We need to find the actual dialog first
    };

    // Find all dialogs to get the actual IDs
    let mut dialog_ids = vec![];
    for i in 0..5 {
        let call_id = format!("call-id-{}", i);
        let from_tag = format!("alice-tag-{}", i);
        let _partial_id = DialogId {
            call_id: call_id.clone(),
            local_tag: "".to_string(),
            remote_tag: from_tag.clone(),
        };

        // Try to find dialog by creating a request and matching
        let test_req = create_invite_request(&from_tag, "", &call_id, "test-branch");
        let test_key = TransactionKey::from_request(&test_req, TransactionRole::Server)?;
        let test_tx = Transaction::new_server(
            test_key,
            test_req,
            endpoint.inner.clone(),
            Some(mock_conn.clone()),
        );
        if let Some(dialog) = dialog_layer.match_dialog(&test_tx) {
            dialog_ids.push(dialog.id());
        }
    }

    // Remove first dialog
    if let Some(dialog_id) = dialog_ids.first() {
        dialog_layer.remove_dialog(dialog_id);
        assert_eq!(dialog_layer.len(), 4);
    }

    Ok(())
}

#[tokio::test]
async fn test_dialog_error_cases() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());
    let mock_conn = create_mock_connection().await?;

    // Test with invalid dialog ID (non-existent to-tag)
    let invite_req = create_invite_request(
        "alice-tag-123",
        "non-existent-tag",
        "call-id-456",
        "z9hG4bKnashds",
    );
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
    let tx = Transaction::new_server(key, invite_req, endpoint.inner.clone(), Some(mock_conn));

    let (state_sender, _) = unbounded_channel();

    // Should return error when trying to get dialog with non-existent to-tag
    let result = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    );

    assert!(result.is_err());

    Ok(())
}

#[tokio::test]
async fn test_server_invite_dialog_with_tcp_transport() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());

    // Create a TCP listener connection (without binding a socket)
    let tcp_addr = SipAddr {
        r#type: Some(Transport::Tcp),
        addr: HostWithPort {
            host: crate::sip::Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                127, 0, 0, 1,
            ))),
            port: Some(5060.into()),
        },
    };
    let tcp_listener = TcpListenerConnection::new(tcp_addr.clone(), None).await?;
    let conn: crate::transport::SipConnection = tcp_listener.into();

    // Create INVITE request
    let invite_req = create_invite_request("alice-tcp-tag", "", "call-id-tcp", "z9hG4bKtcp");
    let key = TransactionKey::from_request(&invite_req, TransactionRole::Server)?;
    let tx = Transaction::new_server(key, invite_req.clone(), endpoint.inner.clone(), Some(conn));

    let (state_sender, _state_receiver) = unbounded_channel();

    let dialog = dialog_layer.get_or_create_server_invite(
        &tx,
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
    )?;

    // Dialog should be created
    assert_eq!(dialog_layer.len(), 1);

    // The remote_uri should have a Transport::Tcp param added
    let remote_uri = dialog.inner.remote_uri.lock();
    let has_tcp_transport = remote_uri
        .params
        .iter()
        .any(|p| matches!(p, Param::Transport(Transport::Tcp)));
    assert!(
        has_tcp_transport,
        "expected Transport::Tcp param in remote_uri, got params: {:?}",
        remote_uri.params
    );

    Ok(())
}

#[tokio::test]
async fn test_make_invite_request_with_tcp_transport() -> crate::Result<()> {
    let token = CancellationToken::new();
    let tl = TransportLayer::new(token.child_token());

    // Add a TCP listener address to the transport layer
    let tcp_addr = SipAddr {
        r#type: Some(Transport::Tcp),
        addr: HostWithPort {
            host: crate::sip::Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                192, 168, 1, 10,
            ))),
            port: Some(5060.into()),
        },
    };
    let tcp_listener = TcpListenerConnection::new(tcp_addr.clone(), None).await?;
    tl.add_transport(crate::transport::SipConnection::TcpListener(tcp_listener));

    let endpoint = EndpointBuilder::new()
        .with_user_agent("rsipstack-test")
        .with_transport_layer(tl)
        .build();
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());

    let destination = SipAddr {
        r#type: Some(Transport::Tcp),
        addr: HostWithPort {
            host: crate::sip::Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                10, 0, 0, 1,
            ))),
            port: Some(5060.into()),
        },
    };

    let opt = crate::dialog::invitation::InviteOption {
        caller: crate::sip::Uri::try_from("sip:alice@example.com")?,
        callee: crate::sip::Uri::try_from("sip:bob@example.com")?,
        contact: crate::sip::Uri::try_from("sip:alice@192.168.1.10:5060")?,
        destination: Some(destination),
        ..Default::default()
    };

    let request = dialog_layer.make_invite_request(&opt)?;

    // Verify Contact header has the transport layer's TCP address and transport param
    let contact = request.contact_header()?.typed()?;
    assert_eq!(
        contact.uri.host_with_port, tcp_addr.addr,
        "Contact URI should use the transport layer's TCP address"
    );
    assert!(
        contact
            .uri
            .params
            .iter()
            .any(|p| matches!(p, Param::Transport(Transport::Tcp))),
        "Contact should have Transport::Tcp param, got: {:?}",
        contact.uri.params
    );
    assert_eq!(
        contact.uri.scheme,
        Some(crate::sip::Scheme::Sip),
        "TCP contact should have sip scheme"
    );

    Ok(())
}

#[tokio::test]
async fn test_make_invite_request_without_transport_uses_contact_as_is() -> crate::Result<()> {
    let token = CancellationToken::new();
    let tl = TransportLayer::new(token.child_token());

    // Add a UDP address so get_via has an address to use
    let udp_conn = UdpConnection::create_connection("127.0.0.1:0".parse()?, None, None).await?;
    tl.add_transport(crate::transport::SipConnection::Udp(udp_conn));

    let endpoint = EndpointBuilder::new()
        .with_user_agent("rsipstack-test")
        .with_transport_layer(tl)
        .build();
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());

    let opt = crate::dialog::invitation::InviteOption {
        caller: crate::sip::Uri::try_from("sip:alice@example.com")?,
        callee: crate::sip::Uri::try_from("sip:bob@example.com")?,
        contact: crate::sip::Uri::try_from("sip:alice@192.168.1.10:5060")?,
        ..Default::default()
    };

    let request = dialog_layer.make_invite_request(&opt)?;
    let contact = request.contact_header()?.typed()?;

    // When no destination transport, contact should remain unchanged
    assert_eq!(
        contact.uri, opt.contact,
        "Contact should remain unchanged when no transport destination"
    );

    Ok(())
}

#[tokio::test]
async fn test_make_invite_request_with_tls_transport_uses_sips_scheme() -> crate::Result<()> {
    let token = CancellationToken::new();
    let tl = TransportLayer::new(token.child_token());

    // Add a TLS listener address
    let tls_addr = SipAddr {
        r#type: Some(Transport::Tls),
        addr: HostWithPort {
            host: crate::sip::Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                192, 168, 1, 10,
            ))),
            port: Some(5061.into()),
        },
    };
    let tcp_listener = TcpListenerConnection::new(tls_addr.clone(), None).await?;
    tl.add_transport(crate::transport::SipConnection::TcpListener(tcp_listener));

    let endpoint = EndpointBuilder::new()
        .with_user_agent("rsipstack-test")
        .with_transport_layer(tl)
        .build();
    let dialog_layer = DialogLayer::new(endpoint.inner.clone());

    let destination = SipAddr {
        r#type: Some(Transport::Tls),
        addr: HostWithPort {
            host: crate::sip::Host::IpAddr(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
                10, 0, 0, 1,
            ))),
            port: Some(5061.into()),
        },
    };

    let opt = crate::dialog::invitation::InviteOption {
        caller: crate::sip::Uri::try_from("sip:alice@example.com")?,
        callee: crate::sip::Uri::try_from("sip:bob@example.com")?,
        contact: crate::sip::Uri::try_from("sip:alice@192.168.1.10:5061")?,
        destination: Some(destination),
        ..Default::default()
    };

    let request = dialog_layer.make_invite_request(&opt)?;
    let contact = request.contact_header()?.typed()?;

    // TLS should use sips scheme
    assert_eq!(
        contact.uri.scheme,
        Some(crate::sip::Scheme::Sips),
        "TLS contact should have sips scheme"
    );
    assert!(
        contact
            .uri
            .params
            .iter()
            .any(|p| matches!(p, Param::Transport(Transport::Tls))),
        "Contact should have Transport::Tls param"
    );

    Ok(())
}