xphone 0.4.6

SIP telephony library with event-driven API — handles SIP signaling, RTP media, codecs, and call state
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
//! Integration tests against a running Asterisk instance.
//!
//! Start with: cd testutil/docker && docker compose up -d
//! Run with:   LOCAL_IP=192.168.65.254 cargo test --features integration --test integration_test -- --nocapture --test-threads=1
//! Stop with:  cd testutil/docker && docker compose down
//!
//! Environment variables:
//!   ASTERISK_HOST     — SIP server address (default: 127.0.0.1)
//!   ASTERISK_PORT     — SIP server port (default: 5160)
//!   ASTERISK_PASSWORD — Extension password (default: test)
//!   LOCAL_IP          — Local IP for SDP (required for Docker on macOS: 192.168.65.254)
//!
//! These tests are gated behind the `integration` feature flag so they
//! never run during normal `cargo test`.

#![cfg(feature = "integration")]

use std::time::Duration;

use xphone::config::Config;
use xphone::sip::client::{Client, ClientConfig};
use xphone::types::ExtensionState;
use xphone::Phone;

fn asterisk_host() -> String {
    std::env::var("ASTERISK_HOST").unwrap_or_else(|_| "127.0.0.1".into())
}

fn asterisk_password() -> String {
    std::env::var("ASTERISK_PASSWORD").unwrap_or_else(|_| "test".into())
}

fn asterisk_port() -> u16 {
    std::env::var("ASTERISK_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(5160)
}

/// Local IP to advertise in SDP, overridable for Docker-on-macOS.
fn local_ip_override() -> Option<String> {
    std::env::var("LOCAL_IP").ok()
}

fn integration_client_config(ext: &str, password: &str) -> ClientConfig {
    let host = asterisk_host();
    let port = asterisk_port();
    ClientConfig {
        server_addr: format!("{}:{}", host, port).parse().unwrap(),
        username: ext.into(),
        password: password.into(),
        domain: host,
        ..Default::default()
    }
}

fn integration_phone_config(ext: &str, password: &str) -> Config {
    Config {
        username: ext.into(),
        password: password.into(),
        host: asterisk_host(),
        port: asterisk_port(),
        local_ip: local_ip_override().unwrap_or_default(),
        register_expiry: Duration::from_secs(10),
        register_retry: Duration::from_secs(1),
        register_max_retry: 3,
        media_timeout: Duration::from_secs(10),
        rtp_port_min: 20000,
        rtp_port_max: 20099,
        ..Config::default()
    }
}

// --- E1: Registration (low-level Client) ---

/// Register extension 1001 with Asterisk using raw SIP client.
#[test]
fn register_1001_raw() {
    let cfg = integration_client_config("1001", &asterisk_password());
    let client = Client::new(cfg).unwrap();

    let (code, reason) = client.send_register(Duration::from_secs(5)).unwrap();
    assert_eq!(code, 200, "expected 200, got {} {}", code, reason);

    client.close();
}

/// Register extension 1002 with Asterisk using raw SIP client.
#[test]
fn register_1002_raw() {
    let cfg = integration_client_config("1002", &asterisk_password());
    let client = Client::new(cfg).unwrap();

    let (code, reason) = client.send_register(Duration::from_secs(5)).unwrap();
    assert_eq!(code, 200, "expected 200, got {} {}", code, reason);

    client.close();
}

/// Registration with wrong password should fail.
#[test]
fn register_wrong_password() {
    let cfg = integration_client_config("1001", "wrong");
    let client = Client::new(cfg).unwrap();

    let result = client.send_register(Duration::from_secs(5));
    if let Ok((code, _)) = result {
        assert_ne!(code, 200, "should not get 200 with wrong password");
    }

    client.close();
}

/// NAT keepalive should not error.
#[test]
fn keepalive() {
    let cfg = integration_client_config("1001", &asterisk_password());
    let client = Client::new(cfg).unwrap();

    let (code, _) = client.send_register(Duration::from_secs(5)).unwrap();
    assert_eq!(code, 200);

    client.send_keepalive().unwrap();
    client.close();
}

// --- E1b: Registration via Phone::connect() ---

/// Register extension 1001 via the full Phone::connect() path.
#[test]
fn phone_connect_and_disconnect() {
    let cfg = integration_phone_config("1001", &asterisk_password());
    let phone = Phone::new(cfg);

    phone.connect().unwrap();
    assert_eq!(phone.state(), xphone::PhoneState::Registered);

    phone.disconnect().unwrap();
    assert_eq!(phone.state(), xphone::PhoneState::Disconnected);
}

/// Phone::connect() with wrong password should fail.
#[test]
fn phone_connect_wrong_password() {
    let cfg = integration_phone_config("1001", "wrong");
    let phone = Phone::new(cfg);

    let result = phone.connect();
    assert!(result.is_err());
}

// --- E2E call tests ---

/// E2: p1 (1001) dials p2 (1002), p2 accepts, p1 ends call.
#[test]
fn dial_between_extensions() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    p1.connect().unwrap();
    p2.connect().unwrap();

    // Set up p2 to auto-accept incoming calls.
    let (call_tx, call_rx) = crossbeam_channel::bounded(1);
    p2.on_incoming(move |call| {
        call.accept().unwrap();
        let _ = call_tx.send(call);
    });

    // p1 dials p2.
    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call1 = p1.dial("1002", opts).unwrap();

    // Wait for p2 to receive and accept the call.
    let call2 = call_rx.recv_timeout(Duration::from_secs(10)).unwrap();

    // Both calls should be active.
    assert_eq!(call1.state(), xphone::types::CallState::Active);
    assert_eq!(call2.state(), xphone::types::CallState::Active);

    // p1 ends the call.
    call1.end().unwrap();

    // Give BYE time to propagate.
    std::thread::sleep(Duration::from_millis(500));

    // p2 should see the call ended by remote.
    assert_eq!(call2.state(), xphone::types::CallState::Ended);

    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}

