1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "socket_spec.h"
18
19 #include <limits>
20 #include <string>
21 #include <string_view>
22 #include <unordered_map>
23 #include <vector>
24
25 #include <android-base/parseint.h>
26 #include <android-base/parsenetaddress.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 #include <cutils/sockets.h>
30
31 #include "adb.h"
32 #include "adb_mdns.h"
33 #include "adb_utils.h"
34 #include "sysdeps.h"
35
36 using namespace std::string_literals;
37
38 using android::base::ConsumePrefix;
39 using android::base::StringPrintf;
40
41 #if defined(__linux__)
42 #define ADB_LINUX 1
43 #else
44 #define ADB_LINUX 0
45 #endif
46
47 #if defined(_WIN32)
48 #define ADB_WINDOWS 1
49 #else
50 #define ADB_WINDOWS 0
51 #endif
52
53 #if ADB_LINUX
54 #include <sys/socket.h>
55 #include "sysdeps/vm_sockets.h"
56 #endif
57
58 // Not static because it is used in commandline.c.
59 int gListenAll = 0;
60
61 struct LocalSocketType {
62 int socket_namespace;
63 bool available;
64 };
65
66 static auto& kLocalSocketTypes = *new std::unordered_map<std::string, LocalSocketType>({
67 #if ADB_HOST
68 { "local", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
69 #else
70 { "local", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_WINDOWS } },
71 #endif
72
73 { "localreserved", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_HOST } },
74 { "localabstract", { ANDROID_SOCKET_NAMESPACE_ABSTRACT, ADB_LINUX } },
75 { "localfilesystem", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
76 });
77
parse_tcp_socket_spec(std::string_view spec,std::string * hostname,int * port,std::string * serial,std::string * error)78 bool parse_tcp_socket_spec(std::string_view spec, std::string* hostname, int* port,
79 std::string* serial, std::string* error) {
80 if (!spec.starts_with("tcp:")) {
81 *error = "specification is not tcp: ";
82 *error += spec;
83 return false;
84 }
85
86 std::string hostname_value;
87 int port_value;
88
89 // If the spec is tcp:<port>, parse it ourselves.
90 // Otherwise, delegate to android::base::ParseNetAddress.
91 if (android::base::ParseInt(&spec[4], &port_value)) {
92 // Do the range checking ourselves, because ParseInt rejects 'tcp:65536' and 'tcp:foo:1234'
93 // identically.
94 if (port_value < 0 || port_value > 65535) {
95 *error = StringPrintf("bad port number '%d'", port_value);
96 return false;
97 }
98 } else {
99 std::string addr(spec.substr(4));
100 port_value = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
101
102 // FIXME: ParseNetAddress rejects port 0. This currently doesn't hurt, because listening
103 // on an address that isn't 'localhost' is unsupported.
104 if (!android::base::ParseNetAddress(addr, &hostname_value, &port_value, serial, error)) {
105 return false;
106 }
107 }
108
109 if (hostname) {
110 *hostname = std::move(hostname_value);
111 }
112
113 if (port) {
114 *port = port_value;
115 }
116
117 return true;
118 }
119
get_host_socket_spec_port(std::string_view spec,std::string * error)120 int get_host_socket_spec_port(std::string_view spec, std::string* error) {
121 int port;
122 if (spec.starts_with("tcp:")) {
123 if (!parse_tcp_socket_spec(spec, nullptr, &port, nullptr, error)) {
124 return -1;
125 }
126 } else if (spec.starts_with("vsock:")) {
127 #if ADB_LINUX
128 std::string spec_str(spec);
129 std::vector<std::string> fragments = android::base::Split(spec_str, ":");
130 if (fragments.size() != 2) {
131 *error = "given vsock server socket string was invalid";
132 return -1;
133 }
134 if (!android::base::ParseInt(fragments[1], &port)) {
135 *error = "could not parse vsock port";
136 errno = EINVAL;
137 return -1;
138 }
139 if (port < 0) {
140 *error = "vsock port was negative.";
141 errno = EINVAL;
142 return -1;
143 }
144 #else // ADB_LINUX
145 *error = "vsock is only supported on linux";
146 return -1;
147 #endif // ADB_LINUX
148 } else {
149 *error = "given socket spec string was invalid";
150 return -1;
151 }
152 return port;
153 }
154
tcp_host_is_local(std::string_view hostname)155 static bool tcp_host_is_local(std::string_view hostname) {
156 // FIXME
157 return hostname.empty() || hostname == "localhost";
158 }
159
is_socket_spec(std::string_view spec)160 bool is_socket_spec(std::string_view spec) {
161 for (const auto& it : kLocalSocketTypes) {
162 std::string prefix = it.first + ":";
163 if (spec.starts_with(prefix)) {
164 return true;
165 }
166 }
167 return spec.starts_with("tcp:") || spec.starts_with("acceptfd:") || spec.starts_with("vsock:");
168 }
169
is_local_socket_spec(std::string_view spec)170 bool is_local_socket_spec(std::string_view spec) {
171 for (const auto& it : kLocalSocketTypes) {
172 std::string prefix = it.first + ":";
173 if (spec.starts_with(prefix)) {
174 return true;
175 }
176 }
177
178 std::string error;
179 std::string hostname;
180 if (!parse_tcp_socket_spec(spec, &hostname, nullptr, nullptr, &error)) {
181 return false;
182 }
183 return tcp_host_is_local(hostname);
184 }
185
socket_spec_connect(unique_fd * fd,std::string_view address,int * port,std::string * serial,std::string * error)186 bool socket_spec_connect(unique_fd* fd, std::string_view address, int* port, std::string* serial,
187 std::string* error) {
188 if (address.starts_with("tcp:")) {
189 std::string hostname;
190 int port_value = port ? *port : 0;
191 if (!parse_tcp_socket_spec(address, &hostname, &port_value, serial, error)) {
192 return false;
193 }
194
195 if (tcp_host_is_local(hostname)) {
196 fd->reset(network_loopback_client(port_value, SOCK_STREAM, error));
197 } else {
198 #if ADB_HOST
199 // Check if the address is an mdns service we can connect to.
200 if (auto mdns_info = mdns_get_connect_service_info(std::string(address.substr(4)));
201 mdns_info != std::nullopt) {
202 fd->reset(network_connect(mdns_info->addr, mdns_info->port, SOCK_STREAM, 0, error));
203 if (fd->get() != -1) {
204 // TODO(joshuaduong): We still show the ip address for the serial. Change it to
205 // use the mdns instance name, so we can adjust to address changes on
206 // reconnects.
207 port_value = mdns_info->port;
208 if (serial) {
209 *serial = android::base::StringPrintf("%s.%s",
210 mdns_info->service_name.c_str(),
211 mdns_info->service_type.c_str());
212 }
213 }
214 } else {
215 fd->reset(network_connect(hostname, port_value, SOCK_STREAM, 0, error));
216 }
217 #else
218 // Disallow arbitrary connections in adbd.
219 *error = "adbd does not support arbitrary tcp connections";
220 return false;
221 #endif
222 }
223
224 if (fd->get() > 0) {
225 int keepalive_interval = 1;
226 if (const char* keepalive_env = getenv("ADB_TCP_KEEPALIVE_INTERVAL")) {
227 android::base::ParseInt(keepalive_env, &keepalive_interval, 0);
228 }
229
230 set_tcp_keepalive(fd->get(), keepalive_interval);
231 disable_tcp_nagle(fd->get());
232 if (port) {
233 *port = port_value;
234 }
235 return true;
236 }
237 return false;
238 } else if (address.starts_with("vsock:")) {
239 #if ADB_LINUX
240 std::string spec_str(address);
241 std::vector<std::string> fragments = android::base::Split(spec_str, ":");
242 unsigned int port_value = port ? *port : 0;
243 if (fragments.size() != 2 && fragments.size() != 3) {
244 *error = android::base::StringPrintf("expected vsock:cid or vsock:cid:port in '%s'",
245 spec_str.c_str());
246 errno = EINVAL;
247 return false;
248 }
249 unsigned int cid = 0;
250 if (!android::base::ParseUint(fragments[1], &cid)) {
251 *error = android::base::StringPrintf("could not parse vsock cid in '%s'",
252 spec_str.c_str());
253 errno = EINVAL;
254 return false;
255 }
256 if (fragments.size() == 3 && !android::base::ParseUint(fragments[2], &port_value)) {
257 *error = android::base::StringPrintf("could not parse vsock port in '%s'",
258 spec_str.c_str());
259 errno = EINVAL;
260 return false;
261 }
262 if (port_value == 0) {
263 *error = android::base::StringPrintf("vsock port was not provided.");
264 errno = EINVAL;
265 return false;
266 }
267 fd->reset(socket(AF_VSOCK, SOCK_STREAM, 0));
268 if (fd->get() == -1) {
269 *error = "could not open vsock socket";
270 return false;
271 }
272 sockaddr_vm addr{};
273 addr.svm_family = AF_VSOCK;
274 addr.svm_port = port_value;
275 addr.svm_cid = cid;
276 if (serial) {
277 *serial = android::base::StringPrintf("vsock:%u:%d", cid, port_value);
278 }
279 if (connect(fd->get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
280 int error_num = errno;
281 *error = android::base::StringPrintf("could not connect to vsock address '%s'",
282 spec_str.c_str());
283 errno = error_num;
284 return false;
285 }
286 if (port) {
287 *port = port_value;
288 }
289 return true;
290 #else // ADB_LINUX
291 *error = "vsock is only supported on Linux";
292 return false;
293 #endif // ADB_LINUX
294 } else if (address.starts_with("acceptfd:")) {
295 *error = "cannot connect to acceptfd";
296 return false;
297 }
298
299 for (const auto& it : kLocalSocketTypes) {
300 std::string prefix = it.first + ":";
301 if (address.starts_with(prefix)) {
302 if (!it.second.available) {
303 *error = StringPrintf("socket type %s is unavailable on this platform",
304 it.first.c_str());
305 return false;
306 }
307
308 fd->reset(network_local_client(&address[prefix.length()], it.second.socket_namespace,
309 SOCK_STREAM, error));
310
311 if (fd->get() < 0) {
312 *error =
313 android::base::StringPrintf("could not connect to %s address '%s'",
314 it.first.c_str(), std::string(address).c_str());
315 return false;
316 }
317
318 if (serial) {
319 *serial = address;
320 }
321 return true;
322 }
323 }
324
325 *error = "unknown socket specification: ";
326 *error += address;
327 return false;
328 }
329
socket_spec_listen(std::string_view spec,std::string * error,int * resolved_port)330 int socket_spec_listen(std::string_view spec, std::string* error, int* resolved_port) {
331 if (spec.starts_with("tcp:")) {
332 std::string hostname;
333 int port;
334 if (!parse_tcp_socket_spec(spec, &hostname, &port, nullptr, error)) {
335 return -1;
336 }
337
338 int result;
339 #if ADB_HOST
340 if (hostname.empty() && gListenAll) {
341 #else
342 if (hostname.empty()) {
343 #endif
344 result = network_inaddr_any_server(port, SOCK_STREAM, error);
345 } else if (tcp_host_is_local(hostname)) {
346 result = network_loopback_server(port, SOCK_STREAM, error, true);
347 } else if (hostname == "::1") {
348 result = network_loopback_server(port, SOCK_STREAM, error, false);
349 } else {
350 // TODO: Implement me.
351 *error = "listening on specified hostname currently unsupported";
352 return -1;
353 }
354
355 if (result >= 0 && resolved_port) {
356 *resolved_port = adb_socket_get_local_port(result);
357 }
358 return result;
359 } else if (spec.starts_with("vsock:")) {
360 #if ADB_LINUX
361 std::string spec_str(spec);
362 std::vector<std::string> fragments = android::base::Split(spec_str, ":");
363 if (fragments.size() != 2) {
364 *error = "given vsock server socket string was invalid";
365 return -1;
366 }
367 int port;
368 if (!android::base::ParseInt(fragments[1], &port)) {
369 *error = "could not parse vsock port";
370 errno = EINVAL;
371 return -1;
372 } else if (port < 0) {
373 *error = "vsock port was negative.";
374 errno = EINVAL;
375 return -1;
376 }
377 unique_fd serverfd(socket(AF_VSOCK, SOCK_STREAM, 0));
378 if (serverfd == -1) {
379 int error_num = errno;
380 *error = android::base::StringPrintf("could not create vsock server: '%s'",
381 strerror(error_num));
382 errno = error_num;
383 return -1;
384 }
385 sockaddr_vm addr{};
386 addr.svm_family = AF_VSOCK;
387 addr.svm_port = port == 0 ? VMADDR_PORT_ANY : port;
388 addr.svm_cid = VMADDR_CID_ANY;
389 socklen_t addr_len = sizeof(addr);
390 if (bind(serverfd.get(), reinterpret_cast<struct sockaddr*>(&addr), addr_len)) {
391 return -1;
392 }
393 if (listen(serverfd.get(), 4)) {
394 return -1;
395 }
396 if (serverfd >= 0 && resolved_port) {
397 if (getsockname(serverfd.get(), reinterpret_cast<sockaddr*>(&addr), &addr_len) == 0) {
398 *resolved_port = addr.svm_port;
399 } else {
400 return -1;
401 }
402 }
403 return serverfd.release();
404 #else // ADB_LINUX
405 *error = "vsock is only supported on linux";
406 return -1;
407 #endif // ADB_LINUX
408 } else if (ConsumePrefix(&spec, "acceptfd:")) {
409 #if ADB_WINDOWS
410 *error = "socket activation not supported under Windows";
411 return -1;
412 #else
413 // We inherited the socket from some kind of launcher. It's already bound and
414 // listening. Return a copy of the FD instead of the FD itself so we implement the
415 // normal "listen" contract and can succeed more than once.
416 unsigned int fd_u;
417 if (!ParseUint(&fd_u, spec) || fd_u > std::numeric_limits<int>::max()) {
418 *error = "invalid fd";
419 return -1;
420 }
421 int fd = static_cast<int>(fd_u);
422 int flags = get_fd_flags(fd);
423 if (flags < 0) {
424 *error = android::base::StringPrintf("could not get flags of inherited fd %d: '%s'", fd,
425 strerror(errno));
426 return -1;
427 }
428 if (flags & FD_CLOEXEC) {
429 *error = android::base::StringPrintf("fd %d was not inherited from parent", fd);
430 return -1;
431 }
432
433 int dummy_sock_type;
434 socklen_t dummy_sock_type_size = sizeof(dummy_sock_type);
435 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &dummy_sock_type, &dummy_sock_type_size)) {
436 *error = android::base::StringPrintf("fd %d does not refer to a socket", fd);
437 return -1;
438 }
439
440 int new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
441 if (new_fd < 0) {
442 *error = android::base::StringPrintf("could not dup inherited fd %d: '%s'", fd,
443 strerror(errno));
444 return -1;
445 }
446 return new_fd;
447 #endif
448 }
449
450 for (const auto& it : kLocalSocketTypes) {
451 std::string prefix = it.first + ":";
452 if (spec.starts_with(prefix)) {
453 if (!it.second.available) {
454 *error = "attempted to listen on unavailable socket type: ";
455 *error += spec;
456 return -1;
457 }
458
459 return network_local_server(&spec[prefix.length()], it.second.socket_namespace,
460 SOCK_STREAM, error);
461 }
462 }
463
464 *error = "unknown socket specification:";
465 *error += spec;
466 return -1;
467 }
468