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(borrowed_fd fd,std::string * error)131 bool adb_status(borrowed_fd 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,bool force_switch=false)152 static int _adb_connect(std::string_view service, TransportId* transport, std::string* error,
153                         bool force_switch = false) {
154     LOG(DEBUG) << "_adb_connect: " << service;
155     if (service.empty() || service.size() > MAX_PAYLOAD) {
156         *error = android::base::StringPrintf("bad service name length (%zd)", service.size());
157         return -1;
158     }
159 
160     std::string reason;
161     unique_fd fd;
162     if (!socket_spec_connect(&fd, __adb_server_socket_spec, nullptr, nullptr, &reason)) {
163         *error = android::base::StringPrintf("cannot connect to daemon at %s: %s",
164                                              __adb_server_socket_spec, reason.c_str());
165         return -2;
166     }
167 
168     if (!service.starts_with("host") || force_switch) {
169         std::optional<TransportId> transport_result = switch_socket_transport(fd.get(), error);
170         if (!transport_result) {
171             return -1;
172         }
173 
174         if (transport) {
175             *transport = *transport_result;
176         }
177     }
178 
179     if (!SendProtocolString(fd.get(), service)) {
180         *error = perror_str("write failure during connection");
181         return -1;
182     }
183 
184     if (!adb_status(fd.get(), error)) {
185         return -1;
186     }
187 
188     D("_adb_connect: return fd %d", fd.get());
189     return fd.release();
190 }
191 
adb_kill_server()192 bool adb_kill_server() {
193     D("adb_kill_server");
194     std::string reason;
195     unique_fd fd;
196     if (!socket_spec_connect(&fd, __adb_server_socket_spec, nullptr, nullptr, &reason)) {
197         fprintf(stderr, "cannot connect to daemon at %s: %s\n", __adb_server_socket_spec,
198                 reason.c_str());
199         return true;
200     }
201 
202     if (!SendProtocolString(fd.get(), "host:kill")) {
203         fprintf(stderr, "error: write failure during connection: %s\n", strerror(errno));
204         return false;
205     }
206 
207     // The server might send OKAY, so consume that.
208     char buf[4];
209     ReadFdExactly(fd.get(), buf, 4);
210     // Now that no more data is expected, wait for socket orderly shutdown or error, indicating
211     // server death.
212     ReadOrderlyShutdown(fd.get());
213     return true;
214 }
215 
adb_connect(std::string_view service,std::string * error)216 int adb_connect(std::string_view service, std::string* error) {
217     return adb_connect(nullptr, service, error);
218 }
219 
220 #if defined(__linux__)
adb_get_server_executable_path()221 std::optional<std::string> adb_get_server_executable_path() {
222     int port;
223     std::string error;
224     if (!parse_tcp_socket_spec(__adb_server_socket_spec, nullptr, &port, nullptr, &error)) {
225         LOG(FATAL) << "failed to parse server socket spec: " << error;
226     }
227 
228     return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adb." + std::to_string(port);
229 }
230 #endif
231 
__adb_check_server_version(std::string * error)232 static bool __adb_check_server_version(std::string* error) {
233     unique_fd fd(_adb_connect("host:version", nullptr, error));
234 
235     bool local = is_local_socket_spec(__adb_server_socket_spec);
236     if (fd == -2 && !local) {
237         fprintf(stderr, "* cannot start server on remote host\n");
238         // error is the original network connection error
239         return false;
240     } else if (fd == -2) {
241         fprintf(stderr, "* daemon not running; starting now at %s\n", __adb_server_socket_spec);
242     start_server:
243         if (launch_server(__adb_server_socket_spec)) {
244             fprintf(stderr, "* failed to start daemon\n");
245             // launch_server() has already printed detailed error info, so just
246             // return a generic error string about the overall adb_connect()
247             // that the caller requested.
248             *error = "cannot connect to daemon";
249             return false;
250         } else {
251             fprintf(stderr, "* daemon started successfully\n");
252         }
253         // The server will wait until it detects all of its connected devices before acking.
254         // Fall through to _adb_connect.
255     } else {
256         // If a server is already running, check its version matches.
257         int version = 0;
258 
259         // If we have a file descriptor, then parse version result.
260         if (fd >= 0) {
261             std::string version_string;
262             if (!ReadProtocolString(fd, &version_string, error)) {
263                 return false;
264             }
265 
266             ReadOrderlyShutdown(fd);
267 
268             if (sscanf(&version_string[0], "%04x", &version) != 1) {
269                 *error = android::base::StringPrintf("cannot parse version string: %s",
270                                                      version_string.c_str());
271                 return false;
272             }
273         } else {
274             // If fd is -1 check for "unknown host service" which would
275             // indicate a version of adb that does not support the
276             // version command, in which case we should fall-through to kill it.
277             if (*error != "unknown host service") {
278                 return false;
279             }
280         }
281 
282         if (version != ADB_SERVER_VERSION) {
283 #if defined(__linux__)
284             if (version > ADB_SERVER_VERSION && local) {
285                 // Try to re-exec the existing adb server's binary.
286                 constexpr const char* adb_reexeced = "adb (re-execed)";
287                 if (strcmp(adb_reexeced, *__adb_argv) != 0) {
288                     __adb_argv[0] = adb_reexeced;
289                     std::optional<std::string> server_path_path = adb_get_server_executable_path();
290                     std::string server_path;
291                     if (server_path_path &&
292                         android::base::ReadFileToString(*server_path_path, &server_path)) {
293                         if (execve(server_path.c_str(), const_cast<char**>(__adb_argv),
294                                    const_cast<char**>(__adb_envp)) == -1) {
295                             LOG(ERROR) << "failed to exec newer version at " << server_path;
296                         }
297 
298                         // Fall-through to restarting the server.
299                     }
300                 }
301             }
302 #endif
303 
304             fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
305                     version, ADB_SERVER_VERSION);
306             adb_kill_server();
307             goto start_server;
308         }
309     }
310 
311     return true;
312 }
313 
adb_check_server_version(std::string * error)314 bool adb_check_server_version(std::string* error) {
315     // Only check the version once per process, since this isn't atomic anyway.
316     static std::once_flag once;
317     static bool result;
318     static std::string* err;
319     std::call_once(once, []() {
320         err = new std::string();
321         result = __adb_check_server_version(err);
322     });
323     *error = *err;
324     return result;
325 }
326 
adb_connect(TransportId * transport,std::string_view service,std::string * error,bool force_switch_device)327 int adb_connect(TransportId* transport, std::string_view service, std::string* error,
328                 bool force_switch_device) {
329     LOG(DEBUG) << "adb_connect: service: " << service;
330 
331     // Query the adb server's version.
332     if (!adb_check_server_version(error)) {
333         return -1;
334     }
335 
336     // if the command is start-server, we are done.
337     if (service == "host:start-server") {
338         return 0;
339     }
340 
341     unique_fd fd(_adb_connect(service, transport, error, force_switch_device));
342     if (fd == -1) {
343         D("_adb_connect error: %s", error->c_str());
344     } else if(fd == -2) {
345         fprintf(stderr, "* daemon still not running\n");
346     }
347     D("adb_connect: return fd %d", fd.get());
348 
349     return fd.release();
350 }
351 
adb_command(const std::string & service)352 bool adb_command(const std::string& service) {
353     std::string error;
354     unique_fd fd(adb_connect(service, &error));
355     if (fd < 0) {
356         fprintf(stderr, "error: %s\n", error.c_str());
357         return false;
358     }
359 
360     if (!adb_status(fd.get(), &error)) {
361         fprintf(stderr, "error: %s\n", error.c_str());
362         return false;
363     }
364 
365     ReadOrderlyShutdown(fd.get());
366     return true;
367 }
368 
adb_query(const std::string & service,std::string * result,std::string * error)369 bool adb_query(const std::string& service, std::string* result, std::string* error) {
370     D("adb_query: %s", service.c_str());
371     unique_fd fd(adb_connect(service, error));
372     if (fd < 0) {
373         return false;
374     }
375 
376     result->clear();
377     if (!ReadProtocolString(fd.get(), result, error)) {
378         return false;
379     }
380 
381     ReadOrderlyShutdown(fd.get());
382     return true;
383 }
384 
format_host_command(const char * command)385 std::string format_host_command(const char* command) {
386     if (__adb_transport_id) {
387         return android::base::StringPrintf("host-transport-id:%" PRIu64 ":%s", __adb_transport_id,
388                                            command);
389     } else if (__adb_serial) {
390         return android::base::StringPrintf("host-serial:%s:%s", __adb_serial, command);
391     }
392 
393     const char* prefix = "host";
394     if (__adb_transport == kTransportUsb) {
395         prefix = "host-usb";
396     } else if (__adb_transport == kTransportLocal) {
397         prefix = "host-local";
398     }
399     return android::base::StringPrintf("%s:%s", prefix, command);
400 }
401 
adb_get_feature_set(FeatureSet * feature_set,std::string * error)402 bool adb_get_feature_set(FeatureSet* feature_set, std::string* error) {
403     static FeatureSet* features = nullptr;
404     if (!features) {
405         std::string result;
406         if (adb_query(format_host_command("features"), &result, error)) {
407             features = new FeatureSet(StringToFeatureSet(result));
408         }
409     }
410     if (features) {
411         *feature_set = *features;
412         return true;
413     }
414     feature_set->clear();
415     return false;
416 }
417