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