aboutsummaryrefslogtreecommitdiff
path: root/sip/src/encoding/request.rs
blob: ab41b7c3cc2d3284d58228b57c7006c683c9269a (plain)
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
use super::{headermap::HeaderMap, method::Method, uri::Uri};
use anyhow::{anyhow, bail};
use std::{fmt::Display, str::FromStr};

#[derive(Debug, Clone)]
pub struct Request {
    pub method: Method,
    pub uri: Uri,
    pub headers: HeaderMap,
    pub body: String,
}

impl Display for Request {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            headers,
            method,
            uri,
            ..
        } = self;
        write!(f, "{method} {uri} SIP/2.0\r\n")?;
        write!(f, "{headers}\r\n")?;
        Ok(())
    }
}
impl FromStr for Request {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut lines = s.lines();
        let statusline = lines.next().ok_or(anyhow!("status line missing"))?;
        let (method, rest) = statusline
            .split_once(" ")
            .ok_or(anyhow!("status line malformed"))?;
        let (uri, sipver) = rest
            .split_once(" ")
            .ok_or(anyhow!("status line malformed"))?;

        let Some(ver) = sipver.strip_prefix("SIP/") else {
            bail!("sip version malformed");
        };
        if ver != "2.0" {
            bail!("sip version {ver:?} is not supported");
        }

        let uri = Uri::from_str(uri)?;

        let headers = HeaderMap::parse(&mut lines)?;
        let method = Method::from_str(method)?;

        Ok(Self {
            body: String::new(),
            headers,
            method,
            uri,
        })
    }
}