• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
98 struct state_info {
99     TransportType transport_type;
100     std::string serial;
101     TransportId transport_id;
102     ConnectionState state;
103 };
104 
wait_for_state(unique_fd fd,state_info * sinfo)105 static void wait_for_state(unique_fd fd, state_info* sinfo) {
106     D("wait_for_state %d", sinfo->state);
107 
108     while (true) {
109         bool is_ambiguous = false;
110         std::string error = "unknown error";
111         const char* serial = sinfo->serial.length() ? sinfo->serial.c_str() : nullptr;
112         atransport* t = acquire_one_transport(sinfo->transport_type, serial, sinfo->transport_id,
113                                               &is_ambiguous, &error);
114         if (sinfo->state == kCsOffline) {
115             // wait-for-disconnect uses kCsOffline, we don't actually want to wait for 'offline'.
116             if (t == nullptr) {
117                 SendOkay(fd);
118                 break;
119             }
120         } else if (t != nullptr &&
121                    (sinfo->state == kCsAny || sinfo->state == t->GetConnectionState())) {
122             SendOkay(fd);
123             break;
124         }
125 
126         if (!is_ambiguous) {
127             adb_pollfd pfd = {.fd = fd.get(), .events = POLLIN};
128             int rc = adb_poll(&pfd, 1, 100);
129             if (rc < 0) {
130                 SendFail(fd, error);
131                 break;
132             } else if (rc > 0 && (pfd.revents & POLLHUP) != 0) {
133                 // The other end of the socket is closed, probably because the other side was
134                 // terminated, bail out.
135                 break;
136             }
137 
138             // Try again...
139         } else {
140             SendFail(fd, error);
141             break;
142         }
143     }
144 
145     D("wait_for_state is done");
146 }
147 
connect_emulator(const std::string & port_spec,std::string * response)148 void connect_emulator(const std::string& port_spec, std::string* response) {
149     std::vector<std::string> pieces = android::base::Split(port_spec, ",");
150     if (pieces.size() != 2) {
151         *response = android::base::StringPrintf("unable to parse '%s' as <console port>,<adb port>",
152                                                 port_spec.c_str());
153         return;
154     }
155 
156     int console_port = strtol(pieces[0].c_str(), nullptr, 0);
157     int adb_port = strtol(pieces[1].c_str(), nullptr, 0);
158     if (console_port <= 0 || adb_port <= 0) {
159         *response = android::base::StringPrintf("Invalid port numbers: %s", port_spec.c_str());
160         return;
161     }
162 
163     // Check if the emulator is already known.
164     // Note: There's a small but harmless race condition here: An emulator not
165     // present just yet could be registered by another invocation right
166     // after doing this check here. However, local_connect protects
167     // against double-registration too. From here, a better error message
168     // can be produced. In the case of the race condition, the very specific
169     // error message won't be shown, but the data doesn't get corrupted.
170     atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
171     if (known_emulator != nullptr) {
172         *response = android::base::StringPrintf("Emulator already registered on port %d", adb_port);
173         return;
174     }
175 
176     // Preconditions met, try to connect to the emulator.
177     std::string error;
178     if (!local_connect_arbitrary_ports(console_port, adb_port, &error)) {
179         *response = android::base::StringPrintf("Connected to emulator on ports %d,%d",
180                                                 console_port, adb_port);
181     } else {
182         *response = android::base::StringPrintf("Could not connect to emulator on ports %d,%d: %s",
183                                                 console_port, adb_port, error.c_str());
184     }
185 }
186 
connect_service(unique_fd fd,std::string host)187 static void connect_service(unique_fd fd, std::string host) {
188     std::string response;
189     if (!strncmp(host.c_str(), "emu:", 4)) {
190         connect_emulator(host.c_str() + 4, &response);
191     } else {
192         connect_device(host, &response);
193     }
194 
195     // Send response for emulator and device
196     SendProtocolString(fd.get(), response);
197 }
198 
pair_service(unique_fd fd,std::string host,std::string password)199 static void pair_service(unique_fd fd, std::string host, std::string password) {
200     std::string response;
201     adb_wifi_pair_device(host, password, response);
202     SendProtocolString(fd.get(), response);
203 }
204 #endif
205 
206 #if ADB_HOST
host_service_to_socket(std::string_view name,std::string_view serial,TransportId transport_id)207 asocket* host_service_to_socket(std::string_view name, std::string_view serial,
208                                 TransportId transport_id) {
209     if (name == "track-devices") {
210         return create_device_tracker(false);
211     } else if (name == "track-devices-l") {
212         return create_device_tracker(true);
213     } else if (android::base::ConsumePrefix(&name, "wait-for-")) {
214         std::shared_ptr<state_info> sinfo = std::make_shared<state_info>();
215         if (sinfo == nullptr) {
216             fprintf(stderr, "couldn't allocate state_info: %s", strerror(errno));
217             return nullptr;
218         }
219 
220         sinfo->serial = serial;
221         sinfo->transport_id = transport_id;
222 
223         if (android::base::ConsumePrefix(&name, "local")) {
224             sinfo->transport_type = kTransportLocal;
225         } else if (android::base::ConsumePrefix(&name, "usb")) {
226             sinfo->transport_type = kTransportUsb;
227         } else if (android::base::ConsumePrefix(&name, "any")) {
228             sinfo->transport_type = kTransportAny;
229         } else {
230             return nullptr;
231         }
232 
233         if (name == "-device") {
234             sinfo->state = kCsDevice;
235         } else if (name == "-recovery") {
236             sinfo->state = kCsRecovery;
237         } else if (name == "-rescue") {
238             sinfo->state = kCsRescue;
239         } else if (name == "-sideload") {
240             sinfo->state = kCsSideload;
241         } else if (name == "-bootloader") {
242             sinfo->state = kCsBootloader;
243         } else if (name == "-any") {
244             sinfo->state = kCsAny;
245         } else if (name == "-disconnect") {
246             sinfo->state = kCsOffline;
247         } else {
248             return nullptr;
249         }
250 
251         unique_fd fd = create_service_thread(
252                 "wait", [sinfo](unique_fd fd) { wait_for_state(std::move(fd), sinfo.get()); });
253         return create_local_socket(std::move(fd));
254     } else if (android::base::ConsumePrefix(&name, "connect:")) {
255         std::string host(name);
256         unique_fd fd = create_service_thread(
257                 "connect", std::bind(connect_service, std::placeholders::_1, host));
258         return create_local_socket(std::move(fd));
259     } else if (android::base::ConsumePrefix(&name, "pair:")) {
260         const char* divider = strchr(name.data(), ':');
261         if (!divider) {
262             return nullptr;
263         }
264         std::string password(name.data(), divider);
265         std::string host(divider + 1);
266         unique_fd fd = create_service_thread(
267                 "pair", std::bind(pair_service, std::placeholders::_1, host, password));
268         return create_local_socket(std::move(fd));
269     }
270     return nullptr;
271 }
272 #endif /* ADB_HOST */
273