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