rustpbx 0.4.2

A SIP PBX implementation in Rust
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
//! Session Timer implementation (RFC 4028)
//!
//! This module implements SIP Session Timers as defined in RFC 4028.
//! Session timers are used to detect and recover from hung SIP sessions
//! by requiring periodic session refresh requests.

use crate::config::SessionTimerMode;
use anyhow::{Result, anyhow};
use std::str::FromStr;
use std::time::Duration;
use std::time::Instant;

// Session timer header constants
pub const HEADER_SESSION_EXPIRES: &str = "Session-Expires";
pub const HEADER_MIN_SE: &str = "Min-SE";
pub const HEADER_SUPPORTED: &str = "Supported";
#[cfg(test)]
pub const HEADER_REQUIRE: &str = "Require";
pub const TIMER_TAG: &str = "timer";

/// Default session expiration interval (30 minutes per RFC 4028 recommendation)
pub const DEFAULT_SESSION_EXPIRES: u64 = 1800;

/// Minimum acceptable session expiration interval (90 seconds per RFC 4028)
pub const MIN_MIN_SE: u64 = 90;

/// Refresher role - determines which party is responsible for session refresh
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionRefresher {
    /// User Agent Client (caller) refreshes
    Uac,
    /// User Agent Server (callee) refreshes
    Uas,
}

impl std::fmt::Display for SessionRefresher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SessionRefresher::Uac => write!(f, "uac"),
            SessionRefresher::Uas => write!(f, "uas"),
        }
    }
}

impl FromStr for SessionRefresher {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "uac" => Ok(SessionRefresher::Uac),
            "uas" => Ok(SessionRefresher::Uas),
            _ => Err(()),
        }
    }
}

impl SessionRefresher {
    pub fn for_local_role(we_are_uac: bool) -> Self {
        if we_are_uac {
            SessionRefresher::Uac
        } else {
            SessionRefresher::Uas
        }
    }

    /// Check if we are the refresher based on our role
    pub fn is_our_role(&self, we_are_uac: bool) -> bool {
        matches!(
            (self, we_are_uac),
            (SessionRefresher::Uac, true) | (SessionRefresher::Uas, false)
        )
    }
}

/// Session timer state machine
#[derive(Debug, Clone)]
pub struct SessionTimerState {
    /// Session timer policy for this dialog
    pub mode: SessionTimerMode,
    /// Timer is enabled (negotiated via Session-Expires header)
    pub enabled: bool,
    /// Session expiration interval
    pub session_interval: Duration,
    /// Minimum session expiration (from Min-SE header)
    pub min_se: Duration,
    /// Who is responsible for refreshing (UAC or UAS)
    pub refresher: SessionRefresher,
    /// Timer is actively running
    pub active: bool,
    /// Currently in the process of refreshing
    pub refreshing: bool,
    /// Last time the session was refreshed
    pub last_refresh: Instant,
    /// Session start time (used for testing)
    #[cfg(test)]
    pub session_start: Instant,
    /// Number of successful refreshes
    pub refresh_count: u32,
    /// Number of failed refresh attempts
    pub failed_refreshes: u32,
}

impl Default for SessionTimerState {
    fn default() -> Self {
        Self {
            mode: SessionTimerMode::Off,
            enabled: false,
            session_interval: Duration::from_secs(DEFAULT_SESSION_EXPIRES),
            min_se: Duration::from_secs(MIN_MIN_SE),
            refresher: SessionRefresher::Uac,
            active: false,
            refreshing: false,
            last_refresh: Instant::now(),
            #[cfg(test)]
            session_start: Instant::now(),
            refresh_count: 0,
            failed_refreshes: 0,
        }
    }
}

impl SessionTimerState {
    /// Create a new session timer state with specific interval
    #[cfg(test)]
    pub fn new(session_interval: Duration, min_se: Duration, refresher: SessionRefresher) -> Self {
        Self {
            mode: SessionTimerMode::Supported,
            enabled: true,
            session_interval,
            min_se,
            refresher,
            active: true,
            refreshing: false,
            last_refresh: Instant::now(),
            session_start: Instant::now(),
            refresh_count: 0,
            failed_refreshes: 0,
        }
    }

