rtci_ice/url/mod.rs
1#[cfg(test)]
2mod url_test;
3
4use std::borrow::Cow;
5use std::convert::From;
6use std::fmt;
7
8use shared::error::*;
9
10/// The type of server used in the ice.URL structure.
11#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
12#[non_exhaustive]
13pub enum SchemeType {
14 /// The URL represents a STUN server.
15 Stun,
16
17 /// The URL represents a STUNS (secure) server.
18 Stuns,
19
20 /// The URL represents a TURN server.
21 Turn,
22
23 /// The URL represents a TURNS (secure) server.
24 Turns,
25
26 #[default]
27 /// Default public constant to use for "enum" like struct comparisons when no value was defined.
28 /// A scheme or transport this crate does not recognise.
29 Unknown,
30}
31
32impl From<&str> for SchemeType {
33 /// Defines a procedure for creating a new `SchemeType` from a raw
34 /// string naming the scheme type.
35 fn from(raw: &str) -> Self {
36 match raw {
37 "stun" => Self::Stun,
38 "stuns" => Self::Stuns,
39 "turn" => Self::Turn,
40 "turns" => Self::Turns,
41 _ => Self::Unknown,
42 }
43 }
44}
45
46impl fmt::Display for SchemeType {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 let s = match *self {
49 SchemeType::Stun => "stun",
50 SchemeType::Stuns => "stuns",
51 SchemeType::Turn => "turn",
52 SchemeType::Turns => "turns",
53 SchemeType::Unknown => "unknown",
54 };
55 write!(f, "{s}")
56 }
57}
58
59/// The transport protocol type that is used in the `ice::url::Url` structure.
60#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
61#[non_exhaustive]
62pub enum ProtoType {
63 /// The URL uses a UDP transport.
64 #[default]
65 Udp,
66
67 /// The URL uses a TCP transport.
68 Tcp,
69
70 /// A transport this crate does not recognise.
71 Unknown,
72}
73
74// defines a procedure for creating a new ProtoType from a raw
75// string naming the transport protocol type.
76impl From<&str> for ProtoType {
77 // NewSchemeType defines a procedure for creating a new SchemeType from a raw
78 // string naming the scheme type.
79 fn from(raw: &str) -> Self {
80 match raw {
81 "udp" => Self::Udp,
82 "tcp" => Self::Tcp,
83 _ => Self::Unknown,
84 }
85 }
86}
87
88impl fmt::Display for ProtoType {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 let s = match *self {
91 Self::Udp => "udp",
92 Self::Tcp => "tcp",
93 Self::Unknown => "unknown",
94 };
95 write!(f, "{s}")
96 }
97}
98
99/// Represents a STUN (rfc7064) or TURN (rfc7065) URL.
100#[derive(Debug, Clone, Default)]
101pub struct Url {
102 /// The URL scheme: `stun`, `stuns`, `turn` or `turns`.
103 pub scheme: SchemeType,
104 /// The server host name or address.
105 pub host: String,
106 /// The server port; defaults to 3478, or 5349 for the secure schemes.
107 pub port: u16,
108 /// The TURN username, for `turn:`/`turns:` URLs.
109 pub username: String,
110 /// The TURN credential.
111 pub password: String,
112 /// The transport to reach the server over, from the URL's `?transport=` parameter.
113 pub proto: ProtoType,
114 /// Whether the URL names the port. Without one, a server's name is looked up with
115 /// S-NAPTR and SRV before its addresses (RFC 5928 section 3, RFC 8489 section 8); with
116 /// one, only its addresses are (RFC 5928 section 3, RFC 7064 section 3.2).
117 pub explicit_port: bool,
118}
119
120impl fmt::Display for Url {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 // An IPv6 literal goes in brackets (RFC 7064 / RFC 7065 through RFC 3986's
123 // IP-literal), whether or not it has a "::" in it.
124 let host = if self.host.contains(':') {
125 "[".to_owned() + self.host.as_str() + "]"
126 } else {
127 self.host.clone()
128 };
129 if self.scheme == SchemeType::Turn || self.scheme == SchemeType::Turns {
130 write!(
131 f,
132 "{}:{}:{}?transport={}",
133 self.scheme, host, self.port, self.proto
134 )
135 } else {
136 write!(f, "{}:{}:{}", self.scheme, host, self.port)
137 }
138 }
139}
140
141impl Url {
142 /// Parses a STUN or TURN urls following the ABNF syntax described in
143 /// [IETF rfc-7064](https://tools.ietf.org/html/rfc7064) and
144 /// [IETF rfc-7065](https://tools.ietf.org/html/rfc7065) respectively, with RFC 8489
145 /// section 8.1: "A 'stuns' URI containing an IP address MUST be rejected" (`ErrHost`).
146 pub fn parse_url(raw: &str) -> Result<Self> {
147 let url = Self::parse_url_lenient(raw)?;
148 if url.scheme == SchemeType::Stuns && url.host.parse::<std::net::IpAddr>().is_ok() {
149 return Err(Error::ErrHost);
150 }
151 Ok(url)
152 }
153
154 /// [`parse_url`](Self::parse_url) without the RFC 8489 section 8.1 rule: a `stuns` URI
155 /// whose host is an IP address is accepted, as browsers do.
156 pub fn parse_url_lenient(raw: &str) -> Result<Self> {
157 // work around for url crate
158 if raw.contains("//") {
159 return Err(Error::ErrInvalidUrl);
160 }
161
162 let mut s = raw.to_string();
163 let pos = raw.find(':');
164 if let Some(p) = pos {
165 s.replace_range(p..=p, "://");
166 } else {
167 return Err(Error::ErrSchemeType);
168 }
169
170 let raw_parts = url::Url::parse(&s)?;
171
172 let scheme = raw_parts.scheme().into();
173
174 let host = if let Some(host) = raw_parts.host_str() {
175 host.trim()
176 .trim_start_matches('[')
177 .trim_end_matches(']')
178 .to_owned()
179 } else {
180 return Err(Error::ErrHost);
181 };
182
183 let explicit_port = raw_parts.port().is_some();
184 let port = if let Some(port) = raw_parts.port() {
185 port
186 } else if scheme == SchemeType::Stun || scheme == SchemeType::Turn {
187 3478
188 } else {
189 5349
190 };
191
192 let mut q_args = raw_parts.query_pairs();
193 let proto = match scheme {
194 SchemeType::Stun => {
195 if q_args.count() > 0 {
196 return Err(Error::ErrStunQuery);
197 }
198 ProtoType::Udp
199 }
200 SchemeType::Stuns => {
201 if q_args.count() > 0 {
202 return Err(Error::ErrStunQuery);
203 }
204 ProtoType::Tcp
205 }
206 SchemeType::Turn => {
207 if q_args.count() > 1 {
208 return Err(Error::ErrInvalidQuery);
209 }
210 if let Some((key, value)) = q_args.next() {
211 if key == Cow::Borrowed("transport") {
212 let proto: ProtoType = value.as_ref().into();
213 if proto == ProtoType::Unknown {
214 return Err(Error::ErrProtoType);
215 }
216 proto
217 } else {
218 return Err(Error::ErrInvalidQuery);
219 }
220 } else {
221 ProtoType::Udp
222 }
223 }
224 SchemeType::Turns => {
225 if q_args.count() > 1 {
226 return Err(Error::ErrInvalidQuery);
227 }
228 if let Some((key, value)) = q_args.next() {
229 if key == Cow::Borrowed("transport") {
230 let proto: ProtoType = value.as_ref().into();
231 if proto == ProtoType::Unknown {
232 return Err(Error::ErrProtoType);
233 }
234 proto
235 } else {
236 return Err(Error::ErrInvalidQuery);
237 }
238 } else {
239 ProtoType::Tcp
240 }
241 }
242 SchemeType::Unknown => {
243 return Err(Error::ErrSchemeType);
244 }
245 };
246
247 Ok(Self {
248 scheme,
249 host,
250 port,
251 username: "".to_owned(),
252 password: "".to_owned(),
253 proto,
254 explicit_port,
255 })
256 }
257
258 /*
259 fn parse_proto(raw:&str) ->Result<ProtoType> {
260 let qArgs= raw.split('=');
261 if qArgs.len() != 2 {
262 return Err(Error::ErrInvalidQuery.into());
263 }
264
265 var proto ProtoType
266 if rawProto := qArgs.Get("transport"); rawProto != "" {
267 if proto = NewProtoType(rawProto); proto == ProtoType(0) {
268 return ProtoType(Unknown), ErrProtoType
269 }
270 return proto, nil
271 }
272
273 if len(qArgs) > 0 {
274 return ProtoType(Unknown), ErrInvalidQuery
275 }
276
277 return proto, nil
278 }*/
279
280 /// Returns whether the this URL's scheme describes secure scheme or not.
281 #[must_use]
282 pub fn is_secure(&self) -> bool {
283 self.scheme == SchemeType::Stuns || self.scheme == SchemeType::Turns
284 }
285}