rsipstack 0.5.5

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
//! Dialog state transition tests
//!
//! This module contains comprehensive tests for dialog state transitions
//! according to RFC 3261 Section 12.

use crate::dialog::{
    dialog::{DialogInner, DialogState, TerminatedReason, TransactionHandle},
    DialogId,
};
use crate::sip::{headers::*, Request, Response, StatusCode};
use crate::transaction::{endpoint::EndpointBuilder, key::TransactionRole};
use crate::transport::TransportLayer;
use tokio::sync::mpsc::unbounded_channel;
use tokio_util::sync::CancellationToken;

/// Test helper to create a mock INVITE request
pub fn create_invite_request(from_tag: &str, to_tag: &str, call_id: &str) -> Request {
    Request {
        method: crate::sip::Method::Invite,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060").unwrap(),
        headers: vec![
            Via::new("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKnashds;received=172.0.0.1")
                .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 a mock response
fn create_response(status: StatusCode, from_tag: &str, to_tag: &str, call_id: &str) -> Response {
    let body = if status == StatusCode::OK {
        b"v=0\r\no=bob 2890844527 2890844528 IN IP4 host.biloxi.com\r\n".to_vec()
    } else {
        vec![]
    };

    Response {
        status_code: status,
        version: crate::sip::Version::V2,
        headers: vec![
            Via::new("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKnashds").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:bob@bob.example.com:5060>").into(),
        ]
        .into(),
        body,
    }
}

pub async fn create_test_endpoint() -> crate::Result<crate::transaction::endpoint::Endpoint> {
    let token = CancellationToken::new();
    let tl = TransportLayer::new(token.child_token());

    // Create a dummy UDP connection for testing using tokio's UdpSocket directly
    let tokio_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await?;
    let local_addr = tokio_socket.local_addr()?;

    let udp_conn = crate::transport::udp::UdpConnection::attach(
        crate::transport::udp::UdpInner {
            conn: tokio_socket,
            addr: crate::transport::SipAddr::from(local_addr),
        },
        None,
        Some(token.child_token()),
    )
    .await;

    tl.inner.add_listener(udp_conn.into());

    let endpoint = EndpointBuilder::new()
        .with_user_agent("rsipstack-test")
        .with_transport_layer(tl)
        .build();
    Ok(endpoint)
}

#[test]
fn test_dialog_id_eq() {
    let dialog_id_1 = DialogId {
        call_id: "test-call-id-123".to_string(),
        local_tag: "456".to_string(),
        remote_tag: "789".to_string(),
    };
    assert_eq!(dialog_id_1.to_string(), "test-call-id-123-456-789");

    let dialog_id_4 = DialogId {
        call_id: "mock".to_string(),
        local_tag: "M3wnsBf".to_string(),
        remote_tag: "1NyRqPt1".to_string(),
    };
    let dialog_id_5 = DialogId {
        call_id: "mock".to_string(),
        local_tag: "1NyRqPt1".to_string(),
        remote_tag: "M3wnsBf".to_string(),
    };
    assert_ne!(dialog_id_4, dialog_id_5);
}
#[tokio::test]
async fn test_dialog_state_transitions() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let (state_sender, _state_receiver) = unbounded_channel();

    // Create dialog ID
    let dialog_id = DialogId {
        call_id: "test-call-id-123".to_string(),
        local_tag: "alice-tag-456".to_string(),
        remote_tag: "bob-tag-789".to_string(),
    };

    // Create INVITE request
    let invite_req = create_invite_request("alice-tag-456", "", "test-call-id-123");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    // Create dialog inner
    let dialog_inner = DialogInner::new(
        TransactionRole::Client,
        dialog_id.clone(),
        invite_req,
        endpoint.inner.clone(),
        state_sender,
        None,
        Some(crate::sip::Uri::try_from(
            "sip:alice@alice.example.com:5060",
        )?),
        tu_sender,
    )?;

    // Test initial state
    let initial_state = dialog_inner.state.lock().clone();
    assert!(matches!(initial_state, DialogState::Calling(_)));

    // Test transition to Trying
    dialog_inner.transition(DialogState::Trying(dialog_id.clone()))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Trying(_)));

    // Test transition to Early
    let ringing_resp = create_response(
        StatusCode::Ringing,
        "alice-tag-456",
        "bob-tag-789",
        "test-call-id-123",
    );
    dialog_inner.transition(DialogState::Early(dialog_id.clone(), ringing_resp))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Early(_, _)));

    // Test transition to Confirmed
    dialog_inner.transition(DialogState::Confirmed(
        dialog_id.clone(),
        Response::default(),
    ))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Confirmed(_, _)));
    assert!(dialog_inner.is_confirmed());

    // Test transition to Terminated
    dialog_inner.transition(DialogState::Terminated(
        dialog_id.clone(),
        TerminatedReason::Timeout,
    ))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Terminated(_, _)));

    Ok(())
}

