• 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 #define  TRACE_TAG   TRACE_ADB
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <ctype.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/time.h>
27 
28 #include "sysdeps.h"
29 #include "adb.h"
30 
31 #if !ADB_HOST
32 #include <private/android_filesystem_config.h>
33 #include <linux/capability.h>
34 #include <linux/prctl.h>
35 #else
36 #include "usb_vendors.h"
37 #endif
38 
39 
40 int HOST = 0;
41 
42 static const char *adb_device_banner = "device";
43 
fatal(const char * fmt,...)44 void fatal(const char *fmt, ...)
45 {
46     va_list ap;
47     va_start(ap, fmt);
48     fprintf(stderr, "error: ");
49     vfprintf(stderr, fmt, ap);
50     fprintf(stderr, "\n");
51     va_end(ap);
52     exit(-1);
53 }
54 
fatal_errno(const char * fmt,...)55 void fatal_errno(const char *fmt, ...)
56 {
57     va_list ap;
58     va_start(ap, fmt);
59     fprintf(stderr, "error: %s: ", strerror(errno));
60     vfprintf(stderr, fmt, ap);
61     fprintf(stderr, "\n");
62     va_end(ap);
63     exit(-1);
64 }
65 
66 int   adb_trace_mask;
67 
68 /* read a comma/space/colum/semi-column separated list of tags
69  * from the ADB_TRACE environment variable and build the trace
70  * mask from it. note that '1' and 'all' are special cases to
71  * enable all tracing
72  */
adb_trace_init(void)73 void  adb_trace_init(void)
74 {
75     const char*  p = getenv("ADB_TRACE");
76     const char*  q;
77 
78     static const struct {
79         const char*  tag;
80         int           flag;
81     } tags[] = {
82         { "1", 0 },
83         { "all", 0 },
84         { "adb", TRACE_ADB },
85         { "sockets", TRACE_SOCKETS },
86         { "packets", TRACE_PACKETS },
87         { "rwx", TRACE_RWX },
88         { "usb", TRACE_USB },
89         { "sync", TRACE_SYNC },
90         { "sysdeps", TRACE_SYSDEPS },
91         { "transport", TRACE_TRANSPORT },
92         { "jdwp", TRACE_JDWP },
93         { NULL, 0 }
94     };
95 
96     if (p == NULL)
97             return;
98 
99     /* use a comma/column/semi-colum/space separated list */
100     while (*p) {
101         int  len, tagn;
102 
103         q = strpbrk(p, " ,:;");
104         if (q == NULL) {
105             q = p + strlen(p);
106         }
107         len = q - p;
108 
109         for (tagn = 0; tags[tagn].tag != NULL; tagn++)
110         {
111             int  taglen = strlen(tags[tagn].tag);
112 
113             if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
114             {
115                 int  flag = tags[tagn].flag;
116                 if (flag == 0) {
117                     adb_trace_mask = ~0;
118                     return;
119                 }
120                 adb_trace_mask |= (1 << flag);
121                 break;
122             }
123         }
124         p = q;
125         if (*p)
126             p++;
127     }
128 }
129 
130 
get_apacket(void)131 apacket *get_apacket(void)
132 {
133     apacket *p = malloc(sizeof(apacket));
134     if(p == 0) fatal("failed to allocate an apacket");
135     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
136     return p;
137 }
138 
put_apacket(apacket * p)139 void put_apacket(apacket *p)
140 {
141     free(p);
142 }
143 
handle_online(void)144 void handle_online(void)
145 {
146     D("adb: online\n");
147 #if !ADB_HOST
148     property_set("adb.connected","1");
149 #endif
150 }
151 
handle_offline(atransport * t)152 void handle_offline(atransport *t)
153 {
154     D("adb: offline\n");
155     //Close the associated usb
156     run_transport_disconnects(t);
157 #if !ADB_HOST
158     property_set("adb.connected","");
159 #endif
160 }
161 
162 #if TRACE_PACKETS
163 #define DUMPMAX 32
print_packet(const char * label,apacket * p)164 void print_packet(const char *label, apacket *p)
165 {
166     char *tag;
167     char *x;
168     unsigned count;
169 
170     switch(p->msg.command){
171     case A_SYNC: tag = "SYNC"; break;
172     case A_CNXN: tag = "CNXN" ; break;
173     case A_OPEN: tag = "OPEN"; break;
174     case A_OKAY: tag = "OKAY"; break;
175     case A_CLSE: tag = "CLSE"; break;
176     case A_WRTE: tag = "WRTE"; break;
177     default: tag = "????"; break;
178     }
179 
180     fprintf(stderr, "%s: %s %08x %08x %04x \"",
181             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
182     count = p->msg.data_length;
183     x = (char*) p->data;
184     if(count > DUMPMAX) {
185         count = DUMPMAX;
186         tag = "\n";
187     } else {
188         tag = "\"\n";
189     }
190     while(count-- > 0){
191         if((*x >= ' ') && (*x < 127)) {
192             fputc(*x, stderr);
193         } else {
194             fputc('.', stderr);
195         }
196         x++;
197     }
198     fprintf(stderr, tag);
199 }
200 #endif
201 
send_ready(unsigned local,unsigned remote,atransport * t)202 static void send_ready(unsigned local, unsigned remote, atransport *t)
203 {
204     D("Calling send_ready \n");
205     apacket *p = get_apacket();
206     p->msg.command = A_OKAY;
207     p->msg.arg0 = local;
208     p->msg.arg1 = remote;
209     send_packet(p, t);
210 }
211 
send_close(unsigned local,unsigned remote,atransport * t)212 static void send_close(unsigned local, unsigned remote, atransport *t)
213 {
214     D("Calling send_close \n");
215     apacket *p = get_apacket();
216     p->msg.command = A_CLSE;
217     p->msg.arg0 = local;
218     p->msg.arg1 = remote;
219     send_packet(p, t);
220 }
221 
send_connect(atransport * t)222 static void send_connect(atransport *t)
223 {
224     D("Calling send_connect \n");
225     apacket *cp = get_apacket();
226     cp->msg.command = A_CNXN;
227     cp->msg.arg0 = A_VERSION;
228     cp->msg.arg1 = MAX_PAYLOAD;
229     snprintf((char*) cp->data, sizeof cp->data, "%s::",
230             HOST ? "host" : adb_device_banner);
231     cp->msg.data_length = strlen((char*) cp->data) + 1;
232     send_packet(cp, t);
233 #if ADB_HOST
234         /* XXX why sleep here? */
235     // allow the device some time to respond to the connect message
236     adb_sleep_ms(1000);
237 #endif
238 }
239 
connection_state_name(atransport * t)240 static char *connection_state_name(atransport *t)
241 {
242     if (t == NULL) {
243         return "unknown";
244     }
245 
246     switch(t->connection_state) {
247     case CS_BOOTLOADER:
248         return "bootloader";
249     case CS_DEVICE:
250         return "device";
251     case CS_OFFLINE:
252         return "offline";
253     default:
254         return "unknown";
255     }
256 }
257 
parse_banner(char * banner,atransport * t)258 void parse_banner(char *banner, atransport *t)
259 {
260     char *type, *product, *end;
261 
262     D("parse_banner: %s\n", banner);
263     type = banner;
264     product = strchr(type, ':');
265     if(product) {
266         *product++ = 0;
267     } else {
268         product = "";
269     }
270 
271         /* remove trailing ':' */
272     end = strchr(product, ':');
273     if(end) *end = 0;
274 
275         /* save product name in device structure */
276     if (t->product == NULL) {
277         t->product = strdup(product);
278     } else if (strcmp(product, t->product) != 0) {
279         free(t->product);
280         t->product = strdup(product);
281     }
282 
283     if(!strcmp(type, "bootloader")){
284         D("setting connection_state to CS_BOOTLOADER\n");
285         t->connection_state = CS_BOOTLOADER;
286         update_transports();
287         return;
288     }
289 
290     if(!strcmp(type, "device")) {
291         D("setting connection_state to CS_DEVICE\n");
292         t->connection_state = CS_DEVICE;
293         update_transports();
294         return;
295     }
296 
297     if(!strcmp(type, "recovery")) {
298         D("setting connection_state to CS_RECOVERY\n");
299         t->connection_state = CS_RECOVERY;
300         update_transports();
301         return;
302     }
303 
304     t->connection_state = CS_HOST;
305 }
306 
handle_packet(apacket * p,atransport * t)307 void handle_packet(apacket *p, atransport *t)
308 {
309     asocket *s;
310 
311     D("handle_packet() %d\n", p->msg.command);
312 
313     print_packet("recv", p);
314 
315     switch(p->msg.command){
316     case A_SYNC:
317         if(p->msg.arg0){
318             send_packet(p, t);
319             if(HOST) send_connect(t);
320         } else {
321             t->connection_state = CS_OFFLINE;
322             handle_offline(t);
323             send_packet(p, t);
324         }
325         return;
326 
327     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
328             /* XXX verify version, etc */
329         if(t->connection_state != CS_OFFLINE) {
330             t->connection_state = CS_OFFLINE;
331             handle_offline(t);
332         }
333         parse_banner((char*) p->data, t);
334         handle_online();
335         if(!HOST) send_connect(t);
336         break;
337 
338     case A_OPEN: /* OPEN(local-id, 0, "destination") */
339         if(t->connection_state != CS_OFFLINE) {
340             char *name = (char*) p->data;
341             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
342             s = create_local_service_socket(name);
343             if(s == 0) {
344                 send_close(0, p->msg.arg0, t);
345             } else {
346                 s->peer = create_remote_socket(p->msg.arg0, t);
347                 s->peer->peer = s;
348                 send_ready(s->id, s->peer->id, t);
349                 s->ready(s);
350             }
351         }
352         break;
353 
354     case A_OKAY: /* READY(local-id, remote-id, "") */
355         if(t->connection_state != CS_OFFLINE) {
356             if((s = find_local_socket(p->msg.arg1))) {
357                 if(s->peer == 0) {
358                     s->peer = create_remote_socket(p->msg.arg0, t);
359                     s->peer->peer = s;
360                 }
361                 s->ready(s);
362             }
363         }
364         break;
365 
366     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
367         if(t->connection_state != CS_OFFLINE) {
368             if((s = find_local_socket(p->msg.arg1))) {
369                 s->close(s);
370             }
371         }
372         break;
373 
374     case A_WRTE:
375         if(t->connection_state != CS_OFFLINE) {
376             if((s = find_local_socket(p->msg.arg1))) {
377                 unsigned rid = p->msg.arg0;
378                 p->len = p->msg.data_length;
379 
380                 if(s->enqueue(s, p) == 0) {
381                     D("Enqueue the socket\n");
382                     send_ready(s->id, rid, t);
383                 }
384                 return;
385             }
386         }
387         break;
388 
389     default:
390         printf("handle_packet: what is %08x?!\n", p->msg.command);
391     }
392 
393     put_apacket(p);
394 }
395 
396 alistener listener_list = {
397     .next = &listener_list,
398     .prev = &listener_list,
399 };
400 
ss_listener_event_func(int _fd,unsigned ev,void * _l)401 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
402 {
403     asocket *s;
404 
405     if(ev & FDE_READ) {
406         struct sockaddr addr;
407         socklen_t alen;
408         int fd;
409 
410         alen = sizeof(addr);
411         fd = adb_socket_accept(_fd, &addr, &alen);
412         if(fd < 0) return;
413 
414         adb_socket_setbufsize(fd, CHUNK_SIZE);
415 
416         s = create_local_socket(fd);
417         if(s) {
418             connect_to_smartsocket(s);
419             return;
420         }
421 
422         adb_close(fd);
423     }
424 }
425 
listener_event_func(int _fd,unsigned ev,void * _l)426 static void listener_event_func(int _fd, unsigned ev, void *_l)
427 {
428     alistener *l = _l;
429     asocket *s;
430 
431     if(ev & FDE_READ) {
432         struct sockaddr addr;
433         socklen_t alen;
434         int fd;
435 
436         alen = sizeof(addr);
437         fd = adb_socket_accept(_fd, &addr, &alen);
438         if(fd < 0) return;
439 
440         s = create_local_socket(fd);
441         if(s) {
442             s->transport = l->transport;
443             connect_to_remote(s, l->connect_to);
444             return;
445         }
446 
447         adb_close(fd);
448     }
449 }
450 
free_listener(alistener * l)451 static void  free_listener(alistener*  l)
452 {
453     if (l->next) {
454         l->next->prev = l->prev;
455         l->prev->next = l->next;
456         l->next = l->prev = l;
457     }
458 
459     // closes the corresponding fd
460     fdevent_remove(&l->fde);
461 
462     if (l->local_name)
463         free((char*)l->local_name);
464 
465     if (l->connect_to)
466         free((char*)l->connect_to);
467 
468     if (l->transport) {
469         remove_transport_disconnect(l->transport, &l->disconnect);
470     }
471     free(l);
472 }
473 
listener_disconnect(void * _l,atransport * t)474 static void listener_disconnect(void*  _l, atransport*  t)
475 {
476     alistener*  l = _l;
477 
478     free_listener(l);
479 }
480 
local_name_to_fd(const char * name)481 int local_name_to_fd(const char *name)
482 {
483     int port;
484 
485     if(!strncmp("tcp:", name, 4)){
486         int  ret;
487         port = atoi(name + 4);
488         ret = socket_loopback_server(port, SOCK_STREAM);
489         return ret;
490     }
491 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
492     // It's non-sensical to support the "reserved" space on the adb host side
493     if(!strncmp(name, "local:", 6)) {
494         return socket_local_server(name + 6,
495                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
496     } else if(!strncmp(name, "localabstract:", 14)) {
497         return socket_local_server(name + 14,
498                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
499     } else if(!strncmp(name, "localfilesystem:", 16)) {
500         return socket_local_server(name + 16,
501                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
502     }
503 
504 #endif
505     printf("unknown local portname '%s'\n", name);
506     return -1;
507 }
508 
remove_listener(const char * local_name,const char * connect_to,atransport * transport)509 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
510 {
511     alistener *l;
512 
513     for (l = listener_list.next; l != &listener_list; l = l->next) {
514         if (!strcmp(local_name, l->local_name) &&
515             !strcmp(connect_to, l->connect_to) &&
516             l->transport && l->transport == transport) {
517 
518             listener_disconnect(l, transport);
519             return 0;
520         }
521     }
522 
523     return -1;
524 }
525 
install_listener(const char * local_name,const char * connect_to,atransport * transport)526 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
527 {
528     alistener *l;
529 
530     //printf("install_listener('%s','%s')\n", local_name, connect_to);
531 
532     for(l = listener_list.next; l != &listener_list; l = l->next){
533         if(strcmp(local_name, l->local_name) == 0) {
534             char *cto;
535 
536                 /* can't repurpose a smartsocket */
537             if(l->connect_to[0] == '*') {
538                 return -1;
539             }
540 
541             cto = strdup(connect_to);
542             if(cto == 0) {
543                 return -1;
544             }
545 
546             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
547             free((void*) l->connect_to);
548             l->connect_to = cto;
549             if (l->transport != transport) {
550                 remove_transport_disconnect(l->transport, &l->disconnect);
551                 l->transport = transport;
552                 add_transport_disconnect(l->transport, &l->disconnect);
553             }
554             return 0;
555         }
556     }
557 
558     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
559     if((l->local_name = strdup(local_name)) == 0) goto nomem;
560     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
561 
562 
563     l->fd = local_name_to_fd(local_name);
564     if(l->fd < 0) {
565         free((void*) l->local_name);
566         free((void*) l->connect_to);
567         free(l);
568         printf("cannot bind '%s'\n", local_name);
569         return -2;
570     }
571 
572     close_on_exec(l->fd);
573     if(!strcmp(l->connect_to, "*smartsocket*")) {
574         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
575     } else {
576         fdevent_install(&l->fde, l->fd, listener_event_func, l);
577     }
578     fdevent_set(&l->fde, FDE_READ);
579 
580     l->next = &listener_list;
581     l->prev = listener_list.prev;
582     l->next->prev = l;
583     l->prev->next = l;
584     l->transport = transport;
585 
586     if (transport) {
587         l->disconnect.opaque = l;
588         l->disconnect.func   = listener_disconnect;
589         add_transport_disconnect(transport, &l->disconnect);
590     }
591     return 0;
592 
593 nomem:
594     fatal("cannot allocate listener");
595     return 0;
596 }
597 
598 #ifdef HAVE_FORKEXEC
sigchld_handler(int n)599 static void sigchld_handler(int n)
600 {
601     int status;
602     while(waitpid(-1, &status, WNOHANG) > 0) ;
603 }
604 #endif
605 
606 #ifdef HAVE_WIN32_PROC
ctrlc_handler(DWORD type)607 static BOOL WINAPI ctrlc_handler(DWORD type)
608 {
609     exit(STATUS_CONTROL_C_EXIT);
610     return TRUE;
611 }
612 #endif
613 
adb_cleanup(void)614 static void adb_cleanup(void)
615 {
616     usb_cleanup();
617 }
618 
start_logging(void)619 void start_logging(void)
620 {
621 #ifdef HAVE_WIN32_PROC
622     char    temp[ MAX_PATH ];
623     FILE*   fnul;
624     FILE*   flog;
625 
626     GetTempPath( sizeof(temp) - 8, temp );
627     strcat( temp, "adb.log" );
628 
629     /* Win32 specific redirections */
630     fnul = fopen( "NUL", "rt" );
631     if (fnul != NULL)
632         stdin[0] = fnul[0];
633 
634     flog = fopen( temp, "at" );
635     if (flog == NULL)
636         flog = fnul;
637 
638     setvbuf( flog, NULL, _IONBF, 0 );
639 
640     stdout[0] = flog[0];
641     stderr[0] = flog[0];
642     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
643 #else
644     int fd;
645 
646     fd = unix_open("/dev/null", O_RDONLY);
647     dup2(fd, 0);
648 
649     fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
650     if(fd < 0) {
651         fd = unix_open("/dev/null", O_WRONLY);
652     }
653     dup2(fd, 1);
654     dup2(fd, 2);
655     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
656 #endif
657 }
658 
659 #if !ADB_HOST
start_device_log(void)660 void start_device_log(void)
661 {
662     int fd;
663     char    path[PATH_MAX];
664     struct tm now;
665     time_t t;
666     char value[PROPERTY_VALUE_MAX];
667 
668     // read the trace mask from persistent property persist.adb.trace_mask
669     // give up if the property is not set or cannot be parsed
670     property_get("persist.adb.trace_mask", value, "");
671     if (sscanf(value, "%x", &adb_trace_mask) != 1)
672         return;
673 
674     adb_mkdir("/data/adb", 0775);
675     tzset();
676     time(&t);
677     localtime_r(&t, &now);
678     strftime(path, sizeof(path),
679                 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
680                 &now);
681     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
682     if (fd < 0)
683         return;
684 
685     // redirect stdout and stderr to the log file
686     dup2(fd, 1);
687     dup2(fd, 2);
688     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
689 
690     fd = unix_open("/dev/null", O_RDONLY);
691     dup2(fd, 0);
692 }
693 #endif
694 
695 #if ADB_HOST
launch_server()696 int launch_server()
697 {
698 #ifdef HAVE_WIN32_PROC
699     /* we need to start the server in the background                    */
700     /* we create a PIPE that will be used to wait for the server's "OK" */
701     /* message since the pipe handles must be inheritable, we use a     */
702     /* security attribute                                               */
703     HANDLE                pipe_read, pipe_write;
704     SECURITY_ATTRIBUTES   sa;
705     STARTUPINFO           startup;
706     PROCESS_INFORMATION   pinfo;
707     char                  program_path[ MAX_PATH ];
708     int                   ret;
709 
710     sa.nLength = sizeof(sa);
711     sa.lpSecurityDescriptor = NULL;
712     sa.bInheritHandle = TRUE;
713 
714     /* create pipe, and ensure its read handle isn't inheritable */
715     ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
716     if (!ret) {
717         fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
718         return -1;
719     }
720 
721     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
722 
723     ZeroMemory( &startup, sizeof(startup) );
724     startup.cb = sizeof(startup);
725     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
726     startup.hStdOutput = pipe_write;
727     startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
728     startup.dwFlags    = STARTF_USESTDHANDLES;
729 
730     ZeroMemory( &pinfo, sizeof(pinfo) );
731 
732     /* get path of current program */
733     GetModuleFileName( NULL, program_path, sizeof(program_path) );
734 
735     ret = CreateProcess(
736             program_path,                              /* program path  */
737             "adb fork-server server",
738                                     /* the fork-server argument will set the
739                                        debug = 2 in the child           */
740             NULL,                   /* process handle is not inheritable */
741             NULL,                    /* thread handle is not inheritable */
742             TRUE,                          /* yes, inherit some handles */
743             DETACHED_PROCESS, /* the new process doesn't have a console */
744             NULL,                     /* use parent's environment block */
745             NULL,                    /* use parent's starting directory */
746             &startup,                 /* startup info, i.e. std handles */
747             &pinfo );
748 
749     CloseHandle( pipe_write );
750 
751     if (!ret) {
752         fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
753         CloseHandle( pipe_read );
754         return -1;
755     }
756 
757     CloseHandle( pinfo.hProcess );
758     CloseHandle( pinfo.hThread );
759 
760     /* wait for the "OK\n" message */
761     {
762         char  temp[3];
763         DWORD  count;
764 
765         ret = ReadFile( pipe_read, temp, 3, &count, NULL );
766         CloseHandle( pipe_read );
767         if ( !ret ) {
768             fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
769             return -1;
770         }
771         if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
772             fprintf(stderr, "ADB server didn't ACK\n" );
773             return -1;
774         }
775     }
776 #elif defined(HAVE_FORKEXEC)
777     char    path[PATH_MAX];
778     int     fd[2];
779 
780     // set up a pipe so the child can tell us when it is ready.
781     // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
782     if (pipe(fd)) {
783         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
784         return -1;
785     }
786     get_my_path(path);
787     pid_t pid = fork();
788     if(pid < 0) return -1;
789 
790     if (pid == 0) {
791         // child side of the fork
792 
793         // redirect stderr to the pipe
794         // we use stderr instead of stdout due to stdout's buffering behavior.
795         adb_close(fd[0]);
796         dup2(fd[1], STDERR_FILENO);
797         adb_close(fd[1]);
798 
799         // child process
800         int result = execl(path, "adb", "fork-server", "server", NULL);
801         // this should not return
802         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
803     } else  {
804         // parent side of the fork
805 
806         char  temp[3];
807 
808         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
809         // wait for the "OK\n" message
810         adb_close(fd[1]);
811         int ret = adb_read(fd[0], temp, 3);
812         adb_close(fd[0]);
813         if (ret < 0) {
814             fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", errno);
815             return -1;
816         }
817         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
818             fprintf(stderr, "ADB server didn't ACK\n" );
819             return -1;
820         }
821 
822         setsid();
823     }
824 #else
825 #error "cannot implement background server start on this platform"
826 #endif
827     return 0;
828 }
829 #endif
830 
adb_main(int is_daemon)831 int adb_main(int is_daemon)
832 {
833 #if !ADB_HOST
834     int secure = 0;
835     int port;
836     char value[PROPERTY_VALUE_MAX];
837 #endif
838 
839     atexit(adb_cleanup);
840 #ifdef HAVE_WIN32_PROC
841     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
842 #elif defined(HAVE_FORKEXEC)
843     signal(SIGCHLD, sigchld_handler);
844     signal(SIGPIPE, SIG_IGN);
845 #endif
846 
847     init_transport_registration();
848 
849 
850 #if ADB_HOST
851     HOST = 1;
852     usb_vendors_init();
853     usb_init();
854     local_init(ADB_LOCAL_TRANSPORT_PORT);
855 
856     if(install_listener("tcp:5037", "*smartsocket*", NULL)) {
857         exit(1);
858     }
859 #else
860     /* run adbd in secure mode if ro.secure is set and
861     ** we are not in the emulator
862     */
863     property_get("ro.kernel.qemu", value, "");
864     if (strcmp(value, "1") != 0) {
865         property_get("ro.secure", value, "");
866         if (strcmp(value, "1") == 0) {
867             // don't run as root if ro.secure is set...
868             secure = 1;
869 
870             // ... except we allow running as root in userdebug builds if the
871             // service.adb.root property has been set by the "adb root" command
872             property_get("ro.debuggable", value, "");
873             if (strcmp(value, "1") == 0) {
874                 property_get("service.adb.root", value, "");
875                 if (strcmp(value, "1") == 0) {
876                     secure = 0;
877                 }
878             }
879         }
880     }
881 
882     /* don't listen on port 5037 if we are running in secure mode */
883     /* don't run as root if we are running in secure mode */
884     if (secure) {
885         struct __user_cap_header_struct header;
886         struct __user_cap_data_struct cap;
887 
888         prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
889 
890         /* add extra groups:
891         ** AID_ADB to access the USB driver
892         ** AID_LOG to read system logs (adb logcat)
893         ** AID_INPUT to diagnose input issues (getevent)
894         ** AID_INET to diagnose network issues (netcfg, ping)
895         ** AID_GRAPHICS to access the frame buffer
896         ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
897         ** AID_SDCARD_RW to allow writing to the SD card
898         */
899         gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
900                            AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_RW };
901         setgroups(sizeof(groups)/sizeof(groups[0]), groups);
902 
903         /* then switch user and group to "shell" */
904         setgid(AID_SHELL);
905         setuid(AID_SHELL);
906 
907         /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
908         header.version = _LINUX_CAPABILITY_VERSION;
909         header.pid = 0;
910         cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
911         cap.inheritable = 0;
912         capset(&header, &cap);
913 
914         D("Local port 5037 disabled\n");
915     } else {
916         if(install_listener("tcp:5037", "*smartsocket*", NULL)) {
917             exit(1);
918         }
919     }
920 
921         /* for the device, start the usb transport if the
922         ** android usb device exists and "service.adb.tcp"
923         ** is not set, otherwise start the network transport.
924         */
925     property_get("service.adb.tcp.port", value, "0");
926     if (sscanf(value, "%d", &port) == 1 && port > 0) {
927         // listen on TCP port specified by service.adb.tcp.port property
928         local_init(port);
929     } else if (access("/dev/android_adb", F_OK) == 0) {
930         // listen on USB
931         usb_init();
932     } else {
933         // listen on default port
934         local_init(ADB_LOCAL_TRANSPORT_PORT);
935     }
936     init_jdwp();
937 #endif
938 
939     if (is_daemon)
940     {
941         // inform our parent that we are up and running.
942 #ifdef HAVE_WIN32_PROC
943         DWORD  count;
944         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
945 #elif defined(HAVE_FORKEXEC)
946         fprintf(stderr, "OK\n");
947 #endif
948         start_logging();
949     }
950 
951     fdevent_loop();
952 
953     usb_cleanup();
954 
955     return 0;
956 }
957 
handle_host_request(char * service,transport_type ttype,char * serial,int reply_fd,asocket * s)958 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
959 {
960     atransport *transport = NULL;
961     char buf[4096];
962 
963     if(!strcmp(service, "kill")) {
964         fprintf(stderr,"adb server killed by remote request\n");
965         fflush(stdout);
966         adb_write(reply_fd, "OKAY", 4);
967         usb_cleanup();
968         exit(0);
969     }
970 
971 #if ADB_HOST
972     // "transport:" is used for switching transport with a specified serial number
973     // "transport-usb:" is used for switching transport to the only USB transport
974     // "transport-local:" is used for switching transport to the only local transport
975     // "transport-any:" is used for switching transport to the only transport
976     if (!strncmp(service, "transport", strlen("transport"))) {
977         char* error_string = "unknown failure";
978         transport_type type = kTransportAny;
979 
980         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
981             type = kTransportUsb;
982         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
983             type = kTransportLocal;
984         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
985             type = kTransportAny;
986         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
987             service += strlen("transport:");
988             serial = strdup(service);
989         }
990 
991         transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
992 
993         if (transport) {
994             s->transport = transport;
995             adb_write(reply_fd, "OKAY", 4);
996         } else {
997             sendfailmsg(reply_fd, error_string);
998         }
999         return 1;
1000     }
1001 
1002     // return a list of all connected devices
1003     if (!strcmp(service, "devices")) {
1004         char buffer[4096];
1005         memset(buf, 0, sizeof(buf));
1006         memset(buffer, 0, sizeof(buffer));
1007         D("Getting device list \n");
1008         list_transports(buffer, sizeof(buffer));
1009         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1010         D("Wrote device list \n");
1011         writex(reply_fd, buf, strlen(buf));
1012         return 0;
1013     }
1014 
1015     // add a new TCP transport
1016     if (!strncmp(service, "connect:", 8)) {
1017         char buffer[4096];
1018         int port, fd;
1019         char* host = service + 8;
1020         char* portstr = strchr(host, ':');
1021 
1022         if (!portstr) {
1023             snprintf(buffer, sizeof(buffer), "unable to parse %s as <host>:<port>", host);
1024             goto done;
1025         }
1026         if (find_transport(host)) {
1027             snprintf(buffer, sizeof(buffer), "Already connected to %s", host);
1028             goto done;
1029         }
1030 
1031         // zero terminate host by overwriting the ':'
1032         *portstr++ = 0;
1033         if (sscanf(portstr, "%d", &port) == 0) {
1034             snprintf(buffer, sizeof(buffer), "bad port number %s", portstr);
1035             goto done;
1036         }
1037 
1038         fd = socket_network_client(host, port, SOCK_STREAM);
1039         if (fd < 0) {
1040             snprintf(buffer, sizeof(buffer), "unable to connect to %s:%d", host, port);
1041             goto done;
1042         }
1043 
1044         D("client: connected on remote on fd %d\n", fd);
1045         close_on_exec(fd);
1046         disable_tcp_nagle(fd);
1047         snprintf(buf, sizeof buf, "%s:%d", host, port);
1048         register_socket_transport(fd, buf, port, 0);
1049         snprintf(buffer, sizeof(buffer), "connected to %s:%d", host, port);
1050 
1051 done:
1052         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1053         writex(reply_fd, buf, strlen(buf));
1054         return 0;
1055     }
1056 
1057     // remove TCP transport
1058     if (!strncmp(service, "disconnect:", 11)) {
1059         char buffer[4096];
1060         memset(buffer, 0, sizeof(buffer));
1061         char* serial = service + 11;
1062         atransport *t = find_transport(serial);
1063 
1064         if (t) {
1065             unregister_transport(t);
1066         } else {
1067             snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1068         }
1069 
1070         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1071         writex(reply_fd, buf, strlen(buf));
1072         return 0;
1073     }
1074 
1075     // returns our value for ADB_SERVER_VERSION
1076     if (!strcmp(service, "version")) {
1077         char version[12];
1078         snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1079         snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1080         writex(reply_fd, buf, strlen(buf));
1081         return 0;
1082     }
1083 
1084     if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1085         char *out = "unknown";
1086          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1087        if (transport && transport->serial) {
1088             out = transport->serial;
1089         }
1090         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1091         writex(reply_fd, buf, strlen(buf));
1092         return 0;
1093     }
1094     // indicates a new emulator instance has started
1095     if (!strncmp(service,"emulator:",9)) {
1096         int  port = atoi(service+9);
1097         local_connect(port);
1098         /* we don't even need to send a reply */
1099         return 0;
1100     }
1101 #endif // ADB_HOST
1102 
1103     if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1104         char *local, *remote, *err;
1105         int r;
1106         atransport *transport;
1107 
1108         int createForward = strncmp(service,"kill",4);
1109 
1110         local = service + (createForward ? 8 : 12);
1111         remote = strchr(local,';');
1112         if(remote == 0) {
1113             sendfailmsg(reply_fd, "malformed forward spec");
1114             return 0;
1115         }
1116 
1117         *remote++ = 0;
1118         if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1119             sendfailmsg(reply_fd, "malformed forward spec");
1120             return 0;
1121         }
1122 
1123         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1124         if (!transport) {
1125             sendfailmsg(reply_fd, err);
1126             return 0;
1127         }
1128 
1129         if (createForward) {
1130             r = install_listener(local, remote, transport);
1131         } else {
1132             r = remove_listener(local, remote, transport);
1133         }
1134         if(r == 0) {
1135                 /* 1st OKAY is connect, 2nd OKAY is status */
1136             writex(reply_fd, "OKAYOKAY", 8);
1137             return 0;
1138         }
1139 
1140         if (createForward) {
1141             sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1142         } else {
1143             sendfailmsg(reply_fd, "cannot remove listener");
1144         }
1145         return 0;
1146     }
1147 
1148     if(!strncmp(service,"get-state",strlen("get-state"))) {
1149         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1150         char *state = connection_state_name(transport);
1151         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1152         writex(reply_fd, buf, strlen(buf));
1153         return 0;
1154     }
1155     return -1;
1156 }
1157 
1158 #if !ADB_HOST
1159 int recovery_mode = 0;
1160 #endif
1161 
main(int argc,char ** argv)1162 int main(int argc, char **argv)
1163 {
1164     adb_trace_init();
1165 #if ADB_HOST
1166     adb_sysdeps_init();
1167     return adb_commandline(argc - 1, argv + 1);
1168 #else
1169     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1170         adb_device_banner = "recovery";
1171         recovery_mode = 1;
1172     }
1173 
1174     start_device_log();
1175     return adb_main(0);
1176 #endif
1177 }
1178