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