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