xref: /aosp_15_r20/external/webrtc/pc/ice_server_parsing.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 #include <tuple>
18 
19 #include "p2p/base/port_interface.h"
20 #include "rtc_base/arraysize.h"
21 #include "rtc_base/checks.h"
22 #include "rtc_base/ip_address.h"
23 #include "rtc_base/logging.h"
24 #include "rtc_base/socket_address.h"
25 #include "rtc_base/string_encode.h"
26 #include "rtc_base/string_to_number.h"
27 
28 namespace webrtc {
29 
30 namespace {
31 // Number of tokens must be preset when TURN uri has transport param.
32 const size_t kTurnTransportTokensNum = 2;
33 // The default stun port.
34 const int kDefaultStunPort = 3478;
35 const int kDefaultStunTlsPort = 5349;
36 const char kTransport[] = "transport";
37 
38 // Allowed characters in hostname per RFC 3986 Appendix A "reg-name"
39 const char kRegNameCharacters[] =
40     "abcdefghijklmnopqrstuvwxyz"
41     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
42     "0123456789"
43     "-._~"          // unreserved
44     "%"             // pct-encoded
45     "!$&'()*+,;=";  // sub-delims
46 
47 // NOTE: Must be in the same order as the ServiceType enum.
48 const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
49 
50 // NOTE: A loop below assumes that the first value of this enum is 0 and all
51 // other values are incremental.
52 enum class ServiceType {
53   STUN = 0,  // Indicates a STUN server.
54   STUNS,     // Indicates a STUN server used with a TLS session.
55   TURN,      // Indicates a TURN server
56   TURNS,     // Indicates a TURN server used with a TLS session.
57   INVALID,   // Unknown.
58 };
59 static_assert(static_cast<size_t>(ServiceType::INVALID) ==
60                   arraysize(kValidIceServiceTypes),
61               "kValidIceServiceTypes must have as many strings as ServiceType "
62               "has values.");
63 
64 // `in_str` should follow of RFC 7064/7065 syntax, but with an optional
65 // "?transport=" already stripped. I.e.,
66 // stunURI       = scheme ":" host [ ":" port ]
67 // scheme        = "stun" / "stuns" / "turn" / "turns"
68 // host          = IP-literal / IPv4address / reg-name
69 // port          = *DIGIT
70 
71 // Return tuple is service_type, host, with service_type == ServiceType::INVALID
72 // on failure.
GetServiceTypeAndHostnameFromUri(absl::string_view in_str)73 std::tuple<ServiceType, absl::string_view> GetServiceTypeAndHostnameFromUri(
74     absl::string_view in_str) {
75   const auto colonpos = in_str.find(':');
76   if (colonpos == absl::string_view::npos) {
77     RTC_LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
78     return {ServiceType::INVALID, ""};
79   }
80   if ((colonpos + 1) == in_str.length()) {
81     RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
82     return {ServiceType::INVALID, ""};
83   }
84   for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
85     if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
86       return {static_cast<ServiceType>(i), in_str.substr(colonpos + 1)};
87     }
88   }
89   return {ServiceType::INVALID, ""};
90 }
91 
ParsePort(absl::string_view in_str)92 absl::optional<int> ParsePort(absl::string_view in_str) {
93   // Make sure port only contains digits. StringToNumber doesn't check this.
94   for (const char& c : in_str) {
95     if (!std::isdigit(static_cast<unsigned char>(c))) {
96       return false;
97     }
98   }
99   return rtc::StringToNumber<int>(in_str);
100 }
101 
102 // This method parses IPv6 and IPv4 literal strings, along with hostnames in
103 // standard hostname:port format.
104 // Consider following formats as correct.
105 // `hostname:port`, |[IPV6 address]:port|, |IPv4 address|:port,
106 // `hostname`, |[IPv6 address]|, |IPv4 address|.
107 
108 // Return tuple is success, host, port.
ParseHostnameAndPortFromString(absl::string_view in_str,int default_port)109 std::tuple<bool, absl::string_view, int> ParseHostnameAndPortFromString(
110     absl::string_view in_str,
111     int default_port) {
112   if (in_str.empty()) {
113     return {false, "", 0};
114   }
115   absl::string_view host;
116   int port = default_port;
117 
118   if (in_str.at(0) == '[') {
119     // IP_literal syntax
120     auto closebracket = in_str.rfind(']');
121     if (closebracket == absl::string_view::npos) {
122       return {false, "", 0};
123     }
124     auto colonpos = in_str.find(':', closebracket);
125     if (absl::string_view::npos != colonpos) {
126       if (absl::optional<int> opt_port =
127               ParsePort(in_str.substr(closebracket + 2))) {
128         port = *opt_port;
129       } else {
130         return {false, "", 0};
131       }
132     }
133     host = in_str.substr(1, closebracket - 1);
134   } else {
135     // IPv4address or reg-name syntax
136     auto colonpos = in_str.find(':');
137     if (absl::string_view::npos != colonpos) {
138       if (absl::optional<int> opt_port =
139               ParsePort(in_str.substr(colonpos + 1))) {
140         port = *opt_port;
141       } else {
142         return {false, "", 0};
143       }
144       host = in_str.substr(0, colonpos);
145     } else {
146       host = in_str;
147     }
148     // RFC 3986 section 3.2.2 and Appendix A - "reg-name" syntax
149     if (host.find_first_not_of(kRegNameCharacters) != absl::string_view::npos) {
150       return {false, "", 0};
151     }
152   }
153   return {!host.empty(), host, port};
154 }
155 
156 // Adds a STUN or TURN server to the appropriate list,
157 // by parsing `url` and using the username/password in `server`.
ParseIceServerUrl(const PeerConnectionInterface::IceServer & server,absl::string_view url,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)158 RTCError ParseIceServerUrl(
159     const PeerConnectionInterface::IceServer& server,
160     absl::string_view url,
161     cricket::ServerAddresses* stun_servers,
162     std::vector<cricket::RelayServerConfig>* turn_servers) {
163   // RFC 7064
164   // stunURI       = scheme ":" host [ ":" port ]
165   // scheme        = "stun" / "stuns"
166 
167   // RFC 7065
168   // turnURI       = scheme ":" host [ ":" port ]
169   //                 [ "?transport=" transport ]
170   // scheme        = "turn" / "turns"
171   // transport     = "udp" / "tcp" / transport-ext
172   // transport-ext = 1*unreserved
173 
174   // RFC 3986
175   // host     = IP-literal / IPv4address / reg-name
176   // port     = *DIGIT
177 
178   RTC_DCHECK(stun_servers != nullptr);
179   RTC_DCHECK(turn_servers != nullptr);
180   cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
181   RTC_DCHECK(!url.empty());
182   std::vector<absl::string_view> tokens = rtc::split(url, '?');
183   absl::string_view uri_without_transport = tokens[0];
184   // Let's look into transport= param, if it exists.
185   if (tokens.size() == kTurnTransportTokensNum) {  // ?transport= is present.
186     std::vector<absl::string_view> transport_tokens =
187         rtc::split(tokens[1], '=');
188     if (transport_tokens[0] != kTransport) {
189       LOG_AND_RETURN_ERROR(
190           RTCErrorType::SYNTAX_ERROR,
191           "ICE server parsing failed: Invalid transport parameter key.");
192     }
193     if (transport_tokens.size() < 2) {
194       LOG_AND_RETURN_ERROR(
195           RTCErrorType::SYNTAX_ERROR,
196           "ICE server parsing failed: Transport parameter missing value.");
197     }
198 
199     absl::optional<cricket::ProtocolType> proto =
200         cricket::StringToProto(transport_tokens[1]);
201     if (!proto ||
202         (*proto != cricket::PROTO_UDP && *proto != cricket::PROTO_TCP)) {
203       LOG_AND_RETURN_ERROR(
204           RTCErrorType::SYNTAX_ERROR,
205           "ICE server parsing failed: Transport parameter should "
206           "always be udp or tcp.");
207     }
208     turn_transport_type = *proto;
209   }
210 
211   auto [service_type, hoststring] =
212       GetServiceTypeAndHostnameFromUri(uri_without_transport);
213   if (service_type == ServiceType::INVALID) {
214     RTC_LOG(LS_ERROR) << "Invalid transport parameter in ICE URI: " << url;
215     LOG_AND_RETURN_ERROR(
216         RTCErrorType::SYNTAX_ERROR,
217         "ICE server parsing failed: Invalid transport parameter in ICE URI");
218   }
219 
220   // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
221   RTC_DCHECK(!hoststring.empty());
222 
223   int default_port = kDefaultStunPort;
224   if (service_type == ServiceType::TURNS) {
225     default_port = kDefaultStunTlsPort;
226     turn_transport_type = cricket::PROTO_TLS;
227   }
228 
229   if (hoststring.find('@') != absl::string_view::npos) {
230     RTC_LOG(LS_ERROR) << "Invalid url with long deprecated user@host syntax: "
231                       << uri_without_transport;
232     LOG_AND_RETURN_ERROR(RTCErrorType::SYNTAX_ERROR,
233                          "ICE server parsing failed: Invalid url with long "
234                          "deprecated user@host syntax");
235   }
236 
237   auto [success, address, port] =
238       ParseHostnameAndPortFromString(hoststring, default_port);
239   if (!success) {
240     RTC_LOG(LS_ERROR) << "Invalid hostname format: " << uri_without_transport;
241     LOG_AND_RETURN_ERROR(RTCErrorType::SYNTAX_ERROR,
242                          "ICE server parsing failed: Invalid hostname format");
243   }
244 
245   if (port <= 0 || port > 0xffff) {
246     RTC_LOG(LS_ERROR) << "Invalid port: " << port;
247     LOG_AND_RETURN_ERROR(RTCErrorType::SYNTAX_ERROR,
248                          "ICE server parsing failed: Invalid port");
249   }
250 
251   switch (service_type) {
252     case ServiceType::STUN:
253     case ServiceType::STUNS:
254       stun_servers->insert(rtc::SocketAddress(address, port));
255       break;
256     case ServiceType::TURN:
257     case ServiceType::TURNS: {
258       if (server.username.empty() || server.password.empty()) {
259         // The WebRTC spec requires throwing an InvalidAccessError when username
260         // or credential are ommitted; this is the native equivalent.
261         LOG_AND_RETURN_ERROR(
262             RTCErrorType::INVALID_PARAMETER,
263             "ICE server parsing failed: TURN server with empty "
264             "username or password");
265       }
266       // If the hostname field is not empty, then the server address must be
267       // the resolved IP for that host, the hostname is needed later for TLS
268       // handshake (SNI and Certificate verification).
269       absl::string_view hostname =
270           server.hostname.empty() ? address : server.hostname;
271       rtc::SocketAddress socket_address(hostname, port);
272       if (!server.hostname.empty()) {
273         rtc::IPAddress ip;
274         if (!IPFromString(address, &ip)) {
275           // When hostname is set, the server address must be a
276           // resolved ip address.
277           LOG_AND_RETURN_ERROR(
278               RTCErrorType::INVALID_PARAMETER,
279               "ICE server parsing failed: "
280               "IceServer has hostname field set, but URI does not "
281               "contain an IP address.");
282         }
283         socket_address.SetResolvedIP(ip);
284       }
285       cricket::RelayServerConfig config =
286           cricket::RelayServerConfig(socket_address, server.username,
287                                      server.password, turn_transport_type);
288       if (server.tls_cert_policy ==
289           PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
290         config.tls_cert_policy =
291             cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
292       }
293       config.tls_alpn_protocols = server.tls_alpn_protocols;
294       config.tls_elliptic_curves = server.tls_elliptic_curves;
295 
296       turn_servers->push_back(config);
297       break;
298     }
299     default:
300       // We shouldn't get to this point with an invalid service_type, we should
301       // have returned an error already.
302       LOG_AND_RETURN_ERROR(
303           RTCErrorType::INTERNAL_ERROR,
304           "ICE server parsing failed: Unexpected service type");
305   }
306   return RTCError::OK();
307 }
308 
309 }  // namespace
310 
ParseIceServersOrError(const PeerConnectionInterface::IceServers & servers,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)311 RTCError ParseIceServersOrError(
312     const PeerConnectionInterface::IceServers& servers,
313     cricket::ServerAddresses* stun_servers,
314     std::vector<cricket::RelayServerConfig>* turn_servers) {
315   for (const PeerConnectionInterface::IceServer& server : servers) {
316     if (!server.urls.empty()) {
317       for (const std::string& url : server.urls) {
318         if (url.empty()) {
319           LOG_AND_RETURN_ERROR(RTCErrorType::SYNTAX_ERROR,
320                                "ICE server parsing failed: Empty uri.");
321         }
322         RTCError err =
323             ParseIceServerUrl(server, url, stun_servers, turn_servers);
324         if (!err.ok()) {
325           return err;
326         }
327       }
328     } else if (!server.uri.empty()) {
329       // Fallback to old .uri if new .urls isn't present.
330       RTCError err =
331           ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
332 
333       if (!err.ok()) {
334         return err;
335       }
336     } else {
337       LOG_AND_RETURN_ERROR(RTCErrorType::SYNTAX_ERROR,
338                            "ICE server parsing failed: Empty uri.");
339     }
340   }
341   return RTCError::OK();
342 }
343 
ParseIceServers(const PeerConnectionInterface::IceServers & servers,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)344 RTCErrorType ParseIceServers(
345     const PeerConnectionInterface::IceServers& servers,
346     cricket::ServerAddresses* stun_servers,
347     std::vector<cricket::RelayServerConfig>* turn_servers) {
348   return ParseIceServersOrError(servers, stun_servers, turn_servers).type();
349 }
350 
351 }  // namespace webrtc
352