    /// Check if a refresh should be sent (RFC 4028)
    /// Returns true if we are the refresher and it's time to send a refresh
    pub fn should_refresh(&self) -> bool {
        if !self.active || !self.enabled || self.refreshing {
            return false;
        }
        // RFC 4028: Refresher should send refresh at half the interval
        self.last_refresh.elapsed() >= self.session_interval / 2
    }

    /// Check if the session has expired (no refresh received)
    pub fn is_expired(&self) -> bool {
        if !self.active || !self.enabled {
            return false;
        }
        // RFC 4028: If no refresh received within interval, session is expired
        self.last_refresh.elapsed() >= self.session_interval
    }

    /// Get the time when next refresh should be sent
    pub fn next_refresh_time(&self) -> Option<Instant> {
        if !self.active || !self.enabled {
            return None;
        }
        Some(self.last_refresh + self.session_interval / 2)
    }

    /// Get the time when session will expire
    pub fn expiration_time(&self) -> Option<Instant> {
        if !self.active || !self.enabled {
            return None;
        }
        Some(self.last_refresh + self.session_interval)
    }

    /// Get remaining time until expiration
    pub fn time_until_expiration(&self) -> Option<Duration> {
        self.expiration_time().map(|exp| {
            let now = Instant::now();
            if exp > now { exp - now } else { Duration::ZERO }
        })
    }

    /// Get remaining time until next refresh is needed
    pub fn time_until_refresh(&self) -> Option<Duration> {
        self.next_refresh_time().map(|next| {
            let now = Instant::now();
            if next > now {
                next - now
            } else {
                Duration::ZERO
            }
        })
    }

    /// Check if we are responsible for refreshing this dialog
    pub fn should_we_refresh(&self, we_are_uac: bool) -> bool {
        self.refresher.is_our_role(we_are_uac)
    }

    /// Get the next wakeup timeout for our role on this dialog
    pub fn next_timeout_for_role(&self, we_are_uac: bool) -> Option<Duration> {
        if !self.active || !self.enabled {
            return None;
        }

        if !self.refreshing && self.should_we_refresh(we_are_uac) {
            self.time_until_refresh()
        } else {
            self.time_until_expiration()
        }
    }

    /// Start a refresh operation
    pub fn start_refresh(&mut self) -> bool {
        if self.refreshing {
            return false;
        }
        self.refreshing = true;
        true
    }

    /// Complete a successful refresh
    pub fn complete_refresh(&mut self) {
        self.last_refresh = Instant::now();
        self.refreshing = false;
        self.refresh_count += 1;
    }

    /// Mark refresh as failed
    pub fn fail_refresh(&mut self) {
        self.refreshing = false;
        self.failed_refreshes += 1;
    }

    /// Update the last refresh time when a refresh is received from remote
    pub fn update_refresh(&mut self) {
        self.last_refresh = Instant::now();
        self.refresh_count += 1;
    }

    /// Generate Session-Expires header value
    pub fn get_session_expires_value(&self) -> String {
        format!(
            "{};refresher={}",
            self.session_interval.as_secs(),
            self.refresher
        )
    }

    /// Generate Min-SE header value
    pub fn get_min_se_value(&self) -> String {
        self.min_se.as_secs().to_string()
    }

    /// Activate the timer
    #[cfg(test)]
    pub fn activate(&mut self) {
        if self.enabled {
            self.active = true;
            self.last_refresh = Instant::now();
        }
    }

    /// Deactivate the timer
    #[cfg(test)]
    pub fn deactivate(&mut self) {
        self.active = false;
    }

    /// Reset the timer with new parameters
    #[cfg(test)]
    pub fn reset(&mut self, interval: Duration, refresher: SessionRefresher) {
        self.session_interval = interval;
        self.refresher = refresher;
        self.last_refresh = Instant::now();
        self.refreshing = false;
    }

    /// Check if we need to include timer in Require header
    #[cfg(test)]
    pub fn require_timer(&self) -> bool {
        self.enabled && self.active
    }

    /// Get session duration
    #[cfg(test)]
    pub fn session_duration(&self) -> Duration {
        self.session_start.elapsed()
    }

