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