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 <android-base/properties.h>
35#include <log/log_properties.h>
36#endif
37
38#include "adb.h"
39#include "adb_io.h"
40#include "transport.h"
41
42static std::recursive_mutex& local_socket_list_lock = *new std::recursive_mutex();
43static unsigned local_socket_next_id = 1;
44
45static 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*/
53static 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.
60asocket* 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
78static 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
85void 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
98void remove_socket(asocket* s) {
99    std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
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
109void 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);
116restart:
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
125static int local_socket_enqueue(asocket* s, apacket* p) {
126    D("LS(%d): enqueue %zu", 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
164enqueue:
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
179static 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
186static 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 %zu 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
212static 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
250static 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        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
385asocket* 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
402asocket* 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 nullptr;
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    if ((!strncmp(name, "root:", 5) && getuid() != 0 && __android_log_is_debuggable()) ||
421        (!strncmp(name, "unroot:", 7) && getuid() == 0) ||
422        !strncmp(name, "usb:", 4) ||
423        !strncmp(name, "tcpip:", 6)) {
424        D("LS(%d): enabling exit_on_close", s->id);
425        s->exit_on_close = 1;
426    }
427#endif
428
429    return s;
430}
431
432#if ADB_HOST
433static asocket* create_host_service_socket(const char* name, const char* serial,
434                                           TransportId transport_id) {
435    asocket* s;
436
437    s = host_service_to_socket(name, serial, transport_id);
438
439    if (s != NULL) {
440        D("LS(%d) bound to '%s'", s->id, name);
441        return s;
442    }
443
444    return s;
445}
446#endif /* ADB_HOST */
447
448static int remote_socket_enqueue(asocket* s, apacket* p) {
449    D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
450    p->msg.command = A_WRTE;
451    p->msg.arg0 = s->peer->id;
452    p->msg.arg1 = s->id;
453    p->msg.data_length = p->len;
454    send_packet(p, s->transport);
455    return 1;
456}
457
458static void remote_socket_ready(asocket* s) {
459    D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
460    apacket* p = get_apacket();
461    p->msg.command = A_OKAY;
462    p->msg.arg0 = s->peer->id;
463    p->msg.arg1 = s->id;
464    send_packet(p, s->transport);
465}
466
467static void remote_socket_shutdown(asocket* s) {
468    D("entered remote_socket_shutdown RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
469      s->peer ? s->peer->fd : -1);
470    apacket* p = get_apacket();
471    p->msg.command = A_CLSE;
472    if (s->peer) {
473        p->msg.arg0 = s->peer->id;
474    }
475    p->msg.arg1 = s->id;
476    send_packet(p, s->transport);
477}
478
479static void remote_socket_close(asocket* s) {
480    if (s->peer) {
481        s->peer->peer = 0;
482        D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
483        s->peer->close(s->peer);
484    }
485    D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
486      s->peer ? s->peer->fd : -1);
487    D("RS(%d): closed", s->id);
488    free(s);
489}
490
491// Create a remote socket to exchange packets with a remote service through transport
492// |t|. Where |id| is the socket id of the corresponding service on the other
493//  side of the transport (it is allocated by the remote side and _cannot_ be 0).
494// Returns a new non-NULL asocket handle.
495asocket* create_remote_socket(unsigned id, atransport* t) {
496    if (id == 0) {
497        fatal("invalid remote socket id (0)");
498    }
499    asocket* s = reinterpret_cast<asocket*>(calloc(1, sizeof(asocket)));
500
501    if (s == NULL) {
502        fatal("cannot allocate socket");
503    }
504    s->id = id;
505    s->enqueue = remote_socket_enqueue;
506    s->ready = remote_socket_ready;
507    s->shutdown = remote_socket_shutdown;
508    s->close = remote_socket_close;
509    s->transport = t;
510
511    D("RS(%d): created", s->id);
512    return s;
513}
514
515void connect_to_remote(asocket* s, const char* destination) {
516    D("Connect_to_remote call RS(%d) fd=%d", s->id, s->fd);
517    apacket* p = get_apacket();
518    size_t len = strlen(destination) + 1;
519
520    if (len > (s->get_max_payload() - 1)) {
521        fatal("destination oversized");
522    }
523
524    D("LS(%d): connect('%s')", s->id, destination);
525    p->msg.command = A_OPEN;
526    p->msg.arg0 = s->id;
527    p->msg.data_length = len;
528    strcpy((char*)p->data, destination);
529    send_packet(p, s->transport);
530}
531
532/* this is used by magic sockets to rig local sockets to
533   send the go-ahead message when they connect */
534static void local_socket_ready_notify(asocket* s) {
535    s->ready = local_socket_ready;
536    s->shutdown = NULL;
537    s->close = local_socket_close;
538    SendOkay(s->fd);
539    s->ready(s);
540}
541
542/* this is used by magic sockets to rig local sockets to
543   send the failure message if they are closed before
544   connected (to avoid closing them without a status message) */
545static void local_socket_close_notify(asocket* s) {
546    s->ready = local_socket_ready;
547    s->shutdown = NULL;
548    s->close = local_socket_close;
549    SendFail(s->fd, "closed");
550    s->close(s);
551}
552
553static unsigned unhex(char* s, int len) {
554    unsigned n = 0, c;
555
556    while (len-- > 0) {
557        switch ((c = *s++)) {
558            case '0':
559            case '1':
560            case '2':
561            case '3':
562            case '4':
563            case '5':
564            case '6':
565            case '7':
566            case '8':
567            case '9':
568                c -= '0';
569                break;
570            case 'a':
571            case 'b':
572            case 'c':
573            case 'd':
574            case 'e':
575            case 'f':
576                c = c - 'a' + 10;
577                break;
578            case 'A':
579            case 'B':
580            case 'C':
581            case 'D':
582            case 'E':
583            case 'F':
584                c = c - 'A' + 10;
585                break;
586            default:
587                return 0xffffffff;
588        }
589
590        n = (n << 4) | c;
591    }
592
593    return n;
594}
595
596#if ADB_HOST
597
598namespace internal {
599
600// Returns the position in |service| following the target serial parameter. Serial format can be
601// any of:
602//   * [tcp:|udp:]<serial>[:<port>]:<command>
603//   * <prefix>:<serial>:<command>
604// Where <port> must be a base-10 number and <prefix> may be any of {usb,product,model,device}.
605//
606// The returned pointer will point to the ':' just before <command>, or nullptr if not found.
607char* skip_host_serial(char* service) {
608    static const std::vector<std::string>& prefixes =
609        *(new std::vector<std::string>{"usb:", "product:", "model:", "device:"});
610
611    for (const std::string& prefix : prefixes) {
612        if (!strncmp(service, prefix.c_str(), prefix.length())) {
613            return strchr(service + prefix.length(), ':');
614        }
615    }
616
617    // For fastboot compatibility, ignore protocol prefixes.
618    if (!strncmp(service, "tcp:", 4) || !strncmp(service, "udp:", 4)) {
619        service += 4;
620    }
621
622    // Check for an IPv6 address. `adb connect` creates the serial number from the canonical
623    // network address so it will always have the [] delimiters.
624    if (service[0] == '[') {
625        char* ipv6_end = strchr(service, ']');
626        if (ipv6_end != nullptr) {
627            service = ipv6_end;
628        }
629    }
630
631    // The next colon we find must either begin the port field or the command field.
632    char* colon_ptr = strchr(service, ':');
633    if (!colon_ptr) {
634        // No colon in service string.
635        return nullptr;
636    }
637
638    // If the next field is only decimal digits and ends with another colon, it's a port.
639    char* serial_end = colon_ptr;
640    if (isdigit(serial_end[1])) {
641        serial_end++;
642        while (*serial_end && isdigit(*serial_end)) {
643            serial_end++;
644        }
645        if (*serial_end != ':') {
646            // Something other than "<port>:" was found, this must be the command field instead.
647            serial_end = colon_ptr;
648        }
649    }
650    return serial_end;
651}
652
653}  // namespace internal
654
655#endif  // ADB_HOST
656
657static int smart_socket_enqueue(asocket* s, apacket* p) {
658    unsigned len;
659#if ADB_HOST
660    char* service = nullptr;
661    char* serial = nullptr;
662    TransportId transport_id = 0;
663    TransportType type = kTransportAny;
664#endif
665
666    D("SS(%d): enqueue %zu", s->id, p->len);
667
668    if (s->pkt_first == 0) {
669        s->pkt_first = p;
670        s->pkt_last = p;
671    } else {
672        if ((s->pkt_first->len + p->len) > s->get_max_payload()) {
673            D("SS(%d): overflow", s->id);
674            put_apacket(p);
675            goto fail;
676        }
677
678        memcpy(s->pkt_first->data + s->pkt_first->len, p->data, p->len);
679        s->pkt_first->len += p->len;
680        put_apacket(p);
681
682        p = s->pkt_first;
683    }
684
685    /* don't bother if we can't decode the length */
686    if (p->len < 4) {
687        return 0;
688    }
689
690    len = unhex(p->data, 4);
691    if ((len < 1) || (len > MAX_PAYLOAD)) {
692        D("SS(%d): bad size (%d)", s->id, len);
693        goto fail;
694    }
695
696    D("SS(%d): len is %d", s->id, len);
697    /* can't do anything until we have the full header */
698    if ((len + 4) > p->len) {
699        D("SS(%d): waiting for %zu more bytes", s->id, len + 4 - p->len);
700        return 0;
701    }
702
703    p->data[len + 4] = 0;
704
705    D("SS(%d): '%s'", s->id, (char*)(p->data + 4));
706
707#if ADB_HOST
708    service = (char*)p->data + 4;
709    if (!strncmp(service, "host-serial:", strlen("host-serial:"))) {
710        char* serial_end;
711        service += strlen("host-serial:");
712
713        // serial number should follow "host:" and could be a host:port string.
714        serial_end = internal::skip_host_serial(service);
715        if (serial_end) {
716            *serial_end = 0;  // terminate string
717            serial = service;
718            service = serial_end + 1;
719        }
720    } else if (!strncmp(service, "host-transport-id:", strlen("host-transport-id:"))) {
721        service += strlen("host-transport-id:");
722        transport_id = strtoll(service, &service, 10);
723
724        if (*service != ':') {
725            return -1;
726        }
727        service++;
728    } else if (!strncmp(service, "host-usb:", strlen("host-usb:"))) {
729        type = kTransportUsb;
730        service += strlen("host-usb:");
731    } else if (!strncmp(service, "host-local:", strlen("host-local:"))) {
732        type = kTransportLocal;
733        service += strlen("host-local:");
734    } else if (!strncmp(service, "host:", strlen("host:"))) {
735        type = kTransportAny;
736        service += strlen("host:");
737    } else {
738        service = nullptr;
739    }
740
741    if (service) {
742        asocket* s2;
743
744        /* some requests are handled immediately -- in that
745        ** case the handle_host_request() routine has sent
746        ** the OKAY or FAIL message and all we have to do
747        ** is clean up.
748        */
749        if (handle_host_request(service, type, serial, transport_id, s->peer->fd, s) == 0) {
750            /* XXX fail message? */
751            D("SS(%d): handled host service '%s'", s->id, service);
752            goto fail;
753        }
754        if (!strncmp(service, "transport", strlen("transport"))) {
755            D("SS(%d): okay transport", s->id);
756            p->len = 0;
757            return 0;
758        }
759
760        /* try to find a local service with this name.
761        ** if no such service exists, we'll fail out
762        ** and tear down here.
763        */
764        s2 = create_host_service_socket(service, serial, transport_id);
765        if (s2 == 0) {
766            D("SS(%d): couldn't create host service '%s'", s->id, service);
767            SendFail(s->peer->fd, "unknown host service");
768            goto fail;
769        }
770
771        /* we've connected to a local host service,
772        ** so we make our peer back into a regular
773        ** local socket and bind it to the new local
774        ** service socket, acknowledge the successful
775        ** connection, and close this smart socket now
776        ** that its work is done.
777        */
778        SendOkay(s->peer->fd);
779
780        s->peer->ready = local_socket_ready;
781        s->peer->shutdown = nullptr;
782        s->peer->close = local_socket_close;
783        s->peer->peer = s2;
784        s2->peer = s->peer;
785        s->peer = 0;
786        D("SS(%d): okay", s->id);
787        s->close(s);
788
789        /* initial state is "ready" */
790        s2->ready(s2);
791        return 0;
792    }
793#else /* !ADB_HOST */
794    if (s->transport == nullptr) {
795        std::string error_msg = "unknown failure";
796        s->transport = acquire_one_transport(kTransportAny, nullptr, 0, nullptr, &error_msg);
797        if (s->transport == nullptr) {
798            SendFail(s->peer->fd, error_msg);
799            goto fail;
800        }
801    }
802#endif
803
804    if (!s->transport) {
805        SendFail(s->peer->fd, "device offline (no transport)");
806        goto fail;
807    } else if (s->transport->GetConnectionState() == kCsOffline) {
808        /* if there's no remote we fail the connection
809         ** right here and terminate it
810         */
811        SendFail(s->peer->fd, "device offline (transport offline)");
812        goto fail;
813    }
814
815    /* instrument our peer to pass the success or fail
816    ** message back once it connects or closes, then
817    ** detach from it, request the connection, and
818    ** tear down
819    */
820    s->peer->ready = local_socket_ready_notify;
821    s->peer->shutdown = nullptr;
822    s->peer->close = local_socket_close_notify;
823    s->peer->peer = 0;
824    /* give him our transport and upref it */
825    s->peer->transport = s->transport;
826
827    connect_to_remote(s->peer, (char*)(p->data + 4));
828    s->peer = 0;
829    s->close(s);
830    return 1;
831
832fail:
833    /* we're going to close our peer as a side-effect, so
834    ** return -1 to signal that state to the local socket
835    ** who is enqueueing against us
836    */
837    s->close(s);
838    return -1;
839}
840
841static void smart_socket_ready(asocket* s) {
842    D("SS(%d): ready", s->id);
843}
844
845static void smart_socket_close(asocket* s) {
846    D("SS(%d): closed", s->id);
847    if (s->pkt_first) {
848        put_apacket(s->pkt_first);
849    }
850    if (s->peer) {
851        s->peer->peer = 0;
852        s->peer->close(s->peer);
853        s->peer = 0;
854    }
855    free(s);
856}
857
858static asocket* create_smart_socket(void) {
859    D("Creating smart socket");
860    asocket* s = reinterpret_cast<asocket*>(calloc(1, sizeof(asocket)));
861    if (s == NULL) fatal("cannot allocate socket");
862    s->enqueue = smart_socket_enqueue;
863    s->ready = smart_socket_ready;
864    s->shutdown = NULL;
865    s->close = smart_socket_close;
866
867    D("SS(%d)", s->id);
868    return s;
869}
870
871void connect_to_smartsocket(asocket* s) {
872    D("Connecting to smart socket");
873    asocket* ss = create_smart_socket();
874    s->peer = ss;
875    ss->peer = s;
876    s->ready(s);
877}
878
879size_t asocket::get_max_payload() const {
880    size_t max_payload = MAX_PAYLOAD;
881    if (transport) {
882        max_payload = std::min(max_payload, transport->get_max_payload());
883    }
884    if (peer && peer->transport) {
885        max_payload = std::min(max_payload, peer->transport->get_max_payload());
886    }
887    return max_payload;
888}
889