rustpbx 0.3.19

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
use anyhow::Result;
use rsip::{
    Header, Transport,
    headers::auth::Algorithm,
    prelude::{HeadersExt, ToTypedHeader},
    typed::Authorization,
};
use rsipstack::{
    transaction::transaction::Transaction,
    transport::{SipAddr, SipConnection},
};
use serde::{Deserialize, Serialize};

use super::{CallForwardingConfig, CallForwardingMode, TransferEndpoint};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SipUser {
    #[serde(default)]
    pub id: u64,
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    pub username: String,
    pub password: Option<String>,
    pub realm: Option<String>,
    pub departments: Option<Vec<String>>,
    pub display_name: Option<String>,
    pub email: Option<String>,
    pub phone: Option<String>,
    pub note: Option<String>,
    #[serde(default)]
    pub allow_guest_calls: bool,
    /// When `true` the extension has opted out of voicemail; unanswered calls
    /// should **not** be forwarded to the voicemail application.
    #[serde(default)]
    pub voicemail_disabled: bool,
    #[serde(default)]
    pub call_forwarding_mode: Option<String>,
    #[serde(default)]
    pub call_forwarding_destination: Option<String>,
    #[serde(default)]
    pub call_forwarding_timeout: Option<i32>,
    /// From the original INVITE
    #[serde(skip)]
    pub origin_contact: Option<rsip::typed::Contact>,
    /// Current contact (may be updated by REGISTER)
    #[serde(skip)]
    pub contact: Option<rsip::typed::Contact>,
    #[serde(skip)]
    pub from: Option<rsip::Uri>,
    #[serde(skip)]
    pub destination: Option<SipAddr>,
    #[serde(default = "default_is_support_webrtc")]
    pub is_support_webrtc: bool,
}

impl ToString for SipUser {
    fn to_string(&self) -> String {
        if let Some(realm) = &self.realm {
            format!("{}@{}", self.username, realm)
        } else {
            self.username.clone()
        }
    }
}

fn default_enabled() -> bool {
    true
}

fn default_is_support_webrtc() -> bool {
    false
}

impl Default for SipUser {
    fn default() -> Self {
        Self {
            id: 0,
            enabled: true,
            username: "".to_string(),
            password: None,
            realm: None,
            origin_contact: None,
            contact: None,
            from: None,
            destination: None,
            is_support_webrtc: false,
            departments: None,
            display_name: None,
            email: None,
            phone: None,
            note: None,
            allow_guest_calls: false,
            voicemail_disabled: false,
            call_forwarding_mode: None,
            call_forwarding_destination: None,
            call_forwarding_timeout: None,
        }
    }
}

impl SipUser {
    pub fn get_contact_username(&self) -> String {
        match self.origin_contact {
            Some(ref contact) => contact.uri.user().unwrap_or_default().to_string(),
            None => self.username.clone(),
        }
    }
    pub fn merge_with(&mut self, other: &SipUser) {
        if self.id == 0 {
            self.id = other.id;
        }
        if self.password.is_none() {
            self.password = other.password.clone();
        }
        if self.realm.is_none() {
            self.realm = other.realm.clone();
        }
        if self.departments.is_none() {
            self.departments = other.departments.clone();
        }
        if self.display_name.is_none() {
            self.display_name = other.display_name.clone();
        }
        if self.email.is_none() {
            self.email = other.email.clone();
        }
        if self.phone.is_none() {
            self.phone = other.phone.clone();
        }
        if self.note.is_none() {
            self.note = other.note.clone();
        }
        if !self.allow_guest_calls {
            self.allow_guest_calls = other.allow_guest_calls;
        }
        if self.origin_contact.is_none() {
            self.origin_contact = other.origin_contact.clone();
        }
        if self.contact.is_none() {
            self.contact = other.contact.clone();
        }
        if self.from.is_none() {
            self.from = other.from.clone();
        }
        if self.destination.is_none() {
            self.destination = other.destination.clone();
        }
        if !self.is_support_webrtc {
            self.is_support_webrtc = other.is_support_webrtc;
        }
    }

