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 <optional>
35 #include <string>
36 #include <thread>
37 #include <vector>
38
39 #include <android-base/file.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <android-base/thread_annotations.h>
43 #include <cutils/sockets.h>
44
45 #include "adb_io.h"
46 #include "adb_utils.h"
47 #include "socket_spec.h"
48 #include "sysdeps/chrono.h"
49
50 static TransportType __adb_transport = kTransportAny;
51 static const char* __adb_serial = nullptr;
52 static TransportId __adb_transport_id = 0;
53
54 static const char* __adb_server_socket_spec;
55
adb_set_transport(TransportType type,const char * serial,TransportId transport_id)56 void adb_set_transport(TransportType type, const char* serial, TransportId transport_id) {
57 __adb_transport = type;
58 __adb_serial = serial;
59 __adb_transport_id = transport_id;
60 }
61
adb_get_transport(TransportType * type,const char ** serial,TransportId * transport_id)62 void adb_get_transport(TransportType* type, const char** serial, TransportId* transport_id) {
63 if (type) *type = __adb_transport;
64 if (serial) *serial = __adb_serial;
65 if (transport_id) *transport_id = __adb_transport_id;
66 }
67
adb_set_socket_spec(const char * socket_spec)68 void adb_set_socket_spec(const char* socket_spec) {
69 if (__adb_server_socket_spec) {
70 LOG(FATAL) << "attempted to reinitialize adb_server_socket_spec " << socket_spec << " (was " << __adb_server_socket_spec << ")";
71 }
72 __adb_server_socket_spec = socket_spec;
73 }
74
switch_socket_transport(int fd,std::string * error)75 static std::optional<TransportId> switch_socket_transport(int fd, std::string* error) {
76 TransportId result;
77 bool read_transport = true;
78
79 std::string service;
80 if (__adb_transport_id) {
81 read_transport = false;
82 service += "host:transport-id:";
83 service += std::to_string(__adb_transport_id);
84 result = __adb_transport_id;
85 } else if (__adb_serial) {
86 service += "host:tport:serial:";
87 service += __adb_serial;
88 } else {
89 const char* transport_type = "???";
90 switch (__adb_transport) {
91 case kTransportUsb:
92 transport_type = "usb";
93 break;
94 case kTransportLocal:
95 transport_type = "local";
96 break;
97 case kTransportAny:
98 transport_type = "any";
99 break;
100 case kTransportHost:
101 // no switch necessary
102 return 0;
103 }
104 service += "host:tport:";
105 service += transport_type;
106 }
107
108 if (!SendProtocolString(fd, service)) {
109 *error = perror_str("write failure during connection");
110 return std::nullopt;
111 }
112
113 LOG(DEBUG) << "Switch transport in progress: " << service;
114
115 if (!adb_status(fd, error)) {
116 D("Switch transport failed: %s", error->c_str());
117 return std::nullopt;
118 }
119
120 if (read_transport) {
121 if (!ReadFdExactly(fd, &result, sizeof(result))) {
122 *error = "failed to read transport id from server";
123 return std::nullopt;
124 }
125 }
126
127 D("Switch transport success");
128 return result;
129 }
130
adb_status(int fd,std::string * error)131 bool adb_status(int fd, std::string* error) {
132 char buf[5];
133 if (!ReadFdExactly(fd, buf, 4)) {
134 *error = perror_str("protocol fault (couldn't read status)");
135 return false;
136 }
137
138 if (!memcmp(buf, "OKAY", 4)) {
139 return true;
140 }
141
142 if (memcmp(buf, "FAIL", 4)) {
143 *error = android::base::StringPrintf("protocol fault (status %02x %02x %02x %02x?!)",
144 buf[0], buf[1], buf[2], buf[3]);
145 return false;
146 }
147
148 ReadProtocolString(fd, error, error);
149 return false;
150 }
151
_adb_connect(std::string_view service,TransportId * transport,std::string * error)152 static int _adb_connect(std::string_view service, TransportId* transport, std::string* error) {
153 LOG(DEBUG) << "_adb_connect: " << service;
154 if (service.empty() || service.size() > MAX_PAYLOAD) {
155 *error = android::base::StringPrintf("bad service name length (%zd)", service.size());
156 return -1;
157 }
158
159 std::string reason;
160 unique_fd fd;
161 if (!socket_spec_connect(&fd, __adb_server_socket_spec, nullptr, nullptr, &reason)) {
162 *error = android::base::StringPrintf("cannot connect to daemon at %s: %s",
163 __adb_server_socket_spec, reason.c_str());
164 return -2;
165 }
166
167 if (!service.starts_with("host")) {
168 std::optional<TransportId> transport_result = switch_socket_transport(fd.get(), error);
169 if (!transport_result) {
170 return -1;
171 }
172
173 if (transport) {
174 *transport = *transport_result;
175 }
176 }
177
178 if (!SendProtocolString(fd.get(), service)) {
179 *error = perror_str("write failure during connection");
180 return -1;
181 }
182
183 if (!adb_status(fd.get(), error)) {
184 return -1;
185 }
186
187 D("_adb_connect: return fd %d", fd.get());
188 return fd.release();
189 }
190
adb_kill_server()191 bool adb_kill_server() {
192 D("adb_kill_server");
193 std::string reason;
194 unique_fd fd;
195 if (!socket_spec_connect(&fd, __adb_server_socket_spec, nullptr, nullptr, &reason)) {
196 fprintf(stderr, "cannot connect to daemon at %s: %s\n", __adb_server_socket_spec,
197 reason.c_str());
198 return true;
199 }
200
201 if (!SendProtocolString(fd.get(), "host:kill")) {
202 fprintf(stderr, "error: write failure during connection: %s\n", strerror(errno));
203 return false;
204 }
205
206 // The server might send OKAY, so consume that.
207 char buf[4];
208 ReadFdExactly(fd.get(), buf, 4);
209 // Now that no more data is expected, wait for socket orderly shutdown or error, indicating
210 // server death.
211 ReadOrderlyShutdown(fd.get());
212 return true;
213 }
214
adb_connect(std::string_view service,std::string * error)215 int adb_connect(std::string_view service, std::string* error) {
216 return adb_connect(nullptr, service, error);
217 }
218
219 #if defined(__linux__)
adb_get_server_executable_path()220 std::optional<std::string> adb_get_server_executable_path() {
221 int port;
222 std::string error;
223 if (!parse_tcp_socket_spec(__adb_server_socket_spec, nullptr, &port, nullptr, &error)) {
224 LOG(FATAL) << "failed to parse server socket spec: " << error;
225 }
226
227 return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adb." + std::to_string(port);
228 }
229 #endif
230
__adb_check_server_version(std::string * error)231 static bool __adb_check_server_version(std::string* error) {
232 unique_fd fd(_adb_connect("host:version", nullptr, error));
233
234 bool local = is_local_socket_spec(__adb_server_socket_spec);
235 if (fd == -2 && !local) {
236 fprintf(stderr, "* cannot start server on remote host\n");
237 // error is the original network connection error
238 return false;
239 } else if (fd == -2) {
240 fprintf(stderr, "* daemon not running; starting now at %s\n", __adb_server_socket_spec);
241 start_server:
242 if (launch_server(__adb_server_socket_spec)) {
243 fprintf(stderr, "* failed to start daemon\n");
244 // launch_server() has already printed detailed error info, so just
245 // return a generic error string about the overall adb_connect()
246 // that the caller requested.
247 *error = "cannot connect to daemon";
248 return false;
249 } else {
250 fprintf(stderr, "* daemon started successfully\n");
251 }
252 // The server will wait until it detects all of its connected devices before acking.
253 // Fall through to _adb_connect.
254 } else {
255 // If a server is already running, check its version matches.
256 int version = 0;
257
258 // If we have a file descriptor, then parse version result.
259 if (fd >= 0) {
260 std::string version_string;
261 if (!ReadProtocolString(fd, &version_string, error)) {
262 return false;
263 }
264
265 ReadOrderlyShutdown(fd);
266
267 if (sscanf(&version_string[0], "%04x", &version) != 1) {
268 *error = android::base::StringPrintf("cannot parse version string: %s",
269 version_string.c_str());
270 return false;
271 }
272 } else {
273 // If fd is -1 check for "unknown host service" which would
274 // indicate a version of adb that does not support the
275 // version command, in which case we should fall-through to kill it.
276 if (*error != "unknown host service") {
277 return false;
278 }
279 }
280
281 if (version != ADB_SERVER_VERSION) {
282 #if defined(__linux__)
283 if (version > ADB_SERVER_VERSION && local) {
284 // Try to re-exec the existing adb server's binary.
285 constexpr const char* adb_reexeced = "adb (re-execed)";
286 if (strcmp(adb_reexeced, *__adb_argv) != 0) {
287 __adb_argv[0] = adb_reexeced;
288 std::optional<std::string> server_path_path = adb_get_server_executable_path();
289 std::string server_path;
290 if (server_path_path &&
291 android::base::ReadFileToString(*server_path_path, &server_path)) {
292 if (execve(server_path.c_str(), const_cast<char**>(__adb_argv),
293 const_cast<char**>(__adb_envp)) == -1) {
294 LOG(ERROR) << "failed to exec newer version at " << server_path;
295 }
296
297 // Fall-through to restarting the server.
298 }
299 }
300 }
301 #endif
302
303 fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
304 version, ADB_SERVER_VERSION);
305 adb_kill_server();
306 goto start_server;
307 }
308 }
309
310 return true;
311 }
312
adb_check_server_version(std::string * error)313 bool adb_check_server_version(std::string* error) {
314 // Only check the version once per process, since this isn't atomic anyway.
315 static std::once_flag once;
316 static bool result;
317 static std::string* err;
318 std::call_once(once, []() {
319 err = new std::string();
320 result = __adb_check_server_version(err);
321 });
322 *error = *err;
323 return result;
324 }
325
adb_connect(TransportId * transport,std::string_view service,std::string * error)326 int adb_connect(TransportId* transport, std::string_view service, std::string* error) {
327 LOG(DEBUG) << "adb_connect: service: " << service;
328
329 // Query the adb server's version.
330 if (!adb_check_server_version(error)) {
331 return -1;
332 }
333
334 // if the command is start-server, we are done.
335 if (service == "host:start-server") {
336 return 0;
337 }
338
339 unique_fd fd(_adb_connect(service, transport, error));
340 if (fd == -1) {
341 D("_adb_connect error: %s", error->c_str());
342 } else if(fd == -2) {
343 fprintf(stderr, "* daemon still not running\n");
344 }
345 D("adb_connect: return fd %d", fd.get());
346
347 return fd.release();
348 }
349
adb_command(const std::string & service)350 bool adb_command(const std::string& service) {
351 std::string error;
352 unique_fd fd(adb_connect(service, &error));
353 if (fd < 0) {
354 fprintf(stderr, "error: %s\n", error.c_str());
355 return false;
356 }
357
358 if (!adb_status(fd.get(), &error)) {
359 fprintf(stderr, "error: %s\n", error.c_str());
360 return false;
361 }
362
363 ReadOrderlyShutdown(fd.get());
364 return true;
365 }
366
adb_query(const std::string & service,std::string * result,std::string * error)367 bool adb_query(const std::string& service, std::string* result, std::string* error) {
368 D("adb_query: %s", service.c_str());
369 unique_fd fd(adb_connect(service, error));
370 if (fd < 0) {
371 return false;
372 }
373
374 result->clear();
375 if (!ReadProtocolString(fd.get(), result, error)) {
376 return false;
377 }
378
379 ReadOrderlyShutdown(fd.get());
380 return true;
381 }
382
format_host_command(const char * command)383 std::string format_host_command(const char* command) {
384 if (__adb_transport_id) {
385 return android::base::StringPrintf("host-transport-id:%" PRIu64 ":%s", __adb_transport_id,
386 command);
387 } else if (__adb_serial) {
388 return android::base::StringPrintf("host-serial:%s:%s", __adb_serial, command);
389 }
390
391 const char* prefix = "host";
392 if (__adb_transport == kTransportUsb) {
393 prefix = "host-usb";
394 } else if (__adb_transport == kTransportLocal) {
395 prefix = "host-local";
396 }
397 return android::base::StringPrintf("%s:%s", prefix, command);
398 }
399
adb_get_feature_set(FeatureSet * feature_set,std::string * error)400 bool adb_get_feature_set(FeatureSet* feature_set, std::string* error) {
401 std::string result;
402 if (adb_query(format_host_command("features"), &result, error)) {
403 *feature_set = StringToFeatureSet(result);
404 return true;
405 }
406 feature_set->clear();
407 return false;
408 }
409