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