blob: 806fb3bc21563fb279d47e4cad2a3cf4c962a211 [file] [log] [blame]
deadbeef1dcb1642017-03-30 04:08:161/*
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 04:47:3111#include "pc/iceserverparsing.h"
deadbeef1dcb1642017-03-30 04:08:1612
13#include <cctype> // For std::isdigit.
14#include <string>
15
Mirko Bonadei92ea95e2017-09-15 04:47:3116#include "rtc_base/arraysize.h"
deadbeef1dcb1642017-03-30 04:08:1617
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 10:09:2560 RTC_LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
deadbeef1dcb1642017-03-30 04:08:1661 return false;
62 }
63 if ((colonpos + 1) == in_str.length()) {
Mirko Bonadei675513b2017-11-09 10:09:2564 RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
deadbeef1dcb1642017-03-30 04:08:1665 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 10:09:25161 RTC_LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef1dcb1642017-03-30 04:08:16162 return RTCErrorType::SYNTAX_ERROR;
163 }
164 if (tokens.size() < 2) {
Mirko Bonadei675513b2017-11-09 10:09:25165 RTC_LOG(LS_WARNING) << "Transport parameter missing value.";
deadbeef1dcb1642017-03-30 04:08:16166 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 10:09:25171 RTC_LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
deadbeef1dcb1642017-03-30 04:08:16172 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 10:09:25180 RTC_LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef1dcb1642017-03-30 04:08:16181 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 10:09:25193 RTC_LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef1dcb1642017-03-30 04:08:16194 return RTCErrorType::SYNTAX_ERROR;
195 }
196 if (tokens.size() == kTurnHostTokensNum) {
197 if (tokens[0].empty() || tokens[1].empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25198 RTC_LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef1dcb1642017-03-30 04:08:16199 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 10:09:25215 RTC_LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef1dcb1642017-03-30 04:08:16216 return RTCErrorType::SYNTAX_ERROR;
217 }
218
219 if (port <= 0 || port > 0xffff) {
Mirko Bonadei675513b2017-11-09 10:09:25220 RTC_LOG(WARNING) << "Invalid port: " << port;
deadbeef1dcb1642017-03-30 04:08:16221 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.
Harald Alvestrandb2a74782018-06-28 11:54:07234 RTC_LOG(LS_ERROR) << "TURN URL without username, or password empty";
deadbeef1dcb1642017-03-30 04:08:16235 return RTCErrorType::INVALID_PARAMETER;
236 }
Emad Omaradab1d2d2017-06-16 22:43:11237 // If the hostname field is not empty, then the server address must be
238 // the resolved IP for that host, the hostname is needed later for TLS
239 // handshake (SNI and Certificate verification).
240 const std::string& hostname =
241 server.hostname.empty() ? address : server.hostname;
242 rtc::SocketAddress socket_address(hostname, port);
243 if (!server.hostname.empty()) {
244 rtc::IPAddress ip;
245 if (!IPFromString(address, &ip)) {
246 // When hostname is set, the server address must be a
247 // resolved ip address.
Mirko Bonadei675513b2017-11-09 10:09:25248 RTC_LOG(LS_ERROR)
249 << "IceServer has hostname field set, but URI does not "
250 "contain an IP address.";
Emad Omaradab1d2d2017-06-16 22:43:11251 return RTCErrorType::INVALID_PARAMETER;
252 }
253 socket_address.SetResolvedIP(ip);
254 }
deadbeef1dcb1642017-03-30 04:08:16255 cricket::RelayServerConfig config = cricket::RelayServerConfig(
Emad Omaradab1d2d2017-06-16 22:43:11256 socket_address, username, server.password, turn_transport_type);
deadbeef1dcb1642017-03-30 04:08:16257 if (server.tls_cert_policy ==
258 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
Sergey Silkin9c147dd2018-09-12 10:45:38259 config.tls_cert_policy =
260 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
deadbeef1dcb1642017-03-30 04:08:16261 }
Sergey Silkin9c147dd2018-09-12 10:45:38262 config.tls_alpn_protocols = server.tls_alpn_protocols;
263 config.tls_elliptic_curves = server.tls_elliptic_curves;
Diogo Real1dca9d52017-08-29 19:18:32264
deadbeef1dcb1642017-03-30 04:08:16265 turn_servers->push_back(config);
266 break;
267 }
268 default:
269 // We shouldn't get to this point with an invalid service_type, we should
270 // have returned an error already.
271 RTC_NOTREACHED() << "Unexpected service type";
272 return RTCErrorType::INTERNAL_ERROR;
273 }
274 return RTCErrorType::NONE;
275}
276
277RTCErrorType ParseIceServers(
278 const PeerConnectionInterface::IceServers& servers,
279 cricket::ServerAddresses* stun_servers,
280 std::vector<cricket::RelayServerConfig>* turn_servers) {
281 for (const PeerConnectionInterface::IceServer& server : servers) {
282 if (!server.urls.empty()) {
283 for (const std::string& url : server.urls) {
284 if (url.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25285 RTC_LOG(LS_ERROR) << "Empty uri.";
deadbeef1dcb1642017-03-30 04:08:16286 return RTCErrorType::SYNTAX_ERROR;
287 }
288 RTCErrorType err =
289 ParseIceServerUrl(server, url, stun_servers, turn_servers);
290 if (err != RTCErrorType::NONE) {
291 return err;
292 }
293 }
294 } else if (!server.uri.empty()) {
295 // Fallback to old .uri if new .urls isn't present.
296 RTCErrorType err =
297 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
298 if (err != RTCErrorType::NONE) {
299 return err;
300 }
301 } else {
Mirko Bonadei675513b2017-11-09 10:09:25302 RTC_LOG(LS_ERROR) << "Empty uri.";
deadbeef1dcb1642017-03-30 04:08:16303 return RTCErrorType::SYNTAX_ERROR;
304 }
305 }
306 // Candidates must have unique priorities, so that connectivity checks
307 // are performed in a well-defined order.
308 int priority = static_cast<int>(turn_servers->size() - 1);
309 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
310 // First in the list gets highest priority.
311 turn_server.priority = priority--;
312 }
313 return RTCErrorType::NONE;
314}
315
316} // namespace webrtc