• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2017 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "pc/ice_server_parsing.h"
12 
13 #include <stddef.h>
14 
15 #include <cctype>  // For std::isdigit.
16 #include <string>
17 
18 #include "p2p/base/port_interface.h"
19 #include "rtc_base/arraysize.h"
20 #include "rtc_base/checks.h"
21 #include "rtc_base/ip_address.h"
22 #include "rtc_base/logging.h"
23 #include "rtc_base/socket_address.h"
24 
25 namespace webrtc {
26 
27 // Number of tokens must be preset when TURN uri has transport param.
28 static const size_t kTurnTransportTokensNum = 2;
29 // The default stun port.
30 static const int kDefaultStunPort = 3478;
31 static const int kDefaultStunTlsPort = 5349;
32 static const char kTransport[] = "transport";
33 
34 // NOTE: Must be in the same order as the ServiceType enum.
35 static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
36 
37 // NOTE: A loop below assumes that the first value of this enum is 0 and all
38 // other values are incremental.
39 enum ServiceType {
40   STUN = 0,  // Indicates a STUN server.
41   STUNS,     // Indicates a STUN server used with a TLS session.
42   TURN,      // Indicates a TURN server
43   TURNS,     // Indicates a TURN server used with a TLS session.
44   INVALID,   // Unknown.
45 };
46 static_assert(INVALID == arraysize(kValidIceServiceTypes),
47               "kValidIceServiceTypes must have as many strings as ServiceType "
48               "has values.");
49 
50 // |in_str| should follow of RFC 7064/7065 syntax, but with an optional
51 // "?transport=" already stripped. I.e.,
52 // stunURI       = scheme ":" host [ ":" port ]
53 // scheme        = "stun" / "stuns" / "turn" / "turns"
54 // host          = IP-literal / IPv4address / reg-name
55 // port          = *DIGIT
GetServiceTypeAndHostnameFromUri(const std::string & in_str,ServiceType * service_type,std::string * hostname)56 static bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
57                                              ServiceType* service_type,
58                                              std::string* hostname) {
59   const std::string::size_type colonpos = in_str.find(':');
60   if (colonpos == std::string::npos) {
61     RTC_LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
62     return false;
63   }
64   if ((colonpos + 1) == in_str.length()) {
65     RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
66     return false;
67   }
68   *service_type = INVALID;
69   for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
70     if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
71       *service_type = static_cast<ServiceType>(i);
72       break;
73     }
74   }
75   if (*service_type == INVALID) {
76     return false;
77   }
78   *hostname = in_str.substr(colonpos + 1, std::string::npos);
79   return true;
80 }
81 
ParsePort(const std::string & in_str,int * port)82 static bool ParsePort(const std::string& in_str, int* port) {
83   // Make sure port only contains digits. FromString doesn't check this.
84   for (const char& c : in_str) {
85     if (!std::isdigit(c)) {
86       return false;
87     }
88   }
89   return rtc::FromString(in_str, port);
90 }
91 
92 // This method parses IPv6 and IPv4 literal strings, along with hostnames in
93 // standard hostname:port format.
94 // Consider following formats as correct.
95 // |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
96 // |hostname|, |[IPv6 address]|, |IPv4 address|.
ParseHostnameAndPortFromString(const std::string & in_str,std::string * host,int * port)97 static bool ParseHostnameAndPortFromString(const std::string& in_str,
98                                            std::string* host,
99                                            int* port) {
100   RTC_DCHECK(host->empty());
101   if (in_str.at(0) == '[') {
102     std::string::size_type closebracket = in_str.rfind(']');
103     if (closebracket != std::string::npos) {
104       std::string::size_type colonpos = in_str.find(':', closebracket);
105       if (std::string::npos != colonpos) {
106         if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
107                        port)) {
108           return false;
109         }
110       }
111       *host = in_str.substr(1, closebracket - 1);
112     } else {
113       return false;
114     }
115   } else {
116     std::string::size_type colonpos = in_str.find(':');
117     if (std::string::npos != colonpos) {
118       if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
119         return false;
120       }
121       *host = in_str.substr(0, colonpos);
122     } else {
123       *host = in_str;
124     }
125   }
126   return !host->empty();
127 }
128 
129 // Adds a STUN or TURN server to the appropriate list,
130 // by parsing |url| and using the username/password in |server|.
ParseIceServerUrl(const PeerConnectionInterface::IceServer & server,const std::string & url,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)131 static RTCErrorType ParseIceServerUrl(
132     const PeerConnectionInterface::IceServer& server,
133     const std::string& url,
134     cricket::ServerAddresses* stun_servers,
135     std::vector<cricket::RelayServerConfig>* turn_servers) {
136   // RFC 7064
137   // stunURI       = scheme ":" host [ ":" port ]
138   // scheme        = "stun" / "stuns"
139 
140   // RFC 7065
141   // turnURI       = scheme ":" host [ ":" port ]
142   //                 [ "?transport=" transport ]
143   // scheme        = "turn" / "turns"
144   // transport     = "udp" / "tcp" / transport-ext
145   // transport-ext = 1*unreserved
146 
147   // RFC 3986
148   // host     = IP-literal / IPv4address / reg-name
149   // port     = *DIGIT
150 
151   RTC_DCHECK(stun_servers != nullptr);
152   RTC_DCHECK(turn_servers != nullptr);
153   std::vector<std::string> tokens;
154   cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
155   RTC_DCHECK(!url.empty());
156   rtc::tokenize_with_empty_tokens(url, '?', &tokens);
157   std::string uri_without_transport = tokens[0];
158   // Let's look into transport= param, if it exists.
159   if (tokens.size() == kTurnTransportTokensNum) {  // ?transport= is present.
160     std::string uri_transport_param = tokens[1];
161     rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
162     if (tokens[0] != kTransport) {
163       RTC_LOG(LS_WARNING) << "Invalid transport parameter key.";
164       return RTCErrorType::SYNTAX_ERROR;
165     }
166     if (tokens.size() < 2) {
167       RTC_LOG(LS_WARNING) << "Transport parameter missing value.";
168       return RTCErrorType::SYNTAX_ERROR;
169     }
170     if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
171         (turn_transport_type != cricket::PROTO_UDP &&
172          turn_transport_type != cricket::PROTO_TCP)) {
173       RTC_LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
174       return RTCErrorType::SYNTAX_ERROR;
175     }
176   }
177 
178   std::string hoststring;
179   ServiceType service_type;
180   if (!GetServiceTypeAndHostnameFromUri(uri_without_transport, &service_type,
181                                         &hoststring)) {
182     RTC_LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
183     return RTCErrorType::SYNTAX_ERROR;
184   }
185 
186   // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
187   RTC_DCHECK(!hoststring.empty());
188 
189   int port = kDefaultStunPort;
190   if (service_type == TURNS) {
191     port = kDefaultStunTlsPort;
192     turn_transport_type = cricket::PROTO_TLS;
193   }
194 
195   if (hoststring.find('@') != std::string::npos) {
196     RTC_LOG(WARNING) << "Invalid url: " << uri_without_transport;
197     RTC_LOG(WARNING)
198         << "Note that user-info@ in turn:-urls is long-deprecated.";
199     return RTCErrorType::SYNTAX_ERROR;
200   }
201   std::string address;
202   if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
203     RTC_LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
204     return RTCErrorType::SYNTAX_ERROR;
205   }
206 
207   if (port <= 0 || port > 0xffff) {
208     RTC_LOG(WARNING) << "Invalid port: " << port;
209     return RTCErrorType::SYNTAX_ERROR;
210   }
211 
212   switch (service_type) {
213     case STUN:
214     case STUNS:
215       stun_servers->insert(rtc::SocketAddress(address, port));
216       break;
217     case TURN:
218     case TURNS: {
219       if (server.username.empty() || server.password.empty()) {
220         // The WebRTC spec requires throwing an InvalidAccessError when username
221         // or credential are ommitted; this is the native equivalent.
222         RTC_LOG(LS_ERROR) << "TURN server with empty username or password";
223         return RTCErrorType::INVALID_PARAMETER;
224       }
225       // If the hostname field is not empty, then the server address must be
226       // the resolved IP for that host, the hostname is needed later for TLS
227       // handshake (SNI and Certificate verification).
228       const std::string& hostname =
229           server.hostname.empty() ? address : server.hostname;
230       rtc::SocketAddress socket_address(hostname, port);
231       if (!server.hostname.empty()) {
232         rtc::IPAddress ip;
233         if (!IPFromString(address, &ip)) {
234           // When hostname is set, the server address must be a
235           // resolved ip address.
236           RTC_LOG(LS_ERROR)
237               << "IceServer has hostname field set, but URI does not "
238                  "contain an IP address.";
239           return RTCErrorType::INVALID_PARAMETER;
240         }
241         socket_address.SetResolvedIP(ip);
242       }
243       cricket::RelayServerConfig config =
244           cricket::RelayServerConfig(socket_address, server.username,
245                                      server.password, turn_transport_type);
246       if (server.tls_cert_policy ==
247           PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
248         config.tls_cert_policy =
249             cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
250       }
251       config.tls_alpn_protocols = server.tls_alpn_protocols;
252       config.tls_elliptic_curves = server.tls_elliptic_curves;
253 
254       turn_servers->push_back(config);
255       break;
256     }
257     default:
258       // We shouldn't get to this point with an invalid service_type, we should
259       // have returned an error already.
260       RTC_NOTREACHED() << "Unexpected service type";
261       return RTCErrorType::INTERNAL_ERROR;
262   }
263   return RTCErrorType::NONE;
264 }
265 
ParseIceServers(const PeerConnectionInterface::IceServers & servers,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)266 RTCErrorType ParseIceServers(
267     const PeerConnectionInterface::IceServers& servers,
268     cricket::ServerAddresses* stun_servers,
269     std::vector<cricket::RelayServerConfig>* turn_servers) {
270   for (const PeerConnectionInterface::IceServer& server : servers) {
271     if (!server.urls.empty()) {
272       for (const std::string& url : server.urls) {
273         if (url.empty()) {
274           RTC_LOG(LS_ERROR) << "Empty uri.";
275           return RTCErrorType::SYNTAX_ERROR;
276         }
277         RTCErrorType err =
278             ParseIceServerUrl(server, url, stun_servers, turn_servers);
279         if (err != RTCErrorType::NONE) {
280           return err;
281         }
282       }
283     } else if (!server.uri.empty()) {
284       // Fallback to old .uri if new .urls isn't present.
285       RTCErrorType err =
286           ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
287       if (err != RTCErrorType::NONE) {
288         return err;
289       }
290     } else {
291       RTC_LOG(LS_ERROR) << "Empty uri.";
292       return RTCErrorType::SYNTAX_ERROR;
293     }
294   }
295   // Candidates must have unique priorities, so that connectivity checks
296   // are performed in a well-defined order.
297   int priority = static_cast<int>(turn_servers->size() - 1);
298   for (cricket::RelayServerConfig& turn_server : *turn_servers) {
299     // First in the list gets highest priority.
300     turn_server.priority = priority--;
301   }
302   return RTCErrorType::NONE;
303 }
304 
305 }  // namespace webrtc
306