#[tokio::test]
async fn test_server_dialog_state_transitions() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let (state_sender, _state_receiver) = unbounded_channel();

    // Create dialog ID
    let dialog_id = DialogId {
        call_id: "test-call-id-server-123".to_string(),
        local_tag: "bob-tag-789".to_string(),
        remote_tag: "alice-tag-456".to_string(),
    };

    // Create INVITE request
    let invite_req = create_invite_request("alice-tag-456", "", "test-call-id-server-123");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    // Create server dialog inner
    let dialog_inner = DialogInner::new(
        TransactionRole::Server,
        dialog_id.clone(),
        invite_req,
        endpoint.inner.clone(),
        state_sender,
        None,
        Some(crate::sip::Uri::try_from("sip:bob@bob.example.com:5060")?),
        tu_sender,
    )?;

    // Test initial state
    let initial_state = dialog_inner.state.lock().clone();
    assert!(matches!(initial_state, DialogState::Calling(_)));

    // Test transition to Trying (server sends 100 Trying)
    dialog_inner.transition(DialogState::Trying(dialog_id.clone()))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Trying(_)));

    // Test transition to WaitAck (server sends 200 OK)
    let ok_resp = create_response(
        StatusCode::OK,
        "alice-tag-456",
        "bob-tag-789",
        "test-call-id-server-123",
    );
    dialog_inner.transition(DialogState::WaitAck(dialog_id.clone(), ok_resp.clone()))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::WaitAck(_, _)));

    // Test transition to Confirmed (after receiving ACK)
    dialog_inner.transition(DialogState::Confirmed(dialog_id.clone(), ok_resp))?;
    let state = dialog_inner.state.lock().clone();
    assert!(matches!(state, DialogState::Confirmed(_, _)));
    assert!(dialog_inner.is_confirmed());

    Ok(())
}

