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