blob: 001fae1449a9f38bfd0f660dc5832e978c3ff3e2 [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)
Dianne Hackborn50458cf2012-03-07 12:57:14 -0800979 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -0400980 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -0500981 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -0800982 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800983 */
The Android Open Source Project20155492009-03-11 12:12:01 -0700984 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -0800985 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
986 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -0700987 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
988 exit(1);
989 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990
991 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -0700992 if (setgid(AID_SHELL) != 0) {
993 exit(1);
994 }
995 if (setuid(AID_SHELL) != 0) {
996 exit(1);
997 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800998
Mike Lockwood5f4b0512009-08-04 20:37:51 -0400999 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1000 header.version = _LINUX_CAPABILITY_VERSION;
1001 header.pid = 0;
1002 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1003 cap.inheritable = 0;
1004 capset(&header, &cap);
1005
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001006 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001008 char local_name[30];
1009 build_local_name(local_name, sizeof(local_name), server_port);
1010 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011 exit(1);
1012 }
1013 }
1014
1015 /* for the device, start the usb transport if the
Mike Lockwood8e2ceae2010-04-20 14:06:40 -04001016 ** android usb device exists and the "service.adb.tcp.port" and
1017 ** "persist.adb.tcp.port" properties are not set.
1018 ** Otherwise start the network transport.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001019 */
Mike Lockwood8e2ceae2010-04-20 14:06:40 -04001020 property_get("service.adb.tcp.port", value, "");
1021 if (!value[0])
1022 property_get("persist.adb.tcp.port", value, "");
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001023 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1024 // listen on TCP port specified by service.adb.tcp.port property
1025 local_init(port);
1026 } else if (access("/dev/android_adb", F_OK) == 0) {
1027 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001028 usb_init();
1029 } else {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001030 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001031 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001032 }
JP Abgrall408fa572011-03-16 15:57:42 -07001033 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001034 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001035 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001036#endif
1037
1038 if (is_daemon)
1039 {
1040 // inform our parent that we are up and running.
1041#ifdef HAVE_WIN32_PROC
1042 DWORD count;
1043 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1044#elif defined(HAVE_FORKEXEC)
1045 fprintf(stderr, "OK\n");
1046#endif
1047 start_logging();
1048 }
JP Abgrall408fa572011-03-16 15:57:42 -07001049 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001050
1051 fdevent_loop();
1052
1053 usb_cleanup();
1054
1055 return 0;
1056}
1057
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001058#if ADB_HOST
1059void connect_device(char* host, char* buffer, int buffer_size)
1060{
1061 int port, fd;
1062 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001063 char hostbuf[100];
1064 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001065
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001066 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1067 if (portstr) {
1068 if (portstr - host >= sizeof(hostbuf)) {
1069 snprintf(buffer, buffer_size, "bad host name %s", host);
1070 return;
1071 }
1072 // zero terminate the host at the point we found the colon
1073 hostbuf[portstr - host] = 0;
1074 if (sscanf(portstr + 1, "%d", &port) == 0) {
1075 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1076 return;
1077 }
1078 } else {
1079 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001080 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001081
1082 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1083 if (find_transport(serial)) {
1084 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001085 return;
1086 }
1087
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001088 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001089 if (fd < 0) {
1090 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1091 return;
1092 }
1093
1094 D("client: connected on remote on fd %d\n", fd);
1095 close_on_exec(fd);
1096 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001097 register_socket_transport(fd, serial, port, 0);
1098 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001099}
1100
1101void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1102{
1103 char* port_separator = strchr(port_spec, ',');
1104 if (!port_separator) {
1105 snprintf(buffer, buffer_size,
1106 "unable to parse '%s' as <console port>,<adb port>",
1107 port_spec);
1108 return;
1109 }
1110
1111 // Zero-terminate console port and make port_separator point to 2nd port.
1112 *port_separator++ = 0;
1113 int console_port = strtol(port_spec, NULL, 0);
1114 int adb_port = strtol(port_separator, NULL, 0);
1115 if (!(console_port > 0 && adb_port > 0)) {
1116 *(port_separator - 1) = ',';
1117 snprintf(buffer, buffer_size,
1118 "Invalid port numbers: Expected positive numbers, got '%s'",
1119 port_spec);
1120 return;
1121 }
1122
1123 /* Check if the emulator is already known.
1124 * Note: There's a small but harmless race condition here: An emulator not
1125 * present just yet could be registered by another invocation right
1126 * after doing this check here. However, local_connect protects
1127 * against double-registration too. From here, a better error message
1128 * can be produced. In the case of the race condition, the very specific
1129 * error message won't be shown, but the data doesn't get corrupted. */
1130 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1131 if (known_emulator != NULL) {
1132 snprintf(buffer, buffer_size,
1133 "Emulator on port %d already registered.", adb_port);
1134 return;
1135 }
1136
1137 /* Check if more emulators can be registered. Similar unproblematic
1138 * race condition as above. */
1139 int candidate_slot = get_available_local_transport_index();
1140 if (candidate_slot < 0) {
1141 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1142 return;
1143 }
1144
1145 /* Preconditions met, try to connect to the emulator. */
1146 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1147 snprintf(buffer, buffer_size,
1148 "Connected to emulator on ports %d,%d", console_port, adb_port);
1149 } else {
1150 snprintf(buffer, buffer_size,
1151 "Could not connect to emulator on ports %d,%d",
1152 console_port, adb_port);
1153 }
1154}
1155#endif
1156
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001157int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1158{
1159 atransport *transport = NULL;
1160 char buf[4096];
1161
1162 if(!strcmp(service, "kill")) {
1163 fprintf(stderr,"adb server killed by remote request\n");
1164 fflush(stdout);
1165 adb_write(reply_fd, "OKAY", 4);
1166 usb_cleanup();
1167 exit(0);
1168 }
1169
1170#if ADB_HOST
1171 // "transport:" is used for switching transport with a specified serial number
1172 // "transport-usb:" is used for switching transport to the only USB transport
1173 // "transport-local:" is used for switching transport to the only local transport
1174 // "transport-any:" is used for switching transport to the only transport
1175 if (!strncmp(service, "transport", strlen("transport"))) {
1176 char* error_string = "unknown failure";
1177 transport_type type = kTransportAny;
1178
1179 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1180 type = kTransportUsb;
1181 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1182 type = kTransportLocal;
1183 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1184 type = kTransportAny;
1185 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1186 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001187 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001188 }
1189
1190 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1191
1192 if (transport) {
1193 s->transport = transport;
1194 adb_write(reply_fd, "OKAY", 4);
1195 } else {
1196 sendfailmsg(reply_fd, error_string);
1197 }
1198 return 1;
1199 }
1200
1201 // return a list of all connected devices
1202 if (!strcmp(service, "devices")) {
1203 char buffer[4096];
1204 memset(buf, 0, sizeof(buf));
1205 memset(buffer, 0, sizeof(buffer));
1206 D("Getting device list \n");
1207 list_transports(buffer, sizeof(buffer));
1208 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1209 D("Wrote device list \n");
1210 writex(reply_fd, buf, strlen(buf));
1211 return 0;
1212 }
1213
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001214 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001215 if (!strncmp(service, "connect:", 8)) {
1216 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001217 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001218 if (!strncmp(host, "emu:", 4)) {
1219 connect_emulator(host + 4, buffer, sizeof(buffer));
1220 } else {
1221 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001222 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001223 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001224 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1225 writex(reply_fd, buf, strlen(buf));
1226 return 0;
1227 }
1228
1229 // remove TCP transport
1230 if (!strncmp(service, "disconnect:", 11)) {
1231 char buffer[4096];
1232 memset(buffer, 0, sizeof(buffer));
1233 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001234 if (serial[0] == 0) {
1235 // disconnect from all TCP devices
1236 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001237 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001238 char hostbuf[100];
1239 // assume port 5555 if no port is specified
1240 if (!strchr(serial, ':')) {
1241 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1242 serial = hostbuf;
1243 }
1244 atransport *t = find_transport(serial);
1245
1246 if (t) {
1247 unregister_transport(t);
1248 } else {
1249 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1250 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001251 }
1252
1253 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001254 writex(reply_fd, buf, strlen(buf));
1255 return 0;
1256 }
1257
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001258 // returns our value for ADB_SERVER_VERSION
1259 if (!strcmp(service, "version")) {
1260 char version[12];
1261 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1262 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1263 writex(reply_fd, buf, strlen(buf));
1264 return 0;
1265 }
1266
1267 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1268 char *out = "unknown";
1269 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1270 if (transport && transport->serial) {
1271 out = transport->serial;
1272 }
1273 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1274 writex(reply_fd, buf, strlen(buf));
1275 return 0;
1276 }
1277 // indicates a new emulator instance has started
1278 if (!strncmp(service,"emulator:",9)) {
1279 int port = atoi(service+9);
1280 local_connect(port);
1281 /* we don't even need to send a reply */
1282 return 0;
1283 }
1284#endif // ADB_HOST
1285
1286 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1287 char *local, *remote, *err;
1288 int r;
1289 atransport *transport;
1290
1291 int createForward = strncmp(service,"kill",4);
1292
1293 local = service + (createForward ? 8 : 12);
1294 remote = strchr(local,';');
1295 if(remote == 0) {
1296 sendfailmsg(reply_fd, "malformed forward spec");
1297 return 0;
1298 }
1299
1300 *remote++ = 0;
1301 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1302 sendfailmsg(reply_fd, "malformed forward spec");
1303 return 0;
1304 }
1305
1306 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1307 if (!transport) {
1308 sendfailmsg(reply_fd, err);
1309 return 0;
1310 }
1311
1312 if (createForward) {
1313 r = install_listener(local, remote, transport);
1314 } else {
1315 r = remove_listener(local, remote, transport);
1316 }
1317 if(r == 0) {
1318 /* 1st OKAY is connect, 2nd OKAY is status */
1319 writex(reply_fd, "OKAYOKAY", 8);
1320 return 0;
1321 }
1322
1323 if (createForward) {
1324 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1325 } else {
1326 sendfailmsg(reply_fd, "cannot remove listener");
1327 }
1328 return 0;
1329 }
1330
1331 if(!strncmp(service,"get-state",strlen("get-state"))) {
1332 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1333 char *state = connection_state_name(transport);
1334 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1335 writex(reply_fd, buf, strlen(buf));
1336 return 0;
1337 }
1338 return -1;
1339}
1340
1341#if !ADB_HOST
1342int recovery_mode = 0;
1343#endif
1344
1345int main(int argc, char **argv)
1346{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001347#if ADB_HOST
1348 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001349 adb_trace_init();
1350 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001351 return adb_commandline(argc - 1, argv + 1);
1352#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001353 /* If adbd runs inside the emulator this will enable adb tracing via
1354 * adb-debug qemud service in the emulator. */
1355 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001356 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1357 adb_device_banner = "recovery";
1358 recovery_mode = 1;
1359 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001360
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001361 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001362 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001363 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001364#endif
1365}