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 ADB
18
19#include "sysdeps.h"
20#include "adb_client.h"
21
22#include <errno.h>
23#include <inttypes.h>
24#include <limits.h>
25#include <stdarg.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31
32#include <condition_variable>
33#include <mutex>
34#include <string>
35#include <thread>
36#include <vector>
37
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <android-base/thread_annotations.h>
41#include <cutils/sockets.h>
42
43#include "adb_io.h"
44#include "adb_utils.h"
45#include "socket_spec.h"
46#include "sysdeps/chrono.h"
47
48static TransportType __adb_transport = kTransportAny;
49static const char* __adb_serial = NULL;
50static TransportId __adb_transport_id = 0;
51
52static const char* __adb_server_socket_spec;
53
54void adb_set_transport(TransportType type, const char* serial, TransportId transport_id) {
55    __adb_transport = type;
56    __adb_serial = serial;
57    __adb_transport_id = transport_id;
58}
59
60void adb_get_transport(TransportType* type, const char** serial, TransportId* transport_id) {
61    if (type) *type = __adb_transport;
62    if (serial) *serial = __adb_serial;
63    if (transport_id) *transport_id = __adb_transport_id;
64}
65
66void adb_set_socket_spec(const char* socket_spec) {
67    if (__adb_server_socket_spec) {
68        LOG(FATAL) << "attempted to reinitialize adb_server_socket_spec " << socket_spec << " (was " << __adb_server_socket_spec << ")";
69    }
70    __adb_server_socket_spec = socket_spec;
71}
72
73static int switch_socket_transport(int fd, std::string* error) {
74    std::string service;
75    if (__adb_transport_id) {
76        service += "host:transport-id:";
77        service += std::to_string(__adb_transport_id);
78    } else if (__adb_serial) {
79        service += "host:transport:";
80        service += __adb_serial;
81    } else {
82        const char* transport_type = "???";
83        switch (__adb_transport) {
84          case kTransportUsb:
85            transport_type = "transport-usb";
86            break;
87          case kTransportLocal:
88            transport_type = "transport-local";
89            break;
90          case kTransportAny:
91            transport_type = "transport-any";
92            break;
93          case kTransportHost:
94            // no switch necessary
95            return 0;
96        }
97        service += "host:";
98        service += transport_type;
99    }
100
101    if (!SendProtocolString(fd, service)) {
102        *error = perror_str("write failure during connection");
103        adb_close(fd);
104        return -1;
105    }
106    D("Switch transport in progress");
107
108    if (!adb_status(fd, error)) {
109        adb_close(fd);
110        D("Switch transport failed: %s", error->c_str());
111        return -1;
112    }
113    D("Switch transport success");
114    return 0;
115}
116
117bool adb_status(int fd, std::string* error) {
118    char buf[5];
119    if (!ReadFdExactly(fd, buf, 4)) {
120        *error = perror_str("protocol fault (couldn't read status)");
121        return false;
122    }
123
124    if (!memcmp(buf, "OKAY", 4)) {
125        return true;
126    }
127
128    if (memcmp(buf, "FAIL", 4)) {
129        *error = android::base::StringPrintf("protocol fault (status %02x %02x %02x %02x?!)",
130                                             buf[0], buf[1], buf[2], buf[3]);
131        return false;
132    }
133
134    ReadProtocolString(fd, error, error);
135    return false;
136}
137
138static int _adb_connect(const std::string& service, std::string* error) {
139    D("_adb_connect: %s", service.c_str());
140    if (service.empty() || service.size() > MAX_PAYLOAD) {
141        *error = android::base::StringPrintf("bad service name length (%zd)",
142                                             service.size());
143        return -1;
144    }
145
146    std::string reason;
147    int fd = socket_spec_connect(__adb_server_socket_spec, &reason);
148    if (fd < 0) {
149        *error = android::base::StringPrintf("cannot connect to daemon at %s: %s",
150                                             __adb_server_socket_spec, reason.c_str());
151        return -2;
152    }
153
154    if (memcmp(&service[0], "host", 4) != 0 && switch_socket_transport(fd, error)) {
155        return -1;
156    }
157
158    if (!SendProtocolString(fd, service)) {
159        *error = perror_str("write failure during connection");
160        adb_close(fd);
161        return -1;
162    }
163
164    if (!adb_status(fd, error)) {
165        adb_close(fd);
166        return -1;
167    }
168
169    D("_adb_connect: return fd %d", fd);
170    return fd;
171}
172
173bool adb_kill_server() {
174    D("adb_kill_server");
175    std::string reason;
176    int fd = socket_spec_connect(__adb_server_socket_spec, &reason);
177    if (fd < 0) {
178        fprintf(stderr, "cannot connect to daemon at %s: %s\n", __adb_server_socket_spec,
179                reason.c_str());
180        return true;
181    }
182
183    if (!SendProtocolString(fd, "host:kill")) {
184        fprintf(stderr, "error: write failure during connection: %s\n", strerror(errno));
185        return false;
186    }
187
188    ReadOrderlyShutdown(fd);
189    return true;
190}
191
192int adb_connect(const std::string& service, std::string* error) {
193    // first query the adb server's version
194    int fd = _adb_connect("host:version", error);
195
196    D("adb_connect: service %s", service.c_str());
197    if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) {
198        fprintf(stderr, "* cannot start server on remote host\n");
199        // error is the original network connection error
200        return fd;
201    } else if (fd == -2) {
202        fprintf(stderr, "* daemon not running; starting now at %s\n", __adb_server_socket_spec);
203    start_server:
204        if (launch_server(__adb_server_socket_spec)) {
205            fprintf(stderr, "* failed to start daemon\n");
206            // launch_server() has already printed detailed error info, so just
207            // return a generic error string about the overall adb_connect()
208            // that the caller requested.
209            *error = "cannot connect to daemon";
210            return -1;
211        } else {
212            fprintf(stderr, "* daemon started successfully\n");
213        }
214        // The server will wait until it detects all of its connected devices before acking.
215        // Fall through to _adb_connect.
216    } else {
217        // If a server is already running, check its version matches.
218        int version = ADB_SERVER_VERSION - 1;
219
220        // If we have a file descriptor, then parse version result.
221        if (fd >= 0) {
222            std::string version_string;
223            if (!ReadProtocolString(fd, &version_string, error)) {
224                adb_close(fd);
225                return -1;
226            }
227
228            ReadOrderlyShutdown(fd);
229            adb_close(fd);
230
231            if (sscanf(&version_string[0], "%04x", &version) != 1) {
232                *error = android::base::StringPrintf("cannot parse version string: %s",
233                                                     version_string.c_str());
234                return -1;
235            }
236        } else {
237            // If fd is -1 check for "unknown host service" which would
238            // indicate a version of adb that does not support the
239            // version command, in which case we should fall-through to kill it.
240            if (*error != "unknown host service") {
241                return fd;
242            }
243        }
244
245        if (version != ADB_SERVER_VERSION) {
246            fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
247                    version, ADB_SERVER_VERSION);
248            adb_kill_server();
249            goto start_server;
250        }
251    }
252
253    // if the command is start-server, we are done.
254    if (service == "host:start-server") {
255        return 0;
256    }
257
258    fd = _adb_connect(service, error);
259    if (fd == -1) {
260        D("_adb_connect error: %s", error->c_str());
261    } else if(fd == -2) {
262        fprintf(stderr, "* daemon still not running\n");
263    }
264    D("adb_connect: return fd %d", fd);
265
266    return fd;
267}
268
269
270bool adb_command(const std::string& service) {
271    std::string error;
272    int fd = adb_connect(service, &error);
273    if (fd < 0) {
274        fprintf(stderr, "error: %s\n", error.c_str());
275        return false;
276    }
277
278    if (!adb_status(fd, &error)) {
279        fprintf(stderr, "error: %s\n", error.c_str());
280        adb_close(fd);
281        return false;
282    }
283
284    ReadOrderlyShutdown(fd);
285    adb_close(fd);
286    return true;
287}
288
289bool adb_query(const std::string& service, std::string* result, std::string* error) {
290    D("adb_query: %s", service.c_str());
291    int fd = adb_connect(service, error);
292    if (fd < 0) {
293        return false;
294    }
295
296    result->clear();
297    if (!ReadProtocolString(fd, result, error)) {
298        adb_close(fd);
299        return false;
300    }
301
302    ReadOrderlyShutdown(fd);
303    adb_close(fd);
304    return true;
305}
306
307std::string format_host_command(const char* command) {
308    if (__adb_transport_id) {
309        return android::base::StringPrintf("host-transport-id:%" PRIu64 ":%s", __adb_transport_id,
310                                           command);
311    } else if (__adb_serial) {
312        return android::base::StringPrintf("host-serial:%s:%s", __adb_serial, command);
313    }
314
315    const char* prefix = "host";
316    if (__adb_transport == kTransportUsb) {
317        prefix = "host-usb";
318    } else if (__adb_transport == kTransportLocal) {
319        prefix = "host-local";
320    }
321    return android::base::StringPrintf("%s:%s", prefix, command);
322}
323
324bool adb_get_feature_set(FeatureSet* feature_set, std::string* error) {
325    std::string result;
326    if (adb_query(format_host_command("features"), &result, error)) {
327        *feature_set = StringToFeatureSet(result);
328        return true;
329    }
330    feature_set->clear();
331    return false;
332}
333