1 /*
2 * Copyright (C) 2007 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 #define TRACE_TAG ADB
18
19 #include "sysdeps.h"
20
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <inttypes.h>
25 #include <limits.h>
26 #include <stdarg.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <iostream>
34
35 #include <memory>
36 #include <string>
37 #include <thread>
38 #include <vector>
39
40 #include <android-base/file.h>
41 #include <android-base/logging.h>
42 #include <android-base/parseint.h>
43 #include <android-base/stringprintf.h>
44 #include <android-base/strings.h>
45
46 #if !defined(_WIN32)
47 #include <sys/ioctl.h>
48 #include <termios.h>
49 #include <unistd.h>
50 #else
51 #define _POSIX
52 #include <signal.h>
53 #endif
54
55 #include <google/protobuf/text_format.h>
56
57 #include "adb.h"
58 #include "adb_auth.h"
59 #include "adb_client.h"
60 #include "adb_install.h"
61 #include "adb_io.h"
62 #include "adb_unique_fd.h"
63 #include "adb_utils.h"
64 #include "app_processes.pb.h"
65 #include "bugreport.h"
66 #include "client/file_sync_client.h"
67 #include "commandline.h"
68 #include "fastdeploy.h"
69 #include "incremental_server.h"
70 #include "services.h"
71 #include "shell_protocol.h"
72 #include "sysdeps/chrono.h"
73
74 extern int gListenAll;
75
76 DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
77
product_file(const std::string & file)78 static std::string product_file(const std::string& file) {
79 const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
80 if (ANDROID_PRODUCT_OUT == nullptr) {
81 error_exit("product directory not specified; set $ANDROID_PRODUCT_OUT");
82 }
83 return std::string{ANDROID_PRODUCT_OUT} + OS_PATH_SEPARATOR_STR + file;
84 }
85
help()86 static void help() {
87 fprintf(stdout, "%s\n", adb_version().c_str());
88 // clang-format off
89 fprintf(stdout,
90 "global options:\n"
91 " -a listen on all network interfaces, not just localhost\n"
92 " -d use USB device (error if multiple devices connected)\n"
93 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
94 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
95 " -t ID use device with given transport id\n"
96 " -H name of adb server host [default=localhost]\n"
97 " -P port of adb server [default=5037]\n"
98 " -L SOCKET listen on given socket for adb server"
99 " [default=tcp:localhost:5037]\n"
100 " --one-device SERIAL|USB only allowed with 'start-server' or 'server nodaemon', server"
101 " will only connect to one USB device, specified by a serial number or USB device"
102 " address.\n"
103 " --exit-on-write-error exit if stdout is closed\n"
104 "\n"
105 "general commands:\n"
106 " devices [-l] list connected devices (-l for long output)\n"
107 " help show this help message\n"
108 " version show version num\n"
109 "\n"
110 "networking:\n"
111 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
112 " disconnect [HOST[:PORT]]\n"
113 " disconnect from given TCP/IP device [default port=5555], or all\n"
114 " pair HOST[:PORT] [PAIRING CODE]\n"
115 " pair with a device for secure TCP/IP communication\n"
116 " forward --list list all forward socket connections\n"
117 " forward [--no-rebind] LOCAL REMOTE\n"
118 " forward socket connection using:\n"
119 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
120 " localabstract:<unix domain socket name>\n"
121 " localreserved:<unix domain socket name>\n"
122 " localfilesystem:<unix domain socket name>\n"
123 " jdwp:<process pid> (remote only)\n"
124 " vsock:<CID>:<port> (remote only)\n"
125 " acceptfd:<fd> (listen only)\n"
126 " forward --remove LOCAL remove specific forward socket connection\n"
127 " forward --remove-all remove all forward socket connections\n"
128 " ppp TTY [PARAMETER...] run PPP over USB\n"
129 " reverse --list list all reverse socket connections from device\n"
130 " reverse [--no-rebind] REMOTE LOCAL\n"
131 " reverse socket connection using:\n"
132 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
133 " localabstract:<unix domain socket name>\n"
134 " localreserved:<unix domain socket name>\n"
135 " localfilesystem:<unix domain socket name>\n"
136 " reverse --remove REMOTE remove specific reverse socket connection\n"
137 " reverse --remove-all remove all reverse socket connections from device\n"
138 " mdns check check if mdns discovery is available\n"
139 " mdns services list all discovered services\n"
140 "\n"
141 "file transfer:\n"
142 " push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE\n"
143 " copy local files/directories to device\n"
144 " --sync: only push files that are newer on the host than the device\n"
145 " -n: dry run: push files to device without storing to the filesystem\n"
146 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
147 " -Z: disable compression\n"
148 " pull [-a] [-z ALGORITHM] [-Z] REMOTE... LOCAL\n"
149 " copy files/dirs from device\n"
150 " -a: preserve file timestamp and mode\n"
151 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
152 " -Z: disable compression\n"
153 " sync [-l] [-z ALGORITHM] [-Z] [all|data|odm|oem|product|system|system_ext|vendor]\n"
154 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
155 " -n: dry run: push files to device without storing to the filesystem\n"
156 " -l: list files that would be copied, but don't copy them\n"
157 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
158 " -Z: disable compression\n"
159 "\n"
160 "shell:\n"
161 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
162 " run remote shell command (interactive shell if no command given)\n"
163 " -e: choose escape character, or \"none\"; default '~'\n"
164 " -n: don't read from stdin\n"
165 " -T: disable pty allocation\n"
166 " -t: allocate a pty if on a tty (-tt: force pty allocation)\n"
167 " -x: disable remote exit codes and stdout/stderr separation\n"
168 " emu COMMAND run emulator console command\n"
169 "\n"
170 "app installation (see also `adb shell cmd package help`):\n"
171 " install [-lrtsdg] [--instant] PACKAGE\n"
172 " push a single package to the device and install it\n"
173 " install-multiple [-lrtsdpg] [--instant] PACKAGE...\n"
174 " push multiple APKs to the device for a single package and install them\n"
175 " install-multi-package [-lrtsdpg] [--instant] PACKAGE...\n"
176 " push one or more packages to the device and install them atomically\n"
177 " -r: replace existing application\n"
178 " -t: allow test packages\n"
179 " -d: allow version code downgrade (debuggable packages only)\n"
180 " -p: partial application install (install-multiple only)\n"
181 " -g: grant all runtime permissions\n"
182 " --abi ABI: override platform's default ABI\n"
183 " --instant: cause the app to be installed as an ephemeral install app\n"
184 " --no-streaming: always push APK to device and invoke Package Manager as separate steps\n"
185 " --streaming: force streaming APK directly into Package Manager\n"
186 " --fastdeploy: use fast deploy\n"
187 " --no-fastdeploy: prevent use of fast deploy\n"
188 " --force-agent: force update of deployment agent when using fast deploy\n"
189 " --date-check-agent: update deployment agent when local version is newer and using fast deploy\n"
190 " --version-check-agent: update deployment agent when local version has different version code and using fast deploy\n"
191 #ifndef _WIN32
192 " --local-agent: locate agent files from local source build (instead of SDK location)\n"
193 #endif
194 " (See also `adb shell pm help` for more options.)\n"
195 //TODO--installlog <filename>
196 " uninstall [-k] PACKAGE\n"
197 " remove this app package from the device\n"
198 " '-k': keep the data and cache directories\n"
199 "\n"
200 "debugging:\n"
201 " bugreport [PATH]\n"
202 " write bugreport to given PATH [default=bugreport.zip];\n"
203 " if PATH is a directory, the bug report is saved in that directory.\n"
204 " devices that don't support zipped bug reports output to stdout.\n"
205 " jdwp list pids of processes hosting a JDWP transport\n"
206 " logcat show device log (logcat --help for more)\n"
207 "\n"
208 "security:\n"
209 " disable-verity disable dm-verity checking on userdebug builds\n"
210 " enable-verity re-enable dm-verity checking on userdebug builds\n"
211 " keygen FILE\n"
212 " generate adb public/private key; private key stored in FILE,\n"
213 "\n"
214 "scripting:\n"
215 " wait-for[-TRANSPORT]-STATE...\n"
216 " wait for device to be in a given state\n"
217 " STATE: device, recovery, rescue, sideload, bootloader, or disconnect\n"
218 " TRANSPORT: usb, local, or any [default=any]\n"
219 " get-state print offline | bootloader | device\n"
220 " get-serialno print <serial-number>\n"
221 " get-devpath print <device-path>\n"
222 " remount [-R]\n"
223 " remount partitions read-write. if a reboot is required, -R will\n"
224 " will automatically reboot the device.\n"
225 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
226 " reboot the device; defaults to booting system image but\n"
227 " supports bootloader and recovery too. sideload reboots\n"
228 " into recovery and automatically starts sideload mode,\n"
229 " sideload-auto-reboot is the same but reboots after sideloading.\n"
230 " sideload OTAPACKAGE sideload the given full OTA package\n"
231 " root restart adbd with root permissions\n"
232 " unroot restart adbd without root permissions\n"
233 " usb restart adbd listening on USB\n"
234 " tcpip PORT restart adbd listening on TCP on PORT\n"
235 "\n"
236 "internal debugging:\n"
237 " start-server ensure that there is a server running\n"
238 " kill-server kill the server if it is running\n"
239 " reconnect kick connection from host side to force reconnect\n"
240 " reconnect device kick connection from device side to force reconnect\n"
241 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
242 "\n"
243 "usb:\n"
244 " attach attach a detached USB device\n"
245 " detach detach from a USB device to allow use by other processes\n"
246 ""
247 "environment variables:\n"
248 " $ADB_TRACE\n"
249 " comma-separated list of debug info to log:\n"
250 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
251 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
252 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
253 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n"
254 " $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus)\n"
255 " $ADB_MDNS_AUTO_CONNECT comma-separated list of mdns services to allow auto-connect (default adb-tls-connect)\n"
256 );
257 // clang-format on
258 }
259
260 #if defined(_WIN32)
261
262 // Implemented in sysdeps_win32.cpp.
263 void stdin_raw_init();
264 void stdin_raw_restore();
265
266 #else
267 static termios g_saved_terminal_state;
268
stdin_raw_init()269 static void stdin_raw_init() {
270 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
271
272 termios tio;
273 if (tcgetattr(STDIN_FILENO, &tio)) return;
274
275 cfmakeraw(&tio);
276
277 // No timeout but request at least one character per read.
278 tio.c_cc[VTIME] = 0;
279 tio.c_cc[VMIN] = 1;
280
281 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
282 }
283
stdin_raw_restore()284 static void stdin_raw_restore() {
285 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
286 }
287 #endif
288
read_and_dump_protocol(borrowed_fd fd,StandardStreamsCallbackInterface * callback)289 int read_and_dump_protocol(borrowed_fd fd, StandardStreamsCallbackInterface* callback) {
290 int exit_code = 0;
291 std::unique_ptr<ShellProtocol> protocol = std::make_unique<ShellProtocol>(fd);
292 if (!protocol) {
293 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
294 return 1;
295 }
296 while (protocol->Read()) {
297 if (protocol->id() == ShellProtocol::kIdStdout) {
298 if (!callback->OnStdout(protocol->data(), protocol->data_length())) {
299 exit_code = SIGPIPE + 128;
300 break;
301 }
302 } else if (protocol->id() == ShellProtocol::kIdStderr) {
303 if (!callback->OnStderr(protocol->data(), protocol->data_length())) {
304 exit_code = SIGPIPE + 128;
305 break;
306 }
307 } else if (protocol->id() == ShellProtocol::kIdExit) {
308 // data() returns a char* which doesn't have defined signedness.
309 // Cast to uint8_t to prevent 255 from being sign extended to INT_MIN,
310 // which doesn't get truncated on Windows.
311 exit_code = static_cast<uint8_t>(protocol->data()[0]);
312 }
313 }
314 return exit_code;
315 }
316
read_and_dump(borrowed_fd fd,bool use_shell_protocol,StandardStreamsCallbackInterface * callback)317 int read_and_dump(borrowed_fd fd, bool use_shell_protocol,
318 StandardStreamsCallbackInterface* callback) {
319 int exit_code = 0;
320 if (fd < 0) return exit_code;
321
322 if (use_shell_protocol) {
323 exit_code = read_and_dump_protocol(fd, callback);
324 } else {
325 char raw_buffer[BUFSIZ];
326 char* buffer_ptr = raw_buffer;
327 while (true) {
328 D("read_and_dump(): pre adb_read(fd=%d)", fd.get());
329 int length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
330 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd.get(), length);
331 if (length <= 0) {
332 break;
333 }
334 if (!callback->OnStdout(buffer_ptr, length)) {
335 break;
336 }
337 }
338 }
339
340 return callback->Done(exit_code);
341 }
342
stdinout_raw_prologue(int inFd,int outFd,int & old_stdin_mode,int & old_stdout_mode)343 static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
344 if (inFd == STDIN_FILENO) {
345 stdin_raw_init();
346 #ifdef _WIN32
347 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
348 if (old_stdin_mode == -1) {
349 PLOG(FATAL) << "could not set stdin to binary";
350 }
351 #endif
352 }
353
354 #ifdef _WIN32
355 if (outFd == STDOUT_FILENO) {
356 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
357 if (old_stdout_mode == -1) {
358 PLOG(FATAL) << "could not set stdout to binary";
359 }
360 }
361 #endif
362 }
363
stdinout_raw_epilogue(int inFd,int outFd,int old_stdin_mode,int old_stdout_mode)364 static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
365 if (inFd == STDIN_FILENO) {
366 stdin_raw_restore();
367 #ifdef _WIN32
368 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
369 PLOG(FATAL) << "could not restore stdin mode";
370 }
371 #endif
372 }
373
374 #ifdef _WIN32
375 if (outFd == STDOUT_FILENO) {
376 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
377 PLOG(FATAL) << "could not restore stdout mode";
378 }
379 }
380 #endif
381 }
382
copy_to_file(int inFd,int outFd)383 bool copy_to_file(int inFd, int outFd) {
384 bool result = true;
385 std::vector<char> buf(64 * 1024);
386 int len;
387 long total = 0;
388 int old_stdin_mode = -1;
389 int old_stdout_mode = -1;
390
391 D("copy_to_file(%d -> %d)", inFd, outFd);
392
393 stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
394
395 while (true) {
396 if (inFd == STDIN_FILENO) {
397 len = unix_read(inFd, buf.data(), buf.size());
398 } else {
399 len = adb_read(inFd, buf.data(), buf.size());
400 }
401 if (len == 0) {
402 D("copy_to_file() : read 0 bytes; exiting");
403 break;
404 }
405 if (len < 0) {
406 D("copy_to_file(): read failed: %s", strerror(errno));
407 result = false;
408 break;
409 }
410 if (outFd == STDOUT_FILENO) {
411 fwrite(buf.data(), 1, len, stdout);
412 fflush(stdout);
413 } else {
414 adb_write(outFd, buf.data(), len);
415 }
416 total += len;
417 }
418
419 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
420
421 D("copy_to_file() finished with %s after %lu bytes", result ? "success" : "failure", total);
422 return result;
423 }
424
send_window_size_change(int fd,std::unique_ptr<ShellProtocol> & shell)425 static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
426 // Old devices can't handle window size changes.
427 if (shell == nullptr) return;
428
429 #if defined(_WIN32)
430 struct winsize {
431 unsigned short ws_row;
432 unsigned short ws_col;
433 unsigned short ws_xpixel;
434 unsigned short ws_ypixel;
435 };
436 #endif
437
438 winsize ws;
439
440 #if defined(_WIN32)
441 // If stdout is redirected to a non-console, we won't be able to get the
442 // console size, but that makes sense.
443 const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
444 if (intptr_handle == -1) return;
445
446 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
447
448 CONSOLE_SCREEN_BUFFER_INFO info;
449 memset(&info, 0, sizeof(info));
450 if (!GetConsoleScreenBufferInfo(handle, &info)) return;
451
452 memset(&ws, 0, sizeof(ws));
453 // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
454 ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
455 // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
456 // than the window, in which case we should use the width of the buffer.
457 ws.ws_col = info.dwSize.X;
458 #else
459 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
460 #endif
461
462 // Send the new window size as human-readable ASCII for debugging convenience.
463 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
464 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
465 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
466 }
467
468 // Used to pass multiple values to the stdin read thread.
469 struct StdinReadArgs {
470 int stdin_fd, write_fd;
471 bool raw_stdin;
472 std::unique_ptr<ShellProtocol> protocol;
473 char escape_char;
474 };
475
476 // Loops to read from stdin and push the data to the given FD.
477 // The argument should be a pointer to a StdinReadArgs object. This function
478 // will take ownership of the object and delete it when finished.
stdin_read_thread_loop(void * x)479 static void stdin_read_thread_loop(void* x) {
480 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
481
482 #if !defined(_WIN32)
483 // Mask SIGTTIN in case we're in a backgrounded process.
484 sigset_t sigset;
485 sigemptyset(&sigset);
486 sigaddset(&sigset, SIGTTIN);
487 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
488 #endif
489
490 #if defined(_WIN32)
491 // _get_interesting_input_record_uncached() causes unix_read_interruptible()
492 // to return -1 with errno == EINTR if the window size changes.
493 #else
494 // Unblock SIGWINCH for this thread, so our read(2) below will be
495 // interrupted if the window size changes.
496 sigset_t mask;
497 sigemptyset(&mask);
498 sigaddset(&mask, SIGWINCH);
499 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
500 #endif
501
502 // Set up the initial window size.
503 send_window_size_change(args->stdin_fd, args->protocol);
504
505 char raw_buffer[BUFSIZ];
506 char* buffer_ptr = raw_buffer;
507 size_t buffer_size = sizeof(raw_buffer);
508 if (args->protocol != nullptr) {
509 buffer_ptr = args->protocol->data();
510 buffer_size = args->protocol->data_capacity();
511 }
512
513 // If we need to parse escape sequences, make life easy.
514 if (args->raw_stdin && args->escape_char != '\0') {
515 buffer_size = 1;
516 }
517
518 enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
519 EscapeState state = kStartOfLine;
520
521 while (true) {
522 // Use unix_read_interruptible() rather than adb_read() for stdin.
523 D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
524 int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
525 buffer_size);
526 if (r == -1 && errno == EINTR) {
527 send_window_size_change(args->stdin_fd, args->protocol);
528 continue;
529 }
530 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
531 if (r <= 0) {
532 // Only devices using the shell protocol know to close subprocess
533 // stdin. For older devices we want to just leave the connection
534 // open, otherwise an unpredictable amount of return data could
535 // be lost due to the FD closing before all data has been received.
536 if (args->protocol) {
537 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
538 }
539 break;
540 }
541 // If we made stdin raw, check input for escape sequences. In
542 // this situation signals like Ctrl+C are sent remotely rather than
543 // interpreted locally so this provides an emergency out if the remote
544 // process starts ignoring the signal. SSH also does this, see the
545 // "escape characters" section on the ssh man page for more info.
546 if (args->raw_stdin && args->escape_char != '\0') {
547 char ch = buffer_ptr[0];
548 if (ch == args->escape_char) {
549 if (state == kStartOfLine) {
550 state = kInEscape;
551 // Swallow the escape character.
552 continue;
553 } else {
554 state = kMidFlow;
555 }
556 } else {
557 if (state == kInEscape) {
558 if (ch == '.') {
559 fprintf(stderr,"\r\n[ disconnected ]\r\n");
560 stdin_raw_restore();
561 exit(0);
562 } else {
563 // We swallowed an escape character that wasn't part of
564 // a valid escape sequence; time to cough it up.
565 buffer_ptr[0] = args->escape_char;
566 buffer_ptr[1] = ch;
567 ++r;
568 }
569 }
570 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
571 }
572 }
573 if (args->protocol) {
574 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
575 break;
576 }
577 } else {
578 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
579 break;
580 }
581 }
582 }
583 }
584
585 // Returns a shell service string with the indicated arguments and command.
ShellServiceString(bool use_shell_protocol,const std::string & type_arg,const std::string & command)586 static std::string ShellServiceString(bool use_shell_protocol,
587 const std::string& type_arg,
588 const std::string& command) {
589 std::vector<std::string> args;
590 if (use_shell_protocol) {
591 args.push_back(kShellServiceArgShellProtocol);
592
593 const char* terminal_type = getenv("TERM");
594 if (terminal_type != nullptr) {
595 args.push_back(std::string("TERM=") + terminal_type);
596 }
597 }
598 if (!type_arg.empty()) {
599 args.push_back(type_arg);
600 }
601
602 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
603 return android::base::StringPrintf("shell%s%s:%s",
604 args.empty() ? "" : ",",
605 android::base::Join(args, ',').c_str(),
606 command.c_str());
607 }
608
609 // Connects to a shell on the device and read/writes data.
610 //
611 // Note: currently this function doesn't properly clean up resources; the
612 // FD connected to the adb server is never closed and the stdin read thread
613 // may never exit.
614 //
615 // On success returns the remote exit code if |use_shell_protocol| is true,
616 // 0 otherwise. On failure returns 1.
RemoteShell(bool use_shell_protocol,const std::string & type_arg,char escape_char,bool empty_command,const std::string & service_string)617 static int RemoteShell(bool use_shell_protocol, const std::string& type_arg, char escape_char,
618 bool empty_command, const std::string& service_string) {
619 // Old devices can't handle a service string that's longer than MAX_PAYLOAD_V1.
620 // Use |use_shell_protocol| to determine whether to allow a command longer than that.
621 if (service_string.size() > MAX_PAYLOAD_V1 && !use_shell_protocol) {
622 fprintf(stderr, "error: shell command too long\n");
623 return 1;
624 }
625
626 // Make local stdin raw if the device allocates a PTY, which happens if:
627 // 1. We are explicitly asking for a PTY shell, or
628 // 2. We don't specify shell type and are starting an interactive session.
629 bool raw_stdin = (type_arg == kShellServiceArgPty || (type_arg.empty() && empty_command));
630
631 std::string error;
632 int fd = adb_connect(service_string, &error);
633 if (fd < 0) {
634 fprintf(stderr,"error: %s\n", error.c_str());
635 return 1;
636 }
637
638 StdinReadArgs* args = new StdinReadArgs;
639 if (!args) {
640 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
641 return 1;
642 }
643 args->stdin_fd = STDIN_FILENO;
644 args->write_fd = fd;
645 args->raw_stdin = raw_stdin;
646 args->escape_char = escape_char;
647 if (use_shell_protocol) {
648 args->protocol = std::make_unique<ShellProtocol>(args->write_fd);
649 }
650
651 if (raw_stdin) stdin_raw_init();
652
653 #if !defined(_WIN32)
654 // Ensure our process is notified if the local window size changes.
655 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
656 // because the whole reason we're sending signals is to unblock the read(2)!
657 // That also means we don't need to do anything in the signal handler:
658 // the side effect of delivering the signal is all we need.
659 struct sigaction sa;
660 memset(&sa, 0, sizeof(sa));
661 sa.sa_handler = [](int) {};
662 sa.sa_flags = 0;
663 sigaction(SIGWINCH, &sa, nullptr);
664
665 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
666 // from it. The stdin read thread will unblock this signal to ensure that it's
667 // the thread that receives the signal.
668 sigset_t mask;
669 sigemptyset(&mask);
670 sigaddset(&mask, SIGWINCH);
671 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
672 #endif
673
674 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
675 std::thread(stdin_read_thread_loop, args).detach();
676 int exit_code = read_and_dump(fd, use_shell_protocol);
677
678 // TODO: properly exit stdin_read_thread_loop and close |fd|.
679
680 // TODO: we should probably install signal handlers for this.
681 // TODO: can we use atexit? even on Windows?
682 if (raw_stdin) stdin_raw_restore();
683
684 return exit_code;
685 }
686
adb_shell(int argc,const char ** argv)687 static int adb_shell(int argc, const char** argv) {
688 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
689
690 // Defaults.
691 char escape_char = '~'; // -e
692 auto&& features = adb_get_feature_set_or_die();
693 bool use_shell_protocol = CanUseFeature(*features, kFeatureShell2); // -x
694 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
695
696 // Parse shell-specific command-line options.
697 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
698 #ifdef _WIN32
699 // fixes "adb shell -l" crash on Windows, b/37284906
700 __argv = const_cast<char**>(argv);
701 #endif
702 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
703 int opt;
704 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
705 switch (opt) {
706 case 'e':
707 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
708 error_exit("-e requires a single-character argument or 'none'");
709 }
710 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
711 break;
712 case 'n':
713 close_stdin();
714 break;
715 case 'x':
716 // This option basically asks for historical behavior, so set options that
717 // correspond to the historical defaults. This is slightly weird in that -Tx
718 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
719 // be our least worst choice...
720 use_shell_protocol = false;
721 tty = kPtyDefinitely;
722 escape_char = '~';
723 break;
724 case 't':
725 // Like ssh, -t arguments are cumulative so that multiple -t's
726 // are needed to force a PTY.
727 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
728 break;
729 case 'T':
730 tty = kPtyNo;
731 break;
732 default:
733 // getopt(3) already printed an error message for us.
734 return 1;
735 }
736 }
737
738 bool is_interactive = (optind == argc);
739
740 std::string shell_type_arg = kShellServiceArgPty;
741 if (tty == kPtyNo) {
742 shell_type_arg = kShellServiceArgRaw;
743 } else if (tty == kPtyAuto) {
744 // If stdin isn't a TTY, default to a raw shell; this lets
745 // things like `adb shell < my_script.sh` work as expected.
746 // Non-interactive shells should also not have a pty.
747 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
748 shell_type_arg = kShellServiceArgRaw;
749 }
750 } else if (tty == kPtyYes) {
751 // A single -t arg isn't enough to override implicit -T.
752 if (!unix_isatty(STDIN_FILENO)) {
753 fprintf(stderr,
754 "Remote PTY will not be allocated because stdin is not a terminal.\n"
755 "Use multiple -t options to force remote PTY allocation.\n");
756 shell_type_arg = kShellServiceArgRaw;
757 }
758 }
759
760 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
761 escape_char, tty,
762 use_shell_protocol ? "true" : "false",
763 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
764
765 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
766 if (!use_shell_protocol) {
767 if (shell_type_arg != kShellServiceArgPty) {
768 fprintf(stderr, "error: %s only supports allocating a pty\n",
769 !CanUseFeature(*features, kFeatureShell2) ? "device" : "-x");
770 return 1;
771 } else {
772 // If we're not using the shell protocol, the type argument must be empty.
773 shell_type_arg = "";
774 }
775 }
776
777 std::string command;
778 if (optind < argc) {
779 // We don't escape here, just like ssh(1). http://b/20564385.
780 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
781 }
782
783 std::string service_string = ShellServiceString(use_shell_protocol, shell_type_arg, command);
784 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command.empty(),
785 service_string);
786 }
787
adb_abb(int argc,const char ** argv)788 static int adb_abb(int argc, const char** argv) {
789 auto&& features = adb_get_feature_set_or_die();
790 if (!CanUseFeature(*features, kFeatureAbb)) {
791 error_exit("abb is not supported by the device");
792 }
793
794 optind = 1; // argv[0] is always "abb", so set `optind` appropriately.
795
796 // Defaults.
797 constexpr char escape_char = '~'; // -e
798 constexpr bool use_shell_protocol = true;
799 constexpr auto shell_type_arg = kShellServiceArgRaw;
800 constexpr bool empty_command = false;
801
802 std::vector<const char*> args(argv + optind, argv + argc);
803 std::string service_string = "abb:" + android::base::Join(args, ABB_ARG_DELIMETER);
804
805 D("abb -e 0x%x [%*.s]\n", escape_char, static_cast<int>(service_string.size()),
806 service_string.data());
807
808 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, empty_command,
809 service_string);
810 }
811
adb_shell_noinput(int argc,const char ** argv)812 static int adb_shell_noinput(int argc, const char** argv) {
813 #if !defined(_WIN32)
814 unique_fd fd(adb_open("/dev/null", O_RDONLY));
815 CHECK_NE(STDIN_FILENO, fd.get());
816 dup2(fd.get(), STDIN_FILENO);
817 #endif
818 return adb_shell(argc, argv);
819 }
820
adb_sideload_legacy(const char * filename,int in_fd,int size)821 static int adb_sideload_legacy(const char* filename, int in_fd, int size) {
822 std::string error;
823 unique_fd out_fd(adb_connect(android::base::StringPrintf("sideload:%d", size), &error));
824 if (out_fd < 0) {
825 fprintf(stderr, "adb: pre-KitKat sideload connection failed: %s\n", error.c_str());
826 return -1;
827 }
828
829 int opt = CHUNK_SIZE;
830 opt = adb_setsockopt(out_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
831
832 char buf[CHUNK_SIZE];
833 int total = size;
834 while (size > 0) {
835 unsigned xfer = (size > CHUNK_SIZE) ? CHUNK_SIZE : size;
836 if (!ReadFdExactly(in_fd, buf, xfer)) {
837 fprintf(stderr, "adb: failed to read data from %s: %s\n", filename, strerror(errno));
838 return -1;
839 }
840 if (!WriteFdExactly(out_fd, buf, xfer)) {
841 std::string error;
842 adb_status(out_fd, &error);
843 fprintf(stderr, "adb: failed to write data: %s\n", error.c_str());
844 return -1;
845 }
846 size -= xfer;
847 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * size) / (total))));
848 fflush(stdout);
849 }
850 printf("\n");
851
852 if (!adb_status(out_fd, &error)) {
853 fprintf(stderr, "adb: error response: %s\n", error.c_str());
854 return -1;
855 }
856
857 return 0;
858 }
859
860 #define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
861
862 // Connects to the sideload / rescue service on the device (served by minadbd) and sends over the
863 // data in an OTA package.
864 //
865 // It uses a simple protocol as follows.
866 //
867 // - The connect message includes the total number of bytes in the file and a block size chosen by
868 // us.
869 //
870 // - The other side sends the desired block number as eight decimal digits (e.g. "00000023" for
871 // block 23). Blocks are numbered from zero.
872 //
873 // - We send back the data of the requested block. The last block is likely to be partial; when the
874 // last block is requested we only send the part of the block that exists, it's not padded up to
875 // the block size.
876 //
877 // - When the other side sends "DONEDONE" or "FAILFAIL" instead of a block number, we have done all
878 // the data transfer.
879 //
adb_sideload_install(const char * filename,bool rescue_mode)880 static int adb_sideload_install(const char* filename, bool rescue_mode) {
881 // TODO: use a LinePrinter instead...
882 struct stat sb;
883 if (stat(filename, &sb) == -1) {
884 fprintf(stderr, "adb: failed to stat file %s: %s\n", filename, strerror(errno));
885 return -1;
886 }
887 unique_fd package_fd(adb_open(filename, O_RDONLY));
888 if (package_fd == -1) {
889 fprintf(stderr, "adb: failed to open file %s: %s\n", filename, strerror(errno));
890 return -1;
891 }
892
893 std::string service = android::base::StringPrintf(
894 "%s:%" PRId64 ":%d", rescue_mode ? "rescue-install" : "sideload-host",
895 static_cast<int64_t>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
896 std::string error;
897 unique_fd device_fd(adb_connect(service, &error));
898 if (device_fd < 0) {
899 fprintf(stderr, "adb: sideload connection failed: %s\n", error.c_str());
900
901 if (rescue_mode) {
902 return -1;
903 }
904
905 // If this is a small enough package, maybe this is an older device that doesn't
906 // support sideload-host. Try falling back to the older (<= K) sideload method.
907 if (sb.st_size > INT_MAX) {
908 return -1;
909 }
910 fprintf(stderr, "adb: trying pre-KitKat sideload method...\n");
911 return adb_sideload_legacy(filename, package_fd.get(), static_cast<int>(sb.st_size));
912 }
913
914 int opt = SIDELOAD_HOST_BLOCK_SIZE;
915 adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
916
917 char buf[SIDELOAD_HOST_BLOCK_SIZE];
918
919 int64_t xfer = 0;
920 int last_percent = -1;
921 while (true) {
922 if (!ReadFdExactly(device_fd, buf, 8)) {
923 fprintf(stderr, "adb: failed to read command: %s\n", strerror(errno));
924 return -1;
925 }
926 buf[8] = '\0';
927
928 if (strcmp(kMinadbdServicesExitSuccess, buf) == 0 ||
929 strcmp(kMinadbdServicesExitFailure, buf) == 0) {
930 printf("\rTotal xfer: %.2fx%*s\n",
931 static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
932 static_cast<int>(strlen(filename) + 10), "");
933 if (strcmp(kMinadbdServicesExitFailure, buf) == 0) {
934 return 1;
935 }
936 return 0;
937 }
938
939 int64_t block = strtoll(buf, nullptr, 10);
940 int64_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
941 if (offset >= static_cast<int64_t>(sb.st_size)) {
942 fprintf(stderr,
943 "adb: failed to read block %" PRId64 " at offset %" PRId64 ", past end %" PRId64
944 "\n",
945 block, offset, static_cast<int64_t>(sb.st_size));
946 return -1;
947 }
948
949 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
950 if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<int64_t>(sb.st_size)) {
951 to_write = sb.st_size - offset;
952 }
953
954 if (adb_lseek(package_fd, offset, SEEK_SET) != offset) {
955 fprintf(stderr, "adb: failed to seek to package block: %s\n", strerror(errno));
956 return -1;
957 }
958 if (!ReadFdExactly(package_fd, buf, to_write)) {
959 fprintf(stderr, "adb: failed to read package block: %s\n", strerror(errno));
960 return -1;
961 }
962
963 if (!WriteFdExactly(device_fd, buf, to_write)) {
964 adb_status(device_fd, &error);
965 fprintf(stderr, "adb: failed to write data '%s' *\n", error.c_str());
966 return -1;
967 }
968 xfer += to_write;
969
970 // For normal OTA packages, we expect to transfer every byte
971 // twice, plus a bit of overhead (one read during
972 // verification, one read of each byte for installation, plus
973 // extra access to things like the zip central directory).
974 // This estimate of the completion becomes 100% when we've
975 // transferred ~2.13 (=100/47) times the package size.
976 int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
977 if (percent != last_percent) {
978 printf("\rserving: '%s' (~%d%%) ", filename, percent);
979 fflush(stdout);
980 last_percent = percent;
981 }
982 }
983 }
984
adb_wipe_devices()985 static int adb_wipe_devices() {
986 auto wipe_devices_message_size = strlen(kMinadbdServicesExitSuccess);
987 std::string error;
988 unique_fd fd(adb_connect(
989 android::base::StringPrintf("rescue-wipe:userdata:%zu", wipe_devices_message_size),
990 &error));
991 if (fd < 0) {
992 fprintf(stderr, "adb: wipe device connection failed: %s\n", error.c_str());
993 return 1;
994 }
995
996 std::string message(wipe_devices_message_size, '\0');
997 if (!ReadFdExactly(fd, message.data(), wipe_devices_message_size)) {
998 fprintf(stderr, "adb: failed to read wipe result: %s\n", strerror(errno));
999 return 1;
1000 }
1001
1002 if (message == kMinadbdServicesExitSuccess) {
1003 return 0;
1004 }
1005
1006 if (message != kMinadbdServicesExitFailure) {
1007 fprintf(stderr, "adb: got unexpected message from rescue wipe %s\n", message.c_str());
1008 }
1009 return 1;
1010 }
1011
ppp(int argc,const char ** argv)1012 static int ppp(int argc, const char** argv) {
1013 #if defined(_WIN32)
1014 error_exit("adb %s not implemented on Win32", argv[0]);
1015 __builtin_unreachable();
1016 #else
1017 if (argc < 2) error_exit("usage: adb %s <adb service name> [ppp opts]", argv[0]);
1018
1019 const char* adb_service_name = argv[1];
1020 std::string error_message;
1021 int fd = adb_connect(adb_service_name, &error_message);
1022 if (fd < 0) {
1023 error_exit("could not open adb service %s: %s", adb_service_name, error_message.c_str());
1024 }
1025
1026 pid_t pid = fork();
1027 if (pid == -1) {
1028 perror_exit("fork failed");
1029 }
1030
1031 if (pid == 0) {
1032 // child side
1033 int i;
1034
1035 // copy args
1036 const char** ppp_args = (const char**)alloca(sizeof(char*) * argc + 1);
1037 ppp_args[0] = "pppd";
1038 for (i = 2 ; i < argc ; i++) {
1039 //argv[2] and beyond become ppp_args[1] and beyond
1040 ppp_args[i - 1] = argv[i];
1041 }
1042 ppp_args[i-1] = nullptr;
1043
1044 dup2(fd, STDIN_FILENO);
1045 dup2(fd, STDOUT_FILENO);
1046 adb_close(STDERR_FILENO);
1047 adb_close(fd);
1048
1049 execvp("pppd", (char* const*)ppp_args);
1050 perror_exit("exec pppd failed");
1051 }
1052
1053 // parent side
1054 adb_close(fd);
1055 return 0;
1056 #endif /* !defined(_WIN32) */
1057 }
1058
wait_for_device(const char * service,std::optional<std::chrono::milliseconds> timeout=std::nullopt)1059 static bool wait_for_device(const char* service,
1060 std::optional<std::chrono::milliseconds> timeout = std::nullopt) {
1061 std::vector<std::string> components = android::base::Split(service, "-");
1062 if (components.size() < 3) {
1063 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1064 return false;
1065 }
1066
1067 // If the first thing after "wait-for-" wasn't a TRANSPORT, insert whatever
1068 // the current transport implies.
1069 if (components[2] != "usb" && components[2] != "local" && components[2] != "any") {
1070 TransportType t;
1071 adb_get_transport(&t, nullptr, nullptr);
1072 auto it = components.begin() + 2;
1073 if (t == kTransportUsb) {
1074 components.insert(it, "usb");
1075 } else if (t == kTransportLocal) {
1076 components.insert(it, "local");
1077 } else {
1078 components.insert(it, "any");
1079 }
1080 }
1081
1082 // Stitch it back together and send it over...
1083 std::string cmd = format_host_command(android::base::Join(components, "-").c_str());
1084 if (timeout) {
1085 std::thread([timeout]() {
1086 std::this_thread::sleep_for(*timeout);
1087 fprintf(stderr, "timeout expired while waiting for device\n");
1088 _exit(1);
1089 }).detach();
1090 }
1091 return adb_command(cmd);
1092 }
1093
adb_root(const char * command)1094 static bool adb_root(const char* command) {
1095 std::string error;
1096
1097 TransportId transport_id;
1098 unique_fd fd(adb_connect(&transport_id, android::base::StringPrintf("%s:", command), &error));
1099 if (fd < 0) {
1100 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1101 return false;
1102 }
1103
1104 // Figure out whether we actually did anything.
1105 char buf[256];
1106 char* cur = buf;
1107 ssize_t bytes_left = sizeof(buf);
1108 while (bytes_left > 0) {
1109 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
1110 if (bytes_read == 0) {
1111 break;
1112 } else if (bytes_read < 0) {
1113 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1114 return false;
1115 }
1116 cur += bytes_read;
1117 bytes_left -= bytes_read;
1118 }
1119
1120 if (bytes_left == 0) {
1121 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1122 return false;
1123 }
1124
1125 fwrite(buf, 1, sizeof(buf) - bytes_left, stdout);
1126 fflush(stdout);
1127 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1128 return true;
1129 }
1130
1131 // Wait for the device to go away.
1132 TransportType previous_type;
1133 const char* previous_serial;
1134 TransportId previous_id;
1135 adb_get_transport(&previous_type, &previous_serial, &previous_id);
1136
1137 adb_set_transport(kTransportAny, nullptr, transport_id);
1138 wait_for_device("wait-for-disconnect");
1139
1140 // Wait for the device to come back.
1141 // If we were using a specific transport ID, there's nothing we can wait for.
1142 if (previous_id == 0) {
1143 adb_set_transport(previous_type, previous_serial, 0);
1144 wait_for_device("wait-for-device", 12000ms);
1145 }
1146
1147 return true;
1148 }
1149
send_shell_command(const std::string & command,bool disable_shell_protocol,StandardStreamsCallbackInterface * callback)1150 int send_shell_command(const std::string& command, bool disable_shell_protocol,
1151 StandardStreamsCallbackInterface* callback) {
1152 unique_fd fd;
1153 bool use_shell_protocol = false;
1154
1155 while (true) {
1156 bool attempt_connection = true;
1157
1158 // Use shell protocol if it's supported and the caller doesn't explicitly
1159 // disable it.
1160 if (!disable_shell_protocol) {
1161 auto&& features = adb_get_feature_set(nullptr);
1162 if (features) {
1163 use_shell_protocol = CanUseFeature(*features, kFeatureShell2);
1164 } else {
1165 // Device was unreachable.
1166 attempt_connection = false;
1167 }
1168 }
1169
1170 if (attempt_connection) {
1171 std::string error;
1172 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1173
1174 fd.reset(adb_connect(service_string, &error));
1175 if (fd >= 0) {
1176 break;
1177 }
1178 }
1179
1180 fprintf(stderr, "- waiting for device -\n");
1181 if (!wait_for_device("wait-for-device")) {
1182 return 1;
1183 }
1184 }
1185
1186 return read_and_dump(fd.get(), use_shell_protocol, callback);
1187 }
1188
logcat(int argc,const char ** argv)1189 static int logcat(int argc, const char** argv) {
1190 char* log_tags = getenv("ANDROID_LOG_TAGS");
1191 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
1192
1193 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
1194
1195 if (!strcmp(argv[0], "longcat")) {
1196 cmd += " -v long";
1197 }
1198
1199 --argc;
1200 ++argv;
1201 while (argc-- > 0) {
1202 cmd += " " + escape_arg(*argv++);
1203 }
1204
1205 return send_shell_command(cmd);
1206 }
1207
write_zeros(int bytes,borrowed_fd fd)1208 static void write_zeros(int bytes, borrowed_fd fd) {
1209 int old_stdin_mode = -1;
1210 int old_stdout_mode = -1;
1211 std::vector<char> buf(bytes);
1212
1213 D("write_zeros(%d) -> %d", bytes, fd.get());
1214
1215 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
1216
1217 if (fd == STDOUT_FILENO) {
1218 fwrite(buf.data(), 1, bytes, stdout);
1219 fflush(stdout);
1220 } else {
1221 adb_write(fd, buf.data(), bytes);
1222 }
1223
1224 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
1225
1226 D("write_zeros() finished");
1227 }
1228
backup(int argc,const char ** argv)1229 static int backup(int argc, const char** argv) {
1230 fprintf(stdout, "WARNING: adb backup is deprecated and may be removed in a future release\n");
1231
1232 const char* filename = "backup.ab";
1233
1234 /* find, extract, and use any -f argument */
1235 for (int i = 1; i < argc; i++) {
1236 if (!strcmp("-f", argv[i])) {
1237 if (i == argc - 1) error_exit("backup -f passed with no filename");
1238 filename = argv[i+1];
1239 for (int j = i+2; j <= argc; ) {
1240 argv[i++] = argv[j++];
1241 }
1242 argc -= 2;
1243 argv[argc] = nullptr;
1244 }
1245 }
1246
1247 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1248 // a list of packages is required.
1249 if (argc < 2) error_exit("backup either needs a list of packages or -all/-shared");
1250
1251 adb_unlink(filename);
1252 unique_fd outFd(adb_creat(filename, 0640));
1253 if (outFd < 0) {
1254 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1255 return EXIT_FAILURE;
1256 }
1257
1258 std::string cmd = "backup:";
1259 --argc;
1260 ++argv;
1261 while (argc-- > 0) {
1262 cmd += " " + escape_arg(*argv++);
1263 }
1264
1265 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
1266 std::string error;
1267 unique_fd fd(adb_connect(cmd, &error));
1268 if (fd < 0) {
1269 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
1270 return EXIT_FAILURE;
1271 }
1272
1273 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
1274 fflush(stdout);
1275
1276 copy_to_file(fd.get(), outFd.get());
1277 return EXIT_SUCCESS;
1278 }
1279
restore(int argc,const char ** argv)1280 static int restore(int argc, const char** argv) {
1281 fprintf(stdout, "WARNING: adb restore is deprecated and may be removed in a future release\n");
1282
1283 if (argc != 2) error_exit("restore requires an argument");
1284
1285 const char* filename = argv[1];
1286 unique_fd tarFd(adb_open(filename, O_RDONLY));
1287 if (tarFd < 0) {
1288 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
1289 return -1;
1290 }
1291
1292 std::string error;
1293 unique_fd fd(adb_connect("restore:", &error));
1294 if (fd < 0) {
1295 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
1296 return -1;
1297 }
1298
1299 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1300 fflush(stdout);
1301
1302 copy_to_file(tarFd.get(), fd.get());
1303
1304 // Provide an in-band EOD marker in case the archive file is malformed
1305 write_zeros(512 * 2, fd);
1306
1307 // Wait until the other side finishes, or it'll get sent SIGHUP.
1308 copy_to_file(fd.get(), STDOUT_FILENO);
1309 return 0;
1310 }
1311
parse_compression_type(const std::string & str,bool allow_numbers)1312 static CompressionType parse_compression_type(const std::string& str, bool allow_numbers) {
1313 if (allow_numbers) {
1314 if (str == "0") {
1315 return CompressionType::None;
1316 } else if (str == "1") {
1317 return CompressionType::Any;
1318 }
1319 }
1320
1321 if (str == "any") {
1322 return CompressionType::Any;
1323 } else if (str == "none") {
1324 return CompressionType::None;
1325 }
1326
1327 if (str == "brotli") {
1328 return CompressionType::Brotli;
1329 } else if (str == "lz4") {
1330 return CompressionType::LZ4;
1331 } else if (str == "zstd") {
1332 return CompressionType::Zstd;
1333 }
1334
1335 error_exit("unexpected compression type %s", str.c_str());
1336 }
1337
parse_push_pull_args(const char ** arg,int narg,std::vector<const char * > * srcs,const char ** dst,bool * copy_attrs,bool * sync,CompressionType * compression,bool * dry_run)1338 static void parse_push_pull_args(const char** arg, int narg, std::vector<const char*>* srcs,
1339 const char** dst, bool* copy_attrs, bool* sync,
1340 CompressionType* compression, bool* dry_run) {
1341 *copy_attrs = false;
1342 if (const char* adb_compression = getenv("ADB_COMPRESSION")) {
1343 *compression = parse_compression_type(adb_compression, true);
1344 }
1345
1346 srcs->clear();
1347 bool ignore_flags = false;
1348 while (narg > 0) {
1349 if (ignore_flags || *arg[0] != '-') {
1350 srcs->push_back(*arg);
1351 } else {
1352 if (!strcmp(*arg, "-p")) {
1353 // Silently ignore for backwards compatibility.
1354 } else if (!strcmp(*arg, "-a")) {
1355 *copy_attrs = true;
1356 } else if (!strcmp(*arg, "-z")) {
1357 if (narg < 2) {
1358 error_exit("-z requires an argument");
1359 }
1360 *compression = parse_compression_type(*++arg, false);
1361 --narg;
1362 } else if (!strcmp(*arg, "-Z")) {
1363 *compression = CompressionType::None;
1364 } else if (dry_run && !strcmp(*arg, "-n")) {
1365 *dry_run = true;
1366 } else if (!strcmp(*arg, "--sync")) {
1367 if (sync != nullptr) {
1368 *sync = true;
1369 }
1370 } else if (!strcmp(*arg, "--")) {
1371 ignore_flags = true;
1372 } else {
1373 error_exit("unrecognized option '%s'", *arg);
1374 }
1375 }
1376 ++arg;
1377 --narg;
1378 }
1379
1380 if (srcs->size() > 1) {
1381 *dst = srcs->back();
1382 srcs->pop_back();
1383 }
1384 }
1385
adb_connect_command(const std::string & command,TransportId * transport,StandardStreamsCallbackInterface * callback)1386 static int adb_connect_command(const std::string& command, TransportId* transport,
1387 StandardStreamsCallbackInterface* callback) {
1388 std::string error;
1389 unique_fd fd(adb_connect(transport, command, &error));
1390 if (fd < 0) {
1391 fprintf(stderr, "error: %s\n", error.c_str());
1392 return 1;
1393 }
1394 read_and_dump(fd, false, callback);
1395 return 0;
1396 }
1397
adb_connect_command(const std::string & command,TransportId * transport=nullptr)1398 static int adb_connect_command(const std::string& command, TransportId* transport = nullptr) {
1399 return adb_connect_command(command, transport, &DEFAULT_STANDARD_STREAMS_CALLBACK);
1400 }
1401
1402 // A class that prints out human readable form of the protobuf message for "track-app" service
1403 // (received in binary format).
1404 class TrackAppStreamsCallback : public DefaultStandardStreamsCallback {
1405 public:
TrackAppStreamsCallback()1406 TrackAppStreamsCallback() : DefaultStandardStreamsCallback(nullptr, nullptr) {}
1407
1408 // Assume the buffer contains at least 4 bytes of valid data.
OnStdout(const char * buffer,size_t length)1409 bool OnStdout(const char* buffer, size_t length) override {
1410 if (length < 4) return true; // Unexpected length received. Do nothing.
1411
1412 adb::proto::AppProcesses binary_proto;
1413 // The first 4 bytes are the length of remaining content in hexadecimal format.
1414 binary_proto.ParseFromString(std::string(buffer + 4, length - 4));
1415 char summary[24]; // The following string includes digits and 16 fixed characters.
1416 int written = snprintf(summary, sizeof(summary), "Process count: %d\n",
1417 binary_proto.process_size());
1418 if (!OnStream(nullptr, stdout, summary, written, false)) {
1419 return false;
1420 }
1421
1422 std::string string_proto;
1423 google::protobuf::TextFormat::PrintToString(binary_proto, &string_proto);
1424 return OnStream(nullptr, stdout, string_proto.data(), string_proto.length(), false);
1425 }
1426
1427 private:
1428 DISALLOW_COPY_AND_ASSIGN(TrackAppStreamsCallback);
1429 };
1430
adb_connect_command_bidirectional(const std::string & command)1431 static int adb_connect_command_bidirectional(const std::string& command) {
1432 std::string error;
1433 unique_fd fd(adb_connect(command, &error));
1434 if (fd < 0) {
1435 fprintf(stderr, "error: %s\n", error.c_str());
1436 return 1;
1437 }
1438
1439 static constexpr auto forward = [](int src, int sink, bool exit_on_end) {
1440 char buf[4096];
1441 while (true) {
1442 int rc = adb_read(src, buf, sizeof(buf));
1443 if (rc == 0) {
1444 if (exit_on_end) {
1445 exit(0);
1446 } else {
1447 adb_shutdown(sink, SHUT_WR);
1448 }
1449 return;
1450 } else if (rc < 0) {
1451 perror_exit("read failed");
1452 }
1453 if (!WriteFdExactly(sink, buf, rc)) {
1454 perror_exit("write failed");
1455 }
1456 }
1457 };
1458
1459 std::thread read(forward, fd.get(), STDOUT_FILENO, true);
1460 std::thread write(forward, STDIN_FILENO, fd.get(), false);
1461 read.join();
1462 write.join();
1463 return 0;
1464 }
1465
adb_get_feature_set_or_die(void)1466 const std::optional<FeatureSet>& adb_get_feature_set_or_die(void) {
1467 std::string error;
1468 const std::optional<FeatureSet>& features = adb_get_feature_set(&error);
1469 if (!features) {
1470 error_exit("%s", error.c_str());
1471 }
1472 return features;
1473 }
1474
1475 // Helper function to handle processing of shell service commands:
1476 // remount, disable/enable-verity. There's only one "feature",
1477 // but they were all moved from adbd to external binaries in the
1478 // same release.
process_remount_or_verity_service(const int argc,const char ** argv)1479 static int process_remount_or_verity_service(const int argc, const char** argv) {
1480 auto&& features = adb_get_feature_set_or_die();
1481 if (CanUseFeature(*features, kFeatureRemountShell)) {
1482 std::vector<const char*> args = {"shell"};
1483 args.insert(args.cend(), argv, argv + argc);
1484 return adb_shell_noinput(args.size(), args.data());
1485 } else if (argc > 1) {
1486 auto command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1487 return adb_connect_command(command);
1488 } else {
1489 return adb_connect_command(std::string(argv[0]) + ":");
1490 }
1491 }
1492
adb_query_command(const std::string & command)1493 static int adb_query_command(const std::string& command) {
1494 std::string result;
1495 std::string error;
1496 if (!adb_query(command, &result, &error)) {
1497 fprintf(stderr, "error: %s\n", error.c_str());
1498 return 1;
1499 }
1500 printf("%s\n", result.c_str());
1501 return 0;
1502 }
1503
1504 // Disallow stdin, stdout, and stderr.
_is_valid_ack_reply_fd(const int ack_reply_fd)1505 static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1506 #ifdef _WIN32
1507 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1508 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1509 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1510 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1511 #else
1512 return ack_reply_fd > 2;
1513 #endif
1514 }
1515
_is_valid_os_fd(int fd)1516 static bool _is_valid_os_fd(int fd) {
1517 // Disallow invalid FDs and stdin/out/err as well.
1518 if (fd < 3) {
1519 return false;
1520 }
1521 #ifdef _WIN32
1522 auto handle = (HANDLE)fd;
1523 DWORD info = 0;
1524 if (GetHandleInformation(handle, &info) == 0) {
1525 return false;
1526 }
1527 #else
1528 int flags = fcntl(fd, F_GETFD);
1529 if (flags == -1) {
1530 return false;
1531 }
1532 #endif
1533 return true;
1534 }
1535
adb_commandline(int argc,const char ** argv)1536 int adb_commandline(int argc, const char** argv) {
1537 bool no_daemon = false;
1538 bool is_daemon = false;
1539 bool is_server = false;
1540 int r;
1541 TransportType transport_type = kTransportAny;
1542 int ack_reply_fd = -1;
1543
1544 #if !defined(_WIN32)
1545 // We'd rather have EPIPE than SIGPIPE.
1546 signal(SIGPIPE, SIG_IGN);
1547 #endif
1548
1549 const char* server_host_str = nullptr;
1550 const char* server_port_str = nullptr;
1551 const char* server_socket_str = nullptr;
1552 const char* one_device_str = nullptr;
1553
1554 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1555 const char* serial = nullptr;
1556 TransportId transport_id = 0;
1557
1558 while (argc > 0) {
1559 if (!strcmp(argv[0], "server")) {
1560 is_server = true;
1561 } else if (!strcmp(argv[0], "nodaemon")) {
1562 no_daemon = true;
1563 } else if (!strcmp(argv[0], "fork-server")) {
1564 /* this is a special flag used only when the ADB client launches the ADB Server */
1565 is_daemon = true;
1566 } else if (!strcmp(argv[0], "--reply-fd")) {
1567 if (argc < 2) error_exit("--reply-fd requires an argument");
1568 const char* reply_fd_str = argv[1];
1569 --argc;
1570 ++argv;
1571 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
1572 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
1573 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
1574 return 1;
1575 }
1576 } else if (!strcmp(argv[0], "--one-device")) {
1577 if (argc < 2) error_exit("--one-device requires an argument");
1578 one_device_str = argv[1];
1579 --argc;
1580 ++argv;
1581 } else if (!strncmp(argv[0], "-s", 2)) {
1582 if (isdigit(argv[0][2])) {
1583 serial = argv[0] + 2;
1584 } else {
1585 if (argc < 2 || argv[0][2] != '\0') error_exit("-s requires an argument");
1586 serial = argv[1];
1587 --argc;
1588 ++argv;
1589 }
1590 } else if (!strncmp(argv[0], "-t", 2)) {
1591 const char* id;
1592 if (isdigit(argv[0][2])) {
1593 id = argv[0] + 2;
1594 } else {
1595 id = argv[1];
1596 --argc;
1597 ++argv;
1598 }
1599 transport_id = strtoll(id, const_cast<char**>(&id), 10);
1600 if (*id != '\0') {
1601 error_exit("invalid transport id");
1602 }
1603 } else if (!strcmp(argv[0], "-d")) {
1604 transport_type = kTransportUsb;
1605 } else if (!strcmp(argv[0], "-e")) {
1606 transport_type = kTransportLocal;
1607 } else if (!strcmp(argv[0], "-a")) {
1608 gListenAll = 1;
1609 } else if (!strncmp(argv[0], "-H", 2)) {
1610 if (argv[0][2] == '\0') {
1611 if (argc < 2) error_exit("-H requires an argument");
1612 server_host_str = argv[1];
1613 --argc;
1614 ++argv;
1615 } else {
1616 server_host_str = argv[0] + 2;
1617 }
1618 } else if (!strncmp(argv[0], "-P", 2)) {
1619 if (argv[0][2] == '\0') {
1620 if (argc < 2) error_exit("-P requires an argument");
1621 server_port_str = argv[1];
1622 --argc;
1623 ++argv;
1624 } else {
1625 server_port_str = argv[0] + 2;
1626 }
1627 } else if (!strcmp(argv[0], "-L")) {
1628 if (argc < 2) error_exit("-L requires an argument");
1629 server_socket_str = argv[1];
1630 --argc;
1631 ++argv;
1632 } else if (strcmp(argv[0], "--exit-on-write-error") == 0) {
1633 DEFAULT_STANDARD_STREAMS_CALLBACK.ReturnErrors(true);
1634 } else {
1635 /* out of recognized modifiers and flags */
1636 break;
1637 }
1638 --argc;
1639 ++argv;
1640 }
1641
1642 if ((server_host_str || server_port_str) && server_socket_str) {
1643 error_exit("-L is incompatible with -H or -P");
1644 }
1645
1646 // If -L, -H, or -P are specified, ignore environment variables.
1647 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
1648 if (!server_host_str && !server_port_str && !server_socket_str) {
1649 server_socket_str = getenv("ADB_SERVER_SOCKET");
1650 }
1651
1652 if (!server_socket_str) {
1653 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1654 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1655
1656 int server_port = DEFAULT_ADB_PORT;
1657 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
1658 if (server_port_str && strlen(server_port_str) > 0) {
1659 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
1660 error_exit(
1661 "$ANDROID_ADB_SERVER_PORT must be a positive number less than 65535: "
1662 "got \"%s\"",
1663 server_port_str);
1664 }
1665 }
1666
1667 int rc;
1668 char* temp;
1669 if (server_host_str) {
1670 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
1671 } else {
1672 rc = asprintf(&temp, "tcp:%d", server_port);
1673 }
1674 if (rc < 0) {
1675 LOG(FATAL) << "failed to allocate server socket specification";
1676 }
1677 server_socket_str = temp;
1678 }
1679
1680 bool server_start =
1681 is_daemon || is_server || (argc > 0 && strcmp(argv[0], "start-server") == 0);
1682 if (one_device_str && !server_start) {
1683 error_exit("--one-device is only allowed when starting a server.");
1684 }
1685
1686 adb_set_one_device(one_device_str);
1687 adb_set_socket_spec(server_socket_str);
1688
1689 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1690 if (transport_type == kTransportAny && serial == nullptr) {
1691 serial = getenv("ANDROID_SERIAL");
1692 }
1693
1694 adb_set_transport(transport_type, serial, transport_id);
1695
1696 if (is_server) {
1697 if (no_daemon || is_daemon) {
1698 if (is_daemon && (ack_reply_fd == -1)) {
1699 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
1700 return 1;
1701 }
1702 r = adb_server_main(is_daemon, server_socket_str, one_device_str, ack_reply_fd);
1703 } else {
1704 r = launch_server(server_socket_str, one_device_str);
1705 }
1706 if (r) {
1707 fprintf(stderr,"* could not start server *\n");
1708 }
1709 return r;
1710 }
1711
1712 if (argc == 0) {
1713 help();
1714 return 1;
1715 }
1716
1717 /* handle wait-for-* prefix */
1718 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
1719 const char* service = argv[0];
1720
1721 if (!wait_for_device(service)) {
1722 return 1;
1723 }
1724
1725 // Allow a command to be run after wait-for-device,
1726 // e.g. 'adb wait-for-device shell'.
1727 if (argc == 1) {
1728 return 0;
1729 }
1730
1731 /* Fall through */
1732 --argc;
1733 ++argv;
1734 }
1735
1736 /* adb_connect() commands */
1737 if (!strcmp(argv[0], "devices")) {
1738 const char *listopt;
1739 if (argc < 2) {
1740 listopt = "";
1741 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
1742 listopt = argv[1];
1743 } else {
1744 error_exit("adb devices [-l]");
1745 }
1746
1747 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
1748 std::string error;
1749 if (!adb_check_server_version(&error)) {
1750 error_exit("failed to check server version: %s", error.c_str());
1751 }
1752 printf("List of devices attached\n");
1753 return adb_query_command(query);
1754 } else if (!strcmp(argv[0], "transport-id")) {
1755 TransportId transport_id;
1756 std::string error;
1757 unique_fd fd(adb_connect(&transport_id, "host:features", &error, true));
1758 if (fd == -1) {
1759 error_exit("%s", error.c_str());
1760 }
1761 printf("%" PRIu64 "\n", transport_id);
1762 return 0;
1763 } else if (!strcmp(argv[0], "connect")) {
1764 if (argc != 2) error_exit("usage: adb connect HOST[:PORT]");
1765
1766 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1767 return adb_query_command(query);
1768 } else if (!strcmp(argv[0], "disconnect")) {
1769 if (argc > 2) error_exit("usage: adb disconnect [HOST[:PORT]]");
1770
1771 std::string query = android::base::StringPrintf("host:disconnect:%s",
1772 (argc == 2) ? argv[1] : "");
1773 return adb_query_command(query);
1774 } else if (!strcmp(argv[0], "abb")) {
1775 return adb_abb(argc, argv);
1776 } else if (!strcmp(argv[0], "pair")) {
1777 if (argc < 2 || argc > 3) error_exit("usage: adb pair HOST[:PORT] [PAIRING CODE]");
1778
1779 std::string password;
1780 if (argc == 2) {
1781 printf("Enter pairing code: ");
1782 fflush(stdout);
1783 if (!std::getline(std::cin, password) || password.empty()) {
1784 error_exit("No pairing code provided");
1785 }
1786 } else {
1787 password = argv[2];
1788 }
1789 std::string query =
1790 android::base::StringPrintf("host:pair:%s:%s", password.c_str(), argv[1]);
1791
1792 return adb_query_command(query);
1793 } else if (!strcmp(argv[0], "emu")) {
1794 return adb_send_emulator_command(argc, argv, serial);
1795 } else if (!strcmp(argv[0], "shell")) {
1796 return adb_shell(argc, argv);
1797 } else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
1798 int exec_in = !strcmp(argv[0], "exec-in");
1799
1800 if (argc < 2) error_exit("usage: adb %s command", argv[0]);
1801
1802 std::string cmd = "exec:";
1803 cmd += argv[1];
1804 argc -= 2;
1805 argv += 2;
1806 while (argc-- > 0) {
1807 cmd += " " + escape_arg(*argv++);
1808 }
1809
1810 std::string error;
1811 unique_fd fd(adb_connect(cmd, &error));
1812 if (fd < 0) {
1813 fprintf(stderr, "error: %s\n", error.c_str());
1814 return -1;
1815 }
1816
1817 if (exec_in) {
1818 copy_to_file(STDIN_FILENO, fd.get());
1819 } else {
1820 copy_to_file(fd.get(), STDOUT_FILENO);
1821 }
1822 return 0;
1823 } else if (!strcmp(argv[0], "kill-server")) {
1824 return adb_kill_server() ? 0 : 1;
1825 } else if (!strcmp(argv[0], "sideload")) {
1826 if (argc != 2) error_exit("sideload requires an argument");
1827 if (adb_sideload_install(argv[1], false /* rescue_mode */)) {
1828 return 1;
1829 } else {
1830 return 0;
1831 }
1832 } else if (!strcmp(argv[0], "rescue")) {
1833 // adb rescue getprop
1834 // adb rescue getprop <prop>
1835 // adb rescue install <filename>
1836 // adb rescue wipe userdata
1837 if (argc < 2) error_exit("rescue requires at least one argument");
1838 if (!strcmp(argv[1], "getprop")) {
1839 if (argc == 2) {
1840 return adb_connect_command("rescue-getprop:");
1841 }
1842 if (argc == 3) {
1843 return adb_connect_command(
1844 android::base::StringPrintf("rescue-getprop:%s", argv[2]));
1845 }
1846 error_exit("invalid rescue getprop arguments");
1847 } else if (!strcmp(argv[1], "install")) {
1848 if (argc != 3) error_exit("rescue install requires two arguments");
1849 if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
1850 return 1;
1851 }
1852 } else if (!strcmp(argv[1], "wipe")) {
1853 if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
1854 error_exit("invalid rescue wipe arguments");
1855 }
1856 return adb_wipe_devices();
1857 } else {
1858 error_exit("invalid rescue argument");
1859 }
1860 return 0;
1861 } else if (!strcmp(argv[0], "tcpip")) {
1862 if (argc != 2) error_exit("tcpip requires an argument");
1863 int port;
1864 if (!android::base::ParseInt(argv[1], &port, 1, 65535)) {
1865 error_exit("tcpip: invalid port: %s", argv[1]);
1866 }
1867 return adb_connect_command(android::base::StringPrintf("tcpip:%d", port));
1868 } else if (!strcmp(argv[0], "remount") || !strcmp(argv[0], "disable-verity") ||
1869 !strcmp(argv[0], "enable-verity")) {
1870 return process_remount_or_verity_service(argc, argv);
1871 } else if (!strcmp(argv[0], "reboot") || !strcmp(argv[0], "reboot-bootloader") ||
1872 !strcmp(argv[0], "reboot-fastboot") || !strcmp(argv[0], "usb")) {
1873 std::string command;
1874 if (!strcmp(argv[0], "reboot-bootloader")) {
1875 command = "reboot:bootloader";
1876 } else if (!strcmp(argv[0], "reboot-fastboot")) {
1877 command = "reboot:fastboot";
1878 } else if (argc > 1) {
1879 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1880 } else {
1881 command = android::base::StringPrintf("%s:", argv[0]);
1882 }
1883 return adb_connect_command(command);
1884 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1885 return adb_root(argv[0]) ? 0 : 1;
1886 } else if (!strcmp(argv[0], "bugreport")) {
1887 Bugreport bugreport;
1888 return bugreport.DoIt(argc, argv);
1889 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
1890 bool reverse = !strcmp(argv[0], "reverse");
1891 --argc;
1892 if (argc < 1) error_exit("%s requires an argument", argv[0]);
1893 ++argv;
1894
1895 // Determine the <host-prefix> for this command.
1896 std::string host_prefix;
1897 if (reverse) {
1898 host_prefix = "reverse:";
1899 } else {
1900 host_prefix = "host:";
1901 }
1902
1903 std::string cmd, error_message;
1904 if (strcmp(argv[0], "--list") == 0) {
1905 if (argc != 1) error_exit("--list doesn't take any arguments");
1906 return adb_query_command(host_prefix + "list-forward");
1907 } else if (strcmp(argv[0], "--remove-all") == 0) {
1908 if (argc != 1) error_exit("--remove-all doesn't take any arguments");
1909 cmd = "killforward-all";
1910 } else if (strcmp(argv[0], "--remove") == 0) {
1911 // forward --remove <local>
1912 if (argc != 2) error_exit("--remove requires an argument");
1913 cmd = std::string("killforward:") + argv[1];
1914 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1915 // forward --no-rebind <local> <remote>
1916 if (argc != 3) error_exit("--no-rebind takes two arguments");
1917 if (forward_targets_are_valid(argv[1], argv[2], &error_message)) {
1918 cmd = std::string("forward:norebind:") + argv[1] + ";" + argv[2];
1919 }
1920 } else {
1921 // forward <local> <remote>
1922 if (argc != 2) error_exit("forward takes two arguments");
1923 if (forward_targets_are_valid(argv[0], argv[1], &error_message)) {
1924 cmd = std::string("forward:") + argv[0] + ";" + argv[1];
1925 }
1926 }
1927
1928 if (!error_message.empty()) {
1929 error_exit("error: %s", error_message.c_str());
1930 }
1931
1932 unique_fd fd(adb_connect(nullptr, host_prefix + cmd, &error_message, true));
1933 if (fd < 0 || !adb_status(fd.get(), &error_message)) {
1934 error_exit("error: %s", error_message.c_str());
1935 }
1936
1937 // Server or device may optionally return a resolved TCP port number.
1938 std::string resolved_port;
1939 if (ReadProtocolString(fd, &resolved_port, &error_message) && !resolved_port.empty()) {
1940 printf("%s\n", resolved_port.c_str());
1941 }
1942
1943 ReadOrderlyShutdown(fd);
1944 return 0;
1945 } else if (!strcmp(argv[0], "mdns")) {
1946 --argc;
1947 if (argc < 1) error_exit("mdns requires an argument");
1948 ++argv;
1949
1950 std::string error;
1951 if (!adb_check_server_version(&error)) {
1952 error_exit("failed to check server version: %s", error.c_str());
1953 }
1954
1955 std::string query = "host:mdns:";
1956 if (!strcmp(argv[0], "check")) {
1957 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1958 query += "check";
1959 } else if (!strcmp(argv[0], "services")) {
1960 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1961 query += "services";
1962 printf("List of discovered mdns services\n");
1963 } else {
1964 error_exit("unknown mdns command [%s]", argv[0]);
1965 }
1966
1967 return adb_query_command(query);
1968 }
1969 /* do_sync_*() commands */
1970 else if (!strcmp(argv[0], "ls")) {
1971 if (argc != 2) error_exit("ls requires an argument");
1972 return do_sync_ls(argv[1]) ? 0 : 1;
1973 } else if (!strcmp(argv[0], "push")) {
1974 bool copy_attrs = false;
1975 bool sync = false;
1976 bool dry_run = false;
1977 CompressionType compression = CompressionType::Any;
1978 std::vector<const char*> srcs;
1979 const char* dst = nullptr;
1980
1981 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, ©_attrs, &sync, &compression,
1982 &dry_run);
1983 if (srcs.empty() || !dst) error_exit("push requires an argument");
1984 return do_sync_push(srcs, dst, sync, compression, dry_run) ? 0 : 1;
1985 } else if (!strcmp(argv[0], "pull")) {
1986 bool copy_attrs = false;
1987 CompressionType compression = CompressionType::None;
1988 std::vector<const char*> srcs;
1989 const char* dst = ".";
1990
1991 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, ©_attrs, nullptr, &compression,
1992 nullptr);
1993 if (srcs.empty()) error_exit("pull requires an argument");
1994 return do_sync_pull(srcs, dst, copy_attrs, compression) ? 0 : 1;
1995 } else if (!strcmp(argv[0], "install")) {
1996 if (argc < 2) error_exit("install requires an argument");
1997 return install_app(argc, argv);
1998 } else if (!strcmp(argv[0], "install-multiple")) {
1999 if (argc < 2) error_exit("install-multiple requires an argument");
2000 return install_multiple_app(argc, argv);
2001 } else if (!strcmp(argv[0], "install-multi-package")) {
2002 if (argc < 2) error_exit("install-multi-package requires an argument");
2003 return install_multi_package(argc, argv);
2004 } else if (!strcmp(argv[0], "uninstall")) {
2005 if (argc < 2) error_exit("uninstall requires an argument");
2006 return uninstall_app(argc, argv);
2007 } else if (!strcmp(argv[0], "sync")) {
2008 std::string src;
2009 bool list_only = false;
2010 bool dry_run = false;
2011 CompressionType compression = CompressionType::Any;
2012
2013 if (const char* adb_compression = getenv("ADB_COMPRESSION"); adb_compression) {
2014 compression = parse_compression_type(adb_compression, true);
2015 }
2016
2017 int opt;
2018 while ((opt = getopt(argc, const_cast<char**>(argv), "lnz:Z")) != -1) {
2019 switch (opt) {
2020 case 'l':
2021 list_only = true;
2022 break;
2023 case 'n':
2024 dry_run = true;
2025 break;
2026 case 'z':
2027 compression = parse_compression_type(optarg, false);
2028 break;
2029 case 'Z':
2030 compression = CompressionType::None;
2031 break;
2032 default:
2033 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
2034 }
2035 }
2036
2037 if (optind == argc) {
2038 src = "all";
2039 } else if (optind + 1 == argc) {
2040 src = argv[optind];
2041 } else {
2042 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
2043 }
2044
2045 std::vector<std::string> partitions{"data", "odm", "oem", "product",
2046 "system", "system_ext", "vendor"};
2047 bool found = false;
2048 for (const auto& partition : partitions) {
2049 if (src == "all" || src == partition) {
2050 std::string src_dir{product_file(partition)};
2051 if (!directory_exists(src_dir)) continue;
2052 found = true;
2053 if (!do_sync_sync(src_dir, "/" + partition, list_only, compression, dry_run)) {
2054 return 1;
2055 }
2056 }
2057 }
2058 if (!found) error_exit("don't know how to sync %s partition", src.c_str());
2059 return 0;
2060 }
2061 /* passthrough commands */
2062 else if (!strcmp(argv[0], "get-state") || !strcmp(argv[0], "get-serialno") ||
2063 !strcmp(argv[0], "get-devpath")) {
2064 return adb_query_command(format_host_command(argv[0]));
2065 }
2066 /* other commands */
2067 else if (!strcmp(argv[0], "logcat") || !strcmp(argv[0], "lolcat") ||
2068 !strcmp(argv[0], "longcat")) {
2069 return logcat(argc, argv);
2070 } else if (!strcmp(argv[0], "ppp")) {
2071 return ppp(argc, argv);
2072 } else if (!strcmp(argv[0], "start-server")) {
2073 std::string error;
2074 const int result = adb_connect("host:start-server", &error);
2075 if (result < 0) {
2076 fprintf(stderr, "error: %s\n", error.c_str());
2077 }
2078 return result;
2079 } else if (!strcmp(argv[0], "backup")) {
2080 return backup(argc, argv);
2081 } else if (!strcmp(argv[0], "restore")) {
2082 return restore(argc, argv);
2083 } else if (!strcmp(argv[0], "keygen")) {
2084 if (argc != 2) error_exit("keygen requires an argument");
2085 // Always print key generation information for keygen command.
2086 adb_trace_enable(AUTH);
2087 return adb_auth_keygen(argv[1]);
2088 } else if (!strcmp(argv[0], "pubkey")) {
2089 if (argc != 2) error_exit("pubkey requires an argument");
2090 return adb_auth_pubkey(argv[1]);
2091 } else if (!strcmp(argv[0], "jdwp")) {
2092 return adb_connect_command("jdwp");
2093 } else if (!strcmp(argv[0], "track-jdwp")) {
2094 return adb_connect_command("track-jdwp");
2095 } else if (!strcmp(argv[0], "track-app")) {
2096 auto&& features = adb_get_feature_set_or_die();
2097 if (!CanUseFeature(*features, kFeatureTrackApp)) {
2098 error_exit("track-app is not supported by the device");
2099 }
2100 TrackAppStreamsCallback callback;
2101 return adb_connect_command("track-app", nullptr, &callback);
2102 } else if (!strcmp(argv[0], "track-devices")) {
2103 if (argc > 2 || (argc == 2 && strcmp(argv[1], "-l"))) {
2104 error_exit("usage: adb track-devices [-l]");
2105 }
2106 return adb_connect_command(argc == 2 ? "host:track-devices-l" : "host:track-devices");
2107 } else if (!strcmp(argv[0], "raw")) {
2108 if (argc != 2) {
2109 error_exit("usage: adb raw SERVICE");
2110 }
2111 return adb_connect_command_bidirectional(argv[1]);
2112 }
2113
2114 /* "adb /?" is a common idiom under Windows */
2115 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
2116 help();
2117 return 0;
2118 } else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
2119 fprintf(stdout, "%s", adb_version().c_str());
2120 return 0;
2121 } else if (!strcmp(argv[0], "features")) {
2122 // Only list the features common to both the adb client and the device.
2123 auto&& features = adb_get_feature_set_or_die();
2124
2125 for (const std::string& name : *features) {
2126 if (CanUseFeature(*features, name)) {
2127 printf("%s\n", name.c_str());
2128 }
2129 }
2130 return 0;
2131 } else if (!strcmp(argv[0], "host-features")) {
2132 return adb_query_command("host:host-features");
2133 } else if (!strcmp(argv[0], "reconnect")) {
2134 if (argc == 1) {
2135 return adb_query_command(format_host_command(argv[0]));
2136 } else if (argc == 2) {
2137 if (!strcmp(argv[1], "device")) {
2138 std::string err;
2139 adb_connect("reconnect", &err);
2140 return 0;
2141 } else if (!strcmp(argv[1], "offline")) {
2142 std::string err;
2143 return adb_query_command("host:reconnect-offline");
2144 } else {
2145 error_exit("usage: adb reconnect [device|offline]");
2146 }
2147 }
2148 } else if (!strcmp(argv[0], "inc-server")) {
2149 if (argc < 4) {
2150 #ifdef _WIN32
2151 error_exit("usage: adb inc-server CONNECTION_HANDLE OUTPUT_HANDLE FILE1 FILE2 ...");
2152 #else
2153 error_exit("usage: adb inc-server CONNECTION_FD OUTPUT_FD FILE1 FILE2 ...");
2154 #endif
2155 }
2156 int connection_fd = atoi(argv[1]);
2157 if (!_is_valid_os_fd(connection_fd)) {
2158 error_exit("Invalid connection_fd number given: %d", connection_fd);
2159 }
2160
2161 connection_fd = adb_register_socket(connection_fd);
2162 close_on_exec(connection_fd);
2163
2164 int output_fd = atoi(argv[2]);
2165 if (!_is_valid_os_fd(output_fd)) {
2166 error_exit("Invalid output_fd number given: %d", output_fd);
2167 }
2168 output_fd = adb_register_socket(output_fd);
2169 close_on_exec(output_fd);
2170 return incremental::serve(connection_fd, output_fd, argc - 3, argv + 3);
2171 } else if (!strcmp(argv[0], "attach") || !strcmp(argv[0], "detach")) {
2172 const char* service = strcmp(argv[0], "attach") == 0 ? "host:attach" : "host:detach";
2173 std::string result;
2174 std::string error;
2175 if (!adb_query(service, &result, &error, true)) {
2176 error_exit("failed to %s: %s", argv[0], error.c_str());
2177 }
2178 printf("%s\n", result.c_str());
2179 return 0;
2180 }
2181
2182 error_exit("unknown command %s", argv[0]);
2183 __builtin_unreachable();
2184 }
2185