    pub fn forwarding_config(&self) -> Option<CallForwardingConfig> {
        let mode_text = self
            .call_forwarding_mode
            .as_deref()
            .map(|value| value.trim().to_lowercase())?;
        if mode_text.is_empty() || mode_text == "none" {
            return None;
        }

        let destination = self
            .call_forwarding_destination
            .as_deref()
            .map(|value| value.trim())?;
        if destination.is_empty() {
            return None;
        }

        let endpoint = TransferEndpoint::parse(destination)?;

        let mode = match mode_text.as_str() {
            "always" => CallForwardingMode::Always,
            "when_busy" | "busy" => CallForwardingMode::WhenBusy,
            "when_not_answered" | "no_answer" => CallForwardingMode::WhenNoAnswer,
            _ => return None,
        };

        let timeout_secs = self
            .call_forwarding_timeout
            .map(|value| CallForwardingConfig::clamp_timeout(value as i64))
            .unwrap_or(super::CALL_FORWARDING_TIMEOUT_DEFAULT_SECS);

        Some(CallForwardingConfig::new(mode, endpoint, timeout_secs))
    }

    fn build_contact(&mut self, tx: &Transaction) {
        let addr = match tx.endpoint_inner.get_addrs().first() {
            Some(addr) => addr.clone(),
            None => return,
        };

        let mut contact_params = vec![];
        match addr.r#type {
            Some(rsip::Transport::Udp) | None => {}
            Some(t) => {
                contact_params.push(rsip::Param::Transport(t));
            }
        }
        let contact = rsip::typed::Contact {
            display_name: None,
            uri: rsip::Uri {
                scheme: addr.r#type.map(|t| t.sip_scheme()),
                auth: Some(rsip::Auth {
                    user: self.get_contact_username(),
                    password: None,
                }),
                host_with_port: addr.addr.clone(),
                ..Default::default()
            },
            params: contact_params,
        };
        self.contact = Some(contact);
    }

    pub fn auth_digest(&self, algorithm: Algorithm) -> String {
        use md5::{Digest, Md5};
        use sha2::{Sha256, Sha512};
        let value = format!(
            "{}:{}:{}",
            self.username,
            self.realm.as_ref().unwrap_or(&"".to_string()),
            self.password.as_ref().unwrap_or(&"".to_string()),
        );
        match algorithm {
            Algorithm::Md5 | Algorithm::Md5Sess => {
                let mut hasher = Md5::new();
                hasher.update(value);
                format!("{:x}", hasher.finalize())
            }
            Algorithm::Sha256 | Algorithm::Sha256Sess => {
                let mut hasher = Sha256::new();
                hasher.update(value);
                format!("{:x}", hasher.finalize())
            }
            Algorithm::Sha512 | Algorithm::Sha512Sess => {
                let mut hasher = Sha512::new();
                hasher.update(value);
                format!("{:x}", hasher.finalize())
            }
        }
    }
}

impl TryFrom<&Transaction> for SipUser {
    type Error = anyhow::Error;

