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
// TODO DOCUMENTATION

// TODO divide Message into traits

#[derive(Debug)]
pub enum MessageType {
    Request(RequestMethod),
    Response(String),
}

#[derive(Debug)]
pub enum RequestMethod {
    Register,
    Invite,
    ACK,
    Cancel,
    Bye,
    Options,
}

// Remove pub's, add getters
#[derive(Debug)]
pub struct Message {
    pub mtype: MessageType, // Request/Response
    pub request_uri: String,

    // Mandatory for request headers:
    pub to: String,
    pub from: String,
    pub cseq: String,
    pub call_id: String,
    pub max_forwards: String,
    pub via: String,

    pub body: String,

    pub domain: String,
}

impl Message {
    pub fn new(mtype: MessageType, domain: String) -> Message {
        Message {
            mtype: mtype,
            request_uri: String::new(),
            to: String::new(),
            from: String::new(),
            cseq: String::new(),
            call_id: String::new(),
            max_forwards: String::new(),
            via: String::new(),
            body: String::new(),
            domain: domain,
        }
    }

    fn get_method_name(&mut self) -> Result<String, &'static str> {
        match &self.mtype {
            MessageType::Request(method) => {
                let method_str = match method {
                    RequestMethod::ACK => "ACK",
                    RequestMethod::Bye => "BYE",
                    RequestMethod::Cancel => "CANCEL",
                    RequestMethod::Invite => "INVITE",
                    RequestMethod::Options => "OPTIONS",
                    RequestMethod::Register => "REGISTER",
                };
                Ok(method_str.to_string())
            },
            MessageType::Response(_) => {
                Err("Incorrect message type.")
            }
        }
    }

    fn get_request_method_from_name(name: &str) -> Result<RequestMethod, &'static str> {
        let method = match name {
            "ACK" => RequestMethod::ACK,
            "BYE" => RequestMethod::Bye,
            "CANCEL" => RequestMethod::Cancel,
            "INVITE" => RequestMethod::Invite,
            "OPTIONS" => RequestMethod::Options,
            "REGISTER" => RequestMethod::Register,
            _ => return Err("Unknown method name.")
        };
        Ok(method)
    }

    // need to change implementation: make struct for each header:
    // for each implement value, build string to avoid this spaghetti
    // also, change branch
    pub fn via(&mut self, proto: String, host: String, port: String) -> &mut Message {
        self.via = format!("Via: SIP/2.0/{} {}:{};branch=z9hG4bK\r\n", proto, host, port);
        self
    }

    // add tag
    pub fn to(&mut self, display_name: String, ext: String) -> &mut Message {
        if display_name.is_empty() {
            self.to = format!("To: sip:{}@{}\r\n", ext, self.domain);
        } else {
            self.to = format!("To: {} <sip:{}@{}>\r\n", display_name, ext, self.domain);
        }
        self
    }

    pub fn get_to(&self) -> String {
        self.to.chars().skip_while(|c| c != &':').skip(1).skip_while(|c| c != &':').take_while(|c| c != &'@').collect()
    }

    // add tag
    pub fn from(&mut self, display_name: String, ext: String) -> &mut Message {
        if display_name.is_empty() {
            self.from = format!("From: sip:{}@{}\r\n", ext, self.domain);
        } else {
            self.from = format!("From: {} <sip:{}@{}>\r\n", display_name, ext, self.domain);
        }
        self
    }

    pub fn get_from(&self) -> String {
        self.from.chars().skip_while(|c| c != &':').skip(1).skip_while(|c| c != &':').take_while(|c| c != &'@').collect()
    }

    pub fn call_id(&mut self, call_id: String) -> &mut Message {
        self.call_id = format!("Call-ID: {}\r\n", call_id);
        self
    }

    pub fn cseq(&mut self, number: String) -> &mut Message {
        self.cseq = format!("CSeq: {} {}\r\n", number, self.get_method_name().unwrap());
        self
    }

    pub fn max_forwards(&mut self, number: String) -> &mut Message {
        self.max_forwards = format!("Max-Forwards: {}\r\n", number);
        self
    }

    pub fn request_uri(&mut self, uri: String) -> &mut Message {
        self.request_uri = uri;
        self
    }

    pub fn build_message(&mut self) -> String {
        let start_line = match &self.mtype {
            MessageType::Request(_) => {
                let method_name = self.get_method_name().unwrap();
                format!("{} sip:{}@{} SIP/2.0\r\n", method_name, self.request_uri, self.domain)
            },
            MessageType::Response(response) => {
                format!("SIP/2.0 {}", response)
            }
        };
        let content_length = match &self.body.is_empty() {
            true => String::from("Content-Length: 0\r\n\r\n"),
            false => format!("Content-Length: {}\r\n\r\n", &self.body.len()),
        };
        format!("{}{}{}{}{}{}{}{}{}", start_line, self.via, self.to, self.from, self.call_id, self.cseq, self.max_forwards, content_length, self.body)
    }

    pub fn parse(msg: &str) -> Message {
        let msg_split = msg.split("\r\n").collect::<Vec<_>>();

        let msg_head = msg_split[0].split(" ").collect::<Vec<_>>();

        let message_type = match msg_head[0].starts_with("SIP") {
            true => MessageType::Response(format!("{} {}", msg_head[0], msg_head[1])),
            false => MessageType::Request(Message::get_request_method_from_name(msg_head[0]).unwrap())
        };

        let mut message = Message::new(message_type, String::new());

        match message.mtype {
            MessageType::Request(_) => message.request_uri = msg_head[1].chars().skip_while(|c| c != &':').skip(1).take_while(|c| c != &'@').collect(),
            _ => ()
        };

        // Need to refactor
        for i in 1..msg_split.len() {
            if msg_split[i].starts_with("Via:") {
                message.via = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("To:") {
                message.to = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("From:") {
                message.from = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("Call-ID:") {
                message.call_id = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("CSeq:") {
                message.cseq = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("Max-Forwards:") {
                message.max_forwards = String::from(msg_split[i]);
            } else if msg_split[i].starts_with("Content-Length:") {
                // do smth
            } else { // body
                message.body = String::from(msg_split[i]);
            }
        }
        message
    }
}

// TODO TESTS!!!
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}