blob: d626259f2673eb4c932ca42e2989dd883b86ceb8 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-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 Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Dan Albertdb6fe642015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
Dan Albertb302d122015-02-24 15:51:19 -080021#include <assert.h>
22#include <ctype.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080023#include <errno.h>
Elliott Hughesd1a5b2b2015-04-17 14:07:52 -070024#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <limits.h>
26#include <stdarg.h>
Dan Albertb302d122015-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 Project9ca14dc2009-03-03 19:32:55 -080031#include <sys/stat.h>
Dan Albertb302d122015-02-24 15:51:19 -080032#include <sys/types.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080033
David Pursell8a5a5aa2015-09-08 17:17:02 -070034#include <memory>
Elliott Hughes170b5682015-04-17 10:59:34 -070035#include <string>
Elliott Hughes73925982016-11-15 12:37:32 -080036#include <thread>
Josh Gao5d093b22015-10-30 16:57:19 -070037#include <vector>
Elliott Hughes170b5682015-04-17 10:59:34 -070038
Elliott Hughese0a6e2a2016-05-26 22:43:19 -070039#include <android-base/file.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080040#include <android-base/logging.h>
Tao Wucaedcb52016-09-16 13:01:24 -070041#include <android-base/parseint.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
Elliott Hughes170b5682015-04-17 10:59:34 -070044
Yabin Cui6704a3c2014-11-17 14:48:25 -080045#if !defined(_WIN32)
Josh Gaof344ecf2015-10-23 15:03:31 -070046#include <signal.h>
Elliott Hughes4c5e8042015-11-04 13:07:47 -080047#include <sys/ioctl.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080048#include <termios.h>
Dan Albertb302d122015-02-24 15:51:19 -080049#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080050#endif
51
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080052#include "adb.h"
Nick Kralevich6183c962014-11-13 15:17:29 -080053#include "adb_auth.h"
Dan Albert66a91b02015-02-24 21:26:58 -080054#include "adb_client.h"
55#include "adb_io.h"
Josh Gaoea7457b2016-08-30 15:39:25 -070056#include "adb_unique_fd.h"
Elliott Hughes38104452015-04-17 13:57:15 -070057#include "adb_utils.h"
Felipe Leme042c3512016-07-19 17:07:22 -070058#include "bugreport.h"
59#include "commandline.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080060#include "file_sync_service.h"
David Pursell22fc5e92015-09-30 13:35:42 -070061#include "services.h"
David Pursell8a5a5aa2015-09-08 17:17:02 -070062#include "shell_service.h"
Josh Gao70267e42016-11-15 18:55:47 -080063#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080064
Elliott Hughes3aec2ba2015-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 Kennedy1e2f7dc2015-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 Project9ca14dc2009-03-03 19:32:55 -080070
Josh Gaoe3a87d02015-11-11 17:56:12 -080071static auto& gProductOutPath = *new std::string();
Matt Gumbel411775c2012-11-14 10:16:17 -080072extern int gListenAll;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080073
Felipe Leme60192aa2016-07-26 12:14:39 -070074DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
75
Elliott Hughes38104452015-04-17 13:57:15 -070076static std::string product_file(const char *extra) {
77 if (gProductOutPath.empty()) {
The Android Open Source Project9ca14dc2009-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 Hughes38104452015-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 Project9ca14dc2009-03-03 19:32:55 -080085}
86
Elliott Hughes38104452015-04-17 13:57:15 -070087static void help() {
Elliott Hughes687f8b42016-09-28 15:25:47 -070088 fprintf(stdout, "%s\n", adb_version().c_str());
Felipe Lemee4893a22016-07-29 17:57:00 -070089 // clang-format off
Elliott Hughes687f8b42016-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 Hughes2d821142017-01-13 16:58:25 -080094 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -070095 " -s SERIAL\n"
Elliott Hughes2d821142017-01-13 16:58:25 -080096 " use device with given serial number (overrides $ANDROID_SERIAL)\n"
Elliott Hughes687f8b42016-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 Project9ca14dc2009-03-03 19:32:55 -0800103 "\n"
Elliott Hughes687f8b42016-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 Hughes52746b02015-06-12 14:26:29 -0700108 "\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800109 "networking:\n"
Elliott Hughes687f8b42016-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 Project9ca14dc2009-03-03 19:32:55 -0800134 "\n"
Elliott Hughes687f8b42016-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 Project9ca14dc2009-03-03 19:32:55 -0800145 "\n"
Elliott Hughes687f8b42016-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 Project9ca14dc2009-03-03 19:32:55 -0800155 "\n"
Elliott Hughes687f8b42016-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 Halsethd8dedd12017-04-11 19:15:17 +0100172 " to show usage run \"adb shell bu help\"\n"
Elliott Hughes687f8b42016-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"
Tim1b29ed32010-02-16 20:18:29 +0000209 "\n"
Yabin Cuid78ed222016-04-05 13:50:44 -0700210 "internal debugging:\n"
Elliott Hughes687f8b42016-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 Hughes52746b02015-06-12 14:26:29 -0700216 "environment variables:\n"
Elliott Hughes687f8b42016-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 Lemee4893a22016-07-29 17:57:00 -0700223 // clang-format on
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800224}
225
Yabin Cui6704a3c2014-11-17 14:48:25 -0800226#if defined(_WIN32)
227
Elliott Hughes6a096932015-04-16 16:47:02 -0700228// Implemented in sysdeps_win32.cpp.
Elliott Hughesa8265792015-11-03 11:18:40 -0800229void stdin_raw_init();
230void stdin_raw_restore();
Yabin Cui6704a3c2014-11-17 14:48:25 -0800231
232#else
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100233static termios g_saved_terminal_state;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800234
Elliott Hughesa8265792015-11-03 11:18:40 -0800235static void stdin_raw_init() {
236 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800237
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100238 termios tio;
Elliott Hughesa8265792015-11-03 11:18:40 -0800239 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800240
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100241 cfmakeraw(&tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800242
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100243 // No timeout but request at least one character per read.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800244 tio.c_cc[VTIME] = 0;
245 tio.c_cc[VMIN] = 1;
246
Elliott Hughesa8265792015-11-03 11:18:40 -0800247 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800248}
249
Elliott Hughesa8265792015-11-03 11:18:40 -0800250static void stdin_raw_restore() {
251 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800252}
253#endif
254
David Pursell8a5a5aa2015-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 Leme60192aa2016-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 Pursell8a5a5aa2015-09-08 17:17:02 -0700262 int exit_code = 0;
Felipe Leme5ad50902016-06-06 16:05:36 -0700263 if (fd < 0) return exit_code;
264
David Pursell8a5a5aa2015-09-08 17:17:02 -0700265 std::unique_ptr<ShellProtocol> protocol;
266 int length = 0;
David Pursell8a5a5aa2015-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 Leme5ad50902016-06-06 16:05:36 -0700279 while (true) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700280 if (use_shell_protocol) {
281 if (!protocol->Read()) {
282 break;
283 }
Felipe Leme60192aa2016-07-26 12:14:39 -0700284 length = protocol->data_length();
David Pursell8a5a5aa2015-09-08 17:17:02 -0700285 switch (protocol->id()) {
286 case ShellProtocol::kIdStdout:
Felipe Leme60192aa2016-07-26 12:14:39 -0700287 callback->OnStdout(buffer_ptr, length);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700288 break;
289 case ShellProtocol::kIdStderr:
Felipe Leme60192aa2016-07-26 12:14:39 -0700290 callback->OnStderr(buffer_ptr, length);
David Pursell8a5a5aa2015-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 Leme60192aa2016-07-26 12:14:39 -0700306 callback->OnStdout(buffer_ptr, length);
Felipe Lemeb6447032016-04-01 17:43:27 -0700307 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800308 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700309
Felipe Leme60192aa2016-07-26 12:14:39 -0700310 return callback->Done(exit_code);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800311}
312
Jeff Sharkey0e0d2512014-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 Hughes0bd85872015-08-25 10:59:45 -0700318 if (len <= 0) {
Jeff Sharkey0e0d2512014-06-09 17:30:57 -0700319 break;
320 }
321
322 buf += len;
323 count -= len;
324 }
325 *buf = '\0';
326}
327
Christopher Tatee0e9f562016-07-06 13:22:22 -0700328static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700329 if (inFd == STDIN_FILENO) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800330 stdin_raw_init();
Spencer Lowe7af2d32015-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 Sharkeyc52ec1a2014-05-26 18:30:43 -0700337 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800338
Spencer Lowe7af2d32015-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 Tatee0e9f562016-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 Lowe7af2d32015-05-22 16:48:31 -0700380
Elliott Hughes7cf35752015-04-17 17:03:59 -0700381 while (true) {
Jeff Sharkeyc52ec1a2014-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 Tate73779122011-04-21 12:53:28 -0700387 if (len == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700388 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tate73779122011-04-21 12:53:28 -0700389 break;
390 }
391 if (len < 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700392 D("copy_to_file(): read failed: %s", strerror(errno));
Christopher Tate73779122011-04-21 12:53:28 -0700393 break;
394 }
Jeff Sharkeyc52ec1a2014-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 Tatefba22972011-06-01 17:56:23 -0700401 total += len;
Christopher Tate73779122011-04-21 12:53:28 -0700402 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800403
Christopher Tatee0e9f562016-07-06 13:22:22 -0700404 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700405
Yabin Cui815ad882015-09-02 17:44:28 -0700406 D("copy_to_file() finished after %lu bytes", total);
Christopher Tatea162e242011-06-10 11:38:37 -0700407 free(buf);
Christopher Tate73779122011-04-21 12:53:28 -0700408}
409
Elliott Hughesa8265792015-11-03 11:18:40 -0800410static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800411 // Old devices can't handle window size changes.
412 if (shell == nullptr) return;
413
Spencer Low55441402015-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 Hughesa8265792015-11-03 11:18:40 -0800423 winsize ws;
Spencer Low55441402015-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 Hughesa8265792015-11-03 11:18:40 -0800444 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
Spencer Low55441402015-11-07 17:34:39 -0800445#endif
Elliott Hughesa8265792015-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 Hughesa8265792015-11-03 11:18:40 -0800451}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800452
David Pursell8a5a5aa2015-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 Pursell3fe11f62015-10-06 15:30:03 -0700456 bool raw_stdin;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700457 std::unique_ptr<ShellProtocol> protocol;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800458 char escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700459};
460
David Pursell8a5a5aa2015-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 Gao382ea6e2016-02-12 14:31:15 -0800464static void stdin_read_thread_loop(void* x) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700465 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800466
Elliott Hughesa8265792015-11-03 11:18:40 -0800467#if !defined(_WIN32)
468 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gaof344ecf2015-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 Low55441402015-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 Hughesa8265792015-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 Hughes4cf6f102015-11-04 13:36:32 -0800490 char raw_buffer[BUFSIZ];
David Pursell8a5a5aa2015-09-08 17:17:02 -0700491 char* buffer_ptr = raw_buffer;
492 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesa8265792015-11-03 11:18:40 -0800493 if (args->protocol != nullptr) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700494 buffer_ptr = args->protocol->data();
495 buffer_size = args->protocol->data_capacity();
496 }
497
Elliott Hughes4cf6f102015-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 Hughesb628cb12015-08-03 10:38:08 -0700506 while (true) {
Spencer Low55441402015-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 Hughesa8265792015-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 Low55441402015-11-07 17:34:39 -0800515 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
David Pursell3fe11f62015-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 Hughes4cf6f102015-11-04 13:36:32 -0800526 // If we made stdin raw, check input for escape sequences. In
David Pursell3fe11f62015-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 Hughes4cf6f102015-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 Hughesa8265792015-11-03 11:18:40 -0800545 stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700546 exit(0);
Elliott Hughes4cf6f102015-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 Pursell3fe11f62015-10-06 15:30:03 -0700553 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800554 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800555 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800556 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800557 }
David Pursell8a5a5aa2015-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 Project9ca14dc2009-03-03 19:32:55 -0800566 }
567 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800568}
569
David Pursell3fe11f62015-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 Hughes401847e2015-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 Pursell3fe11f62015-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 Hughes4cf6f102015-11-04 13:36:32 -0800603 char escape_char,
David Pursell3fe11f62015-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 Hughes04a98c22015-04-29 08:35:59 -0700614 std::string error;
David Pursella07dbad2015-09-22 10:43:08 -0700615 int fd = adb_connect(service_string, &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700616 if (fd < 0) {
617 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800618 return 1;
619 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800620
David Pursell8a5a5aa2015-09-08 17:17:02 -0700621 StdinReadArgs* args = new StdinReadArgs;
622 if (!args) {
623 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesd0269c92015-04-21 19:39:52 -0700624 return 1;
625 }
David Pursell3fe11f62015-10-06 15:30:03 -0700626 args->stdin_fd = STDIN_FILENO;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700627 args->write_fd = fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700628 args->raw_stdin = raw_stdin;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800629 args->escape_char = escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700630 if (use_shell_protocol) {
631 args->protocol.reset(new ShellProtocol(args->write_fd));
632 }
Elliott Hughesd0269c92015-04-21 19:39:52 -0700633
Elliott Hughesa8265792015-11-03 11:18:40 -0800634 if (raw_stdin) stdin_raw_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800635
Elliott Hughesa8265792015-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?
Josh Gao0f3312a2017-04-12 17:00:49 -0700658 std::thread(stdin_read_thread_loop, args).detach();
659 int exit_code = read_and_dump(fd, use_shell_protocol);
Elliott Hughesf2517142015-05-05 13:41:21 -0700660
Elliott Hughesa8265792015-11-03 11:18:40 -0800661 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell3fe11f62015-10-06 15:30:03 -0700662
Elliott Hughesa8265792015-11-03 11:18:40 -0800663 // TODO: we should probably install signal handlers for this.
664 // TODO: can we use atexit? even on Windows?
665 if (raw_stdin) stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700666
David Pursell8a5a5aa2015-09-08 17:17:02 -0700667 return exit_code;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800668}
669
Josh Gao91d53b52016-01-31 19:12:26 -0800670static int adb_shell(int argc, const char** argv) {
David Pursell9650d862016-01-21 19:56:50 -0800671 FeatureSet features;
Josh Gao91d53b52016-01-31 19:12:26 -0800672 std::string error;
Josh Gao91d53b52016-01-31 19:12:26 -0800673 if (!adb_get_feature_set(&features, &error)) {
674 fprintf(stderr, "error: %s\n", error.c_str());
David Pursell9650d862016-01-21 19:56:50 -0800675 return 1;
676 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800677
Elliott Hughes02e33782016-10-19 14:47:11 -0700678 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
679
680 // Defaults.
681 char escape_char = '~'; // -e
682 bool use_shell_protocol = CanUseFeature(features, kFeatureShell2); // -x
683 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
Elliott Hughesda945812015-04-29 12:28:13 -0700684
Elliott Hughesa8265792015-11-03 11:18:40 -0800685 // Parse shell-specific command-line options.
Elliott Hughes02e33782016-10-19 14:47:11 -0700686 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
687 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
688 int opt;
689 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
690 switch (opt) {
691 case 'e':
692 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
Elliott Hughes65bc2272017-04-18 14:34:16 -0700693 return syntax_error("-e requires a single-character argument or 'none'");
Elliott Hughes02e33782016-10-19 14:47:11 -0700694 }
695 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
696 break;
697 case 'n':
698 close_stdin();
699 break;
700 case 'x':
701 // This option basically asks for historical behavior, so set options that
702 // correspond to the historical defaults. This is slightly weird in that -Tx
703 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
704 // be our least worst choice...
705 use_shell_protocol = false;
706 tty = kPtyDefinitely;
707 escape_char = '~';
708 break;
709 case 't':
710 // Like ssh, -t arguments are cumulative so that multiple -t's
711 // are needed to force a PTY.
712 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
713 break;
714 case 'T':
715 tty = kPtyNo;
716 break;
717 default:
718 // getopt(3) already printed an error message for us.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800719 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800720 }
Elliott Hughesda945812015-04-29 12:28:13 -0700721 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800722
Elliott Hughes02e33782016-10-19 14:47:11 -0700723 bool is_interactive = (optind == argc);
David Pursell182dc322016-01-27 16:07:52 -0800724
Elliott Hughes02e33782016-10-19 14:47:11 -0700725 std::string shell_type_arg = kShellServiceArgPty;
726 if (tty == kPtyNo) {
727 shell_type_arg = kShellServiceArgRaw;
728 } else if (tty == kPtyAuto) {
729 // If stdin isn't a TTY, default to a raw shell; this lets
730 // things like `adb shell < my_script.sh` work as expected.
731 // Non-interactive shells should also not have a pty.
732 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800733 shell_type_arg = kShellServiceArgRaw;
Elliott Hughes02e33782016-10-19 14:47:11 -0700734 }
735 } else if (tty == kPtyYes) {
736 // A single -t arg isn't enough to override implicit -T.
737 if (!unix_isatty(STDIN_FILENO)) {
738 fprintf(stderr,
739 "Remote PTY will not be allocated because stdin is not a terminal.\n"
740 "Use multiple -t options to force remote PTY allocation.\n");
741 shell_type_arg = kShellServiceArgRaw;
742 }
743 }
744
745 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
746 escape_char, tty,
747 use_shell_protocol ? "true" : "false",
748 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
749
750 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
751 if (!use_shell_protocol) {
752 if (shell_type_arg != kShellServiceArgPty) {
753 fprintf(stderr, "error: %s only supports allocating a pty\n",
754 !CanUseFeature(features, kFeatureShell2) ? "device" : "-x");
755 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800756 } else {
Elliott Hughes02e33782016-10-19 14:47:11 -0700757 // If we're not using the shell protocol, the type argument must be empty.
758 shell_type_arg = "";
Elliott Hughesa8265792015-11-03 11:18:40 -0800759 }
David Purselle570b982015-09-14 15:33:50 -0700760 }
Elliott Hughesa8265792015-11-03 11:18:40 -0800761
762 std::string command;
Elliott Hughes02e33782016-10-19 14:47:11 -0700763 if (optind < argc) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800764 // We don't escape here, just like ssh(1). http://b/20564385.
Elliott Hughes02e33782016-10-19 14:47:11 -0700765 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
Elliott Hughesa8265792015-11-03 11:18:40 -0800766 }
767
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800768 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command);
David Purselle570b982015-09-14 15:33:50 -0700769}
770
Elliott Hughes96038eb2017-03-21 17:14:18 -0700771static int adb_download_buffer(const char* service, const char* filename) {
772 std::string content;
773 if (!android::base::ReadFileToString(filename, &content)) {
774 fprintf(stderr, "error: couldn't read %s: %s\n", filename, strerror(errno));
775 return -1;
776 }
777
778 const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
779 unsigned sz = content.size();
780
Elliott Hughes04a98c22015-04-29 08:35:59 -0700781 std::string error;
Elliott Hughesda945812015-04-29 12:28:13 -0700782 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700783 if (fd < 0) {
784 fprintf(stderr,"error: %s\n", error.c_str());
Doug Zongker6b217ed2012-01-09 14:54:53 -0800785 return -1;
786 }
787
788 int opt = CHUNK_SIZE;
Spencer Low31aafa62015-01-25 14:40:16 -0800789 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
Doug Zongker6b217ed2012-01-09 14:54:53 -0800790
Elliott Hughesda945812015-04-29 12:28:13 -0700791 unsigned total = sz;
Dan Albertf30d73c2015-02-25 17:51:28 -0800792 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800793
Elliott Hughes96038eb2017-03-21 17:14:18 -0700794 const char* x = strrchr(service, ':');
795 if (x) service = x + 1;
Doug Zongker6b217ed2012-01-09 14:54:53 -0800796
Elliott Hughesda945812015-04-29 12:28:13 -0700797 while (sz > 0) {
Doug Zongker6b217ed2012-01-09 14:54:53 -0800798 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
Elliott Hughes04a98c22015-04-29 08:35:59 -0700799 if (!WriteFdExactly(fd, ptr, xfer)) {
800 std::string error;
801 adb_status(fd, &error);
802 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Spencer Lowcc4a4b12015-10-14 17:32:44 -0700803 adb_close(fd);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800804 return -1;
805 }
806 sz -= xfer;
807 ptr += xfer;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700808 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * sz) / (total))));
809 fflush(stdout);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800810 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700811 printf("\n");
Doug Zongker6b217ed2012-01-09 14:54:53 -0800812
Elliott Hughes88b4c852015-04-30 17:32:03 -0700813 if (!adb_status(fd, &error)) {
814 fprintf(stderr,"* error response '%s' *\n", error.c_str());
Spencer Lowcc4a4b12015-10-14 17:32:44 -0700815 adb_close(fd);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800816 return -1;
817 }
818
819 adb_close(fd);
820 return 0;
821}
822
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700823#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
824
825/*
826 * The sideload-host protocol serves the data in a file (given on the
827 * command line) to the client, using a simple protocol:
828 *
829 * - The connect message includes the total number of bytes in the
830 * file and a block size chosen by us.
831 *
832 * - The other side sends the desired block number as eight decimal
833 * digits (eg "00000023" for block 23). Blocks are numbered from
834 * zero.
835 *
836 * - We send back the data of the requested block. The last block is
837 * likely to be partial; when the last block is requested we only
838 * send the part of the block that exists, it's not padded up to the
839 * block size.
840 *
841 * - When the other side sends "DONEDONE" instead of a block number,
842 * we hang up.
843 */
Elliott Hughes96038eb2017-03-21 17:14:18 -0700844static int adb_sideload_host(const char* filename) {
Elliott Hughes65bc2272017-04-18 14:34:16 -0700845 // TODO: use a LinePrinter instead...
846 fprintf(stdout, "opening '%s'...\n", filename);
847 fflush(stdout);
848
Elliott Hughes96038eb2017-03-21 17:14:18 -0700849 struct stat sb;
850 if (stat(filename, &sb) == -1) {
851 fprintf(stderr, "failed to stat file %s: %s\n", filename, strerror(errno));
852 return -1;
853 }
854 unique_fd package_fd(adb_open(filename, O_RDONLY));
855 if (package_fd == -1) {
856 fprintf(stderr, "failed to open file %s: %s\n", filename, strerror(errno));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700857 return -1;
858 }
859
Elliott Hughes65bc2272017-04-18 14:34:16 -0700860 fprintf(stdout, "connecting...\n");
861 fflush(stdout);
Elliott Hughes96038eb2017-03-21 17:14:18 -0700862 std::string service = android::base::StringPrintf(
863 "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700864 std::string error;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700865 unique_fd device_fd(adb_connect(service, &error));
866 if (device_fd < 0) {
867 // Try falling back to the older (<= K) sideload method. Maybe this
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700868 // is an older device that doesn't support sideload-host.
Elliott Hughes74d8e612016-06-15 14:45:34 -0700869 fprintf(stderr, "falling back to older sideload method...\n");
Elliott Hughes96038eb2017-03-21 17:14:18 -0700870 return adb_download_buffer("sideload", filename);
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700871 }
872
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700873 int opt = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700874 adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
875
876 char buf[SIDELOAD_HOST_BLOCK_SIZE];
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700877
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700878 size_t xfer = 0;
879 int last_percent = -1;
Elliott Hughes7cf35752015-04-17 17:03:59 -0700880 while (true) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700881 if (!ReadFdExactly(device_fd, buf, 8)) {
Elliott Hughes04a98c22015-04-29 08:35:59 -0700882 fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700883 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700884 }
Elliott Hughesda945812015-04-29 12:28:13 -0700885 buf[8] = '\0';
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700886
Elliott Hughesda945812015-04-29 12:28:13 -0700887 if (strcmp("DONEDONE", buf) == 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700888 printf("\rTotal xfer: %.2fx%*s\n",
Elliott Hughes96038eb2017-03-21 17:14:18 -0700889 static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
890 static_cast<int>(strlen(filename) + 10), "");
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700891 return 0;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700892 }
893
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700894 int block = strtol(buf, NULL, 10);
895
896 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700897 if (offset >= static_cast<size_t>(sb.st_size)) {
Elliott Hughes04a98c22015-04-29 08:35:59 -0700898 fprintf(stderr, "* attempt to read block %d past end\n", block);
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700899 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700900 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700901
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700902 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700903 if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<size_t>(sb.st_size)) {
904 to_write = sb.st_size - offset;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700905 }
906
Elliott Hughes96038eb2017-03-21 17:14:18 -0700907 if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) {
908 fprintf(stderr, "* failed to seek to package block: %s\n", strerror(errno));
909 return -1;
910 }
911 if (!ReadFdExactly(package_fd, buf, to_write)) {
912 fprintf(stderr, "* failed to read package block: %s\n", strerror(errno));
913 return -1;
914 }
915
916 if (!WriteFdExactly(device_fd, buf, to_write)) {
917 adb_status(device_fd, &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700918 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700919 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700920 }
921 xfer += to_write;
922
923 // For normal OTA packages, we expect to transfer every byte
924 // twice, plus a bit of overhead (one read during
925 // verification, one read of each byte for installation, plus
926 // extra access to things like the zip central directory).
927 // This estimate of the completion becomes 100% when we've
928 // transferred ~2.13 (=100/47) times the package size.
Elliott Hughes96038eb2017-03-21 17:14:18 -0700929 int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700930 if (percent != last_percent) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700931 printf("\rserving: '%s' (~%d%%) ", filename, percent);
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700932 fflush(stdout);
933 last_percent = percent;
934 }
935 }
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700936}
937
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800938/**
939 * Run ppp in "notty" mode against a resource listed as the first parameter
940 * eg:
941 *
942 * ppp dev:/dev/omap_csmi_tty0 <ppp options>
943 *
944 */
Elliott Hughes38104452015-04-17 13:57:15 -0700945static int ppp(int argc, const char** argv) {
Yabin Cui2fa43212014-11-11 09:24:11 -0800946#if defined(_WIN32)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800947 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
948 return -1;
949#else
Elliott Hughes65bc2272017-04-18 14:34:16 -0700950 if (argc < 2) return syntax_error("adb %s <adb service name> [ppp opts]", argv[0]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800951
Dan Albertf30d73c2015-02-25 17:51:28 -0800952 const char* adb_service_name = argv[1];
Elliott Hughes04a98c22015-04-29 08:35:59 -0700953 std::string error;
954 int fd = adb_connect(adb_service_name, &error);
955 if (fd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -0700956 fprintf(stderr, "adb: could not open adb service %s: %s\n", adb_service_name, error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800957 return 1;
958 }
959
Elliott Hughes04a98c22015-04-29 08:35:59 -0700960 pid_t pid = fork();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800961
962 if (pid < 0) {
963 perror("from fork()");
964 return 1;
965 } else if (pid == 0) {
966 int err;
967 int i;
968 const char **ppp_args;
969
970 // copy args
971 ppp_args = (const char **) alloca(sizeof(char *) * argc + 1);
972 ppp_args[0] = "pppd";
973 for (i = 2 ; i < argc ; i++) {
974 //argv[2] and beyond become ppp_args[1] and beyond
975 ppp_args[i - 1] = argv[i];
976 }
977 ppp_args[i-1] = NULL;
978
979 // child side
980
981 dup2(fd, STDIN_FILENO);
982 dup2(fd, STDOUT_FILENO);
983 adb_close(STDERR_FILENO);
984 adb_close(fd);
985
986 err = execvp("pppd", (char * const *)ppp_args);
987
988 if (err < 0) {
989 perror("execing pppd");
990 }
991 exit(-1);
992 } else {
993 // parent side
994
995 adb_close(fd);
996 return 0;
997 }
Yabin Cui2fa43212014-11-11 09:24:11 -0800998#endif /* !defined(_WIN32) */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800999}
1000
Josh Gao63cede32016-04-13 12:14:16 -07001001static bool wait_for_device(const char* service, TransportType t, const char* serial) {
1002 std::vector<std::string> components = android::base::Split(service, "-");
1003 if (components.size() < 3 || components.size() > 4) {
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001004 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1005 return false;
1006 }
1007
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001008 // Was the caller vague about what they'd like us to wait for?
1009 // If so, check they weren't more specific in their choice of transport type.
Josh Gao63cede32016-04-13 12:14:16 -07001010 if (components.size() == 3) {
1011 auto it = components.begin() + 2;
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001012 if (t == kTransportUsb) {
Josh Gao63cede32016-04-13 12:14:16 -07001013 components.insert(it, "usb");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001014 } else if (t == kTransportLocal) {
Josh Gao63cede32016-04-13 12:14:16 -07001015 components.insert(it, "local");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001016 } else {
Josh Gao63cede32016-04-13 12:14:16 -07001017 components.insert(it, "any");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001018 }
Josh Gao63cede32016-04-13 12:14:16 -07001019 } else if (components[2] != "any" && components[2] != "local" && components[2] != "usb") {
1020 fprintf(stderr, "adb: unknown type %s; expected 'any', 'local', or 'usb'\n",
1021 components[2].c_str());
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001022 return false;
1023 }
1024
Josh Gao071328d2016-04-13 12:18:58 -07001025 if (components[3] != "any" && components[3] != "bootloader" && components[3] != "device" &&
1026 components[3] != "recovery" && components[3] != "sideload") {
Josh Gao63cede32016-04-13 12:14:16 -07001027 fprintf(stderr,
1028 "adb: unknown state %s; "
Josh Gao071328d2016-04-13 12:18:58 -07001029 "expected 'any', 'bootloader', 'device', 'recovery', or 'sideload'\n",
Josh Gao63cede32016-04-13 12:14:16 -07001030 components[3].c_str());
1031 return false;
1032 }
1033
1034 std::string cmd = format_host_command(android::base::Join(components, "-").c_str(), t, serial);
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001035 return adb_command(cmd);
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001036}
1037
Josh Gaod1d03392016-03-04 15:16:18 -08001038static bool adb_root(const char* command) {
1039 std::string error;
Josh Gaod1d03392016-03-04 15:16:18 -08001040
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001041 unique_fd fd(adb_connect(android::base::StringPrintf("%s:", command), &error));
1042 if (fd < 0) {
Josh Gaod1d03392016-03-04 15:16:18 -08001043 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1044 return false;
1045 }
1046
1047 // Figure out whether we actually did anything.
1048 char buf[256];
1049 char* cur = buf;
1050 ssize_t bytes_left = sizeof(buf);
1051 while (bytes_left > 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001052 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
Josh Gaod1d03392016-03-04 15:16:18 -08001053 if (bytes_read == 0) {
1054 break;
1055 } else if (bytes_read < 0) {
1056 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1057 return false;
1058 }
1059 cur += bytes_read;
1060 bytes_left -= bytes_read;
1061 }
1062
1063 if (bytes_left == 0) {
1064 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1065 return false;
1066 }
1067
1068 fflush(stdout);
1069 WriteFdExactly(STDOUT_FILENO, buf, sizeof(buf) - bytes_left);
1070 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1071 return true;
1072 }
1073
Josh Gaod3d9cbf2016-06-16 14:00:09 -07001074 // Give adbd some time to kill itself and come back up.
1075 // We can't use wait-for-device because devices (e.g. adb over network) might not come back.
Josh Gao70267e42016-11-15 18:55:47 -08001076 std::this_thread::sleep_for(3s);
Josh Gaod3d9cbf2016-06-16 14:00:09 -07001077 return true;
Josh Gaod1d03392016-03-04 15:16:18 -08001078}
1079
Felipe Leme042c3512016-07-19 17:07:22 -07001080int send_shell_command(TransportType transport_type, const char* serial, const std::string& command,
Felipe Leme60192aa2016-07-26 12:14:39 -07001081 bool disable_shell_protocol, StandardStreamsCallbackInterface* callback) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001082 int fd;
David Pursell9650d862016-01-21 19:56:50 -08001083 bool use_shell_protocol = false;
1084
Elliott Hughes170b5682015-04-17 10:59:34 -07001085 while (true) {
David Pursell9650d862016-01-21 19:56:50 -08001086 bool attempt_connection = true;
1087
Felipe Leme60192aa2016-07-26 12:14:39 -07001088 // Use shell protocol if it's supported and the caller doesn't explicitly
1089 // disable it.
David Pursell9650d862016-01-21 19:56:50 -08001090 if (!disable_shell_protocol) {
1091 FeatureSet features;
Josh Gao91d53b52016-01-31 19:12:26 -08001092 std::string error;
1093 if (adb_get_feature_set(&features, &error)) {
David Pursell9650d862016-01-21 19:56:50 -08001094 use_shell_protocol = CanUseFeature(features, kFeatureShell2);
1095 } else {
1096 // Device was unreachable.
1097 attempt_connection = false;
1098 }
Elliott Hughes04a98c22015-04-29 08:35:59 -07001099 }
David Pursell9650d862016-01-21 19:56:50 -08001100
1101 if (attempt_connection) {
1102 std::string error;
1103 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1104
1105 fd = adb_connect(service_string, &error);
1106 if (fd >= 0) {
1107 break;
1108 }
1109 }
1110
Felipe Leme60192aa2016-07-26 12:14:39 -07001111 fprintf(stderr, "- waiting for device -\n");
Josh Gao6a7e5732016-02-24 15:16:17 -08001112 if (!wait_for_device("wait-for-device", transport_type, serial)) {
1113 return 1;
1114 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001115 }
1116
Felipe Leme60192aa2016-07-26 12:14:39 -07001117 int exit_code = read_and_dump(fd, use_shell_protocol, callback);
David Purselle570b982015-09-14 15:33:50 -07001118
1119 if (adb_close(fd) < 0) {
1120 PLOG(ERROR) << "failure closing FD " << fd;
Elliott Hughes170b5682015-04-17 10:59:34 -07001121 }
David Purselle570b982015-09-14 15:33:50 -07001122
1123 return exit_code;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001124}
1125
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001126static int logcat(TransportType transport, const char* serial, int argc, const char** argv) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001127 char* log_tags = getenv("ANDROID_LOG_TAGS");
1128 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001129
David Pursell22fc5e92015-09-30 13:35:42 -07001130 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001131
Jeff Sharkey824d1062014-06-10 11:31:24 -07001132 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001133 cmd += " -v long";
Christopher Tate7b9b5162011-11-30 13:00:33 -08001134 }
1135
Elliott Hughese4b64792015-04-17 20:11:08 -07001136 --argc;
1137 ++argv;
Elliott Hughes170b5682015-04-17 10:59:34 -07001138 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001139 cmd += " " + escape_arg(*argv++);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001140 }
1141
David Pursell22fc5e92015-09-30 13:35:42 -07001142 // No need for shell protocol with logcat, always disable for simplicity.
1143 return send_shell_command(transport, serial, cmd, true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001144}
1145
Christopher Tatee0e9f562016-07-06 13:22:22 -07001146static void write_zeros(int bytes, int fd) {
1147 int old_stdin_mode = -1;
1148 int old_stdout_mode = -1;
1149 char* buf = (char*) calloc(1, bytes);
1150 if (buf == nullptr) fatal("couldn't allocate buffer for write_zeros");
1151
1152 D("write_zeros(%d) -> %d", bytes, fd);
1153
1154 stdinout_raw_prologue(-1, fd, old_stdin_mode, old_stdout_mode);
1155
1156 if (fd == STDOUT_FILENO) {
1157 fwrite(buf, 1, bytes, stdout);
1158 fflush(stdout);
1159 } else {
1160 adb_write(fd, buf, bytes);
1161 }
1162
1163 stdinout_raw_prologue(-1, fd, old_stdin_mode, old_stdout_mode);
1164
1165 D("write_zeros() finished");
1166 free(buf);
1167}
1168
Dan Albertf30d73c2015-02-25 17:51:28 -08001169static int backup(int argc, const char** argv) {
Elliott Hughes1c1f7dc2015-08-21 20:31:31 -07001170 const char* filename = "backup.ab";
Christopher Tate73779122011-04-21 12:53:28 -07001171
Christopher Tatefba22972011-06-01 17:56:23 -07001172 /* find, extract, and use any -f argument */
Elliott Hughese4b64792015-04-17 20:11:08 -07001173 for (int i = 1; i < argc; i++) {
Christopher Tatefba22972011-06-01 17:56:23 -07001174 if (!strcmp("-f", argv[i])) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001175 if (i == argc - 1) return syntax_error("backup -f passed with no filename");
Christopher Tatefba22972011-06-01 17:56:23 -07001176 filename = argv[i+1];
Elliott Hughese4b64792015-04-17 20:11:08 -07001177 for (int j = i+2; j <= argc; ) {
Christopher Tatefba22972011-06-01 17:56:23 -07001178 argv[i++] = argv[j++];
1179 }
1180 argc -= 2;
1181 argv[argc] = NULL;
1182 }
Christopher Tate73779122011-04-21 12:53:28 -07001183 }
1184
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001185 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1186 // a list of packages is required.
Elliott Hughes65bc2272017-04-18 14:34:16 -07001187 if (argc < 2) return syntax_error("backup either needs a list of packages or -all/-shared");
Christopher Tatecf4f16a2011-08-22 17:12:08 -07001188
Christopher Tate1e9f2392011-12-08 19:04:34 -08001189 adb_unlink(filename);
Elliott Hughese4b64792015-04-17 20:11:08 -07001190 int outFd = adb_creat(filename, 0640);
Christopher Tate73779122011-04-21 12:53:28 -07001191 if (outFd < 0) {
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001192 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1193 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001194 }
1195
Elliott Hughese4b64792015-04-17 20:11:08 -07001196 std::string cmd = "backup:";
1197 --argc;
1198 ++argv;
1199 while (argc-- > 0) {
1200 cmd += " " + escape_arg(*argv++);
Christopher Tate73779122011-04-21 12:53:28 -07001201 }
1202
Yabin Cui815ad882015-09-02 17:44:28 -07001203 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes04a98c22015-04-29 08:35:59 -07001204 std::string error;
Elliott Hughesda945812015-04-29 12:28:13 -07001205 int fd = adb_connect(cmd, &error);
Christopher Tate73779122011-04-21 12:53:28 -07001206 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001207 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Christopher Tate73779122011-04-21 12:53:28 -07001208 adb_close(outFd);
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001209 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001210 }
1211
Elliott Hughes65bc2272017-04-18 14:34:16 -07001212 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001213 fflush(stdout);
1214
Christopher Tate73779122011-04-21 12:53:28 -07001215 copy_to_file(fd, outFd);
1216
1217 adb_close(fd);
1218 adb_close(outFd);
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001219 return EXIT_SUCCESS;
Christopher Tate73779122011-04-21 12:53:28 -07001220}
1221
Dan Albertf30d73c2015-02-25 17:51:28 -08001222static int restore(int argc, const char** argv) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001223 if (argc != 2) return syntax_error("restore requires an argument");
Christopher Tatecf5379b2011-05-17 15:52:54 -07001224
Elliott Hughes04a98c22015-04-29 08:35:59 -07001225 const char* filename = argv[1];
1226 int tarFd = adb_open(filename, O_RDONLY);
Christopher Tatecf5379b2011-05-17 15:52:54 -07001227 if (tarFd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001228 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001229 return -1;
1230 }
1231
Elliott Hughes04a98c22015-04-29 08:35:59 -07001232 std::string error;
1233 int fd = adb_connect("restore:", &error);
Christopher Tatecf5379b2011-05-17 15:52:54 -07001234 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001235 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001236 adb_close(tarFd);
1237 return -1;
1238 }
1239
Elliott Hughes65bc2272017-04-18 14:34:16 -07001240 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1241 fflush(stdout);
1242
Christopher Tatecf5379b2011-05-17 15:52:54 -07001243 copy_to_file(tarFd, fd);
1244
Christopher Tatee0e9f562016-07-06 13:22:22 -07001245 // Provide an in-band EOD marker in case the archive file is malformed
1246 write_zeros(512*2, fd);
1247
Josh Gao95230e82016-03-04 15:51:03 -08001248 // Wait until the other side finishes, or it'll get sent SIGHUP.
1249 copy_to_file(fd, STDOUT_FILENO);
1250
Christopher Tatecf5379b2011-05-17 15:52:54 -07001251 adb_close(fd);
1252 adb_close(tarFd);
1253 return 0;
1254}
1255
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001256/* <hint> may be:
1257 * - A simple product name
1258 * e.g., "sooner"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001259 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
1260 * e.g., "out/target/product/sooner"
1261 * - An absolute path to the PRODUCT_OUT dir
1262 * e.g., "/src/device/out/target/product/sooner"
1263 *
1264 * Given <hint>, try to construct an absolute path to the
1265 * ANDROID_PRODUCT_OUT dir.
1266 */
Elliott Hughesd189cfb2015-07-30 17:42:01 -07001267static std::string find_product_out_path(const std::string& hint) {
1268 if (hint.empty()) {
Elliott Hughes38104452015-04-17 13:57:15 -07001269 return "";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001270 }
1271
Elliott Hughes38104452015-04-17 13:57:15 -07001272 // If it's already absolute, don't bother doing any work.
Elliott Hughesd189cfb2015-07-30 17:42:01 -07001273 if (adb_is_absolute_host_path(hint.c_str())) {
Elliott Hughes38104452015-04-17 13:57:15 -07001274 return hint;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001275 }
1276
Chih-Hung Hsieh90b40f62016-07-27 16:25:51 -07001277 // If any of the OS_PATH_SEPARATORS is found, assume it's a relative path;
Elliott Hughes38104452015-04-17 13:57:15 -07001278 // make it absolute.
Chih-Hung Hsieh90b40f62016-07-27 16:25:51 -07001279 // NOLINT: Do not complain if OS_PATH_SEPARATORS has only one character.
1280 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) { // NOLINT
Elliott Hughes7cf35752015-04-17 17:03:59 -07001281 std::string cwd;
1282 if (!getcwd(&cwd)) {
Felipe Lemee4893a22016-07-29 17:57:00 -07001283 perror("adb: getcwd failed");
Elliott Hughes38104452015-04-17 13:57:15 -07001284 return "";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001285 }
Elliott Hughesd189cfb2015-07-30 17:42:01 -07001286 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001287 }
1288
Elliott Hughes38104452015-04-17 13:57:15 -07001289 // It's a string without any slashes. Try to do something with it.
1290 //
1291 // Try to find the root of the build tree, and build a PRODUCT_OUT
1292 // path from there.
Elliott Hughes7cf35752015-04-17 17:03:59 -07001293 char* top = getenv("ANDROID_BUILD_TOP");
Elliott Hughes38104452015-04-17 13:57:15 -07001294 if (top == nullptr) {
Elliott Hughes7cf35752015-04-17 17:03:59 -07001295 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
Elliott Hughes38104452015-04-17 13:57:15 -07001296 return "";
1297 }
Elliott Hughes7cf35752015-04-17 17:03:59 -07001298
1299 std::string path = top;
Elliott Hughes38104452015-04-17 13:57:15 -07001300 path += OS_PATH_SEPARATOR_STR;
1301 path += "out";
1302 path += OS_PATH_SEPARATOR_STR;
1303 path += "target";
1304 path += OS_PATH_SEPARATOR_STR;
1305 path += "product";
1306 path += OS_PATH_SEPARATOR_STR;
1307 path += hint;
1308 if (!directory_exists(path)) {
1309 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
Elliott Hughesd189cfb2015-07-30 17:42:01 -07001310 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str());
Elliott Hughes7cf35752015-04-17 17:03:59 -07001311 return "";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001312 }
Elliott Hughes38104452015-04-17 13:57:15 -07001313 return path;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001314}
1315
Josh Gao5d093b22015-10-30 16:57:19 -07001316static void parse_push_pull_args(const char** arg, int narg,
1317 std::vector<const char*>* srcs,
1318 const char** dst, bool* copy_attrs) {
1319 *copy_attrs = false;
Mark Lindner9f9d1452014-03-11 17:55:59 -07001320
Josh Gao5d093b22015-10-30 16:57:19 -07001321 srcs->clear();
1322 bool ignore_flags = false;
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001323 while (narg > 0) {
Josh Gao5d093b22015-10-30 16:57:19 -07001324 if (ignore_flags || *arg[0] != '-') {
1325 srcs->push_back(*arg);
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001326 } else {
Josh Gao5d093b22015-10-30 16:57:19 -07001327 if (!strcmp(*arg, "-p")) {
1328 // Silently ignore for backwards compatibility.
1329 } else if (!strcmp(*arg, "-a")) {
1330 *copy_attrs = true;
1331 } else if (!strcmp(*arg, "--")) {
1332 ignore_flags = true;
1333 } else {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001334 syntax_error("unrecognized option '%s'", *arg);
Josh Gao5d093b22015-10-30 16:57:19 -07001335 exit(1);
1336 }
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001337 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001338 ++arg;
1339 --narg;
1340 }
1341
Josh Gao5d093b22015-10-30 16:57:19 -07001342 if (srcs->size() > 1) {
1343 *dst = srcs->back();
1344 srcs->pop_back();
Mark Lindner9f9d1452014-03-11 17:55:59 -07001345 }
1346}
1347
Elliott Hughesda945812015-04-29 12:28:13 -07001348static int adb_connect_command(const std::string& command) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001349 std::string error;
1350 int fd = adb_connect(command, &error);
Elliott Hughesdabb9742015-05-07 23:37:40 -07001351 if (fd < 0) {
1352 fprintf(stderr, "error: %s\n", error.c_str());
1353 return 1;
Tao Bao0db67642015-03-29 11:22:34 -07001354 }
Elliott Hughesdabb9742015-05-07 23:37:40 -07001355 read_and_dump(fd);
1356 adb_close(fd);
1357 return 0;
Tao Bao0db67642015-03-29 11:22:34 -07001358}
1359
Elliott Hughesda945812015-04-29 12:28:13 -07001360static int adb_query_command(const std::string& command) {
1361 std::string result;
1362 std::string error;
1363 if (!adb_query(command, &result, &error)) {
1364 fprintf(stderr, "error: %s\n", error.c_str());
1365 return 1;
1366 }
1367 printf("%s\n", result.c_str());
1368 return 0;
1369}
1370
Spencer Lowe98825e2015-09-07 16:20:13 -07001371// Disallow stdin, stdout, and stderr.
1372static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1373#ifdef _WIN32
1374 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1375 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1376 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1377 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1378#else
1379 return ack_reply_fd > 2;
1380#endif
1381}
1382
Todd Kennedy8c5cf622016-07-20 16:22:37 -07001383static bool _use_legacy_install() {
1384 FeatureSet features;
1385 std::string error;
1386 if (!adb_get_feature_set(&features, &error)) {
1387 fprintf(stderr, "error: %s\n", error.c_str());
1388 return true;
1389 }
1390 return !CanUseFeature(features, kFeatureCmd);
1391}
1392
Elliott Hughes02e33782016-10-19 14:47:11 -07001393int adb_commandline(int argc, const char** argv) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001394 int no_daemon = 0;
1395 int is_daemon = 0;
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001396 int is_server = 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001397 int r;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001398 TransportType transport_type = kTransportAny;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001399 int ack_reply_fd = -1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001400
Elliott Hughes4919c172015-11-18 18:07:48 -08001401#if !defined(_WIN32)
1402 // We'd rather have EPIPE than SIGPIPE.
1403 signal(SIGPIPE, SIG_IGN);
1404#endif
1405
Elliott Hughes38104452015-04-17 13:57:15 -07001406 // If defined, this should be an absolute path to
1407 // the directory containing all of the various system images
1408 // for a particular product. If not defined, and the adb
1409 // command requires this information, then the user must
1410 // specify the path using "-p".
1411 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
1412 if (ANDROID_PRODUCT_OUT != nullptr) {
1413 gProductOutPath = ANDROID_PRODUCT_OUT;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001414 }
1415 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
1416
Josh Gaobb4f8602016-08-25 16:00:22 -07001417 const char* server_host_str = nullptr;
1418 const char* server_port_str = nullptr;
1419 const char* server_socket_str = nullptr;
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001420
Elliott Hughes67943d12015-10-07 14:55:10 -07001421 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1422 const char* serial = nullptr;
1423
Riley Andrews03b4b372014-12-05 17:37:24 -08001424 while (argc > 0) {
1425 if (!strcmp(argv[0],"server")) {
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001426 is_server = 1;
Riley Andrews03b4b372014-12-05 17:37:24 -08001427 } else if (!strcmp(argv[0],"nodaemon")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001428 no_daemon = 1;
1429 } else if (!strcmp(argv[0], "fork-server")) {
1430 /* this is a special flag used only when the ADB client launches the ADB Server */
1431 is_daemon = 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001432 } else if (!strcmp(argv[0], "--reply-fd")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001433 if (argc < 2) return syntax_error("--reply-fd requires an argument");
Siva Velusamya55dbd82015-08-07 10:10:29 -07001434 const char* reply_fd_str = argv[1];
1435 argc--;
1436 argv++;
1437 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowe98825e2015-09-07 16:20:13 -07001438 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001439 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001440 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001441 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001442 } else if (!strncmp(argv[0], "-p", 2)) {
Elliott Hughes13376832015-07-31 13:18:22 -07001443 const char* product = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001444 if (argv[0][2] == '\0') {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001445 if (argc < 2) return syntax_error("-p requires an argument");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001446 product = argv[1];
1447 argc--;
1448 argv++;
1449 } else {
Vairavan Srinivasanadc39402012-08-04 16:40:50 -07001450 product = argv[0] + 2;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001451 }
Elliott Hughes13376832015-07-31 13:18:22 -07001452 gProductOutPath = find_product_out_path(product);
Elliott Hughes38104452015-04-17 13:57:15 -07001453 if (gProductOutPath.empty()) {
1454 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001455 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001456 }
1457 } else if (argv[0][0]=='-' && argv[0][1]=='s') {
1458 if (isdigit(argv[0][2])) {
1459 serial = argv[0] + 2;
1460 } else {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001461 if (argc < 2 || argv[0][2] != '\0') return syntax_error("-s requires an argument");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001462 serial = argv[1];
1463 argc--;
1464 argv++;
1465 }
1466 } else if (!strcmp(argv[0],"-d")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001467 transport_type = kTransportUsb;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001468 } else if (!strcmp(argv[0],"-e")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001469 transport_type = kTransportLocal;
Matt Gumbel411775c2012-11-14 10:16:17 -08001470 } else if (!strcmp(argv[0],"-a")) {
1471 gListenAll = 1;
Riley Andrews03b4b372014-12-05 17:37:24 -08001472 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001473 if (argv[0][2] == '\0') {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001474 if (argc < 2) return syntax_error("-H requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001475 server_host_str = argv[1];
Matt Gumbel411775c2012-11-14 10:16:17 -08001476 argc--;
1477 argv++;
1478 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001479 server_host_str = argv[0] + 2;
Matt Gumbel411775c2012-11-14 10:16:17 -08001480 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001481 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001482 if (argv[0][2] == '\0') {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001483 if (argc < 2) return syntax_error("-P requires an argument");
Matt Gumbel411775c2012-11-14 10:16:17 -08001484 server_port_str = argv[1];
1485 argc--;
1486 argv++;
1487 } else {
1488 server_port_str = argv[0] + 2;
1489 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001490 } else if (!strcmp(argv[0], "-L")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001491 if (argc < 2) return syntax_error("-L requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001492 server_socket_str = argv[1];
1493 argc--;
1494 argv++;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001495 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001496 /* out of recognized modifiers and flags */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001497 break;
1498 }
1499 argc--;
1500 argv++;
1501 }
1502
Josh Gaobb4f8602016-08-25 16:00:22 -07001503 if ((server_host_str || server_port_str) && server_socket_str) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001504 return syntax_error("-L is incompatible with -H or -P");
Josh Gaobb4f8602016-08-25 16:00:22 -07001505 }
1506
1507 // If -L, -H, or -P are specified, ignore environment variables.
1508 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
Tao Wucaedcb52016-09-16 13:01:24 -07001509 if (!server_host_str && !server_port_str && !server_socket_str) {
1510 server_socket_str = getenv("ADB_SERVER_SOCKET");
Josh Gaobb4f8602016-08-25 16:00:22 -07001511 }
1512
1513 if (!server_socket_str) {
1514 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1515 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1516
Tao Wucaedcb52016-09-16 13:01:24 -07001517 int server_port = DEFAULT_ADB_PORT;
Josh Gaobb4f8602016-08-25 16:00:22 -07001518 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
Tao Wucaedcb52016-09-16 13:01:24 -07001519 if (server_port_str && strlen(server_port_str) > 0) {
1520 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
1521 fprintf(stderr,
1522 "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive"
1523 " number less than 65535. Got \"%s\"\n",
1524 server_port_str);
1525 exit(1);
1526 }
1527 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001528
1529 int rc;
1530 char* temp;
1531 if (server_host_str) {
Tao Wucaedcb52016-09-16 13:01:24 -07001532 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001533 } else {
Tao Wucaedcb52016-09-16 13:01:24 -07001534 rc = asprintf(&temp, "tcp:%d", server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001535 }
1536 if (rc < 0) {
1537 fatal("failed to allocate server socket specification");
1538 }
1539 server_socket_str = temp;
1540 }
1541
1542 adb_set_socket_spec(server_socket_str);
1543
Elliott Hughes67943d12015-10-07 14:55:10 -07001544 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1545 if (transport_type == kTransportAny && serial == nullptr) {
1546 serial = getenv("ANDROID_SERIAL");
1547 }
1548
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001549 adb_set_transport(transport_type, serial);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001550
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001551 if (is_server) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001552 if (no_daemon || is_daemon) {
Spencer Lowb28812f2015-08-08 15:07:07 -07001553 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001554 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001555 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001556 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001557 r = adb_server_main(is_daemon, server_socket_str, ack_reply_fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001558 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001559 r = launch_server(server_socket_str);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001560 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001561 if (r) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001562 fprintf(stderr,"* could not start server *\n");
1563 }
1564 return r;
1565 }
1566
Riley Andrews03b4b372014-12-05 17:37:24 -08001567 if (argc == 0) {
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001568 help();
1569 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001570 }
1571
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001572 /* handle wait-for-* prefix */
1573 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001574 const char* service = argv[0];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001575
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001576 if (!wait_for_device(service, transport_type, serial)) {
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001577 return 1;
1578 }
1579
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001580 // Allow a command to be run after wait-for-device,
1581 // e.g. 'adb wait-for-device shell'.
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001582 if (argc == 1) {
1583 return 0;
1584 }
1585
1586 /* Fall through */
1587 argc--;
1588 argv++;
1589 }
1590
1591 /* adb_connect() commands */
Riley Andrews03b4b372014-12-05 17:37:24 -08001592 if (!strcmp(argv[0], "devices")) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001593 const char *listopt;
Elliott Hughesda945812015-04-29 12:28:13 -07001594 if (argc < 2) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001595 listopt = "";
Elliott Hughesda945812015-04-29 12:28:13 -07001596 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001597 listopt = argv[1];
Elliott Hughesda945812015-04-29 12:28:13 -07001598 } else {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001599 return syntax_error("adb devices [-l]");
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001600 }
Elliott Hughesda945812015-04-29 12:28:13 -07001601
1602 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
1603 printf("List of devices attached\n");
1604 return adb_query_command(query);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001605 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001606 else if (!strcmp(argv[0], "connect")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001607 if (argc != 2) return syntax_error("adb connect <host>[:<port>]");
Elliott Hughesda945812015-04-29 12:28:13 -07001608
1609 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1610 return adb_query_command(query);
Mike Lockwood01c2c302010-05-24 10:44:35 -04001611 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001612 else if (!strcmp(argv[0], "disconnect")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001613 if (argc > 2) return syntax_error("adb disconnect [<host>[:<port>]]");
Elliott Hughesda945812015-04-29 12:28:13 -07001614
1615 std::string query = android::base::StringPrintf("host:disconnect:%s",
1616 (argc == 2) ? argv[1] : "");
1617 return adb_query_command(query);
Mike Lockwood26b88e32009-08-24 15:58:40 -07001618 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001619 else if (!strcmp(argv[0], "emu")) {
Spencer Low7dc759f2015-05-06 16:13:42 -07001620 return adb_send_emulator_command(argc, argv, serial);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001621 }
Elliott Hughesa8265792015-11-03 11:18:40 -08001622 else if (!strcmp(argv[0], "shell")) {
Josh Gao91d53b52016-01-31 19:12:26 -08001623 return adb_shell(argc, argv);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001624 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001625 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001626 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001627
Elliott Hughes65bc2272017-04-18 14:34:16 -07001628 if (argc < 2) return syntax_error("adb %s command", argv[0]);
Zach Riggle328870b2016-04-14 17:18:04 -04001629
Elliott Hughes170b5682015-04-17 10:59:34 -07001630 std::string cmd = "exec:";
1631 cmd += argv[1];
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001632 argc -= 2;
1633 argv += 2;
1634 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001635 cmd += " " + escape_arg(*argv++);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001636 }
1637
Elliott Hughes04a98c22015-04-29 08:35:59 -07001638 std::string error;
Elliott Hughesda945812015-04-29 12:28:13 -07001639 int fd = adb_connect(cmd, &error);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001640 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001641 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001642 return -1;
1643 }
1644
1645 if (exec_in) {
1646 copy_to_file(STDIN_FILENO, fd);
1647 } else {
1648 copy_to_file(fd, STDOUT_FILENO);
1649 }
1650
1651 adb_close(fd);
1652 return 0;
1653 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001654 else if (!strcmp(argv[0], "kill-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001655 std::string error;
1656 int fd = _adb_connect("host:kill", &error);
Spencer Low85ee64b2015-08-11 17:05:02 -07001657 if (fd == -2) {
1658 // Failed to make network connection to server. Don't output the
1659 // network error since that is expected.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001660 fprintf(stderr,"* server not running *\n");
Spencer Low85ee64b2015-08-11 17:05:02 -07001661 // Successful exit code because the server is already "killed".
1662 return 0;
1663 } else if (fd == -1) {
1664 // Some other error.
1665 fprintf(stderr, "error: %s\n", error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001666 return 1;
Spencer Low85ee64b2015-08-11 17:05:02 -07001667 } else {
1668 // Successfully connected, kill command sent, okay status came back.
1669 // Server should exit() in a moment, if not already.
Spencer Lowcc4a4b12015-10-14 17:32:44 -07001670 ReadOrderlyShutdown(fd);
Spencer Low85ee64b2015-08-11 17:05:02 -07001671 adb_close(fd);
1672 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001673 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001674 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001675 else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001676 if (argc != 2) return syntax_error("sideload requires an argument");
Doug Zongkerbcad29f2014-06-26 15:35:36 -07001677 if (adb_sideload_host(argv[1])) {
Doug Zongker6b217ed2012-01-09 14:54:53 -08001678 return 1;
1679 } else {
1680 return 0;
1681 }
1682 }
Elliott Hughesd94e8ba2015-07-21 16:13:40 -07001683 else if (!strcmp(argv[0], "tcpip") && argc > 1) {
1684 return adb_connect_command(android::base::StringPrintf("tcpip:%s", argv[1]));
1685 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001686 else if (!strcmp(argv[0], "remount") ||
1687 !strcmp(argv[0], "reboot") ||
1688 !strcmp(argv[0], "reboot-bootloader") ||
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001689 !strcmp(argv[0], "usb") ||
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001690 !strcmp(argv[0], "disable-verity") ||
1691 !strcmp(argv[0], "enable-verity")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001692 std::string command;
Tao Bao0db67642015-03-29 11:22:34 -07001693 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001694 command = "reboot:bootloader";
Tao Bao0db67642015-03-29 11:22:34 -07001695 } else if (argc > 1) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001696 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao0db67642015-03-29 11:22:34 -07001697 } else {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001698 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Project9c753402009-03-13 13:04:37 -07001699 }
Tao Bao0db67642015-03-29 11:22:34 -07001700 return adb_connect_command(command);
Josh Gaod1d03392016-03-04 15:16:18 -08001701 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1702 return adb_root(argv[0]) ? 0 : 1;
1703 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme042c3512016-07-19 17:07:22 -07001704 Bugreport bugreport;
1705 return bugreport.DoIt(transport_type, serial, argc, argv);
Felipe Lemeb6447032016-04-01 17:43:27 -07001706 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001707 bool reverse = !strcmp(argv[0], "reverse");
1708 ++argv;
1709 --argc;
Elliott Hughes65bc2272017-04-18 14:34:16 -07001710 if (argc < 1) return syntax_error("%s requires an argument", argv[0]);
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001711
1712 // Determine the <host-prefix> for this command.
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001713 std::string host_prefix;
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001714 if (reverse) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001715 host_prefix = "reverse";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001716 } else {
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001717 if (serial) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001718 host_prefix = android::base::StringPrintf("host-serial:%s", serial);
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001719 } else if (transport_type == kTransportUsb) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001720 host_prefix = "host-usb";
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001721 } else if (transport_type == kTransportLocal) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001722 host_prefix = "host-local";
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001723 } else {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001724 host_prefix = "host";
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001725 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001726 }
1727
David Pursell19d0c232016-04-07 11:25:48 -07001728 std::string cmd, error;
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001729 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001730 if (argc != 1) return syntax_error("--list doesn't take any arguments");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001731 return adb_query_command(host_prefix + ":list-forward");
1732 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001733 if (argc != 1) return syntax_error("--remove-all doesn't take any arguments");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001734 cmd = host_prefix + ":killforward-all";
1735 } else if (strcmp(argv[0], "--remove") == 0) {
1736 // forward --remove <local>
Elliott Hughes65bc2272017-04-18 14:34:16 -07001737 if (argc != 2) return syntax_error("--remove requires an argument");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001738 cmd = host_prefix + ":killforward:" + argv[1];
1739 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1740 // forward --no-rebind <local> <remote>
Elliott Hughes65bc2272017-04-18 14:34:16 -07001741 if (argc != 3) return syntax_error("--no-rebind takes two arguments");
David Pursell19d0c232016-04-07 11:25:48 -07001742 if (forward_targets_are_valid(argv[1], argv[2], &error)) {
1743 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
1744 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001745 } else {
1746 // forward <local> <remote>
Elliott Hughes65bc2272017-04-18 14:34:16 -07001747 if (argc != 2) return syntax_error("forward takes two arguments");
David Pursell19d0c232016-04-07 11:25:48 -07001748 if (forward_targets_are_valid(argv[0], argv[1], &error)) {
1749 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
1750 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001751 }
1752
David Pursell19d0c232016-04-07 11:25:48 -07001753 if (!error.empty()) {
1754 fprintf(stderr, "error: %s\n", error.c_str());
1755 return 1;
1756 }
1757
1758 int fd = adb_connect(cmd, &error);
1759 if (fd < 0 || !adb_status(fd, &error)) {
1760 adb_close(fd);
1761 fprintf(stderr, "error: %s\n", error.c_str());
1762 return 1;
1763 }
1764
1765 // Server or device may optionally return a resolved TCP port number.
1766 std::string resolved_port;
1767 if (ReadProtocolString(fd, &resolved_port, &error) && !resolved_port.empty()) {
1768 printf("%s\n", resolved_port.c_str());
1769 }
1770
1771 ReadOrderlyShutdown(fd);
1772 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001773 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001774 /* do_sync_*() commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001775 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001776 if (argc != 2) return syntax_error("ls requires an argument");
Elliott Hughesb628cb12015-08-03 10:38:08 -07001777 return do_sync_ls(argv[1]) ? 0 : 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001778 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001779 else if (!strcmp(argv[0], "push")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001780 bool copy_attrs = false;
1781 std::vector<const char*> srcs;
1782 const char* dst = nullptr;
Mark Lindner9f9d1452014-03-11 17:55:59 -07001783
Josh Gao5d093b22015-10-30 16:57:19 -07001784 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
Elliott Hughes65bc2272017-04-18 14:34:16 -07001785 if (srcs.empty() || !dst) return syntax_error("push requires an argument");
Josh Gao5d093b22015-10-30 16:57:19 -07001786 return do_sync_push(srcs, dst) ? 0 : 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001787 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001788 else if (!strcmp(argv[0], "pull")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001789 bool copy_attrs = false;
1790 std::vector<const char*> srcs;
1791 const char* dst = ".";
Mark Lindner9f9d1452014-03-11 17:55:59 -07001792
Josh Gao5d093b22015-10-30 16:57:19 -07001793 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
Elliott Hughes65bc2272017-04-18 14:34:16 -07001794 if (srcs.empty()) return syntax_error("pull requires an argument");
Josh Gao5d093b22015-10-30 16:57:19 -07001795 return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001796 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001797 else if (!strcmp(argv[0], "install")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001798 if (argc < 2) return syntax_error("install requires an argument");
Todd Kennedy8c5cf622016-07-20 16:22:37 -07001799 if (_use_legacy_install()) {
1800 return install_app_legacy(transport_type, serial, argc, argv);
David Pursell9650d862016-01-21 19:56:50 -08001801 }
Todd Kennedy8c5cf622016-07-20 16:22:37 -07001802 return install_app(transport_type, serial, argc, argv);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001803 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001804 else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001805 if (argc < 2) return syntax_error("install-multiple requires an argument");
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001806 return install_multiple_app(transport_type, serial, argc, argv);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07001807 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001808 else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001809 if (argc < 2) return syntax_error("uninstall requires an argument");
Todd Kennedy8c5cf622016-07-20 16:22:37 -07001810 if (_use_legacy_install()) {
1811 return uninstall_app_legacy(transport_type, serial, argc, argv);
David Pursell9650d862016-01-21 19:56:50 -08001812 }
Todd Kennedy8c5cf622016-07-20 16:22:37 -07001813 return uninstall_app(transport_type, serial, argc, argv);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001814 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001815 else if (!strcmp(argv[0], "sync")) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001816 std::string src;
Elliott Hughes38104452015-04-17 13:57:15 -07001817 bool list_only = false;
Riley Andrews03b4b372014-12-05 17:37:24 -08001818 if (argc < 2) {
Elliott Hughes38104452015-04-17 13:57:15 -07001819 // No local path was specified.
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001820 src = "";
Anthony Newnamdd2db142010-02-22 08:36:49 -06001821 } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001822 list_only = true;
Anthony Newnamdd2db142010-02-22 08:36:49 -06001823 if (argc == 3) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001824 src = argv[2];
Anthony Newnamdd2db142010-02-22 08:36:49 -06001825 } else {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001826 src = "";
Anthony Newnamdd2db142010-02-22 08:36:49 -06001827 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001828 } else if (argc == 2) {
Elliott Hughes38104452015-04-17 13:57:15 -07001829 // A local path or "android"/"data" arg was specified.
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001830 src = argv[1];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001831 } else {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001832 return syntax_error("adb sync [-l] [PARTITION]");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001833 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001834
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001835 if (src != "" &&
1836 src != "system" && src != "data" && src != "vendor" && src != "oem") {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001837 return syntax_error("don't know how to sync %s partition", src.c_str());
Elliott Hughes38104452015-04-17 13:57:15 -07001838 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001839
Elliott Hughes38104452015-04-17 13:57:15 -07001840 std::string system_src_path = product_file("system");
1841 std::string data_src_path = product_file("data");
1842 std::string vendor_src_path = product_file("vendor");
1843 std::string oem_src_path = product_file("oem");
Elliott Hughes38104452015-04-17 13:57:15 -07001844
Elliott Hughesb628cb12015-08-03 10:38:08 -07001845 bool okay = true;
1846 if (okay && (src.empty() || src == "system")) {
1847 okay = do_sync_sync(system_src_path, "/system", list_only);
Elliott Hughes38104452015-04-17 13:57:15 -07001848 }
Elliott Hughesb628cb12015-08-03 10:38:08 -07001849 if (okay && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) {
1850 okay = do_sync_sync(vendor_src_path, "/vendor", list_only);
Elliott Hughes38104452015-04-17 13:57:15 -07001851 }
Elliott Hughesb628cb12015-08-03 10:38:08 -07001852 if (okay && (src.empty() || src == "oem") && directory_exists(oem_src_path)) {
1853 okay = do_sync_sync(oem_src_path, "/oem", list_only);
Elliott Hughes38104452015-04-17 13:57:15 -07001854 }
Elliott Hughesb628cb12015-08-03 10:38:08 -07001855 if (okay && (src.empty() || src == "data")) {
1856 okay = do_sync_sync(data_src_path, "/data", list_only);
Elliott Hughes38104452015-04-17 13:57:15 -07001857 }
Elliott Hughesb628cb12015-08-03 10:38:08 -07001858 return okay ? 0 : 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001859 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001860 /* passthrough commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001861 else if (!strcmp(argv[0],"get-state") ||
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001862 !strcmp(argv[0],"get-serialno") ||
1863 !strcmp(argv[0],"get-devpath"))
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001864 {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001865 return adb_query_command(format_host_command(argv[0], transport_type, serial));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001866 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001867 /* other commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001868 else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001869 return logcat(transport_type, serial, argc, argv);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001870 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001871 else if (!strcmp(argv[0],"ppp")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001872 return ppp(argc, argv);
1873 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001874 else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001875 std::string error;
Spencer Low85ee64b2015-08-11 17:05:02 -07001876 const int result = adb_connect("host:start-server", &error);
1877 if (result < 0) {
1878 fprintf(stderr, "error: %s\n", error.c_str());
1879 }
1880 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001881 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001882 else if (!strcmp(argv[0], "backup")) {
Christopher Tate73779122011-04-21 12:53:28 -07001883 return backup(argc, argv);
1884 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001885 else if (!strcmp(argv[0], "restore")) {
Christopher Tatecf5379b2011-05-17 15:52:54 -07001886 return restore(argc, argv);
1887 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001888 else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001889 if (argc != 2) return syntax_error("keygen requires an argument");
Yabin Cui19bec5b2015-09-22 15:52:57 -07001890 // Always print key generation information for keygen command.
1891 adb_trace_enable(AUTH);
Nick Kralevich6183c962014-11-13 15:17:29 -08001892 return adb_auth_keygen(argv[1]);
1893 }
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001894 else if (!strcmp(argv[0], "jdwp")) {
Tao Bao0db67642015-03-29 11:22:34 -07001895 return adb_connect_command("jdwp");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001896 }
Josh Gao39d01bb2016-05-13 18:18:23 -07001897 else if (!strcmp(argv[0], "track-jdwp")) {
1898 return adb_connect_command("track-jdwp");
1899 }
1900 else if (!strcmp(argv[0], "track-devices")) {
1901 return adb_connect_command("host:track-devices");
1902 }
1903
1904
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001905 /* "adb /?" is a common idiom under Windows */
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001906 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001907 help();
1908 return 0;
1909 }
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001910 else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughesb9f01642015-08-12 08:32:10 -07001911 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001912 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08001913 } else if (!strcmp(argv[0], "features")) {
David Pursella07dbad2015-09-22 10:43:08 -07001914 // Only list the features common to both the adb client and the device.
David Pursell9650d862016-01-21 19:56:50 -08001915 FeatureSet features;
Josh Gao91d53b52016-01-31 19:12:26 -08001916 std::string error;
1917 if (!adb_get_feature_set(&features, &error)) {
1918 fprintf(stderr, "error: %s\n", error.c_str());
David Pursell9650d862016-01-21 19:56:50 -08001919 return 1;
1920 }
1921
David Pursella07dbad2015-09-22 10:43:08 -07001922 for (const std::string& name : features) {
David Pursell22fc5e92015-09-30 13:35:42 -07001923 if (CanUseFeature(features, name)) {
David Pursella07dbad2015-09-22 10:43:08 -07001924 printf("%s\n", name.c_str());
1925 }
1926 }
1927 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08001928 } else if (!strcmp(argv[0], "host-features")) {
1929 return adb_query_command("host:host-features");
Yabin Cuid78ed222016-04-05 13:50:44 -07001930 } else if (!strcmp(argv[0], "reconnect")) {
1931 if (argc == 1) {
1932 return adb_query_command("host:reconnect");
Josh Gao4e562502016-10-27 14:01:08 -07001933 } else if (argc == 2) {
1934 if (!strcmp(argv[1], "device")) {
1935 std::string err;
1936 adb_connect("reconnect", &err);
1937 return 0;
1938 } else if (!strcmp(argv[1], "offline")) {
1939 std::string err;
1940 return adb_query_command("host:reconnect-offline");
1941 } else {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001942 return syntax_error("adb reconnect [device|offline]");
Josh Gao4e562502016-10-27 14:01:08 -07001943 }
Yabin Cuid78ed222016-04-05 13:50:44 -07001944 }
Dan Albert996c12e2015-05-20 18:58:41 -07001945 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001946
Elliott Hughes65bc2272017-04-18 14:34:16 -07001947 syntax_error("unknown command %s", argv[0]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001948 return 1;
1949}
1950
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001951static int uninstall_app(TransportType transport, const char* serial, int argc, const char** argv) {
1952 // 'adb uninstall' takes the same arguments as 'cmd package uninstall' on device
1953 std::string cmd = "cmd package";
Elliott Hughes170b5682015-04-17 10:59:34 -07001954 while (argc-- > 0) {
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001955 // deny the '-k' option until the remaining data/cache can be removed with adb/UI
1956 if (strcmp(*argv, "-k") == 0) {
1957 printf(
1958 "The -k option uninstalls the application while retaining the data/cache.\n"
1959 "At the moment, there is no way to remove the remaining data.\n"
1960 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
1961 "If you truly wish to continue, execute 'adb shell cmd package uninstall -k'.\n");
1962 return EXIT_FAILURE;
1963 }
Elliott Hughese4b64792015-04-17 20:11:08 -07001964 cmd += " " + escape_arg(*argv++);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001965 }
1966
David Pursell22fc5e92015-09-30 13:35:42 -07001967 return send_shell_command(transport, serial, cmd, false);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001968}
1969
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001970static int install_app(TransportType transport, const char* serial, int argc, const char** argv) {
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001971 // The last argument must be the APK file
1972 const char* file = argv[argc - 1];
Elliott Hughes976bd832016-10-24 18:29:21 -07001973 if (!android::base::EndsWithIgnoreCase(file, ".apk")) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001974 return syntax_error("filename doesn't end .apk: %s", file);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001975 }
1976
Elliott Hughes976bd832016-10-24 18:29:21 -07001977 struct stat sb;
1978 if (stat(file, &sb) == -1) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001979 fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
Elliott Hughes976bd832016-10-24 18:29:21 -07001980 return 1;
Kenny Root3802c992011-08-05 11:19:45 -07001981 }
1982
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001983 int localFd = adb_open(file, O_RDONLY);
1984 if (localFd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07001985 fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001986 return 1;
1987 }
Kenny Root3802c992011-08-05 11:19:45 -07001988
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08001989 std::string error;
1990 std::string cmd = "exec:cmd package";
1991
1992 // don't copy the APK name, but, copy the rest of the arguments as-is
1993 while (argc-- > 1) {
1994 cmd += " " + escape_arg(std::string(*argv++));
1995 }
1996
1997 // add size parameter [required for streaming installs]
1998 // do last to override any user specified value
1999 cmd += " " + android::base::StringPrintf("-S %" PRIu64, static_cast<uint64_t>(sb.st_size));
2000
2001 int remoteFd = adb_connect(cmd, &error);
2002 if (remoteFd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002003 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002004 adb_close(localFd);
2005 return 1;
2006 }
2007
2008 char buf[BUFSIZ];
2009 copy_to_file(localFd, remoteFd);
2010 read_status_line(remoteFd, buf, sizeof(buf));
2011
2012 adb_close(localFd);
2013 adb_close(remoteFd);
2014
Elliott Hughes65bc2272017-04-18 14:34:16 -07002015 if (!strncmp("Success", buf, 7)) {
2016 fputs(buf, stdout);
2017 return 0;
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002018 }
Elliott Hughes65bc2272017-04-18 14:34:16 -07002019 fprintf(stderr, "adb: failed to install %s: %s", file, buf);
2020 return 1;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002021}
2022
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07002023static int install_multiple_app(TransportType transport, const char* serial, int argc,
Elliott Hughes38104452015-04-17 13:57:15 -07002024 const char** argv)
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002025{
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002026 // Find all APK arguments starting at end.
2027 // All other arguments passed through verbatim.
2028 int first_apk = -1;
Elliott Hughes976bd832016-10-24 18:29:21 -07002029 uint64_t total_size = 0;
2030 for (int i = argc - 1; i >= 0; i--) {
Dan Albertf30d73c2015-02-25 17:51:28 -08002031 const char* file = argv[i];
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002032
Elliott Hughes976bd832016-10-24 18:29:21 -07002033 if (android::base::EndsWithIgnoreCase(file, ".apk")) {
2034 struct stat sb;
2035 if (stat(file, &sb) != -1) total_size += sb.st_size;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002036 first_apk = i;
2037 } else {
2038 break;
2039 }
Kenny Root3802c992011-08-05 11:19:45 -07002040 }
2041
Elliott Hughes65bc2272017-04-18 14:34:16 -07002042 if (first_apk == -1) return syntax_error("need APK file on command line");
Kenny Root3802c992011-08-05 11:19:45 -07002043
Todd Kennedy8c5cf622016-07-20 16:22:37 -07002044 std::string install_cmd;
2045 if (_use_legacy_install()) {
2046 install_cmd = "exec:pm";
2047 } else {
2048 install_cmd = "exec:cmd package";
2049 }
2050
2051 std::string cmd = android::base::StringPrintf("%s install-create -S %" PRIu64, install_cmd.c_str(), total_size);
Elliott Hughes976bd832016-10-24 18:29:21 -07002052 for (int i = 1; i < first_apk; i++) {
Elliott Hughese4b64792015-04-17 20:11:08 -07002053 cmd += " " + escape_arg(argv[i]);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002054 }
2055
2056 // Create install session
Elliott Hughes04a98c22015-04-29 08:35:59 -07002057 std::string error;
Elliott Hughesda945812015-04-29 12:28:13 -07002058 int fd = adb_connect(cmd, &error);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002059 if (fd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002060 fprintf(stderr, "adb: connect error for create: %s\n", error.c_str());
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002061 return EXIT_FAILURE;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002062 }
Elliott Hughes170b5682015-04-17 10:59:34 -07002063 char buf[BUFSIZ];
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002064 read_status_line(fd, buf, sizeof(buf));
2065 adb_close(fd);
2066
2067 int session_id = -1;
2068 if (!strncmp("Success", buf, 7)) {
2069 char* start = strrchr(buf, '[');
2070 char* end = strrchr(buf, ']');
2071 if (start && end) {
2072 *end = '\0';
2073 session_id = strtol(start + 1, NULL, 10);
2074 }
2075 }
2076 if (session_id < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002077 fprintf(stderr, "adb: failed to create session\n");
Christopher Tate29721da2014-07-14 16:45:13 -07002078 fputs(buf, stderr);
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002079 return EXIT_FAILURE;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002080 }
2081
2082 // Valid session, now stream the APKs
2083 int success = 1;
Elliott Hughes976bd832016-10-24 18:29:21 -07002084 for (int i = first_apk; i < argc; i++) {
Dan Albertf30d73c2015-02-25 17:51:28 -08002085 const char* file = argv[i];
Elliott Hughes976bd832016-10-24 18:29:21 -07002086 struct stat sb;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002087 if (stat(file, &sb) == -1) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002088 fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002089 success = 0;
2090 goto finalize_session;
2091 }
2092
Elliott Hughesd1a5b2b2015-04-17 14:07:52 -07002093 std::string cmd = android::base::StringPrintf(
Todd Kennedy8c5cf622016-07-20 16:22:37 -07002094 "%s install-write -S %" PRIu64 " %d %d_%s -",
Colin Crosse6794072017-02-23 21:23:05 -08002095 install_cmd.c_str(), static_cast<uint64_t>(sb.st_size), session_id, i,
2096 android::base::Basename(file).c_str());
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002097
2098 int localFd = adb_open(file, O_RDONLY);
2099 if (localFd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002100 fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002101 success = 0;
2102 goto finalize_session;
2103 }
2104
Elliott Hughes04a98c22015-04-29 08:35:59 -07002105 std::string error;
Elliott Hughesda945812015-04-29 12:28:13 -07002106 int remoteFd = adb_connect(cmd, &error);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002107 if (remoteFd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002108 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002109 adb_close(localFd);
2110 success = 0;
2111 goto finalize_session;
2112 }
2113
2114 copy_to_file(localFd, remoteFd);
2115 read_status_line(remoteFd, buf, sizeof(buf));
2116
2117 adb_close(localFd);
2118 adb_close(remoteFd);
2119
2120 if (strncmp("Success", buf, 7)) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002121 fprintf(stderr, "adb: failed to write %s\n", file);
Christopher Tate29721da2014-07-14 16:45:13 -07002122 fputs(buf, stderr);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002123 success = 0;
2124 goto finalize_session;
2125 }
2126 }
2127
2128finalize_session:
Jeff Sharkey01f6fbf2014-07-25 09:58:25 -07002129 // Commit session if we streamed everything okay; otherwise abandon
Elliott Hughesda945812015-04-29 12:28:13 -07002130 std::string service =
Todd Kennedy8c5cf622016-07-20 16:22:37 -07002131 android::base::StringPrintf("%s install-%s %d",
2132 install_cmd.c_str(), success ? "commit" : "abandon", session_id);
Elliott Hughesda945812015-04-29 12:28:13 -07002133 fd = adb_connect(service, &error);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002134 if (fd < 0) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002135 fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002136 return EXIT_FAILURE;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002137 }
2138 read_status_line(fd, buf, sizeof(buf));
2139 adb_close(fd);
2140
2141 if (!strncmp("Success", buf, 7)) {
Elliott Hughes65bc2272017-04-18 14:34:16 -07002142 fputs(buf, stdout);
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002143 return 0;
Jeff Sharkey0e0d2512014-06-09 17:30:57 -07002144 }
Elliott Hughes65bc2272017-04-18 14:34:16 -07002145 fprintf(stderr, "adb: failed to finalize session\n");
2146 fputs(buf, stderr);
2147 return EXIT_FAILURE;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002148}
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002149
2150static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) {
2151 std::string cmd = "pm";
2152
2153 while (argc-- > 0) {
2154 cmd += " " + escape_arg(*argv++);
2155 }
2156
2157 return send_shell_command(transport, serial, cmd, false);
2158}
2159
2160static int uninstall_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
2161 /* if the user choose the -k option, we refuse to do it until devices are
2162 out with the option to uninstall the remaining data somehow (adb/ui) */
2163 int i;
2164 for (i = 1; i < argc; i++) {
2165 if (!strcmp(argv[i], "-k")) {
2166 printf(
2167 "The -k option uninstalls the application while retaining the data/cache.\n"
2168 "At the moment, there is no way to remove the remaining data.\n"
2169 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
2170 "If you truly wish to continue, execute 'adb shell pm uninstall -k'\n.");
2171 return EXIT_FAILURE;
2172 }
2173 }
2174
2175 /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
2176 return pm_command(transport, serial, argc, argv);
2177}
2178
2179static int delete_file(TransportType transport, const char* serial, const std::string& filename) {
2180 std::string cmd = "rm -f " + escape_arg(filename);
2181 return send_shell_command(transport, serial, cmd, false);
2182}
2183
2184static int install_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
2185 static const char *const DATA_DEST = "/data/local/tmp/%s";
2186 static const char *const SD_DEST = "/sdcard/tmp/%s";
2187 const char* where = DATA_DEST;
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002188
Elliott Hughes976bd832016-10-24 18:29:21 -07002189 for (int i = 1; i < argc; i++) {
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002190 if (!strcmp(argv[i], "-s")) {
2191 where = SD_DEST;
2192 }
2193 }
2194
2195 // Find last APK argument.
2196 // All other arguments passed through verbatim.
2197 int last_apk = -1;
Elliott Hughes976bd832016-10-24 18:29:21 -07002198 for (int i = argc - 1; i >= 0; i--) {
2199 if (android::base::EndsWithIgnoreCase(argv[i], ".apk")) {
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002200 last_apk = i;
2201 break;
2202 }
2203 }
2204
Elliott Hughes65bc2272017-04-18 14:34:16 -07002205 if (last_apk == -1) return syntax_error("need APK file on command line");
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002206
2207 int result = -1;
2208 std::vector<const char*> apk_file = {argv[last_apk]};
2209 std::string apk_dest = android::base::StringPrintf(
Colin Crosse6794072017-02-23 21:23:05 -08002210 where, android::base::Basename(argv[last_apk]).c_str());
Todd Kennedy1e2f7dc2015-11-03 16:53:08 -08002211 if (!do_sync_push(apk_file, apk_dest.c_str())) goto cleanup_apk;
2212 argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
2213 result = pm_command(transport, serial, argc, argv);
2214
2215cleanup_apk:
2216 delete_file(transport, serial, apk_dest);
2217 return result;
2218}