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(transport_type t, const char* serial, int argc, const char** argv);
51static int install_multiple_app(transport_type t, const char* serial, int argc, const char** argv);
52static int uninstall_app(transport_type 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        "                                 (see 'adb help all')\n"
114        "  adb shell                    - run remote shell interactively\n"
115        "  adb shell <command>          - run remote shell command\n"
116        "  adb emu <command>            - run emulator console command\n"
117        "  adb logcat [ <filter-spec> ] - View device log\n"
118        "  adb forward --list           - list all forward socket connections.\n"
119        "                                 the format is a list of lines with the following format:\n"
120        "                                    <serial> \" \" <local> \" \" <remote> \"\\n\"\n"
121        "  adb forward <local> <remote> - forward socket connections\n"
122        "                                 forward specs are one of: \n"
123        "                                   tcp:<port>\n"
124        "                                   localabstract:<unix domain socket name>\n"
125        "                                   localreserved:<unix domain socket name>\n"
126        "                                   localfilesystem:<unix domain socket name>\n"
127        "                                   dev:<character device name>\n"
128        "                                   jdwp:<process pid> (remote only)\n"
129        "  adb forward --no-rebind <local> <remote>\n"
130        "                               - same as 'adb forward <local> <remote>' but fails\n"
131        "                                 if <local> is already forwarded\n"
132        "  adb forward --remove <local> - remove a specific forward socket connection\n"
133        "  adb forward --remove-all     - remove all forward socket connections\n"
134        "  adb reverse --list           - list all reverse socket connections from device\n"
135        "  adb reverse <remote> <local> - reverse socket connections\n"
136        "                                 reverse specs are one of:\n"
137        "                                   tcp:<port>\n"
138        "                                   localabstract:<unix domain socket name>\n"
139        "                                   localreserved:<unix domain socket name>\n"
140        "                                   localfilesystem:<unix domain socket name>\n"
141        "  adb reverse --norebind <remote> <local>\n"
142        "                               - same as 'adb reverse <remote> <local>' but fails\n"
143        "                                 if <remote> is already reversed.\n"
144        "  adb reverse --remove <remote>\n"
145        "                               - remove a specific reversed socket connection\n"
146        "  adb reverse --remove-all     - remove all reversed socket connections from device\n"
147        "  adb jdwp                     - list PIDs of processes hosting a JDWP transport\n"
148        "  adb install [-lrtsdg] <file>\n"
149        "                               - push this package file to the device and install it\n"
150        "                                 (-l: forward lock application)\n"
151        "                                 (-r: replace existing application)\n"
152        "                                 (-t: allow test packages)\n"
153        "                                 (-s: install application on sdcard)\n"
154        "                                 (-d: allow version code downgrade)\n"
155        "                                 (-g: grant all runtime permissions)\n"
156        "  adb install-multiple [-lrtsdpg] <file...>\n"
157        "                               - push this package file to the device and install it\n"
158        "                                 (-l: forward lock application)\n"
159        "                                 (-r: replace existing application)\n"
160        "                                 (-t: allow test packages)\n"
161        "                                 (-s: install application on sdcard)\n"
162        "                                 (-d: allow version code downgrade)\n"
163        "                                 (-p: partial application install)\n"
164        "                                 (-g: grant all runtime permissions)\n"
165        "  adb uninstall [-k] <package> - remove this app package from the device\n"
166        "                                 ('-k' means keep the data and cache directories)\n"
167        "  adb bugreport                - return all information from the device\n"
168        "                                 that should be included in a bug report.\n"
169        "\n"
170        "  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n"
171        "                               - write an archive of the device's data to <file>.\n"
172        "                                 If no -f option is supplied then the data is written\n"
173        "                                 to \"backup.ab\" in the current directory.\n"
174        "                                 (-apk|-noapk enable/disable backup of the .apks themselves\n"
175        "                                    in the archive; the default is noapk.)\n"
176        "                                 (-obb|-noobb enable/disable backup of any installed apk expansion\n"
177        "                                    (aka .obb) files associated with each application; the default\n"
178        "                                    is noobb.)\n"
179        "                                 (-shared|-noshared enable/disable backup of the device's\n"
180        "                                    shared storage / SD card contents; the default is noshared.)\n"
181        "                                 (-all means to back up all installed applications)\n"
182        "                                 (-system|-nosystem toggles whether -all automatically includes\n"
183        "                                    system applications; the default is to include system apps)\n"
184        "                                 (<packages...> is the list of applications to be backed up.  If\n"
185        "                                    the -all or -shared flags are passed, then the package\n"
186        "                                    list is optional.  Applications explicitly given on the\n"
187        "                                    command line will be included even if -nosystem would\n"
188        "                                    ordinarily cause them to be omitted.)\n"
189        "\n"
190        "  adb restore <file>           - restore device contents from the <file> backup archive\n"
191        "\n"
192        "  adb disable-verity           - disable dm-verity checking on USERDEBUG builds\n"
193        "  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds\n"
194        "  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,\n"
195        "                                 and the public key is stored in <file>.pub. Any existing files\n"
196        "                                 are overwritten.\n"
197        "  adb help                     - show this help message\n"
198        "  adb version                  - show version num\n"
199        "\n"
200        "scripting:\n"
201        "  adb wait-for-device          - block until device is online\n"
202        "  adb start-server             - ensure that there is a server running\n"
203        "  adb kill-server              - kill the server if it is running\n"
204        "  adb get-state                - prints: offline | bootloader | device\n"
205        "  adb get-serialno             - prints: <serial-number>\n"
206        "  adb get-devpath              - prints: <device-path>\n"
207        "  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n"
208        "  adb reboot [bootloader|recovery]\n"
209        "                               - reboots the device, optionally into the bootloader or recovery program.\n"
210        "  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).\n"
211        "  adb reboot sideload-auto-reboot\n"
212        "                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n"
213        "  adb reboot-bootloader        - reboots the device into the bootloader\n"
214        "  adb root                     - restarts the adbd daemon with root permissions\n"
215        "  adb unroot                   - restarts the adbd daemon without root permissions\n"
216        "  adb usb                      - restarts the adbd daemon listening on USB\n"
217        "  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port\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        "environmental 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    adb_thread_t thr;
408    int fdi;
409
410    std::string error;
411    int fd = adb_connect("shell:", &error);
412    if (fd < 0) {
413        fprintf(stderr,"error: %s\n", error.c_str());
414        return 1;
415    }
416    fdi = 0; //dup(0);
417
418    int* fds = reinterpret_cast<int*>(malloc(sizeof(int) * 2));
419    if (fds == nullptr) {
420        fprintf(stderr, "couldn't allocate fds array: %s\n", strerror(errno));
421        return 1;
422    }
423
424    fds[0] = fd;
425    fds[1] = fdi;
426
427    stdin_raw_init(fdi);
428    adb_thread_create(&thr, 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, transport_type 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, transport_type 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    std::string error;
692    if (adb_command(cmd, &error)) {
693        D("failure: %s *\n", error.c_str());
694        fprintf(stderr,"error: %s\n", error.c_str());
695        return false;
696    }
697
698    return true;
699}
700
701static int send_shell_command(transport_type transport_type, const char* serial,
702                              const std::string& command) {
703    int fd;
704    while (true) {
705        std::string error;
706        fd = adb_connect(command, &error);
707        if (fd >= 0) {
708            break;
709        }
710        fprintf(stderr,"- waiting for device -\n");
711        adb_sleep_ms(1000);
712        wait_for_device("wait-for-device", transport_type, serial);
713    }
714
715    read_and_dump(fd);
716    int rc = adb_close(fd);
717    if (rc) {
718        perror("close");
719    }
720    return rc;
721}
722
723static int logcat(transport_type transport, const char* serial, int argc, const char** argv) {
724    char* log_tags = getenv("ANDROID_LOG_TAGS");
725    std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
726
727    std::string cmd = "shell:export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
728
729    if (!strcmp(argv[0], "longcat")) {
730        cmd += " -v long";
731    }
732
733    --argc;
734    ++argv;
735    while (argc-- > 0) {
736        cmd += " " + escape_arg(*argv++);
737    }
738
739    return send_shell_command(transport, serial, cmd);
740}
741
742static int mkdirs(const char *path)
743{
744    int ret;
745    char *x = (char *)path + 1;
746
747    for(;;) {
748        x = adb_dirstart(x);
749        if(x == 0) return 0;
750        *x = 0;
751        ret = adb_mkdir(path, 0775);
752        *x = OS_PATH_SEPARATOR;
753        if((ret < 0) && (errno != EEXIST)) {
754            return ret;
755        }
756        x++;
757    }
758    return 0;
759}
760
761static int backup(int argc, const char** argv) {
762    const char* filename = "./backup.ab";
763
764    /* find, extract, and use any -f argument */
765    for (int i = 1; i < argc; i++) {
766        if (!strcmp("-f", argv[i])) {
767            if (i == argc-1) {
768                fprintf(stderr, "adb: -f passed with no filename\n");
769                return usage();
770            }
771            filename = argv[i+1];
772            for (int j = i+2; j <= argc; ) {
773                argv[i++] = argv[j++];
774            }
775            argc -= 2;
776            argv[argc] = NULL;
777        }
778    }
779
780    /* bare "adb backup" or "adb backup -f filename" are not valid invocations */
781    if (argc < 2) return usage();
782
783    adb_unlink(filename);
784    mkdirs(filename);
785    int outFd = adb_creat(filename, 0640);
786    if (outFd < 0) {
787        fprintf(stderr, "adb: unable to open file %s\n", filename);
788        return -1;
789    }
790
791    std::string cmd = "backup:";
792    --argc;
793    ++argv;
794    while (argc-- > 0) {
795        cmd += " " + escape_arg(*argv++);
796    }
797
798    D("backup. filename=%s cmd=%s\n", filename, cmd.c_str());
799    std::string error;
800    int fd = adb_connect(cmd, &error);
801    if (fd < 0) {
802        fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
803        adb_close(outFd);
804        return -1;
805    }
806
807    printf("Now unlock your device and confirm the backup operation.\n");
808    copy_to_file(fd, outFd);
809
810    adb_close(fd);
811    adb_close(outFd);
812    return 0;
813}
814
815static int restore(int argc, const char** argv) {
816    if (argc != 2) return usage();
817
818    const char* filename = argv[1];
819    int tarFd = adb_open(filename, O_RDONLY);
820    if (tarFd < 0) {
821        fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
822        return -1;
823    }
824
825    std::string error;
826    int fd = adb_connect("restore:", &error);
827    if (fd < 0) {
828        fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
829        adb_close(tarFd);
830        return -1;
831    }
832
833    printf("Now unlock your device and confirm the restore operation.\n");
834    copy_to_file(tarFd, fd);
835
836    adb_close(fd);
837    adb_close(tarFd);
838    return 0;
839}
840
841/* <hint> may be:
842 * - A simple product name
843 *   e.g., "sooner"
844 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
845 *   e.g., "out/target/product/sooner"
846 * - An absolute path to the PRODUCT_OUT dir
847 *   e.g., "/src/device/out/target/product/sooner"
848 *
849 * Given <hint>, try to construct an absolute path to the
850 * ANDROID_PRODUCT_OUT dir.
851 */
852static std::string find_product_out_path(const char* hint) {
853    if (hint == NULL || hint[0] == '\0') {
854        return "";
855    }
856
857    // If it's already absolute, don't bother doing any work.
858    if (adb_is_absolute_host_path(hint)) {
859        return hint;
860    }
861
862    // If there are any slashes in it, assume it's a relative path;
863    // make it absolute.
864    if (adb_dirstart(hint) != nullptr) {
865        std::string cwd;
866        if (!getcwd(&cwd)) {
867            fprintf(stderr, "adb: getcwd failed: %s\n", strerror(errno));
868            return "";
869        }
870        return android::base::StringPrintf("%s%s%s", cwd.c_str(), OS_PATH_SEPARATOR_STR, hint);
871    }
872
873    // It's a string without any slashes.  Try to do something with it.
874    //
875    // Try to find the root of the build tree, and build a PRODUCT_OUT
876    // path from there.
877    char* top = getenv("ANDROID_BUILD_TOP");
878    if (top == nullptr) {
879        fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
880        return "";
881    }
882
883    std::string path = top;
884    path += OS_PATH_SEPARATOR_STR;
885    path += "out";
886    path += OS_PATH_SEPARATOR_STR;
887    path += "target";
888    path += OS_PATH_SEPARATOR_STR;
889    path += "product";
890    path += OS_PATH_SEPARATOR_STR;
891    path += hint;
892    if (!directory_exists(path)) {
893        fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
894                        "\"%s\" doesn't exist\n", hint, path.c_str());
895        return "";
896    }
897    return path;
898}
899
900static void parse_push_pull_args(const char **arg, int narg, char const **path1,
901                                 char const **path2, int *show_progress,
902                                 int *copy_attrs) {
903    *show_progress = 0;
904    *copy_attrs = 0;
905
906    while (narg > 0) {
907        if (!strcmp(*arg, "-p")) {
908            *show_progress = 1;
909        } else if (!strcmp(*arg, "-a")) {
910            *copy_attrs = 1;
911        } else {
912            break;
913        }
914        ++arg;
915        --narg;
916    }
917
918    if (narg > 0) {
919        *path1 = *arg;
920        ++arg;
921        --narg;
922    }
923
924    if (narg > 0) {
925        *path2 = *arg;
926    }
927}
928
929static int adb_connect_command(const std::string& command) {
930    std::string error;
931    int fd = adb_connect(command, &error);
932    if (fd < 0) {
933        fprintf(stderr, "error: %s\n", error.c_str());
934        return 1;
935    }
936    read_and_dump(fd);
937    adb_close(fd);
938    return 0;
939}
940
941static int adb_query_command(const std::string& command) {
942    std::string result;
943    std::string error;
944    if (!adb_query(command, &result, &error)) {
945        fprintf(stderr, "error: %s\n", error.c_str());
946        return 1;
947    }
948    printf("%s\n", result.c_str());
949    return 0;
950}
951
952int adb_commandline(int argc, const char **argv) {
953    int no_daemon = 0;
954    int is_daemon = 0;
955    int is_server = 0;
956    int persist = 0;
957    int r;
958    transport_type ttype = kTransportAny;
959    const char* serial = NULL;
960    const char* server_port_str = NULL;
961
962    // If defined, this should be an absolute path to
963    // the directory containing all of the various system images
964    // for a particular product.  If not defined, and the adb
965    // command requires this information, then the user must
966    // specify the path using "-p".
967    char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
968    if (ANDROID_PRODUCT_OUT != nullptr) {
969        gProductOutPath = ANDROID_PRODUCT_OUT;
970    }
971    // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
972
973    serial = getenv("ANDROID_SERIAL");
974
975    /* Validate and assign the server port */
976    server_port_str = getenv("ANDROID_ADB_SERVER_PORT");
977    int server_port = DEFAULT_ADB_PORT;
978    if (server_port_str && strlen(server_port_str) > 0) {
979        server_port = (int) strtol(server_port_str, NULL, 0);
980        if (server_port <= 0 || server_port > 65535) {
981            fprintf(stderr,
982                    "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65535. Got \"%s\"\n",
983                    server_port_str);
984            return usage();
985        }
986    }
987
988    /* modifiers and flags */
989    while (argc > 0) {
990        if (!strcmp(argv[0],"server")) {
991            is_server = 1;
992        } else if (!strcmp(argv[0],"nodaemon")) {
993            no_daemon = 1;
994        } else if (!strcmp(argv[0], "fork-server")) {
995            /* this is a special flag used only when the ADB client launches the ADB Server */
996            is_daemon = 1;
997        } else if (!strcmp(argv[0],"persist")) {
998            persist = 1;
999        } else if (!strncmp(argv[0], "-p", 2)) {
1000            const char *product = NULL;
1001            if (argv[0][2] == '\0') {
1002                if (argc < 2) return usage();
1003                product = argv[1];
1004                argc--;
1005                argv++;
1006            } else {
1007                product = argv[0] + 2;
1008            }
1009            gProductOutPath = find_product_out_path(product);
1010            if (gProductOutPath.empty()) {
1011                fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
1012                return usage();
1013            }
1014        } else if (argv[0][0]=='-' && argv[0][1]=='s') {
1015            if (isdigit(argv[0][2])) {
1016                serial = argv[0] + 2;
1017            } else {
1018                if (argc < 2 || argv[0][2] != '\0') return usage();
1019                serial = argv[1];
1020                argc--;
1021                argv++;
1022            }
1023        } else if (!strcmp(argv[0],"-d")) {
1024            ttype = kTransportUsb;
1025        } else if (!strcmp(argv[0],"-e")) {
1026            ttype = kTransportLocal;
1027        } else if (!strcmp(argv[0],"-a")) {
1028            gListenAll = 1;
1029        } else if (!strncmp(argv[0], "-H", 2)) {
1030            const char *hostname = NULL;
1031            if (argv[0][2] == '\0') {
1032                if (argc < 2) return usage();
1033                hostname = argv[1];
1034                argc--;
1035                argv++;
1036            } else {
1037                hostname = argv[0] + 2;
1038            }
1039            adb_set_tcp_name(hostname);
1040
1041        } else if (!strncmp(argv[0], "-P", 2)) {
1042            if (argv[0][2] == '\0') {
1043                if (argc < 2) return usage();
1044                server_port_str = argv[1];
1045                argc--;
1046                argv++;
1047            } else {
1048                server_port_str = argv[0] + 2;
1049            }
1050            if (strlen(server_port_str) > 0) {
1051                server_port = (int) strtol(server_port_str, NULL, 0);
1052                if (server_port <= 0 || server_port > 65535) {
1053                    fprintf(stderr,
1054                            "adb: port number must be a positive number less than 65536. Got \"%s\"\n",
1055                            server_port_str);
1056                    return usage();
1057                }
1058            } else {
1059                fprintf(stderr,
1060                "adb: port number must be a positive number less than 65536. Got empty string.\n");
1061                return usage();
1062            }
1063        } else {
1064                /* out of recognized modifiers and flags */
1065            break;
1066        }
1067        argc--;
1068        argv++;
1069    }
1070
1071    adb_set_transport(ttype, serial);
1072    adb_set_tcp_specifics(server_port);
1073
1074    if (is_server) {
1075        if (no_daemon || is_daemon) {
1076            r = adb_main(is_daemon, server_port);
1077        } else {
1078            r = launch_server(server_port);
1079        }
1080        if (r) {
1081            fprintf(stderr,"* could not start server *\n");
1082        }
1083        return r;
1084    }
1085
1086    if (argc == 0) {
1087        return usage();
1088    }
1089
1090    /* handle wait-for-* prefix */
1091    if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
1092        const char* service = argv[0];
1093
1094        if (!wait_for_device(service, ttype, serial)) {
1095            return 1;
1096        }
1097
1098        // Allow a command to be run after wait-for-device,
1099        // e.g. 'adb wait-for-device shell'.
1100        if (argc == 1) {
1101            return 0;
1102        }
1103
1104        /* Fall through */
1105        argc--;
1106        argv++;
1107    }
1108
1109    /* adb_connect() commands */
1110    if (!strcmp(argv[0], "devices")) {
1111        const char *listopt;
1112        if (argc < 2) {
1113            listopt = "";
1114        } else if (argc == 2 && !strcmp(argv[1], "-l")) {
1115            listopt = argv[1];
1116        } else {
1117            fprintf(stderr, "Usage: adb devices [-l]\n");
1118            return 1;
1119        }
1120
1121        std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
1122        printf("List of devices attached\n");
1123        return adb_query_command(query);
1124    }
1125    else if (!strcmp(argv[0], "connect")) {
1126        if (argc != 2) {
1127            fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
1128            return 1;
1129        }
1130
1131        std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1132        return adb_query_command(query);
1133    }
1134    else if (!strcmp(argv[0], "disconnect")) {
1135        if (argc > 2) {
1136            fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
1137            return 1;
1138        }
1139
1140        std::string query = android::base::StringPrintf("host:disconnect:%s",
1141                                                        (argc == 2) ? argv[1] : "");
1142        return adb_query_command(query);
1143    }
1144    else if (!strcmp(argv[0], "emu")) {
1145        return adb_send_emulator_command(argc, argv);
1146    }
1147    else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
1148        char h = (argv[0][0] == 'h');
1149
1150        if (h) {
1151            printf("\x1b[41;33m");
1152            fflush(stdout);
1153        }
1154
1155        if (argc < 2) {
1156            D("starting interactive shell\n");
1157            r = interactive_shell();
1158            if (h) {
1159                printf("\x1b[0m");
1160                fflush(stdout);
1161            }
1162            return r;
1163        }
1164
1165        std::string cmd = "shell:";
1166        --argc;
1167        ++argv;
1168        while (argc-- > 0) {
1169            // We don't escape here, just like ssh(1). http://b/20564385.
1170            cmd += *argv++;
1171            if (*argv) cmd += " ";
1172        }
1173
1174        while (true) {
1175            D("interactive shell loop. cmd=%s\n", cmd.c_str());
1176            std::string error;
1177            int fd = adb_connect(cmd, &error);
1178            int r;
1179            if (fd >= 0) {
1180                D("about to read_and_dump(fd=%d)\n", fd);
1181                read_and_dump(fd);
1182                D("read_and_dump() done.\n");
1183                adb_close(fd);
1184                r = 0;
1185            } else {
1186                fprintf(stderr,"error: %s\n", error.c_str());
1187                r = -1;
1188            }
1189
1190            if (persist) {
1191                fprintf(stderr,"\n- waiting for device -\n");
1192                adb_sleep_ms(1000);
1193                wait_for_device("wait-for-device", ttype, serial);
1194            } else {
1195                if (h) {
1196                    printf("\x1b[0m");
1197                    fflush(stdout);
1198                }
1199                D("interactive shell loop. return r=%d\n", r);
1200                return r;
1201            }
1202        }
1203    }
1204    else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
1205        int exec_in = !strcmp(argv[0], "exec-in");
1206
1207        std::string cmd = "exec:";
1208        cmd += argv[1];
1209        argc -= 2;
1210        argv += 2;
1211        while (argc-- > 0) {
1212            cmd += " " + escape_arg(*argv++);
1213        }
1214
1215        std::string error;
1216        int fd = adb_connect(cmd, &error);
1217        if (fd < 0) {
1218            fprintf(stderr, "error: %s\n", error.c_str());
1219            return -1;
1220        }
1221
1222        if (exec_in) {
1223            copy_to_file(STDIN_FILENO, fd);
1224        } else {
1225            copy_to_file(fd, STDOUT_FILENO);
1226        }
1227
1228        adb_close(fd);
1229        return 0;
1230    }
1231    else if (!strcmp(argv[0], "kill-server")) {
1232        std::string error;
1233        int fd = _adb_connect("host:kill", &error);
1234        if (fd == -1) {
1235            fprintf(stderr,"* server not running *\n");
1236            return 1;
1237        }
1238        return 0;
1239    }
1240    else if (!strcmp(argv[0], "sideload")) {
1241        if (argc != 2) return usage();
1242        if (adb_sideload_host(argv[1])) {
1243            return 1;
1244        } else {
1245            return 0;
1246        }
1247    }
1248    else if (!strcmp(argv[0], "remount") ||
1249             !strcmp(argv[0], "reboot") ||
1250             !strcmp(argv[0], "reboot-bootloader") ||
1251             !strcmp(argv[0], "tcpip") ||
1252             !strcmp(argv[0], "usb") ||
1253             !strcmp(argv[0], "root") ||
1254             !strcmp(argv[0], "unroot") ||
1255             !strcmp(argv[0], "disable-verity") ||
1256             !strcmp(argv[0], "enable-verity")) {
1257        std::string command;
1258        if (!strcmp(argv[0], "reboot-bootloader")) {
1259            command = "reboot:bootloader";
1260        } else if (argc > 1) {
1261            command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1262        } else {
1263            command = android::base::StringPrintf("%s:", argv[0]);
1264        }
1265        return adb_connect_command(command);
1266    }
1267    else if (!strcmp(argv[0], "bugreport")) {
1268        if (argc != 1) return usage();
1269        return send_shell_command(ttype, serial, "shell:bugreport");
1270    }
1271    /* adb_command() wrapper commands */
1272    else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
1273        std::string cmd;
1274        char host_prefix[64];
1275        char reverse = (char) !strcmp(argv[0], "reverse");
1276        char remove = 0;
1277        char remove_all = 0;
1278        char list = 0;
1279        char no_rebind = 0;
1280
1281        // Parse options here.
1282        while (argc > 1 && argv[1][0] == '-') {
1283            if (!strcmp(argv[1], "--list"))
1284                list = 1;
1285            else if (!strcmp(argv[1], "--remove"))
1286                remove = 1;
1287            else if (!strcmp(argv[1], "--remove-all"))
1288                remove_all = 1;
1289            else if (!strcmp(argv[1], "--no-rebind"))
1290                no_rebind = 1;
1291            else {
1292                return usage();
1293            }
1294            argc--;
1295            argv++;
1296        }
1297
1298        // Ensure we can only use one option at a time.
1299        if (list + remove + remove_all + no_rebind > 1) {
1300            return usage();
1301        }
1302
1303        // Determine the <host-prefix> for this command.
1304        if (reverse) {
1305            snprintf(host_prefix, sizeof host_prefix, "reverse");
1306        } else {
1307            if (serial) {
1308                snprintf(host_prefix, sizeof host_prefix, "host-serial:%s",
1309                        serial);
1310            } else if (ttype == kTransportUsb) {
1311                snprintf(host_prefix, sizeof host_prefix, "host-usb");
1312            } else if (ttype == kTransportLocal) {
1313                snprintf(host_prefix, sizeof host_prefix, "host-local");
1314            } else {
1315                snprintf(host_prefix, sizeof host_prefix, "host");
1316            }
1317        }
1318
1319        // Implement forward --list
1320        if (list) {
1321            if (argc != 1) {
1322                return usage();
1323            }
1324
1325            std::string query = android::base::StringPrintf("%s:list-forward", host_prefix);
1326            return adb_query_command(query);
1327        }
1328
1329        // Implement forward --remove-all
1330        else if (remove_all) {
1331            if (argc != 1) return usage();
1332            cmd = android::base::StringPrintf("%s:killforward-all", host_prefix);
1333        }
1334
1335        // Implement forward --remove <local>
1336        else if (remove) {
1337            if (argc != 2) return usage();
1338            cmd = android::base::StringPrintf("%s:killforward:%s", host_prefix, argv[1]);
1339        }
1340        // Or implement one of:
1341        //    forward <local> <remote>
1342        //    forward --no-rebind <local> <remote>
1343        else {
1344            if (argc != 3) return usage();
1345            const char* command = no_rebind ? "forward:norebind" : "forward";
1346            cmd = android::base::StringPrintf("%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]);
1347        }
1348
1349        std::string error;
1350        if (adb_command(cmd, &error)) {
1351            fprintf(stderr, "error: %s\n", error.c_str());
1352            return 1;
1353        }
1354        return 0;
1355    }
1356    /* do_sync_*() commands */
1357    else if (!strcmp(argv[0], "ls")) {
1358        if (argc != 2) return usage();
1359        return do_sync_ls(argv[1]);
1360    }
1361    else if (!strcmp(argv[0], "push")) {
1362        int show_progress = 0;
1363        int copy_attrs = 0; // unused
1364        const char* lpath = NULL, *rpath = NULL;
1365
1366        parse_push_pull_args(&argv[1], argc - 1, &lpath, &rpath, &show_progress, &copy_attrs);
1367
1368        if ((lpath != NULL) && (rpath != NULL)) {
1369            return do_sync_push(lpath, rpath, show_progress);
1370        }
1371
1372        return usage();
1373    }
1374    else if (!strcmp(argv[0], "pull")) {
1375        int show_progress = 0;
1376        int copy_attrs = 0;
1377        const char* rpath = NULL, *lpath = ".";
1378
1379        parse_push_pull_args(&argv[1], argc - 1, &rpath, &lpath, &show_progress, &copy_attrs);
1380
1381        if (rpath != NULL) {
1382            return do_sync_pull(rpath, lpath, show_progress, copy_attrs);
1383        }
1384
1385        return usage();
1386    }
1387    else if (!strcmp(argv[0], "install")) {
1388        if (argc < 2) return usage();
1389        return install_app(ttype, serial, argc, argv);
1390    }
1391    else if (!strcmp(argv[0], "install-multiple")) {
1392        if (argc < 2) return usage();
1393        return install_multiple_app(ttype, serial, argc, argv);
1394    }
1395    else if (!strcmp(argv[0], "uninstall")) {
1396        if (argc < 2) return usage();
1397        return uninstall_app(ttype, serial, argc, argv);
1398    }
1399    else if (!strcmp(argv[0], "sync")) {
1400        std::string src;
1401        bool list_only = false;
1402        if (argc < 2) {
1403            // No local path was specified.
1404            src = "";
1405        } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
1406            list_only = true;
1407            if (argc == 3) {
1408                src = argv[2];
1409            } else {
1410                src = "";
1411            }
1412        } else if (argc == 2) {
1413            // A local path or "android"/"data" arg was specified.
1414            src = argv[1];
1415        } else {
1416            return usage();
1417        }
1418
1419        if (src != "" &&
1420            src != "system" && src != "data" && src != "vendor" && src != "oem") {
1421            return usage();
1422        }
1423
1424        std::string system_src_path = product_file("system");
1425        std::string data_src_path = product_file("data");
1426        std::string vendor_src_path = product_file("vendor");
1427        std::string oem_src_path = product_file("oem");
1428
1429        int rc = 0;
1430        if (rc == 0 && (src.empty() || src == "system")) {
1431            rc = do_sync_sync(system_src_path, "/system", list_only);
1432        }
1433        if (rc == 0 && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) {
1434            rc = do_sync_sync(vendor_src_path, "/vendor", list_only);
1435        }
1436        if (rc == 0 && (src.empty() || src == "oem") && directory_exists(oem_src_path)) {
1437            rc = do_sync_sync(oem_src_path, "/oem", list_only);
1438        }
1439        if (rc == 0 && (src.empty() || src == "data")) {
1440            rc = do_sync_sync(data_src_path, "/data", list_only);
1441        }
1442        return rc;
1443    }
1444    /* passthrough commands */
1445    else if (!strcmp(argv[0],"get-state") ||
1446        !strcmp(argv[0],"get-serialno") ||
1447        !strcmp(argv[0],"get-devpath"))
1448    {
1449        return adb_query_command(format_host_command(argv[0], ttype, serial));
1450    }
1451    /* other commands */
1452    else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
1453        return logcat(ttype, serial, argc, argv);
1454    }
1455    else if (!strcmp(argv[0],"ppp")) {
1456        return ppp(argc, argv);
1457    }
1458    else if (!strcmp(argv[0], "start-server")) {
1459        std::string error;
1460        return adb_connect("host:start-server", &error);
1461    }
1462    else if (!strcmp(argv[0], "backup")) {
1463        return backup(argc, argv);
1464    }
1465    else if (!strcmp(argv[0], "restore")) {
1466        return restore(argc, argv);
1467    }
1468    else if (!strcmp(argv[0], "keygen")) {
1469        if (argc < 2) return usage();
1470        return adb_auth_keygen(argv[1]);
1471    }
1472    else if (!strcmp(argv[0], "jdwp")) {
1473        return adb_connect_command("jdwp");
1474    }
1475    /* "adb /?" is a common idiom under Windows */
1476    else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
1477        help();
1478        return 0;
1479    }
1480    else if (!strcmp(argv[0], "version")) {
1481        version(stdout);
1482        return 0;
1483    }
1484
1485    usage();
1486    return 1;
1487}
1488
1489static int pm_command(transport_type transport, const char* serial,
1490                      int argc, const char** argv)
1491{
1492    std::string cmd = "shell:pm";
1493
1494    while (argc-- > 0) {
1495        cmd += " " + escape_arg(*argv++);
1496    }
1497
1498    return send_shell_command(transport, serial, cmd);
1499}
1500
1501static int uninstall_app(transport_type transport, const char* serial, int argc,
1502                         const char** argv)
1503{
1504    /* if the user choose the -k option, we refuse to do it until devices are
1505       out with the option to uninstall the remaining data somehow (adb/ui) */
1506    if (argc == 3 && strcmp(argv[1], "-k") == 0)
1507    {
1508        printf(
1509            "The -k option uninstalls the application while retaining the data/cache.\n"
1510            "At the moment, there is no way to remove the remaining data.\n"
1511            "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
1512            "If you truly wish to continue, execute 'adb shell pm uninstall -k %s'\n", argv[2]);
1513        return -1;
1514    }
1515
1516    /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
1517    return pm_command(transport, serial, argc, argv);
1518}
1519
1520static int delete_file(transport_type transport, const char* serial, char* filename)
1521{
1522    std::string cmd = "shell:rm -f " + escape_arg(filename);
1523    return send_shell_command(transport, serial, cmd);
1524}
1525
1526static const char* get_basename(const char* filename)
1527{
1528    const char* basename = adb_dirstop(filename);
1529    if (basename) {
1530        basename++;
1531        return basename;
1532    } else {
1533        return filename;
1534    }
1535}
1536
1537static int install_app(transport_type transport, const char* serial, int argc,
1538                       const char** argv)
1539{
1540    static const char *const DATA_DEST = "/data/local/tmp/%s";
1541    static const char *const SD_DEST = "/sdcard/tmp/%s";
1542    const char* where = DATA_DEST;
1543    int i;
1544    struct stat sb;
1545
1546    for (i = 1; i < argc; i++) {
1547        if (!strcmp(argv[i], "-s")) {
1548            where = SD_DEST;
1549        }
1550    }
1551
1552    // Find last APK argument.
1553    // All other arguments passed through verbatim.
1554    int last_apk = -1;
1555    for (i = argc - 1; i >= 0; i--) {
1556        const char* file = argv[i];
1557        char* dot = strrchr(file, '.');
1558        if (dot && !strcasecmp(dot, ".apk")) {
1559            if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
1560                fprintf(stderr, "Invalid APK file: %s\n", file);
1561                return -1;
1562            }
1563
1564            last_apk = i;
1565            break;
1566        }
1567    }
1568
1569    if (last_apk == -1) {
1570        fprintf(stderr, "Missing APK file\n");
1571        return -1;
1572    }
1573
1574    const char* apk_file = argv[last_apk];
1575    char apk_dest[PATH_MAX];
1576    snprintf(apk_dest, sizeof apk_dest, where, get_basename(apk_file));
1577    int err = do_sync_push(apk_file, apk_dest, 0 /* no show progress */);
1578    if (err) {
1579        goto cleanup_apk;
1580    } else {
1581        argv[last_apk] = apk_dest; /* destination name, not source location */
1582    }
1583
1584    err = pm_command(transport, serial, argc, argv);
1585
1586cleanup_apk:
1587    delete_file(transport, serial, apk_dest);
1588    return err;
1589}
1590
1591static int install_multiple_app(transport_type transport, const char* serial, int argc,
1592                                const char** argv)
1593{
1594    int i;
1595    struct stat sb;
1596    uint64_t total_size = 0;
1597
1598    // Find all APK arguments starting at end.
1599    // All other arguments passed through verbatim.
1600    int first_apk = -1;
1601    for (i = argc - 1; i >= 0; i--) {
1602        const char* file = argv[i];
1603        char* dot = strrchr(file, '.');
1604        if (dot && !strcasecmp(dot, ".apk")) {
1605            if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
1606                fprintf(stderr, "Invalid APK file: %s\n", file);
1607                return -1;
1608            }
1609
1610            total_size += sb.st_size;
1611            first_apk = i;
1612        } else {
1613            break;
1614        }
1615    }
1616
1617    if (first_apk == -1) {
1618        fprintf(stderr, "Missing APK file\n");
1619        return 1;
1620    }
1621
1622#if defined(_WIN32) // Remove when we're using clang for Win32.
1623    std::string cmd = android::base::StringPrintf("exec:pm install-create -S %u", (unsigned) total_size);
1624#else
1625    std::string cmd = android::base::StringPrintf("exec:pm install-create -S %" PRIu64, total_size);
1626#endif
1627    for (i = 1; i < first_apk; i++) {
1628        cmd += " " + escape_arg(argv[i]);
1629    }
1630
1631    // Create install session
1632    std::string error;
1633    int fd = adb_connect(cmd, &error);
1634    if (fd < 0) {
1635        fprintf(stderr, "Connect error for create: %s\n", error.c_str());
1636        return -1;
1637    }
1638    char buf[BUFSIZ];
1639    read_status_line(fd, buf, sizeof(buf));
1640    adb_close(fd);
1641
1642    int session_id = -1;
1643    if (!strncmp("Success", buf, 7)) {
1644        char* start = strrchr(buf, '[');
1645        char* end = strrchr(buf, ']');
1646        if (start && end) {
1647            *end = '\0';
1648            session_id = strtol(start + 1, NULL, 10);
1649        }
1650    }
1651    if (session_id < 0) {
1652        fprintf(stderr, "Failed to create session\n");
1653        fputs(buf, stderr);
1654        return -1;
1655    }
1656
1657    // Valid session, now stream the APKs
1658    int success = 1;
1659    for (i = first_apk; i < argc; i++) {
1660        const char* file = argv[i];
1661        if (stat(file, &sb) == -1) {
1662            fprintf(stderr, "Failed to stat %s\n", file);
1663            success = 0;
1664            goto finalize_session;
1665        }
1666
1667#if defined(_WIN32) // Remove when we're using clang for Win32.
1668        std::string cmd = android::base::StringPrintf(
1669                "exec:pm install-write -S %u %d %d_%s -",
1670                (unsigned) sb.st_size, session_id, i, get_basename(file));
1671#else
1672        std::string cmd = android::base::StringPrintf(
1673                "exec:pm install-write -S %" PRIu64 " %d %d_%s -",
1674                static_cast<uint64_t>(sb.st_size), session_id, i, get_basename(file));
1675#endif
1676
1677        int localFd = adb_open(file, O_RDONLY);
1678        if (localFd < 0) {
1679            fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
1680            success = 0;
1681            goto finalize_session;
1682        }
1683
1684        std::string error;
1685        int remoteFd = adb_connect(cmd, &error);
1686        if (remoteFd < 0) {
1687            fprintf(stderr, "Connect error for write: %s\n", error.c_str());
1688            adb_close(localFd);
1689            success = 0;
1690            goto finalize_session;
1691        }
1692
1693        copy_to_file(localFd, remoteFd);
1694        read_status_line(remoteFd, buf, sizeof(buf));
1695
1696        adb_close(localFd);
1697        adb_close(remoteFd);
1698
1699        if (strncmp("Success", buf, 7)) {
1700            fprintf(stderr, "Failed to write %s\n", file);
1701            fputs(buf, stderr);
1702            success = 0;
1703            goto finalize_session;
1704        }
1705    }
1706
1707finalize_session:
1708    // Commit session if we streamed everything okay; otherwise abandon
1709    std::string service =
1710            android::base::StringPrintf("exec:pm install-%s %d",
1711                                        success ? "commit" : "abandon", session_id);
1712    fd = adb_connect(service, &error);
1713    if (fd < 0) {
1714        fprintf(stderr, "Connect error for finalize: %s\n", error.c_str());
1715        return -1;
1716    }
1717    read_status_line(fd, buf, sizeof(buf));
1718    adb_close(fd);
1719
1720    if (!strncmp("Success", buf, 7)) {
1721        fputs(buf, stderr);
1722        return 0;
1723    } else {
1724        fprintf(stderr, "Failed to finalize session\n");
1725        fputs(buf, stderr);
1726        return -1;
1727    }
1728}
1729