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