blob: ed6693ce75e153f552f9cc9aacb1e7c264410723 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Dan Albert33134262015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
Dan Albert76649012015-02-24 15:51:19 -080021#include <assert.h>
22#include <ctype.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023#include <errno.h>
Elliott Hughes2940ccf2015-04-17 14:07:52 -070024#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <limits.h>
26#include <stdarg.h>
Dan Albert76649012015-02-24 15:51:19 -080027#include <stdint.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080031#include <sys/stat.h>
Dan Albert76649012015-02-24 15:51:19 -080032#include <sys/types.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080033
David Pursell606835a2015-09-08 17:17:02 -070034#include <memory>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070035#include <string>
Elliott Hughesdbe91ee2016-11-15 12:37:32 -080036#include <thread>
Josh Gao05786772015-10-30 16:57:19 -070037#include <vector>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070038
Elliott Hughese8b663f2016-05-26 22:43:19 -070039#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/logging.h>
Tao Wu135f4ab2016-09-16 13:01:24 -070041#include <android-base/parseint.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070044
Yabin Cuid325e862014-11-17 14:48:25 -080045#if !defined(_WIN32)
Josh Gao8dcdb572015-10-23 15:03:31 -070046#include <signal.h>
Elliott Hughes0fbf9612015-11-04 13:07:47 -080047#include <sys/ioctl.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080048#include <termios.h>
Dan Albert76649012015-02-24 15:51:19 -080049#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050#endif
51
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080052#include "adb.h"
Nick Kralevichbea3f9c2014-11-13 15:17:29 -080053#include "adb_auth.h"
Dan Albertcc731cc2015-02-24 21:26:58 -080054#include "adb_client.h"
55#include "adb_io.h"
Josh Gao924d35a2016-08-30 15:39:25 -070056#include "adb_unique_fd.h"
Elliott Hughes58305772015-04-17 13:57:15 -070057#include "adb_utils.h"
Felipe Leme698e0652016-07-19 17:07:22 -070058#include "bugreport.h"
59#include "commandline.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080060#include "file_sync_service.h"
David Pursell70ef7b42015-09-30 13:35:42 -070061#include "services.h"
David Pursell606835a2015-09-08 17:17:02 -070062#include "shell_service.h"
Josh Gao4602adb2016-11-15 18:55:47 -080063#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064
Elliott Hughes3bd73c12015-05-05 13:10:43 -070065static int install_app(TransportType t, const char* serial, int argc, const char** argv);
66static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv);
67static int uninstall_app(TransportType t, const char* serial, int argc, const char** argv);
Todd Kennedy6fa848a2015-11-03 16:53:08 -080068static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
69static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080070
Josh Gaob7b1edf2015-11-11 17:56:12 -080071static auto& gProductOutPath = *new std::string();
Matt Gumbeld7b33082012-11-14 10:16:17 -080072extern int gListenAll;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080073
Felipe Leme0d4f0502016-07-26 12:14:39 -070074DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
75
Elliott Hughes58305772015-04-17 13:57:15 -070076static std::string product_file(const char *extra) {
77 if (gProductOutPath.empty()) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080078 fprintf(stderr, "adb: Product directory not specified; "
79 "use -p or define ANDROID_PRODUCT_OUT\n");
80 exit(1);
81 }
82
Elliott Hughes58305772015-04-17 13:57:15 -070083 return android::base::StringPrintf("%s%s%s",
84 gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080085}
86
Elliott Hughes58305772015-04-17 13:57:15 -070087static void help() {
Elliott Hughes4bf9bc12016-09-28 15:25:47 -070088 fprintf(stdout, "%s\n", adb_version().c_str());
Felipe Lemeb3239722016-07-29 17:57:00 -070089 // clang-format off
Elliott Hughes4bf9bc12016-09-28 15:25:47 -070090 fprintf(stdout,
91 "global options:\n"
92 " -a listen on all network interfaces, not just localhost\n"
93 " -d use USB device (error if multiple devices connected)\n"
Elliott Hughes83ab5c22017-01-13 16:58:25 -080094 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -070095 " -s SERIAL\n"
Elliott Hughes83ab5c22017-01-13 16:58:25 -080096 " use device with given serial number (overrides $ANDROID_SERIAL)\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -070097 " -p PRODUCT\n"
98 " name or path ('angler'/'out/target/product/angler');\n"
99 " default $ANDROID_PRODUCT_OUT\n"
100 " -H name of adb server host [default=localhost]\n"
101 " -P port of adb server [default=5037]\n"
102 " -L SOCKET listen on given socket for adb server [default=tcp:localhost:5037]\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800103 "\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700104 "general commands:\n"
105 " devices [-l] list connected devices (-l for long output)\n"
106 " help show this help message\n"
107 " version show version num\n"
Elliott Hughes7e067cf2015-06-12 14:26:29 -0700108 "\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800109 "networking:\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700110 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
111 " disconnect [HOST[:PORT]]\n"
112 " disconnect from given TCP/IP device [default port=5555], or all\n"
113 " forward --list list all forward socket connections\n"
114 " forward [--no-rebind] LOCAL REMOTE\n"
115 " forward socket connection using:\n"
116 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
117 " localabstract:<unix domain socket name>\n"
118 " localreserved:<unix domain socket name>\n"
119 " localfilesystem:<unix domain socket name>\n"
120 " dev:<character device name>\n"
121 " jdwp:<process pid> (remote only)\n"
122 " forward --remove LOCAL remove specific forward socket connection\n"
123 " forward --remove-all remove all forward socket connections\n"
124 " ppp TTY [PARAMETER...] run PPP over USB\n"
125 " reverse --list list all reverse socket connections from device\n"
126 " reverse [--no-rebind] REMOTE LOCAL\n"
127 " reverse socket connection using:\n"
128 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
129 " localabstract:<unix domain socket name>\n"
130 " localreserved:<unix domain socket name>\n"
131 " localfilesystem:<unix domain socket name>\n"
132 " reverse --remove REMOTE remove specific reverse socket connection\n"
133 " reverse --remove-all remove all reverse socket connections from device\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800134 "\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700135 "file transfer:\n"
136 " push LOCAL... REMOTE\n"
137 " copy local files/directories to device\n"
138 " pull [-a] REMOTE... LOCAL\n"
139 " copy files/dirs from device\n"
140 " -a: preserve file timestamp and mode\n"
141 " sync [DIR]\n"
142 " copy all changed files to device; if DIR is \"system\", \"vendor\", \"oem\",\n"
143 " or \"data\", only sync that partition (default all)\n"
144 " -l: list but don't copy\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800145 "\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700146 "shell:\n"
147 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
148 " run remote shell command (interactive shell if no command given)\n"
149 " -e: choose escape character, or \"none\"; default '~'\n"
150 " -n: don't read from stdin\n"
151 " -T: disable PTY allocation\n"
152 " -t: force PTY allocation\n"
153 " -x: disable remote exit codes and stdout/stderr separation\n"
154 " emu COMMAND run emulator console command\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800155 "\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700156 "app installation:\n"
157 " install [-lrtsdg] PACKAGE\n"
158 " install-multiple [-lrtsdpg] PACKAGE...\n"
159 " push package(s) to the device and install them\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 (debuggable packages only)\n"
165 " -p: partial application install (install-multiple only)\n"
166 " -g: grant all runtime permissions\n"
167 " uninstall [-k] PACKAGE\n"
168 " remove this app package from the device\n"
169 " '-k': keep the data and cache directories\n"
170 "\n"
171 "backup/restore:\n"
Johan Toras Halsetheca1b3b2017-04-11 19:15:17 +0100172 " to show usage run \"adb shell bu help\"\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700173 "\n"
174 "debugging:\n"
175 " bugreport [PATH]\n"
176 " write bugreport to given PATH [default=bugreport.zip];\n"
177 " if PATH is a directory, the bug report is saved in that directory.\n"
178 " devices that don't support zipped bug reports output to stdout.\n"
179 " jdwp list pids of processes hosting a JDWP transport\n"
180 " logcat show device log (logcat --help for more)\n"
181 "\n"
182 "security:\n"
183 " disable-verity disable dm-verity checking on userdebug builds\n"
184 " enable-verity re-enable dm-verity checking on userdebug builds\n"
185 " keygen FILE\n"
186 " generate adb public/private key; private key stored in FILE,\n"
187 " public key stored in FILE.pub (existing files overwritten)\n"
188 "\n"
189 "scripting:\n"
190 " wait-for[-TRANSPORT]-STATE\n"
191 " wait for device to be in the given state\n"
192 " State: device, recovery, sideload, or bootloader\n"
193 " Transport: usb, local, or any [default=any]\n"
194 " get-state print offline | bootloader | device\n"
195 " get-serialno print <serial-number>\n"
196 " get-devpath print <device-path>\n"
197 " remount\n"
198 " remount /system, /vendor, and /oem partitions read-write\n"
199 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
200 " reboot the device; defaults to booting system image but\n"
201 " supports bootloader and recovery too. sideload reboots\n"
202 " into recovery and automatically starts sideload mode,\n"
203 " sideload-auto-reboot is the same but reboots after sideloading.\n"
204 " sideload OTAPACKAGE sideload the given full OTA package\n"
205 " root restart adbd with root permissions\n"
206 " unroot restart adbd without root permissions\n"
207 " usb restart adb server listening on USB\n"
208 " tcpip PORT restart adb server listening on TCP on PORT\n"
Timcd643152010-02-16 20:18:29 +0000209 "\n"
Yabin Cui1f4ec192016-04-05 13:50:44 -0700210 "internal debugging:\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700211 " start-server ensure that there is a server running\n"
212 " kill-server kill the server if it is running\n"
213 " reconnect kick connection from host side to force reconnect\n"
214 " reconnect device kick connection from device side to force reconnect\n"
215 "\n"
Elliott Hughes7e067cf2015-06-12 14:26:29 -0700216 "environment variables:\n"
Elliott Hughes4bf9bc12016-09-28 15:25:47 -0700217 " $ADB_TRACE\n"
218 " comma-separated list of debug info to log:\n"
219 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
220 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
221 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
222 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n");
Felipe Lemeb3239722016-07-29 17:57:00 -0700223 // clang-format on
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800224}
225
Yabin Cuid325e862014-11-17 14:48:25 -0800226#if defined(_WIN32)
227
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700228// Implemented in sysdeps_win32.cpp.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800229void stdin_raw_init();
230void stdin_raw_restore();
Yabin Cuid325e862014-11-17 14:48:25 -0800231
232#else
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100233static termios g_saved_terminal_state;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800235static void stdin_raw_init() {
236 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800237
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100238 termios tio;
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800239 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100241 cfmakeraw(&tio);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100243 // No timeout but request at least one character per read.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800244 tio.c_cc[VTIME] = 0;
245 tio.c_cc[VMIN] = 1;
246
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800247 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248}
249
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800250static void stdin_raw_restore() {
251 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800252}
253#endif
254
David Pursell606835a2015-09-08 17:17:02 -0700255// Reads from |fd| and prints received data. If |use_shell_protocol| is true
256// this expects that incoming data will use the shell protocol, in which case
257// stdout/stderr are routed independently and the remote exit code will be
258// returned.
Felipe Leme0d4f0502016-07-26 12:14:39 -0700259// if |callback| is non-null, stdout/stderr output will be handled by it.
260int read_and_dump(int fd, bool use_shell_protocol = false,
261 StandardStreamsCallbackInterface* callback = &DEFAULT_STANDARD_STREAMS_CALLBACK) {
David Pursell606835a2015-09-08 17:17:02 -0700262 int exit_code = 0;
Felipe Lemed1dd1252016-06-06 16:05:36 -0700263 if (fd < 0) return exit_code;
264
David Pursell606835a2015-09-08 17:17:02 -0700265 std::unique_ptr<ShellProtocol> protocol;
266 int length = 0;
David Pursell606835a2015-09-08 17:17:02 -0700267
268 char raw_buffer[BUFSIZ];
269 char* buffer_ptr = raw_buffer;
270 if (use_shell_protocol) {
271 protocol.reset(new ShellProtocol(fd));
272 if (!protocol) {
273 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
274 return 1;
275 }
276 buffer_ptr = protocol->data();
277 }
278
Felipe Lemed1dd1252016-06-06 16:05:36 -0700279 while (true) {
David Pursell606835a2015-09-08 17:17:02 -0700280 if (use_shell_protocol) {
281 if (!protocol->Read()) {
282 break;
283 }
Felipe Leme0d4f0502016-07-26 12:14:39 -0700284 length = protocol->data_length();
David Pursell606835a2015-09-08 17:17:02 -0700285 switch (protocol->id()) {
286 case ShellProtocol::kIdStdout:
Felipe Leme0d4f0502016-07-26 12:14:39 -0700287 callback->OnStdout(buffer_ptr, length);
David Pursell606835a2015-09-08 17:17:02 -0700288 break;
289 case ShellProtocol::kIdStderr:
Felipe Leme0d4f0502016-07-26 12:14:39 -0700290 callback->OnStderr(buffer_ptr, length);
David Pursell606835a2015-09-08 17:17:02 -0700291 break;
292 case ShellProtocol::kIdExit:
293 exit_code = protocol->data()[0];
294 continue;
295 default:
296 continue;
297 }
298 length = protocol->data_length();
299 } else {
300 D("read_and_dump(): pre adb_read(fd=%d)", fd);
301 length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
302 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd, length);
303 if (length <= 0) {
304 break;
305 }
Felipe Leme0d4f0502016-07-26 12:14:39 -0700306 callback->OnStdout(buffer_ptr, length);
Felipe Leme44a42672016-04-01 17:43:27 -0700307 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800308 }
David Pursell606835a2015-09-08 17:17:02 -0700309
Felipe Leme0d4f0502016-07-26 12:14:39 -0700310 return callback->Done(exit_code);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800311}
312
Jeff Sharkey960df972014-06-09 17:30:57 -0700313static void read_status_line(int fd, char* buf, size_t count)
314{
315 count--;
316 while (count > 0) {
317 int len = adb_read(fd, buf, count);
Elliott Hughes8fcd8bc2015-08-25 10:59:45 -0700318 if (len <= 0) {
Jeff Sharkey960df972014-06-09 17:30:57 -0700319 break;
320 }
321
322 buf += len;
323 count -= len;
324 }
325 *buf = '\0';
326}
327
Christopher Tatec42f1bb2016-07-06 13:22:22 -0700328static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700329 if (inFd == STDIN_FILENO) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800330 stdin_raw_init();
Spencer Lowb7dfb792015-05-22 16:48:31 -0700331#ifdef _WIN32
332 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
333 if (old_stdin_mode == -1) {
334 fatal_errno("could not set stdin to binary");
335 }
336#endif
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700337 }
Yabin Cuid325e862014-11-17 14:48:25 -0800338
Spencer Lowb7dfb792015-05-22 16:48:31 -0700339#ifdef _WIN32
340 if (outFd == STDOUT_FILENO) {
341 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
342 if (old_stdout_mode == -1) {
343 fatal_errno("could not set stdout to binary");
344 }
345 }
346#endif
Christopher Tatec42f1bb2016-07-06 13:22:22 -0700347}
348
349static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
350 if (inFd == STDIN_FILENO) {
351 stdin_raw_restore();
352#ifdef _WIN32
353 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
354 fatal_errno("could not restore stdin mode");
355 }
356#endif
357 }
358
359#ifdef _WIN32
360 if (outFd == STDOUT_FILENO) {
361 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
362 fatal_errno("could not restore stdout mode");
363 }
364 }
365#endif
366}
367
368static void copy_to_file(int inFd, int outFd) {
369 const size_t BUFSIZE = 32 * 1024;
370 char* buf = (char*) malloc(BUFSIZE);
371 if (buf == nullptr) fatal("couldn't allocate buffer for copy_to_file");
372 int len;
373 long total = 0;
374 int old_stdin_mode = -1;
375 int old_stdout_mode = -1;
376
377 D("copy_to_file(%d -> %d)", inFd, outFd);
378
379 stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowb7dfb792015-05-22 16:48:31 -0700380
Elliott Hughesa7090b92015-04-17 17:03:59 -0700381 while (true) {
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700382 if (inFd == STDIN_FILENO) {
383 len = unix_read(inFd, buf, BUFSIZE);
384 } else {
385 len = adb_read(inFd, buf, BUFSIZE);
386 }
Christopher Tated2f54152011-04-21 12:53:28 -0700387 if (len == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700388 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tated2f54152011-04-21 12:53:28 -0700389 break;
390 }
391 if (len < 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700392 D("copy_to_file(): read failed: %s", strerror(errno));
Christopher Tated2f54152011-04-21 12:53:28 -0700393 break;
394 }
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700395 if (outFd == STDOUT_FILENO) {
396 fwrite(buf, 1, len, stdout);
397 fflush(stdout);
398 } else {
399 adb_write(outFd, buf, len);
400 }
Christopher Tatec9cd3b92011-06-01 17:56:23 -0700401 total += len;
Christopher Tated2f54152011-04-21 12:53:28 -0700402 }
Yabin Cuid325e862014-11-17 14:48:25 -0800403
Christopher Tatec42f1bb2016-07-06 13:22:22 -0700404 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowb7dfb792015-05-22 16:48:31 -0700405
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700406 D("copy_to_file() finished after %lu bytes", total);
Christopher Tate5b811fa2011-06-10 11:38:37 -0700407 free(buf);
Christopher Tated2f54152011-04-21 12:53:28 -0700408}
409
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800410static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800411 // Old devices can't handle window size changes.
412 if (shell == nullptr) return;
413
Spencer Low2e02dc62015-11-07 17:34:39 -0800414#if defined(_WIN32)
415 struct winsize {
416 unsigned short ws_row;
417 unsigned short ws_col;
418 unsigned short ws_xpixel;
419 unsigned short ws_ypixel;
420 };
421#endif
422
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800423 winsize ws;
Spencer Low2e02dc62015-11-07 17:34:39 -0800424
425#if defined(_WIN32)
426 // If stdout is redirected to a non-console, we won't be able to get the
427 // console size, but that makes sense.
428 const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
429 if (intptr_handle == -1) return;
430
431 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
432
433 CONSOLE_SCREEN_BUFFER_INFO info;
434 memset(&info, 0, sizeof(info));
435 if (!GetConsoleScreenBufferInfo(handle, &info)) return;
436
437 memset(&ws, 0, sizeof(ws));
438 // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
439 ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
440 // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
441 // than the window, in which case we should use the width of the buffer.
442 ws.ws_col = info.dwSize.X;
443#else
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800444 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
Spencer Low2e02dc62015-11-07 17:34:39 -0800445#endif
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800446
447 // Send the new window size as human-readable ASCII for debugging convenience.
448 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
449 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
450 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800451}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452
David Pursell606835a2015-09-08 17:17:02 -0700453// Used to pass multiple values to the stdin read thread.
454struct StdinReadArgs {
455 int stdin_fd, write_fd;
David Pursell1ed57f02015-10-06 15:30:03 -0700456 bool raw_stdin;
David Pursell606835a2015-09-08 17:17:02 -0700457 std::unique_ptr<ShellProtocol> protocol;
Elliott Hughes28416d62015-11-04 13:36:32 -0800458 char escape_char;
David Pursell606835a2015-09-08 17:17:02 -0700459};
460
David Pursell606835a2015-09-08 17:17:02 -0700461// Loops to read from stdin and push the data to the given FD.
462// The argument should be a pointer to a StdinReadArgs object. This function
463// will take ownership of the object and delete it when finished.
Josh Gaod9db09c2016-02-12 14:31:15 -0800464static void stdin_read_thread_loop(void* x) {
David Pursell606835a2015-09-08 17:17:02 -0700465 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800467#if !defined(_WIN32)
468 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gao8dcdb572015-10-23 15:03:31 -0700469 sigset_t sigset;
470 sigemptyset(&sigset);
471 sigaddset(&sigset, SIGTTIN);
472 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
473#endif
474
Spencer Low2e02dc62015-11-07 17:34:39 -0800475#if defined(_WIN32)
476 // _get_interesting_input_record_uncached() causes unix_read_interruptible()
477 // to return -1 with errno == EINTR if the window size changes.
478#else
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800479 // Unblock SIGWINCH for this thread, so our read(2) below will be
480 // interrupted if the window size changes.
481 sigset_t mask;
482 sigemptyset(&mask);
483 sigaddset(&mask, SIGWINCH);
484 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
485#endif
486
487 // Set up the initial window size.
488 send_window_size_change(args->stdin_fd, args->protocol);
489
Elliott Hughes28416d62015-11-04 13:36:32 -0800490 char raw_buffer[BUFSIZ];
David Pursell606835a2015-09-08 17:17:02 -0700491 char* buffer_ptr = raw_buffer;
492 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800493 if (args->protocol != nullptr) {
David Pursell606835a2015-09-08 17:17:02 -0700494 buffer_ptr = args->protocol->data();
495 buffer_size = args->protocol->data_capacity();
496 }
497
Elliott Hughes28416d62015-11-04 13:36:32 -0800498 // If we need to parse escape sequences, make life easy.
499 if (args->raw_stdin && args->escape_char != '\0') {
500 buffer_size = 1;
501 }
502
503 enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
504 EscapeState state = kStartOfLine;
505
Elliott Hughesaa245492015-08-03 10:38:08 -0700506 while (true) {
Spencer Low2e02dc62015-11-07 17:34:39 -0800507 // Use unix_read_interruptible() rather than adb_read() for stdin.
508 D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
509 int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
510 buffer_size);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800511 if (r == -1 && errno == EINTR) {
512 send_window_size_change(args->stdin_fd, args->protocol);
513 continue;
514 }
Spencer Low2e02dc62015-11-07 17:34:39 -0800515 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
David Pursell1ed57f02015-10-06 15:30:03 -0700516 if (r <= 0) {
517 // Only devices using the shell protocol know to close subprocess
518 // stdin. For older devices we want to just leave the connection
519 // open, otherwise an unpredictable amount of return data could
520 // be lost due to the FD closing before all data has been received.
521 if (args->protocol) {
522 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
523 }
524 break;
525 }
Elliott Hughes28416d62015-11-04 13:36:32 -0800526 // If we made stdin raw, check input for escape sequences. In
David Pursell1ed57f02015-10-06 15:30:03 -0700527 // this situation signals like Ctrl+C are sent remotely rather than
528 // interpreted locally so this provides an emergency out if the remote
529 // process starts ignoring the signal. SSH also does this, see the
530 // "escape characters" section on the ssh man page for more info.
Elliott Hughes28416d62015-11-04 13:36:32 -0800531 if (args->raw_stdin && args->escape_char != '\0') {
532 char ch = buffer_ptr[0];
533 if (ch == args->escape_char) {
534 if (state == kStartOfLine) {
535 state = kInEscape;
536 // Swallow the escape character.
537 continue;
538 } else {
539 state = kMidFlow;
540 }
541 } else {
542 if (state == kInEscape) {
543 if (ch == '.') {
544 fprintf(stderr,"\r\n[ disconnected ]\r\n");
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800545 stdin_raw_restore();
David Pursell1ed57f02015-10-06 15:30:03 -0700546 exit(0);
Elliott Hughes28416d62015-11-04 13:36:32 -0800547 } else {
548 // We swallowed an escape character that wasn't part of
549 // a valid escape sequence; time to cough it up.
550 buffer_ptr[0] = args->escape_char;
551 buffer_ptr[1] = ch;
552 ++r;
David Pursell1ed57f02015-10-06 15:30:03 -0700553 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554 }
Elliott Hughes28416d62015-11-04 13:36:32 -0800555 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 }
David Pursell606835a2015-09-08 17:17:02 -0700558 if (args->protocol) {
559 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
560 break;
561 }
562 } else {
563 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
564 break;
565 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566 }
567 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568}
569
David Pursell1ed57f02015-10-06 15:30:03 -0700570// Returns a shell service string with the indicated arguments and command.
571static std::string ShellServiceString(bool use_shell_protocol,
572 const std::string& type_arg,
573 const std::string& command) {
574 std::vector<std::string> args;
575 if (use_shell_protocol) {
576 args.push_back(kShellServiceArgShellProtocol);
Elliott Hughesc2252df2015-11-18 12:45:48 -0800577
578 const char* terminal_type = getenv("TERM");
579 if (terminal_type != nullptr) {
580 args.push_back(std::string("TERM=") + terminal_type);
581 }
David Pursell1ed57f02015-10-06 15:30:03 -0700582 }
583 if (!type_arg.empty()) {
584 args.push_back(type_arg);
585 }
586
587 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
588 return android::base::StringPrintf("shell%s%s:%s",
589 args.empty() ? "" : ",",
590 android::base::Join(args, ',').c_str(),
591 command.c_str());
592}
593
594// Connects to a shell on the device and read/writes data.
595//
596// Note: currently this function doesn't properly clean up resources; the
597// FD connected to the adb server is never closed and the stdin read thread
598// may never exit.
599//
600// On success returns the remote exit code if |use_shell_protocol| is true,
601// 0 otherwise. On failure returns 1.
602static int RemoteShell(bool use_shell_protocol, const std::string& type_arg,
Elliott Hughes28416d62015-11-04 13:36:32 -0800603 char escape_char,
David Pursell1ed57f02015-10-06 15:30:03 -0700604 const std::string& command) {
605 std::string service_string = ShellServiceString(use_shell_protocol,
606 type_arg, command);
607
608 // Make local stdin raw if the device allocates a PTY, which happens if:
609 // 1. We are explicitly asking for a PTY shell, or
610 // 2. We don't specify shell type and are starting an interactive session.
611 bool raw_stdin = (type_arg == kShellServiceArgPty ||
612 (type_arg.empty() && command.empty()));
613
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700614 std::string error;
David Pursell4e2fd362015-09-22 10:43:08 -0700615 int fd = adb_connect(service_string, &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700616 if (fd < 0) {
617 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800618 return 1;
619 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620
David Pursell606835a2015-09-08 17:17:02 -0700621 StdinReadArgs* args = new StdinReadArgs;
622 if (!args) {
623 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700624 return 1;
625 }
David Pursell1ed57f02015-10-06 15:30:03 -0700626 args->stdin_fd = STDIN_FILENO;
David Pursell606835a2015-09-08 17:17:02 -0700627 args->write_fd = fd;
David Pursell1ed57f02015-10-06 15:30:03 -0700628 args->raw_stdin = raw_stdin;
Elliott Hughes28416d62015-11-04 13:36:32 -0800629 args->escape_char = escape_char;
David Pursell606835a2015-09-08 17:17:02 -0700630 if (use_shell_protocol) {
631 args->protocol.reset(new ShellProtocol(args->write_fd));
632 }
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700633
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800634 if (raw_stdin) stdin_raw_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800636#if !defined(_WIN32)
637 // Ensure our process is notified if the local window size changes.
638 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
639 // because the whole reason we're sending signals is to unblock the read(2)!
640 // That also means we don't need to do anything in the signal handler:
641 // the side effect of delivering the signal is all we need.
642 struct sigaction sa;
643 memset(&sa, 0, sizeof(sa));
644 sa.sa_handler = [](int) {};
645 sa.sa_flags = 0;
646 sigaction(SIGWINCH, &sa, nullptr);
647
648 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
649 // from it. The stdin read thread will unblock this signal to ensure that it's
650 // the thread that receives the signal.
651 sigset_t mask;
652 sigemptyset(&mask);
653 sigaddset(&mask, SIGWINCH);
654 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
655#endif
656
657 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
658 int exit_code = 1;
659 if (!adb_thread_create(stdin_read_thread_loop, args)) {
David Pursell606835a2015-09-08 17:17:02 -0700660 PLOG(ERROR) << "error starting stdin read thread";
David Pursell606835a2015-09-08 17:17:02 -0700661 delete args;
662 } else {
663 exit_code = read_and_dump(fd, use_shell_protocol);
664 }
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700665
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800666 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell1ed57f02015-10-06 15:30:03 -0700667
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800668 // TODO: we should probably install signal handlers for this.
669 // TODO: can we use atexit? even on Windows?
670 if (raw_stdin) stdin_raw_restore();
David Pursell1ed57f02015-10-06 15:30:03 -0700671
David Pursell606835a2015-09-08 17:17:02 -0700672 return exit_code;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800673}
674
Josh Gaof3f6a1d2016-01-31 19:12:26 -0800675static int adb_shell(int argc, const char** argv) {
David Pursell0aacbbe2016-01-21 19:56:50 -0800676 FeatureSet features;
Josh Gaof3f6a1d2016-01-31 19:12:26 -0800677 std::string error;
Josh Gaof3f6a1d2016-01-31 19:12:26 -0800678 if (!adb_get_feature_set(&features, &error)) {
679 fprintf(stderr, "error: %s\n", error.c_str());
David Pursell0aacbbe2016-01-21 19:56:50 -0800680 return 1;
681 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800682
Elliott Hughescabfa112016-10-19 14:47:11 -0700683 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
684
685 // Defaults.
686 char escape_char = '~'; // -e
687 bool use_shell_protocol = CanUseFeature(features, kFeatureShell2); // -x
688 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
Elliott Hughes6452a892015-04-29 12:28:13 -0700689
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800690 // Parse shell-specific command-line options.
Elliott Hughescabfa112016-10-19 14:47:11 -0700691 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
692 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
693 int opt;
694 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
695 switch (opt) {
696 case 'e':
697 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
698 fprintf(stderr, "error: -e requires a single-character argument or 'none'\n");
699 return 1;
700 }
701 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
702 break;
703 case 'n':
704 close_stdin();
705 break;
706 case 'x':
707 // This option basically asks for historical behavior, so set options that
708 // correspond to the historical defaults. This is slightly weird in that -Tx
709 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
710 // be our least worst choice...
711 use_shell_protocol = false;
712 tty = kPtyDefinitely;
713 escape_char = '~';
714 break;
715 case 't':
716 // Like ssh, -t arguments are cumulative so that multiple -t's
717 // are needed to force a PTY.
718 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
719 break;
720 case 'T':
721 tty = kPtyNo;
722 break;
723 default:
724 // getopt(3) already printed an error message for us.
Elliott Hughes28416d62015-11-04 13:36:32 -0800725 return 1;
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800726 }
Elliott Hughes6452a892015-04-29 12:28:13 -0700727 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728
Elliott Hughescabfa112016-10-19 14:47:11 -0700729 bool is_interactive = (optind == argc);
David Pursell57dd5ae2016-01-27 16:07:52 -0800730
Elliott Hughescabfa112016-10-19 14:47:11 -0700731 std::string shell_type_arg = kShellServiceArgPty;
732 if (tty == kPtyNo) {
733 shell_type_arg = kShellServiceArgRaw;
734 } else if (tty == kPtyAuto) {
735 // If stdin isn't a TTY, default to a raw shell; this lets
736 // things like `adb shell < my_script.sh` work as expected.
737 // Non-interactive shells should also not have a pty.
738 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800739 shell_type_arg = kShellServiceArgRaw;
Elliott Hughescabfa112016-10-19 14:47:11 -0700740 }
741 } else if (tty == kPtyYes) {
742 // A single -t arg isn't enough to override implicit -T.
743 if (!unix_isatty(STDIN_FILENO)) {
744 fprintf(stderr,
745 "Remote PTY will not be allocated because stdin is not a terminal.\n"
746 "Use multiple -t options to force remote PTY allocation.\n");
747 shell_type_arg = kShellServiceArgRaw;
748 }
749 }
750
751 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
752 escape_char, tty,
753 use_shell_protocol ? "true" : "false",
754 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
755
756 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
757 if (!use_shell_protocol) {
758 if (shell_type_arg != kShellServiceArgPty) {
759 fprintf(stderr, "error: %s only supports allocating a pty\n",
760 !CanUseFeature(features, kFeatureShell2) ? "device" : "-x");
761 return 1;
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800762 } else {
Elliott Hughescabfa112016-10-19 14:47:11 -0700763 // If we're not using the shell protocol, the type argument must be empty.
764 shell_type_arg = "";
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800765 }
David Pursell71c83122015-09-14 15:33:50 -0700766 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800767
768 std::string command;
Elliott Hughescabfa112016-10-19 14:47:11 -0700769 if (optind < argc) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800770 // We don't escape here, just like ssh(1). http://b/20564385.
Elliott Hughescabfa112016-10-19 14:47:11 -0700771 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800772 }
773
Elliott Hughes28416d62015-11-04 13:36:32 -0800774 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command);
David Pursell71c83122015-09-14 15:33:50 -0700775}
776
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700777static int adb_download_buffer(const char* service, const char* filename) {
778 std::string content;
779 if (!android::base::ReadFileToString(filename, &content)) {
780 fprintf(stderr, "error: couldn't read %s: %s\n", filename, strerror(errno));
781 return -1;
782 }
783
784 const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
785 unsigned sz = content.size();
786
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700787 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -0700788 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700789 if (fd < 0) {
790 fprintf(stderr,"error: %s\n", error.c_str());
Doug Zongker447f0612012-01-09 14:54:53 -0800791 return -1;
792 }
793
794 int opt = CHUNK_SIZE;
Spencer Lowf055c192015-01-25 14:40:16 -0800795 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
Doug Zongker447f0612012-01-09 14:54:53 -0800796
Elliott Hughes6452a892015-04-29 12:28:13 -0700797 unsigned total = sz;
Dan Albertbac34742015-02-25 17:51:28 -0800798 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
Doug Zongker447f0612012-01-09 14:54:53 -0800799
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700800 const char* x = strrchr(service, ':');
801 if (x) service = x + 1;
Doug Zongker447f0612012-01-09 14:54:53 -0800802
Elliott Hughes6452a892015-04-29 12:28:13 -0700803 while (sz > 0) {
Doug Zongker447f0612012-01-09 14:54:53 -0800804 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700805 if (!WriteFdExactly(fd, ptr, xfer)) {
806 std::string error;
807 adb_status(fd, &error);
808 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Spencer Low351ecd12015-10-14 17:32:44 -0700809 adb_close(fd);
Doug Zongker447f0612012-01-09 14:54:53 -0800810 return -1;
811 }
812 sz -= xfer;
813 ptr += xfer;
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700814 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * sz) / (total))));
815 fflush(stdout);
Doug Zongker447f0612012-01-09 14:54:53 -0800816 }
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700817 printf("\n");
Doug Zongker447f0612012-01-09 14:54:53 -0800818
Elliott Hughese67f1f82015-04-30 17:32:03 -0700819 if (!adb_status(fd, &error)) {
820 fprintf(stderr,"* error response '%s' *\n", error.c_str());
Spencer Low351ecd12015-10-14 17:32:44 -0700821 adb_close(fd);
Doug Zongker447f0612012-01-09 14:54:53 -0800822 return -1;
823 }
824
825 adb_close(fd);
826 return 0;
827}
828
Doug Zongker71fe5842014-06-26 15:35:36 -0700829#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
830
831/*
832 * The sideload-host protocol serves the data in a file (given on the
833 * command line) to the client, using a simple protocol:
834 *
835 * - The connect message includes the total number of bytes in the
836 * file and a block size chosen by us.
837 *
838 * - The other side sends the desired block number as eight decimal
839 * digits (eg "00000023" for block 23). Blocks are numbered from
840 * zero.
841 *
842 * - We send back the data of the requested block. The last block is
843 * likely to be partial; when the last block is requested we only
844 * send the part of the block that exists, it's not padded up to the
845 * block size.
846 *
847 * - When the other side sends "DONEDONE" instead of a block number,
848 * we hang up.
849 */
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700850static int adb_sideload_host(const char* filename) {
851 fprintf(stderr, "opening '%s'...\n", filename);
852 struct stat sb;
853 if (stat(filename, &sb) == -1) {
854 fprintf(stderr, "failed to stat file %s: %s\n", filename, strerror(errno));
855 return -1;
856 }
857 unique_fd package_fd(adb_open(filename, O_RDONLY));
858 if (package_fd == -1) {
859 fprintf(stderr, "failed to open file %s: %s\n", filename, strerror(errno));
Doug Zongker71fe5842014-06-26 15:35:36 -0700860 return -1;
861 }
862
Elliott Hughes14415142016-06-15 14:45:34 -0700863 fprintf(stderr, "connecting...\n");
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700864 std::string service = android::base::StringPrintf(
865 "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700866 std::string error;
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700867 unique_fd device_fd(adb_connect(service, &error));
868 if (device_fd < 0) {
869 // Try falling back to the older (<= K) sideload method. Maybe this
Doug Zongker71fe5842014-06-26 15:35:36 -0700870 // is an older device that doesn't support sideload-host.
Elliott Hughes14415142016-06-15 14:45:34 -0700871 fprintf(stderr, "falling back to older sideload method...\n");
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700872 return adb_download_buffer("sideload", filename);
Doug Zongker71fe5842014-06-26 15:35:36 -0700873 }
874
Elliott Hughese8b663f2016-05-26 22:43:19 -0700875 int opt = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700876 adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
877
878 char buf[SIDELOAD_HOST_BLOCK_SIZE];
Doug Zongker71fe5842014-06-26 15:35:36 -0700879
Elliott Hughese8b663f2016-05-26 22:43:19 -0700880 size_t xfer = 0;
881 int last_percent = -1;
Elliott Hughesa7090b92015-04-17 17:03:59 -0700882 while (true) {
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700883 if (!ReadFdExactly(device_fd, buf, 8)) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700884 fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
Elliott Hughese8b663f2016-05-26 22:43:19 -0700885 return -1;
Doug Zongker71fe5842014-06-26 15:35:36 -0700886 }
Elliott Hughes6452a892015-04-29 12:28:13 -0700887 buf[8] = '\0';
Doug Zongker71fe5842014-06-26 15:35:36 -0700888
Elliott Hughes6452a892015-04-29 12:28:13 -0700889 if (strcmp("DONEDONE", buf) == 0) {
Elliott Hughese8b663f2016-05-26 22:43:19 -0700890 printf("\rTotal xfer: %.2fx%*s\n",
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700891 static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
892 static_cast<int>(strlen(filename) + 10), "");
Elliott Hughese8b663f2016-05-26 22:43:19 -0700893 return 0;
Doug Zongker71fe5842014-06-26 15:35:36 -0700894 }
895
Doug Zongker71fe5842014-06-26 15:35:36 -0700896 int block = strtol(buf, NULL, 10);
897
898 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700899 if (offset >= static_cast<size_t>(sb.st_size)) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700900 fprintf(stderr, "* attempt to read block %d past end\n", block);
Elliott Hughese8b663f2016-05-26 22:43:19 -0700901 return -1;
Doug Zongker71fe5842014-06-26 15:35:36 -0700902 }
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700903
Doug Zongker71fe5842014-06-26 15:35:36 -0700904 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700905 if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<size_t>(sb.st_size)) {
906 to_write = sb.st_size - offset;
Doug Zongker71fe5842014-06-26 15:35:36 -0700907 }
908
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700909 if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) {
910 fprintf(stderr, "* failed to seek to package block: %s\n", strerror(errno));
911 return -1;
912 }
913 if (!ReadFdExactly(package_fd, buf, to_write)) {
914 fprintf(stderr, "* failed to read package block: %s\n", strerror(errno));
915 return -1;
916 }
917
918 if (!WriteFdExactly(device_fd, buf, to_write)) {
919 adb_status(device_fd, &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700920 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Elliott Hughese8b663f2016-05-26 22:43:19 -0700921 return -1;
Doug Zongker71fe5842014-06-26 15:35:36 -0700922 }
923 xfer += to_write;
924
925 // For normal OTA packages, we expect to transfer every byte
926 // twice, plus a bit of overhead (one read during
927 // verification, one read of each byte for installation, plus
928 // extra access to things like the zip central directory).
929 // This estimate of the completion becomes 100% when we've
930 // transferred ~2.13 (=100/47) times the package size.
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700931 int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
Doug Zongker71fe5842014-06-26 15:35:36 -0700932 if (percent != last_percent) {
Elliott Hughesee1ac7102017-03-21 17:14:18 -0700933 printf("\rserving: '%s' (~%d%%) ", filename, percent);
Doug Zongker71fe5842014-06-26 15:35:36 -0700934 fflush(stdout);
935 last_percent = percent;
936 }
937 }
Doug Zongker71fe5842014-06-26 15:35:36 -0700938}
939
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800940/**
941 * Run ppp in "notty" mode against a resource listed as the first parameter
942 * eg:
943 *
944 * ppp dev:/dev/omap_csmi_tty0 <ppp options>
945 *
946 */
Elliott Hughes58305772015-04-17 13:57:15 -0700947static int ppp(int argc, const char** argv) {
Yabin Cuie77b6a02014-11-11 09:24:11 -0800948#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
950 return -1;
951#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800952 if (argc < 2) {
953 fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n",
954 argv[0]);
955
956 return 1;
957 }
958
Dan Albertbac34742015-02-25 17:51:28 -0800959 const char* adb_service_name = argv[1];
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700960 std::string error;
961 int fd = adb_connect(adb_service_name, &error);
962 if (fd < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963 fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n",
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700964 adb_service_name, error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800965 return 1;
966 }
967
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700968 pid_t pid = fork();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800969
970 if (pid < 0) {
971 perror("from fork()");
972 return 1;
973 } else if (pid == 0) {
974 int err;
975 int i;
976 const char **ppp_args;
977
978 // copy args
979 ppp_args = (const char **) alloca(sizeof(char *) * argc + 1);
980 ppp_args[0] = "pppd";
981 for (i = 2 ; i < argc ; i++) {
982 //argv[2] and beyond become ppp_args[1] and beyond
983 ppp_args[i - 1] = argv[i];
984 }
985 ppp_args[i-1] = NULL;
986
987 // child side
988
989 dup2(fd, STDIN_FILENO);
990 dup2(fd, STDOUT_FILENO);
991 adb_close(STDERR_FILENO);
992 adb_close(fd);
993
994 err = execvp("pppd", (char * const *)ppp_args);
995
996 if (err < 0) {
997 perror("execing pppd");
998 }
999 exit(-1);
1000 } else {
1001 // parent side
1002
1003 adb_close(fd);
1004 return 0;
1005 }
Yabin Cuie77b6a02014-11-11 09:24:11 -08001006#endif /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007}
1008
Josh Gao08881e72016-04-13 12:14:16 -07001009static bool wait_for_device(const char* service, TransportType t, const char* serial) {
1010 std::vector<std::string> components = android::base::Split(service, "-");
1011 if (components.size() < 3 || components.size() > 4) {
Leo Sartre1fbc9db2015-11-27 18:56:48 +01001012 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1013 return false;
1014 }
1015
Elliott Hughes2b101112015-05-04 19:29:32 -07001016 // Was the caller vague about what they'd like us to wait for?
1017 // If so, check they weren't more specific in their choice of transport type.
Josh Gao08881e72016-04-13 12:14:16 -07001018 if (components.size() == 3) {
1019 auto it = components.begin() + 2;
Elliott Hughes2b101112015-05-04 19:29:32 -07001020 if (t == kTransportUsb) {
Josh Gao08881e72016-04-13 12:14:16 -07001021 components.insert(it, "usb");
Elliott Hughes2b101112015-05-04 19:29:32 -07001022 } else if (t == kTransportLocal) {
Josh Gao08881e72016-04-13 12:14:16 -07001023 components.insert(it, "local");
Elliott Hughes2b101112015-05-04 19:29:32 -07001024 } else {
Josh Gao08881e72016-04-13 12:14:16 -07001025 components.insert(it, "any");
Elliott Hughes2b101112015-05-04 19:29:32 -07001026 }
Josh Gao08881e72016-04-13 12:14:16 -07001027 } else if (components[2] != "any" && components[2] != "local" && components[2] != "usb") {
1028 fprintf(stderr, "adb: unknown type %s; expected 'any', 'local', or 'usb'\n",
1029 components[2].c_str());
Leo Sartre1fbc9db2015-11-27 18:56:48 +01001030 return false;
1031 }
1032
Josh Gao86441c32016-04-13 12:18:58 -07001033 if (components[3] != "any" && components[3] != "bootloader" && components[3] != "device" &&
1034 components[3] != "recovery" && components[3] != "sideload") {
Josh Gao08881e72016-04-13 12:14:16 -07001035 fprintf(stderr,
1036 "adb: unknown state %s; "
Josh Gao86441c32016-04-13 12:18:58 -07001037 "expected 'any', 'bootloader', 'device', 'recovery', or 'sideload'\n",
Josh Gao08881e72016-04-13 12:14:16 -07001038 components[3].c_str());
1039 return false;
1040 }
1041
1042 std::string cmd = format_host_command(android::base::Join(components, "-").c_str(), t, serial);
Elliott Hughes424af022015-05-29 17:55:19 -07001043 return adb_command(cmd);
Elliott Hughes2b101112015-05-04 19:29:32 -07001044}
1045
Josh Gao06c73ae2016-03-04 15:16:18 -08001046static bool adb_root(const char* command) {
1047 std::string error;
Josh Gao06c73ae2016-03-04 15:16:18 -08001048
Elliott Hughese8b663f2016-05-26 22:43:19 -07001049 unique_fd fd(adb_connect(android::base::StringPrintf("%s:", command), &error));
1050 if (fd < 0) {
Josh Gao06c73ae2016-03-04 15:16:18 -08001051 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1052 return false;
1053 }
1054
1055 // Figure out whether we actually did anything.
1056 char buf[256];
1057 char* cur = buf;
1058 ssize_t bytes_left = sizeof(buf);
1059 while (bytes_left > 0) {
Elliott Hughese8b663f2016-05-26 22:43:19 -07001060 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
Josh Gao06c73ae2016-03-04 15:16:18 -08001061 if (bytes_read == 0) {
1062 break;
1063 } else if (bytes_read < 0) {
1064 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1065 return false;
1066 }
1067 cur += bytes_read;
1068 bytes_left -= bytes_read;
1069 }
1070
1071 if (bytes_left == 0) {
1072 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1073 return false;
1074 }
1075
1076 fflush(stdout);
1077 WriteFdExactly(STDOUT_FILENO, buf, sizeof(buf) - bytes_left);
1078 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1079 return true;
1080 }
1081
Josh Gao05824732016-06-16 14:00:09 -07001082 // Give adbd some time to kill itself and come back up.
1083 // We can't use wait-for-device because devices (e.g. adb over network) might not come back.
Josh Gao4602adb2016-11-15 18:55:47 -08001084 std::this_thread::sleep_for(3s);
Josh Gao05824732016-06-16 14:00:09 -07001085 return true;
Josh Gao06c73ae2016-03-04 15:16:18 -08001086}
1087
Felipe Leme698e0652016-07-19 17:07:22 -07001088int send_shell_command(TransportType transport_type, const char* serial, const std::string& command,
Felipe Leme0d4f0502016-07-26 12:14:39 -07001089 bool disable_shell_protocol, StandardStreamsCallbackInterface* callback) {
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001090 int fd;
David Pursell0aacbbe2016-01-21 19:56:50 -08001091 bool use_shell_protocol = false;
1092
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001093 while (true) {
David Pursell0aacbbe2016-01-21 19:56:50 -08001094 bool attempt_connection = true;
1095
Felipe Leme0d4f0502016-07-26 12:14:39 -07001096 // Use shell protocol if it's supported and the caller doesn't explicitly
1097 // disable it.
David Pursell0aacbbe2016-01-21 19:56:50 -08001098 if (!disable_shell_protocol) {
1099 FeatureSet features;
Josh Gaof3f6a1d2016-01-31 19:12:26 -08001100 std::string error;
1101 if (adb_get_feature_set(&features, &error)) {
David Pursell0aacbbe2016-01-21 19:56:50 -08001102 use_shell_protocol = CanUseFeature(features, kFeatureShell2);
1103 } else {
1104 // Device was unreachable.
1105 attempt_connection = false;
1106 }
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001107 }
David Pursell0aacbbe2016-01-21 19:56:50 -08001108
1109 if (attempt_connection) {
1110 std::string error;
1111 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1112
1113 fd = adb_connect(service_string, &error);
1114 if (fd >= 0) {
1115 break;
1116 }
1117 }
1118
Felipe Leme0d4f0502016-07-26 12:14:39 -07001119 fprintf(stderr, "- waiting for device -\n");
Josh Gaob6117c42016-02-24 15:16:17 -08001120 if (!wait_for_device("wait-for-device", transport_type, serial)) {
1121 return 1;
1122 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001123 }
1124
Felipe Leme0d4f0502016-07-26 12:14:39 -07001125 int exit_code = read_and_dump(fd, use_shell_protocol, callback);
David Pursell71c83122015-09-14 15:33:50 -07001126
1127 if (adb_close(fd) < 0) {
1128 PLOG(ERROR) << "failure closing FD " << fd;
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001129 }
David Pursell71c83122015-09-14 15:33:50 -07001130
1131 return exit_code;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001132}
1133
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001134static int logcat(TransportType transport, const char* serial, int argc, const char** argv) {
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001135 char* log_tags = getenv("ANDROID_LOG_TAGS");
1136 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001137
David Pursell70ef7b42015-09-30 13:35:42 -07001138 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001139
Jeff Sharkeyfd546e82014-06-10 11:31:24 -07001140 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001141 cmd += " -v long";
Christopher Tatedb0a8802011-11-30 13:00:33 -08001142 }
1143
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001144 --argc;
1145 ++argv;
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001146 while (argc-- > 0) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001147 cmd += " " + escape_arg(*argv++);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001148 }
1149
David Pursell70ef7b42015-09-30 13:35:42 -07001150 // No need for shell protocol with logcat, always disable for simplicity.
1151 return send_shell_command(transport, serial, cmd, true);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152}
1153
Christopher Tatec42f1bb2016-07-06 13:22:22 -07001154static void write_zeros(int bytes, int fd) {
1155 int old_stdin_mode = -1;
1156 int old_stdout_mode = -1;
1157 char* buf = (char*) calloc(1, bytes);
1158 if (buf == nullptr) fatal("couldn't allocate buffer for write_zeros");
1159
1160 D("write_zeros(%d) -> %d", bytes, fd);
1161
1162 stdinout_raw_prologue(-1, fd, old_stdin_mode, old_stdout_mode);
1163
1164 if (fd == STDOUT_FILENO) {
1165 fwrite(buf, 1, bytes, stdout);
1166 fflush(stdout);
1167 } else {
1168 adb_write(fd, buf, bytes);
1169 }
1170
1171 stdinout_raw_prologue(-1, fd, old_stdin_mode, old_stdout_mode);
1172
1173 D("write_zeros() finished");
1174 free(buf);
1175}
1176
Dan Albertbac34742015-02-25 17:51:28 -08001177static int backup(int argc, const char** argv) {
Elliott Hughes24f165f2015-08-21 20:31:31 -07001178 const char* filename = "backup.ab";
Christopher Tated2f54152011-04-21 12:53:28 -07001179
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001180 /* find, extract, and use any -f argument */
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001181 for (int i = 1; i < argc; i++) {
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001182 if (!strcmp("-f", argv[i])) {
1183 if (i == argc-1) {
Elliott Hughes56e68132015-11-13 11:04:10 -08001184 fprintf(stderr, "adb: backup -f passed with no filename.\n");
1185 return EXIT_FAILURE;
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001186 }
1187 filename = argv[i+1];
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001188 for (int j = i+2; j <= argc; ) {
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001189 argv[i++] = argv[j++];
1190 }
1191 argc -= 2;
1192 argv[argc] = NULL;
1193 }
Christopher Tated2f54152011-04-21 12:53:28 -07001194 }
1195
Elliott Hughes56e68132015-11-13 11:04:10 -08001196 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1197 // a list of packages is required.
1198 if (argc < 2) {
1199 fprintf(stderr, "adb: backup either needs a list of packages or -all/-shared.\n");
1200 return EXIT_FAILURE;
1201 }
Christopher Tatebb86bc52011-08-22 17:12:08 -07001202
Christopher Tateb1dfffe2011-12-08 19:04:34 -08001203 adb_unlink(filename);
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001204 int outFd = adb_creat(filename, 0640);
Christopher Tated2f54152011-04-21 12:53:28 -07001205 if (outFd < 0) {
Elliott Hughes56e68132015-11-13 11:04:10 -08001206 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1207 return EXIT_FAILURE;
Christopher Tated2f54152011-04-21 12:53:28 -07001208 }
1209
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001210 std::string cmd = "backup:";
1211 --argc;
1212 ++argv;
1213 while (argc-- > 0) {
1214 cmd += " " + escape_arg(*argv++);
Christopher Tated2f54152011-04-21 12:53:28 -07001215 }
1216
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001217 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001218 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001219 int fd = adb_connect(cmd, &error);
Christopher Tated2f54152011-04-21 12:53:28 -07001220 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001221 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Christopher Tated2f54152011-04-21 12:53:28 -07001222 adb_close(outFd);
Elliott Hughes56e68132015-11-13 11:04:10 -08001223 return EXIT_FAILURE;
Christopher Tated2f54152011-04-21 12:53:28 -07001224 }
1225
Elliott Hughes56e68132015-11-13 11:04:10 -08001226 printf("Now unlock your device and confirm the backup operation...\n");
1227 fflush(stdout);
1228
Christopher Tated2f54152011-04-21 12:53:28 -07001229 copy_to_file(fd, outFd);
1230
1231 adb_close(fd);
1232 adb_close(outFd);
Elliott Hughes56e68132015-11-13 11:04:10 -08001233 return EXIT_SUCCESS;
Christopher Tated2f54152011-04-21 12:53:28 -07001234}
1235
Dan Albertbac34742015-02-25 17:51:28 -08001236static int restore(int argc, const char** argv) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001237 if (argc != 2) return usage("restore requires an argument");
Christopher Tate702967a2011-05-17 15:52:54 -07001238
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001239 const char* filename = argv[1];
1240 int tarFd = adb_open(filename, O_RDONLY);
Christopher Tate702967a2011-05-17 15:52:54 -07001241 if (tarFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001242 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tate702967a2011-05-17 15:52:54 -07001243 return -1;
1244 }
1245
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001246 std::string error;
1247 int fd = adb_connect("restore:", &error);
Christopher Tate702967a2011-05-17 15:52:54 -07001248 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001249 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tate702967a2011-05-17 15:52:54 -07001250 adb_close(tarFd);
1251 return -1;
1252 }
1253
Christopher Tatebffa4ca2012-01-06 15:43:03 -08001254 printf("Now unlock your device and confirm the restore operation.\n");
Christopher Tate702967a2011-05-17 15:52:54 -07001255 copy_to_file(tarFd, fd);
1256
Christopher Tatec42f1bb2016-07-06 13:22:22 -07001257 // Provide an in-band EOD marker in case the archive file is malformed
1258 write_zeros(512*2, fd);
1259
Josh Gao5767d0d2016-03-04 15:51:03 -08001260 // Wait until the other side finishes, or it'll get sent SIGHUP.
1261 copy_to_file(fd, STDOUT_FILENO);
1262
Christopher Tate702967a2011-05-17 15:52:54 -07001263 adb_close(fd);
1264 adb_close(tarFd);
1265 return 0;
1266}
1267
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001268/* <hint> may be:
1269 * - A simple product name
1270 * e.g., "sooner"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001271 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
1272 * e.g., "out/target/product/sooner"
1273 * - An absolute path to the PRODUCT_OUT dir
1274 * e.g., "/src/device/out/target/product/sooner"
1275 *
1276 * Given <hint>, try to construct an absolute path to the
1277 * ANDROID_PRODUCT_OUT dir.
1278 */
Elliott Hughes5c742702015-07-30 17:42:01 -07001279static std::string find_product_out_path(const std::string& hint) {
1280 if (hint.empty()) {
Elliott Hughes58305772015-04-17 13:57:15 -07001281 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001282 }
1283
Elliott Hughes58305772015-04-17 13:57:15 -07001284 // If it's already absolute, don't bother doing any work.
Elliott Hughes5c742702015-07-30 17:42:01 -07001285 if (adb_is_absolute_host_path(hint.c_str())) {
Elliott Hughes58305772015-04-17 13:57:15 -07001286 return hint;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001287 }
1288
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001289 // If any of the OS_PATH_SEPARATORS is found, assume it's a relative path;
Elliott Hughes58305772015-04-17 13:57:15 -07001290 // make it absolute.
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001291 // NOLINT: Do not complain if OS_PATH_SEPARATORS has only one character.
1292 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) { // NOLINT
Elliott Hughesa7090b92015-04-17 17:03:59 -07001293 std::string cwd;
1294 if (!getcwd(&cwd)) {
Felipe Lemeb3239722016-07-29 17:57:00 -07001295 perror("adb: getcwd failed");
Elliott Hughes58305772015-04-17 13:57:15 -07001296 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001297 }
Elliott Hughes5c742702015-07-30 17:42:01 -07001298 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001299 }
1300
Elliott Hughes58305772015-04-17 13:57:15 -07001301 // It's a string without any slashes. Try to do something with it.
1302 //
1303 // Try to find the root of the build tree, and build a PRODUCT_OUT
1304 // path from there.
Elliott Hughesa7090b92015-04-17 17:03:59 -07001305 char* top = getenv("ANDROID_BUILD_TOP");
Elliott Hughes58305772015-04-17 13:57:15 -07001306 if (top == nullptr) {
Elliott Hughesa7090b92015-04-17 17:03:59 -07001307 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
Elliott Hughes58305772015-04-17 13:57:15 -07001308 return "";
1309 }
Elliott Hughesa7090b92015-04-17 17:03:59 -07001310
1311 std::string path = top;
Elliott Hughes58305772015-04-17 13:57:15 -07001312 path += OS_PATH_SEPARATOR_STR;
1313 path += "out";
1314 path += OS_PATH_SEPARATOR_STR;
1315 path += "target";
1316 path += OS_PATH_SEPARATOR_STR;
1317 path += "product";
1318 path += OS_PATH_SEPARATOR_STR;
1319 path += hint;
1320 if (!directory_exists(path)) {
1321 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
Elliott Hughes5c742702015-07-30 17:42:01 -07001322 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str());
Elliott Hughesa7090b92015-04-17 17:03:59 -07001323 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001324 }
Elliott Hughes58305772015-04-17 13:57:15 -07001325 return path;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001326}
1327
Josh Gao05786772015-10-30 16:57:19 -07001328static void parse_push_pull_args(const char** arg, int narg,
1329 std::vector<const char*>* srcs,
1330 const char** dst, bool* copy_attrs) {
1331 *copy_attrs = false;
Mark Lindner76f2a932014-03-11 17:55:59 -07001332
Josh Gao05786772015-10-30 16:57:19 -07001333 srcs->clear();
1334 bool ignore_flags = false;
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001335 while (narg > 0) {
Josh Gao05786772015-10-30 16:57:19 -07001336 if (ignore_flags || *arg[0] != '-') {
1337 srcs->push_back(*arg);
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001338 } else {
Josh Gao05786772015-10-30 16:57:19 -07001339 if (!strcmp(*arg, "-p")) {
1340 // Silently ignore for backwards compatibility.
1341 } else if (!strcmp(*arg, "-a")) {
1342 *copy_attrs = true;
1343 } else if (!strcmp(*arg, "--")) {
1344 ignore_flags = true;
1345 } else {
1346 fprintf(stderr, "adb: unrecognized option '%s'\n", *arg);
1347 exit(1);
1348 }
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001349 }
Mark Lindner76f2a932014-03-11 17:55:59 -07001350 ++arg;
1351 --narg;
1352 }
1353
Josh Gao05786772015-10-30 16:57:19 -07001354 if (srcs->size() > 1) {
1355 *dst = srcs->back();
1356 srcs->pop_back();
Mark Lindner76f2a932014-03-11 17:55:59 -07001357 }
1358}
1359
Elliott Hughes6452a892015-04-29 12:28:13 -07001360static int adb_connect_command(const std::string& command) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001361 std::string error;
1362 int fd = adb_connect(command, &error);
Elliott Hughes5677c232015-05-07 23:37:40 -07001363 if (fd < 0) {
1364 fprintf(stderr, "error: %s\n", error.c_str());
1365 return 1;
Tao Bao175b7bb2015-03-29 11:22:34 -07001366 }
Elliott Hughes5677c232015-05-07 23:37:40 -07001367 read_and_dump(fd);
1368 adb_close(fd);
1369 return 0;
Tao Bao175b7bb2015-03-29 11:22:34 -07001370}
1371
Elliott Hughes6452a892015-04-29 12:28:13 -07001372static int adb_query_command(const std::string& command) {
1373 std::string result;
1374 std::string error;
1375 if (!adb_query(command, &result, &error)) {
1376 fprintf(stderr, "error: %s\n", error.c_str());
1377 return 1;
1378 }
1379 printf("%s\n", result.c_str());
1380 return 0;
1381}
1382
Spencer Lowa13df302015-09-07 16:20:13 -07001383// Disallow stdin, stdout, and stderr.
1384static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1385#ifdef _WIN32
1386 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1387 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1388 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1389 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1390#else
1391 return ack_reply_fd > 2;
1392#endif
1393}
1394
Todd Kennedy248722e2016-07-20 16:22:37 -07001395static bool _use_legacy_install() {
1396 FeatureSet features;
1397 std::string error;
1398 if (!adb_get_feature_set(&features, &error)) {
1399 fprintf(stderr, "error: %s\n", error.c_str());
1400 return true;
1401 }
1402 return !CanUseFeature(features, kFeatureCmd);
1403}
1404
Elliott Hughescabfa112016-10-19 14:47:11 -07001405int adb_commandline(int argc, const char** argv) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001406 int no_daemon = 0;
1407 int is_daemon = 0;
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001408 int is_server = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001409 int r;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001410 TransportType transport_type = kTransportAny;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001411 int ack_reply_fd = -1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001412
Elliott Hughes65433da2015-11-18 18:07:48 -08001413#if !defined(_WIN32)
1414 // We'd rather have EPIPE than SIGPIPE.
1415 signal(SIGPIPE, SIG_IGN);
1416#endif
1417
Elliott Hughes58305772015-04-17 13:57:15 -07001418 // If defined, this should be an absolute path to
1419 // the directory containing all of the various system images
1420 // for a particular product. If not defined, and the adb
1421 // command requires this information, then the user must
1422 // specify the path using "-p".
1423 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
1424 if (ANDROID_PRODUCT_OUT != nullptr) {
1425 gProductOutPath = ANDROID_PRODUCT_OUT;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001426 }
1427 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
1428
Josh Gao9c869b52016-08-25 16:00:22 -07001429 const char* server_host_str = nullptr;
1430 const char* server_port_str = nullptr;
1431 const char* server_socket_str = nullptr;
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001432
Elliott Hughes8d28e192015-10-07 14:55:10 -07001433 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1434 const char* serial = nullptr;
1435
Riley Andrews98f58e82014-12-05 17:37:24 -08001436 while (argc > 0) {
1437 if (!strcmp(argv[0],"server")) {
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001438 is_server = 1;
Riley Andrews98f58e82014-12-05 17:37:24 -08001439 } else if (!strcmp(argv[0],"nodaemon")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001440 no_daemon = 1;
1441 } else if (!strcmp(argv[0], "fork-server")) {
1442 /* this is a special flag used only when the ADB client launches the ADB Server */
1443 is_daemon = 1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001444 } else if (!strcmp(argv[0], "--reply-fd")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001445 if (argc < 2) return usage("--reply-fd requires an argument");
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001446 const char* reply_fd_str = argv[1];
1447 argc--;
1448 argv++;
1449 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowa13df302015-09-07 16:20:13 -07001450 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001451 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001452 return 1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001453 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001454 } else if (!strncmp(argv[0], "-p", 2)) {
Elliott Hughes048b27c2015-07-31 13:18:22 -07001455 const char* product = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001456 if (argv[0][2] == '\0') {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001457 if (argc < 2) return usage("-p requires an argument");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001458 product = argv[1];
1459 argc--;
1460 argv++;
1461 } else {
Vairavan Srinivasan81273232012-08-04 16:40:50 -07001462 product = argv[0] + 2;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001463 }
Elliott Hughes048b27c2015-07-31 13:18:22 -07001464 gProductOutPath = find_product_out_path(product);
Elliott Hughes58305772015-04-17 13:57:15 -07001465 if (gProductOutPath.empty()) {
1466 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001467 return 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001468 }
1469 } else if (argv[0][0]=='-' && argv[0][1]=='s') {
1470 if (isdigit(argv[0][2])) {
1471 serial = argv[0] + 2;
1472 } else {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001473 if (argc < 2 || argv[0][2] != '\0') return usage("-s requires an argument");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001474 serial = argv[1];
1475 argc--;
1476 argv++;
1477 }
1478 } else if (!strcmp(argv[0],"-d")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001479 transport_type = kTransportUsb;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001480 } else if (!strcmp(argv[0],"-e")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001481 transport_type = kTransportLocal;
Matt Gumbeld7b33082012-11-14 10:16:17 -08001482 } else if (!strcmp(argv[0],"-a")) {
1483 gListenAll = 1;
Riley Andrews98f58e82014-12-05 17:37:24 -08001484 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbeld7b33082012-11-14 10:16:17 -08001485 if (argv[0][2] == '\0') {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001486 if (argc < 2) return usage("-H requires an argument");
Josh Gao9c869b52016-08-25 16:00:22 -07001487 server_host_str = argv[1];
Matt Gumbeld7b33082012-11-14 10:16:17 -08001488 argc--;
1489 argv++;
1490 } else {
Josh Gao9c869b52016-08-25 16:00:22 -07001491 server_host_str = argv[0] + 2;
Matt Gumbeld7b33082012-11-14 10:16:17 -08001492 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001493 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbeld7b33082012-11-14 10:16:17 -08001494 if (argv[0][2] == '\0') {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001495 if (argc < 2) return usage("-P requires an argument");
Matt Gumbeld7b33082012-11-14 10:16:17 -08001496 server_port_str = argv[1];
1497 argc--;
1498 argv++;
1499 } else {
1500 server_port_str = argv[0] + 2;
1501 }
Josh Gao9c869b52016-08-25 16:00:22 -07001502 } else if (!strcmp(argv[0], "-L")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001503 if (argc < 2) return usage("-L requires an argument");
Josh Gao9c869b52016-08-25 16:00:22 -07001504 server_socket_str = argv[1];
1505 argc--;
1506 argv++;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001507 } else {
Josh Gao9c869b52016-08-25 16:00:22 -07001508 /* out of recognized modifiers and flags */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001509 break;
1510 }
1511 argc--;
1512 argv++;
1513 }
1514
Josh Gao9c869b52016-08-25 16:00:22 -07001515 if ((server_host_str || server_port_str) && server_socket_str) {
1516 fprintf(stderr, "adb: -L is incompatible with -H or -P\n");
1517 exit(1);
1518 }
1519
1520 // If -L, -H, or -P are specified, ignore environment variables.
1521 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
Tao Wu135f4ab2016-09-16 13:01:24 -07001522 if (!server_host_str && !server_port_str && !server_socket_str) {
1523 server_socket_str = getenv("ADB_SERVER_SOCKET");
Josh Gao9c869b52016-08-25 16:00:22 -07001524 }
1525
1526 if (!server_socket_str) {
1527 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1528 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1529
Tao Wu135f4ab2016-09-16 13:01:24 -07001530 int server_port = DEFAULT_ADB_PORT;
Josh Gao9c869b52016-08-25 16:00:22 -07001531 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
Tao Wu135f4ab2016-09-16 13:01:24 -07001532 if (server_port_str && strlen(server_port_str) > 0) {
1533 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
1534 fprintf(stderr,
1535 "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive"
1536 " number less than 65535. Got \"%s\"\n",
1537 server_port_str);
1538 exit(1);
1539 }
1540 }
Josh Gao9c869b52016-08-25 16:00:22 -07001541
1542 int rc;
1543 char* temp;
1544 if (server_host_str) {
Tao Wu135f4ab2016-09-16 13:01:24 -07001545 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
Josh Gao9c869b52016-08-25 16:00:22 -07001546 } else {
Tao Wu135f4ab2016-09-16 13:01:24 -07001547 rc = asprintf(&temp, "tcp:%d", server_port);
Josh Gao9c869b52016-08-25 16:00:22 -07001548 }
1549 if (rc < 0) {
1550 fatal("failed to allocate server socket specification");
1551 }
1552 server_socket_str = temp;
1553 }
1554
1555 adb_set_socket_spec(server_socket_str);
1556
Elliott Hughes8d28e192015-10-07 14:55:10 -07001557 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1558 if (transport_type == kTransportAny && serial == nullptr) {
1559 serial = getenv("ANDROID_SERIAL");
1560 }
1561
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001562 adb_set_transport(transport_type, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001563
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001564 if (is_server) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001565 if (no_daemon || is_daemon) {
Spencer Low5c398d22015-08-08 15:07:07 -07001566 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001567 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001568 return 1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001569 }
Josh Gao9c869b52016-08-25 16:00:22 -07001570 r = adb_server_main(is_daemon, server_socket_str, ack_reply_fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001571 } else {
Josh Gao9c869b52016-08-25 16:00:22 -07001572 r = launch_server(server_socket_str);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001573 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001574 if (r) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001575 fprintf(stderr,"* could not start server *\n");
1576 }
1577 return r;
1578 }
1579
Riley Andrews98f58e82014-12-05 17:37:24 -08001580 if (argc == 0) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001581 help();
1582 return 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001583 }
1584
Riley Andrewsc8514c82014-12-05 17:32:46 -08001585 /* handle wait-for-* prefix */
1586 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertbac34742015-02-25 17:51:28 -08001587 const char* service = argv[0];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001588
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001589 if (!wait_for_device(service, transport_type, serial)) {
Riley Andrewsc8514c82014-12-05 17:32:46 -08001590 return 1;
1591 }
1592
Elliott Hughes2b101112015-05-04 19:29:32 -07001593 // Allow a command to be run after wait-for-device,
1594 // e.g. 'adb wait-for-device shell'.
Riley Andrewsc8514c82014-12-05 17:32:46 -08001595 if (argc == 1) {
1596 return 0;
1597 }
1598
1599 /* Fall through */
1600 argc--;
1601 argv++;
1602 }
1603
1604 /* adb_connect() commands */
Riley Andrews98f58e82014-12-05 17:37:24 -08001605 if (!strcmp(argv[0], "devices")) {
Dan Albertbac34742015-02-25 17:51:28 -08001606 const char *listopt;
Elliott Hughes6452a892015-04-29 12:28:13 -07001607 if (argc < 2) {
Scott Andersone109d262012-04-20 11:21:14 -07001608 listopt = "";
Elliott Hughes6452a892015-04-29 12:28:13 -07001609 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Andersone109d262012-04-20 11:21:14 -07001610 listopt = argv[1];
Elliott Hughes6452a892015-04-29 12:28:13 -07001611 } else {
Scott Andersone109d262012-04-20 11:21:14 -07001612 fprintf(stderr, "Usage: adb devices [-l]\n");
1613 return 1;
1614 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001615
1616 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
1617 printf("List of devices attached\n");
1618 return adb_query_command(query);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001619 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001620 else if (!strcmp(argv[0], "connect")) {
Mike Lockwoodff196702009-08-24 15:58:40 -07001621 if (argc != 2) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001622 fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
Mike Lockwoodff196702009-08-24 15:58:40 -07001623 return 1;
1624 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001625
1626 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1627 return adb_query_command(query);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001628 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001629 else if (!strcmp(argv[0], "disconnect")) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001630 if (argc > 2) {
1631 fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
1632 return 1;
1633 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001634
1635 std::string query = android::base::StringPrintf("host:disconnect:%s",
1636 (argc == 2) ? argv[1] : "");
1637 return adb_query_command(query);
Mike Lockwoodff196702009-08-24 15:58:40 -07001638 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001639 else if (!strcmp(argv[0], "emu")) {
Spencer Low142ec752015-05-06 16:13:42 -07001640 return adb_send_emulator_command(argc, argv, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001641 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08001642 else if (!strcmp(argv[0], "shell")) {
Josh Gaof3f6a1d2016-01-31 19:12:26 -08001643 return adb_shell(argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001644 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001645 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001646 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001647
Zach Riggleccafc792016-04-14 17:18:04 -04001648 if (argc < 2) {
1649 fprintf(stderr, "Usage: adb %s command\n", argv[0]);
1650 return 1;
1651 }
1652
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001653 std::string cmd = "exec:";
1654 cmd += argv[1];
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001655 argc -= 2;
1656 argv += 2;
1657 while (argc-- > 0) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001658 cmd += " " + escape_arg(*argv++);
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001659 }
1660
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001661 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001662 int fd = adb_connect(cmd, &error);
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001663 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001664 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001665 return -1;
1666 }
1667
1668 if (exec_in) {
1669 copy_to_file(STDIN_FILENO, fd);
1670 } else {
1671 copy_to_file(fd, STDOUT_FILENO);
1672 }
1673
1674 adb_close(fd);
1675 return 0;
1676 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001677 else if (!strcmp(argv[0], "kill-server")) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001678 std::string error;
1679 int fd = _adb_connect("host:kill", &error);
Spencer Lowf18fc082015-08-11 17:05:02 -07001680 if (fd == -2) {
1681 // Failed to make network connection to server. Don't output the
1682 // network error since that is expected.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001683 fprintf(stderr,"* server not running *\n");
Spencer Lowf18fc082015-08-11 17:05:02 -07001684 // Successful exit code because the server is already "killed".
1685 return 0;
1686 } else if (fd == -1) {
1687 // Some other error.
1688 fprintf(stderr, "error: %s\n", error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001689 return 1;
Spencer Lowf18fc082015-08-11 17:05:02 -07001690 } else {
1691 // Successfully connected, kill command sent, okay status came back.
1692 // Server should exit() in a moment, if not already.
Spencer Low351ecd12015-10-14 17:32:44 -07001693 ReadOrderlyShutdown(fd);
Spencer Lowf18fc082015-08-11 17:05:02 -07001694 adb_close(fd);
1695 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001696 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001697 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001698 else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001699 if (argc != 2) return usage("sideload requires an argument");
Doug Zongker71fe5842014-06-26 15:35:36 -07001700 if (adb_sideload_host(argv[1])) {
Doug Zongker447f0612012-01-09 14:54:53 -08001701 return 1;
1702 } else {
1703 return 0;
1704 }
1705 }
Elliott Hughes19d80b82015-07-21 16:13:40 -07001706 else if (!strcmp(argv[0], "tcpip") && argc > 1) {
1707 return adb_connect_command(android::base::StringPrintf("tcpip:%s", argv[1]));
1708 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001709 else if (!strcmp(argv[0], "remount") ||
1710 !strcmp(argv[0], "reboot") ||
1711 !strcmp(argv[0], "reboot-bootloader") ||
Riley Andrewsc8514c82014-12-05 17:32:46 -08001712 !strcmp(argv[0], "usb") ||
Riley Andrewsc8514c82014-12-05 17:32:46 -08001713 !strcmp(argv[0], "disable-verity") ||
1714 !strcmp(argv[0], "enable-verity")) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001715 std::string command;
Tao Bao175b7bb2015-03-29 11:22:34 -07001716 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001717 command = "reboot:bootloader";
Tao Bao175b7bb2015-03-29 11:22:34 -07001718 } else if (argc > 1) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001719 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao175b7bb2015-03-29 11:22:34 -07001720 } else {
Elliott Hughes5677c232015-05-07 23:37:40 -07001721 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Projecte037fd72009-03-13 13:04:37 -07001722 }
Tao Bao175b7bb2015-03-29 11:22:34 -07001723 return adb_connect_command(command);
Josh Gao06c73ae2016-03-04 15:16:18 -08001724 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1725 return adb_root(argv[0]) ? 0 : 1;
1726 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme698e0652016-07-19 17:07:22 -07001727 Bugreport bugreport;
1728 return bugreport.DoIt(transport_type, serial, argc, argv);
Felipe Leme44a42672016-04-01 17:43:27 -07001729 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughes424af022015-05-29 17:55:19 -07001730 bool reverse = !strcmp(argv[0], "reverse");
1731 ++argv;
1732 --argc;
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001733 if (argc < 1) return usage("%s requires an argument", argv[0]);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001734
1735 // Determine the <host-prefix> for this command.
Elliott Hughes424af022015-05-29 17:55:19 -07001736 std::string host_prefix;
David 'Digit' Turner25258692013-03-21 21:07:42 +01001737 if (reverse) {
Elliott Hughes424af022015-05-29 17:55:19 -07001738 host_prefix = "reverse";
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001739 } else {
David 'Digit' Turner25258692013-03-21 21:07:42 +01001740 if (serial) {
Elliott Hughes424af022015-05-29 17:55:19 -07001741 host_prefix = android::base::StringPrintf("host-serial:%s", serial);
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001742 } else if (transport_type == kTransportUsb) {
Elliott Hughes424af022015-05-29 17:55:19 -07001743 host_prefix = "host-usb";
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001744 } else if (transport_type == kTransportLocal) {
Elliott Hughes424af022015-05-29 17:55:19 -07001745 host_prefix = "host-local";
David 'Digit' Turner25258692013-03-21 21:07:42 +01001746 } else {
Elliott Hughes424af022015-05-29 17:55:19 -07001747 host_prefix = "host";
David 'Digit' Turner25258692013-03-21 21:07:42 +01001748 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001749 }
1750
David Purselleaae97e2016-04-07 11:25:48 -07001751 std::string cmd, error;
Elliott Hughes424af022015-05-29 17:55:19 -07001752 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001753 if (argc != 1) return usage("--list doesn't take any arguments");
Elliott Hughes424af022015-05-29 17:55:19 -07001754 return adb_query_command(host_prefix + ":list-forward");
1755 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001756 if (argc != 1) return usage("--remove-all doesn't take any arguments");
Elliott Hughes424af022015-05-29 17:55:19 -07001757 cmd = host_prefix + ":killforward-all";
1758 } else if (strcmp(argv[0], "--remove") == 0) {
1759 // forward --remove <local>
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001760 if (argc != 2) return usage("--remove requires an argument");
Elliott Hughes424af022015-05-29 17:55:19 -07001761 cmd = host_prefix + ":killforward:" + argv[1];
1762 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1763 // forward --no-rebind <local> <remote>
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001764 if (argc != 3) return usage("--no-rebind takes two arguments");
David Purselleaae97e2016-04-07 11:25:48 -07001765 if (forward_targets_are_valid(argv[1], argv[2], &error)) {
1766 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
1767 }
Elliott Hughes424af022015-05-29 17:55:19 -07001768 } else {
1769 // forward <local> <remote>
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001770 if (argc != 2) return usage("forward takes two arguments");
David Purselleaae97e2016-04-07 11:25:48 -07001771 if (forward_targets_are_valid(argv[0], argv[1], &error)) {
1772 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
1773 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001774 }
1775
David Purselleaae97e2016-04-07 11:25:48 -07001776 if (!error.empty()) {
1777 fprintf(stderr, "error: %s\n", error.c_str());
1778 return 1;
1779 }
1780
1781 int fd = adb_connect(cmd, &error);
1782 if (fd < 0 || !adb_status(fd, &error)) {
1783 adb_close(fd);
1784 fprintf(stderr, "error: %s\n", error.c_str());
1785 return 1;
1786 }
1787
1788 // Server or device may optionally return a resolved TCP port number.
1789 std::string resolved_port;
1790 if (ReadProtocolString(fd, &resolved_port, &error) && !resolved_port.empty()) {
1791 printf("%s\n", resolved_port.c_str());
1792 }
1793
1794 ReadOrderlyShutdown(fd);
1795 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001796 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001797 /* do_sync_*() commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001798 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001799 if (argc != 2) return usage("ls requires an argument");
Elliott Hughesaa245492015-08-03 10:38:08 -07001800 return do_sync_ls(argv[1]) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001801 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001802 else if (!strcmp(argv[0], "push")) {
Josh Gao05786772015-10-30 16:57:19 -07001803 bool copy_attrs = false;
1804 std::vector<const char*> srcs;
1805 const char* dst = nullptr;
Mark Lindner76f2a932014-03-11 17:55:59 -07001806
Josh Gao05786772015-10-30 16:57:19 -07001807 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001808 if (srcs.empty() || !dst) return usage("push requires an argument");
Josh Gao05786772015-10-30 16:57:19 -07001809 return do_sync_push(srcs, dst) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001810 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001811 else if (!strcmp(argv[0], "pull")) {
Josh Gao05786772015-10-30 16:57:19 -07001812 bool copy_attrs = false;
1813 std::vector<const char*> srcs;
1814 const char* dst = ".";
Mark Lindner76f2a932014-03-11 17:55:59 -07001815
Josh Gao05786772015-10-30 16:57:19 -07001816 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001817 if (srcs.empty()) return usage("pull requires an argument");
Josh Gao05786772015-10-30 16:57:19 -07001818 return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001819 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001820 else if (!strcmp(argv[0], "install")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001821 if (argc < 2) return usage("install requires an argument");
Todd Kennedy248722e2016-07-20 16:22:37 -07001822 if (_use_legacy_install()) {
1823 return install_app_legacy(transport_type, serial, argc, argv);
David Pursell0aacbbe2016-01-21 19:56:50 -08001824 }
Todd Kennedy248722e2016-07-20 16:22:37 -07001825 return install_app(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001826 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001827 else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001828 if (argc < 2) return usage("install-multiple requires an argument");
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001829 return install_multiple_app(transport_type, serial, argc, argv);
Jeff Sharkey960df972014-06-09 17:30:57 -07001830 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001831 else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001832 if (argc < 2) return usage("uninstall requires an argument");
Todd Kennedy248722e2016-07-20 16:22:37 -07001833 if (_use_legacy_install()) {
1834 return uninstall_app_legacy(transport_type, serial, argc, argv);
David Pursell0aacbbe2016-01-21 19:56:50 -08001835 }
Todd Kennedy248722e2016-07-20 16:22:37 -07001836 return uninstall_app(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001837 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001838 else if (!strcmp(argv[0], "sync")) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001839 std::string src;
Elliott Hughes58305772015-04-17 13:57:15 -07001840 bool list_only = false;
Riley Andrews98f58e82014-12-05 17:37:24 -08001841 if (argc < 2) {
Elliott Hughes58305772015-04-17 13:57:15 -07001842 // No local path was specified.
Elliott Hughesd236d072015-04-21 10:17:07 -07001843 src = "";
Anthony Newnam705c9442010-02-22 08:36:49 -06001844 } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001845 list_only = true;
Anthony Newnam705c9442010-02-22 08:36:49 -06001846 if (argc == 3) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001847 src = argv[2];
Anthony Newnam705c9442010-02-22 08:36:49 -06001848 } else {
Elliott Hughesd236d072015-04-21 10:17:07 -07001849 src = "";
Anthony Newnam705c9442010-02-22 08:36:49 -06001850 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001851 } else if (argc == 2) {
Elliott Hughes58305772015-04-17 13:57:15 -07001852 // A local path or "android"/"data" arg was specified.
Elliott Hughesd236d072015-04-21 10:17:07 -07001853 src = argv[1];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001854 } else {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001855 return usage("usage: adb sync [-l] [PARTITION]");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001856 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001857
Elliott Hughesd236d072015-04-21 10:17:07 -07001858 if (src != "" &&
1859 src != "system" && src != "data" && src != "vendor" && src != "oem") {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001860 return usage("don't know how to sync %s partition", src.c_str());
Elliott Hughes58305772015-04-17 13:57:15 -07001861 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001862
Elliott Hughes58305772015-04-17 13:57:15 -07001863 std::string system_src_path = product_file("system");
1864 std::string data_src_path = product_file("data");
1865 std::string vendor_src_path = product_file("vendor");
1866 std::string oem_src_path = product_file("oem");
Elliott Hughes58305772015-04-17 13:57:15 -07001867
Elliott Hughesaa245492015-08-03 10:38:08 -07001868 bool okay = true;
1869 if (okay && (src.empty() || src == "system")) {
1870 okay = do_sync_sync(system_src_path, "/system", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001871 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001872 if (okay && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) {
1873 okay = do_sync_sync(vendor_src_path, "/vendor", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001874 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001875 if (okay && (src.empty() || src == "oem") && directory_exists(oem_src_path)) {
1876 okay = do_sync_sync(oem_src_path, "/oem", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001877 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001878 if (okay && (src.empty() || src == "data")) {
1879 okay = do_sync_sync(data_src_path, "/data", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001880 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001881 return okay ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001882 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001883 /* passthrough commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001884 else if (!strcmp(argv[0],"get-state") ||
Scott Andersone109d262012-04-20 11:21:14 -07001885 !strcmp(argv[0],"get-serialno") ||
1886 !strcmp(argv[0],"get-devpath"))
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001887 {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001888 return adb_query_command(format_host_command(argv[0], transport_type, serial));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001889 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001890 /* other commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001891 else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001892 return logcat(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001893 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001894 else if (!strcmp(argv[0],"ppp")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001895 return ppp(argc, argv);
1896 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001897 else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001898 std::string error;
Spencer Lowf18fc082015-08-11 17:05:02 -07001899 const int result = adb_connect("host:start-server", &error);
1900 if (result < 0) {
1901 fprintf(stderr, "error: %s\n", error.c_str());
1902 }
1903 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001904 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001905 else if (!strcmp(argv[0], "backup")) {
Christopher Tated2f54152011-04-21 12:53:28 -07001906 return backup(argc, argv);
1907 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001908 else if (!strcmp(argv[0], "restore")) {
Christopher Tate702967a2011-05-17 15:52:54 -07001909 return restore(argc, argv);
1910 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001911 else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001912 if (argc != 2) return usage("keygen requires an argument");
Yabin Cuiaed3c612015-09-22 15:52:57 -07001913 // Always print key generation information for keygen command.
1914 adb_trace_enable(AUTH);
Nick Kralevichbea3f9c2014-11-13 15:17:29 -08001915 return adb_auth_keygen(argv[1]);
1916 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001917 else if (!strcmp(argv[0], "jdwp")) {
Tao Bao175b7bb2015-03-29 11:22:34 -07001918 return adb_connect_command("jdwp");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001919 }
Josh Gaob463baf2016-05-13 18:18:23 -07001920 else if (!strcmp(argv[0], "track-jdwp")) {
1921 return adb_connect_command("track-jdwp");
1922 }
1923 else if (!strcmp(argv[0], "track-devices")) {
1924 return adb_connect_command("host:track-devices");
1925 }
1926
1927
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001928 /* "adb /?" is a common idiom under Windows */
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001929 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001930 help();
1931 return 0;
1932 }
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001933 else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughes42ae2602015-08-12 08:32:10 -07001934 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001935 return 0;
Josh Gao5d1756c2017-02-22 17:07:01 -08001936 } else if (!strcmp(argv[0], "features")) {
David Pursell4e2fd362015-09-22 10:43:08 -07001937 // Only list the features common to both the adb client and the device.
David Pursell0aacbbe2016-01-21 19:56:50 -08001938 FeatureSet features;
Josh Gaof3f6a1d2016-01-31 19:12:26 -08001939 std::string error;
1940 if (!adb_get_feature_set(&features, &error)) {
1941 fprintf(stderr, "error: %s\n", error.c_str());
David Pursell0aacbbe2016-01-21 19:56:50 -08001942 return 1;
1943 }
1944
David Pursell4e2fd362015-09-22 10:43:08 -07001945 for (const std::string& name : features) {
David Pursell70ef7b42015-09-30 13:35:42 -07001946 if (CanUseFeature(features, name)) {
David Pursell4e2fd362015-09-22 10:43:08 -07001947 printf("%s\n", name.c_str());
1948 }
1949 }
1950 return 0;
Josh Gao5d1756c2017-02-22 17:07:01 -08001951 } else if (!strcmp(argv[0], "host-features")) {
1952 return adb_query_command("host:host-features");
Yabin Cui1f4ec192016-04-05 13:50:44 -07001953 } else if (!strcmp(argv[0], "reconnect")) {
1954 if (argc == 1) {
1955 return adb_query_command("host:reconnect");
Josh Gao22d2b3e2016-10-27 14:01:08 -07001956 } else if (argc == 2) {
1957 if (!strcmp(argv[1], "device")) {
1958 std::string err;
1959 adb_connect("reconnect", &err);
1960 return 0;
1961 } else if (!strcmp(argv[1], "offline")) {
1962 std::string err;
1963 return adb_query_command("host:reconnect-offline");
1964 } else {
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001965 return usage("usage: adb reconnect [device|offline]");
Josh Gao22d2b3e2016-10-27 14:01:08 -07001966 }
Yabin Cui1f4ec192016-04-05 13:50:44 -07001967 }
Dan Albert90d4b732015-05-20 18:58:41 -07001968 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001969
Elliott Hughes2ec36b02017-02-06 16:20:30 -08001970 usage("unknown command %s", argv[0]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001971 return 1;
1972}
1973
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001974static int uninstall_app(TransportType transport, const char* serial, int argc, const char** argv) {
1975 // 'adb uninstall' takes the same arguments as 'cmd package uninstall' on device
1976 std::string cmd = "cmd package";
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001977 while (argc-- > 0) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001978 // deny the '-k' option until the remaining data/cache can be removed with adb/UI
1979 if (strcmp(*argv, "-k") == 0) {
1980 printf(
1981 "The -k option uninstalls the application while retaining the data/cache.\n"
1982 "At the moment, there is no way to remove the remaining data.\n"
1983 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
1984 "If you truly wish to continue, execute 'adb shell cmd package uninstall -k'.\n");
1985 return EXIT_FAILURE;
1986 }
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001987 cmd += " " + escape_arg(*argv++);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001988 }
1989
David Pursell70ef7b42015-09-30 13:35:42 -07001990 return send_shell_command(transport, serial, cmd, false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001991}
1992
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001993static int install_app(TransportType transport, const char* serial, int argc, const char** argv) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001994 // The last argument must be the APK file
1995 const char* file = argv[argc - 1];
Elliott Hughes72884782016-10-24 18:29:21 -07001996 if (!android::base::EndsWithIgnoreCase(file, ".apk")) {
1997 fprintf(stderr, "Filename doesn't end .apk: %s\n", file);
1998 return EXIT_FAILURE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001999 }
2000
Elliott Hughes72884782016-10-24 18:29:21 -07002001 struct stat sb;
2002 if (stat(file, &sb) == -1) {
2003 fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
2004 return 1;
Kenny Root597ea5b2011-08-05 11:19:45 -07002005 }
2006
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002007 int localFd = adb_open(file, O_RDONLY);
2008 if (localFd < 0) {
2009 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
2010 return 1;
2011 }
Kenny Root597ea5b2011-08-05 11:19:45 -07002012
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002013 std::string error;
2014 std::string cmd = "exec:cmd package";
2015
2016 // don't copy the APK name, but, copy the rest of the arguments as-is
2017 while (argc-- > 1) {
2018 cmd += " " + escape_arg(std::string(*argv++));
2019 }
2020
2021 // add size parameter [required for streaming installs]
2022 // do last to override any user specified value
2023 cmd += " " + android::base::StringPrintf("-S %" PRIu64, static_cast<uint64_t>(sb.st_size));
2024
2025 int remoteFd = adb_connect(cmd, &error);
2026 if (remoteFd < 0) {
2027 fprintf(stderr, "Connect error for write: %s\n", error.c_str());
2028 adb_close(localFd);
2029 return 1;
2030 }
2031
2032 char buf[BUFSIZ];
2033 copy_to_file(localFd, remoteFd);
2034 read_status_line(remoteFd, buf, sizeof(buf));
2035
2036 adb_close(localFd);
2037 adb_close(remoteFd);
2038
2039 if (strncmp("Success", buf, 7)) {
Elliott Hughesfe018852015-12-17 14:04:38 -08002040 fprintf(stderr, "Failed to install %s: %s", file, buf);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002041 return 1;
2042 }
2043 fputs(buf, stderr);
2044 return 0;
Jeff Sharkey960df972014-06-09 17:30:57 -07002045}
2046
Elliott Hughes3bd73c12015-05-05 13:10:43 -07002047static int install_multiple_app(TransportType transport, const char* serial, int argc,
Elliott Hughes58305772015-04-17 13:57:15 -07002048 const char** argv)
Jeff Sharkey960df972014-06-09 17:30:57 -07002049{
Jeff Sharkey960df972014-06-09 17:30:57 -07002050 // Find all APK arguments starting at end.
2051 // All other arguments passed through verbatim.
2052 int first_apk = -1;
Elliott Hughes72884782016-10-24 18:29:21 -07002053 uint64_t total_size = 0;
2054 for (int i = argc - 1; i >= 0; i--) {
Dan Albertbac34742015-02-25 17:51:28 -08002055 const char* file = argv[i];
Jeff Sharkey960df972014-06-09 17:30:57 -07002056
Elliott Hughes72884782016-10-24 18:29:21 -07002057 if (android::base::EndsWithIgnoreCase(file, ".apk")) {
2058 struct stat sb;
2059 if (stat(file, &sb) != -1) total_size += sb.st_size;
Jeff Sharkey960df972014-06-09 17:30:57 -07002060 first_apk = i;
2061 } else {
2062 break;
2063 }
Kenny Root597ea5b2011-08-05 11:19:45 -07002064 }
2065
Jeff Sharkey960df972014-06-09 17:30:57 -07002066 if (first_apk == -1) {
Elliott Hughes72884782016-10-24 18:29:21 -07002067 fprintf(stderr, "No APK file on command line\n");
Jeff Sharkey960df972014-06-09 17:30:57 -07002068 return 1;
2069 }
Kenny Root597ea5b2011-08-05 11:19:45 -07002070
Todd Kennedy248722e2016-07-20 16:22:37 -07002071 std::string install_cmd;
2072 if (_use_legacy_install()) {
2073 install_cmd = "exec:pm";
2074 } else {
2075 install_cmd = "exec:cmd package";
2076 }
2077
2078 std::string cmd = android::base::StringPrintf("%s install-create -S %" PRIu64, install_cmd.c_str(), total_size);
Elliott Hughes72884782016-10-24 18:29:21 -07002079 for (int i = 1; i < first_apk; i++) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07002080 cmd += " " + escape_arg(argv[i]);
Jeff Sharkey960df972014-06-09 17:30:57 -07002081 }
2082
2083 // Create install session
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002084 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07002085 int fd = adb_connect(cmd, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07002086 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002087 fprintf(stderr, "Connect error for create: %s\n", error.c_str());
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002088 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07002089 }
Elliott Hughes2baae3a2015-04-17 10:59:34 -07002090 char buf[BUFSIZ];
Jeff Sharkey960df972014-06-09 17:30:57 -07002091 read_status_line(fd, buf, sizeof(buf));
2092 adb_close(fd);
2093
2094 int session_id = -1;
2095 if (!strncmp("Success", buf, 7)) {
2096 char* start = strrchr(buf, '[');
2097 char* end = strrchr(buf, ']');
2098 if (start && end) {
2099 *end = '\0';
2100 session_id = strtol(start + 1, NULL, 10);
2101 }
2102 }
2103 if (session_id < 0) {
2104 fprintf(stderr, "Failed to create session\n");
Christopher Tate71bbc672014-07-14 16:45:13 -07002105 fputs(buf, stderr);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002106 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07002107 }
2108
2109 // Valid session, now stream the APKs
2110 int success = 1;
Elliott Hughes72884782016-10-24 18:29:21 -07002111 for (int i = first_apk; i < argc; i++) {
Dan Albertbac34742015-02-25 17:51:28 -08002112 const char* file = argv[i];
Elliott Hughes72884782016-10-24 18:29:21 -07002113 struct stat sb;
Jeff Sharkey960df972014-06-09 17:30:57 -07002114 if (stat(file, &sb) == -1) {
Elliott Hughes72884782016-10-24 18:29:21 -07002115 fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
Jeff Sharkey960df972014-06-09 17:30:57 -07002116 success = 0;
2117 goto finalize_session;
2118 }
2119
Elliott Hughes2940ccf2015-04-17 14:07:52 -07002120 std::string cmd = android::base::StringPrintf(
Todd Kennedy248722e2016-07-20 16:22:37 -07002121 "%s install-write -S %" PRIu64 " %d %d_%s -",
Colin Cross58021d12017-02-23 21:23:05 -08002122 install_cmd.c_str(), static_cast<uint64_t>(sb.st_size), session_id, i,
2123 android::base::Basename(file).c_str());
Jeff Sharkey960df972014-06-09 17:30:57 -07002124
2125 int localFd = adb_open(file, O_RDONLY);
2126 if (localFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002127 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
Jeff Sharkey960df972014-06-09 17:30:57 -07002128 success = 0;
2129 goto finalize_session;
2130 }
2131
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002132 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07002133 int remoteFd = adb_connect(cmd, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07002134 if (remoteFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002135 fprintf(stderr, "Connect error for write: %s\n", error.c_str());
Jeff Sharkey960df972014-06-09 17:30:57 -07002136 adb_close(localFd);
2137 success = 0;
2138 goto finalize_session;
2139 }
2140
2141 copy_to_file(localFd, remoteFd);
2142 read_status_line(remoteFd, buf, sizeof(buf));
2143
2144 adb_close(localFd);
2145 adb_close(remoteFd);
2146
2147 if (strncmp("Success", buf, 7)) {
2148 fprintf(stderr, "Failed to write %s\n", file);
Christopher Tate71bbc672014-07-14 16:45:13 -07002149 fputs(buf, stderr);
Jeff Sharkey960df972014-06-09 17:30:57 -07002150 success = 0;
2151 goto finalize_session;
2152 }
2153 }
2154
2155finalize_session:
Jeff Sharkeyac77e1f2014-07-25 09:58:25 -07002156 // Commit session if we streamed everything okay; otherwise abandon
Elliott Hughes6452a892015-04-29 12:28:13 -07002157 std::string service =
Todd Kennedy248722e2016-07-20 16:22:37 -07002158 android::base::StringPrintf("%s install-%s %d",
2159 install_cmd.c_str(), success ? "commit" : "abandon", session_id);
Elliott Hughes6452a892015-04-29 12:28:13 -07002160 fd = adb_connect(service, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07002161 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07002162 fprintf(stderr, "Connect error for finalize: %s\n", error.c_str());
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002163 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07002164 }
2165 read_status_line(fd, buf, sizeof(buf));
2166 adb_close(fd);
2167
2168 if (!strncmp("Success", buf, 7)) {
Christopher Tate71bbc672014-07-14 16:45:13 -07002169 fputs(buf, stderr);
Jeff Sharkey960df972014-06-09 17:30:57 -07002170 return 0;
2171 } else {
2172 fprintf(stderr, "Failed to finalize session\n");
Christopher Tate71bbc672014-07-14 16:45:13 -07002173 fputs(buf, stderr);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002174 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07002175 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002176}
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002177
2178static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) {
2179 std::string cmd = "pm";
2180
2181 while (argc-- > 0) {
2182 cmd += " " + escape_arg(*argv++);
2183 }
2184
2185 return send_shell_command(transport, serial, cmd, false);
2186}
2187
2188static int uninstall_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
2189 /* if the user choose the -k option, we refuse to do it until devices are
2190 out with the option to uninstall the remaining data somehow (adb/ui) */
2191 int i;
2192 for (i = 1; i < argc; i++) {
2193 if (!strcmp(argv[i], "-k")) {
2194 printf(
2195 "The -k option uninstalls the application while retaining the data/cache.\n"
2196 "At the moment, there is no way to remove the remaining data.\n"
2197 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
2198 "If you truly wish to continue, execute 'adb shell pm uninstall -k'\n.");
2199 return EXIT_FAILURE;
2200 }
2201 }
2202
2203 /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
2204 return pm_command(transport, serial, argc, argv);
2205}
2206
2207static int delete_file(TransportType transport, const char* serial, const std::string& filename) {
2208 std::string cmd = "rm -f " + escape_arg(filename);
2209 return send_shell_command(transport, serial, cmd, false);
2210}
2211
2212static int install_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
2213 static const char *const DATA_DEST = "/data/local/tmp/%s";
2214 static const char *const SD_DEST = "/sdcard/tmp/%s";
2215 const char* where = DATA_DEST;
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002216
Elliott Hughes72884782016-10-24 18:29:21 -07002217 for (int i = 1; i < argc; i++) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002218 if (!strcmp(argv[i], "-s")) {
2219 where = SD_DEST;
2220 }
2221 }
2222
2223 // Find last APK argument.
2224 // All other arguments passed through verbatim.
2225 int last_apk = -1;
Elliott Hughes72884782016-10-24 18:29:21 -07002226 for (int i = argc - 1; i >= 0; i--) {
2227 if (android::base::EndsWithIgnoreCase(argv[i], ".apk")) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002228 last_apk = i;
2229 break;
2230 }
2231 }
2232
2233 if (last_apk == -1) {
Elliott Hughes72884782016-10-24 18:29:21 -07002234 fprintf(stderr, "No APK file on command line\n");
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002235 return EXIT_FAILURE;
2236 }
2237
2238 int result = -1;
2239 std::vector<const char*> apk_file = {argv[last_apk]};
2240 std::string apk_dest = android::base::StringPrintf(
Colin Cross58021d12017-02-23 21:23:05 -08002241 where, android::base::Basename(argv[last_apk]).c_str());
Todd Kennedy6fa848a2015-11-03 16:53:08 -08002242 if (!do_sync_push(apk_file, apk_dest.c_str())) goto cleanup_apk;
2243 argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
2244 result = pm_command(transport, serial, argc, argv);
2245
2246cleanup_apk:
2247 delete_file(transport, serial, apk_dest);
2248 return result;
2249}