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