blob: b260954f04a997798612459936adfaa086944697 [file] [log] [blame]
deadbeef1dcb1642017-03-29 21:08:16 -07001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/iceserverparsing.h"
deadbeef1dcb1642017-03-29 21:08:16 -070012
13#include <cctype> // For std::isdigit.
14#include <string>
15
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "rtc_base/arraysize.h"
deadbeef1dcb1642017-03-29 21:08:16 -070017
18namespace webrtc {
19
20// The min number of tokens must present in Turn host uri.
21// e.g. user@turn.example.org
22static const size_t kTurnHostTokensNum = 2;
23// Number of tokens must be preset when TURN uri has transport param.
24static const size_t kTurnTransportTokensNum = 2;
25// The default stun port.
26static const int kDefaultStunPort = 3478;
27static const int kDefaultStunTlsPort = 5349;
28static const char kTransport[] = "transport";
29
30// NOTE: Must be in the same order as the ServiceType enum.
31static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
32
33// NOTE: A loop below assumes that the first value of this enum is 0 and all
34// other values are incremental.
35enum ServiceType {
36 STUN = 0, // Indicates a STUN server.
37 STUNS, // Indicates a STUN server used with a TLS session.
38 TURN, // Indicates a TURN server
39 TURNS, // Indicates a TURN server used with a TLS session.
40 INVALID, // Unknown.
41};
42static_assert(INVALID == arraysize(kValidIceServiceTypes),
43 "kValidIceServiceTypes must have as many strings as ServiceType "
44 "has values.");
45
46// |in_str| should be of format
47// stunURI = scheme ":" stun-host [ ":" stun-port ]
48// scheme = "stun" / "stuns"
49// stun-host = IP-literal / IPv4address / reg-name
50// stun-port = *DIGIT
51//
52// draft-petithuguenin-behave-turn-uris-01
53// turnURI = scheme ":" turn-host [ ":" turn-port ]
54// turn-host = username@IP-literal / IPv4address / reg-name
55static bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
56 ServiceType* service_type,
57 std::string* hostname) {
58 const std::string::size_type colonpos = in_str.find(':');
59 if (colonpos == std::string::npos) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010060 RTC_LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
deadbeef1dcb1642017-03-29 21:08:16 -070061 return false;
62 }
63 if ((colonpos + 1) == in_str.length()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010064 RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
deadbeef1dcb1642017-03-29 21:08:16 -070065 return false;
66 }
67 *service_type = INVALID;
68 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
69 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
70 *service_type = static_cast<ServiceType>(i);
71 break;
72 }
73 }
74 if (*service_type == INVALID) {
75 return false;
76 }
77 *hostname = in_str.substr(colonpos + 1, std::string::npos);
78 return true;
79}
80
81static bool ParsePort(const std::string& in_str, int* port) {
82 // Make sure port only contains digits. FromString doesn't check this.
83 for (const char& c : in_str) {
84 if (!std::isdigit(c)) {
85 return false;
86 }
87 }
88 return rtc::FromString(in_str, port);
89}
90
91// This method parses IPv6 and IPv4 literal strings, along with hostnames in
92// standard hostname:port format.
93// Consider following formats as correct.
94// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
95// |hostname|, |[IPv6 address]|, |IPv4 address|.
96static bool ParseHostnameAndPortFromString(const std::string& in_str,
97 std::string* host,
98 int* port) {
99 RTC_DCHECK(host->empty());
100 if (in_str.at(0) == '[') {
101 std::string::size_type closebracket = in_str.rfind(']');
102 if (closebracket != std::string::npos) {
103 std::string::size_type colonpos = in_str.find(':', closebracket);
104 if (std::string::npos != colonpos) {
105 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
106 port)) {
107 return false;
108 }
109 }
110 *host = in_str.substr(1, closebracket - 1);
111 } else {
112 return false;
113 }
114 } else {
115 std::string::size_type colonpos = in_str.find(':');
116 if (std::string::npos != colonpos) {
117 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
118 return false;
119 }
120 *host = in_str.substr(0, colonpos);
121 } else {
122 *host = in_str;
123 }
124 }
125 return !host->empty();
126}
127
128// Adds a STUN or TURN server to the appropriate list,
129// by parsing |url| and using the username/password in |server|.
130static RTCErrorType ParseIceServerUrl(
131 const PeerConnectionInterface::IceServer& server,
132 const std::string& url,
133 cricket::ServerAddresses* stun_servers,
134 std::vector<cricket::RelayServerConfig>* turn_servers) {
135 // draft-nandakumar-rtcweb-stun-uri-01
136 // stunURI = scheme ":" stun-host [ ":" stun-port ]
137 // scheme = "stun" / "stuns"
138 // stun-host = IP-literal / IPv4address / reg-name
139 // stun-port = *DIGIT
140
141 // draft-petithuguenin-behave-turn-uris-01
142 // turnURI = scheme ":" turn-host [ ":" turn-port ]
143 // [ "?transport=" transport ]
144 // scheme = "turn" / "turns"
145 // transport = "udp" / "tcp" / transport-ext
146 // transport-ext = 1*unreserved
147 // turn-host = IP-literal / IPv4address / reg-name
148 // turn-port = *DIGIT
149 RTC_DCHECK(stun_servers != nullptr);
150 RTC_DCHECK(turn_servers != nullptr);
151 std::vector<std::string> tokens;
152 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
153 RTC_DCHECK(!url.empty());
154 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
155 std::string uri_without_transport = tokens[0];
156 // Let's look into transport= param, if it exists.
157 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
158 std::string uri_transport_param = tokens[1];
159 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
160 if (tokens[0] != kTransport) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100161 RTC_LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef1dcb1642017-03-29 21:08:16 -0700162 return RTCErrorType::SYNTAX_ERROR;
163 }
164 if (tokens.size() < 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100165 RTC_LOG(LS_WARNING) << "Transport parameter missing value.";
deadbeef1dcb1642017-03-29 21:08:16 -0700166 return RTCErrorType::SYNTAX_ERROR;
167 }
168 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
169 (turn_transport_type != cricket::PROTO_UDP &&
170 turn_transport_type != cricket::PROTO_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 RTC_LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
deadbeef1dcb1642017-03-29 21:08:16 -0700172 return RTCErrorType::SYNTAX_ERROR;
173 }
174 }
175
176 std::string hoststring;
177 ServiceType service_type;
178 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport, &service_type,
179 &hoststring)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100180 RTC_LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef1dcb1642017-03-29 21:08:16 -0700181 return RTCErrorType::SYNTAX_ERROR;
182 }
183
184 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
185 RTC_DCHECK(!hoststring.empty());
186
187 // Let's break hostname.
188 tokens.clear();
189 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
190
191 std::string username(server.username);
192 if (tokens.size() > kTurnHostTokensNum) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100193 RTC_LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef1dcb1642017-03-29 21:08:16 -0700194 return RTCErrorType::SYNTAX_ERROR;
195 }
196 if (tokens.size() == kTurnHostTokensNum) {
197 if (tokens[0].empty() || tokens[1].empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100198 RTC_LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef1dcb1642017-03-29 21:08:16 -0700199 return RTCErrorType::SYNTAX_ERROR;
200 }
201 username.assign(rtc::s_url_decode(tokens[0]));
202 hoststring = tokens[1];
203 } else {
204 hoststring = tokens[0];
205 }
206
207 int port = kDefaultStunPort;
208 if (service_type == TURNS) {
209 port = kDefaultStunTlsPort;
210 turn_transport_type = cricket::PROTO_TLS;
211 }
212
213 std::string address;
214 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100215 RTC_LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef1dcb1642017-03-29 21:08:16 -0700216 return RTCErrorType::SYNTAX_ERROR;
217 }
218
219 if (port <= 0 || port > 0xffff) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100220 RTC_LOG(WARNING) << "Invalid port: " << port;
deadbeef1dcb1642017-03-29 21:08:16 -0700221 return RTCErrorType::SYNTAX_ERROR;
222 }
223
224 switch (service_type) {
225 case STUN:
226 case STUNS:
227 stun_servers->insert(rtc::SocketAddress(address, port));
228 break;
229 case TURN:
230 case TURNS: {
231 if (username.empty() || server.password.empty()) {
232 // The WebRTC spec requires throwing an InvalidAccessError when username
233 // or credential are ommitted; this is the native equivalent.
234 return RTCErrorType::INVALID_PARAMETER;
235 }
Emad Omaradab1d2d2017-06-16 15:43:11 -0700236 // If the hostname field is not empty, then the server address must be
237 // the resolved IP for that host, the hostname is needed later for TLS
238 // handshake (SNI and Certificate verification).
239 const std::string& hostname =
240 server.hostname.empty() ? address : server.hostname;
241 rtc::SocketAddress socket_address(hostname, port);
242 if (!server.hostname.empty()) {
243 rtc::IPAddress ip;
244 if (!IPFromString(address, &ip)) {
245 // When hostname is set, the server address must be a
246 // resolved ip address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100247 RTC_LOG(LS_ERROR)
248 << "IceServer has hostname field set, but URI does not "
249 "contain an IP address.";
Emad Omaradab1d2d2017-06-16 15:43:11 -0700250 return RTCErrorType::INVALID_PARAMETER;
251 }
252 socket_address.SetResolvedIP(ip);
253 }
deadbeef1dcb1642017-03-29 21:08:16 -0700254 cricket::RelayServerConfig config = cricket::RelayServerConfig(
Emad Omaradab1d2d2017-06-16 15:43:11 -0700255 socket_address, username, server.password, turn_transport_type);
deadbeef1dcb1642017-03-29 21:08:16 -0700256 if (server.tls_cert_policy ==
257 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
258 config.tls_cert_policy =
259 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
260 }
Diogo Real1dca9d52017-08-29 12:18:32 -0700261 config.tls_alpn_protocols = server.tls_alpn_protocols;
Diogo Real7bd1f1b2017-09-08 12:50:41 -0700262 config.tls_elliptic_curves = server.tls_elliptic_curves;
Diogo Real1dca9d52017-08-29 12:18:32 -0700263
deadbeef1dcb1642017-03-29 21:08:16 -0700264 turn_servers->push_back(config);
265 break;
266 }
267 default:
268 // We shouldn't get to this point with an invalid service_type, we should
269 // have returned an error already.
270 RTC_NOTREACHED() << "Unexpected service type";
271 return RTCErrorType::INTERNAL_ERROR;
272 }
273 return RTCErrorType::NONE;
274}
275
276RTCErrorType ParseIceServers(
277 const PeerConnectionInterface::IceServers& servers,
278 cricket::ServerAddresses* stun_servers,
279 std::vector<cricket::RelayServerConfig>* turn_servers) {
280 for (const PeerConnectionInterface::IceServer& server : servers) {
281 if (!server.urls.empty()) {
282 for (const std::string& url : server.urls) {
283 if (url.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100284 RTC_LOG(LS_ERROR) << "Empty uri.";
deadbeef1dcb1642017-03-29 21:08:16 -0700285 return RTCErrorType::SYNTAX_ERROR;
286 }
287 RTCErrorType err =
288 ParseIceServerUrl(server, url, stun_servers, turn_servers);
289 if (err != RTCErrorType::NONE) {
290 return err;
291 }
292 }
293 } else if (!server.uri.empty()) {
294 // Fallback to old .uri if new .urls isn't present.
295 RTCErrorType err =
296 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
297 if (err != RTCErrorType::NONE) {
298 return err;
299 }
300 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100301 RTC_LOG(LS_ERROR) << "Empty uri.";
deadbeef1dcb1642017-03-29 21:08:16 -0700302 return RTCErrorType::SYNTAX_ERROR;
303 }
304 }
305 // Candidates must have unique priorities, so that connectivity checks
306 // are performed in a well-defined order.
307 int priority = static_cast<int>(turn_servers->size() - 1);
308 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
309 // First in the list gets highest priority.
310 turn_server.priority = priority--;
311 }
312 return RTCErrorType::NONE;
313}
314
315} // namespace webrtc