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
#[cfg(test)]
mod url_test;

use crate::error::*;

use std::borrow::Cow;
use std::convert::From;
use std::fmt;

/// The type of server used in the ice.URL structure.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum SchemeType {
    /// The URL represents a STUN server.
    Stun,

    /// The URL represents a STUNS (secure) server.
    Stuns,

    /// The URL represents a TURN server.
    Turn,

    /// The URL represents a TURNS (secure) server.
    Turns,

    /// Default public constant to use for "enum" like struct comparisons when no value was defined.
    Unknown,
}

impl Default for SchemeType {
    fn default() -> Self {
        Self::Unknown
    }
}

impl From<&str> for SchemeType {
    /// Defines a procedure for creating a new `SchemeType` from a raw
    /// string naming the scheme type.
    fn from(raw: &str) -> Self {
        match raw {
            "stun" => Self::Stun,
            "stuns" => Self::Stuns,
            "turn" => Self::Turn,
            "turns" => Self::Turns,
            _ => Self::Unknown,
        }
    }
}

impl fmt::Display for SchemeType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match *self {
            SchemeType::Stun => "stun",
            SchemeType::Stuns => "stuns",
            SchemeType::Turn => "turn",
            SchemeType::Turns => "turns",
            SchemeType::Unknown => "unknown",
        };
        write!(f, "{}", s)
    }
}

/// The transport protocol type that is used in the `ice::url::Url` structure.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum ProtoType {
    /// The URL uses a UDP transport.
    Udp,

    /// The URL uses a TCP transport.
    Tcp,

    Unknown,
}

impl Default for ProtoType {
    fn default() -> Self {
        Self::Udp
    }
}

// defines a procedure for creating a new ProtoType from a raw
// string naming the transport protocol type.
impl From<&str> for ProtoType {
    // NewSchemeType defines a procedure for creating a new SchemeType from a raw
    // string naming the scheme type.
    fn from(raw: &str) -> Self {
        match raw {
            "udp" => Self::Udp,
            "tcp" => Self::Tcp,
            _ => Self::Unknown,
        }
    }
}

impl fmt::Display for ProtoType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match *self {
            Self::Udp => "udp",
            Self::Tcp => "tcp",
            Self::Unknown => "unknown",
        };
        write!(f, "{}", s)
    }
}

/// Represents a STUN (rfc7064) or TURN (rfc7065) URL.
#[derive(Debug, Clone, Default)]
pub struct Url {
    pub scheme: SchemeType,
    pub host: String,
    pub port: u16,
    pub username: String,
    pub password: String,
    pub proto: ProtoType,
}

impl fmt::Display for Url {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let host = if self.host.contains("::") {
            "[".to_owned() + self.host.as_str() + "]"
        } else {
            self.host.clone()
        };
        if self.scheme == SchemeType::Turn || self.scheme == SchemeType::Turns {
            write!(
                f,
                "{}:{}:{}?transport={}",
                self.scheme, host, self.port, self.proto
            )
        } else {
            write!(f, "{}:{}:{}", self.scheme, host, self.port)
        }
    }
}

impl Url {
    /// Parses a STUN or TURN urls following the ABNF syntax described in
    /// [IETF rfc-7064](https://tools.ietf.org/html/rfc7064) and
    /// [IETF rfc-7065](https://tools.ietf.org/html/rfc7065) respectively.
    pub fn parse_url(raw: &str) -> Result<Self> {
        // work around for url crate
        if raw.contains("//") {
            return Err(Error::ErrInvalidUrl);
        }

        let mut s = raw.to_string();
        let pos = raw.find(':');
        if let Some(p) = pos {
            s.replace_range(p..=p, "://");
        } else {
            return Err(Error::ErrSchemeType);
        }

        let raw_parts = url::Url::parse(&s)?;

        let scheme = raw_parts.scheme().into();

        let host = if let Some(host) = raw_parts.host_str() {
            host.trim()
                .trim_start_matches('[')
                .trim_end_matches(']')
                .to_owned()
        } else {
            return Err(Error::ErrHost);
        };

        let port = if let Some(port) = raw_parts.port() {
            port
        } else if scheme == SchemeType::Stun || scheme == SchemeType::Turn {
            3478
        } else {
            5349
        };

        let mut q_args = raw_parts.query_pairs();
        let proto = match scheme {
            SchemeType::Stun => {
                if q_args.count() > 0 {
                    return Err(Error::ErrStunQuery);
                }
                ProtoType::Udp
            }
            SchemeType::Stuns => {
                if q_args.count() > 0 {
                    return Err(Error::ErrStunQuery);
                }
                ProtoType::Tcp
            }
            SchemeType::Turn => {
                if q_args.count() > 1 {
                    return Err(Error::ErrInvalidQuery);
                }
                if let Some((key, value)) = q_args.next() {
                    if key == Cow::Borrowed("transport") {
                        let proto: ProtoType = value.as_ref().into();
                        if proto == ProtoType::Unknown {
                            return Err(Error::ErrProtoType);
                        }
                        proto
                    } else {
                        return Err(Error::ErrInvalidQuery);
                    }
                } else {
                    ProtoType::Udp
                }
            }
            SchemeType::Turns => {
                if q_args.count() > 1 {
                    return Err(Error::ErrInvalidQuery);
                }
                if let Some((key, value)) = q_args.next() {
                    if key == Cow::Borrowed("transport") {
                        let proto: ProtoType = value.as_ref().into();
                        if proto == ProtoType::Unknown {
                            return Err(Error::ErrProtoType);
                        }
                        proto
                    } else {
                        return Err(Error::ErrInvalidQuery);
                    }
                } else {
                    ProtoType::Tcp
                }
            }
            SchemeType::Unknown => {
                return Err(Error::ErrSchemeType);
            }
        };

        Ok(Self {
            scheme,
            host,
            port,
            username: "".to_owned(),
            password: "".to_owned(),
            proto,
        })
    }

    /*
    fn parse_proto(raw:&str) ->Result<ProtoType> {
        let qArgs= raw.split('=');
        if qArgs.len() != 2 {
            return Err(Error::ErrInvalidQuery.into());
        }

        var proto ProtoType
        if rawProto := qArgs.Get("transport"); rawProto != "" {
            if proto = NewProtoType(rawProto); proto == ProtoType(0) {
                return ProtoType(Unknown), ErrProtoType
            }
            return proto, nil
        }

        if len(qArgs) > 0 {
            return ProtoType(Unknown), ErrInvalidQuery
        }

        return proto, nil
    }*/

    /// Returns whether the this URL's scheme describes secure scheme or not.
    #[must_use]
    pub fn is_secure(&self) -> bool {
        self.scheme == SchemeType::Stuns || self.scheme == SchemeType::Turns
    }
}