Skip to main content

active_call/useragent/
registration.rs

1use anyhow::Result;
2use rsipstack::dialog::{authenticate::Credential, registration::Registration};
3use rsipstack::rsip::{HostWithPort, Response, StatusCodeKind, Transport};
4use rsipstack::transport::SipAddr;
5use serde::{Deserialize, Serialize};
6use std::time::Instant;
7use tokio_util::sync::CancellationToken;
8use tracing::{debug, warn};
9
10use super::public_address::{normalize_transport, should_update_address};
11
12#[derive(Debug, Deserialize, Clone, Serialize)]
13pub struct UserCredential {
14    pub username: String,
15    pub password: String,
16    pub realm: Option<String>,
17}
18
19#[derive(Debug, Deserialize, Clone, Serialize)]
20pub struct RegisterOption {
21    pub server: String,
22    pub username: String,
23    pub display_name: Option<String>,
24    pub disabled: Option<bool>,
25    pub credential: Option<UserCredential>,
26}
27
28impl From<UserCredential> for Credential {
29    fn from(val: UserCredential) -> Self {
30        Credential {
31            username: val.username,
32            password: val.password,
33            realm: val.realm,
34        }
35    }
36}
37
38impl RegisterOption {
39    pub fn aor(&self) -> String {
40        format!("{}@{}", self.username, self.server)
41    }
42}
43
44pub struct RegistrationHandle {
45    pub registration: Registration,
46    pub option: RegisterOption,
47    pub cancel_token: CancellationToken,
48    pub start_time: Instant,
49    pub last_update: Instant,
50    pub last_response: Option<Response>,
51}
52
53impl RegistrationHandle {
54    pub fn should_retry_registration_now(
55        &self,
56        local_addr: &SipAddr,
57        current_contact_address: &HostWithPort,
58        discovered_public_address: Option<&HostWithPort>,
59    ) -> bool {
60        if normalize_transport(local_addr.r#type.as_ref()) != Transport::Udp {
61            return false;
62        }
63
64        discovered_public_address
65            .is_some_and(|address| should_update_address(current_contact_address, address))
66    }
67
68    pub async fn do_register(
69        &mut self,
70        sip_server: &rsipstack::rsip::Uri,
71        expires: Option<u32>,
72        contact: &rsipstack::rsip::typed::Contact,
73    ) -> Result<(u32, Option<HostWithPort>)> {
74        self.registration.contact = Some(contact.clone());
75        let resp = match self
76            .registration
77            .register(sip_server.clone(), expires)
78            .await
79            .map_err(|e| anyhow::anyhow!("Registration failed: {}", e))
80        {
81            Ok(resp) => resp,
82            Err(e) => {
83                warn!("registration failed: {}", e);
84                return Err(anyhow::anyhow!("Registration failed: {}", e));
85            }
86        };
87        debug!(
88            user = self.option.aor(),
89            "registration response: {:?}", resp
90        );
91        match resp.status_code().kind() {
92            StatusCodeKind::Successful => {
93                self.last_update = Instant::now();
94                self.last_response = Some(resp);
95                Ok((
96                    self.registration.expires(),
97                    self.registration.public_address.clone(),
98                ))
99            }
100            _ => Err(anyhow::anyhow!("{:?}", resp.reason_phrase())),
101        }
102    }
103}