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