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 <limits.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 
31 #include <string>
32 #include <thread>
33 #include <vector>
34 
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <cutils/sockets.h>
38 
39 #include "adb_io.h"
40 #include "adb_utils.h"
41 #include "socket_spec.h"
42 #include "sysdeps/chrono.h"
43 
44 static TransportType __adb_transport = kTransportAny;
45 static const char* __adb_serial = NULL;
46 
47 static const char* __adb_server_socket_spec;
48 
adb_set_transport(TransportType type,const char * serial)49 void adb_set_transport(TransportType type, const char* serial) {
50     __adb_transport = type;
51     __adb_serial = serial;
52 }
53 
adb_set_socket_spec(const char * socket_spec)54 void adb_set_socket_spec(const char* socket_spec) {
55     if (__adb_server_socket_spec) {
56         LOG(FATAL) << "attempted to reinitialize adb_server_socket_spec " << socket_spec << " (was " << __adb_server_socket_spec << ")";
57     }
58     __adb_server_socket_spec = socket_spec;
59 }
60 
switch_socket_transport(int fd,std::string * error)61 static int switch_socket_transport(int fd, std::string* error) {
62     std::string service;
63     if (__adb_serial) {
64         service += "host:transport:";
65         service += __adb_serial;
66     } else {
67         const char* transport_type = "???";
68         switch (__adb_transport) {
69           case kTransportUsb:
70             transport_type = "transport-usb";
71             break;
72           case kTransportLocal:
73             transport_type = "transport-local";
74             break;
75           case kTransportAny:
76             transport_type = "transport-any";
77             break;
78           case kTransportHost:
79             // no switch necessary
80             return 0;
81         }
82         service += "host:";
83         service += transport_type;
84     }
85 
86     if (!SendProtocolString(fd, service)) {
87         *error = perror_str("write failure during connection");
88         adb_close(fd);
89         return -1;
90     }
91     D("Switch transport in progress");
92 
93     if (!adb_status(fd, error)) {
94         adb_close(fd);
95         D("Switch transport failed: %s", error->c_str());
96         return -1;
97     }
98     D("Switch transport success");
99     return 0;
100 }
101 
adb_status(int fd,std::string * error)102 bool adb_status(int fd, std::string* error) {
103     char buf[5];
104     if (!ReadFdExactly(fd, buf, 4)) {
105         *error = perror_str("protocol fault (couldn't read status)");
106         return false;
107     }
108 
109     if (!memcmp(buf, "OKAY", 4)) {
110         return true;
111     }
112 
113     if (memcmp(buf, "FAIL", 4)) {
114         *error = android::base::StringPrintf("protocol fault (status %02x %02x %02x %02x?!)",
115                                              buf[0], buf[1], buf[2], buf[3]);
116         return false;
117     }
118 
119     ReadProtocolString(fd, error, error);
120     return false;
121 }
122 
_adb_connect(const std::string & service,std::string * error)123 int _adb_connect(const std::string& service, std::string* error) {
124     D("_adb_connect: %s", service.c_str());
125     if (service.empty() || service.size() > MAX_PAYLOAD_V1) {
126         *error = android::base::StringPrintf("bad service name length (%zd)",
127                                              service.size());
128         return -1;
129     }
130 
131     std::string reason;
132     int fd = socket_spec_connect(__adb_server_socket_spec, &reason);
133     if (fd < 0) {
134         *error = android::base::StringPrintf("cannot connect to daemon at %s: %s",
135                                              __adb_server_socket_spec, reason.c_str());
136         return -2;
137     }
138 
139     if ((memcmp(&service[0],"host",4) != 0 || service == "host:reconnect") &&
140         switch_socket_transport(fd, error)) {
141         return -1;
142     }
143 
144     if (!SendProtocolString(fd, service)) {
145         *error = perror_str("write failure during connection");
146         adb_close(fd);
147         return -1;
148     }
149 
150     if (service != "reconnect") {
151         if (!adb_status(fd, error)) {
152             adb_close(fd);
153             return -1;
154         }
155     }
156 
157     D("_adb_connect: return fd %d", fd);
158     return fd;
159 }
160 
adb_connect(const std::string & service,std::string * error)161 int adb_connect(const std::string& service, std::string* error) {
162     // first query the adb server's version
163     int fd = _adb_connect("host:version", error);
164 
165     D("adb_connect: service %s", service.c_str());
166     if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) {
167         fprintf(stderr,"** Cannot start server on remote host\n");
168         // error is the original network connection error
169         return fd;
170     } else if (fd == -2) {
171         fprintf(stdout, "* daemon not running. starting it now at %s *\n", __adb_server_socket_spec);
172     start_server:
173         if (launch_server(__adb_server_socket_spec)) {
174             fprintf(stderr,"* failed to start daemon *\n");
175             // launch_server() has already printed detailed error info, so just
176             // return a generic error string about the overall adb_connect()
177             // that the caller requested.
178             *error = "cannot connect to daemon";
179             return -1;
180         } else {
181             fprintf(stdout,"* daemon started successfully *\n");
182         }
183         // Give the server some time to start properly and detect devices.
184         std::this_thread::sleep_for(3s);
185         // fall through to _adb_connect
186     } else {
187         // If a server is already running, check its version matches.
188         int version = ADB_SERVER_VERSION - 1;
189 
190         // If we have a file descriptor, then parse version result.
191         if (fd >= 0) {
192             std::string version_string;
193             if (!ReadProtocolString(fd, &version_string, error)) {
194                 adb_close(fd);
195                 return -1;
196             }
197 
198             ReadOrderlyShutdown(fd);
199             adb_close(fd);
200 
201             if (sscanf(&version_string[0], "%04x", &version) != 1) {
202                 *error = android::base::StringPrintf("cannot parse version string: %s",
203                                                      version_string.c_str());
204                 return -1;
205             }
206         } else {
207             // If fd is -1 check for "unknown host service" which would
208             // indicate a version of adb that does not support the
209             // version command, in which case we should fall-through to kill it.
210             if (*error != "unknown host service") {
211                 return fd;
212             }
213         }
214 
215         if (version != ADB_SERVER_VERSION) {
216             printf("adb server version (%d) doesn't match this client (%d); killing...\n",
217                    version, ADB_SERVER_VERSION);
218             fd = _adb_connect("host:kill", error);
219             if (fd >= 0) {
220                 ReadOrderlyShutdown(fd);
221                 adb_close(fd);
222             } else {
223                 // If we couldn't connect to the server or had some other error,
224                 // report it, but still try to start the server.
225                 fprintf(stderr, "error: %s\n", error->c_str());
226             }
227 
228             /* XXX can we better detect its death? */
229             std::this_thread::sleep_for(2s);
230             goto start_server;
231         }
232     }
233 
234     // if the command is start-server, we are done.
235     if (service == "host:start-server") {
236         return 0;
237     }
238 
239     fd = _adb_connect(service, error);
240     if (fd == -1) {
241         D("_adb_connect error: %s", error->c_str());
242     } else if(fd == -2) {
243         fprintf(stderr,"** daemon still not running\n");
244     }
245     D("adb_connect: return fd %d", fd);
246 
247     return fd;
248 }
249 
250 
adb_command(const std::string & service)251 bool adb_command(const std::string& service) {
252     std::string error;
253     int fd = adb_connect(service, &error);
254     if (fd < 0) {
255         fprintf(stderr, "error: %s\n", error.c_str());
256         return false;
257     }
258 
259     if (!adb_status(fd, &error)) {
260         fprintf(stderr, "error: %s\n", error.c_str());
261         adb_close(fd);
262         return false;
263     }
264 
265     ReadOrderlyShutdown(fd);
266     adb_close(fd);
267     return true;
268 }
269 
adb_query(const std::string & service,std::string * result,std::string * error)270 bool adb_query(const std::string& service, std::string* result, std::string* error) {
271     D("adb_query: %s", service.c_str());
272     int fd = adb_connect(service, error);
273     if (fd < 0) {
274         return false;
275     }
276 
277     result->clear();
278     if (!ReadProtocolString(fd, result, error)) {
279         adb_close(fd);
280         return false;
281     }
282 
283     ReadOrderlyShutdown(fd);
284     adb_close(fd);
285     return true;
286 }
287 
format_host_command(const char * command,TransportType type,const char * serial)288 std::string format_host_command(const char* command, TransportType type, const char* serial) {
289     if (serial) {
290         return android::base::StringPrintf("host-serial:%s:%s", serial, command);
291     }
292 
293     const char* prefix = "host";
294     if (type == kTransportUsb) {
295         prefix = "host-usb";
296     } else if (type == kTransportLocal) {
297         prefix = "host-local";
298     }
299     return android::base::StringPrintf("%s:%s", prefix, command);
300 }
301 
adb_get_feature_set(FeatureSet * feature_set,std::string * error)302 bool adb_get_feature_set(FeatureSet* feature_set, std::string* error) {
303     std::string result;
304     if (adb_query(format_host_command("features", __adb_transport, __adb_serial), &result, error)) {
305         *feature_set = StringToFeatureSet(result);
306         return true;
307     }
308     feature_set->clear();
309     return false;
310 }
311