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