#[tokio::test]
async fn test_dialog_in_dialog_requests() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let (state_sender, _state_receiver) = unbounded_channel();

    // Create dialog ID
    let dialog_id = DialogId {
        call_id: "test-call-id-in-dialog-123".to_string(),
        local_tag: "alice-tag-456".to_string(),
        remote_tag: "bob-tag-789".to_string(),
    };

    // Create initial INVITE request
    let invite_req =
        create_invite_request("alice-tag-456", "bob-tag-789", "test-call-id-in-dialog-123");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    // Create confirmed dialog
    let dialog_inner = DialogInner::new(
        TransactionRole::Client,
        dialog_id.clone(),
        invite_req,
        endpoint.inner.clone(),
        state_sender,
        None,
        Some(crate::sip::Uri::try_from(
            "sip:alice@alice.example.com:5060",
        )?),
        tu_sender,
    )?;

    // Set dialog to confirmed state
    dialog_inner.transition(DialogState::Confirmed(
        dialog_id.clone(),
        Response::default(),
    ))?;
    assert!(dialog_inner.is_confirmed());

    // Test INFO request in dialog
    let info_req = Request {
        method: crate::sip::Method::Info,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060")?,
        headers: vec![
            Via::new("SIP/2.0/UDP 127.0.0.1:5060;branch=z9hG4bK-info").into(),
            CSeq::new("2 INFO").into(),
            From::new("Alice <sip:alice@example.com>;tag=alice-tag-456").into(),
            To::new("Bob <sip:bob@example.com>;tag=bob-tag-789").into(),
            CallId::new("test-call-id-in-dialog-123").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: vec![],
    };

    let (handle, _) = TransactionHandle::new();
    dialog_inner.transition(DialogState::Info(dialog_id.clone(), info_req, handle))?;

    // Test UPDATE request in dialog
    let update_req = Request {
        method: crate::sip::Method::Update,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060")?,
        headers: vec![
            Via::new("SIP/2.0/UDP 127.0.0.1:5060;branch=z9hG4bK-update").into(),
            CSeq::new("3 UPDATE").into(),
            From::new("Alice <sip:alice@example.com>;tag=alice-tag-456").into(),
            To::new("Bob <sip:bob@example.com>;tag=bob-tag-789").into(),
            CallId::new("test-call-id-in-dialog-123").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: b"v=0\r\no=alice 2890844526 2890844528 IN IP4 host.atlanta.com\r\n".to_vec(),
    };

    let (handle, _) = TransactionHandle::new();
    dialog_inner.transition(DialogState::Updated(dialog_id.clone(), update_req, handle))?;

    // Test OPTIONS request in dialog
    let options_req = Request {
        method: crate::sip::Method::Options,
        uri: crate::sip::Uri::try_from("sip:bob@example.com:5060")?,
        headers: vec![
            Via::new("SIP/2.0/UDP 127.0.0.1:5060;branch=z9hG4bK-options").into(),
            CSeq::new("4 OPTIONS").into(),
            From::new("Alice <sip:alice@example.com>;tag=alice-tag-456").into(),
            To::new("Bob <sip:bob@example.com>;tag=bob-tag-789").into(),
            CallId::new("test-call-id-in-dialog-123").into(),
        ]
        .into(),
        version: crate::sip::Version::V2,
        body: vec![],
    };

    let (handle, _) = TransactionHandle::new();
    dialog_inner.transition(DialogState::Options(dialog_id.clone(), options_req, handle))?;

    // Dialog should still be confirmed after in-dialog requests
    assert!(dialog_inner.is_confirmed());

    Ok(())
}

#[tokio::test]
async fn test_dialog_termination_scenarios() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let (state_sender, _state_receiver) = unbounded_channel();

    // Test 1: Termination with error status code
    let dialog_id_1 = DialogId {
        call_id: "test-call-id-term-1".to_string(),
        local_tag: "alice-tag-456".to_string(),
        remote_tag: "bob-tag-789".to_string(),
    };

    let invite_req_1 = create_invite_request("alice-tag-456", "", "test-call-id-term-1");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    let dialog_inner_1 = DialogInner::new(
        TransactionRole::Client,
        dialog_id_1.clone(),
        invite_req_1,
        endpoint.inner.clone(),
        state_sender.clone(),
        None,
        Some(crate::sip::Uri::try_from(
            "sip:alice@alice.example.com:5060",
        )?),
        tu_sender,
    )?;

    // Terminate with error
    dialog_inner_1.transition(DialogState::Terminated(
        dialog_id_1.clone(),
        TerminatedReason::UasBusy,
    ))?;
    let state = dialog_inner_1.state.lock().clone();
    assert!(matches!(
        state,
        DialogState::Terminated(_, TerminatedReason::UasBusy)
    ));

    // Test 2: Normal termination (BYE)
    let dialog_id_2 = DialogId {
        call_id: "test-call-id-term-2".to_string(),
        local_tag: "alice-tag-456".to_string(),
        remote_tag: "bob-tag-789".to_string(),
    };

    let invite_req_2 = create_invite_request("alice-tag-456", "bob-tag-789", "test-call-id-term-2");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    let dialog_inner_2 = DialogInner::new(
        TransactionRole::Client,
        dialog_id_2.clone(),
        invite_req_2,
        endpoint.inner.clone(),
        state_sender.clone(),
        None,
        Some(crate::sip::Uri::try_from(
            "sip:alice@alice.example.com:5060",
        )?),
        tu_sender,
    )?;

    // First confirm the dialog
    dialog_inner_2.transition(DialogState::Confirmed(
        dialog_id_2.clone(),
        Response::default(),
    ))?;
    assert!(dialog_inner_2.is_confirmed());

    // Then terminate normally
    dialog_inner_2.transition(DialogState::Terminated(
        dialog_id_2.clone(),
        TerminatedReason::UacBye,
    ))?;
    let state = dialog_inner_2.state.lock().clone();
    assert!(matches!(state, DialogState::Terminated(_, _)));

    Ok(())
}

