blob: 60568f5562fe213d522e0f6cbabde79e4a38a02a [file] [log] [blame]
The Android Open Source Projectdd7bc332009-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>
Mike Lockwood1f546e62009-05-25 18:17:55 -040026#include <sys/time.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080027
28#include "sysdeps.h"
29#include "adb.h"
30
31#if !ADB_HOST
32#include <private/android_filesystem_config.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040033#include <linux/capability.h>
34#include <linux/prctl.h>
Xavier Ducroheta09fbd12009-05-20 17:33:53 -070035#else
36#include "usb_vendors.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080037#endif
38
JP Abgrall408fa572011-03-16 15:57:42 -070039#if ADB_TRACE
40ADB_MUTEX_DEFINE( D_lock );
41#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042
43int HOST = 0;
44
45static const char *adb_device_banner = "device";
46
47void fatal(const char *fmt, ...)
48{
49 va_list ap;
50 va_start(ap, fmt);
51 fprintf(stderr, "error: ");
52 vfprintf(stderr, fmt, ap);
53 fprintf(stderr, "\n");
54 va_end(ap);
55 exit(-1);
56}
57
58void fatal_errno(const char *fmt, ...)
59{
60 va_list ap;
61 va_start(ap, fmt);
62 fprintf(stderr, "error: %s: ", strerror(errno));
63 vfprintf(stderr, fmt, ap);
64 fprintf(stderr, "\n");
65 va_end(ap);
66 exit(-1);
67}
68
69int adb_trace_mask;
70
71/* read a comma/space/colum/semi-column separated list of tags
72 * from the ADB_TRACE environment variable and build the trace
73 * mask from it. note that '1' and 'all' are special cases to
74 * enable all tracing
75 */
76void adb_trace_init(void)
77{
78 const char* p = getenv("ADB_TRACE");
79 const char* q;
80
81 static const struct {
82 const char* tag;
83 int flag;
84 } tags[] = {
85 { "1", 0 },
86 { "all", 0 },
87 { "adb", TRACE_ADB },
88 { "sockets", TRACE_SOCKETS },
89 { "packets", TRACE_PACKETS },
90 { "rwx", TRACE_RWX },
91 { "usb", TRACE_USB },
92 { "sync", TRACE_SYNC },
93 { "sysdeps", TRACE_SYSDEPS },
94 { "transport", TRACE_TRANSPORT },
95 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -070096 { "services", TRACE_SERVICES },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080097 { NULL, 0 }
98 };
99
100 if (p == NULL)
101 return;
102
103 /* use a comma/column/semi-colum/space separated list */
104 while (*p) {
105 int len, tagn;
106
107 q = strpbrk(p, " ,:;");
108 if (q == NULL) {
109 q = p + strlen(p);
110 }
111 len = q - p;
112
113 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
114 {
115 int taglen = strlen(tags[tagn].tag);
116
117 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
118 {
119 int flag = tags[tagn].flag;
120 if (flag == 0) {
121 adb_trace_mask = ~0;
122 return;
123 }
124 adb_trace_mask |= (1 << flag);
125 break;
126 }
127 }
128 p = q;
129 if (*p)
130 p++;
131 }
132}
133
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800134#if !ADB_HOST
135/*
136 * Implements ADB tracing inside the emulator.
137 */
138
139#include <stdarg.h>
140
141/*
142 * Redefine open and write for qemu_pipe.h that contains inlined references
143 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
144 */
145
146#undef open
147#undef write
148#define open adb_open
149#define write adb_write
150#include <hardware/qemu_pipe.h>
151#undef open
152#undef write
153#define open ___xxx_open
154#define write ___xxx_write
155
156/* A handle to adb-debug qemud service in the emulator. */
157int adb_debug_qemu = -1;
158
159/* Initializes connection with the adb-debug qemud service in the emulator. */
160static int adb_qemu_trace_init(void)
161{
162 char con_name[32];
163
164 if (adb_debug_qemu >= 0) {
165 return 0;
166 }
167
168 /* adb debugging QEMUD service connection request. */
169 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
170 adb_debug_qemu = qemu_pipe_open(con_name);
171 return (adb_debug_qemu >= 0) ? 0 : -1;
172}
173
174void adb_qemu_trace(const char* fmt, ...)
175{
176 va_list args;
177 va_start(args, fmt);
178 char msg[1024];
179
180 if (adb_debug_qemu >= 0) {
181 vsnprintf(msg, sizeof(msg), fmt, args);
182 adb_write(adb_debug_qemu, msg, strlen(msg));
183 }
184}
185#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800186
187apacket *get_apacket(void)
188{
189 apacket *p = malloc(sizeof(apacket));
190 if(p == 0) fatal("failed to allocate an apacket");
191 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
192 return p;
193}
194
195void put_apacket(apacket *p)
196{
197 free(p);
198}
199
200void handle_online(void)
201{
202 D("adb: online\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800203}
204
205void handle_offline(atransport *t)
206{
207 D("adb: offline\n");
208 //Close the associated usb
209 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210}
211
212#if TRACE_PACKETS
213#define DUMPMAX 32
214void print_packet(const char *label, apacket *p)
215{
216 char *tag;
217 char *x;
218 unsigned count;
219
220 switch(p->msg.command){
221 case A_SYNC: tag = "SYNC"; break;
222 case A_CNXN: tag = "CNXN" ; break;
223 case A_OPEN: tag = "OPEN"; break;
224 case A_OKAY: tag = "OKAY"; break;
225 case A_CLSE: tag = "CLSE"; break;
226 case A_WRTE: tag = "WRTE"; break;
227 default: tag = "????"; break;
228 }
229
230 fprintf(stderr, "%s: %s %08x %08x %04x \"",
231 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
232 count = p->msg.data_length;
233 x = (char*) p->data;
234 if(count > DUMPMAX) {
235 count = DUMPMAX;
236 tag = "\n";
237 } else {
238 tag = "\"\n";
239 }
240 while(count-- > 0){
241 if((*x >= ' ') && (*x < 127)) {
242 fputc(*x, stderr);
243 } else {
244 fputc('.', stderr);
245 }
246 x++;
247 }
248 fprintf(stderr, tag);
249}
250#endif
251
252static void send_ready(unsigned local, unsigned remote, atransport *t)
253{
254 D("Calling send_ready \n");
255 apacket *p = get_apacket();
256 p->msg.command = A_OKAY;
257 p->msg.arg0 = local;
258 p->msg.arg1 = remote;
259 send_packet(p, t);
260}
261
262static void send_close(unsigned local, unsigned remote, atransport *t)
263{
264 D("Calling send_close \n");
265 apacket *p = get_apacket();
266 p->msg.command = A_CLSE;
267 p->msg.arg0 = local;
268 p->msg.arg1 = remote;
269 send_packet(p, t);
270}
271
272static void send_connect(atransport *t)
273{
274 D("Calling send_connect \n");
275 apacket *cp = get_apacket();
276 cp->msg.command = A_CNXN;
277 cp->msg.arg0 = A_VERSION;
278 cp->msg.arg1 = MAX_PAYLOAD;
279 snprintf((char*) cp->data, sizeof cp->data, "%s::",
280 HOST ? "host" : adb_device_banner);
281 cp->msg.data_length = strlen((char*) cp->data) + 1;
282 send_packet(cp, t);
283#if ADB_HOST
284 /* XXX why sleep here? */
285 // allow the device some time to respond to the connect message
286 adb_sleep_ms(1000);
287#endif
288}
289
290static char *connection_state_name(atransport *t)
291{
292 if (t == NULL) {
293 return "unknown";
294 }
295
296 switch(t->connection_state) {
297 case CS_BOOTLOADER:
298 return "bootloader";
299 case CS_DEVICE:
300 return "device";
301 case CS_OFFLINE:
302 return "offline";
303 default:
304 return "unknown";
305 }
306}
307
308void parse_banner(char *banner, atransport *t)
309{
310 char *type, *product, *end;
311
312 D("parse_banner: %s\n", banner);
313 type = banner;
314 product = strchr(type, ':');
315 if(product) {
316 *product++ = 0;
317 } else {
318 product = "";
319 }
320
321 /* remove trailing ':' */
322 end = strchr(product, ':');
323 if(end) *end = 0;
324
325 /* save product name in device structure */
326 if (t->product == NULL) {
327 t->product = strdup(product);
328 } else if (strcmp(product, t->product) != 0) {
329 free(t->product);
330 t->product = strdup(product);
331 }
332
333 if(!strcmp(type, "bootloader")){
334 D("setting connection_state to CS_BOOTLOADER\n");
335 t->connection_state = CS_BOOTLOADER;
336 update_transports();
337 return;
338 }
339
340 if(!strcmp(type, "device")) {
341 D("setting connection_state to CS_DEVICE\n");
342 t->connection_state = CS_DEVICE;
343 update_transports();
344 return;
345 }
346
347 if(!strcmp(type, "recovery")) {
348 D("setting connection_state to CS_RECOVERY\n");
349 t->connection_state = CS_RECOVERY;
350 update_transports();
351 return;
352 }
353
Doug Zongker447f0612012-01-09 14:54:53 -0800354 if(!strcmp(type, "sideload")) {
355 D("setting connection_state to CS_SIDELOAD\n");
356 t->connection_state = CS_SIDELOAD;
357 update_transports();
358 return;
359 }
360
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800361 t->connection_state = CS_HOST;
362}
363
364void handle_packet(apacket *p, atransport *t)
365{
366 asocket *s;
367
Viral Mehta899913f2010-06-16 18:41:28 +0530368 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
369 ((char*) (&(p->msg.command)))[1],
370 ((char*) (&(p->msg.command)))[2],
371 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800372 print_packet("recv", p);
373
374 switch(p->msg.command){
375 case A_SYNC:
376 if(p->msg.arg0){
377 send_packet(p, t);
378 if(HOST) send_connect(t);
379 } else {
380 t->connection_state = CS_OFFLINE;
381 handle_offline(t);
382 send_packet(p, t);
383 }
384 return;
385
386 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
387 /* XXX verify version, etc */
388 if(t->connection_state != CS_OFFLINE) {
389 t->connection_state = CS_OFFLINE;
390 handle_offline(t);
391 }
392 parse_banner((char*) p->data, t);
393 handle_online();
394 if(!HOST) send_connect(t);
395 break;
396
397 case A_OPEN: /* OPEN(local-id, 0, "destination") */
398 if(t->connection_state != CS_OFFLINE) {
399 char *name = (char*) p->data;
400 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
401 s = create_local_service_socket(name);
402 if(s == 0) {
403 send_close(0, p->msg.arg0, t);
404 } else {
405 s->peer = create_remote_socket(p->msg.arg0, t);
406 s->peer->peer = s;
407 send_ready(s->id, s->peer->id, t);
408 s->ready(s);
409 }
410 }
411 break;
412
413 case A_OKAY: /* READY(local-id, remote-id, "") */
414 if(t->connection_state != CS_OFFLINE) {
415 if((s = find_local_socket(p->msg.arg1))) {
416 if(s->peer == 0) {
417 s->peer = create_remote_socket(p->msg.arg0, t);
418 s->peer->peer = s;
419 }
420 s->ready(s);
421 }
422 }
423 break;
424
425 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
426 if(t->connection_state != CS_OFFLINE) {
427 if((s = find_local_socket(p->msg.arg1))) {
428 s->close(s);
429 }
430 }
431 break;
432
433 case A_WRTE:
434 if(t->connection_state != CS_OFFLINE) {
435 if((s = find_local_socket(p->msg.arg1))) {
436 unsigned rid = p->msg.arg0;
437 p->len = p->msg.data_length;
438
439 if(s->enqueue(s, p) == 0) {
440 D("Enqueue the socket\n");
441 send_ready(s->id, rid, t);
442 }
443 return;
444 }
445 }
446 break;
447
448 default:
449 printf("handle_packet: what is %08x?!\n", p->msg.command);
450 }
451
452 put_apacket(p);
453}
454
455alistener listener_list = {
456 .next = &listener_list,
457 .prev = &listener_list,
458};
459
460static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
461{
462 asocket *s;
463
464 if(ev & FDE_READ) {
465 struct sockaddr addr;
466 socklen_t alen;
467 int fd;
468
469 alen = sizeof(addr);
470 fd = adb_socket_accept(_fd, &addr, &alen);
471 if(fd < 0) return;
472
473 adb_socket_setbufsize(fd, CHUNK_SIZE);
474
475 s = create_local_socket(fd);
476 if(s) {
477 connect_to_smartsocket(s);
478 return;
479 }
480
481 adb_close(fd);
482 }
483}
484
485static void listener_event_func(int _fd, unsigned ev, void *_l)
486{
487 alistener *l = _l;
488 asocket *s;
489
490 if(ev & FDE_READ) {
491 struct sockaddr addr;
492 socklen_t alen;
493 int fd;
494
495 alen = sizeof(addr);
496 fd = adb_socket_accept(_fd, &addr, &alen);
497 if(fd < 0) return;
498
499 s = create_local_socket(fd);
500 if(s) {
501 s->transport = l->transport;
502 connect_to_remote(s, l->connect_to);
503 return;
504 }
505
506 adb_close(fd);
507 }
508}
509
510static void free_listener(alistener* l)
511{
512 if (l->next) {
513 l->next->prev = l->prev;
514 l->prev->next = l->next;
515 l->next = l->prev = l;
516 }
517
518 // closes the corresponding fd
519 fdevent_remove(&l->fde);
520
521 if (l->local_name)
522 free((char*)l->local_name);
523
524 if (l->connect_to)
525 free((char*)l->connect_to);
526
527 if (l->transport) {
528 remove_transport_disconnect(l->transport, &l->disconnect);
529 }
530 free(l);
531}
532
533static void listener_disconnect(void* _l, atransport* t)
534{
535 alistener* l = _l;
536
537 free_listener(l);
538}
539
540int local_name_to_fd(const char *name)
541{
542 int port;
543
544 if(!strncmp("tcp:", name, 4)){
545 int ret;
546 port = atoi(name + 4);
547 ret = socket_loopback_server(port, SOCK_STREAM);
548 return ret;
549 }
550#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
551 // It's non-sensical to support the "reserved" space on the adb host side
552 if(!strncmp(name, "local:", 6)) {
553 return socket_local_server(name + 6,
554 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
555 } else if(!strncmp(name, "localabstract:", 14)) {
556 return socket_local_server(name + 14,
557 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
558 } else if(!strncmp(name, "localfilesystem:", 16)) {
559 return socket_local_server(name + 16,
560 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
561 }
562
563#endif
564 printf("unknown local portname '%s'\n", name);
565 return -1;
566}
567
568static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
569{
570 alistener *l;
571
572 for (l = listener_list.next; l != &listener_list; l = l->next) {
573 if (!strcmp(local_name, l->local_name) &&
574 !strcmp(connect_to, l->connect_to) &&
575 l->transport && l->transport == transport) {
576
577 listener_disconnect(l, transport);
578 return 0;
579 }
580 }
581
582 return -1;
583}
584
585static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
586{
587 alistener *l;
588
589 //printf("install_listener('%s','%s')\n", local_name, connect_to);
590
591 for(l = listener_list.next; l != &listener_list; l = l->next){
592 if(strcmp(local_name, l->local_name) == 0) {
593 char *cto;
594
595 /* can't repurpose a smartsocket */
596 if(l->connect_to[0] == '*') {
597 return -1;
598 }
599
600 cto = strdup(connect_to);
601 if(cto == 0) {
602 return -1;
603 }
604
605 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
606 free((void*) l->connect_to);
607 l->connect_to = cto;
608 if (l->transport != transport) {
609 remove_transport_disconnect(l->transport, &l->disconnect);
610 l->transport = transport;
611 add_transport_disconnect(l->transport, &l->disconnect);
612 }
613 return 0;
614 }
615 }
616
617 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
618 if((l->local_name = strdup(local_name)) == 0) goto nomem;
619 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
620
621
622 l->fd = local_name_to_fd(local_name);
623 if(l->fd < 0) {
624 free((void*) l->local_name);
625 free((void*) l->connect_to);
626 free(l);
627 printf("cannot bind '%s'\n", local_name);
628 return -2;
629 }
630
631 close_on_exec(l->fd);
632 if(!strcmp(l->connect_to, "*smartsocket*")) {
633 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
634 } else {
635 fdevent_install(&l->fde, l->fd, listener_event_func, l);
636 }
637 fdevent_set(&l->fde, FDE_READ);
638
639 l->next = &listener_list;
640 l->prev = listener_list.prev;
641 l->next->prev = l;
642 l->prev->next = l;
643 l->transport = transport;
644
645 if (transport) {
646 l->disconnect.opaque = l;
647 l->disconnect.func = listener_disconnect;
648 add_transport_disconnect(transport, &l->disconnect);
649 }
650 return 0;
651
652nomem:
653 fatal("cannot allocate listener");
654 return 0;
655}
656
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657#ifdef HAVE_WIN32_PROC
658static BOOL WINAPI ctrlc_handler(DWORD type)
659{
660 exit(STATUS_CONTROL_C_EXIT);
661 return TRUE;
662}
663#endif
664
665static void adb_cleanup(void)
666{
667 usb_cleanup();
668}
669
670void start_logging(void)
671{
672#ifdef HAVE_WIN32_PROC
673 char temp[ MAX_PATH ];
674 FILE* fnul;
675 FILE* flog;
676
677 GetTempPath( sizeof(temp) - 8, temp );
678 strcat( temp, "adb.log" );
679
680 /* Win32 specific redirections */
681 fnul = fopen( "NUL", "rt" );
682 if (fnul != NULL)
683 stdin[0] = fnul[0];
684
685 flog = fopen( temp, "at" );
686 if (flog == NULL)
687 flog = fnul;
688
689 setvbuf( flog, NULL, _IONBF, 0 );
690
691 stdout[0] = flog[0];
692 stderr[0] = flog[0];
693 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
694#else
695 int fd;
696
697 fd = unix_open("/dev/null", O_RDONLY);
698 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700699 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800700
701 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
702 if(fd < 0) {
703 fd = unix_open("/dev/null", O_WRONLY);
704 }
705 dup2(fd, 1);
706 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700707 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800708 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
709#endif
710}
711
712#if !ADB_HOST
713void start_device_log(void)
714{
715 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400716 char path[PATH_MAX];
717 struct tm now;
718 time_t t;
719 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720
Mike Lockwood1f546e62009-05-25 18:17:55 -0400721 // read the trace mask from persistent property persist.adb.trace_mask
722 // give up if the property is not set or cannot be parsed
723 property_get("persist.adb.trace_mask", value, "");
724 if (sscanf(value, "%x", &adb_trace_mask) != 1)
725 return;
726
727 adb_mkdir("/data/adb", 0775);
728 tzset();
729 time(&t);
730 localtime_r(&t, &now);
731 strftime(path, sizeof(path),
732 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
733 &now);
734 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 if (fd < 0)
736 return;
737
738 // redirect stdout and stderr to the log file
739 dup2(fd, 1);
740 dup2(fd, 2);
741 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800742 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743
744 fd = unix_open("/dev/null", O_RDONLY);
745 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800746 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800747}
748#endif
749
750#if ADB_HOST
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100751int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800752{
753#ifdef HAVE_WIN32_PROC
754 /* we need to start the server in the background */
755 /* we create a PIPE that will be used to wait for the server's "OK" */
756 /* message since the pipe handles must be inheritable, we use a */
757 /* security attribute */
758 HANDLE pipe_read, pipe_write;
759 SECURITY_ATTRIBUTES sa;
760 STARTUPINFO startup;
761 PROCESS_INFORMATION pinfo;
762 char program_path[ MAX_PATH ];
763 int ret;
764
765 sa.nLength = sizeof(sa);
766 sa.lpSecurityDescriptor = NULL;
767 sa.bInheritHandle = TRUE;
768
769 /* create pipe, and ensure its read handle isn't inheritable */
770 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
771 if (!ret) {
772 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
773 return -1;
774 }
775
776 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
777
778 ZeroMemory( &startup, sizeof(startup) );
779 startup.cb = sizeof(startup);
780 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
781 startup.hStdOutput = pipe_write;
782 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
783 startup.dwFlags = STARTF_USESTDHANDLES;
784
785 ZeroMemory( &pinfo, sizeof(pinfo) );
786
787 /* get path of current program */
788 GetModuleFileName( NULL, program_path, sizeof(program_path) );
789
790 ret = CreateProcess(
791 program_path, /* program path */
792 "adb fork-server server",
793 /* the fork-server argument will set the
794 debug = 2 in the child */
795 NULL, /* process handle is not inheritable */
796 NULL, /* thread handle is not inheritable */
797 TRUE, /* yes, inherit some handles */
798 DETACHED_PROCESS, /* the new process doesn't have a console */
799 NULL, /* use parent's environment block */
800 NULL, /* use parent's starting directory */
801 &startup, /* startup info, i.e. std handles */
802 &pinfo );
803
804 CloseHandle( pipe_write );
805
806 if (!ret) {
807 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
808 CloseHandle( pipe_read );
809 return -1;
810 }
811
812 CloseHandle( pinfo.hProcess );
813 CloseHandle( pinfo.hThread );
814
815 /* wait for the "OK\n" message */
816 {
817 char temp[3];
818 DWORD count;
819
820 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
821 CloseHandle( pipe_read );
822 if ( !ret ) {
823 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
824 return -1;
825 }
826 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
827 fprintf(stderr, "ADB server didn't ACK\n" );
828 return -1;
829 }
830 }
831#elif defined(HAVE_FORKEXEC)
832 char path[PATH_MAX];
833 int fd[2];
834
835 // set up a pipe so the child can tell us when it is ready.
836 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
837 if (pipe(fd)) {
838 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
839 return -1;
840 }
Alexey Tarasov31664102009-10-22 02:55:00 +1100841 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 pid_t pid = fork();
843 if(pid < 0) return -1;
844
845 if (pid == 0) {
846 // child side of the fork
847
848 // redirect stderr to the pipe
849 // we use stderr instead of stdout due to stdout's buffering behavior.
850 adb_close(fd[0]);
851 dup2(fd[1], STDERR_FILENO);
852 adb_close(fd[1]);
853
854 // child process
855 int result = execl(path, "adb", "fork-server", "server", NULL);
856 // this should not return
857 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
858 } else {
859 // parent side of the fork
860
861 char temp[3];
862
863 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
864 // wait for the "OK\n" message
865 adb_close(fd[1]);
866 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -0700867 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800868 adb_close(fd[0]);
869 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -0700870 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800871 return -1;
872 }
873 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
874 fprintf(stderr, "ADB server didn't ACK\n" );
875 return -1;
876 }
877
878 setsid();
879 }
880#else
881#error "cannot implement background server start on this platform"
882#endif
883 return 0;
884}
885#endif
886
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100887/* Constructs a local name of form tcp:port.
888 * target_str points to the target string, it's content will be overwritten.
889 * target_size is the capacity of the target string.
890 * server_port is the port number to use for the local name.
891 */
892void build_local_name(char* target_str, size_t target_size, int server_port)
893{
894 snprintf(target_str, target_size, "tcp:%d", server_port);
895}
896
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800897#if !ADB_HOST
898static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -0800899#ifndef ALLOW_ADBD_ROOT
900 return 1;
901#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800902 int secure = 0;
903 char value[PROPERTY_VALUE_MAX];
904
905 /* run adbd in secure mode if ro.secure is set and
906 ** we are not in the emulator
907 */
908 property_get("ro.kernel.qemu", value, "");
909 if (strcmp(value, "1") != 0) {
910 property_get("ro.secure", value, "1");
911 if (strcmp(value, "1") == 0) {
912 // don't run as root if ro.secure is set...
913 secure = 1;
914
915 // ... except we allow running as root in userdebug builds if the
916 // service.adb.root property has been set by the "adb root" command
917 property_get("ro.debuggable", value, "");
918 if (strcmp(value, "1") == 0) {
919 property_get("service.adb.root", value, "");
920 if (strcmp(value, "1") == 0) {
921 secure = 0;
922 }
923 }
924 }
925 }
926 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -0800927#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800928}
929#endif /* !ADB_HOST */
930
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100931int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800932{
933#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -0700934 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800935 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800936#endif
937
938 atexit(adb_cleanup);
939#ifdef HAVE_WIN32_PROC
940 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
941#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -0700942 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800943 signal(SIGPIPE, SIG_IGN);
944#endif
945
946 init_transport_registration();
947
948
949#if ADB_HOST
950 HOST = 1;
Xavier Ducroheta09fbd12009-05-20 17:33:53 -0700951 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800952 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100953 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100955 char local_name[30];
956 build_local_name(local_name, sizeof(local_name), server_port);
957 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800958 exit(1);
959 }
960#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800961
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100962 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800964 if (should_drop_privileges()) {
Mike Lockwood5f4b0512009-08-04 20:37:51 -0400965 struct __user_cap_header_struct header;
966 struct __user_cap_data_struct cap;
967
Nick Kralevich44db9902010-08-27 14:35:07 -0700968 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
969 exit(1);
970 }
Mike Lockwood5f4b0512009-08-04 20:37:51 -0400971
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800972 /* add extra groups:
973 ** AID_ADB to access the USB driver
974 ** AID_LOG to read system logs (adb logcat)
975 ** AID_INPUT to diagnose input issues (getevent)
976 ** AID_INET to diagnose network issues (netcfg, ping)
977 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -0700978 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Mike Lockwood6a3075c2009-05-25 13:52:00 -0400979 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -0500980 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -0800981 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800982 */
The Android Open Source Project20155492009-03-11 12:12:01 -0700983 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
JP Abgrall61b90bd2011-11-09 10:30:08 -0800984 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_RW, AID_MOUNT,
985 AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -0700986 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
987 exit(1);
988 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800989
990 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -0700991 if (setgid(AID_SHELL) != 0) {
992 exit(1);
993 }
994 if (setuid(AID_SHELL) != 0) {
995 exit(1);
996 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997
Mike Lockwood5f4b0512009-08-04 20:37:51 -0400998 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
999 header.version = _LINUX_CAPABILITY_VERSION;
1000 header.pid = 0;
1001 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1002 cap.inheritable = 0;
1003 capset(&header, &cap);
1004
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001005 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001006 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001007 char local_name[30];
1008 build_local_name(local_name, sizeof(local_name), server_port);
1009 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001010 exit(1);
1011 }
1012 }
1013
1014 /* for the device, start the usb transport if the
Mike Lockwood8e2ceae2010-04-20 14:06:40 -04001015 ** android usb device exists and the "service.adb.tcp.port" and
1016 ** "persist.adb.tcp.port" properties are not set.
1017 ** Otherwise start the network transport.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 */
Mike Lockwood8e2ceae2010-04-20 14:06:40 -04001019 property_get("service.adb.tcp.port", value, "");
1020 if (!value[0])
1021 property_get("persist.adb.tcp.port", value, "");
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001022 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1023 // listen on TCP port specified by service.adb.tcp.port property
1024 local_init(port);
1025 } else if (access("/dev/android_adb", F_OK) == 0) {
1026 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001027 usb_init();
1028 } else {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001029 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001030 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001031 }
JP Abgrall408fa572011-03-16 15:57:42 -07001032 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001033 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001034 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001035#endif
1036
1037 if (is_daemon)
1038 {
1039 // inform our parent that we are up and running.
1040#ifdef HAVE_WIN32_PROC
1041 DWORD count;
1042 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1043#elif defined(HAVE_FORKEXEC)
1044 fprintf(stderr, "OK\n");
1045#endif
1046 start_logging();
1047 }
JP Abgrall408fa572011-03-16 15:57:42 -07001048 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001049
1050 fdevent_loop();
1051
1052 usb_cleanup();
1053
1054 return 0;
1055}
1056
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001057#if ADB_HOST
1058void connect_device(char* host, char* buffer, int buffer_size)
1059{
1060 int port, fd;
1061 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001062 char hostbuf[100];
1063 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001064
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001065 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1066 if (portstr) {
1067 if (portstr - host >= sizeof(hostbuf)) {
1068 snprintf(buffer, buffer_size, "bad host name %s", host);
1069 return;
1070 }
1071 // zero terminate the host at the point we found the colon
1072 hostbuf[portstr - host] = 0;
1073 if (sscanf(portstr + 1, "%d", &port) == 0) {
1074 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1075 return;
1076 }
1077 } else {
1078 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001079 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001080
1081 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1082 if (find_transport(serial)) {
1083 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001084 return;
1085 }
1086
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001087 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001088 if (fd < 0) {
1089 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1090 return;
1091 }
1092
1093 D("client: connected on remote on fd %d\n", fd);
1094 close_on_exec(fd);
1095 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001096 register_socket_transport(fd, serial, port, 0);
1097 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001098}
1099
1100void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1101{
1102 char* port_separator = strchr(port_spec, ',');
1103 if (!port_separator) {
1104 snprintf(buffer, buffer_size,
1105 "unable to parse '%s' as <console port>,<adb port>",
1106 port_spec);
1107 return;
1108 }
1109
1110 // Zero-terminate console port and make port_separator point to 2nd port.
1111 *port_separator++ = 0;
1112 int console_port = strtol(port_spec, NULL, 0);
1113 int adb_port = strtol(port_separator, NULL, 0);
1114 if (!(console_port > 0 && adb_port > 0)) {
1115 *(port_separator - 1) = ',';
1116 snprintf(buffer, buffer_size,
1117 "Invalid port numbers: Expected positive numbers, got '%s'",
1118 port_spec);
1119 return;
1120 }
1121
1122 /* Check if the emulator is already known.
1123 * Note: There's a small but harmless race condition here: An emulator not
1124 * present just yet could be registered by another invocation right
1125 * after doing this check here. However, local_connect protects
1126 * against double-registration too. From here, a better error message
1127 * can be produced. In the case of the race condition, the very specific
1128 * error message won't be shown, but the data doesn't get corrupted. */
1129 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1130 if (known_emulator != NULL) {
1131 snprintf(buffer, buffer_size,
1132 "Emulator on port %d already registered.", adb_port);
1133 return;
1134 }
1135
1136 /* Check if more emulators can be registered. Similar unproblematic
1137 * race condition as above. */
1138 int candidate_slot = get_available_local_transport_index();
1139 if (candidate_slot < 0) {
1140 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1141 return;
1142 }
1143
1144 /* Preconditions met, try to connect to the emulator. */
1145 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1146 snprintf(buffer, buffer_size,
1147 "Connected to emulator on ports %d,%d", console_port, adb_port);
1148 } else {
1149 snprintf(buffer, buffer_size,
1150 "Could not connect to emulator on ports %d,%d",
1151 console_port, adb_port);
1152 }
1153}
1154#endif
1155
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001156int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1157{
1158 atransport *transport = NULL;
1159 char buf[4096];
1160
1161 if(!strcmp(service, "kill")) {
1162 fprintf(stderr,"adb server killed by remote request\n");
1163 fflush(stdout);
1164 adb_write(reply_fd, "OKAY", 4);
1165 usb_cleanup();
1166 exit(0);
1167 }
1168
1169#if ADB_HOST
1170 // "transport:" is used for switching transport with a specified serial number
1171 // "transport-usb:" is used for switching transport to the only USB transport
1172 // "transport-local:" is used for switching transport to the only local transport
1173 // "transport-any:" is used for switching transport to the only transport
1174 if (!strncmp(service, "transport", strlen("transport"))) {
1175 char* error_string = "unknown failure";
1176 transport_type type = kTransportAny;
1177
1178 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1179 type = kTransportUsb;
1180 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1181 type = kTransportLocal;
1182 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1183 type = kTransportAny;
1184 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1185 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001186 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187 }
1188
1189 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1190
1191 if (transport) {
1192 s->transport = transport;
1193 adb_write(reply_fd, "OKAY", 4);
1194 } else {
1195 sendfailmsg(reply_fd, error_string);
1196 }
1197 return 1;
1198 }
1199
1200 // return a list of all connected devices
1201 if (!strcmp(service, "devices")) {
1202 char buffer[4096];
1203 memset(buf, 0, sizeof(buf));
1204 memset(buffer, 0, sizeof(buffer));
1205 D("Getting device list \n");
1206 list_transports(buffer, sizeof(buffer));
1207 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1208 D("Wrote device list \n");
1209 writex(reply_fd, buf, strlen(buf));
1210 return 0;
1211 }
1212
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001213 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001214 if (!strncmp(service, "connect:", 8)) {
1215 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001216 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001217 if (!strncmp(host, "emu:", 4)) {
1218 connect_emulator(host + 4, buffer, sizeof(buffer));
1219 } else {
1220 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001221 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001222 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001223 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1224 writex(reply_fd, buf, strlen(buf));
1225 return 0;
1226 }
1227
1228 // remove TCP transport
1229 if (!strncmp(service, "disconnect:", 11)) {
1230 char buffer[4096];
1231 memset(buffer, 0, sizeof(buffer));
1232 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001233 if (serial[0] == 0) {
1234 // disconnect from all TCP devices
1235 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001236 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001237 char hostbuf[100];
1238 // assume port 5555 if no port is specified
1239 if (!strchr(serial, ':')) {
1240 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1241 serial = hostbuf;
1242 }
1243 atransport *t = find_transport(serial);
1244
1245 if (t) {
1246 unregister_transport(t);
1247 } else {
1248 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1249 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001250 }
1251
1252 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001253 writex(reply_fd, buf, strlen(buf));
1254 return 0;
1255 }
1256
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001257 // returns our value for ADB_SERVER_VERSION
1258 if (!strcmp(service, "version")) {
1259 char version[12];
1260 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1261 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1262 writex(reply_fd, buf, strlen(buf));
1263 return 0;
1264 }
1265
1266 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1267 char *out = "unknown";
1268 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1269 if (transport && transport->serial) {
1270 out = transport->serial;
1271 }
1272 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1273 writex(reply_fd, buf, strlen(buf));
1274 return 0;
1275 }
1276 // indicates a new emulator instance has started
1277 if (!strncmp(service,"emulator:",9)) {
1278 int port = atoi(service+9);
1279 local_connect(port);
1280 /* we don't even need to send a reply */
1281 return 0;
1282 }
1283#endif // ADB_HOST
1284
1285 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1286 char *local, *remote, *err;
1287 int r;
1288 atransport *transport;
1289
1290 int createForward = strncmp(service,"kill",4);
1291
1292 local = service + (createForward ? 8 : 12);
1293 remote = strchr(local,';');
1294 if(remote == 0) {
1295 sendfailmsg(reply_fd, "malformed forward spec");
1296 return 0;
1297 }
1298
1299 *remote++ = 0;
1300 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1301 sendfailmsg(reply_fd, "malformed forward spec");
1302 return 0;
1303 }
1304
1305 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1306 if (!transport) {
1307 sendfailmsg(reply_fd, err);
1308 return 0;
1309 }
1310
1311 if (createForward) {
1312 r = install_listener(local, remote, transport);
1313 } else {
1314 r = remove_listener(local, remote, transport);
1315 }
1316 if(r == 0) {
1317 /* 1st OKAY is connect, 2nd OKAY is status */
1318 writex(reply_fd, "OKAYOKAY", 8);
1319 return 0;
1320 }
1321
1322 if (createForward) {
1323 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1324 } else {
1325 sendfailmsg(reply_fd, "cannot remove listener");
1326 }
1327 return 0;
1328 }
1329
1330 if(!strncmp(service,"get-state",strlen("get-state"))) {
1331 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1332 char *state = connection_state_name(transport);
1333 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1334 writex(reply_fd, buf, strlen(buf));
1335 return 0;
1336 }
1337 return -1;
1338}
1339
1340#if !ADB_HOST
1341int recovery_mode = 0;
1342#endif
1343
1344int main(int argc, char **argv)
1345{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001346#if ADB_HOST
1347 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001348 adb_trace_init();
1349 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001350 return adb_commandline(argc - 1, argv + 1);
1351#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001352 /* If adbd runs inside the emulator this will enable adb tracing via
1353 * adb-debug qemud service in the emulator. */
1354 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001355 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1356 adb_device_banner = "recovery";
1357 recovery_mode = 1;
1358 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001359
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001360 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001361 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001362 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001363#endif
1364}