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 <mutex>
30 #include <string>
31 #include <vector>
32 
33 #if !ADB_HOST
34 #include "cutils/properties.h"
35 #endif
36 
37 #include "adb.h"
38 #include "adb_io.h"
39 #include "sysdeps/mutex.h"
40 #include "transport.h"
41 
42 static std::recursive_mutex& local_socket_list_lock = *new std::recursive_mutex();
43 static unsigned local_socket_next_id = 1;
44 
45 static asocket local_socket_list = {
46     .next = &local_socket_list, .prev = &local_socket_list,
47 };
48 
49 /* the the list of currently closing local sockets.
50 ** these have no peer anymore, but still packets to
51 ** write to their fd.
52 */
53 static asocket local_socket_closing_list = {
54     .next = &local_socket_closing_list, .prev = &local_socket_closing_list,
55 };
56 
57 // Parse the global list of sockets to find one with id |local_id|.
58 // If |peer_id| is not 0, also check that it is connected to a peer
59 // with id |peer_id|. Returns an asocket handle on success, NULL on failure.
find_local_socket(unsigned local_id,unsigned peer_id)60 asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
61     asocket* s;
62     asocket* result = NULL;
63 
64     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
65     for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
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 
insert_local_socket(asocket * s,asocket * list)78 static void insert_local_socket(asocket* s, asocket* list) {
79     s->next = list;
80     s->prev = s->next->prev;
81     s->prev->next = s;
82     s->next->prev = s;
83 }
84 
install_local_socket(asocket * s)85 void install_local_socket(asocket* s) {
86     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
87 
88     s->id = local_socket_next_id++;
89 
90     // Socket ids should never be 0.
91     if (local_socket_next_id == 0) {
92         fatal("local socket id overflow");
93     }
94 
95     insert_local_socket(s, &local_socket_list);
96 }
97 
remove_socket(asocket * s)98 void remove_socket(asocket* s) {
99     // socket_list_lock should already be held
100     if (s->prev && s->next) {
101         s->prev->next = s->next;
102         s->next->prev = s->prev;
103         s->next = 0;
104         s->prev = 0;
105         s->id = 0;
106     }
107 }
108 
close_all_sockets(atransport * t)109 void close_all_sockets(atransport* t) {
110     asocket* s;
111 
112     /* this is a little gross, but since s->close() *will* modify
113     ** the list out from under you, your options are limited.
114     */
115     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
116 restart:
117     for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
118         if (s->transport == t || (s->peer && s->peer->transport == t)) {
119             s->close(s);
120             goto restart;
121         }
122     }
123 }
124 
local_socket_enqueue(asocket * s,apacket * p)125 static int local_socket_enqueue(asocket* s, apacket* p) {
126     D("LS(%d): enqueue %d", s->id, p->len);
127 
128     p->ptr = p->data;
129 
130     /* if there is already data queue'd, we will receive
131     ** events when it's time to write.  just add this to
132     ** the tail
133     */
134     if (s->pkt_first) {
135         goto enqueue;
136     }
137 
138     /* write as much as we can, until we
139     ** would block or there is an error/eof
140     */
141     while (p->len > 0) {
142         int r = adb_write(s->fd, p->ptr, p->len);
143         if (r > 0) {
144             p->len -= r;
145             p->ptr += r;
146             continue;
147         }
148         if ((r == 0) || (errno != EAGAIN)) {
149             D("LS(%d): not ready, errno=%d: %s", s->id, errno, strerror(errno));
150             put_apacket(p);
151             s->has_write_error = true;
152             s->close(s);
153             return 1; /* not ready (error) */
154         } else {
155             break;
156         }
157     }
158 
159     if (p->len == 0) {
160         put_apacket(p);
161         return 0; /* ready for more data */
162     }
163 
164 enqueue:
165     p->next = 0;
166     if (s->pkt_first) {
167         s->pkt_last->next = p;
168     } else {
169         s->pkt_first = p;
170     }
171     s->pkt_last = p;
172 
173     /* make sure we are notified when we can drain the queue */
174     fdevent_add(&s->fde, FDE_WRITE);
175 
176     return 1; /* not ready (backlog) */
177 }
178 
local_socket_ready(asocket * s)179 static void local_socket_ready(asocket* s) {
180     /* far side is ready for data, pay attention to
181        readable events */
182     fdevent_add(&s->fde, FDE_READ);
183 }
184 
185 // be sure to hold the socket list lock when calling this
local_socket_destroy(asocket * s)186 static void local_socket_destroy(asocket* s) {
187     apacket *p, *n;
188     int exit_on_close = s->exit_on_close;
189 
190     D("LS(%d): destroying fde.fd=%d", s->id, s->fde.fd);
191 
192     /* IMPORTANT: the remove closes the fd
193     ** that belongs to this socket
194     */
195     fdevent_remove(&s->fde);
196 
197     /* dispose of any unwritten data */
198     for (p = s->pkt_first; p; p = n) {
199         D("LS(%d): discarding %d bytes", s->id, p->len);
200         n = p->next;
201         put_apacket(p);
202     }
203     remove_socket(s);
204     free(s);
205 
206     if (exit_on_close) {
207         D("local_socket_destroy: exiting");
208         exit(1);
209     }
210 }
211 
local_socket_close(asocket * s)212 static void local_socket_close(asocket* s) {
213     D("entered local_socket_close. LS(%d) fd=%d", s->id, s->fd);
214     std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
215     if (s->peer) {
216         D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
217         /* Note: it's important to call shutdown before disconnecting from
218          * the peer, this ensures that remote sockets can still get the id
219          * of the local socket they're connected to, to send a CLOSE()
220          * protocol event. */
221         if (s->peer->shutdown) {
222             s->peer->shutdown(s->peer);
223         }
224         s->peer->peer = nullptr;
225         s->peer->close(s->peer);
226         s->peer = nullptr;
227     }
228 
229     /* If we are already closing, or if there are no
230     ** pending packets, destroy immediately
231     */
232     if (s->closing || s->has_write_error || s->pkt_first == NULL) {
233         int id = s->id;
234         local_socket_destroy(s);
235         D("LS(%d): closed", id);
236         return;
237     }
238 
239     /* otherwise, put on the closing list
240     */
241     D("LS(%d): closing", s->id);
242     s->closing = 1;
243     fdevent_del(&s->fde, FDE_READ);
244     remove_socket(s);
245     D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd);
246     insert_local_socket(s, &local_socket_closing_list);
247     CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE);
248 }
249 
local_socket_event_func(int fd,unsigned ev,void * _s)250 static void local_socket_event_func(int fd, unsigned ev, void* _s) {
251     asocket* s = reinterpret_cast<asocket*>(_s);
252     D("LS(%d): event_func(fd=%d(==%d), ev=%04x)", s->id, s->fd, fd, ev);
253 
254     /* put the FDE_WRITE processing before the FDE_READ
255     ** in order to simplify the code.
256     */
257     if (ev & FDE_WRITE) {
258         apacket* p;
259         while ((p = s->pkt_first) != nullptr) {
260             while (p->len > 0) {
261                 int r = adb_write(fd, p->ptr, p->len);
262                 if (r == -1) {
263                     /* returning here is ok because FDE_READ will
264                     ** be processed in the next iteration loop
265                     */
266                     if (errno == EAGAIN) {
267                         return;
268                     }
269                 } else if (r > 0) {
270                     p->ptr += r;
271                     p->len -= r;
272                     continue;
273                 }
274 
275                 D(" closing after write because r=%d and errno is %d", r, errno);
276                 s->has_write_error = true;
277                 s->close(s);
278                 return;
279             }
280 
281             if (p->len == 0) {
282                 s->pkt_first = p->next;
283                 if (s->pkt_first == 0) {
284                     s->pkt_last = 0;
285                 }
286                 put_apacket(p);
287             }
288         }
289 
290         /* if we sent the last packet of a closing socket,
291         ** we can now destroy it.
292         */
293         if (s->closing) {
294             D(" closing because 'closing' is set after write");
295             s->close(s);
296             return;
297         }
298 
299         /* no more packets queued, so we can ignore
300         ** writable events again and tell our peer
301         ** to resume writing
302         */
303         fdevent_del(&s->fde, FDE_WRITE);
304         s->peer->ready(s->peer);
305     }
306 
307     if (ev & FDE_READ) {
308         apacket* p = get_apacket();
309         unsigned char* x = p->data;
310         const size_t max_payload = s->get_max_payload();
311         size_t avail = max_payload;
312         int r = 0;
313         int is_eof = 0;
314 
315         while (avail > 0) {
316             r = adb_read(fd, x, avail);
317             D("LS(%d): post adb_read(fd=%d,...) r=%d (errno=%d) avail=%zu", s->id, s->fd, r,
318               r < 0 ? errno : 0, avail);
319             if (r == -1) {
320                 if (errno == EAGAIN) {
321                     break;
322                 }
323             } else if (r > 0) {
324                 avail -= r;
325                 x += r;
326                 continue;
327             }
328 
329             /* r = 0 or unhandled error */
330             is_eof = 1;
331             break;
332         }
333         D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d", s->id, s->fd, r, is_eof,
334           s->fde.force_eof);
335         if ((avail == max_payload) || (s->peer == 0)) {
336             put_apacket(p);
337         } else {
338             p->len = max_payload - avail;
339 
340             // s->peer->enqueue() may call s->close() and free s,
341             // so save variables for debug printing below.
342             unsigned saved_id = s->id;
343             int saved_fd = s->fd;
344             r = s->peer->enqueue(s->peer, p);
345             D("LS(%u): fd=%d post peer->enqueue(). r=%d", saved_id, saved_fd, r);
346 
347             if (r < 0) {
348                 /* error return means they closed us as a side-effect
349                 ** and we must return immediately.
350                 **
351                 ** note that if we still have buffered packets, the
352                 ** socket will be placed on the closing socket list.
353                 ** this handler function will be called again
354                 ** to process FDE_WRITE events.
355                 */
356                 return;
357             }
358 
359             if (r > 0) {
360                 /* if the remote cannot accept further events,
361                 ** we disable notification of READs.  They'll
362                 ** be enabled again when we get a call to ready()
363                 */
364                 fdevent_del(&s->fde, FDE_READ);
365             }
366         }
367         /* Don't allow a forced eof if data is still there */
368         if ((s->fde.force_eof && !r) || is_eof) {
369             D(" closing because is_eof=%d r=%d s->fde.force_eof=%d", is_eof, r, s->fde.force_eof);
370             s->close(s);
371             return;
372         }
373     }
374 
375     if (ev & FDE_ERROR) {
376         /* this should be caught be the next read or write
377         ** catching it here means we may skip the last few
378         ** bytes of readable data.
379         */
380         D("LS(%d): FDE_ERROR (fd=%d)", s->id, s->fd);
381         return;
382     }
383 }
384 
create_local_socket(int fd)385 asocket* create_local_socket(int fd) {
386     asocket* s = reinterpret_cast<asocket*>(calloc(1, sizeof(asocket)));
387     if (s == NULL) {
388         fatal("cannot allocate socket");
389     }
390     s->fd = fd;
391     s->enqueue = local_socket_enqueue;
392     s->ready = local_socket_ready;
393     s->shutdown = NULL;
394     s->close = local_socket_close;
395     install_local_socket(s);
396 
397     fdevent_install(&s->fde, 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(const char * name,const atransport * transport)402 asocket* create_local_service_socket(const char* name, const atransport* transport) {
403 #if !ADB_HOST
404     if (!strcmp(name, "jdwp")) {
405         return create_jdwp_service_socket();
406     }
407     if (!strcmp(name, "track-jdwp")) {
408         return create_jdwp_tracker_service_socket();
409     }
410 #endif
411     int fd = service_to_fd(name, transport);
412     if (fd < 0) {
413         return 0;
414     }
415 
416     asocket* s = create_local_socket(fd);
417     D("LS(%d): bound to '%s' via %d", s->id, name, fd);
418 
419 #if !ADB_HOST
420     char debug[PROPERTY_VALUE_MAX];
421     if (!strncmp(name, "root:", 5)) {
422         property_get("ro.debuggable", debug, "");
423     }
424 
425     if ((!strncmp(name, "root:", 5) && getuid() != 0 && strcmp(debug, "1") == 0) ||
426         (!strncmp(name, "unroot:", 7) && getuid() == 0) ||
427         !strncmp(name, "usb:", 4) ||
428         !strncmp(name, "tcpip:", 6)) {
429         D("LS(%d): enabling exit_on_close", s->id);
430         s->exit_on_close = 1;
431     }
432 #endif
433 
434     return s;
435 }
436 
437 #if ADB_HOST
create_host_service_socket(const char * name,const char * serial)438 static asocket* create_host_service_socket(const char* name, const char* serial) {
439     asocket* s;
440 
441     s = host_service_to_socket(name, serial);
442 
443     if (s != NULL) {
444         D("LS(%d) bound to '%s'", s->id, name);
445         return s;
446     }
447 
448     return s;
449 }
450 #endif /* ADB_HOST */
451 
remote_socket_enqueue(asocket * s,apacket * p)452 static int remote_socket_enqueue(asocket* s, apacket* p) {
453     D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
454     p->msg.command = A_WRTE;
455     p->msg.arg0 = s->peer->id;
456     p->msg.arg1 = s->id;
457     p->msg.data_length = p->len;
458     send_packet(p, s->transport);
459     return 1;
460 }
461 
remote_socket_ready(asocket * s)462 static void remote_socket_ready(asocket* s) {
463     D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
464     apacket* p = get_apacket();
465     p->msg.command = A_OKAY;
466     p->msg.arg0 = s->peer->id;
467     p->msg.arg1 = s->id;
468     send_packet(p, s->transport);
469 }
470 
remote_socket_shutdown(asocket * s)471 static void remote_socket_shutdown(asocket* s) {
472     D("entered remote_socket_shutdown RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
473       s->peer ? s->peer->fd : -1);
474     apacket* p = get_apacket();
475     p->msg.command = A_CLSE;
476     if (s->peer) {
477         p->msg.arg0 = s->peer->id;
478     }
479     p->msg.arg1 = s->id;
480     send_packet(p, s->transport);
481 }
482 
remote_socket_close(asocket * s)483 static void remote_socket_close(asocket* s) {
484     if (s->peer) {
485         s->peer->peer = 0;
486         D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
487         s->peer->close(s->peer);
488     }
489     D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
490       s->peer ? s->peer->fd : -1);
491     D("RS(%d): closed", s->id);
492     free(s);
493 }
494 
495 // Create a remote socket to exchange packets with a remote service through transport
496 // |t|. Where |id| is the socket id of the corresponding service on the other
497 //  side of the transport (it is allocated by the remote side and _cannot_ be 0).
498 // Returns a new non-NULL asocket handle.
create_remote_socket(unsigned id,atransport * t)499 asocket* create_remote_socket(unsigned id, atransport* t) {
500     if (id == 0) {
501         fatal("invalid remote socket id (0)");
502     }
503     asocket* s = reinterpret_cast<asocket*>(calloc(1, sizeof(asocket)));
504 
505     if (s == NULL) {
506         fatal("cannot allocate socket");
507     }
508     s->id = id;
509     s->enqueue = remote_socket_enqueue;
510     s->ready = remote_socket_ready;
511     s->shutdown = remote_socket_shutdown;
512     s->close = remote_socket_close;
513     s->transport = t;
514 
515     D("RS(%d): created", s->id);
516     return s;
517 }
518 
connect_to_remote(asocket * s,const char * destination)519 void connect_to_remote(asocket* s, const char* destination) {
520     D("Connect_to_remote call RS(%d) fd=%d", s->id, s->fd);
521     apacket* p = get_apacket();
522     size_t len = strlen(destination) + 1;
523 
524     if (len > (s->get_max_payload() - 1)) {
525         fatal("destination oversized");
526     }
527 
528     D("LS(%d): connect('%s')", s->id, destination);
529     p->msg.command = A_OPEN;
530     p->msg.arg0 = s->id;
531     p->msg.data_length = len;
532     strcpy((char*)p->data, destination);
533     send_packet(p, s->transport);
534 }
535 
536 /* this is used by magic sockets to rig local sockets to
537    send the go-ahead message when they connect */
local_socket_ready_notify(asocket * s)538 static void local_socket_ready_notify(asocket* s) {
539     s->ready = local_socket_ready;
540     s->shutdown = NULL;
541     s->close = local_socket_close;
542     SendOkay(s->fd);
543     s->ready(s);
544 }
545 
546 /* this is used by magic sockets to rig local sockets to
547    send the failure message if they are closed before
548    connected (to avoid closing them without a status message) */
local_socket_close_notify(asocket * s)549 static void local_socket_close_notify(asocket* s) {
550     s->ready = local_socket_ready;
551     s->shutdown = NULL;
552     s->close = local_socket_close;
553     SendFail(s->fd, "closed");
554     s->close(s);
555 }
556 
unhex(unsigned char * s,int len)557 static unsigned unhex(unsigned char* s, int len) {
558     unsigned n = 0, c;
559 
560     while (len-- > 0) {
561         switch ((c = *s++)) {
562             case '0':
563             case '1':
564             case '2':
565             case '3':
566             case '4':
567             case '5':
568             case '6':
569             case '7':
570             case '8':
571             case '9':
572                 c -= '0';
573                 break;
574             case 'a':
575             case 'b':
576             case 'c':
577             case 'd':
578             case 'e':
579             case 'f':
580                 c = c - 'a' + 10;
581                 break;
582             case 'A':
583             case 'B':
584             case 'C':
585             case 'D':
586             case 'E':
587             case 'F':
588                 c = c - 'A' + 10;
589                 break;
590             default:
591                 return 0xffffffff;
592         }
593 
594         n = (n << 4) | c;
595     }
596 
597     return n;
598 }
599 
600 #if ADB_HOST
601 
602 namespace internal {
603 
604 // Returns the position in |service| following the target serial parameter. Serial format can be
605 // any of:
606 //   * [tcp:|udp:]<serial>[:<port>]:<command>
607 //   * <prefix>:<serial>:<command>
608 // Where <port> must be a base-10 number and <prefix> may be any of {usb,product,model,device}.
609 //
610 // The returned pointer will point to the ':' just before <command>, or nullptr if not found.
skip_host_serial(const char * service)611 char* skip_host_serial(const char* service) {
612     static const std::vector<std::string>& prefixes =
613         *(new std::vector<std::string>{"usb:", "product:", "model:", "device:"});
614 
615     for (const std::string& prefix : prefixes) {
616         if (!strncmp(service, prefix.c_str(), prefix.length())) {
617             return strchr(service + prefix.length(), ':');
618         }
619     }
620 
621     // For fastboot compatibility, ignore protocol prefixes.
622     if (!strncmp(service, "tcp:", 4) || !strncmp(service, "udp:", 4)) {
623         service += 4;
624     }
625 
626     char* first_colon = strchr(service, ':');
627     if (!first_colon) {
628         // No colon in service string.
629         return nullptr;
630     }
631 
632     char* serial_end = first_colon;
633     if (isdigit(serial_end[1])) {
634         serial_end++;
635         while (*serial_end && isdigit(*serial_end)) {
636             serial_end++;
637         }
638         if (*serial_end != ':') {
639             // Something other than numbers was found, reset the end.
640             serial_end = first_colon;
641         }
642     }
643     return serial_end;
644 }
645 
646 }  // namespace internal
647 
648 #endif  // ADB_HOST
649 
smart_socket_enqueue(asocket * s,apacket * p)650 static int smart_socket_enqueue(asocket* s, apacket* p) {
651     unsigned len;
652 #if ADB_HOST
653     char* service = nullptr;
654     char* serial = nullptr;
655     TransportType type = kTransportAny;
656 #endif
657 
658     D("SS(%d): enqueue %d", s->id, p->len);
659 
660     if (s->pkt_first == 0) {
661         s->pkt_first = p;
662         s->pkt_last = p;
663     } else {
664         if ((s->pkt_first->len + p->len) > s->get_max_payload()) {
665             D("SS(%d): overflow", s->id);
666             put_apacket(p);
667             goto fail;
668         }
669 
670         memcpy(s->pkt_first->data + s->pkt_first->len, p->data, p->len);
671         s->pkt_first->len += p->len;
672         put_apacket(p);
673 
674         p = s->pkt_first;
675     }
676 
677     /* don't bother if we can't decode the length */
678     if (p->len < 4) {
679         return 0;
680     }
681 
682     len = unhex(p->data, 4);
683     if ((len < 1) || (len > MAX_PAYLOAD_V1)) {
684         D("SS(%d): bad size (%d)", s->id, len);
685         goto fail;
686     }
687 
688     D("SS(%d): len is %d", s->id, len);
689     /* can't do anything until we have the full header */
690     if ((len + 4) > p->len) {
691         D("SS(%d): waiting for %d more bytes", s->id, len + 4 - p->len);
692         return 0;
693     }
694 
695     p->data[len + 4] = 0;
696 
697     D("SS(%d): '%s'", s->id, (char*)(p->data + 4));
698 
699 #if ADB_HOST
700     service = (char*)p->data + 4;
701     if (!strncmp(service, "host-serial:", strlen("host-serial:"))) {
702         char* serial_end;
703         service += strlen("host-serial:");
704 
705         // serial number should follow "host:" and could be a host:port string.
706         serial_end = internal::skip_host_serial(service);
707         if (serial_end) {
708             *serial_end = 0;  // terminate string
709             serial = service;
710             service = serial_end + 1;
711         }
712     } else if (!strncmp(service, "host-usb:", strlen("host-usb:"))) {
713         type = kTransportUsb;
714         service += strlen("host-usb:");
715     } else if (!strncmp(service, "host-local:", strlen("host-local:"))) {
716         type = kTransportLocal;
717         service += strlen("host-local:");
718     } else if (!strncmp(service, "host:", strlen("host:"))) {
719         type = kTransportAny;
720         service += strlen("host:");
721     } else {
722         service = nullptr;
723     }
724 
725     if (service) {
726         asocket* s2;
727 
728         /* some requests are handled immediately -- in that
729         ** case the handle_host_request() routine has sent
730         ** the OKAY or FAIL message and all we have to do
731         ** is clean up.
732         */
733         if (handle_host_request(service, type, serial, s->peer->fd, s) == 0) {
734             /* XXX fail message? */
735             D("SS(%d): handled host service '%s'", s->id, service);
736             goto fail;
737         }
738         if (!strncmp(service, "transport", strlen("transport"))) {
739             D("SS(%d): okay transport", s->id);
740             p->len = 0;
741             return 0;
742         }
743 
744         /* try to find a local service with this name.
745         ** if no such service exists, we'll fail out
746         ** and tear down here.
747         */
748         s2 = create_host_service_socket(service, serial);
749         if (s2 == 0) {
750             D("SS(%d): couldn't create host service '%s'", s->id, service);
751             SendFail(s->peer->fd, "unknown host service");
752             goto fail;
753         }
754 
755         /* we've connected to a local host service,
756         ** so we make our peer back into a regular
757         ** local socket and bind it to the new local
758         ** service socket, acknowledge the successful
759         ** connection, and close this smart socket now
760         ** that its work is done.
761         */
762         SendOkay(s->peer->fd);
763 
764         s->peer->ready = local_socket_ready;
765         s->peer->shutdown = nullptr;
766         s->peer->close = local_socket_close;
767         s->peer->peer = s2;
768         s2->peer = s->peer;
769         s->peer = 0;
770         D("SS(%d): okay", s->id);
771         s->close(s);
772 
773         /* initial state is "ready" */
774         s2->ready(s2);
775         return 0;
776     }
777 #else /* !ADB_HOST */
778     if (s->transport == nullptr) {
779         std::string error_msg = "unknown failure";
780         s->transport = acquire_one_transport(kTransportAny, nullptr, nullptr, &error_msg);
781         if (s->transport == nullptr) {
782             SendFail(s->peer->fd, error_msg);
783             goto fail;
784         }
785     }
786 #endif
787 
788     if (!(s->transport) || (s->transport->connection_state == kCsOffline)) {
789         /* if there's no remote we fail the connection
790          ** right here and terminate it
791          */
792         SendFail(s->peer->fd, "device offline (x)");
793         goto fail;
794     }
795 
796     /* instrument our peer to pass the success or fail
797     ** message back once it connects or closes, then
798     ** detach from it, request the connection, and
799     ** tear down
800     */
801     s->peer->ready = local_socket_ready_notify;
802     s->peer->shutdown = nullptr;
803     s->peer->close = local_socket_close_notify;
804     s->peer->peer = 0;
805     /* give him our transport and upref it */
806     s->peer->transport = s->transport;
807 
808     connect_to_remote(s->peer, (char*)(p->data + 4));
809     s->peer = 0;
810     s->close(s);
811     return 1;
812 
813 fail:
814     /* we're going to close our peer as a side-effect, so
815     ** return -1 to signal that state to the local socket
816     ** who is enqueueing against us
817     */
818     s->close(s);
819     return -1;
820 }
821 
smart_socket_ready(asocket * s)822 static void smart_socket_ready(asocket* s) {
823     D("SS(%d): ready", s->id);
824 }
825 
smart_socket_close(asocket * s)826 static void smart_socket_close(asocket* s) {
827     D("SS(%d): closed", s->id);
828     if (s->pkt_first) {
829         put_apacket(s->pkt_first);
830     }
831     if (s->peer) {
832         s->peer->peer = 0;
833         s->peer->close(s->peer);
834         s->peer = 0;
835     }
836     free(s);
837 }
838 
create_smart_socket(void)839 static asocket* create_smart_socket(void) {
840     D("Creating smart socket");
841     asocket* s = reinterpret_cast<asocket*>(calloc(1, sizeof(asocket)));
842     if (s == NULL) fatal("cannot allocate socket");
843     s->enqueue = smart_socket_enqueue;
844     s->ready = smart_socket_ready;
845     s->shutdown = NULL;
846     s->close = smart_socket_close;
847 
848     D("SS(%d)", s->id);
849     return s;
850 }
851 
connect_to_smartsocket(asocket * s)852 void connect_to_smartsocket(asocket* s) {
853     D("Connecting to smart socket");
854     asocket* ss = create_smart_socket();
855     s->peer = ss;
856     ss->peer = s;
857     s->ready(s);
858 }
859 
get_max_payload() const860 size_t asocket::get_max_payload() const {
861     size_t max_payload = MAX_PAYLOAD;
862     if (transport) {
863         max_payload = std::min(max_payload, transport->get_max_payload());
864     }
865     if (peer && peer->transport) {
866         max_payload = std::min(max_payload, peer->transport->get_max_payload());
867     }
868     return max_payload;
869 }
870