1 /*
2  * Copyright (C) 2007 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 SERVICES
18 
19 #include "sysdeps.h"
20 
21 #include <errno.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #include <cstring>
28 #include <thread>
29 
30 #include <android-base/stringprintf.h>
31 #include <android-base/strings.h>
32 #include <cutils/sockets.h>
33 
34 #include "adb.h"
35 #include "adb_io.h"
36 #include "adb_unique_fd.h"
37 #include "adb_utils.h"
38 #include "adb_wifi.h"
39 #include "services.h"
40 #include "socket_spec.h"
41 #include "sysdeps.h"
42 #include "transport.h"
43 
44 namespace {
45 
service_bootstrap_func(std::string service_name,std::function<void (unique_fd)> func,unique_fd fd)46 void service_bootstrap_func(std::string service_name, std::function<void(unique_fd)> func,
47                             unique_fd fd) {
48     adb_thread_setname(android::base::StringPrintf("%s svc %d", service_name.c_str(), fd.get()));
49     func(std::move(fd));
50 }
51 
52 }  // namespace
53 
create_service_thread(const char * service_name,std::function<void (unique_fd)> func)54 unique_fd create_service_thread(const char* service_name, std::function<void(unique_fd)> func) {
55     int s[2];
56     if (adb_socketpair(s)) {
57         printf("cannot create service socket pair\n");
58         return unique_fd();
59     }
60     D("socketpair: (%d,%d)", s[0], s[1]);
61 
62 #if !ADB_HOST
63     if (strcmp(service_name, "sync") == 0) {
64         // Set file sync service socket to maximum size
65         int max_buf = LINUX_MAX_SOCKET_SIZE;
66         adb_setsockopt(s[0], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
67         adb_setsockopt(s[1], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
68     }
69 #endif  // !ADB_HOST
70 
71     std::thread(service_bootstrap_func, service_name, func, unique_fd(s[1])).detach();
72 
73     D("service thread started, %d:%d", s[0], s[1]);
74     return unique_fd(s[0]);
75 }
76 
service_to_fd(std::string_view name,atransport * transport)77 unique_fd service_to_fd(std::string_view name, atransport* transport) {
78     unique_fd ret;
79 
80     if (is_socket_spec(name)) {
81         std::string error;
82         if (!socket_spec_connect(&ret, name, nullptr, nullptr, &error)) {
83             LOG(ERROR) << "failed to connect to socket '" << name << "': " << error;
84         }
85     } else {
86 #if !ADB_HOST
87         ret = daemon_service_to_fd(name, transport);
88 #endif
89     }
90 
91     if (ret >= 0) {
92         close_on_exec(ret.get());
93     }
94     return ret;
95 }
96 
97 #if ADB_HOST
connect_emulator(const std::string & port_spec,std::string * response)98 void connect_emulator(const std::string& port_spec, std::string* response) {
99     std::vector<std::string> pieces = android::base::Split(port_spec, ",");
100     if (pieces.size() != 2) {
101         *response = android::base::StringPrintf("unable to parse '%s' as <console port>,<adb port>",
102                                                 port_spec.c_str());
103         return;
104     }
105 
106     int console_port = strtol(pieces[0].c_str(), nullptr, 0);
107     int adb_port = strtol(pieces[1].c_str(), nullptr, 0);
108     if (console_port <= 0 || adb_port <= 0) {
109         *response = android::base::StringPrintf("Invalid port numbers: %s", port_spec.c_str());
110         return;
111     }
112 
113     // Check if the emulator is already known.
114     // Note: There's a small but harmless race condition here: An emulator not
115     // present just yet could be registered by another invocation right
116     // after doing this check here. However, local_connect protects
117     // against double-registration too. From here, a better error message
118     // can be produced. In the case of the race condition, the very specific
119     // error message won't be shown, but the data doesn't get corrupted.
120     atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
121     if (known_emulator != nullptr) {
122         *response = android::base::StringPrintf("Emulator already registered on port %d", adb_port);
123         return;
124     }
125 
126     // Preconditions met, try to connect to the emulator.
127     std::string error;
128     if (!local_connect_arbitrary_ports(console_port, adb_port, &error)) {
129         *response = android::base::StringPrintf("Connected to emulator on ports %d,%d",
130                                                 console_port, adb_port);
131     } else {
132         *response = android::base::StringPrintf("Could not connect to emulator on ports %d,%d: %s",
133                                                 console_port, adb_port, error.c_str());
134     }
135 }
136 
connect_service(unique_fd fd,std::string host)137 static void connect_service(unique_fd fd, std::string host) {
138     std::string response;
139     if (!strncmp(host.c_str(), "emu:", 4)) {
140         connect_emulator(host.c_str() + 4, &response);
141     } else {
142         connect_device(host, &response);
143     }
144 
145     // Send response for emulator and device
146     SendProtocolString(fd.get(), response);
147 }
148 
pair_service(unique_fd fd,std::string host,std::string password)149 static void pair_service(unique_fd fd, std::string host, std::string password) {
150     std::string response;
151     adb_wifi_pair_device(host, password, response);
152     if (android::base::StartsWith(response, "Successful")) {
153         SendProtocolString(fd.get(), response);
154     } else {
155         SendFail(fd, response);
156     }
157 }
158 
wait_service(unique_fd fd,std::string serial,TransportId transport_id,std::string spec)159 static void wait_service(unique_fd fd, std::string serial, TransportId transport_id,
160                          std::string spec) {
161     std::vector<std::string> components = android::base::Split(spec, "-");
162     if (components.size() < 2) {
163         SendFail(fd, "short wait-for-: " + spec);
164         return;
165     }
166 
167     TransportType transport_type;
168     if (components[0] == "local") {
169         transport_type = kTransportLocal;
170     } else if (components[0] == "usb") {
171         transport_type = kTransportUsb;
172     } else if (components[0] == "any") {
173         transport_type = kTransportAny;
174     } else {
175         SendFail(fd, "bad wait-for- transport: " + spec);
176         return;
177     }
178 
179     std::vector<ConnectionState> states;
180     for (size_t i = 1; i < components.size(); ++i) {
181         if (components[i] == "device") {
182             states.push_back(kCsDevice);
183         } else if (components[i] == "recovery") {
184             states.push_back(kCsRecovery);
185         } else if (components[i] == "rescue") {
186             states.push_back(kCsRescue);
187         } else if (components[i] == "sideload") {
188             states.push_back(kCsSideload);
189         } else if (components[i] == "bootloader") {
190             states.push_back(kCsBootloader);
191         } else if (components[i] == "any") {
192             states.push_back(kCsAny);
193         } else if (components[i] == "disconnect") {
194             states.push_back(kCsOffline);
195         } else {
196             SendFail(fd, "bad wait-for- state: " + spec);
197             return;
198         }
199     }
200 
201     while (true) {
202         bool is_ambiguous = false;
203         std::string error = "unknown error";
204         atransport* t =
205                 acquire_one_transport(transport_type, !serial.empty() ? serial.c_str() : nullptr,
206                                       transport_id, &is_ambiguous, &error);
207 
208         // If the target transport disconnect (to wait-for) is unclear, punt
209         // to the user for corrective action (e.g. specify `adb -s <>
210         // wait-for-disconnect`).
211         if (is_ambiguous) {
212             SendFail(fd, error);
213             return;
214         }
215         for (const auto& state : states) {
216             if (state == kCsOffline) {
217                 // Special case for wait-for-disconnect:
218                 // We want to wait for USB devices to completely disappear, but
219                 // TCP devices can go into the offline state, since we
220                 // automatically reconnect (disabling WiFi or disconnecting
221                 // from the WiFi connection would trigger transition from
222                 // `device` to `offline`).
223                 // If the transport is torn down (regardless of whether it is
224                 // USB or wireless), unblock.
225                 if (!t) {
226                     SendOkay(fd);
227                     return;
228                 }
229             } else {
230                 if (t && (state == kCsAny || state == t->GetConnectionState())) {
231                     SendOkay(fd);
232                     return;
233                 }
234             }
235         }
236 
237         // Sleep before retrying.
238         adb_pollfd pfd = {.fd = fd.get(), .events = POLLIN};
239         if (adb_poll(&pfd, 1, 100) != 0) {
240             // The other end of the socket is closed, probably because the
241             // client terminated. Bail out.
242             SendFail(fd, error);
243             return;
244         }
245     }
246 }
247 #endif
248 
249 #if ADB_HOST
host_service_to_socket(std::string_view name,std::string_view serial,TransportId transport_id)250 asocket* host_service_to_socket(std::string_view name, std::string_view serial,
251                                 TransportId transport_id) {
252     if (name == "track-devices") {
253         return create_device_tracker(SHORT_TEXT);
254     } else if (name == "track-devices-l") {
255         return create_device_tracker(LONG_TEXT);
256     } else if (name == "track-devices-proto-binary") {
257         return create_device_tracker(PROTOBUF);
258     } else if (name == "track-devices-proto-text") {
259         return create_device_tracker(TEXT_PROTOBUF);
260     } else if (android::base::ConsumePrefix(&name, "wait-for-")) {
261         std::string spec(name);
262         unique_fd fd =
263                 create_service_thread("wait", std::bind(wait_service, std::placeholders::_1,
264                                                         std::string(serial), transport_id, spec));
265         return create_local_socket(std::move(fd));
266     } else if (android::base::ConsumePrefix(&name, "connect:")) {
267         std::string host(name);
268         unique_fd fd = create_service_thread(
269                 "connect", std::bind(connect_service, std::placeholders::_1, host));
270         return create_local_socket(std::move(fd));
271     } else if (android::base::ConsumePrefix(&name, "pair:")) {
272         const char* divider = strchr(name.data(), ':');
273         if (!divider) {
274             return nullptr;
275         }
276         std::string password(name.data(), divider);
277         std::string host(divider + 1);
278         unique_fd fd = create_service_thread(
279                 "pair", std::bind(pair_service, std::placeholders::_1, host, password));
280         return create_local_socket(std::move(fd));
281     }
282     return nullptr;
283 }
284 #endif /* ADB_HOST */
285