    /// Get timer statistics
    #[cfg(test)]
    pub fn stats(&self) -> TimerStats {
        TimerStats {
            enabled: self.enabled,
            active: self.active,
            refreshing: self.refreshing,
            session_interval_secs: self.session_interval.as_secs(),
            min_se_secs: self.min_se.as_secs(),
            refresher: format!("{}", self.refresher),
            refresh_count: self.refresh_count,
            failed_refreshes: self.failed_refreshes,
            session_duration_secs: self.session_duration().as_secs(),
            time_until_refresh_secs: self.time_until_refresh().map(|d| d.as_secs()),
            time_until_expiration_secs: self.time_until_expiration().map(|d| d.as_secs()),
        }
    }
}

/// Timer statistics for diagnostics
#[derive(Debug, Clone, serde::Serialize)]
#[cfg(test)]
pub struct TimerStats {
    pub enabled: bool,
    pub active: bool,
    pub refreshing: bool,
    pub session_interval_secs: u64,
    pub min_se_secs: u64,
    pub refresher: String,
    pub refresh_count: u32,
    pub failed_refreshes: u32,
    pub session_duration_secs: u64,
    pub time_until_refresh_secs: Option<u64>,
    pub time_until_expiration_secs: Option<u64>,
}

/// Get header value by name (case-insensitive)
pub fn get_header_value(headers: &rsipstack::sip::Headers, name: &str) -> Option<String> {
    headers
        .iter()
        .find(|header| header.name().eq_ignore_ascii_case(name))
        .map(|header| header.value().to_string())
}

/// Parse Session-Expires header value
/// Returns (interval, refresher) where refresher is optional
pub fn parse_session_expires(value: &str) -> Option<(Duration, Option<SessionRefresher>)> {
    let parts: Vec<&str> = value.split(';').collect();
    if parts.is_empty() {
        return None;
    }

    let seconds = parts[0].trim().parse::<u64>().ok()?;
    let mut refresher = None;

    for part in parts.iter().skip(1) {
        let part = part.trim();
        if part.starts_with("refresher=") {
            let val = part.trim_start_matches("refresher=");
            refresher = SessionRefresher::from_str(val).ok();
        }
    }

    Some((Duration::from_secs(seconds), refresher))
}

/// Check if the message has timer support (Supported: timer header)
pub fn has_timer_support(headers: &rsipstack::sip::Headers) -> bool {
    headers.iter().any(|h| match h {
        rsipstack::sip::Header::Supported(s) => s.value().split(',').any(|v| v.trim() == TIMER_TAG),
        rsipstack::sip::Header::Other(n, v) if n.eq_ignore_ascii_case(HEADER_SUPPORTED) => {
            v.split(',').any(|v| v.trim() == TIMER_TAG)
        }
        _ => false,
    })
}

/// Parse Min-SE header value
pub fn parse_min_se(value: &str) -> Option<Duration> {
    let seconds = value.trim().parse::<u64>().ok()?;
    Some(Duration::from_secs(seconds))
}

pub fn select_server_timer_refresher(
    peer_supports_timer: bool,
    session_expires_present: bool,
    requested_refresher: Option<SessionRefresher>,
) -> SessionRefresher {
    if let Some(refresher) = requested_refresher {
        refresher
    } else if peer_supports_timer && session_expires_present {
        SessionRefresher::Uac
    } else {
        SessionRefresher::Uas
    }
}

pub fn select_client_timer_refresher(
    requested_refresher: Option<SessionRefresher>,
) -> SessionRefresher {
    requested_refresher.unwrap_or(SessionRefresher::Uac)
}

pub fn apply_session_timer_headers(
    timer: &mut SessionTimerState,
    headers: &rsipstack::sip::Headers,
) -> Result<()> {
    if let Some(se_value) = get_header_value(headers, HEADER_SESSION_EXPIRES)
        && let Some((interval, refresher)) = parse_session_expires(&se_value)
    {
        if interval < timer.min_se {
            return Err(anyhow!(
                "Session-Expires too small: {} < {}",
                interval.as_secs(),
                timer.min_se.as_secs()
            ));
        }

        timer.session_interval = interval;
        if let Some(new_refresher) = refresher {
            timer.refresher = new_refresher;
        }
    }

    Ok(())
}

