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