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