commandline.cpp revision 8dcdb57dafd554e801de97012e7d0ef6ec63a5ac
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 34#include <memory> 35#include <string> 36 37#include <base/logging.h> 38#include <base/stringprintf.h> 39#include <base/strings.h> 40 41#if !defined(_WIN32) 42#include <signal.h> 43#include <termios.h> 44#include <unistd.h> 45#endif 46 47#include "adb.h" 48#include "adb_auth.h" 49#include "adb_client.h" 50#include "adb_io.h" 51#include "adb_utils.h" 52#include "file_sync_service.h" 53#include "services.h" 54#include "shell_service.h" 55#include "transport.h" 56 57static int install_app(TransportType t, const char* serial, int argc, const char** argv); 58static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv); 59static int uninstall_app(TransportType t, const char* serial, int argc, const char** argv); 60 61static std::string gProductOutPath; 62extern int gListenAll; 63 64static std::string product_file(const char *extra) { 65 if (gProductOutPath.empty()) { 66 fprintf(stderr, "adb: Product directory not specified; " 67 "use -p or define ANDROID_PRODUCT_OUT\n"); 68 exit(1); 69 } 70 71 return android::base::StringPrintf("%s%s%s", 72 gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra); 73} 74 75static void help() { 76 fprintf(stderr, "%s\n", adb_version().c_str()); 77 fprintf(stderr, 78 " -a - directs adb to listen on all interfaces for a connection\n" 79 " -d - directs command to the only connected USB device\n" 80 " returns an error if more than one USB device is present.\n" 81 " -e - directs command to the only running emulator.\n" 82 " returns an error if more than one emulator is running.\n" 83 " -s <specific device> - directs command to the device or emulator with the given\n" 84 " serial number or qualifier. Overrides ANDROID_SERIAL\n" 85 " environment variable.\n" 86 " -p <product name or path> - simple product name like 'sooner', or\n" 87 " a relative/absolute path to a product\n" 88 " out directory like 'out/target/product/sooner'.\n" 89 " If -p is not specified, the ANDROID_PRODUCT_OUT\n" 90 " environment variable is used, which must\n" 91 " be an absolute path.\n" 92 " -H - Name of adb server host (default: localhost)\n" 93 " -P - Port of adb server (default: 5037)\n" 94 " devices [-l] - list all connected devices\n" 95 " ('-l' will also list device qualifiers)\n" 96 " connect <host>[:<port>] - connect to a device via TCP/IP\n" 97 " Port 5555 is used by default if no port number is specified.\n" 98 " disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.\n" 99 " Port 5555 is used by default if no port number is specified.\n" 100 " Using this command with no additional arguments\n" 101 " will disconnect from all connected TCP/IP devices.\n" 102 "\n" 103 "device commands:\n" 104 " adb push [-p] <local> <remote>\n" 105 " - copy file/dir to device\n" 106 " ('-p' to display the transfer progress)\n" 107 " adb pull [-p] [-a] <remote> [<local>]\n" 108 " - copy file/dir from device\n" 109 " ('-p' to display the transfer progress)\n" 110 " ('-a' means copy timestamp and mode)\n" 111 " adb sync [ <directory> ] - copy host->device only if changed\n" 112 " (-l means list but don't copy)\n" 113 " adb shell [-Ttx] - run remote shell interactively\n" 114 " adb shell [-Ttx] <command> - run remote shell command\n" 115 " (-T disables PTY allocation)\n" 116 " (-t forces PTY allocation)\n" 117 " (-x disables remote exit codes and stdout/stderr separation)\n" 118 " adb emu <command> - run emulator console command\n" 119 " adb logcat [ <filter-spec> ] - View device log\n" 120 " adb forward --list - list all forward socket connections.\n" 121 " the format is a list of lines with the following format:\n" 122 " <serial> \" \" <local> \" \" <remote> \"\\n\"\n" 123 " adb forward <local> <remote> - forward socket connections\n" 124 " forward specs are one of: \n" 125 " tcp:<port>\n" 126 " localabstract:<unix domain socket name>\n" 127 " localreserved:<unix domain socket name>\n" 128 " localfilesystem:<unix domain socket name>\n" 129 " dev:<character device name>\n" 130 " jdwp:<process pid> (remote only)\n" 131 " adb forward --no-rebind <local> <remote>\n" 132 " - same as 'adb forward <local> <remote>' but fails\n" 133 " if <local> is already forwarded\n" 134 " adb forward --remove <local> - remove a specific forward socket connection\n" 135 " adb forward --remove-all - remove all forward socket connections\n" 136 " adb reverse --list - list all reverse socket connections from device\n" 137 " adb reverse <remote> <local> - reverse socket connections\n" 138 " reverse specs are one of:\n" 139 " tcp:<port>\n" 140 " localabstract:<unix domain socket name>\n" 141 " localreserved:<unix domain socket name>\n" 142 " localfilesystem:<unix domain socket name>\n" 143 " adb reverse --norebind <remote> <local>\n" 144 " - same as 'adb reverse <remote> <local>' but fails\n" 145 " if <remote> is already reversed.\n" 146 " adb reverse --remove <remote>\n" 147 " - remove a specific reversed socket connection\n" 148 " adb reverse --remove-all - remove all reversed socket connections from device\n" 149 " adb jdwp - list PIDs of processes hosting a JDWP transport\n" 150 " adb install [-lrtsdg] <file>\n" 151 " - push this package file to the device and install it\n" 152 " (-l: forward lock application)\n" 153 " (-r: replace existing application)\n" 154 " (-t: allow test packages)\n" 155 " (-s: install application on sdcard)\n" 156 " (-d: allow version code downgrade)\n" 157 " (-g: grant all runtime permissions)\n" 158 " adb install-multiple [-lrtsdpg] <file...>\n" 159 " - push this package file to the device and install it\n" 160 " (-l: forward lock application)\n" 161 " (-r: replace existing application)\n" 162 " (-t: allow test packages)\n" 163 " (-s: install application on sdcard)\n" 164 " (-d: allow version code downgrade)\n" 165 " (-p: partial application install)\n" 166 " (-g: grant all runtime permissions)\n" 167 " adb uninstall [-k] <package> - remove this app package from the device\n" 168 " ('-k' means keep the data and cache directories)\n" 169 " adb bugreport - return all information from the device\n" 170 " that should be included in a bug report.\n" 171 "\n" 172 " adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n" 173 " - write an archive of the device's data to <file>.\n" 174 " If no -f option is supplied then the data is written\n" 175 " to \"backup.ab\" in the current directory.\n" 176 " (-apk|-noapk enable/disable backup of the .apks themselves\n" 177 " in the archive; the default is noapk.)\n" 178 " (-obb|-noobb enable/disable backup of any installed apk expansion\n" 179 " (aka .obb) files associated with each application; the default\n" 180 " is noobb.)\n" 181 " (-shared|-noshared enable/disable backup of the device's\n" 182 " shared storage / SD card contents; the default is noshared.)\n" 183 " (-all means to back up all installed applications)\n" 184 " (-system|-nosystem toggles whether -all automatically includes\n" 185 " system applications; the default is to include system apps)\n" 186 " (<packages...> is the list of applications to be backed up. If\n" 187 " the -all or -shared flags are passed, then the package\n" 188 " list is optional. Applications explicitly given on the\n" 189 " command line will be included even if -nosystem would\n" 190 " ordinarily cause them to be omitted.)\n" 191 "\n" 192 " adb restore <file> - restore device contents from the <file> backup archive\n" 193 "\n" 194 " adb disable-verity - disable dm-verity checking on USERDEBUG builds\n" 195 " adb enable-verity - re-enable dm-verity checking on USERDEBUG builds\n" 196 " adb keygen <file> - generate adb public/private key. The private key is stored in <file>,\n" 197 " and the public key is stored in <file>.pub. Any existing files\n" 198 " are overwritten.\n" 199 " adb help - show this help message\n" 200 " adb version - show version num\n" 201 "\n" 202 "scripting:\n" 203 " adb wait-for-device - block until device is online\n" 204 " adb start-server - ensure that there is a server running\n" 205 " adb kill-server - kill the server if it is running\n" 206 " adb get-state - prints: offline | bootloader | device\n" 207 " adb get-serialno - prints: <serial-number>\n" 208 " adb get-devpath - prints: <device-path>\n" 209 " adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n" 210 " adb reboot [bootloader|recovery]\n" 211 " - reboots the device, optionally into the bootloader or recovery program.\n" 212 " adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).\n" 213 " adb reboot sideload-auto-reboot\n" 214 " - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n" 215 " adb sideload <file> - sideloads the given package\n" 216 " adb root - restarts the adbd daemon with root permissions\n" 217 " adb unroot - restarts the adbd daemon without root permissions\n" 218 " adb usb - restarts the adbd daemon listening on USB\n" 219 " adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port\n" 220 "\n" 221 "networking:\n" 222 " adb ppp <tty> [parameters] - Run PPP over USB.\n" 223 " Note: you should not automatically start a PPP connection.\n" 224 " <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1\n" 225 " [parameters] - Eg. defaultroute debug dump local notty usepeerdns\n" 226 "\n" 227 "adb sync notes: adb sync [ <directory> ]\n" 228 " <localdir> can be interpreted in several ways:\n" 229 "\n" 230 " - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.\n" 231 "\n" 232 " - If it is \"system\", \"vendor\", \"oem\" or \"data\", only the corresponding partition\n" 233 " is updated.\n" 234 "\n" 235 "environment variables:\n" 236 " ADB_TRACE - Print debug information. A comma separated list of the following values\n" 237 " 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp\n" 238 " ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.\n" 239 " ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.\n" 240 ); 241} 242 243static int usage() { 244 help(); 245 return 1; 246} 247 248#if defined(_WIN32) 249 250// Implemented in sysdeps_win32.cpp. 251void stdin_raw_init(int fd); 252void stdin_raw_restore(int fd); 253 254#else 255static termios g_saved_terminal_state; 256 257static void stdin_raw_init(int fd) { 258 if (tcgetattr(fd, &g_saved_terminal_state)) return; 259 260 termios tio; 261 if (tcgetattr(fd, &tio)) return; 262 263 cfmakeraw(&tio); 264 265 // No timeout but request at least one character per read. 266 tio.c_cc[VTIME] = 0; 267 tio.c_cc[VMIN] = 1; 268 269 tcsetattr(fd, TCSAFLUSH, &tio); 270} 271 272static void stdin_raw_restore(int fd) { 273 tcsetattr(fd, TCSAFLUSH, &g_saved_terminal_state); 274} 275#endif 276 277// Reads from |fd| and prints received data. If |use_shell_protocol| is true 278// this expects that incoming data will use the shell protocol, in which case 279// stdout/stderr are routed independently and the remote exit code will be 280// returned. 281static int read_and_dump(int fd, bool use_shell_protocol=false) { 282 int exit_code = 0; 283 std::unique_ptr<ShellProtocol> protocol; 284 int length = 0; 285 FILE* outfile = stdout; 286 287 char raw_buffer[BUFSIZ]; 288 char* buffer_ptr = raw_buffer; 289 if (use_shell_protocol) { 290 protocol.reset(new 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 (fd >= 0) { 299 if (use_shell_protocol) { 300 if (!protocol->Read()) { 301 break; 302 } 303 switch (protocol->id()) { 304 case ShellProtocol::kIdStdout: 305 outfile = stdout; 306 break; 307 case ShellProtocol::kIdStderr: 308 outfile = stderr; 309 break; 310 case ShellProtocol::kIdExit: 311 exit_code = protocol->data()[0]; 312 continue; 313 default: 314 continue; 315 } 316 length = protocol->data_length(); 317 } else { 318 D("read_and_dump(): pre adb_read(fd=%d)", fd); 319 length = adb_read(fd, raw_buffer, sizeof(raw_buffer)); 320 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd, length); 321 if (length <= 0) { 322 break; 323 } 324 } 325 326 fwrite(buffer_ptr, 1, length, outfile); 327 fflush(outfile); 328 } 329 330 return exit_code; 331} 332 333static void read_status_line(int fd, char* buf, size_t count) 334{ 335 count--; 336 while (count > 0) { 337 int len = adb_read(fd, buf, count); 338 if (len <= 0) { 339 break; 340 } 341 342 buf += len; 343 count -= len; 344 } 345 *buf = '\0'; 346} 347 348static void copy_to_file(int inFd, int outFd) { 349 const size_t BUFSIZE = 32 * 1024; 350 char* buf = (char*) malloc(BUFSIZE); 351 if (buf == nullptr) fatal("couldn't allocate buffer for copy_to_file"); 352 int len; 353 long total = 0; 354#ifdef _WIN32 355 int old_stdin_mode = -1; 356 int old_stdout_mode = -1; 357#endif 358 359 D("copy_to_file(%d -> %d)", inFd, outFd); 360 361 if (inFd == STDIN_FILENO) { 362 stdin_raw_init(STDIN_FILENO); 363#ifdef _WIN32 364 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY); 365 if (old_stdin_mode == -1) { 366 fatal_errno("could not set stdin to binary"); 367 } 368#endif 369 } 370 371#ifdef _WIN32 372 if (outFd == STDOUT_FILENO) { 373 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY); 374 if (old_stdout_mode == -1) { 375 fatal_errno("could not set stdout to binary"); 376 } 377 } 378#endif 379 380 while (true) { 381 if (inFd == STDIN_FILENO) { 382 len = unix_read(inFd, buf, BUFSIZE); 383 } else { 384 len = adb_read(inFd, buf, BUFSIZE); 385 } 386 if (len == 0) { 387 D("copy_to_file() : read 0 bytes; exiting"); 388 break; 389 } 390 if (len < 0) { 391 D("copy_to_file(): read failed: %s", strerror(errno)); 392 break; 393 } 394 if (outFd == STDOUT_FILENO) { 395 fwrite(buf, 1, len, stdout); 396 fflush(stdout); 397 } else { 398 adb_write(outFd, buf, len); 399 } 400 total += len; 401 } 402 403 if (inFd == STDIN_FILENO) { 404 stdin_raw_restore(STDIN_FILENO); 405#ifdef _WIN32 406 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) { 407 fatal_errno("could not restore stdin mode"); 408 } 409#endif 410 } 411 412#ifdef _WIN32 413 if (outFd == STDOUT_FILENO) { 414 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) { 415 fatal_errno("could not restore stdout mode"); 416 } 417 } 418#endif 419 420 D("copy_to_file() finished after %lu bytes", total); 421 free(buf); 422} 423 424namespace { 425 426// Used to pass multiple values to the stdin read thread. 427struct StdinReadArgs { 428 int stdin_fd, write_fd; 429 bool raw_stdin; 430 std::unique_ptr<ShellProtocol> protocol; 431}; 432 433} // namespace 434 435// Loops to read from stdin and push the data to the given FD. 436// The argument should be a pointer to a StdinReadArgs object. This function 437// will take ownership of the object and delete it when finished. 438static void* stdin_read_thread(void* x) { 439 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x)); 440 int state = 0; 441 442 adb_thread_setname("stdin reader"); 443 444#ifndef __WIN32 445 // Mask SIGTTIN in case we're in a backgrounded process 446 sigset_t sigset; 447 sigemptyset(&sigset); 448 sigaddset(&sigset, SIGTTIN); 449 pthread_sigmask(SIG_BLOCK, &sigset, nullptr); 450#endif 451 452 char raw_buffer[1024]; 453 char* buffer_ptr = raw_buffer; 454 size_t buffer_size = sizeof(raw_buffer); 455 if (args->protocol) { 456 buffer_ptr = args->protocol->data(); 457 buffer_size = args->protocol->data_capacity(); 458 } 459 460 while (true) { 461 // Use unix_read() rather than adb_read() for stdin. 462 D("stdin_read_thread(): pre unix_read(fdi=%d,...)", args->stdin_fd); 463 int r = unix_read(args->stdin_fd, buffer_ptr, buffer_size); 464 D("stdin_read_thread(): post unix_read(fdi=%d,...)", args->stdin_fd); 465 if (r <= 0) { 466 // Only devices using the shell protocol know to close subprocess 467 // stdin. For older devices we want to just leave the connection 468 // open, otherwise an unpredictable amount of return data could 469 // be lost due to the FD closing before all data has been received. 470 if (args->protocol) { 471 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0); 472 } 473 break; 474 } 475 // If we made stdin raw, check input for the "~." escape sequence. In 476 // this situation signals like Ctrl+C are sent remotely rather than 477 // interpreted locally so this provides an emergency out if the remote 478 // process starts ignoring the signal. SSH also does this, see the 479 // "escape characters" section on the ssh man page for more info. 480 if (args->raw_stdin) { 481 for (int n = 0; n < r; n++){ 482 switch(buffer_ptr[n]) { 483 case '\n': 484 state = 1; 485 break; 486 case '\r': 487 state = 1; 488 break; 489 case '~': 490 if(state == 1) state++; 491 break; 492 case '.': 493 if(state == 2) { 494 stdin_raw_restore(args->stdin_fd); 495 fprintf(stderr,"\n* disconnect *\n"); 496 exit(0); 497 } 498 default: 499 state = 0; 500 } 501 } 502 } 503 if (args->protocol) { 504 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) { 505 break; 506 } 507 } else { 508 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) { 509 break; 510 } 511 } 512 } 513 514 return nullptr; 515} 516 517// Returns a shell service string with the indicated arguments and command. 518static std::string ShellServiceString(bool use_shell_protocol, 519 const std::string& type_arg, 520 const std::string& command) { 521 std::vector<std::string> args; 522 if (use_shell_protocol) { 523 args.push_back(kShellServiceArgShellProtocol); 524 } 525 if (!type_arg.empty()) { 526 args.push_back(type_arg); 527 } 528 529 // Shell service string can look like: shell[,arg1,arg2,...]:[command]. 530 return android::base::StringPrintf("shell%s%s:%s", 531 args.empty() ? "" : ",", 532 android::base::Join(args, ',').c_str(), 533 command.c_str()); 534} 535 536// Connects to a shell on the device and read/writes data. 537// 538// Note: currently this function doesn't properly clean up resources; the 539// FD connected to the adb server is never closed and the stdin read thread 540// may never exit. 541// 542// On success returns the remote exit code if |use_shell_protocol| is true, 543// 0 otherwise. On failure returns 1. 544static int RemoteShell(bool use_shell_protocol, const std::string& type_arg, 545 const std::string& command) { 546 std::string service_string = ShellServiceString(use_shell_protocol, 547 type_arg, command); 548 549 // Make local stdin raw if the device allocates a PTY, which happens if: 550 // 1. We are explicitly asking for a PTY shell, or 551 // 2. We don't specify shell type and are starting an interactive session. 552 bool raw_stdin = (type_arg == kShellServiceArgPty || 553 (type_arg.empty() && command.empty())); 554 555 std::string error; 556 int fd = adb_connect(service_string, &error); 557 if (fd < 0) { 558 fprintf(stderr,"error: %s\n", error.c_str()); 559 return 1; 560 } 561 562 StdinReadArgs* args = new StdinReadArgs; 563 if (!args) { 564 LOG(ERROR) << "couldn't allocate StdinReadArgs object"; 565 return 1; 566 } 567 args->stdin_fd = STDIN_FILENO; 568 args->write_fd = fd; 569 args->raw_stdin = raw_stdin; 570 if (use_shell_protocol) { 571 args->protocol.reset(new ShellProtocol(args->write_fd)); 572 } 573 574 if (raw_stdin) { 575 stdin_raw_init(STDIN_FILENO); 576 } 577 578 int exit_code = 0; 579 if (!adb_thread_create(stdin_read_thread, args)) { 580 PLOG(ERROR) << "error starting stdin read thread"; 581 exit_code = 1; 582 delete args; 583 } else { 584 exit_code = read_and_dump(fd, use_shell_protocol); 585 } 586 587 if (raw_stdin) { 588 stdin_raw_restore(STDIN_FILENO); 589 } 590 591 // TODO(dpursell): properly exit stdin_read_thread and close |fd|. 592 593 return exit_code; 594} 595 596 597static std::string format_host_command(const char* command, TransportType type, const char* serial) { 598 if (serial) { 599 return android::base::StringPrintf("host-serial:%s:%s", serial, command); 600 } 601 602 const char* prefix = "host"; 603 if (type == kTransportUsb) { 604 prefix = "host-usb"; 605 } else if (type == kTransportLocal) { 606 prefix = "host-local"; 607 } 608 return android::base::StringPrintf("%s:%s", prefix, command); 609} 610 611// Returns the FeatureSet for the indicated transport. 612static FeatureSet GetFeatureSet(TransportType transport_type, 613 const char* serial) { 614 std::string result, error; 615 616 if (adb_query(format_host_command("features", transport_type, serial), 617 &result, &error)) { 618 return StringToFeatureSet(result); 619 } 620 return FeatureSet(); 621} 622 623static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz, 624 bool show_progress) 625{ 626 std::string error; 627 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error); 628 if (fd < 0) { 629 fprintf(stderr,"error: %s\n", error.c_str()); 630 return -1; 631 } 632 633 int opt = CHUNK_SIZE; 634 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt)); 635 636 unsigned total = sz; 637 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); 638 639 if (show_progress) { 640 const char* x = strrchr(service, ':'); 641 if (x) service = x + 1; 642 } 643 644 while (sz > 0) { 645 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz; 646 if (!WriteFdExactly(fd, ptr, xfer)) { 647 std::string error; 648 adb_status(fd, &error); 649 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 650 return -1; 651 } 652 sz -= xfer; 653 ptr += xfer; 654 if (show_progress) { 655 printf("sending: '%s' %4d%% \r", fn, (int)(100LL - ((100LL * sz) / (total)))); 656 fflush(stdout); 657 } 658 } 659 if (show_progress) { 660 printf("\n"); 661 } 662 663 if (!adb_status(fd, &error)) { 664 fprintf(stderr,"* error response '%s' *\n", error.c_str()); 665 return -1; 666 } 667 668 adb_close(fd); 669 return 0; 670} 671 672#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE) 673 674/* 675 * The sideload-host protocol serves the data in a file (given on the 676 * command line) to the client, using a simple protocol: 677 * 678 * - The connect message includes the total number of bytes in the 679 * file and a block size chosen by us. 680 * 681 * - The other side sends the desired block number as eight decimal 682 * digits (eg "00000023" for block 23). Blocks are numbered from 683 * zero. 684 * 685 * - We send back the data of the requested block. The last block is 686 * likely to be partial; when the last block is requested we only 687 * send the part of the block that exists, it's not padded up to the 688 * block size. 689 * 690 * - When the other side sends "DONEDONE" instead of a block number, 691 * we hang up. 692 */ 693static int adb_sideload_host(const char* fn) { 694 unsigned sz; 695 size_t xfer = 0; 696 int status; 697 int last_percent = -1; 698 int opt = SIDELOAD_HOST_BLOCK_SIZE; 699 700 printf("loading: '%s'", fn); 701 fflush(stdout); 702 uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz)); 703 if (data == 0) { 704 printf("\n"); 705 fprintf(stderr, "* cannot read '%s' *\n", fn); 706 return -1; 707 } 708 709 std::string service = 710 android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE); 711 std::string error; 712 int fd = adb_connect(service, &error); 713 if (fd < 0) { 714 // Try falling back to the older sideload method. Maybe this 715 // is an older device that doesn't support sideload-host. 716 printf("\n"); 717 status = adb_download_buffer("sideload", fn, data, sz, true); 718 goto done; 719 } 720 721 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt)); 722 723 while (true) { 724 char buf[9]; 725 if (!ReadFdExactly(fd, buf, 8)) { 726 fprintf(stderr, "* failed to read command: %s\n", strerror(errno)); 727 status = -1; 728 goto done; 729 } 730 buf[8] = '\0'; 731 732 if (strcmp("DONEDONE", buf) == 0) { 733 status = 0; 734 break; 735 } 736 737 int block = strtol(buf, NULL, 10); 738 739 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE; 740 if (offset >= sz) { 741 fprintf(stderr, "* attempt to read block %d past end\n", block); 742 status = -1; 743 goto done; 744 } 745 uint8_t* start = data + offset; 746 size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE; 747 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE; 748 if (offset_end > sz) { 749 to_write = sz - offset; 750 } 751 752 if(!WriteFdExactly(fd, start, to_write)) { 753 adb_status(fd, &error); 754 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 755 status = -1; 756 goto done; 757 } 758 xfer += to_write; 759 760 // For normal OTA packages, we expect to transfer every byte 761 // twice, plus a bit of overhead (one read during 762 // verification, one read of each byte for installation, plus 763 // extra access to things like the zip central directory). 764 // This estimate of the completion becomes 100% when we've 765 // transferred ~2.13 (=100/47) times the package size. 766 int percent = (int)(xfer * 47LL / (sz ? sz : 1)); 767 if (percent != last_percent) { 768 printf("\rserving: '%s' (~%d%%) ", fn, percent); 769 fflush(stdout); 770 last_percent = percent; 771 } 772 } 773 774 printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, ""); 775 776 done: 777 if (fd >= 0) adb_close(fd); 778 free(data); 779 return status; 780} 781 782/** 783 * Run ppp in "notty" mode against a resource listed as the first parameter 784 * eg: 785 * 786 * ppp dev:/dev/omap_csmi_tty0 <ppp options> 787 * 788 */ 789static int ppp(int argc, const char** argv) { 790#if defined(_WIN32) 791 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]); 792 return -1; 793#else 794 if (argc < 2) { 795 fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n", 796 argv[0]); 797 798 return 1; 799 } 800 801 const char* adb_service_name = argv[1]; 802 std::string error; 803 int fd = adb_connect(adb_service_name, &error); 804 if (fd < 0) { 805 fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n", 806 adb_service_name, error.c_str()); 807 return 1; 808 } 809 810 pid_t pid = fork(); 811 812 if (pid < 0) { 813 perror("from fork()"); 814 return 1; 815 } else if (pid == 0) { 816 int err; 817 int i; 818 const char **ppp_args; 819 820 // copy args 821 ppp_args = (const char **) alloca(sizeof(char *) * argc + 1); 822 ppp_args[0] = "pppd"; 823 for (i = 2 ; i < argc ; i++) { 824 //argv[2] and beyond become ppp_args[1] and beyond 825 ppp_args[i - 1] = argv[i]; 826 } 827 ppp_args[i-1] = NULL; 828 829 // child side 830 831 dup2(fd, STDIN_FILENO); 832 dup2(fd, STDOUT_FILENO); 833 adb_close(STDERR_FILENO); 834 adb_close(fd); 835 836 err = execvp("pppd", (char * const *)ppp_args); 837 838 if (err < 0) { 839 perror("execing pppd"); 840 } 841 exit(-1); 842 } else { 843 // parent side 844 845 adb_close(fd); 846 return 0; 847 } 848#endif /* !defined(_WIN32) */ 849} 850 851static bool wait_for_device(const char* service, TransportType t, const char* serial) { 852 // Was the caller vague about what they'd like us to wait for? 853 // If so, check they weren't more specific in their choice of transport type. 854 if (strcmp(service, "wait-for-device") == 0) { 855 if (t == kTransportUsb) { 856 service = "wait-for-usb"; 857 } else if (t == kTransportLocal) { 858 service = "wait-for-local"; 859 } else { 860 service = "wait-for-any"; 861 } 862 } 863 864 std::string cmd = format_host_command(service, t, serial); 865 return adb_command(cmd); 866} 867 868// Connects to the device "shell" service with |command| and prints the 869// resulting output. 870static int send_shell_command(TransportType transport_type, const char* serial, 871 const std::string& command, 872 bool disable_shell_protocol) { 873 // Only use shell protocol if it's supported and the caller doesn't want 874 // to explicitly disable it. 875 bool use_shell_protocol = false; 876 if (!disable_shell_protocol) { 877 FeatureSet features = GetFeatureSet(transport_type, serial); 878 use_shell_protocol = CanUseFeature(features, kFeatureShell2); 879 } 880 881 std::string service_string = ShellServiceString(use_shell_protocol, "", 882 command); 883 884 int fd; 885 while (true) { 886 std::string error; 887 fd = adb_connect(service_string, &error); 888 if (fd >= 0) { 889 break; 890 } 891 fprintf(stderr,"- waiting for device -\n"); 892 adb_sleep_ms(1000); 893 wait_for_device("wait-for-device", transport_type, serial); 894 } 895 896 int exit_code = read_and_dump(fd, use_shell_protocol); 897 898 if (adb_close(fd) < 0) { 899 PLOG(ERROR) << "failure closing FD " << fd; 900 } 901 902 return exit_code; 903} 904 905static int logcat(TransportType transport, const char* serial, int argc, const char** argv) { 906 char* log_tags = getenv("ANDROID_LOG_TAGS"); 907 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags); 908 909 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat"; 910 911 if (!strcmp(argv[0], "longcat")) { 912 cmd += " -v long"; 913 } 914 915 --argc; 916 ++argv; 917 while (argc-- > 0) { 918 cmd += " " + escape_arg(*argv++); 919 } 920 921 // No need for shell protocol with logcat, always disable for simplicity. 922 return send_shell_command(transport, serial, cmd, true); 923} 924 925static int backup(int argc, const char** argv) { 926 const char* filename = "./backup.ab"; 927 928 /* find, extract, and use any -f argument */ 929 for (int i = 1; i < argc; i++) { 930 if (!strcmp("-f", argv[i])) { 931 if (i == argc-1) { 932 fprintf(stderr, "adb: -f passed with no filename\n"); 933 return usage(); 934 } 935 filename = argv[i+1]; 936 for (int j = i+2; j <= argc; ) { 937 argv[i++] = argv[j++]; 938 } 939 argc -= 2; 940 argv[argc] = NULL; 941 } 942 } 943 944 /* bare "adb backup" or "adb backup -f filename" are not valid invocations */ 945 if (argc < 2) return usage(); 946 947 adb_unlink(filename); 948 mkdirs(filename); 949 int outFd = adb_creat(filename, 0640); 950 if (outFd < 0) { 951 fprintf(stderr, "adb: unable to open file %s\n", filename); 952 return -1; 953 } 954 955 std::string cmd = "backup:"; 956 --argc; 957 ++argv; 958 while (argc-- > 0) { 959 cmd += " " + escape_arg(*argv++); 960 } 961 962 D("backup. filename=%s cmd=%s", filename, cmd.c_str()); 963 std::string error; 964 int fd = adb_connect(cmd, &error); 965 if (fd < 0) { 966 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str()); 967 adb_close(outFd); 968 return -1; 969 } 970 971 printf("Now unlock your device and confirm the backup operation.\n"); 972 copy_to_file(fd, outFd); 973 974 adb_close(fd); 975 adb_close(outFd); 976 return 0; 977} 978 979static int restore(int argc, const char** argv) { 980 if (argc != 2) return usage(); 981 982 const char* filename = argv[1]; 983 int tarFd = adb_open(filename, O_RDONLY); 984 if (tarFd < 0) { 985 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno)); 986 return -1; 987 } 988 989 std::string error; 990 int fd = adb_connect("restore:", &error); 991 if (fd < 0) { 992 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str()); 993 adb_close(tarFd); 994 return -1; 995 } 996 997 printf("Now unlock your device and confirm the restore operation.\n"); 998 copy_to_file(tarFd, fd); 999 1000 adb_close(fd); 1001 adb_close(tarFd); 1002 return 0; 1003} 1004 1005/* <hint> may be: 1006 * - A simple product name 1007 * e.g., "sooner" 1008 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir 1009 * e.g., "out/target/product/sooner" 1010 * - An absolute path to the PRODUCT_OUT dir 1011 * e.g., "/src/device/out/target/product/sooner" 1012 * 1013 * Given <hint>, try to construct an absolute path to the 1014 * ANDROID_PRODUCT_OUT dir. 1015 */ 1016static std::string find_product_out_path(const std::string& hint) { 1017 if (hint.empty()) { 1018 return ""; 1019 } 1020 1021 // If it's already absolute, don't bother doing any work. 1022 if (adb_is_absolute_host_path(hint.c_str())) { 1023 return hint; 1024 } 1025 1026 // If there are any slashes in it, assume it's a relative path; 1027 // make it absolute. 1028 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) { 1029 std::string cwd; 1030 if (!getcwd(&cwd)) { 1031 fprintf(stderr, "adb: getcwd failed: %s\n", strerror(errno)); 1032 return ""; 1033 } 1034 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str()); 1035 } 1036 1037 // It's a string without any slashes. Try to do something with it. 1038 // 1039 // Try to find the root of the build tree, and build a PRODUCT_OUT 1040 // path from there. 1041 char* top = getenv("ANDROID_BUILD_TOP"); 1042 if (top == nullptr) { 1043 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n"); 1044 return ""; 1045 } 1046 1047 std::string path = top; 1048 path += OS_PATH_SEPARATOR_STR; 1049 path += "out"; 1050 path += OS_PATH_SEPARATOR_STR; 1051 path += "target"; 1052 path += OS_PATH_SEPARATOR_STR; 1053 path += "product"; 1054 path += OS_PATH_SEPARATOR_STR; 1055 path += hint; 1056 if (!directory_exists(path)) { 1057 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; " 1058 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str()); 1059 return ""; 1060 } 1061 return path; 1062} 1063 1064static void parse_push_pull_args(const char **arg, int narg, char const **path1, 1065 char const **path2, bool* show_progress, 1066 int *copy_attrs) { 1067 *show_progress = false; 1068 *copy_attrs = 0; 1069 1070 while (narg > 0) { 1071 if (!strcmp(*arg, "-p")) { 1072 *show_progress = true; 1073 } else if (!strcmp(*arg, "-a")) { 1074 *copy_attrs = 1; 1075 } else { 1076 break; 1077 } 1078 ++arg; 1079 --narg; 1080 } 1081 1082 if (narg > 0) { 1083 *path1 = *arg; 1084 ++arg; 1085 --narg; 1086 } 1087 1088 if (narg > 0) { 1089 *path2 = *arg; 1090 } 1091} 1092 1093static int adb_connect_command(const std::string& command) { 1094 std::string error; 1095 int fd = adb_connect(command, &error); 1096 if (fd < 0) { 1097 fprintf(stderr, "error: %s\n", error.c_str()); 1098 return 1; 1099 } 1100 read_and_dump(fd); 1101 adb_close(fd); 1102 return 0; 1103} 1104 1105static int adb_query_command(const std::string& command) { 1106 std::string result; 1107 std::string error; 1108 if (!adb_query(command, &result, &error)) { 1109 fprintf(stderr, "error: %s\n", error.c_str()); 1110 return 1; 1111 } 1112 printf("%s\n", result.c_str()); 1113 return 0; 1114} 1115 1116// Disallow stdin, stdout, and stderr. 1117static bool _is_valid_ack_reply_fd(const int ack_reply_fd) { 1118#ifdef _WIN32 1119 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd); 1120 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) && 1121 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) && 1122 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle); 1123#else 1124 return ack_reply_fd > 2; 1125#endif 1126} 1127 1128int adb_commandline(int argc, const char **argv) { 1129 int no_daemon = 0; 1130 int is_daemon = 0; 1131 int is_server = 0; 1132 int r; 1133 TransportType transport_type = kTransportAny; 1134 int ack_reply_fd = -1; 1135 1136 // If defined, this should be an absolute path to 1137 // the directory containing all of the various system images 1138 // for a particular product. If not defined, and the adb 1139 // command requires this information, then the user must 1140 // specify the path using "-p". 1141 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT"); 1142 if (ANDROID_PRODUCT_OUT != nullptr) { 1143 gProductOutPath = ANDROID_PRODUCT_OUT; 1144 } 1145 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint 1146 1147 /* Validate and assign the server port */ 1148 const char* server_port_str = getenv("ANDROID_ADB_SERVER_PORT"); 1149 int server_port = DEFAULT_ADB_PORT; 1150 if (server_port_str && strlen(server_port_str) > 0) { 1151 server_port = strtol(server_port_str, nullptr, 0); 1152 if (server_port <= 0 || server_port > 65535) { 1153 fprintf(stderr, 1154 "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65536. Got \"%s\"\n", 1155 server_port_str); 1156 return usage(); 1157 } 1158 } 1159 1160 // We need to check for -d and -e before we look at $ANDROID_SERIAL. 1161 const char* serial = nullptr; 1162 1163 while (argc > 0) { 1164 if (!strcmp(argv[0],"server")) { 1165 is_server = 1; 1166 } else if (!strcmp(argv[0],"nodaemon")) { 1167 no_daemon = 1; 1168 } else if (!strcmp(argv[0], "fork-server")) { 1169 /* this is a special flag used only when the ADB client launches the ADB Server */ 1170 is_daemon = 1; 1171 } else if (!strcmp(argv[0], "--reply-fd")) { 1172 if (argc < 2) return usage(); 1173 const char* reply_fd_str = argv[1]; 1174 argc--; 1175 argv++; 1176 ack_reply_fd = strtol(reply_fd_str, nullptr, 10); 1177 if (!_is_valid_ack_reply_fd(ack_reply_fd)) { 1178 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str); 1179 return usage(); 1180 } 1181 } else if (!strncmp(argv[0], "-p", 2)) { 1182 const char* product = nullptr; 1183 if (argv[0][2] == '\0') { 1184 if (argc < 2) return usage(); 1185 product = argv[1]; 1186 argc--; 1187 argv++; 1188 } else { 1189 product = argv[0] + 2; 1190 } 1191 gProductOutPath = find_product_out_path(product); 1192 if (gProductOutPath.empty()) { 1193 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product); 1194 return usage(); 1195 } 1196 } else if (argv[0][0]=='-' && argv[0][1]=='s') { 1197 if (isdigit(argv[0][2])) { 1198 serial = argv[0] + 2; 1199 } else { 1200 if (argc < 2 || argv[0][2] != '\0') return usage(); 1201 serial = argv[1]; 1202 argc--; 1203 argv++; 1204 } 1205 } else if (!strcmp(argv[0],"-d")) { 1206 transport_type = kTransportUsb; 1207 } else if (!strcmp(argv[0],"-e")) { 1208 transport_type = kTransportLocal; 1209 } else if (!strcmp(argv[0],"-a")) { 1210 gListenAll = 1; 1211 } else if (!strncmp(argv[0], "-H", 2)) { 1212 const char *hostname = NULL; 1213 if (argv[0][2] == '\0') { 1214 if (argc < 2) return usage(); 1215 hostname = argv[1]; 1216 argc--; 1217 argv++; 1218 } else { 1219 hostname = argv[0] + 2; 1220 } 1221 adb_set_tcp_name(hostname); 1222 1223 } else if (!strncmp(argv[0], "-P", 2)) { 1224 if (argv[0][2] == '\0') { 1225 if (argc < 2) return usage(); 1226 server_port_str = argv[1]; 1227 argc--; 1228 argv++; 1229 } else { 1230 server_port_str = argv[0] + 2; 1231 } 1232 if (strlen(server_port_str) > 0) { 1233 server_port = (int) strtol(server_port_str, NULL, 0); 1234 if (server_port <= 0 || server_port > 65535) { 1235 fprintf(stderr, 1236 "adb: port number must be a positive number less than 65536. Got \"%s\"\n", 1237 server_port_str); 1238 return usage(); 1239 } 1240 } else { 1241 fprintf(stderr, 1242 "adb: port number must be a positive number less than 65536. Got empty string.\n"); 1243 return usage(); 1244 } 1245 } else { 1246 /* out of recognized modifiers and flags */ 1247 break; 1248 } 1249 argc--; 1250 argv++; 1251 } 1252 1253 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL. 1254 if (transport_type == kTransportAny && serial == nullptr) { 1255 serial = getenv("ANDROID_SERIAL"); 1256 } 1257 1258 adb_set_transport(transport_type, serial); 1259 adb_set_tcp_specifics(server_port); 1260 1261 if (is_server) { 1262 if (no_daemon || is_daemon) { 1263 if (is_daemon && (ack_reply_fd == -1)) { 1264 fprintf(stderr, "reply fd for adb server to client communication not specified.\n"); 1265 return usage(); 1266 } 1267 r = adb_main(is_daemon, server_port, ack_reply_fd); 1268 } else { 1269 r = launch_server(server_port); 1270 } 1271 if (r) { 1272 fprintf(stderr,"* could not start server *\n"); 1273 } 1274 return r; 1275 } 1276 1277 if (argc == 0) { 1278 return usage(); 1279 } 1280 1281 /* handle wait-for-* prefix */ 1282 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) { 1283 const char* service = argv[0]; 1284 1285 if (!wait_for_device(service, transport_type, serial)) { 1286 return 1; 1287 } 1288 1289 // Allow a command to be run after wait-for-device, 1290 // e.g. 'adb wait-for-device shell'. 1291 if (argc == 1) { 1292 return 0; 1293 } 1294 1295 /* Fall through */ 1296 argc--; 1297 argv++; 1298 } 1299 1300 /* adb_connect() commands */ 1301 if (!strcmp(argv[0], "devices")) { 1302 const char *listopt; 1303 if (argc < 2) { 1304 listopt = ""; 1305 } else if (argc == 2 && !strcmp(argv[1], "-l")) { 1306 listopt = argv[1]; 1307 } else { 1308 fprintf(stderr, "Usage: adb devices [-l]\n"); 1309 return 1; 1310 } 1311 1312 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt); 1313 printf("List of devices attached\n"); 1314 return adb_query_command(query); 1315 } 1316 else if (!strcmp(argv[0], "connect")) { 1317 if (argc != 2) { 1318 fprintf(stderr, "Usage: adb connect <host>[:<port>]\n"); 1319 return 1; 1320 } 1321 1322 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]); 1323 return adb_query_command(query); 1324 } 1325 else if (!strcmp(argv[0], "disconnect")) { 1326 if (argc > 2) { 1327 fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n"); 1328 return 1; 1329 } 1330 1331 std::string query = android::base::StringPrintf("host:disconnect:%s", 1332 (argc == 2) ? argv[1] : ""); 1333 return adb_query_command(query); 1334 } 1335 else if (!strcmp(argv[0], "emu")) { 1336 return adb_send_emulator_command(argc, argv, serial); 1337 } 1338 else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) { 1339 char h = (argv[0][0] == 'h'); 1340 1341 FeatureSet features = GetFeatureSet(transport_type, serial); 1342 1343 bool use_shell_protocol = CanUseFeature(features, kFeatureShell2); 1344 if (!use_shell_protocol) { 1345 D("shell protocol not supported, using raw data transfer"); 1346 } else { 1347 D("using shell protocol"); 1348 } 1349 1350 // Parse shell-specific command-line options. 1351 // argv[0] is always "shell". 1352 --argc; 1353 ++argv; 1354 std::string shell_type_arg; 1355 while (argc) { 1356 if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) { 1357 if (!CanUseFeature(features, kFeatureShell2)) { 1358 fprintf(stderr, "error: target doesn't support PTY args -Tt\n"); 1359 return 1; 1360 } 1361 shell_type_arg = (argv[0][1] == 'T') ? kShellServiceArgRaw 1362 : kShellServiceArgPty; 1363 --argc; 1364 ++argv; 1365 } else if (!strcmp(argv[0], "-x")) { 1366 use_shell_protocol = false; 1367 --argc; 1368 ++argv; 1369 } else { 1370 break; 1371 } 1372 } 1373 1374 std::string command; 1375 if (argc) { 1376 // We don't escape here, just like ssh(1). http://b/20564385. 1377 command = android::base::Join( 1378 std::vector<const char*>(argv, argv + argc), ' '); 1379 } 1380 1381 if (h) { 1382 printf("\x1b[41;33m"); 1383 fflush(stdout); 1384 } 1385 1386 r = RemoteShell(use_shell_protocol, shell_type_arg, command); 1387 1388 if (h) { 1389 printf("\x1b[0m"); 1390 fflush(stdout); 1391 } 1392 1393 return r; 1394 } 1395 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) { 1396 int exec_in = !strcmp(argv[0], "exec-in"); 1397 1398 std::string cmd = "exec:"; 1399 cmd += argv[1]; 1400 argc -= 2; 1401 argv += 2; 1402 while (argc-- > 0) { 1403 cmd += " " + escape_arg(*argv++); 1404 } 1405 1406 std::string error; 1407 int fd = adb_connect(cmd, &error); 1408 if (fd < 0) { 1409 fprintf(stderr, "error: %s\n", error.c_str()); 1410 return -1; 1411 } 1412 1413 if (exec_in) { 1414 copy_to_file(STDIN_FILENO, fd); 1415 } else { 1416 copy_to_file(fd, STDOUT_FILENO); 1417 } 1418 1419 adb_close(fd); 1420 return 0; 1421 } 1422 else if (!strcmp(argv[0], "kill-server")) { 1423 std::string error; 1424 int fd = _adb_connect("host:kill", &error); 1425 if (fd == -2) { 1426 // Failed to make network connection to server. Don't output the 1427 // network error since that is expected. 1428 fprintf(stderr,"* server not running *\n"); 1429 // Successful exit code because the server is already "killed". 1430 return 0; 1431 } else if (fd == -1) { 1432 // Some other error. 1433 fprintf(stderr, "error: %s\n", error.c_str()); 1434 return 1; 1435 } else { 1436 // Successfully connected, kill command sent, okay status came back. 1437 // Server should exit() in a moment, if not already. 1438 adb_close(fd); 1439 return 0; 1440 } 1441 } 1442 else if (!strcmp(argv[0], "sideload")) { 1443 if (argc != 2) return usage(); 1444 if (adb_sideload_host(argv[1])) { 1445 return 1; 1446 } else { 1447 return 0; 1448 } 1449 } 1450 else if (!strcmp(argv[0], "tcpip") && argc > 1) { 1451 return adb_connect_command(android::base::StringPrintf("tcpip:%s", argv[1])); 1452 } 1453 else if (!strcmp(argv[0], "remount") || 1454 !strcmp(argv[0], "reboot") || 1455 !strcmp(argv[0], "reboot-bootloader") || 1456 !strcmp(argv[0], "usb") || 1457 !strcmp(argv[0], "root") || 1458 !strcmp(argv[0], "unroot") || 1459 !strcmp(argv[0], "disable-verity") || 1460 !strcmp(argv[0], "enable-verity")) { 1461 std::string command; 1462 if (!strcmp(argv[0], "reboot-bootloader")) { 1463 command = "reboot:bootloader"; 1464 } else if (argc > 1) { 1465 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]); 1466 } else { 1467 command = android::base::StringPrintf("%s:", argv[0]); 1468 } 1469 return adb_connect_command(command); 1470 } 1471 else if (!strcmp(argv[0], "bugreport")) { 1472 if (argc != 1) return usage(); 1473 // No need for shell protocol with bugreport, always disable for 1474 // simplicity. 1475 return send_shell_command(transport_type, serial, "bugreport", true); 1476 } 1477 else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) { 1478 bool reverse = !strcmp(argv[0], "reverse"); 1479 ++argv; 1480 --argc; 1481 if (argc < 1) return usage(); 1482 1483 // Determine the <host-prefix> for this command. 1484 std::string host_prefix; 1485 if (reverse) { 1486 host_prefix = "reverse"; 1487 } else { 1488 if (serial) { 1489 host_prefix = android::base::StringPrintf("host-serial:%s", serial); 1490 } else if (transport_type == kTransportUsb) { 1491 host_prefix = "host-usb"; 1492 } else if (transport_type == kTransportLocal) { 1493 host_prefix = "host-local"; 1494 } else { 1495 host_prefix = "host"; 1496 } 1497 } 1498 1499 std::string cmd; 1500 if (strcmp(argv[0], "--list") == 0) { 1501 if (argc != 1) return usage(); 1502 return adb_query_command(host_prefix + ":list-forward"); 1503 } else if (strcmp(argv[0], "--remove-all") == 0) { 1504 if (argc != 1) return usage(); 1505 cmd = host_prefix + ":killforward-all"; 1506 } else if (strcmp(argv[0], "--remove") == 0) { 1507 // forward --remove <local> 1508 if (argc != 2) return usage(); 1509 cmd = host_prefix + ":killforward:" + argv[1]; 1510 } else if (strcmp(argv[0], "--no-rebind") == 0) { 1511 // forward --no-rebind <local> <remote> 1512 if (argc != 3) return usage(); 1513 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2]; 1514 } else { 1515 // forward <local> <remote> 1516 if (argc != 2) return usage(); 1517 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1]; 1518 } 1519 1520 return adb_command(cmd) ? 0 : 1; 1521 } 1522 /* do_sync_*() commands */ 1523 else if (!strcmp(argv[0], "ls")) { 1524 if (argc != 2) return usage(); 1525 return do_sync_ls(argv[1]) ? 0 : 1; 1526 } 1527 else if (!strcmp(argv[0], "push")) { 1528 bool show_progress = false; 1529 int copy_attrs = 0; 1530 const char* lpath = NULL, *rpath = NULL; 1531 1532 parse_push_pull_args(&argv[1], argc - 1, &lpath, &rpath, &show_progress, ©_attrs); 1533 if (!lpath || !rpath || copy_attrs != 0) return usage(); 1534 return do_sync_push(lpath, rpath, show_progress) ? 0 : 1; 1535 } 1536 else if (!strcmp(argv[0], "pull")) { 1537 bool show_progress = false; 1538 int copy_attrs = 0; 1539 const char* rpath = NULL, *lpath = "."; 1540 1541 parse_push_pull_args(&argv[1], argc - 1, &rpath, &lpath, &show_progress, ©_attrs); 1542 if (!rpath) return usage(); 1543 return do_sync_pull(rpath, lpath, show_progress, copy_attrs) ? 0 : 1; 1544 } 1545 else if (!strcmp(argv[0], "install")) { 1546 if (argc < 2) return usage(); 1547 return install_app(transport_type, serial, argc, argv); 1548 } 1549 else if (!strcmp(argv[0], "install-multiple")) { 1550 if (argc < 2) return usage(); 1551 return install_multiple_app(transport_type, serial, argc, argv); 1552 } 1553 else if (!strcmp(argv[0], "uninstall")) { 1554 if (argc < 2) return usage(); 1555 return uninstall_app(transport_type, serial, argc, argv); 1556 } 1557 else if (!strcmp(argv[0], "sync")) { 1558 std::string src; 1559 bool list_only = false; 1560 if (argc < 2) { 1561 // No local path was specified. 1562 src = ""; 1563 } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) { 1564 list_only = true; 1565 if (argc == 3) { 1566 src = argv[2]; 1567 } else { 1568 src = ""; 1569 } 1570 } else if (argc == 2) { 1571 // A local path or "android"/"data" arg was specified. 1572 src = argv[1]; 1573 } else { 1574 return usage(); 1575 } 1576 1577 if (src != "" && 1578 src != "system" && src != "data" && src != "vendor" && src != "oem") { 1579 return usage(); 1580 } 1581 1582 std::string system_src_path = product_file("system"); 1583 std::string data_src_path = product_file("data"); 1584 std::string vendor_src_path = product_file("vendor"); 1585 std::string oem_src_path = product_file("oem"); 1586 1587 bool okay = true; 1588 if (okay && (src.empty() || src == "system")) { 1589 okay = do_sync_sync(system_src_path, "/system", list_only); 1590 } 1591 if (okay && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) { 1592 okay = do_sync_sync(vendor_src_path, "/vendor", list_only); 1593 } 1594 if (okay && (src.empty() || src == "oem") && directory_exists(oem_src_path)) { 1595 okay = do_sync_sync(oem_src_path, "/oem", list_only); 1596 } 1597 if (okay && (src.empty() || src == "data")) { 1598 okay = do_sync_sync(data_src_path, "/data", list_only); 1599 } 1600 return okay ? 0 : 1; 1601 } 1602 /* passthrough commands */ 1603 else if (!strcmp(argv[0],"get-state") || 1604 !strcmp(argv[0],"get-serialno") || 1605 !strcmp(argv[0],"get-devpath")) 1606 { 1607 return adb_query_command(format_host_command(argv[0], transport_type, serial)); 1608 } 1609 /* other commands */ 1610 else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) { 1611 return logcat(transport_type, serial, argc, argv); 1612 } 1613 else if (!strcmp(argv[0],"ppp")) { 1614 return ppp(argc, argv); 1615 } 1616 else if (!strcmp(argv[0], "start-server")) { 1617 std::string error; 1618 const int result = adb_connect("host:start-server", &error); 1619 if (result < 0) { 1620 fprintf(stderr, "error: %s\n", error.c_str()); 1621 } 1622 return result; 1623 } 1624 else if (!strcmp(argv[0], "backup")) { 1625 return backup(argc, argv); 1626 } 1627 else if (!strcmp(argv[0], "restore")) { 1628 return restore(argc, argv); 1629 } 1630 else if (!strcmp(argv[0], "keygen")) { 1631 if (argc < 2) return usage(); 1632 // Always print key generation information for keygen command. 1633 adb_trace_enable(AUTH); 1634 return adb_auth_keygen(argv[1]); 1635 } 1636 else if (!strcmp(argv[0], "jdwp")) { 1637 return adb_connect_command("jdwp"); 1638 } 1639 /* "adb /?" is a common idiom under Windows */ 1640 else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) { 1641 help(); 1642 return 0; 1643 } 1644 else if (!strcmp(argv[0], "version")) { 1645 fprintf(stdout, "%s", adb_version().c_str()); 1646 return 0; 1647 } 1648 else if (!strcmp(argv[0], "features")) { 1649 // Only list the features common to both the adb client and the device. 1650 FeatureSet features = GetFeatureSet(transport_type, serial); 1651 for (const std::string& name : features) { 1652 if (CanUseFeature(features, name)) { 1653 printf("%s\n", name.c_str()); 1654 } 1655 } 1656 return 0; 1657 } 1658 1659 usage(); 1660 return 1; 1661} 1662 1663static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) { 1664 std::string cmd = "pm"; 1665 1666 while (argc-- > 0) { 1667 cmd += " " + escape_arg(*argv++); 1668 } 1669 1670 // TODO(dpursell): add command-line arguments to install/uninstall to 1671 // manually disable shell protocol if needed. 1672 return send_shell_command(transport, serial, cmd, false); 1673} 1674 1675static int uninstall_app(TransportType transport, const char* serial, int argc, const char** argv) { 1676 /* if the user choose the -k option, we refuse to do it until devices are 1677 out with the option to uninstall the remaining data somehow (adb/ui) */ 1678 if (argc == 3 && strcmp(argv[1], "-k") == 0) 1679 { 1680 printf( 1681 "The -k option uninstalls the application while retaining the data/cache.\n" 1682 "At the moment, there is no way to remove the remaining data.\n" 1683 "You will have to reinstall the application with the same signature, and fully uninstall it.\n" 1684 "If you truly wish to continue, execute 'adb shell pm uninstall -k %s'\n", argv[2]); 1685 return -1; 1686 } 1687 1688 /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */ 1689 return pm_command(transport, serial, argc, argv); 1690} 1691 1692static int delete_file(TransportType transport, const char* serial, const std::string& filename) { 1693 std::string cmd = "rm -f " + escape_arg(filename); 1694 return send_shell_command(transport, serial, cmd, false); 1695} 1696 1697static int install_app(TransportType transport, const char* serial, int argc, const char** argv) { 1698 static const char *const DATA_DEST = "/data/local/tmp/%s"; 1699 static const char *const SD_DEST = "/sdcard/tmp/%s"; 1700 const char* where = DATA_DEST; 1701 int i; 1702 struct stat sb; 1703 1704 for (i = 1; i < argc; i++) { 1705 if (!strcmp(argv[i], "-s")) { 1706 where = SD_DEST; 1707 } 1708 } 1709 1710 // Find last APK argument. 1711 // All other arguments passed through verbatim. 1712 int last_apk = -1; 1713 for (i = argc - 1; i >= 0; i--) { 1714 const char* file = argv[i]; 1715 const char* dot = strrchr(file, '.'); 1716 if (dot && !strcasecmp(dot, ".apk")) { 1717 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) { 1718 fprintf(stderr, "Invalid APK file: %s\n", file); 1719 return -1; 1720 } 1721 1722 last_apk = i; 1723 break; 1724 } 1725 } 1726 1727 if (last_apk == -1) { 1728 fprintf(stderr, "Missing APK file\n"); 1729 return -1; 1730 } 1731 1732 int result = -1; 1733 const char* apk_file = argv[last_apk]; 1734 std::string apk_dest = android::base::StringPrintf(where, adb_basename(apk_file).c_str()); 1735 if (!do_sync_push(apk_file, apk_dest.c_str(), false)) goto cleanup_apk; 1736 argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */ 1737 result = pm_command(transport, serial, argc, argv); 1738 1739cleanup_apk: 1740 delete_file(transport, serial, apk_dest); 1741 return result; 1742} 1743 1744static int install_multiple_app(TransportType transport, const char* serial, int argc, 1745 const char** argv) 1746{ 1747 int i; 1748 struct stat sb; 1749 uint64_t total_size = 0; 1750 1751 // Find all APK arguments starting at end. 1752 // All other arguments passed through verbatim. 1753 int first_apk = -1; 1754 for (i = argc - 1; i >= 0; i--) { 1755 const char* file = argv[i]; 1756 const char* dot = strrchr(file, '.'); 1757 if (dot && !strcasecmp(dot, ".apk")) { 1758 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) { 1759 fprintf(stderr, "Invalid APK file: %s\n", file); 1760 return -1; 1761 } 1762 1763 total_size += sb.st_size; 1764 first_apk = i; 1765 } else { 1766 break; 1767 } 1768 } 1769 1770 if (first_apk == -1) { 1771 fprintf(stderr, "Missing APK file\n"); 1772 return 1; 1773 } 1774 1775 std::string cmd = android::base::StringPrintf("exec:pm install-create -S %" PRIu64, total_size); 1776 for (i = 1; i < first_apk; i++) { 1777 cmd += " " + escape_arg(argv[i]); 1778 } 1779 1780 // Create install session 1781 std::string error; 1782 int fd = adb_connect(cmd, &error); 1783 if (fd < 0) { 1784 fprintf(stderr, "Connect error for create: %s\n", error.c_str()); 1785 return -1; 1786 } 1787 char buf[BUFSIZ]; 1788 read_status_line(fd, buf, sizeof(buf)); 1789 adb_close(fd); 1790 1791 int session_id = -1; 1792 if (!strncmp("Success", buf, 7)) { 1793 char* start = strrchr(buf, '['); 1794 char* end = strrchr(buf, ']'); 1795 if (start && end) { 1796 *end = '\0'; 1797 session_id = strtol(start + 1, NULL, 10); 1798 } 1799 } 1800 if (session_id < 0) { 1801 fprintf(stderr, "Failed to create session\n"); 1802 fputs(buf, stderr); 1803 return -1; 1804 } 1805 1806 // Valid session, now stream the APKs 1807 int success = 1; 1808 for (i = first_apk; i < argc; i++) { 1809 const char* file = argv[i]; 1810 if (stat(file, &sb) == -1) { 1811 fprintf(stderr, "Failed to stat %s\n", file); 1812 success = 0; 1813 goto finalize_session; 1814 } 1815 1816 std::string cmd = android::base::StringPrintf( 1817 "exec:pm install-write -S %" PRIu64 " %d %d_%s -", 1818 static_cast<uint64_t>(sb.st_size), session_id, i, adb_basename(file).c_str()); 1819 1820 int localFd = adb_open(file, O_RDONLY); 1821 if (localFd < 0) { 1822 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno)); 1823 success = 0; 1824 goto finalize_session; 1825 } 1826 1827 std::string error; 1828 int remoteFd = adb_connect(cmd, &error); 1829 if (remoteFd < 0) { 1830 fprintf(stderr, "Connect error for write: %s\n", error.c_str()); 1831 adb_close(localFd); 1832 success = 0; 1833 goto finalize_session; 1834 } 1835 1836 copy_to_file(localFd, remoteFd); 1837 read_status_line(remoteFd, buf, sizeof(buf)); 1838 1839 adb_close(localFd); 1840 adb_close(remoteFd); 1841 1842 if (strncmp("Success", buf, 7)) { 1843 fprintf(stderr, "Failed to write %s\n", file); 1844 fputs(buf, stderr); 1845 success = 0; 1846 goto finalize_session; 1847 } 1848 } 1849 1850finalize_session: 1851 // Commit session if we streamed everything okay; otherwise abandon 1852 std::string service = 1853 android::base::StringPrintf("exec:pm install-%s %d", 1854 success ? "commit" : "abandon", session_id); 1855 fd = adb_connect(service, &error); 1856 if (fd < 0) { 1857 fprintf(stderr, "Connect error for finalize: %s\n", error.c_str()); 1858 return -1; 1859 } 1860 read_status_line(fd, buf, sizeof(buf)); 1861 adb_close(fd); 1862 1863 if (!strncmp("Success", buf, 7)) { 1864 fputs(buf, stderr); 1865 return 0; 1866 } else { 1867 fprintf(stderr, "Failed to finalize session\n"); 1868 fputs(buf, stderr); 1869 return -1; 1870 } 1871} 1872