• 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 SOCKETS
18 
19 #include "sysdeps.h"
20 
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 
28 #include <algorithm>
29 #include <chrono>
30 #include <mutex>
31 #include <string>
32 #include <vector>
33 
34 #if !ADB_HOST
35 #include <android-base/properties.h>
36 #include <log/log_properties.h>
37 #endif
38 
39 #include "adb.h"
40 #include "adb_io.h"
41 #include "adb_utils.h"
42 #include "transport.h"
43 #include "types.h"
44 
45 using namespace std::chrono_literals;
46 
47 static std::recursive_mutex& local_socket_list_lock = *new std::recursive_mutex();
48 static unsigned local_socket_next_id = 1;
49 
50 static auto& local_socket_list = *new std::vector<asocket*>();
51 
52 /* the the list of currently closing local sockets.
53 ** these have no peer anymore, but still packets to
54 ** write to their fd.
55 */
56 static auto& local_socket_closing_list = *new std::vector<asocket*>();
57 
58 // Parse the global list of sockets to find one with id |local_id|.
59 // If |peer_id| is not 0, also check that it is connected to a peer
60 // with id |peer_id|. Returns an asocket handle on success, NULL on failure.
find_local_socket(unsigned local_id,unsigned peer_id)61 asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
62     asocket* result = nullptr;
63 
64     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
65     for (asocket* s : local_socket_list) {
66         if (s->id != local_id) {
67             continue;
68         }
69         if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
70             result = s;
71         }
72         break;
73     }
74 
75     return result;
76 }
77 
install_local_socket(asocket * s)78 void install_local_socket(asocket* s) {
79     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
80 
81     s->id = local_socket_next_id++;
82 
83     // Socket ids should never be 0.
84     if (local_socket_next_id == 0) {
85         LOG(FATAL) << "local socket id overflow";
86     }
87 
88     local_socket_list.push_back(s);
89 }
90 
remove_socket(asocket * s)91 void remove_socket(asocket* s) {
92     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
93     for (auto list : { &local_socket_list, &local_socket_closing_list }) {
94         list->erase(std::remove_if(list->begin(), list->end(), [s](asocket* x) { return x == s; }),
95                     list->end());
96     }
97 }
98 
close_all_sockets(atransport * t)99 void close_all_sockets(atransport* t) {
100     /* this is a little gross, but since s->close() *will* modify
101     ** the list out from under you, your options are limited.
102     */
103     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
104 restart:
105     for (asocket* s : local_socket_list) {
106         if (s->transport == t || (s->peer && s->peer->transport == t)) {
107             s->close(s);
108             goto restart;
109         }
110     }
111 }
112 
113 enum class SocketFlushResult {
114     Destroyed,
115     TryAgain,
116     Completed,
117 };
118 
local_socket_flush_incoming(asocket * s)119 static SocketFlushResult local_socket_flush_incoming(asocket* s) {
120     if (!s->packet_queue.empty()) {
121         std::vector<adb_iovec> iov = s->packet_queue.iovecs();
122         ssize_t rc = adb_writev(s->fd, iov.data(), iov.size());
123         if (rc > 0 && static_cast<size_t>(rc) == s->packet_queue.size()) {
124             s->packet_queue.clear();
125         } else if (rc > 0) {
126             // TODO: Implement a faster drop_front?
127             s->packet_queue.take_front(rc);
128             fdevent_add(s->fde, FDE_WRITE);
129             return SocketFlushResult::TryAgain;
130         } else if (rc == -1 && errno == EAGAIN) {
131             fdevent_add(s->fde, FDE_WRITE);
132             return SocketFlushResult::TryAgain;
133         } else {
134             // We failed to write, but it's possible that we can still read from the socket.
135             // Give that a try before giving up.
136             s->has_write_error = true;
137         }
138     }
139 
140     // If we sent the last packet of a closing socket, we can now destroy it.
141     if (s->closing) {
142         s->close(s);
143         return SocketFlushResult::Destroyed;
144     }
145 
146     fdevent_del(s->fde, FDE_WRITE);
147     return SocketFlushResult::Completed;
148 }
149 
150 // Returns false if the socket has been closed and destroyed as a side-effect of this function.
local_socket_flush_outgoing(asocket * s)151 static bool local_socket_flush_outgoing(asocket* s) {
152     const size_t max_payload = s->get_max_payload();
153     apacket::payload_type data;
154     data.resize(max_payload);
155     char* x = &data[0];
156     size_t avail = max_payload;
157     int r = 0;
158     int is_eof = 0;
159 
160     while (avail > 0) {
161         r = adb_read(s->fd, x, avail);
162         D("LS(%d): post adb_read(fd=%d,...) r=%d (errno=%d) avail=%zu", s->id, s->fd, r,
163           r < 0 ? errno : 0, avail);
164         if (r == -1) {
165             if (errno == EAGAIN) {
166                 break;
167             }
168         } else if (r > 0) {
169             avail -= r;
170             x += r;
171             continue;
172         }
173 
174         /* r = 0 or unhandled error */
175         is_eof = 1;
176         break;
177     }
178     D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d", s->id, s->fd, r, is_eof,
179       s->fde->force_eof);
180 
181     if (avail != max_payload && s->peer) {
182         data.resize(max_payload - avail);
183 
184         // s->peer->enqueue() may call s->close() and free s,
185         // so save variables for debug printing below.
186         unsigned saved_id = s->id;
187         int saved_fd = s->fd;
188         r = s->peer->enqueue(s->peer, std::move(data));
189         D("LS(%u): fd=%d post peer->enqueue(). r=%d", saved_id, saved_fd, r);
190 
191         if (r < 0) {
192             // Error return means they closed us as a side-effect and we must
193             // return immediately.
194             //
195             // Note that if we still have buffered packets, the socket will be
196             // placed on the closing socket list. This handler function will be
197             // called again to process FDE_WRITE events.
198             return false;
199         }
200 
201         if (r > 0) {
202             /* if the remote cannot accept further events,
203             ** we disable notification of READs.  They'll
204             ** be enabled again when we get a call to ready()
205             */
206             fdevent_del(s->fde, FDE_READ);
207         }
208     }
209 
210     // Don't allow a forced eof if data is still there.
211     if ((s->fde->force_eof && !r) || is_eof) {
212         D(" closing because is_eof=%d r=%d s->fde.force_eof=%d", is_eof, r, s->fde->force_eof);
213         s->close(s);
214         return false;
215     }
216 
217     return true;
218 }
219 
local_socket_enqueue(asocket * s,apacket::payload_type data)220 static int local_socket_enqueue(asocket* s, apacket::payload_type data) {
221     D("LS(%d): enqueue %zu", s->id, data.size());
222 
223     s->packet_queue.append(std::move(data));
224     switch (local_socket_flush_incoming(s)) {
225         case SocketFlushResult::Destroyed:
226             return -1;
227 
228         case SocketFlushResult::TryAgain:
229             return 1;
230 
231         case SocketFlushResult::Completed:
232             return 0;
233     }
234 
235     return !s->packet_queue.empty();
236 }
237 
local_socket_ready(asocket * s)238 static void local_socket_ready(asocket* s) {
239     /* far side is ready for data, pay attention to
240        readable events */
241     fdevent_add(s->fde, FDE_READ);
242 }
243 
244 struct ClosingSocket {
245     std::chrono::steady_clock::time_point begin;
246 };
247 
248 // The standard (RFC 1122 - 4.2.2.13) says that if we call close on a
249 // socket while we have pending data, a TCP RST should be sent to the
250 // other end to notify it that we didn't read all of its data. However,
251 // this can result in data that we've successfully written out to be dropped
252 // on the other end. To avoid this, instead of immediately closing a
253 // socket, call shutdown on it instead, and then read from the file
254 // descriptor until we hit EOF or an error before closing.
deferred_close(unique_fd fd)255 static void deferred_close(unique_fd fd) {
256     // Shutdown the socket in the outgoing direction only, so that
257     // we don't have the same problem on the opposite end.
258     adb_shutdown(fd.get(), SHUT_WR);
259     auto callback = [](fdevent* fde, unsigned event, void* arg) {
260         auto socket_info = static_cast<ClosingSocket*>(arg);
261         if (event & FDE_READ) {
262             ssize_t rc;
263             char buf[BUFSIZ];
264             while ((rc = adb_read(fde->fd.get(), buf, sizeof(buf))) > 0) {
265                 continue;
266             }
267 
268             if (rc == -1 && errno == EAGAIN) {
269                 // There's potentially more data to read.
270                 auto duration = std::chrono::steady_clock::now() - socket_info->begin;
271                 if (duration > 1s) {
272                     LOG(WARNING) << "timeout expired while flushing socket, closing";
273                 } else {
274                     return;
275                 }
276             }
277         } else if (event & FDE_TIMEOUT) {
278             LOG(WARNING) << "timeout expired while flushing socket, closing";
279         }
280 
281         // Either there was an error, we hit the end of the socket, or our timeout expired.
282         fdevent_destroy(fde);
283         delete socket_info;
284     };
285 
286     ClosingSocket* socket_info = new ClosingSocket{
287             .begin = std::chrono::steady_clock::now(),
288     };
289 
290     fdevent* fde = fdevent_create(fd.release(), callback, socket_info);
291     fdevent_add(fde, FDE_READ);
292     fdevent_set_timeout(fde, 1s);
293 }
294 
295 // be sure to hold the socket list lock when calling this
local_socket_destroy(asocket * s)296 static void local_socket_destroy(asocket* s) {
297     int exit_on_close = s->exit_on_close;
298 
299     D("LS(%d): destroying fde.fd=%d", s->id, s->fd);
300 
301     deferred_close(fdevent_release(s->fde));
302 
303     remove_socket(s);
304     delete s;
305 
306     if (exit_on_close) {
307         D("local_socket_destroy: exiting");
308         exit(1);
309     }
310 }
311 
local_socket_close(asocket * s)312 static void local_socket_close(asocket* s) {
313     D("entered local_socket_close. LS(%d) fd=%d", s->id, s->fd);
314     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
315     if (s->peer) {
316         D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
317         /* Note: it's important to call shutdown before disconnecting from
318          * the peer, this ensures that remote sockets can still get the id
319          * of the local socket they're connected to, to send a CLOSE()
320          * protocol event. */
321         if (s->peer->shutdown) {
322             s->peer->shutdown(s->peer);
323         }
324         s->peer->peer = nullptr;
325         s->peer->close(s->peer);
326         s->peer = nullptr;
327     }
328 
329     /* If we are already closing, or if there are no
330     ** pending packets, destroy immediately
331     */
332     if (s->closing || s->has_write_error || s->packet_queue.empty()) {
333         int id = s->id;
334         local_socket_destroy(s);
335         D("LS(%d): closed", id);
336         return;
337     }
338 
339     /* otherwise, put on the closing list
340     */
341     D("LS(%d): closing", s->id);
342     s->closing = 1;
343     fdevent_del(s->fde, FDE_READ);
344     remove_socket(s);
345     D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd);
346     local_socket_closing_list.push_back(s);
347     CHECK_EQ(FDE_WRITE, s->fde->state & FDE_WRITE);
348 }
349 
local_socket_event_func(int fd,unsigned ev,void * _s)350 static void local_socket_event_func(int fd, unsigned ev, void* _s) {
351     asocket* s = reinterpret_cast<asocket*>(_s);
352     D("LS(%d): event_func(fd=%d(==%d), ev=%04x)", s->id, s->fd, fd, ev);
353 
354     /* put the FDE_WRITE processing before the FDE_READ
355     ** in order to simplify the code.
356     */
357     if (ev & FDE_WRITE) {
358         switch (local_socket_flush_incoming(s)) {
359             case SocketFlushResult::Destroyed:
360                 return;
361 
362             case SocketFlushResult::TryAgain:
363                 break;
364 
365             case SocketFlushResult::Completed:
366                 s->peer->ready(s->peer);
367                 break;
368         }
369     }
370 
371     if (ev & FDE_READ) {
372         if (!local_socket_flush_outgoing(s)) {
373             return;
374         }
375     }
376 
377     if (ev & FDE_ERROR) {
378         /* this should be caught be the next read or write
379         ** catching it here means we may skip the last few
380         ** bytes of readable data.
381         */
382         D("LS(%d): FDE_ERROR (fd=%d)", s->id, s->fd);
383         return;
384     }
385 }
386 
create_local_socket(unique_fd ufd)387 asocket* create_local_socket(unique_fd ufd) {
388     int fd = ufd.release();
389     asocket* s = new asocket();
390     s->fd = fd;
391     s->enqueue = local_socket_enqueue;
392     s->ready = local_socket_ready;
393     s->shutdown = nullptr;
394     s->close = local_socket_close;
395     install_local_socket(s);
396 
397     s->fde = fdevent_create(fd, local_socket_event_func, s);
398     D("LS(%d): created (fd=%d)", s->id, s->fd);
399     return s;
400 }
401 
create_local_service_socket(std::string_view name,atransport * transport)402 asocket* create_local_service_socket(std::string_view name, atransport* transport) {
403 #if !ADB_HOST
404     if (asocket* s = daemon_service_to_socket(name); s) {
405         return s;
406     }
407 #endif
408     unique_fd fd = service_to_fd(name, transport);
409     if (fd < 0) {
410         return nullptr;
411     }
412 
413     int fd_value = fd.get();
414     asocket* s = create_local_socket(std::move(fd));
415     LOG(VERBOSE) << "LS(" << s->id << "): bound to '" << name << "' via " << fd_value;
416 
417 #if !ADB_HOST
418     if ((name.starts_with("root:") && getuid() != 0 && __android_log_is_debuggable()) ||
419         (name.starts_with("unroot:") && getuid() == 0) || name.starts_with("usb:") ||
420         name.starts_with("tcpip:")) {
421         D("LS(%d): enabling exit_on_close", s->id);
422         s->exit_on_close = 1;
423     }
424 #endif
425 
426     return s;
427 }
428 
remote_socket_enqueue(asocket * s,apacket::payload_type data)429 static int remote_socket_enqueue(asocket* s, apacket::payload_type data) {
430     D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
431     apacket* p = get_apacket();
432 
433     p->msg.command = A_WRTE;
434     p->msg.arg0 = s->peer->id;
435     p->msg.arg1 = s->id;
436 
437     if (data.size() > MAX_PAYLOAD) {
438         put_apacket(p);
439         return -1;
440     }
441 
442     p->payload = std::move(data);
443     p->msg.data_length = p->payload.size();
444 
445     send_packet(p, s->transport);
446     return 1;
447 }
448 
remote_socket_ready(asocket * s)449 static void remote_socket_ready(asocket* s) {
450     D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
451     apacket* p = get_apacket();
452     p->msg.command = A_OKAY;
453     p->msg.arg0 = s->peer->id;
454     p->msg.arg1 = s->id;
455     send_packet(p, s->transport);
456 }
457 
remote_socket_shutdown(asocket * s)458 static void remote_socket_shutdown(asocket* s) {
459     D("entered remote_socket_shutdown RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
460       s->peer ? s->peer->fd : -1);
461     apacket* p = get_apacket();
462     p->msg.command = A_CLSE;
463     if (s->peer) {
464         p->msg.arg0 = s->peer->id;
465     }
466     p->msg.arg1 = s->id;
467     send_packet(p, s->transport);
468 }
469 
remote_socket_close(asocket * s)470 static void remote_socket_close(asocket* s) {
471     if (s->peer) {
472         s->peer->peer = nullptr;
473         D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
474         s->peer->close(s->peer);
475     }
476     D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
477       s->peer ? s->peer->fd : -1);
478     D("RS(%d): closed", s->id);
479     delete s;
480 }
481 
482 // Create a remote socket to exchange packets with a remote service through transport
483 // |t|. Where |id| is the socket id of the corresponding service on the other
484 //  side of the transport (it is allocated by the remote side and _cannot_ be 0).
485 // Returns a new non-NULL asocket handle.
create_remote_socket(unsigned id,atransport * t)486 asocket* create_remote_socket(unsigned id, atransport* t) {
487     if (id == 0) {
488         LOG(FATAL) << "invalid remote socket id (0)";
489     }
490     asocket* s = new asocket();
491     s->id = id;
492     s->enqueue = remote_socket_enqueue;
493     s->ready = remote_socket_ready;
494     s->shutdown = remote_socket_shutdown;
495     s->close = remote_socket_close;
496     s->transport = t;
497 
498     D("RS(%d): created", s->id);
499     return s;
500 }
501 
connect_to_remote(asocket * s,std::string_view destination)502 void connect_to_remote(asocket* s, std::string_view destination) {
503     D("Connect_to_remote call RS(%d) fd=%d", s->id, s->fd);
504     apacket* p = get_apacket();
505 
506     LOG(VERBOSE) << "LS(" << s->id << ": connect(" << destination << ")";
507     p->msg.command = A_OPEN;
508     p->msg.arg0 = s->id;
509 
510     // adbd used to expect a null-terminated string.
511     // Keep doing so to maintain backward compatibility.
512     p->payload.resize(destination.size() + 1);
513     memcpy(p->payload.data(), destination.data(), destination.size());
514     p->payload[destination.size()] = '\0';
515     p->msg.data_length = p->payload.size();
516 
517     CHECK_LE(p->msg.data_length, s->get_max_payload());
518 
519     send_packet(p, s->transport);
520 }
521 
522 /* this is used by magic sockets to rig local sockets to
523    send the go-ahead message when they connect */
local_socket_ready_notify(asocket * s)524 static void local_socket_ready_notify(asocket* s) {
525     s->ready = local_socket_ready;
526     s->shutdown = nullptr;
527     s->close = local_socket_close;
528     SendOkay(s->fd);
529     s->ready(s);
530 }
531 
532 /* this is used by magic sockets to rig local sockets to
533    send the failure message if they are closed before
534    connected (to avoid closing them without a status message) */
local_socket_close_notify(asocket * s)535 static void local_socket_close_notify(asocket* s) {
536     s->ready = local_socket_ready;
537     s->shutdown = nullptr;
538     s->close = local_socket_close;
539     SendFail(s->fd, "closed");
540     s->close(s);
541 }
542 
unhex(const char * s,int len)543 static unsigned unhex(const char* s, int len) {
544     unsigned n = 0, c;
545 
546     while (len-- > 0) {
547         switch ((c = *s++)) {
548             case '0':
549             case '1':
550             case '2':
551             case '3':
552             case '4':
553             case '5':
554             case '6':
555             case '7':
556             case '8':
557             case '9':
558                 c -= '0';
559                 break;
560             case 'a':
561             case 'b':
562             case 'c':
563             case 'd':
564             case 'e':
565             case 'f':
566                 c = c - 'a' + 10;
567                 break;
568             case 'A':
569             case 'B':
570             case 'C':
571             case 'D':
572             case 'E':
573             case 'F':
574                 c = c - 'A' + 10;
575                 break;
576             default:
577                 return 0xffffffff;
578         }
579 
580         n = (n << 4) | c;
581     }
582 
583     return n;
584 }
585 
586 #if ADB_HOST
587 
588 namespace internal {
589 
590 // Parses a host service string of the following format:
591 //   * [tcp:|udp:]<serial>[:<port>]:<command>
592 //   * <prefix>:<serial>:<command>
593 // Where <port> must be a base-10 number and <prefix> may be any of {usb,product,model,device}.
parse_host_service(std::string_view * out_serial,std::string_view * out_command,std::string_view full_service)594 bool parse_host_service(std::string_view* out_serial, std::string_view* out_command,
595                         std::string_view full_service) {
596     if (full_service.empty()) {
597         return false;
598     }
599 
600     std::string_view serial;
601     std::string_view command = full_service;
602     // Remove |count| bytes from the beginning of command and add them to |serial|.
603     auto consume = [&full_service, &serial, &command](size_t count) {
604         CHECK_LE(count, command.size());
605         if (!serial.empty()) {
606             CHECK_EQ(serial.data() + serial.size(), command.data());
607         }
608 
609         serial = full_service.substr(0, serial.size() + count);
610         command.remove_prefix(count);
611     };
612 
613     // Remove the trailing : from serial, and assign the values to the output parameters.
614     auto finish = [out_serial, out_command, &serial, &command] {
615         if (serial.empty() || command.empty()) {
616             return false;
617         }
618 
619         CHECK_EQ(':', serial.back());
620         serial.remove_suffix(1);
621 
622         *out_serial = serial;
623         *out_command = command;
624         return true;
625     };
626 
627     static constexpr std::string_view prefixes[] = {"usb:", "product:", "model:", "device:"};
628     for (std::string_view prefix : prefixes) {
629         if (command.starts_with(prefix)) {
630             consume(prefix.size());
631 
632             size_t offset = command.find_first_of(':');
633             if (offset == std::string::npos) {
634                 return false;
635             }
636             consume(offset + 1);
637             return finish();
638         }
639     }
640 
641     // For fastboot compatibility, ignore protocol prefixes.
642     if (command.starts_with("tcp:") || command.starts_with("udp:")) {
643         consume(4);
644         if (command.empty()) {
645             return false;
646         }
647     }
648     if (command.starts_with("vsock:")) {
649         // vsock serials are vsock:cid:port, which have an extra colon compared to tcp.
650         size_t next_colon = command.find(':');
651         if (next_colon == std::string::npos) {
652             return false;
653         }
654         consume(next_colon + 1);
655     }
656 
657     bool found_address = false;
658     if (command[0] == '[') {
659         // Read an IPv6 address. `adb connect` creates the serial number from the canonical
660         // network address so it will always have the [] delimiters.
661         size_t ipv6_end = command.find_first_of(']');
662         if (ipv6_end != std::string::npos) {
663             consume(ipv6_end + 1);
664             if (command.empty()) {
665                 // Nothing after the IPv6 address.
666                 return false;
667             } else if (command[0] != ':') {
668                 // Garbage after the IPv6 address.
669                 return false;
670             }
671             consume(1);
672             found_address = true;
673         }
674     }
675 
676     if (!found_address) {
677         // Scan ahead to the next colon.
678         size_t offset = command.find_first_of(':');
679         if (offset == std::string::npos) {
680             return false;
681         }
682         consume(offset + 1);
683     }
684 
685     // We're either at the beginning of a port, or the command itself.
686     // Look for a port in between colons.
687     size_t next_colon = command.find_first_of(':');
688     if (next_colon == std::string::npos) {
689         // No colon, we must be at the command.
690         return finish();
691     }
692 
693     bool port_valid = true;
694     if (command.size() <= next_colon) {
695         return false;
696     }
697 
698     std::string_view port = command.substr(0, next_colon);
699     for (auto digit : port) {
700         if (!isdigit(digit)) {
701             // Port isn't a number.
702             port_valid = false;
703             break;
704         }
705     }
706 
707     if (port_valid) {
708         consume(next_colon + 1);
709     }
710     return finish();
711 }
712 
713 }  // namespace internal
714 
715 #endif  // ADB_HOST
716 
smart_socket_enqueue(asocket * s,apacket::payload_type data)717 static int smart_socket_enqueue(asocket* s, apacket::payload_type data) {
718 #if ADB_HOST
719     std::string_view service;
720     std::string_view serial;
721     TransportId transport_id = 0;
722     TransportType type = kTransportAny;
723 #endif
724 
725     D("SS(%d): enqueue %zu", s->id, data.size());
726 
727     if (s->smart_socket_data.empty()) {
728         // TODO: Make this an IOVector?
729         s->smart_socket_data.assign(data.begin(), data.end());
730     } else {
731         std::copy(data.begin(), data.end(), std::back_inserter(s->smart_socket_data));
732     }
733 
734     /* don't bother if we can't decode the length */
735     if (s->smart_socket_data.size() < 4) {
736         return 0;
737     }
738 
739     uint32_t len = unhex(s->smart_socket_data.data(), 4);
740     if (len == 0 || len > MAX_PAYLOAD) {
741         D("SS(%d): bad size (%u)", s->id, len);
742         goto fail;
743     }
744 
745     D("SS(%d): len is %u", s->id, len);
746     /* can't do anything until we have the full header */
747     if ((len + 4) > s->smart_socket_data.size()) {
748         D("SS(%d): waiting for %zu more bytes", s->id, len + 4 - s->smart_socket_data.size());
749         return 0;
750     }
751 
752     s->smart_socket_data[len + 4] = 0;
753 
754     D("SS(%d): '%s'", s->id, (char*)(s->smart_socket_data.data() + 4));
755 
756 #if ADB_HOST
757     service = std::string_view(s->smart_socket_data).substr(4);
758     if (ConsumePrefix(&service, "host-serial:")) {
759         // serial number should follow "host:" and could be a host:port string.
760         if (!internal::parse_host_service(&serial, &service, service)) {
761             LOG(ERROR) << "SS(" << s->id << "): failed to parse host service: " << service;
762             goto fail;
763         }
764     } else if (ConsumePrefix(&service, "host-transport-id:")) {
765         if (!ParseUint(&transport_id, service, &service)) {
766             LOG(ERROR) << "SS(" << s->id << "): failed to parse host transport id: " << service;
767             return -1;
768         }
769         if (!ConsumePrefix(&service, ":")) {
770             LOG(ERROR) << "SS(" << s->id << "): host-transport-id without command";
771             return -1;
772         }
773     } else if (ConsumePrefix(&service, "host-usb:")) {
774         type = kTransportUsb;
775     } else if (ConsumePrefix(&service, "host-local:")) {
776         type = kTransportLocal;
777     } else if (ConsumePrefix(&service, "host:")) {
778         type = kTransportAny;
779     } else {
780         service = std::string_view{};
781     }
782 
783     if (!service.empty()) {
784         asocket* s2;
785 
786         // Some requests are handled immediately -- in that case the handle_host_request() routine
787         // has sent the OKAY or FAIL message and all we have to do is clean up.
788         auto host_request_result = handle_host_request(
789                 service, type, serial.empty() ? nullptr : std::string(serial).c_str(), transport_id,
790                 s->peer->fd, s);
791 
792         switch (host_request_result) {
793             case HostRequestResult::Handled:
794                 LOG(VERBOSE) << "SS(" << s->id << "): handled host service '" << service << "'";
795                 goto fail;
796 
797             case HostRequestResult::SwitchedTransport:
798                 D("SS(%d): okay transport", s->id);
799                 s->smart_socket_data.clear();
800                 return 0;
801 
802             case HostRequestResult::Unhandled:
803                 break;
804         }
805 
806         /* try to find a local service with this name.
807         ** if no such service exists, we'll fail out
808         ** and tear down here.
809         */
810         // TODO: Convert to string_view.
811         s2 = host_service_to_socket(service, serial, transport_id);
812         if (s2 == nullptr) {
813             LOG(VERBOSE) << "SS(" << s->id << "): couldn't create host service '" << service << "'";
814             SendFail(s->peer->fd, "unknown host service");
815             goto fail;
816         }
817 
818         /* we've connected to a local host service,
819         ** so we make our peer back into a regular
820         ** local socket and bind it to the new local
821         ** service socket, acknowledge the successful
822         ** connection, and close this smart socket now
823         ** that its work is done.
824         */
825         SendOkay(s->peer->fd);
826 
827         s->peer->ready = local_socket_ready;
828         s->peer->shutdown = nullptr;
829         s->peer->close = local_socket_close;
830         s->peer->peer = s2;
831         s2->peer = s->peer;
832         s->peer = nullptr;
833         D("SS(%d): okay", s->id);
834         s->close(s);
835 
836         /* initial state is "ready" */
837         s2->ready(s2);
838         return 0;
839     }
840 #else /* !ADB_HOST */
841     if (s->transport == nullptr) {
842         std::string error_msg = "unknown failure";
843         s->transport = acquire_one_transport(kTransportAny, nullptr, 0, nullptr, &error_msg);
844         if (s->transport == nullptr) {
845             SendFail(s->peer->fd, error_msg);
846             goto fail;
847         }
848     }
849 #endif
850 
851     if (!s->transport) {
852         SendFail(s->peer->fd, "device offline (no transport)");
853         goto fail;
854     } else if (!ConnectionStateIsOnline(s->transport->GetConnectionState())) {
855         /* if there's no remote we fail the connection
856          ** right here and terminate it
857          */
858         SendFail(s->peer->fd, "device offline (transport offline)");
859         goto fail;
860     }
861 
862     /* instrument our peer to pass the success or fail
863     ** message back once it connects or closes, then
864     ** detach from it, request the connection, and
865     ** tear down
866     */
867     s->peer->ready = local_socket_ready_notify;
868     s->peer->shutdown = nullptr;
869     s->peer->close = local_socket_close_notify;
870     s->peer->peer = nullptr;
871     /* give him our transport and upref it */
872     s->peer->transport = s->transport;
873 
874     connect_to_remote(s->peer, std::string_view(s->smart_socket_data).substr(4));
875     s->peer = nullptr;
876     s->close(s);
877     return 1;
878 
879 fail:
880     /* we're going to close our peer as a side-effect, so
881     ** return -1 to signal that state to the local socket
882     ** who is enqueueing against us
883     */
884     s->close(s);
885     return -1;
886 }
887 
smart_socket_ready(asocket * s)888 static void smart_socket_ready(asocket* s) {
889     D("SS(%d): ready", s->id);
890 }
891 
smart_socket_close(asocket * s)892 static void smart_socket_close(asocket* s) {
893     D("SS(%d): closed", s->id);
894     if (s->peer) {
895         s->peer->peer = nullptr;
896         s->peer->close(s->peer);
897         s->peer = nullptr;
898     }
899     delete s;
900 }
901 
create_smart_socket(void)902 static asocket* create_smart_socket(void) {
903     D("Creating smart socket");
904     asocket* s = new asocket();
905     s->enqueue = smart_socket_enqueue;
906     s->ready = smart_socket_ready;
907     s->shutdown = nullptr;
908     s->close = smart_socket_close;
909 
910     D("SS(%d)", s->id);
911     return s;
912 }
913 
connect_to_smartsocket(asocket * s)914 void connect_to_smartsocket(asocket* s) {
915     D("Connecting to smart socket");
916     asocket* ss = create_smart_socket();
917     s->peer = ss;
918     ss->peer = s;
919     s->ready(s);
920 }
921 
get_max_payload() const922 size_t asocket::get_max_payload() const {
923     size_t max_payload = MAX_PAYLOAD;
924     if (transport) {
925         max_payload = std::min(max_payload, transport->get_max_payload());
926     }
927     if (peer && peer->transport) {
928         max_payload = std::min(max_payload, peer->transport->get_max_payload());
929     }
930     return max_payload;
931 }
932