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