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