/// E3: p1 dials p2, p2 accepts, p1 sends BYE, p2 sees EndedByRemote.
#[test]
fn inbound_accept_and_remote_bye() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    p1.connect().unwrap();
    p2.connect().unwrap();

    let (ended_tx, ended_rx) = crossbeam_channel::bounded::<xphone::types::EndReason>(1);
    let (call_tx, call_rx) = crossbeam_channel::bounded(1);

    p2.on_incoming(move |call| {
        let ended_tx = ended_tx.clone();
        call.on_ended(move |reason| {
            let _ = ended_tx.send(reason);
        });
        call.accept().unwrap();
        let _ = call_tx.send(true);
    });

    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call1 = p1.dial("1002", opts).unwrap();

    // Wait for accept.
    call_rx.recv_timeout(Duration::from_secs(10)).unwrap();

    // p1 ends the call.
    call1.end().unwrap();

    // p2 should get EndedByRemote.
    let reason = ended_rx.recv_timeout(Duration::from_secs(5)).unwrap();
    assert_eq!(reason, xphone::types::EndReason::Remote);

    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}

/// E4: p1 dials p2, p2 accepts, p1 holds, p1 resumes, p1 ends.
#[test]
fn hold_resume() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    p1.connect().unwrap();
    p2.connect().unwrap();

    let (call_tx, call_rx) = crossbeam_channel::bounded(1);
    p2.on_incoming(move |call| {
        call.accept().unwrap();
        let _ = call_tx.send(call);
    });

    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call1 = p1.dial("1002", opts).unwrap();
    let _call2 = call_rx.recv_timeout(Duration::from_secs(10)).unwrap();

    assert_eq!(call1.state(), xphone::types::CallState::Active);

    // Hold.
    call1.hold().unwrap();
    assert_eq!(call1.state(), xphone::types::CallState::OnHold);

    // Give Asterisk time to process the re-INVITE.
    std::thread::sleep(Duration::from_millis(500));

    // Resume.
    call1.resume().unwrap();
    assert_eq!(call1.state(), xphone::types::CallState::Active);

    std::thread::sleep(Duration::from_millis(500));

    // End.
    call1.end().unwrap();

    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}

/// E5: p1 dials p2, p2 sends DTMF "5", p1 receives it via OnDTMF.
/// Ignored in CI: Asterisk bridge DTMF relay is timing-sensitive.
/// Run locally: cargo test --features integration --test integration_test dtmf -- --ignored
#[test]
#[ignore]
fn dtmf_send_receive() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    p1.connect().unwrap();
    p2.connect().unwrap();

    // Set up p2 to auto-accept incoming calls.
    let (call_tx, call_rx) = crossbeam_channel::bounded(1);
    p2.on_incoming(move |call| {
        call.accept().unwrap();
        let _ = call_tx.send(call);
    });

    // p1 dials p2.
    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call1 = p1.dial("1002", opts).unwrap();

    // Wait for p2 to receive and accept the call.
    let call2 = call_rx.recv_timeout(Duration::from_secs(10)).unwrap();

    assert_eq!(call1.state(), xphone::types::CallState::Active);
    assert_eq!(call2.state(), xphone::types::CallState::Active);

    // Register DTMF callback on p1's outbound call.
    let (dtmf_tx, dtmf_rx) = crossbeam_channel::bounded(10);
    call1.on_dtmf(move |digit| {
        let _ = dtmf_tx.send(digit);
    });

    // Wait for RTP media paths to fully establish through Asterisk bridge.
    // CI environments are slower, so give extra time.
    std::thread::sleep(Duration::from_secs(2));

    // p2 sends DTMF digit "5" — retry up to 3 times in case the bridge isn't ready.
    let mut digit = None;
    for attempt in 0..3 {
        if attempt > 0 {
            std::thread::sleep(Duration::from_secs(1));
        }
        call2.send_dtmf("5").unwrap();
        if let Ok(d) = dtmf_rx.recv_timeout(Duration::from_secs(3)) {
            digit = Some(d);
            break;
        }
    }
    assert_eq!(digit.expect("DTMF digit never received by p1"), "5");

    call1.end().unwrap();

    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}

