• 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 <thread>
28 
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31 #include <cutils/sockets.h>
32 
33 #include "adb.h"
34 #include "adb_io.h"
35 #include "adb_unique_fd.h"
36 #include "adb_utils.h"
37 #include "services.h"
38 #include "socket_spec.h"
39 #include "sysdeps.h"
40 #include "transport.h"
41 
42 namespace {
43 
service_bootstrap_func(std::string service_name,std::function<void (unique_fd)> func,unique_fd fd)44 void service_bootstrap_func(std::string service_name, std::function<void(unique_fd)> func,
45                             unique_fd fd) {
46     adb_thread_setname(android::base::StringPrintf("%s svc %d", service_name.c_str(), fd.get()));
47     func(std::move(fd));
48 }
49 
50 }  // namespace
51 
create_service_thread(const char * service_name,std::function<void (unique_fd)> func)52 unique_fd create_service_thread(const char* service_name, std::function<void(unique_fd)> func) {
53     int s[2];
54     if (adb_socketpair(s)) {
55         printf("cannot create service socket pair\n");
56         return unique_fd();
57     }
58     D("socketpair: (%d,%d)", s[0], s[1]);
59 
60 #if !ADB_HOST
61     if (strcmp(service_name, "sync") == 0) {
62         // Set file sync service socket to maximum size
63         int max_buf = LINUX_MAX_SOCKET_SIZE;
64         adb_setsockopt(s[0], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
65         adb_setsockopt(s[1], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
66     }
67 #endif  // !ADB_HOST
68 
69     std::thread(service_bootstrap_func, service_name, func, unique_fd(s[1])).detach();
70 
71     D("service thread started, %d:%d", s[0], s[1]);
72     return unique_fd(s[0]);
73 }
74 
service_to_fd(std::string_view name,atransport * transport)75 unique_fd service_to_fd(std::string_view name, atransport* transport) {
76     unique_fd ret;
77 
78     if (is_socket_spec(name)) {
79         std::string error;
80         if (!socket_spec_connect(&ret, name, nullptr, nullptr, &error)) {
81             LOG(ERROR) << "failed to connect to socket '" << name << "': " << error;
82         }
83     } else {
84 #if !ADB_HOST
85         ret = daemon_service_to_fd(name, transport);
86 #endif
87     }
88 
89     if (ret >= 0) {
90         close_on_exec(ret.get());
91     }
92     return ret;
93 }
94 
95 #if ADB_HOST
96 struct state_info {
97     TransportType transport_type;
98     std::string serial;
99     TransportId transport_id;
100     ConnectionState state;
101 };
102 
wait_for_state(int fd,state_info * sinfo)103 static void wait_for_state(int fd, state_info* sinfo) {
104     D("wait_for_state %d", sinfo->state);
105 
106     while (true) {
107         bool is_ambiguous = false;
108         std::string error = "unknown error";
109         const char* serial = sinfo->serial.length() ? sinfo->serial.c_str() : nullptr;
110         atransport* t = acquire_one_transport(sinfo->transport_type, serial, sinfo->transport_id,
111                                               &is_ambiguous, &error);
112         if (sinfo->state == kCsOffline) {
113             // wait-for-disconnect uses kCsOffline, we don't actually want to wait for 'offline'.
114             if (t == nullptr) {
115                 SendOkay(fd);
116                 break;
117             }
118         } else if (t != nullptr &&
119                    (sinfo->state == kCsAny || sinfo->state == t->GetConnectionState())) {
120             SendOkay(fd);
121             break;
122         }
123 
124         if (!is_ambiguous) {
125             adb_pollfd pfd = {.fd = fd, .events = POLLIN};
126             int rc = adb_poll(&pfd, 1, 100);
127             if (rc < 0) {
128                 SendFail(fd, error);
129                 break;
130             } else if (rc > 0 && (pfd.revents & POLLHUP) != 0) {
131                 // The other end of the socket is closed, probably because the other side was
132                 // terminated, bail out.
133                 break;
134             }
135 
136             // Try again...
137         } else {
138             SendFail(fd, error);
139             break;
140         }
141     }
142 
143     adb_close(fd);
144     D("wait_for_state is done");
145 }
146 
connect_emulator(const std::string & port_spec,std::string * response)147 void connect_emulator(const std::string& port_spec, std::string* response) {
148     std::vector<std::string> pieces = android::base::Split(port_spec, ",");
149     if (pieces.size() != 2) {
150         *response = android::base::StringPrintf("unable to parse '%s' as <console port>,<adb port>",
151                                                 port_spec.c_str());
152         return;
153     }
154 
155     int console_port = strtol(pieces[0].c_str(), nullptr, 0);
156     int adb_port = strtol(pieces[1].c_str(), nullptr, 0);
157     if (console_port <= 0 || adb_port <= 0) {
158         *response = android::base::StringPrintf("Invalid port numbers: %s", port_spec.c_str());
159         return;
160     }
161 
162     // Check if the emulator is already known.
163     // Note: There's a small but harmless race condition here: An emulator not
164     // present just yet could be registered by another invocation right
165     // after doing this check here. However, local_connect protects
166     // against double-registration too. From here, a better error message
167     // can be produced. In the case of the race condition, the very specific
168     // error message won't be shown, but the data doesn't get corrupted.
169     atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
170     if (known_emulator != nullptr) {
171         *response = android::base::StringPrintf("Emulator already registered on port %d", adb_port);
172         return;
173     }
174 
175     // Preconditions met, try to connect to the emulator.
176     std::string error;
177     if (!local_connect_arbitrary_ports(console_port, adb_port, &error)) {
178         *response = android::base::StringPrintf("Connected to emulator on ports %d,%d",
179                                                 console_port, adb_port);
180     } else {
181         *response = android::base::StringPrintf("Could not connect to emulator on ports %d,%d: %s",
182                                                 console_port, adb_port, error.c_str());
183     }
184 }
185 
connect_service(unique_fd fd,std::string host)186 static void connect_service(unique_fd fd, std::string host) {
187     std::string response;
188     if (!strncmp(host.c_str(), "emu:", 4)) {
189         connect_emulator(host.c_str() + 4, &response);
190     } else {
191         connect_device(host, &response);
192     }
193 
194     // Send response for emulator and device
195     SendProtocolString(fd.get(), response);
196 }
197 #endif
198 
199 #if ADB_HOST
host_service_to_socket(std::string_view name,std::string_view serial,TransportId transport_id)200 asocket* host_service_to_socket(std::string_view name, std::string_view serial,
201                                 TransportId transport_id) {
202     if (name == "track-devices") {
203         return create_device_tracker(false);
204     } else if (name == "track-devices-l") {
205         return create_device_tracker(true);
206     } else if (ConsumePrefix(&name, "wait-for-")) {
207         std::shared_ptr<state_info> sinfo = std::make_shared<state_info>();
208         if (sinfo == nullptr) {
209             fprintf(stderr, "couldn't allocate state_info: %s", strerror(errno));
210             return nullptr;
211         }
212 
213         sinfo->serial = serial;
214         sinfo->transport_id = transport_id;
215 
216         if (ConsumePrefix(&name, "local")) {
217             sinfo->transport_type = kTransportLocal;
218         } else if (ConsumePrefix(&name, "usb")) {
219             sinfo->transport_type = kTransportUsb;
220         } else if (ConsumePrefix(&name, "any")) {
221             sinfo->transport_type = kTransportAny;
222         } else {
223             return nullptr;
224         }
225 
226         if (name == "-device") {
227             sinfo->state = kCsDevice;
228         } else if (name == "-recovery") {
229             sinfo->state = kCsRecovery;
230         } else if (name == "-rescue") {
231             sinfo->state = kCsRescue;
232         } else if (name == "-sideload") {
233             sinfo->state = kCsSideload;
234         } else if (name == "-bootloader") {
235             sinfo->state = kCsBootloader;
236         } else if (name == "-any") {
237             sinfo->state = kCsAny;
238         } else if (name == "-disconnect") {
239             sinfo->state = kCsOffline;
240         } else {
241             return nullptr;
242         }
243 
244         unique_fd fd = create_service_thread("wait", [sinfo](int fd) {
245             wait_for_state(fd, sinfo.get());
246         });
247         return create_local_socket(std::move(fd));
248     } else if (ConsumePrefix(&name, "connect:")) {
249         std::string host(name);
250         unique_fd fd = create_service_thread(
251                 "connect", std::bind(connect_service, std::placeholders::_1, host));
252         return create_local_socket(std::move(fd));
253     }
254     return nullptr;
255 }
256 #endif /* ADB_HOST */
257