adb_client.cpp revision 8d8126a705dd3c5734a0894f88c2c758784bd469
1/*
2 * Copyright (C) 2015 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#include "adb_client.h"
21
22#include <errno.h>
23#include <limits.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30
31#include <string>
32#include <vector>
33
34#include <base/stringprintf.h>
35#include <base/strings.h>
36
37#include "adb_io.h"
38
39static TransportType __adb_transport = kTransportAny;
40static const char* __adb_serial = NULL;
41
42static int __adb_server_port = DEFAULT_ADB_PORT;
43static const char* __adb_server_name = NULL;
44
45static std::string perror_str(const char* msg) {
46    return android::base::StringPrintf("%s: %s", msg, strerror(errno));
47}
48
49static bool ReadProtocolString(int fd, std::string* s, std::string* error) {
50    char buf[5];
51    if (!ReadFdExactly(fd, buf, 4)) {
52        *error = perror_str("protocol fault (couldn't read status length)");
53        return false;
54    }
55    buf[4] = 0;
56
57    unsigned long len = strtoul(buf, 0, 16);
58    s->resize(len, '\0');
59    if (!ReadFdExactly(fd, &(*s)[0], len)) {
60        *error = perror_str("protocol fault (couldn't read status message)");
61        return false;
62    }
63
64    return true;
65}
66
67void adb_set_transport(TransportType type, const char* serial)
68{
69    __adb_transport = type;
70    __adb_serial = serial;
71}
72
73void adb_set_tcp_specifics(int server_port)
74{
75    __adb_server_port = server_port;
76}
77
78void adb_set_tcp_name(const char* hostname)
79{
80    __adb_server_name = hostname;
81}
82
83static int switch_socket_transport(int fd, std::string* error) {
84    std::string service;
85    if (__adb_serial) {
86        service += "host:transport:";
87        service += __adb_serial;
88    } else {
89        const char* transport_type = "???";
90        switch (__adb_transport) {
91          case kTransportUsb:
92            transport_type = "transport-usb";
93            break;
94          case kTransportLocal:
95            transport_type = "transport-local";
96            break;
97          case kTransportAny:
98            transport_type = "transport-any";
99            break;
100          case kTransportHost:
101            // no switch necessary
102            return 0;
103        }
104        service += "host:";
105        service += transport_type;
106    }
107
108    if (!SendProtocolString(fd, service)) {
109        *error = perror_str("write failure during connection");
110        adb_close(fd);
111        return -1;
112    }
113    D("Switch transport in progress\n");
114
115    if (!adb_status(fd, error)) {
116        adb_close(fd);
117        D("Switch transport failed: %s\n", error->c_str());
118        return -1;
119    }
120    D("Switch transport success\n");
121    return 0;
122}
123
124bool adb_status(int fd, std::string* error) {
125    char buf[5];
126    if (!ReadFdExactly(fd, buf, 4)) {
127        *error = perror_str("protocol fault (couldn't read status)");
128        return false;
129    }
130
131    if (!memcmp(buf, "OKAY", 4)) {
132        return true;
133    }
134
135    if (memcmp(buf, "FAIL", 4)) {
136        *error = android::base::StringPrintf("protocol fault (status %02x %02x %02x %02x?!)",
137                                             buf[0], buf[1], buf[2], buf[3]);
138        return false;
139    }
140
141    ReadProtocolString(fd, error, error);
142    return false;
143}
144
145int _adb_connect(const std::string& service, std::string* error) {
146    D("_adb_connect: %s\n", service.c_str());
147    if (service.empty() || service.size() > 1024) {
148        *error = android::base::StringPrintf("bad service name length (%zd)",
149                                             service.size());
150        return -1;
151    }
152
153    int fd;
154    if (__adb_server_name) {
155        fd = socket_network_client(__adb_server_name, __adb_server_port, SOCK_STREAM);
156    } else {
157        fd = socket_loopback_client(__adb_server_port, SOCK_STREAM);
158    }
159    if (fd < 0) {
160        *error = perror_str("cannot connect to daemon");
161        return -2;
162    }
163
164    if (memcmp(&service[0],"host",4) != 0 && switch_socket_transport(fd, error)) {
165        return -1;
166    }
167
168    if(!SendProtocolString(fd, service)) {
169        *error = perror_str("write failure during connection");
170        adb_close(fd);
171        return -1;
172    }
173
174    if (!adb_status(fd, error)) {
175        adb_close(fd);
176        return -1;
177    }
178
179    D("_adb_connect: return fd %d\n", fd);
180    return fd;
181}
182
183int adb_connect(const std::string& service, std::string* error) {
184    // first query the adb server's version
185    int fd = _adb_connect("host:version", error);
186
187    D("adb_connect: service %s\n", service.c_str());
188    if (fd == -2 && __adb_server_name) {
189        fprintf(stderr,"** Cannot start server on remote host\n");
190        return fd;
191    } else if (fd == -2) {
192        fprintf(stdout,"* daemon not running. starting it now on port %d *\n",
193                __adb_server_port);
194    start_server:
195        if (launch_server(__adb_server_port)) {
196            fprintf(stderr,"* failed to start daemon *\n");
197            return -1;
198        } else {
199            fprintf(stdout,"* daemon started successfully *\n");
200        }
201        /* give the server some time to start properly and detect devices */
202        adb_sleep_ms(3000);
203        // fall through to _adb_connect
204    } else {
205        // if server was running, check its version to make sure it is not out of date
206        int version = ADB_SERVER_VERSION - 1;
207
208        // if we have a file descriptor, then parse version result
209        if (fd >= 0) {
210            std::string version_string;
211            if (!ReadProtocolString(fd, &version_string, error)) {
212                goto error;
213            }
214
215            adb_close(fd);
216
217            if (sscanf(&version_string[0], "%04x", &version) != 1) {
218                goto error;
219            }
220        } else {
221            // if fd is -1, then check for "unknown host service",
222            // which would indicate a version of adb that does not support the version command
223            if (*error == "unknown host service") {
224                return fd;
225            }
226        }
227
228        if (version != ADB_SERVER_VERSION) {
229            printf("adb server is out of date.  killing...\n");
230            fd = _adb_connect("host:kill", error);
231            adb_close(fd);
232
233            /* XXX can we better detect its death? */
234            adb_sleep_ms(2000);
235            goto start_server;
236        }
237    }
238
239    // if the command is start-server, we are done.
240    if (service == "host:start-server") {
241        return 0;
242    }
243
244    fd = _adb_connect(service, error);
245    if (fd == -1) {
246        D("_adb_connect error: %s\n", error->c_str());
247    } else if(fd == -2) {
248        fprintf(stderr,"** daemon still not running\n");
249    }
250    D("adb_connect: return fd %d\n", fd);
251
252    return fd;
253error:
254    adb_close(fd);
255    return -1;
256}
257
258
259bool adb_command(const std::string& service) {
260    std::string error;
261    int fd = adb_connect(service, &error);
262    if (fd < 0) {
263        fprintf(stderr, "error: %s\n", error.c_str());
264        return false;
265    }
266
267    if (!adb_status(fd, &error)) {
268        fprintf(stderr, "error: %s\n", error.c_str());
269        adb_close(fd);
270        return false;
271    }
272
273    return true;
274}
275
276bool adb_query(const std::string& service, std::string* result, std::string* error) {
277    D("adb_query: %s\n", service.c_str());
278    int fd = adb_connect(service, error);
279    if (fd < 0) {
280        fprintf(stderr,"error: %s\n", error->c_str());
281        return 0;
282    }
283
284    result->clear();
285    if (!ReadProtocolString(fd, result, error)) {
286        adb_close(fd);
287        return false;
288    }
289    return true;
290}
291