#[tokio::test]
async fn test_dialog_sequence_numbers() -> crate::Result<()> {
    let endpoint = create_test_endpoint().await?;
    let (state_sender, _state_receiver) = unbounded_channel();

    let dialog_id = DialogId {
        call_id: "test-call-id-seq-123".to_string(),
        local_tag: "alice-tag-456".to_string(),
        remote_tag: "bob-tag-789".to_string(),
    };

    let invite_req = create_invite_request("alice-tag-456", "bob-tag-789", "test-call-id-seq-123");
    let (tu_sender, _tu_receiver) = unbounded_channel();

    let dialog_inner = DialogInner::new(
        TransactionRole::Client,
        dialog_id.clone(),
        invite_req,
        endpoint.inner.clone(),
        state_sender,
        None,
        Some(crate::sip::Uri::try_from(
            "sip:alice@alice.example.com:5060",
        )?),
        tu_sender,
    )?;

    // Test initial sequence number
    let initial_seq = dialog_inner.get_local_seq();
    assert_eq!(initial_seq, 1); // Based on CSeq from initial request

    // Test increment
    let next_seq = dialog_inner.increment_local_seq();
    assert_eq!(next_seq, 2);
    assert_eq!(dialog_inner.get_local_seq(), 2);

    Ok(())
}

#[tokio::test]
async fn test_dialog_state_display() -> crate::Result<()> {
    let dialog_id = DialogId {
        call_id: "test-call-id-display".to_string(),
        local_tag: "alice-tag".to_string(),
        remote_tag: "bob-tag".to_string(),
    };

    // Test all state display formats
    let calling_state = DialogState::Calling(dialog_id.clone());
    assert!(calling_state.to_string().contains("Calling"));

    let trying_state = DialogState::Trying(dialog_id.clone());
    assert!(trying_state.to_string().contains("Trying"));

    let confirmed_state = DialogState::Confirmed(dialog_id.clone(), Response::default());
    assert!(confirmed_state.to_string().contains("Confirmed"));
    assert!(confirmed_state.is_confirmed());

    let terminated_state = DialogState::Terminated(dialog_id.clone(), TerminatedReason::Timeout);
    assert!(terminated_state.to_string().contains("Terminated"));
    assert!(terminated_state.to_string().contains("Timeout"));

    Ok(())
}

#[tokio::test]
async fn test_dialog_id_creation() -> crate::Result<()> {
    // Test from Request
    let request = create_invite_request("alice-tag-123", "", "call-id-456");
    let dialog_id = DialogId::try_from((&request, TransactionRole::Client))?;
    assert_eq!(dialog_id.call_id, "call-id-456");
    assert_eq!(dialog_id.local_tag, "alice-tag-123");
    assert_eq!(dialog_id.remote_tag, "");

    // Test from Response
    let response = create_response(
        StatusCode::OK,
        "alice-tag-123",
        "bob-tag-789",
        "call-id-456",
    );
    let dialog_id_resp = DialogId::try_from((&response, TransactionRole::Client))?;
    assert_eq!(dialog_id_resp.call_id, "call-id-456");
    assert_eq!(dialog_id_resp.local_tag, "alice-tag-123");
    assert_eq!(dialog_id_resp.remote_tag, "bob-tag-789");

    // Test display
    let display_str = dialog_id_resp.to_string();
    assert!(display_str.contains("call-id-456"));
    assert!(display_str.contains("alice-tag-123"));
    assert!(display_str.contains("bob-tag-789"));

    Ok(())
}