    fn try_from(tx: &Transaction) -> Result<Self, Self::Error> {
        let from_header = tx.original.from_header()?;
        let from_uri = from_header.uri()?;
        let from_display_name = from_header
            .typed()
            .ok()
            .and_then(|h| h.display_name)
            .map(|s| s.to_string());

        let (username, realm) = match check_authorization_headers(&tx.original) {
            Ok(Some((user, _))) => (user.username, user.realm),
            _ => {
                let username = from_uri.user().unwrap_or_default().to_string();
                let realm = from_uri.host().to_string();
                let realm = if let Some(port) = from_uri.port() {
                    Some(format!("{}:{}", realm, port))
                } else {
                    Some(realm)
                };
                (username, realm)
            }
        };

        let origin_contact = match tx.original.contact_header() {
            Ok(contact) => contact.typed().ok(),
            Err(_) => None,
        };
        // Use rsipstack's via_received functionality to get destination
        let via_header = tx.original.via_header()?;
        let (via_transport, destination_addr) = SipConnection::parse_target_from_via(via_header)
            .map_err(|e| anyhow::anyhow!("failed to parse via header: {:?}", e))?;

        let destination = SipAddr {
            r#type: Some(via_transport),
            addr: destination_addr,
        };

        let is_support_webrtc = matches!(via_transport, Transport::Wss | Transport::Ws);

        let mut u = SipUser {
            id: 0,
            username,
            password: None,
            enabled: true,
            realm,
            origin_contact,
            contact: None,
            from: Some(from_uri),
            destination: Some(destination),
            is_support_webrtc,
            call_forwarding_mode: None,
            call_forwarding_destination: None,
            call_forwarding_timeout: None,
            departments: None,
            display_name: from_display_name,
            email: None,
            phone: None,
            note: None,
            allow_guest_calls: false,
            voicemail_disabled: false,
        };
        u.build_contact(tx);
        Ok(u)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── SipUser::voicemail_disabled ────────────────────────────────────────────

    #[test]
    fn voicemail_disabled_default_is_false() {
        // Voicemail should be active for a user unless explicitly disabled.
        let user = SipUser::default();
        assert!(
            !user.voicemail_disabled,
            "SipUser::default() must have voicemail_disabled = false"
        );
    }

    #[test]
    fn voicemail_disabled_can_be_set_true() {
        let user = SipUser {
            username: "1001".into(),
            voicemail_disabled: true,
            ..Default::default()
        };
        assert!(user.voicemail_disabled);
    }

    #[test]
    fn merge_with_does_not_override_voicemail_disabled_when_true() {
        // If the primary record already has voicemail_disabled = true the
        // merge should **not** overwrite it with the other side's false.
        let mut primary = SipUser {
            username: "1001".into(),
            voicemail_disabled: true,
            ..Default::default()
        };
        let secondary = SipUser {
            username: "1001".into(),
            voicemail_disabled: false,
            email: Some("alice@pbx.local".into()),
            ..Default::default()
        };
        primary.merge_with(&secondary);
        // voicemail_disabled is a plain bool; merge_with only copies optional
        // fields and bool flags using the `if !flag { flag = other }` pattern.
        // voicemail_disabled is intentionally NOT merged (it is not an Option),
        // so the primary side wins.
        assert!(
            primary.voicemail_disabled,
            "primary.voicemail_disabled should remain true after merge"
        );
        // merge_with should still fill in missing optional fields
        assert_eq!(primary.email.as_deref(), Some("alice@pbx.local"));
    }

    #[test]
    fn merge_with_propagates_voicemail_disabled_when_not_yet_set() {
        // A freshly built SipUser (voicemail_disabled = false) that merges with
        // a DB record that also has voicemail_disabled = false stays false.
        let mut primary = SipUser::default();
        let secondary = SipUser {
            voicemail_disabled: false,
            ..Default::default()
        };
        primary.merge_with(&secondary);
        assert!(!primary.voicemail_disabled);
    }
}

pub fn check_authorization_headers(
    req: &rsip::Request,
) -> Result<Option<(SipUser, Authorization)>> {
    // First try Authorization header (for backward compatibility with existing tests)
    if let Some(auth_header) = rsip::header_opt!(req.headers.iter(), Header::Authorization) {
        let challenge = auth_header.typed()?;
        let user = SipUser {
            username: challenge.username.to_string(),
            realm: Some(challenge.realm.to_string()),
            ..Default::default()
        };
        return Ok(Some((user, challenge)));
    }
    // Then try Proxy-Authorization header
    if let Some(proxy_auth_header) =
        rsip::header_opt!(req.headers.iter(), Header::ProxyAuthorization)
    {
        let challenge = proxy_auth_header.typed()?.0;
        let user = SipUser {
            username: challenge.username.to_string(),
            realm: Some(challenge.realm.to_string()),
            ..Default::default()
        };
        return Ok(Some((user, challenge)));
    }

    Ok(None)
}