blob: 8b04fda390c7dc72c76ed332fd3df3944018fa97 [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>
Scott Andersonc7993af2012-05-25 13:55:46 -070024#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <string.h>
26#include <time.h>
Mike Lockwood1f546e62009-05-25 18:17:55 -040027#include <sys/time.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080028
29#include "sysdeps.h"
30#include "adb.h"
31
Scott Andersone82c2db2012-05-25 14:10:02 -070032#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
33
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080034#if !ADB_HOST
35#include <private/android_filesystem_config.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040036#include <linux/capability.h>
37#include <linux/prctl.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070038#include <sys/mount.h>
Xavier Ducroheta09fbd12009-05-20 17:33:53 -070039#else
40#include "usb_vendors.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080041#endif
42
JP Abgrall408fa572011-03-16 15:57:42 -070043#if ADB_TRACE
44ADB_MUTEX_DEFINE( D_lock );
45#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046
47int HOST = 0;
48
Scott Andersone82c2db2012-05-25 14:10:02 -070049#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050static const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070051#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080052
53void fatal(const char *fmt, ...)
54{
55 va_list ap;
56 va_start(ap, fmt);
57 fprintf(stderr, "error: ");
58 vfprintf(stderr, fmt, ap);
59 fprintf(stderr, "\n");
60 va_end(ap);
61 exit(-1);
62}
63
64void fatal_errno(const char *fmt, ...)
65{
66 va_list ap;
67 va_start(ap, fmt);
68 fprintf(stderr, "error: %s: ", strerror(errno));
69 vfprintf(stderr, fmt, ap);
70 fprintf(stderr, "\n");
71 va_end(ap);
72 exit(-1);
73}
74
75int adb_trace_mask;
76
77/* read a comma/space/colum/semi-column separated list of tags
78 * from the ADB_TRACE environment variable and build the trace
79 * mask from it. note that '1' and 'all' are special cases to
80 * enable all tracing
81 */
82void adb_trace_init(void)
83{
84 const char* p = getenv("ADB_TRACE");
85 const char* q;
86
87 static const struct {
88 const char* tag;
89 int flag;
90 } tags[] = {
91 { "1", 0 },
92 { "all", 0 },
93 { "adb", TRACE_ADB },
94 { "sockets", TRACE_SOCKETS },
95 { "packets", TRACE_PACKETS },
96 { "rwx", TRACE_RWX },
97 { "usb", TRACE_USB },
98 { "sync", TRACE_SYNC },
99 { "sysdeps", TRACE_SYSDEPS },
100 { "transport", TRACE_TRANSPORT },
101 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700102 { "services", TRACE_SERVICES },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800103 { NULL, 0 }
104 };
105
106 if (p == NULL)
107 return;
108
109 /* use a comma/column/semi-colum/space separated list */
110 while (*p) {
111 int len, tagn;
112
113 q = strpbrk(p, " ,:;");
114 if (q == NULL) {
115 q = p + strlen(p);
116 }
117 len = q - p;
118
119 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
120 {
121 int taglen = strlen(tags[tagn].tag);
122
123 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
124 {
125 int flag = tags[tagn].flag;
126 if (flag == 0) {
127 adb_trace_mask = ~0;
128 return;
129 }
130 adb_trace_mask |= (1 << flag);
131 break;
132 }
133 }
134 p = q;
135 if (*p)
136 p++;
137 }
138}
139
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800140#if !ADB_HOST
141/*
142 * Implements ADB tracing inside the emulator.
143 */
144
145#include <stdarg.h>
146
147/*
148 * Redefine open and write for qemu_pipe.h that contains inlined references
149 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
150 */
151
152#undef open
153#undef write
154#define open adb_open
155#define write adb_write
156#include <hardware/qemu_pipe.h>
157#undef open
158#undef write
159#define open ___xxx_open
160#define write ___xxx_write
161
162/* A handle to adb-debug qemud service in the emulator. */
163int adb_debug_qemu = -1;
164
165/* Initializes connection with the adb-debug qemud service in the emulator. */
166static int adb_qemu_trace_init(void)
167{
168 char con_name[32];
169
170 if (adb_debug_qemu >= 0) {
171 return 0;
172 }
173
174 /* adb debugging QEMUD service connection request. */
175 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
176 adb_debug_qemu = qemu_pipe_open(con_name);
177 return (adb_debug_qemu >= 0) ? 0 : -1;
178}
179
180void adb_qemu_trace(const char* fmt, ...)
181{
182 va_list args;
183 va_start(args, fmt);
184 char msg[1024];
185
186 if (adb_debug_qemu >= 0) {
187 vsnprintf(msg, sizeof(msg), fmt, args);
188 adb_write(adb_debug_qemu, msg, strlen(msg));
189 }
190}
191#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192
193apacket *get_apacket(void)
194{
195 apacket *p = malloc(sizeof(apacket));
196 if(p == 0) fatal("failed to allocate an apacket");
197 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
198 return p;
199}
200
201void put_apacket(apacket *p)
202{
203 free(p);
204}
205
Benoit Goby3fc95a92012-08-20 23:04:11 -0700206void handle_online(void)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207{
208 D("adb: online\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800209}
210
211void handle_offline(atransport *t)
212{
213 D("adb: offline\n");
214 //Close the associated usb
215 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800216}
217
Benoit Goby3fc95a92012-08-20 23:04:11 -0700218#if TRACE_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800219#define DUMPMAX 32
220void print_packet(const char *label, apacket *p)
221{
222 char *tag;
223 char *x;
224 unsigned count;
225
226 switch(p->msg.command){
227 case A_SYNC: tag = "SYNC"; break;
228 case A_CNXN: tag = "CNXN" ; break;
229 case A_OPEN: tag = "OPEN"; break;
230 case A_OKAY: tag = "OKAY"; break;
231 case A_CLSE: tag = "CLSE"; break;
232 case A_WRTE: tag = "WRTE"; break;
233 default: tag = "????"; break;
234 }
235
236 fprintf(stderr, "%s: %s %08x %08x %04x \"",
237 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
238 count = p->msg.data_length;
239 x = (char*) p->data;
240 if(count > DUMPMAX) {
241 count = DUMPMAX;
242 tag = "\n";
243 } else {
244 tag = "\"\n";
245 }
246 while(count-- > 0){
247 if((*x >= ' ') && (*x < 127)) {
248 fputc(*x, stderr);
249 } else {
250 fputc('.', stderr);
251 }
252 x++;
253 }
Benoit Goby3fc95a92012-08-20 23:04:11 -0700254 fprintf(stderr, tag);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800255}
256#endif
257
258static void send_ready(unsigned local, unsigned remote, atransport *t)
259{
260 D("Calling send_ready \n");
261 apacket *p = get_apacket();
262 p->msg.command = A_OKAY;
263 p->msg.arg0 = local;
264 p->msg.arg1 = remote;
265 send_packet(p, t);
266}
267
268static void send_close(unsigned local, unsigned remote, atransport *t)
269{
270 D("Calling send_close \n");
271 apacket *p = get_apacket();
272 p->msg.command = A_CLSE;
273 p->msg.arg0 = local;
274 p->msg.arg1 = remote;
275 send_packet(p, t);
276}
277
Scott Andersone82c2db2012-05-25 14:10:02 -0700278static size_t fill_connect_data(char *buf, size_t bufsize)
279{
280#if ADB_HOST
281 return snprintf(buf, bufsize, "host::") + 1;
282#else
283 static const char *cnxn_props[] = {
284 "ro.product.name",
285 "ro.product.model",
286 "ro.product.device",
287 };
288 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
289 int i;
290 size_t remaining = bufsize;
291 size_t len;
292
293 len = snprintf(buf, remaining, "%s::", adb_device_banner);
294 remaining -= len;
295 buf += len;
296 for (i = 0; i < num_cnxn_props; i++) {
297 char value[PROPERTY_VALUE_MAX];
298 property_get(cnxn_props[i], value, "");
299 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
300 remaining -= len;
301 buf += len;
302 }
303
304 return bufsize - remaining + 1;
305#endif
306}
307
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800308static void send_connect(atransport *t)
309{
310 D("Calling send_connect \n");
311 apacket *cp = get_apacket();
312 cp->msg.command = A_CNXN;
313 cp->msg.arg0 = A_VERSION;
314 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700315 cp->msg.data_length = fill_connect_data((char *)cp->data,
316 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317 send_packet(cp, t);
Benoit Goby3fc95a92012-08-20 23:04:11 -0700318#if ADB_HOST
319 /* XXX why sleep here? */
320 // allow the device some time to respond to the connect message
321 adb_sleep_ms(1000);
322#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800323}
324
325static char *connection_state_name(atransport *t)
326{
327 if (t == NULL) {
328 return "unknown";
329 }
330
331 switch(t->connection_state) {
332 case CS_BOOTLOADER:
333 return "bootloader";
334 case CS_DEVICE:
335 return "device";
336 case CS_OFFLINE:
337 return "offline";
338 default:
339 return "unknown";
340 }
341}
342
Scott Andersone82c2db2012-05-25 14:10:02 -0700343/* qual_overwrite is used to overwrite a qualifier string. dst is a
344 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700345 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700346 */
347static void qual_overwrite(char **dst, const char *src)
348{
349 if (!dst)
350 return;
351
352 free(*dst);
353 *dst = NULL;
354
355 if (!src || !*src)
356 return;
357
358 *dst = strdup(src);
359}
360
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800361void parse_banner(char *banner, atransport *t)
362{
Scott Andersone82c2db2012-05-25 14:10:02 -0700363 static const char *prop_seps = ";";
364 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700365 char *cp;
366 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800367
368 D("parse_banner: %s\n", banner);
369 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700370 cp = strchr(type, ':');
371 if (cp) {
372 *cp++ = 0;
373 /* Nothing is done with second field. */
374 cp = strchr(cp, ':');
375 if (cp) {
376 char *save;
377 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700378 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700379 while (key) {
380 cp = strchr(key, key_val_sep);
381 if (cp) {
382 *cp++ = '\0';
383 if (!strcmp(key, "ro.product.name"))
384 qual_overwrite(&t->product, cp);
385 else if (!strcmp(key, "ro.product.model"))
386 qual_overwrite(&t->model, cp);
387 else if (!strcmp(key, "ro.product.device"))
388 qual_overwrite(&t->device, cp);
389 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700390 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700391 }
392 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393 }
394
395 if(!strcmp(type, "bootloader")){
396 D("setting connection_state to CS_BOOTLOADER\n");
397 t->connection_state = CS_BOOTLOADER;
398 update_transports();
399 return;
400 }
401
402 if(!strcmp(type, "device")) {
403 D("setting connection_state to CS_DEVICE\n");
404 t->connection_state = CS_DEVICE;
405 update_transports();
406 return;
407 }
408
409 if(!strcmp(type, "recovery")) {
410 D("setting connection_state to CS_RECOVERY\n");
411 t->connection_state = CS_RECOVERY;
412 update_transports();
413 return;
414 }
415
Doug Zongker447f0612012-01-09 14:54:53 -0800416 if(!strcmp(type, "sideload")) {
417 D("setting connection_state to CS_SIDELOAD\n");
418 t->connection_state = CS_SIDELOAD;
419 update_transports();
420 return;
421 }
422
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423 t->connection_state = CS_HOST;
424}
425
426void handle_packet(apacket *p, atransport *t)
427{
428 asocket *s;
429
Viral Mehta899913f2010-06-16 18:41:28 +0530430 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
431 ((char*) (&(p->msg.command)))[1],
432 ((char*) (&(p->msg.command)))[2],
433 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 print_packet("recv", p);
435
436 switch(p->msg.command){
437 case A_SYNC:
438 if(p->msg.arg0){
439 send_packet(p, t);
440 if(HOST) send_connect(t);
441 } else {
442 t->connection_state = CS_OFFLINE;
443 handle_offline(t);
444 send_packet(p, t);
445 }
446 return;
447
448 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
449 /* XXX verify version, etc */
450 if(t->connection_state != CS_OFFLINE) {
451 t->connection_state = CS_OFFLINE;
452 handle_offline(t);
453 }
454 parse_banner((char*) p->data, t);
Benoit Goby3fc95a92012-08-20 23:04:11 -0700455 handle_online();
456 if(!HOST) send_connect(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457 break;
458
459 case A_OPEN: /* OPEN(local-id, 0, "destination") */
Benoit Goby3fc95a92012-08-20 23:04:11 -0700460 if(t->connection_state != CS_OFFLINE) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461 char *name = (char*) p->data;
462 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
463 s = create_local_service_socket(name);
464 if(s == 0) {
465 send_close(0, p->msg.arg0, t);
466 } else {
467 s->peer = create_remote_socket(p->msg.arg0, t);
468 s->peer->peer = s;
469 send_ready(s->id, s->peer->id, t);
470 s->ready(s);
471 }
472 }
473 break;
474
475 case A_OKAY: /* READY(local-id, remote-id, "") */
Benoit Goby3fc95a92012-08-20 23:04:11 -0700476 if(t->connection_state != CS_OFFLINE) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477 if((s = find_local_socket(p->msg.arg1))) {
478 if(s->peer == 0) {
479 s->peer = create_remote_socket(p->msg.arg0, t);
480 s->peer->peer = s;
481 }
482 s->ready(s);
483 }
484 }
485 break;
486
487 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
Benoit Goby3fc95a92012-08-20 23:04:11 -0700488 if(t->connection_state != CS_OFFLINE) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489 if((s = find_local_socket(p->msg.arg1))) {
490 s->close(s);
491 }
492 }
493 break;
494
495 case A_WRTE:
Benoit Goby3fc95a92012-08-20 23:04:11 -0700496 if(t->connection_state != CS_OFFLINE) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497 if((s = find_local_socket(p->msg.arg1))) {
498 unsigned rid = p->msg.arg0;
499 p->len = p->msg.data_length;
500
501 if(s->enqueue(s, p) == 0) {
502 D("Enqueue the socket\n");
503 send_ready(s->id, rid, t);
504 }
505 return;
506 }
507 }
508 break;
509
510 default:
511 printf("handle_packet: what is %08x?!\n", p->msg.command);
512 }
513
514 put_apacket(p);
515}
516
517alistener listener_list = {
518 .next = &listener_list,
519 .prev = &listener_list,
520};
521
522static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
523{
524 asocket *s;
525
526 if(ev & FDE_READ) {
527 struct sockaddr addr;
528 socklen_t alen;
529 int fd;
530
531 alen = sizeof(addr);
532 fd = adb_socket_accept(_fd, &addr, &alen);
533 if(fd < 0) return;
534
535 adb_socket_setbufsize(fd, CHUNK_SIZE);
536
537 s = create_local_socket(fd);
538 if(s) {
539 connect_to_smartsocket(s);
540 return;
541 }
542
543 adb_close(fd);
544 }
545}
546
547static void listener_event_func(int _fd, unsigned ev, void *_l)
548{
549 alistener *l = _l;
550 asocket *s;
551
552 if(ev & FDE_READ) {
553 struct sockaddr addr;
554 socklen_t alen;
555 int fd;
556
557 alen = sizeof(addr);
558 fd = adb_socket_accept(_fd, &addr, &alen);
559 if(fd < 0) return;
560
561 s = create_local_socket(fd);
562 if(s) {
563 s->transport = l->transport;
564 connect_to_remote(s, l->connect_to);
565 return;
566 }
567
568 adb_close(fd);
569 }
570}
571
572static void free_listener(alistener* l)
573{
574 if (l->next) {
575 l->next->prev = l->prev;
576 l->prev->next = l->next;
577 l->next = l->prev = l;
578 }
579
580 // closes the corresponding fd
581 fdevent_remove(&l->fde);
582
583 if (l->local_name)
584 free((char*)l->local_name);
585
586 if (l->connect_to)
587 free((char*)l->connect_to);
588
589 if (l->transport) {
590 remove_transport_disconnect(l->transport, &l->disconnect);
591 }
592 free(l);
593}
594
595static void listener_disconnect(void* _l, atransport* t)
596{
597 alistener* l = _l;
598
599 free_listener(l);
600}
601
602int local_name_to_fd(const char *name)
603{
604 int port;
605
606 if(!strncmp("tcp:", name, 4)){
607 int ret;
608 port = atoi(name + 4);
609 ret = socket_loopback_server(port, SOCK_STREAM);
610 return ret;
611 }
612#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
613 // It's non-sensical to support the "reserved" space on the adb host side
614 if(!strncmp(name, "local:", 6)) {
615 return socket_local_server(name + 6,
616 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
617 } else if(!strncmp(name, "localabstract:", 14)) {
618 return socket_local_server(name + 14,
619 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
620 } else if(!strncmp(name, "localfilesystem:", 16)) {
621 return socket_local_server(name + 16,
622 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
623 }
624
625#endif
626 printf("unknown local portname '%s'\n", name);
627 return -1;
628}
629
630static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
631{
632 alistener *l;
633
634 for (l = listener_list.next; l != &listener_list; l = l->next) {
635 if (!strcmp(local_name, l->local_name) &&
636 !strcmp(connect_to, l->connect_to) &&
637 l->transport && l->transport == transport) {
638
639 listener_disconnect(l, transport);
640 return 0;
641 }
642 }
643
644 return -1;
645}
646
647static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
648{
649 alistener *l;
650
651 //printf("install_listener('%s','%s')\n", local_name, connect_to);
652
653 for(l = listener_list.next; l != &listener_list; l = l->next){
654 if(strcmp(local_name, l->local_name) == 0) {
655 char *cto;
656
657 /* can't repurpose a smartsocket */
658 if(l->connect_to[0] == '*') {
659 return -1;
660 }
661
662 cto = strdup(connect_to);
663 if(cto == 0) {
664 return -1;
665 }
666
667 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
668 free((void*) l->connect_to);
669 l->connect_to = cto;
670 if (l->transport != transport) {
671 remove_transport_disconnect(l->transport, &l->disconnect);
672 l->transport = transport;
673 add_transport_disconnect(l->transport, &l->disconnect);
674 }
675 return 0;
676 }
677 }
678
679 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
680 if((l->local_name = strdup(local_name)) == 0) goto nomem;
681 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
682
683
684 l->fd = local_name_to_fd(local_name);
685 if(l->fd < 0) {
686 free((void*) l->local_name);
687 free((void*) l->connect_to);
688 free(l);
689 printf("cannot bind '%s'\n", local_name);
690 return -2;
691 }
692
693 close_on_exec(l->fd);
694 if(!strcmp(l->connect_to, "*smartsocket*")) {
695 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
696 } else {
697 fdevent_install(&l->fde, l->fd, listener_event_func, l);
698 }
699 fdevent_set(&l->fde, FDE_READ);
700
701 l->next = &listener_list;
702 l->prev = listener_list.prev;
703 l->next->prev = l;
704 l->prev->next = l;
705 l->transport = transport;
706
707 if (transport) {
708 l->disconnect.opaque = l;
709 l->disconnect.func = listener_disconnect;
710 add_transport_disconnect(transport, &l->disconnect);
711 }
712 return 0;
713
714nomem:
715 fatal("cannot allocate listener");
716 return 0;
717}
718
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719#ifdef HAVE_WIN32_PROC
720static BOOL WINAPI ctrlc_handler(DWORD type)
721{
722 exit(STATUS_CONTROL_C_EXIT);
723 return TRUE;
724}
725#endif
726
727static void adb_cleanup(void)
728{
729 usb_cleanup();
730}
731
732void start_logging(void)
733{
734#ifdef HAVE_WIN32_PROC
735 char temp[ MAX_PATH ];
736 FILE* fnul;
737 FILE* flog;
738
739 GetTempPath( sizeof(temp) - 8, temp );
740 strcat( temp, "adb.log" );
741
742 /* Win32 specific redirections */
743 fnul = fopen( "NUL", "rt" );
744 if (fnul != NULL)
745 stdin[0] = fnul[0];
746
747 flog = fopen( temp, "at" );
748 if (flog == NULL)
749 flog = fnul;
750
751 setvbuf( flog, NULL, _IONBF, 0 );
752
753 stdout[0] = flog[0];
754 stderr[0] = flog[0];
755 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
756#else
757 int fd;
758
759 fd = unix_open("/dev/null", O_RDONLY);
760 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700761 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800762
763 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
764 if(fd < 0) {
765 fd = unix_open("/dev/null", O_WRONLY);
766 }
767 dup2(fd, 1);
768 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700769 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
771#endif
772}
773
774#if !ADB_HOST
775void start_device_log(void)
776{
777 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400778 char path[PATH_MAX];
779 struct tm now;
780 time_t t;
781 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800782
Mike Lockwood1f546e62009-05-25 18:17:55 -0400783 // read the trace mask from persistent property persist.adb.trace_mask
784 // give up if the property is not set or cannot be parsed
785 property_get("persist.adb.trace_mask", value, "");
786 if (sscanf(value, "%x", &adb_trace_mask) != 1)
787 return;
788
789 adb_mkdir("/data/adb", 0775);
790 tzset();
791 time(&t);
792 localtime_r(&t, &now);
793 strftime(path, sizeof(path),
794 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
795 &now);
796 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800797 if (fd < 0)
798 return;
799
800 // redirect stdout and stderr to the log file
801 dup2(fd, 1);
802 dup2(fd, 2);
803 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800804 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800805
806 fd = unix_open("/dev/null", O_RDONLY);
807 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800808 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800809}
810#endif
811
812#if ADB_HOST
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100813int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814{
815#ifdef HAVE_WIN32_PROC
816 /* we need to start the server in the background */
817 /* we create a PIPE that will be used to wait for the server's "OK" */
818 /* message since the pipe handles must be inheritable, we use a */
819 /* security attribute */
820 HANDLE pipe_read, pipe_write;
821 SECURITY_ATTRIBUTES sa;
822 STARTUPINFO startup;
823 PROCESS_INFORMATION pinfo;
824 char program_path[ MAX_PATH ];
825 int ret;
826
827 sa.nLength = sizeof(sa);
828 sa.lpSecurityDescriptor = NULL;
829 sa.bInheritHandle = TRUE;
830
831 /* create pipe, and ensure its read handle isn't inheritable */
832 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
833 if (!ret) {
834 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
835 return -1;
836 }
837
838 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
839
840 ZeroMemory( &startup, sizeof(startup) );
841 startup.cb = sizeof(startup);
842 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
843 startup.hStdOutput = pipe_write;
844 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
845 startup.dwFlags = STARTF_USESTDHANDLES;
846
847 ZeroMemory( &pinfo, sizeof(pinfo) );
848
849 /* get path of current program */
850 GetModuleFileName( NULL, program_path, sizeof(program_path) );
851
852 ret = CreateProcess(
853 program_path, /* program path */
854 "adb fork-server server",
855 /* the fork-server argument will set the
856 debug = 2 in the child */
857 NULL, /* process handle is not inheritable */
858 NULL, /* thread handle is not inheritable */
859 TRUE, /* yes, inherit some handles */
860 DETACHED_PROCESS, /* the new process doesn't have a console */
861 NULL, /* use parent's environment block */
862 NULL, /* use parent's starting directory */
863 &startup, /* startup info, i.e. std handles */
864 &pinfo );
865
866 CloseHandle( pipe_write );
867
868 if (!ret) {
869 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
870 CloseHandle( pipe_read );
871 return -1;
872 }
873
874 CloseHandle( pinfo.hProcess );
875 CloseHandle( pinfo.hThread );
876
877 /* wait for the "OK\n" message */
878 {
879 char temp[3];
880 DWORD count;
881
882 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
883 CloseHandle( pipe_read );
884 if ( !ret ) {
885 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
886 return -1;
887 }
888 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
889 fprintf(stderr, "ADB server didn't ACK\n" );
890 return -1;
891 }
892 }
893#elif defined(HAVE_FORKEXEC)
894 char path[PATH_MAX];
895 int fd[2];
896
897 // set up a pipe so the child can tell us when it is ready.
898 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
899 if (pipe(fd)) {
900 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
901 return -1;
902 }
Alexey Tarasov31664102009-10-22 02:55:00 +1100903 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904 pid_t pid = fork();
905 if(pid < 0) return -1;
906
907 if (pid == 0) {
908 // child side of the fork
909
910 // redirect stderr to the pipe
911 // we use stderr instead of stdout due to stdout's buffering behavior.
912 adb_close(fd[0]);
913 dup2(fd[1], STDERR_FILENO);
914 adb_close(fd[1]);
915
916 // child process
917 int result = execl(path, "adb", "fork-server", "server", NULL);
918 // this should not return
919 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
920 } else {
921 // parent side of the fork
922
923 char temp[3];
924
925 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
926 // wait for the "OK\n" message
927 adb_close(fd[1]);
928 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -0700929 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800930 adb_close(fd[0]);
931 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -0700932 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800933 return -1;
934 }
935 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
936 fprintf(stderr, "ADB server didn't ACK\n" );
937 return -1;
938 }
939
940 setsid();
941 }
942#else
943#error "cannot implement background server start on this platform"
944#endif
945 return 0;
946}
947#endif
948
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100949/* Constructs a local name of form tcp:port.
950 * target_str points to the target string, it's content will be overwritten.
951 * target_size is the capacity of the target string.
952 * server_port is the port number to use for the local name.
953 */
954void build_local_name(char* target_str, size_t target_size, int server_port)
955{
956 snprintf(target_str, target_size, "tcp:%d", server_port);
957}
958
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800959#if !ADB_HOST
960static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -0800961#ifndef ALLOW_ADBD_ROOT
962 return 1;
963#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800964 int secure = 0;
965 char value[PROPERTY_VALUE_MAX];
966
967 /* run adbd in secure mode if ro.secure is set and
968 ** we are not in the emulator
969 */
970 property_get("ro.kernel.qemu", value, "");
971 if (strcmp(value, "1") != 0) {
972 property_get("ro.secure", value, "1");
973 if (strcmp(value, "1") == 0) {
974 // don't run as root if ro.secure is set...
975 secure = 1;
976
977 // ... except we allow running as root in userdebug builds if the
978 // service.adb.root property has been set by the "adb root" command
979 property_get("ro.debuggable", value, "");
980 if (strcmp(value, "1") == 0) {
981 property_get("service.adb.root", value, "");
982 if (strcmp(value, "1") == 0) {
983 secure = 0;
984 }
985 }
986 }
987 }
988 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -0800989#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800990}
991#endif /* !ADB_HOST */
992
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100993int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800994{
995#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -0700996 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -0700998
999 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001000#endif
1001
1002 atexit(adb_cleanup);
1003#ifdef HAVE_WIN32_PROC
1004 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1005#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -07001006 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 signal(SIGPIPE, SIG_IGN);
1008#endif
1009
1010 init_transport_registration();
1011
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001012#if ADB_HOST
1013 HOST = 1;
Xavier Ducroheta09fbd12009-05-20 17:33:53 -07001014 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001015 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001016 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001017
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001018 char local_name[30];
1019 build_local_name(local_name, sizeof(local_name), server_port);
1020 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001021 exit(1);
1022 }
1023#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001025 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001027 if (should_drop_privileges()) {
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001028 struct __user_cap_header_struct header;
1029 struct __user_cap_data_struct cap;
1030
Nick Kralevich44db9902010-08-27 14:35:07 -07001031 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1032 exit(1);
1033 }
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001034
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001035 /* add extra groups:
1036 ** AID_ADB to access the USB driver
1037 ** AID_LOG to read system logs (adb logcat)
1038 ** AID_INPUT to diagnose input issues (getevent)
1039 ** AID_INET to diagnose network issues (netcfg, ping)
1040 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -07001041 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001042 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -04001043 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -05001044 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -08001045 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001046 */
The Android Open Source Project20155492009-03-11 12:12:01 -07001047 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001048 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1049 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -07001050 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1051 exit(1);
1052 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001053
1054 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -07001055 if (setgid(AID_SHELL) != 0) {
1056 exit(1);
1057 }
1058 if (setuid(AID_SHELL) != 0) {
1059 exit(1);
1060 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001061
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001062 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1063 header.version = _LINUX_CAPABILITY_VERSION;
1064 header.pid = 0;
1065 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1066 cap.inheritable = 0;
1067 capset(&header, &cap);
1068
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001069 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001070 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001071 char local_name[30];
1072 build_local_name(local_name, sizeof(local_name), server_port);
1073 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001074 exit(1);
1075 }
1076 }
1077
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001078 int usb = 0;
1079 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001080 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001081 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001082 usb = 1;
1083 }
1084
1085 // If one of these properties is set, also listen on that port
1086 // If one of the properties isn't set and we couldn't listen on usb,
1087 // listen on the default port.
1088 property_get("service.adb.tcp.port", value, "");
1089 if (!value[0]) {
1090 property_get("persist.adb.tcp.port", value, "");
1091 }
1092 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1093 printf("using port=%d\n", port);
1094 // listen on TCP port specified by service.adb.tcp.port property
1095 local_init(port);
1096 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001097 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001098 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001099 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001100
JP Abgrall408fa572011-03-16 15:57:42 -07001101 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001102 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001103 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001104#endif
1105
1106 if (is_daemon)
1107 {
1108 // inform our parent that we are up and running.
1109#ifdef HAVE_WIN32_PROC
1110 DWORD count;
1111 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1112#elif defined(HAVE_FORKEXEC)
1113 fprintf(stderr, "OK\n");
1114#endif
1115 start_logging();
1116 }
JP Abgrall408fa572011-03-16 15:57:42 -07001117 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001118
1119 fdevent_loop();
1120
1121 usb_cleanup();
1122
1123 return 0;
1124}
1125
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001126#if ADB_HOST
1127void connect_device(char* host, char* buffer, int buffer_size)
1128{
1129 int port, fd;
1130 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001131 char hostbuf[100];
1132 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001133
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001134 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1135 if (portstr) {
Scott Andersonc7993af2012-05-25 13:55:46 -07001136 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001137 snprintf(buffer, buffer_size, "bad host name %s", host);
1138 return;
1139 }
1140 // zero terminate the host at the point we found the colon
1141 hostbuf[portstr - host] = 0;
1142 if (sscanf(portstr + 1, "%d", &port) == 0) {
1143 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1144 return;
1145 }
1146 } else {
1147 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001148 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001149
1150 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1151 if (find_transport(serial)) {
1152 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001153 return;
1154 }
1155
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001156 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001157 if (fd < 0) {
1158 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1159 return;
1160 }
1161
1162 D("client: connected on remote on fd %d\n", fd);
1163 close_on_exec(fd);
1164 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001165 register_socket_transport(fd, serial, port, 0);
1166 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001167}
1168
1169void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1170{
1171 char* port_separator = strchr(port_spec, ',');
1172 if (!port_separator) {
1173 snprintf(buffer, buffer_size,
1174 "unable to parse '%s' as <console port>,<adb port>",
1175 port_spec);
1176 return;
1177 }
1178
1179 // Zero-terminate console port and make port_separator point to 2nd port.
1180 *port_separator++ = 0;
1181 int console_port = strtol(port_spec, NULL, 0);
1182 int adb_port = strtol(port_separator, NULL, 0);
1183 if (!(console_port > 0 && adb_port > 0)) {
1184 *(port_separator - 1) = ',';
1185 snprintf(buffer, buffer_size,
1186 "Invalid port numbers: Expected positive numbers, got '%s'",
1187 port_spec);
1188 return;
1189 }
1190
1191 /* Check if the emulator is already known.
1192 * Note: There's a small but harmless race condition here: An emulator not
1193 * present just yet could be registered by another invocation right
1194 * after doing this check here. However, local_connect protects
1195 * against double-registration too. From here, a better error message
1196 * can be produced. In the case of the race condition, the very specific
1197 * error message won't be shown, but the data doesn't get corrupted. */
1198 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1199 if (known_emulator != NULL) {
1200 snprintf(buffer, buffer_size,
1201 "Emulator on port %d already registered.", adb_port);
1202 return;
1203 }
1204
1205 /* Check if more emulators can be registered. Similar unproblematic
1206 * race condition as above. */
1207 int candidate_slot = get_available_local_transport_index();
1208 if (candidate_slot < 0) {
1209 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1210 return;
1211 }
1212
1213 /* Preconditions met, try to connect to the emulator. */
1214 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1215 snprintf(buffer, buffer_size,
1216 "Connected to emulator on ports %d,%d", console_port, adb_port);
1217 } else {
1218 snprintf(buffer, buffer_size,
1219 "Could not connect to emulator on ports %d,%d",
1220 console_port, adb_port);
1221 }
1222}
1223#endif
1224
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001225int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1226{
1227 atransport *transport = NULL;
1228 char buf[4096];
1229
1230 if(!strcmp(service, "kill")) {
1231 fprintf(stderr,"adb server killed by remote request\n");
1232 fflush(stdout);
1233 adb_write(reply_fd, "OKAY", 4);
1234 usb_cleanup();
1235 exit(0);
1236 }
1237
1238#if ADB_HOST
1239 // "transport:" is used for switching transport with a specified serial number
1240 // "transport-usb:" is used for switching transport to the only USB transport
1241 // "transport-local:" is used for switching transport to the only local transport
1242 // "transport-any:" is used for switching transport to the only transport
1243 if (!strncmp(service, "transport", strlen("transport"))) {
1244 char* error_string = "unknown failure";
1245 transport_type type = kTransportAny;
1246
1247 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1248 type = kTransportUsb;
1249 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1250 type = kTransportLocal;
1251 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1252 type = kTransportAny;
1253 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1254 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001255 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001256 }
1257
1258 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1259
1260 if (transport) {
1261 s->transport = transport;
1262 adb_write(reply_fd, "OKAY", 4);
1263 } else {
1264 sendfailmsg(reply_fd, error_string);
1265 }
1266 return 1;
1267 }
1268
1269 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001270 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001271 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001272 int use_long = !strcmp(service+7, "-l");
1273 if (use_long || service[7] == 0) {
1274 memset(buf, 0, sizeof(buf));
1275 memset(buffer, 0, sizeof(buffer));
1276 D("Getting device list \n");
1277 list_transports(buffer, sizeof(buffer), use_long);
1278 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1279 D("Wrote device list \n");
1280 writex(reply_fd, buf, strlen(buf));
1281 return 0;
1282 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001283 }
1284
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001285 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001286 if (!strncmp(service, "connect:", 8)) {
1287 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001288 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001289 if (!strncmp(host, "emu:", 4)) {
1290 connect_emulator(host + 4, buffer, sizeof(buffer));
1291 } else {
1292 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001293 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001294 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001295 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1296 writex(reply_fd, buf, strlen(buf));
1297 return 0;
1298 }
1299
1300 // remove TCP transport
1301 if (!strncmp(service, "disconnect:", 11)) {
1302 char buffer[4096];
1303 memset(buffer, 0, sizeof(buffer));
1304 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001305 if (serial[0] == 0) {
1306 // disconnect from all TCP devices
1307 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001308 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001309 char hostbuf[100];
1310 // assume port 5555 if no port is specified
1311 if (!strchr(serial, ':')) {
1312 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1313 serial = hostbuf;
1314 }
1315 atransport *t = find_transport(serial);
1316
1317 if (t) {
1318 unregister_transport(t);
1319 } else {
1320 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1321 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001322 }
1323
1324 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001325 writex(reply_fd, buf, strlen(buf));
1326 return 0;
1327 }
1328
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001329 // returns our value for ADB_SERVER_VERSION
1330 if (!strcmp(service, "version")) {
1331 char version[12];
1332 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1333 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1334 writex(reply_fd, buf, strlen(buf));
1335 return 0;
1336 }
1337
1338 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1339 char *out = "unknown";
1340 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1341 if (transport && transport->serial) {
1342 out = transport->serial;
1343 }
1344 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1345 writex(reply_fd, buf, strlen(buf));
1346 return 0;
1347 }
Scott Andersone109d262012-04-20 11:21:14 -07001348 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1349 char *out = "unknown";
1350 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1351 if (transport && transport->devpath) {
1352 out = transport->devpath;
1353 }
1354 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1355 writex(reply_fd, buf, strlen(buf));
1356 return 0;
1357 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001358 // indicates a new emulator instance has started
1359 if (!strncmp(service,"emulator:",9)) {
1360 int port = atoi(service+9);
1361 local_connect(port);
1362 /* we don't even need to send a reply */
1363 return 0;
1364 }
1365#endif // ADB_HOST
1366
1367 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1368 char *local, *remote, *err;
1369 int r;
1370 atransport *transport;
1371
1372 int createForward = strncmp(service,"kill",4);
1373
1374 local = service + (createForward ? 8 : 12);
1375 remote = strchr(local,';');
1376 if(remote == 0) {
1377 sendfailmsg(reply_fd, "malformed forward spec");
1378 return 0;
1379 }
1380
1381 *remote++ = 0;
1382 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1383 sendfailmsg(reply_fd, "malformed forward spec");
1384 return 0;
1385 }
1386
1387 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1388 if (!transport) {
1389 sendfailmsg(reply_fd, err);
1390 return 0;
1391 }
1392
1393 if (createForward) {
1394 r = install_listener(local, remote, transport);
1395 } else {
1396 r = remove_listener(local, remote, transport);
1397 }
1398 if(r == 0) {
1399 /* 1st OKAY is connect, 2nd OKAY is status */
1400 writex(reply_fd, "OKAYOKAY", 8);
1401 return 0;
1402 }
1403
1404 if (createForward) {
1405 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1406 } else {
1407 sendfailmsg(reply_fd, "cannot remove listener");
1408 }
1409 return 0;
1410 }
1411
1412 if(!strncmp(service,"get-state",strlen("get-state"))) {
1413 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1414 char *state = connection_state_name(transport);
1415 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1416 writex(reply_fd, buf, strlen(buf));
1417 return 0;
1418 }
1419 return -1;
1420}
1421
1422#if !ADB_HOST
1423int recovery_mode = 0;
1424#endif
1425
1426int main(int argc, char **argv)
1427{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001428#if ADB_HOST
1429 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001430 adb_trace_init();
1431 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001432 return adb_commandline(argc - 1, argv + 1);
1433#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001434 /* If adbd runs inside the emulator this will enable adb tracing via
1435 * adb-debug qemud service in the emulator. */
1436 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001437 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1438 adb_device_banner = "recovery";
1439 recovery_mode = 1;
1440 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001441
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001442 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001443 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001444 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001445#endif
1446}