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