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 if (launch_server(__adb_server_socket_spec, __adb_client_one_device)) {
266 fprintf(stderr, "* failed to start daemon\n");
267 // launch_server() has already printed detailed error info, so just
268 // return a generic error string about the overall adb_connect()
269 // that the caller requested.
270 *error = "cannot connect to daemon";
271 return false;
272 } else {
273 fprintf(stderr, "* daemon started successfully\n");
274 }
275 // The server will wait until it detects all of its connected devices before acking.
276 // Fall through to _adb_connect.
277 } else {
278 // If a server is already running, check its version matches.
279 int version = 0;
280
281 // If we have a file descriptor, then parse version result.
282 if (fd >= 0) {
283 std::string version_string;
284 if (!ReadProtocolString(fd, &version_string, error)) {
285 return false;
286 }
287
288 ReadOrderlyShutdown(fd);
289
290 if (sscanf(&version_string[0], "%04x", &version) != 1) {
291 *error = android::base::StringPrintf("cannot parse version string: %s",
292 version_string.c_str());
293 return false;
294 }
295 } else {
296 // If fd is -1 check for "unknown host service" which would
297 // indicate a version of adb that does not support the
298 // version command, in which case we should fall-through to kill it.
299 if (*error != "unknown host service") {
300 return false;
301 }
302 }
303
304 if (version != ADB_SERVER_VERSION) {
305 #if defined(__linux__)
306 if (version > ADB_SERVER_VERSION && local) {
307 // Try to re-exec the existing adb server's binary.
308 constexpr const char* adb_reexeced = "adb (re-execed)";
309 if (strcmp(adb_reexeced, *__adb_argv) != 0) {
310 __adb_argv[0] = adb_reexeced;
311 std::optional<std::string> server_path_path = adb_get_server_executable_path();
312 std::string server_path;
313 if (server_path_path &&
314 android::base::ReadFileToString(*server_path_path, &server_path)) {
315 if (execve(server_path.c_str(), const_cast<char**>(__adb_argv),
316 const_cast<char**>(__adb_envp)) == -1) {
317 LOG(ERROR) << "failed to exec newer version at " << server_path;
318 }
319
320 // Fall-through to restarting the server.
321 }
322 }
323 }
324 #endif
325
326 fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
327 version, ADB_SERVER_VERSION);
328 adb_kill_server();
329 goto start_server;
330 }
331 }
332
333 return true;
334 }
335
adb_check_server_version(std::string * error)336 bool adb_check_server_version(std::string* error) {
337 // Only check the version once per process, since this isn't atomic anyway.
338 static std::once_flag once;
339 static bool result;
340 static std::string* err;
341 std::call_once(once, []() {
342 err = new std::string();
343 result = __adb_check_server_version(err);
344 });
345 *error = *err;
346 return result;
347 }
348
adb_connect(TransportId * transport,std::string_view service,std::string * error,bool force_switch_device)349 int adb_connect(TransportId* transport, std::string_view service, std::string* error,
350 bool force_switch_device) {
351 LOG(DEBUG) << "adb_connect: service: " << service;
352
353 // Query the adb server's version.
354 if (!adb_check_server_version(error)) {
355 return -1;
356 }
357
358 // if the command is start-server, we are done.
359 if (service == "host:start-server") {
360 return 0;
361 }
362
363 unique_fd fd(_adb_connect(service, transport, error, force_switch_device));
364 if (fd == -1) {
365 D("_adb_connect error: %s", error->c_str());
366 } else if(fd == -2) {
367 fprintf(stderr, "* daemon still not running\n");
368 }
369 D("adb_connect: return fd %d", fd.get());
370
371 return fd.release();
372 }
373
adb_command(const std::string & service)374 bool adb_command(const std::string& service) {
375 std::string error;
376 unique_fd fd(adb_connect(service, &error));
377 if (fd < 0) {
378 fprintf(stderr, "error: %s\n", error.c_str());
379 return false;
380 }
381
382 if (!adb_status(fd.get(), &error)) {
383 fprintf(stderr, "error: %s\n", error.c_str());
384 return false;
385 }
386
387 ReadOrderlyShutdown(fd.get());
388 return true;
389 }
390
adb_query(const std::string & service,std::string * result,std::string * error,bool force_switch_device)391 bool adb_query(const std::string& service, std::string* result, std::string* error,
392 bool force_switch_device) {
393 D("adb_query: %s", service.c_str());
394 unique_fd fd(adb_connect(nullptr, service, error, force_switch_device));
395 if (fd < 0) {
396 return false;
397 }
398
399 result->clear();
400 if (!ReadProtocolString(fd.get(), result, error)) {
401 return false;
402 }
403
404 ReadOrderlyShutdown(fd.get());
405 return true;
406 }
407
format_host_command(const char * command)408 std::string format_host_command(const char* command) {
409 if (__adb_transport_id) {
410 return android::base::StringPrintf("host-transport-id:%" PRIu64 ":%s", __adb_transport_id,
411 command);
412 } else if (__adb_serial) {
413 return android::base::StringPrintf("host-serial:%s:%s", __adb_serial, command);
414 }
415
416 const char* prefix = "host";
417 if (__adb_transport == kTransportUsb) {
418 prefix = "host-usb";
419 } else if (__adb_transport == kTransportLocal) {
420 prefix = "host-local";
421 }
422 return android::base::StringPrintf("%s:%s", prefix, command);
423 }
424
adb_get_feature_set(std::string * error)425 const std::optional<FeatureSet>& adb_get_feature_set(std::string* error) {
426 static std::mutex feature_mutex [[clang::no_destroy]];
427 static std::optional<FeatureSet> features [[clang::no_destroy]] GUARDED_BY(feature_mutex);
428 std::lock_guard<std::mutex> lock(feature_mutex);
429 if (!features) {
430 std::string result;
431 std::string err;
432 if (adb_query(format_host_command("features"), &result, &err)) {
433 features = StringToFeatureSet(result);
434 } else {
435 if (error) {
436 *error = err;
437 }
438 }
439 }
440 return features;
441 }
442