/// E6: dial 9999 (echo), send silence RTP, verify we receive echoed RTP back.
#[test]
fn echo_test() {
    let cfg = integration_phone_config("1001", &asterisk_password());
    let p = Phone::new(cfg);
    p.connect().unwrap();

    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call = p.dial("9999", opts).unwrap();
    assert_eq!(call.state(), xphone::types::CallState::Active);

    // Get media channels.
    let rtp_writer = call.rtp_writer().expect("rtp_writer channel not available");
    let rtp_reader = call.rtp_reader().expect("rtp_reader channel not available");

    // Send silence via RTPWriter so Asterisk Echo() has something to reflect.
    let silence = vec![0xFFu8; 160]; // PCMU silence
    for i in 0..50 {
        let pkt = xphone::types::RtpPacket {
            header: xphone::types::RtpHeader {
                version: 2,
                payload_type: 0, // PCMU
                sequence_number: i as u16,
                timestamp: (i as u32) * 160,
                ssrc: 0xDEADBEEF,
                marker: false,
            },
            payload: silence.clone(),
        };
        let _ = rtp_writer.send(pkt);
        std::thread::sleep(Duration::from_millis(20));
    }

    // Verify we receive echoed RTP back.
    let pkt = rtp_reader
        .recv_timeout(Duration::from_secs(5))
        .expect("no echo response received");
    assert!(!pkt.payload.is_empty());

    call.end().unwrap();
    p.disconnect().unwrap();
}

/// E7: p1 sends a SIP MESSAGE to p2, p2 receives it via on_message callback.
#[test]
fn sip_message_between_extensions() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    let (msg_tx, msg_rx) = crossbeam_channel::bounded(1);
    p2.on_message(move |msg| {
        let _ = msg_tx.send(msg);
    });

    p1.connect().unwrap();
    p2.connect().unwrap();

    // p1 sends MESSAGE to 1002.
    p1.send_message("1002", "Hello from 1001").unwrap();

    // p2 should receive it.
    let msg = msg_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("MESSAGE not received by p2");
    assert_eq!(msg.body, "Hello from 1001");
    assert_eq!(msg.content_type, "text/plain");
    assert!(
        msg.from.contains("1001"),
        "from should contain sender: {}",
        msg.from
    );

    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}

/// E8: p1 watches p2 via BLF, p2 dials p1, p1 sees state changes.
#[test]
fn blf_watch_state_changes() {
    let cfg1 = integration_phone_config("1001", &asterisk_password());
    let cfg2 = integration_phone_config("1002", &asterisk_password());

    let p1 = Phone::new(cfg1);
    let p2 = Phone::new(cfg2);

    p1.connect().unwrap();
    p2.connect().unwrap();

    // p1 watches extension 1002.
    let (blf_tx, blf_rx) = crossbeam_channel::bounded(10);
    p1.watch("1002", move |status, _prev| {
        let _ = blf_tx.send(status.state);
    })
    .unwrap();

    // Wait for initial NOTIFY (Available since 1002 is registered with no calls).
    let initial = blf_rx.recv_timeout(Duration::from_secs(5));
    if let Ok(state) = initial {
        assert_eq!(state, ExtensionState::Available);
    }

    // Set up p1 to auto-accept incoming calls.
    let (call_tx, call_rx) = crossbeam_channel::bounded(1);
    p1.on_incoming(move |call| {
        call.accept().unwrap();
        let _ = call_tx.send(call);
    });

    // p2 dials p1 — p1's BLF watcher should see 1002 go to Ringing or OnThePhone.
    let opts = xphone::config::DialOptions {
        timeout: Duration::from_secs(10),
        ..Default::default()
    };
    let call2 = p2.dial("1001", opts).unwrap();

    // Wait for p1 to accept the call.
    let _call1 = call_rx.recv_timeout(Duration::from_secs(10)).unwrap();

    // Collect BLF state changes — expect at least one non-Available state.
    let mut saw_busy = false;
    for _ in 0..10 {
        match blf_rx.recv_timeout(Duration::from_secs(2)) {
            Ok(ExtensionState::OnThePhone) | Ok(ExtensionState::Ringing) => {
                saw_busy = true;
                break;
            }
            Ok(_) => continue,
            Err(_) => break,
        }
    }
    assert!(saw_busy, "expected BLF to show Ringing or OnThePhone");

    // End call — BLF should return to Available.
    call2.end().unwrap();
    std::thread::sleep(Duration::from_millis(500));

    let mut saw_available = false;
    for _ in 0..10 {
        match blf_rx.recv_timeout(Duration::from_secs(2)) {
            Ok(ExtensionState::Available) => {
                saw_available = true;
                break;
            }
            Ok(_) => continue,
            Err(_) => break,
        }
    }
    assert!(
        saw_available,
        "expected BLF to return to Available after hangup"
    );

    p1.unwatch("1002").unwrap();
    p1.disconnect().unwrap();
    p2.disconnect().unwrap();
}