blob: 817410d133a0f3ebe9fb2ee7a1f794519fc15c55 [file] [log] [blame]
Doug Zongker9270a202012-01-09 15:16:13 -08001/*
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#include <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <errno.h>
21#include <string.h>
22#include <ctype.h>
23
24#include "sysdeps.h"
25
26#define TRACE_TAG TRACE_SOCKETS
27#include "adb.h"
28
29ADB_MUTEX_DEFINE( socket_list_lock );
30
31static void local_socket_close_locked(asocket *s);
32
33int sendfailmsg(int fd, const char *reason)
34{
35 char buf[9];
36 int len;
37 len = strlen(reason);
38 if(len > 0xffff) len = 0xffff;
39 snprintf(buf, sizeof buf, "FAIL%04x", len);
40 if(writex(fd, buf, 8)) return -1;
41 return writex(fd, reason, len);
42}
43
44//extern int online;
45
46static unsigned local_socket_next_id = 1;
47
48static asocket local_socket_list = {
49 .next = &local_socket_list,
50 .prev = &local_socket_list,
51};
52
53/* the the list of currently closing local sockets.
54** these have no peer anymore, but still packets to
55** write to their fd.
56*/
57static asocket local_socket_closing_list = {
58 .next = &local_socket_closing_list,
59 .prev = &local_socket_closing_list,
60};
61
62asocket *find_local_socket(unsigned id)
63{
64 asocket *s;
65 asocket *result = NULL;
66
67 adb_mutex_lock(&socket_list_lock);
68 for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
69 if (s->id == id) {
70 result = s;
71 break;
72 }
73 }
74 adb_mutex_unlock(&socket_list_lock);
75
76 return result;
77}
78
79static void
80insert_local_socket(asocket* s, asocket* list)
81{
82 s->next = list;
83 s->prev = s->next->prev;
84 s->prev->next = s;
85 s->next->prev = s;
86}
87
88
89void install_local_socket(asocket *s)
90{
91 adb_mutex_lock(&socket_list_lock);
92
93 s->id = local_socket_next_id++;
94 insert_local_socket(s, &local_socket_list);
95
96 adb_mutex_unlock(&socket_list_lock);
97}
98
99void remove_socket(asocket *s)
100{
101 // socket_list_lock should already be held
102 if (s->prev && s->next)
103 {
104 s->prev->next = s->next;
105 s->next->prev = s->prev;
106 s->next = 0;
107 s->prev = 0;
108 s->id = 0;
109 }
110}
111
112void close_all_sockets(atransport *t)
113{
114 asocket *s;
115
116 /* this is a little gross, but since s->close() *will* modify
117 ** the list out from under you, your options are limited.
118 */
119 adb_mutex_lock(&socket_list_lock);
120restart:
121 for(s = local_socket_list.next; s != &local_socket_list; s = s->next){
122 if(s->transport == t || (s->peer && s->peer->transport == t)) {
123 local_socket_close_locked(s);
124 goto restart;
125 }
126 }
127 adb_mutex_unlock(&socket_list_lock);
128}
129
130static int local_socket_enqueue(asocket *s, apacket *p)
131{
132 D("LS(%d): enqueue %d\n", s->id, p->len);
133
134 p->ptr = p->data;
135
136 /* if there is already data queue'd, we will receive
137 ** events when it's time to write. just add this to
138 ** the tail
139 */
140 if(s->pkt_first) {
141 goto enqueue;
142 }
143
144 /* write as much as we can, until we
145 ** would block or there is an error/eof
146 */
147 while(p->len > 0) {
148 int r = adb_write(s->fd, p->ptr, p->len);
149 if(r > 0) {
150 p->len -= r;
151 p->ptr += r;
152 continue;
153 }
154 if((r == 0) || (errno != EAGAIN)) {
155 D( "LS(%d): not ready, errno=%d: %s\n", s->id, errno, strerror(errno) );
156 s->close(s);
157 return 1; /* not ready (error) */
158 } else {
159 break;
160 }
161 }
162
163 if(p->len == 0) {
164 put_apacket(p);
165 return 0; /* ready for more data */
166 }
167
168enqueue:
169 p->next = 0;
170 if(s->pkt_first) {
171 s->pkt_last->next = p;
172 } else {
173 s->pkt_first = p;
174 }
175 s->pkt_last = p;
176
177 /* make sure we are notified when we can drain the queue */
178 fdevent_add(&s->fde, FDE_WRITE);
179
180 return 1; /* not ready (backlog) */
181}
182
183static void local_socket_ready(asocket *s)
184{
185 /* far side is ready for data, pay attention to
186 readable events */
187 fdevent_add(&s->fde, FDE_READ);
188// D("LS(%d): ready()\n", s->id);
189}
190
191static void local_socket_close(asocket *s)
192{
193 adb_mutex_lock(&socket_list_lock);
194 local_socket_close_locked(s);
195 adb_mutex_unlock(&socket_list_lock);
196}
197
198// be sure to hold the socket list lock when calling this
199static void local_socket_destroy(asocket *s)
200{
201 apacket *p, *n;
202 D("LS(%d): destroying fde.fd=%d\n", s->id, s->fde.fd);
203
204 /* IMPORTANT: the remove closes the fd
205 ** that belongs to this socket
206 */
207 fdevent_remove(&s->fde);
208
209 /* dispose of any unwritten data */
210 for(p = s->pkt_first; p; p = n) {
211 D("LS(%d): discarding %d bytes\n", s->id, p->len);
212 n = p->next;
213 put_apacket(p);
214 }
215 remove_socket(s);
216 free(s);
217}
218
219
220static void local_socket_close_locked(asocket *s)
221{
222 D("entered. LS(%d) fd=%d\n", s->id, s->fd);
223 if(s->peer) {
224 D("LS(%d): closing peer. peer->id=%d peer->fd=%d\n",
225 s->id, s->peer->id, s->peer->fd);
226 s->peer->peer = 0;
227 // tweak to avoid deadlock
228 if (s->peer->close == local_socket_close) {
229 local_socket_close_locked(s->peer);
230 } else {
231 s->peer->close(s->peer);
232 }
233 s->peer = 0;
234 }
235
236 /* If we are already closing, or if there are no
237 ** pending packets, destroy immediately
238 */
239 if (s->closing || s->pkt_first == NULL) {
240 int id = s->id;
241 local_socket_destroy(s);
242 D("LS(%d): closed\n", id);
243 return;
244 }
245
246 /* otherwise, put on the closing list
247 */
248 D("LS(%d): closing\n", s->id);
249 s->closing = 1;
250 fdevent_del(&s->fde, FDE_READ);
251 remove_socket(s);
252 D("LS(%d): put on socket_closing_list fd=%d\n", s->id, s->fd);
253 insert_local_socket(s, &local_socket_closing_list);
254}
255
256static void local_socket_event_func(int fd, unsigned ev, void *_s)
257{
258 asocket *s = _s;
259
260 D("LS(%d): event_func(fd=%d(==%d), ev=%04x)\n", s->id, s->fd, fd, ev);
261
262 /* put the FDE_WRITE processing before the FDE_READ
263 ** in order to simplify the code.
264 */
265 if(ev & FDE_WRITE){
266 apacket *p;
267
268 while((p = s->pkt_first) != 0) {
269 while(p->len > 0) {
270 int r = adb_write(fd, p->ptr, p->len);
271 if(r > 0) {
272 p->ptr += r;
273 p->len -= r;
274 continue;
275 }
276 if(r < 0) {
277 /* returning here is ok because FDE_READ will
278 ** be processed in the next iteration loop
279 */
280 if(errno == EAGAIN) return;
281 if(errno == EINTR) continue;
282 }
283 D(" closing after write because r=%d and errno is %d\n", r, errno);
284 s->close(s);
285 return;
286 }
287
288 if(p->len == 0) {
289 s->pkt_first = p->next;
290 if(s->pkt_first == 0) s->pkt_last = 0;
291 put_apacket(p);
292 }
293 }
294
295 /* if we sent the last packet of a closing socket,
296 ** we can now destroy it.
297 */
298 if (s->closing) {
299 D(" closing because 'closing' is set after write\n");
300 s->close(s);
301 return;
302 }
303
304 /* no more packets queued, so we can ignore
305 ** writable events again and tell our peer
306 ** to resume writing
307 */
308 fdevent_del(&s->fde, FDE_WRITE);
309 s->peer->ready(s->peer);
310 }
311
312
313 if(ev & FDE_READ){
314 apacket *p = get_apacket();
315 unsigned char *x = p->data;
316 size_t avail = MAX_PAYLOAD;
317 int r;
318 int is_eof = 0;
319
320 while(avail > 0) {
321 r = adb_read(fd, x, avail);
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700322 D("LS(%d): post adb_read(fd=%d,...) r=%d (errno=%d) avail=%zu\n",
323 s->id, s->fd, r, r<0?errno:0, avail);
Doug Zongker9270a202012-01-09 15:16:13 -0800324 if(r > 0) {
325 avail -= r;
326 x += r;
327 continue;
328 }
329 if(r < 0) {
330 if(errno == EAGAIN) break;
331 if(errno == EINTR) continue;
332 }
333
334 /* r = 0 or unhandled error */
335 is_eof = 1;
336 break;
337 }
338 D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d\n",
339 s->id, s->fd, r, is_eof, s->fde.force_eof);
340 if((avail == MAX_PAYLOAD) || (s->peer == 0)) {
341 put_apacket(p);
342 } else {
343 p->len = MAX_PAYLOAD - avail;
344
345 r = s->peer->enqueue(s->peer, p);
346 D("LS(%d): fd=%d post peer->enqueue(). r=%d\n", s->id, s->fd, r);
347
348 if(r < 0) {
349 /* error return means they closed us as a side-effect
350 ** and we must return immediately.
351 **
352 ** note that if we still have buffered packets, the
353 ** socket will be placed on the closing socket list.
354 ** this handler function will be called again
355 ** to process FDE_WRITE events.
356 */
357 return;
358 }
359
360 if(r > 0) {
361 /* if the remote cannot accept further events,
362 ** we disable notification of READs. They'll
363 ** be enabled again when we get a call to ready()
364 */
365 fdevent_del(&s->fde, FDE_READ);
366 }
367 }
368 /* Don't allow a forced eof if data is still there */
369 if((s->fde.force_eof && !r) || is_eof) {
370 D(" closing because is_eof=%d r=%d s->fde.force_eof=%d\n", is_eof, r, s->fde.force_eof);
371 s->close(s);
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// s->close(s);
381 D("LS(%d): FDE_ERROR (fd=%d)\n", s->id, s->fd);
382
383 return;
384 }
385}
386
387asocket *create_local_socket(int fd)
388{
389 asocket *s = calloc(1, sizeof(asocket));
390 if (s == NULL) fatal("cannot allocate socket");
391 s->fd = fd;
392 s->enqueue = local_socket_enqueue;
393 s->ready = local_socket_ready;
394 s->close = local_socket_close;
395 install_local_socket(s);
396
397 fdevent_install(&s->fde, fd, local_socket_event_func, s);
398/* fdevent_add(&s->fde, FDE_ERROR); */
399 //fprintf(stderr, "Created local socket in create_local_socket \n");
400 D("LS(%d): created (fd=%d)\n", s->id, s->fd);
401 return s;
402}
403
404asocket *create_local_service_socket(const char *name)
405{
406 asocket *s;
407 int fd;
408
409 fd = service_to_fd(name);
410 if(fd < 0) return 0;
411
412 s = create_local_socket(fd);
413 D("LS(%d): bound to '%s' via %d\n", s->id, name, fd);
414 return s;
415}
416
Doug Zongker9270a202012-01-09 15:16:13 -0800417/* a Remote socket is used to send/receive data to/from a given transport object
418** it needs to be closed when the transport is forcibly destroyed by the user
419*/
420typedef struct aremotesocket {
421 asocket socket;
422 adisconnect disconnect;
423} aremotesocket;
424
425static int remote_socket_enqueue(asocket *s, apacket *p)
426{
427 D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d\n",
428 s->id, s->fd, s->peer->fd);
429 p->msg.command = A_WRTE;
430 p->msg.arg0 = s->peer->id;
431 p->msg.arg1 = s->id;
432 p->msg.data_length = p->len;
433 send_packet(p, s->transport);
434 return 1;
435}
436
437static void remote_socket_ready(asocket *s)
438{
439 D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d\n",
440 s->id, s->fd, s->peer->fd);
441 apacket *p = get_apacket();
442 p->msg.command = A_OKAY;
443 p->msg.arg0 = s->peer->id;
444 p->msg.arg1 = s->id;
445 send_packet(p, s->transport);
446}
447
448static void remote_socket_close(asocket *s)
449{
450 D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d\n",
451 s->id, s->fd, s->peer?s->peer->fd:-1);
452 apacket *p = get_apacket();
453 p->msg.command = A_CLSE;
454 if(s->peer) {
455 p->msg.arg0 = s->peer->id;
456 s->peer->peer = 0;
457 D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d\n",
458 s->id, s->peer->id, s->peer->fd);
459 s->peer->close(s->peer);
460 }
461 p->msg.arg1 = s->id;
462 send_packet(p, s->transport);
463 D("RS(%d): closed\n", s->id);
464 remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
465 free(s);
466}
467
468static void remote_socket_disconnect(void* _s, atransport* t)
469{
470 asocket* s = _s;
471 asocket* peer = s->peer;
472
473 D("remote_socket_disconnect RS(%d)\n", s->id);
474 if (peer) {
475 peer->peer = NULL;
476 peer->close(peer);
477 }
478 remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
479 free(s);
480}
481
482asocket *create_remote_socket(unsigned id, atransport *t)
483{
484 asocket *s = calloc(1, sizeof(aremotesocket));
485 adisconnect* dis = &((aremotesocket*)s)->disconnect;
486
487 if (s == NULL) fatal("cannot allocate socket");
488 s->id = id;
489 s->enqueue = remote_socket_enqueue;
490 s->ready = remote_socket_ready;
491 s->close = remote_socket_close;
492 s->transport = t;
493
494 dis->func = remote_socket_disconnect;
495 dis->opaque = s;
496 add_transport_disconnect( t, dis );
497 D("RS(%d): created\n", s->id);
498 return s;
499}
500
501void connect_to_remote(asocket *s, const char *destination)
502{
503 D("Connect_to_remote call RS(%d) fd=%d\n", s->id, s->fd);
504 apacket *p = get_apacket();
505 int len = strlen(destination) + 1;
506
507 if(len > (MAX_PAYLOAD-1)) {
508 fatal("destination oversized");
509 }
510
511 D("LS(%d): connect('%s')\n", s->id, destination);
512 p->msg.command = A_OPEN;
513 p->msg.arg0 = s->id;
514 p->msg.data_length = len;
515 strcpy((char*) p->data, destination);
516 send_packet(p, s->transport);
517}
518
519
520/* this is used by magic sockets to rig local sockets to
521 send the go-ahead message when they connect */
522static void local_socket_ready_notify(asocket *s)
523{
524 s->ready = local_socket_ready;
525 s->close = local_socket_close;
526 adb_write(s->fd, "OKAY", 4);
527 s->ready(s);
528}
529
530/* this is used by magic sockets to rig local sockets to
531 send the failure message if they are closed before
532 connected (to avoid closing them without a status message) */
533static void local_socket_close_notify(asocket *s)
534{
535 s->ready = local_socket_ready;
536 s->close = local_socket_close;
537 sendfailmsg(s->fd, "closed");
538 s->close(s);
539}
540
541unsigned unhex(unsigned char *s, int len)
542{
543 unsigned n = 0, c;
544
545 while(len-- > 0) {
546 switch((c = *s++)) {
547 case '0': case '1': case '2':
548 case '3': case '4': case '5':
549 case '6': case '7': case '8':
550 case '9':
551 c -= '0';
552 break;
553 case 'a': case 'b': case 'c':
554 case 'd': case 'e': case 'f':
555 c = c - 'a' + 10;
556 break;
557 case 'A': case 'B': case 'C':
558 case 'D': case 'E': case 'F':
559 c = c - 'A' + 10;
560 break;
561 default:
562 return 0xffffffff;
563 }
564
565 n = (n << 4) | c;
566 }
567
568 return n;
569}
570
571/* skip_host_serial return the position in a string
572 skipping over the 'serial' parameter in the ADB protocol,
573 where parameter string may be a host:port string containing
574 the protocol delimiter (colon). */
575char *skip_host_serial(char *service) {
576 char *first_colon, *serial_end;
577
578 first_colon = strchr(service, ':');
579 if (!first_colon) {
580 /* No colon in service string. */
581 return NULL;
582 }
583 serial_end = first_colon;
584 if (isdigit(serial_end[1])) {
585 serial_end++;
586 while ((*serial_end) && isdigit(*serial_end)) {
587 serial_end++;
588 }
589 if ((*serial_end) != ':') {
590 // Something other than numbers was found, reset the end.
591 serial_end = first_colon;
592 }
593 }
594 return serial_end;
595}
596
597static int smart_socket_enqueue(asocket *s, apacket *p)
598{
599 unsigned len;
Doug Zongker9270a202012-01-09 15:16:13 -0800600
601 D("SS(%d): enqueue %d\n", s->id, p->len);
602
603 if(s->pkt_first == 0) {
604 s->pkt_first = p;
605 s->pkt_last = p;
606 } else {
607 if((s->pkt_first->len + p->len) > MAX_PAYLOAD) {
608 D("SS(%d): overflow\n", s->id);
609 put_apacket(p);
610 goto fail;
611 }
612
613 memcpy(s->pkt_first->data + s->pkt_first->len,
614 p->data, p->len);
615 s->pkt_first->len += p->len;
616 put_apacket(p);
617
618 p = s->pkt_first;
619 }
620
621 /* don't bother if we can't decode the length */
622 if(p->len < 4) return 0;
623
624 len = unhex(p->data, 4);
625 if((len < 1) || (len > 1024)) {
626 D("SS(%d): bad size (%d)\n", s->id, len);
627 goto fail;
628 }
629
630 D("SS(%d): len is %d\n", s->id, len );
631 /* can't do anything until we have the full header */
632 if((len + 4) > p->len) {
633 D("SS(%d): waiting for %d more bytes\n", s->id, len+4 - p->len);
634 return 0;
635 }
636
637 p->data[len + 4] = 0;
638
639 D("SS(%d): '%s'\n", s->id, (char*) (p->data + 4));
640
Doug Zongker9270a202012-01-09 15:16:13 -0800641 if (s->transport == NULL) {
642 char* error_string = "unknown failure";
643 s->transport = acquire_one_transport (CS_ANY,
644 kTransportAny, NULL, &error_string);
645
646 if (s->transport == NULL) {
647 sendfailmsg(s->peer->fd, error_string);
648 goto fail;
649 }
650 }
Doug Zongker9270a202012-01-09 15:16:13 -0800651
652 if(!(s->transport) || (s->transport->connection_state == CS_OFFLINE)) {
653 /* if there's no remote we fail the connection
654 ** right here and terminate it
655 */
656 sendfailmsg(s->peer->fd, "device offline (x)");
657 goto fail;
658 }
659
660
661 /* instrument our peer to pass the success or fail
662 ** message back once it connects or closes, then
663 ** detach from it, request the connection, and
664 ** tear down
665 */
666 s->peer->ready = local_socket_ready_notify;
667 s->peer->close = local_socket_close_notify;
668 s->peer->peer = 0;
669 /* give him our transport and upref it */
670 s->peer->transport = s->transport;
671
672 connect_to_remote(s->peer, (char*) (p->data + 4));
673 s->peer = 0;
674 s->close(s);
675 return 1;
676
677fail:
678 /* we're going to close our peer as a side-effect, so
679 ** return -1 to signal that state to the local socket
680 ** who is enqueueing against us
681 */
682 s->close(s);
683 return -1;
684}
685
686static void smart_socket_ready(asocket *s)
687{
688 D("SS(%d): ready\n", s->id);
689}
690
691static void smart_socket_close(asocket *s)
692{
693 D("SS(%d): closed\n", s->id);
694 if(s->pkt_first){
695 put_apacket(s->pkt_first);
696 }
697 if(s->peer) {
698 s->peer->peer = 0;
699 s->peer->close(s->peer);
700 s->peer = 0;
701 }
702 free(s);
703}
704
705asocket *create_smart_socket(void (*action_cb)(asocket *s, const char *act))
706{
707 D("Creating smart socket \n");
708 asocket *s = calloc(1, sizeof(asocket));
709 if (s == NULL) fatal("cannot allocate socket");
710 s->enqueue = smart_socket_enqueue;
711 s->ready = smart_socket_ready;
712 s->close = smart_socket_close;
713 s->extra = action_cb;
714
715 D("SS(%d): created %p\n", s->id, action_cb);
716 return s;
717}
718
719void smart_socket_action(asocket *s, const char *act)
720{
721
722}
723
724void connect_to_smartsocket(asocket *s)
725{
726 D("Connecting to smart socket \n");
727 asocket *ss = create_smart_socket(smart_socket_action);
728 s->peer = ss;
729 ss->peer = s;
730 s->ready(s);
731}