pub fn apply_refresh_response(
    timer: &mut SessionTimerState,
    headers: &rsipstack::sip::Headers,
    we_are_uac: bool,
) -> Result<()> {
    if get_header_value(headers, HEADER_SESSION_EXPIRES).is_none() {
        timer.complete_refresh();
        if timer.mode.is_always() {
            // Keep the local side responsible for refreshes when always mode is forcing
            // session timers but the peer omits Session-Expires in a successful refresh.
            timer.refresher = SessionRefresher::for_local_role(we_are_uac);
        } else {
            timer.enabled = false;
            timer.active = false;
        }
        return Ok(());
    }

    if let Err(e) = apply_session_timer_headers(timer, headers) {
        timer.fail_refresh();
        return Err(e);
    }

    timer.complete_refresh();
    Ok(())
}

fn build_timer_headers(
    session_expires: String,
    min_se: String,
    include_content_type: bool,
) -> Vec<rsipstack::sip::Header> {
    let mut headers = Vec::new();
    if include_content_type {
        headers.push(rsipstack::sip::Header::ContentType(
            "application/sdp".into(),
        ));
    }
    headers.push(rsipstack::sip::Header::Other(
        HEADER_SESSION_EXPIRES.to_string(),
        session_expires,
    ));
    headers.push(rsipstack::sip::Header::Other(
        HEADER_MIN_SE.to_string(),
        min_se,
    ));
    headers.push(rsipstack::sip::Header::Supported(
        rsipstack::sip::headers::Supported::from(TIMER_TAG),
    ));
    headers
}

pub fn build_default_session_timer_headers(
    session_expires: u64,
    min_se: u64,
) -> Vec<rsipstack::sip::Header> {
    build_timer_headers(session_expires.to_string(), min_se.to_string(), false)
}

pub fn build_session_timer_headers(
    timer: &SessionTimerState,
    include_content_type: bool,
) -> Vec<rsipstack::sip::Header> {
    build_timer_headers(
        timer.get_session_expires_value(),
        timer.get_min_se_value(),
        include_content_type,
    )
}

pub fn build_session_timer_response_headers(
    timer: &SessionTimerState,
) -> Vec<rsipstack::sip::Header> {
    vec![rsipstack::sip::Header::Other(
        HEADER_SESSION_EXPIRES.to_string(),
        timer.get_session_expires_value(),
    )]
}

/// Check if timer is required (Require: timer header)
#[cfg(test)]
pub fn is_timer_required(headers: &rsipstack::sip::Headers) -> bool {
    headers.iter().any(|h| match h {
        rsipstack::sip::Header::Require(s) => s.value().split(',').any(|v| v.trim() == TIMER_TAG),
        rsipstack::sip::Header::Other(n, v) if n.eq_ignore_ascii_case(HEADER_REQUIRE) => {
            v.split(',').any(|v| v.trim() == TIMER_TAG)
        }
        _ => false,
    })
}

/// Build Session-Expires header
#[cfg(test)]
pub fn build_session_expires_header(
    interval: Duration,
    refresher: SessionRefresher,
) -> rsipstack::sip::Header {
    let value = format!("{};refresher={}", interval.as_secs(), refresher);
    rsipstack::sip::Header::Other(HEADER_SESSION_EXPIRES.to_string(), value)
}

/// Build Min-SE header
#[cfg(test)]
pub fn build_min_se_header(min_se: Duration) -> rsipstack::sip::Header {
    rsipstack::sip::Header::Other(HEADER_MIN_SE.to_string(), min_se.as_secs().to_string())
}

/// Calculate the appropriate session interval based on negotiation
/// Returns Ok(interval) or Err(min_se) if the requested interval is too small
#[cfg(test)]
pub fn negotiate_session_interval(
    requested: Duration,
    local_min_se: Duration,
) -> Result<Duration, Duration> {
    if requested < local_min_se {
        Err(local_min_se)
    } else {
        Ok(requested)
    }
}

#[cfg(test)]
#[path = "session_timer_tests.rs"]
mod session_timer_tests;