• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #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 
29 ADB_MUTEX_DEFINE( socket_list_lock );
30 
31 static void local_socket_close_locked(asocket *s);
32 
sendfailmsg(int fd,const char * reason)33 int 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 
46 static unsigned local_socket_next_id = 1;
47 
48 static 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 */
57 static asocket local_socket_closing_list = {
58     .next = &local_socket_closing_list,
59     .prev = &local_socket_closing_list,
60 };
61 
find_local_socket(unsigned id)62 asocket *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 
79 static void
insert_local_socket(asocket * s,asocket * list)80 insert_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 
install_local_socket(asocket * s)89 void 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 
remove_socket(asocket * s)99 void 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 
close_all_sockets(atransport * t)112 void 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);
120 restart:
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 
local_socket_enqueue(asocket * s,apacket * p)130 static 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 
168 enqueue:
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 
local_socket_ready(asocket * s)183 static 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 
local_socket_close(asocket * s)191 static 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
local_socket_destroy(asocket * s)199 static 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 
local_socket_close_locked(asocket * s)220 static 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 
local_socket_event_func(int fd,unsigned ev,void * _s)256 static 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);
322             D("LS(%d): post adb_read(fd=%d,...) r=%d (errno=%d) avail=%d\n", s->id, s->fd, r, r<0?errno:0, avail);
323             if(r > 0) {
324                 avail -= r;
325                 x += r;
326                 continue;
327             }
328             if(r < 0) {
329                 if(errno == EAGAIN) break;
330                 if(errno == EINTR) continue;
331             }
332 
333                 /* r = 0 or unhandled error */
334             is_eof = 1;
335             break;
336         }
337         D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d\n",
338           s->id, s->fd, r, is_eof, s->fde.force_eof);
339         if((avail == MAX_PAYLOAD) || (s->peer == 0)) {
340             put_apacket(p);
341         } else {
342             p->len = MAX_PAYLOAD - avail;
343 
344             r = s->peer->enqueue(s->peer, p);
345             D("LS(%d): fd=%d post peer->enqueue(). r=%d\n", s->id, s->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\n", is_eof, r, s->fde.force_eof);
370             s->close(s);
371         }
372     }
373 
374     if(ev & FDE_ERROR){
375             /* this should be caught be the next read or write
376             ** catching it here means we may skip the last few
377             ** bytes of readable data.
378             */
379 //        s->close(s);
380         D("LS(%d): FDE_ERROR (fd=%d)\n", s->id, s->fd);
381 
382         return;
383     }
384 }
385 
create_local_socket(int fd)386 asocket *create_local_socket(int fd)
387 {
388     asocket *s = calloc(1, sizeof(asocket));
389     if (s == NULL) fatal("cannot allocate socket");
390     s->fd = fd;
391     s->enqueue = local_socket_enqueue;
392     s->ready = local_socket_ready;
393     s->close = local_socket_close;
394     install_local_socket(s);
395 
396     fdevent_install(&s->fde, fd, local_socket_event_func, s);
397 /*    fdevent_add(&s->fde, FDE_ERROR); */
398     //fprintf(stderr, "Created local socket in create_local_socket \n");
399     D("LS(%d): created (fd=%d)\n", s->id, s->fd);
400     return s;
401 }
402 
create_local_service_socket(const char * name)403 asocket *create_local_service_socket(const char *name)
404 {
405     asocket *s;
406     int fd;
407 
408     fd = service_to_fd(name);
409     if(fd < 0) return 0;
410 
411     s = create_local_socket(fd);
412     D("LS(%d): bound to '%s' via %d\n", s->id, name, fd);
413     return s;
414 }
415 
416 /* a Remote socket is used to send/receive data to/from a given transport object
417 ** it needs to be closed when the transport is forcibly destroyed by the user
418 */
419 typedef struct aremotesocket {
420     asocket      socket;
421     adisconnect  disconnect;
422 } aremotesocket;
423 
remote_socket_enqueue(asocket * s,apacket * p)424 static int remote_socket_enqueue(asocket *s, apacket *p)
425 {
426     D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d\n",
427       s->id, s->fd, s->peer->fd);
428     p->msg.command = A_WRTE;
429     p->msg.arg0 = s->peer->id;
430     p->msg.arg1 = s->id;
431     p->msg.data_length = p->len;
432     send_packet(p, s->transport);
433     return 1;
434 }
435 
remote_socket_ready(asocket * s)436 static void remote_socket_ready(asocket *s)
437 {
438     D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d\n",
439       s->id, s->fd, s->peer->fd);
440     apacket *p = get_apacket();
441     p->msg.command = A_OKAY;
442     p->msg.arg0 = s->peer->id;
443     p->msg.arg1 = s->id;
444     send_packet(p, s->transport);
445 }
446 
remote_socket_close(asocket * s)447 static void remote_socket_close(asocket *s)
448 {
449     D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d\n",
450       s->id, s->fd, s->peer?s->peer->fd:-1);
451     apacket *p = get_apacket();
452     p->msg.command = A_CLSE;
453     if(s->peer) {
454         p->msg.arg0 = s->peer->id;
455         s->peer->peer = 0;
456         D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d\n",
457           s->id, s->peer->id, s->peer->fd);
458         s->peer->close(s->peer);
459     }
460     p->msg.arg1 = s->id;
461     send_packet(p, s->transport);
462     D("RS(%d): closed\n", s->id);
463     remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
464     free(s);
465 }
466 
remote_socket_disconnect(void * _s,atransport * t)467 static void remote_socket_disconnect(void*  _s, atransport*  t)
468 {
469     asocket*  s    = _s;
470     asocket*  peer = s->peer;
471 
472     D("remote_socket_disconnect RS(%d)\n", s->id);
473     if (peer) {
474         peer->peer = NULL;
475         peer->close(peer);
476     }
477     remove_transport_disconnect( s->transport, &((aremotesocket*)s)->disconnect );
478     free(s);
479 }
480 
create_remote_socket(unsigned id,atransport * t)481 asocket *create_remote_socket(unsigned id, atransport *t)
482 {
483     asocket *s = calloc(1, sizeof(aremotesocket));
484     adisconnect*  dis = &((aremotesocket*)s)->disconnect;
485 
486     if (s == NULL) fatal("cannot allocate socket");
487     s->id = id;
488     s->enqueue = remote_socket_enqueue;
489     s->ready = remote_socket_ready;
490     s->close = remote_socket_close;
491     s->transport = t;
492 
493     dis->func   = remote_socket_disconnect;
494     dis->opaque = s;
495     add_transport_disconnect( t, dis );
496     D("RS(%d): created\n", s->id);
497     return s;
498 }
499 
connect_to_remote(asocket * s,const char * destination)500 void connect_to_remote(asocket *s, const char *destination)
501 {
502     D("Connect_to_remote call RS(%d) fd=%d\n", s->id, s->fd);
503     apacket *p = get_apacket();
504     int len = strlen(destination) + 1;
505 
506     if(len > (MAX_PAYLOAD-1)) {
507         fatal("destination oversized");
508     }
509 
510     D("LS(%d): connect('%s')\n", s->id, destination);
511     p->msg.command = A_OPEN;
512     p->msg.arg0 = s->id;
513     p->msg.data_length = len;
514     strcpy((char*) p->data, destination);
515     send_packet(p, s->transport);
516 }
517 
518 
519 /* this is used by magic sockets to rig local sockets to
520    send the go-ahead message when they connect */
local_socket_ready_notify(asocket * s)521 static void local_socket_ready_notify(asocket *s)
522 {
523     s->ready = local_socket_ready;
524     s->close = local_socket_close;
525     adb_write(s->fd, "OKAY", 4);
526     s->ready(s);
527 }
528 
529 /* this is used by magic sockets to rig local sockets to
530    send the failure message if they are closed before
531    connected (to avoid closing them without a status message) */
local_socket_close_notify(asocket * s)532 static void local_socket_close_notify(asocket *s)
533 {
534     s->ready = local_socket_ready;
535     s->close = local_socket_close;
536     sendfailmsg(s->fd, "closed");
537     s->close(s);
538 }
539 
unhex(unsigned char * s,int len)540 unsigned unhex(unsigned char *s, int len)
541 {
542     unsigned n = 0, c;
543 
544     while(len-- > 0) {
545         switch((c = *s++)) {
546         case '0': case '1': case '2':
547         case '3': case '4': case '5':
548         case '6': case '7': case '8':
549         case '9':
550             c -= '0';
551             break;
552         case 'a': case 'b': case 'c':
553         case 'd': case 'e': case 'f':
554             c = c - 'a' + 10;
555             break;
556         case 'A': case 'B': case 'C':
557         case 'D': case 'E': case 'F':
558             c = c - 'A' + 10;
559             break;
560         default:
561             return 0xffffffff;
562         }
563 
564         n = (n << 4) | c;
565     }
566 
567     return n;
568 }
569 
570 /* skip_host_serial return the position in a string
571    skipping over the 'serial' parameter in the ADB protocol,
572    where parameter string may be a host:port string containing
573    the protocol delimiter (colon). */
skip_host_serial(char * service)574 char *skip_host_serial(char *service) {
575     char *first_colon, *serial_end;
576 
577     first_colon = strchr(service, ':');
578     if (!first_colon) {
579         /* No colon in service string. */
580         return NULL;
581     }
582     serial_end = first_colon;
583     if (isdigit(serial_end[1])) {
584         serial_end++;
585         while ((*serial_end) && isdigit(*serial_end)) {
586             serial_end++;
587         }
588         if ((*serial_end) != ':') {
589             // Something other than numbers was found, reset the end.
590             serial_end = first_colon;
591         }
592     }
593     return serial_end;
594 }
595 
smart_socket_enqueue(asocket * s,apacket * p)596 static int smart_socket_enqueue(asocket *s, apacket *p)
597 {
598     unsigned len;
599 
600     D("SS(%d): enqueue %d\n", s->id, p->len);
601 
602     if(s->pkt_first == 0) {
603         s->pkt_first = p;
604         s->pkt_last = p;
605     } else {
606         if((s->pkt_first->len + p->len) > MAX_PAYLOAD) {
607             D("SS(%d): overflow\n", s->id);
608             put_apacket(p);
609             goto fail;
610         }
611 
612         memcpy(s->pkt_first->data + s->pkt_first->len,
613                p->data, p->len);
614         s->pkt_first->len += p->len;
615         put_apacket(p);
616 
617         p = s->pkt_first;
618     }
619 
620         /* don't bother if we can't decode the length */
621     if(p->len < 4) return 0;
622 
623     len = unhex(p->data, 4);
624     if((len < 1) ||  (len > 1024)) {
625         D("SS(%d): bad size (%d)\n", s->id, len);
626         goto fail;
627     }
628 
629     D("SS(%d): len is %d\n", s->id, len );
630         /* can't do anything until we have the full header */
631     if((len + 4) > p->len) {
632         D("SS(%d): waiting for %d more bytes\n", s->id, len+4 - p->len);
633         return 0;
634     }
635 
636     p->data[len + 4] = 0;
637 
638     D("SS(%d): '%s'\n", s->id, (char*) (p->data + 4));
639 
640     if (s->transport == NULL) {
641         char* error_string = "unknown failure";
642         s->transport = acquire_one_transport (CS_ANY,
643                 kTransportAny, NULL, &error_string);
644 
645         if (s->transport == NULL) {
646             sendfailmsg(s->peer->fd, error_string);
647             goto fail;
648         }
649     }
650 
651     if(!(s->transport) || (s->transport->connection_state == CS_OFFLINE)) {
652            /* if there's no remote we fail the connection
653             ** right here and terminate it
654             */
655         sendfailmsg(s->peer->fd, "device offline (x)");
656         goto fail;
657     }
658 
659 
660         /* instrument our peer to pass the success or fail
661         ** message back once it connects or closes, then
662         ** detach from it, request the connection, and
663         ** tear down
664         */
665     s->peer->ready = local_socket_ready_notify;
666     s->peer->close = local_socket_close_notify;
667     s->peer->peer = 0;
668         /* give him our transport and upref it */
669     s->peer->transport = s->transport;
670 
671     connect_to_remote(s->peer, (char*) (p->data + 4));
672     s->peer = 0;
673     s->close(s);
674     return 1;
675 
676 fail:
677         /* we're going to close our peer as a side-effect, so
678         ** return -1 to signal that state to the local socket
679         ** who is enqueueing against us
680         */
681     s->close(s);
682     return -1;
683 }
684 
smart_socket_ready(asocket * s)685 static void smart_socket_ready(asocket *s)
686 {
687     D("SS(%d): ready\n", s->id);
688 }
689 
smart_socket_close(asocket * s)690 static void smart_socket_close(asocket *s)
691 {
692     D("SS(%d): closed\n", s->id);
693     if(s->pkt_first){
694         put_apacket(s->pkt_first);
695     }
696     if(s->peer) {
697         s->peer->peer = 0;
698         s->peer->close(s->peer);
699         s->peer = 0;
700     }
701     free(s);
702 }
703 
create_smart_socket(void (* action_cb)(asocket * s,const char * act))704 asocket *create_smart_socket(void (*action_cb)(asocket *s, const char *act))
705 {
706     D("Creating smart socket \n");
707     asocket *s = calloc(1, sizeof(asocket));
708     if (s == NULL) fatal("cannot allocate socket");
709     s->enqueue = smart_socket_enqueue;
710     s->ready = smart_socket_ready;
711     s->close = smart_socket_close;
712     s->extra = action_cb;
713 
714     D("SS(%d): created %p\n", s->id, action_cb);
715     return s;
716 }
717 
smart_socket_action(asocket * s,const char * act)718 void smart_socket_action(asocket *s, const char *act)
719 {
720 
721 }
722 
connect_to_smartsocket(asocket * s)723 void connect_to_smartsocket(asocket *s)
724 {
725     D("Connecting to smart socket \n");
726     asocket *ss = create_smart_socket(smart_socket_action);
727     s->peer = ss;
728     ss->peer = s;
729     s->ready(s);
730 }
731