blob: 9871939c349ce7b5066b75dc633813d87ba16617 [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"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070031#include "adb_auth.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032
Scott Andersone82c2db2012-05-25 14:10:02 -070033#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
34
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080035#if !ADB_HOST
36#include <private/android_filesystem_config.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040037#include <linux/capability.h>
38#include <linux/prctl.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070039#include <sys/mount.h>
Xavier Ducroheta09fbd12009-05-20 17:33:53 -070040#else
41#include "usb_vendors.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#endif
43
JP Abgrall408fa572011-03-16 15:57:42 -070044#if ADB_TRACE
45ADB_MUTEX_DEFINE( D_lock );
46#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047
48int HOST = 0;
49
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070050static int auth_enabled = 0;
51
Scott Andersone82c2db2012-05-25 14:10:02 -070052#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080053static const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070054#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080055
56void fatal(const char *fmt, ...)
57{
58 va_list ap;
59 va_start(ap, fmt);
60 fprintf(stderr, "error: ");
61 vfprintf(stderr, fmt, ap);
62 fprintf(stderr, "\n");
63 va_end(ap);
64 exit(-1);
65}
66
67void fatal_errno(const char *fmt, ...)
68{
69 va_list ap;
70 va_start(ap, fmt);
71 fprintf(stderr, "error: %s: ", strerror(errno));
72 vfprintf(stderr, fmt, ap);
73 fprintf(stderr, "\n");
74 va_end(ap);
75 exit(-1);
76}
77
78int adb_trace_mask;
79
80/* read a comma/space/colum/semi-column separated list of tags
81 * from the ADB_TRACE environment variable and build the trace
82 * mask from it. note that '1' and 'all' are special cases to
83 * enable all tracing
84 */
85void adb_trace_init(void)
86{
87 const char* p = getenv("ADB_TRACE");
88 const char* q;
89
90 static const struct {
91 const char* tag;
92 int flag;
93 } tags[] = {
94 { "1", 0 },
95 { "all", 0 },
96 { "adb", TRACE_ADB },
97 { "sockets", TRACE_SOCKETS },
98 { "packets", TRACE_PACKETS },
99 { "rwx", TRACE_RWX },
100 { "usb", TRACE_USB },
101 { "sync", TRACE_SYNC },
102 { "sysdeps", TRACE_SYSDEPS },
103 { "transport", TRACE_TRANSPORT },
104 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700105 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700106 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800107 { NULL, 0 }
108 };
109
110 if (p == NULL)
111 return;
112
113 /* use a comma/column/semi-colum/space separated list */
114 while (*p) {
115 int len, tagn;
116
117 q = strpbrk(p, " ,:;");
118 if (q == NULL) {
119 q = p + strlen(p);
120 }
121 len = q - p;
122
123 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
124 {
125 int taglen = strlen(tags[tagn].tag);
126
127 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
128 {
129 int flag = tags[tagn].flag;
130 if (flag == 0) {
131 adb_trace_mask = ~0;
132 return;
133 }
134 adb_trace_mask |= (1 << flag);
135 break;
136 }
137 }
138 p = q;
139 if (*p)
140 p++;
141 }
142}
143
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800144#if !ADB_HOST
145/*
146 * Implements ADB tracing inside the emulator.
147 */
148
149#include <stdarg.h>
150
151/*
152 * Redefine open and write for qemu_pipe.h that contains inlined references
153 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
154 */
155
156#undef open
157#undef write
158#define open adb_open
159#define write adb_write
160#include <hardware/qemu_pipe.h>
161#undef open
162#undef write
163#define open ___xxx_open
164#define write ___xxx_write
165
166/* A handle to adb-debug qemud service in the emulator. */
167int adb_debug_qemu = -1;
168
169/* Initializes connection with the adb-debug qemud service in the emulator. */
170static int adb_qemu_trace_init(void)
171{
172 char con_name[32];
173
174 if (adb_debug_qemu >= 0) {
175 return 0;
176 }
177
178 /* adb debugging QEMUD service connection request. */
179 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
180 adb_debug_qemu = qemu_pipe_open(con_name);
181 return (adb_debug_qemu >= 0) ? 0 : -1;
182}
183
184void adb_qemu_trace(const char* fmt, ...)
185{
186 va_list args;
187 va_start(args, fmt);
188 char msg[1024];
189
190 if (adb_debug_qemu >= 0) {
191 vsnprintf(msg, sizeof(msg), fmt, args);
192 adb_write(adb_debug_qemu, msg, strlen(msg));
193 }
194}
195#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196
197apacket *get_apacket(void)
198{
199 apacket *p = malloc(sizeof(apacket));
200 if(p == 0) fatal("failed to allocate an apacket");
201 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
202 return p;
203}
204
205void put_apacket(apacket *p)
206{
207 free(p);
208}
209
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700210void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800211{
212 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700213 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214}
215
216void handle_offline(atransport *t)
217{
218 D("adb: offline\n");
219 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700220 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800221 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222}
223
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700224#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800225#define DUMPMAX 32
226void print_packet(const char *label, apacket *p)
227{
228 char *tag;
229 char *x;
230 unsigned count;
231
232 switch(p->msg.command){
233 case A_SYNC: tag = "SYNC"; break;
234 case A_CNXN: tag = "CNXN" ; break;
235 case A_OPEN: tag = "OPEN"; break;
236 case A_OKAY: tag = "OKAY"; break;
237 case A_CLSE: tag = "CLSE"; break;
238 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700239 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240 default: tag = "????"; break;
241 }
242
243 fprintf(stderr, "%s: %s %08x %08x %04x \"",
244 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
245 count = p->msg.data_length;
246 x = (char*) p->data;
247 if(count > DUMPMAX) {
248 count = DUMPMAX;
249 tag = "\n";
250 } else {
251 tag = "\"\n";
252 }
253 while(count-- > 0){
254 if((*x >= ' ') && (*x < 127)) {
255 fputc(*x, stderr);
256 } else {
257 fputc('.', stderr);
258 }
259 x++;
260 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700261 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262}
263#endif
264
265static void send_ready(unsigned local, unsigned remote, atransport *t)
266{
267 D("Calling send_ready \n");
268 apacket *p = get_apacket();
269 p->msg.command = A_OKAY;
270 p->msg.arg0 = local;
271 p->msg.arg1 = remote;
272 send_packet(p, t);
273}
274
275static void send_close(unsigned local, unsigned remote, atransport *t)
276{
277 D("Calling send_close \n");
278 apacket *p = get_apacket();
279 p->msg.command = A_CLSE;
280 p->msg.arg0 = local;
281 p->msg.arg1 = remote;
282 send_packet(p, t);
283}
284
Scott Andersone82c2db2012-05-25 14:10:02 -0700285static size_t fill_connect_data(char *buf, size_t bufsize)
286{
287#if ADB_HOST
288 return snprintf(buf, bufsize, "host::") + 1;
289#else
290 static const char *cnxn_props[] = {
291 "ro.product.name",
292 "ro.product.model",
293 "ro.product.device",
294 };
295 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
296 int i;
297 size_t remaining = bufsize;
298 size_t len;
299
300 len = snprintf(buf, remaining, "%s::", adb_device_banner);
301 remaining -= len;
302 buf += len;
303 for (i = 0; i < num_cnxn_props; i++) {
304 char value[PROPERTY_VALUE_MAX];
305 property_get(cnxn_props[i], value, "");
306 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
307 remaining -= len;
308 buf += len;
309 }
310
311 return bufsize - remaining + 1;
312#endif
313}
314
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800315static void send_connect(atransport *t)
316{
317 D("Calling send_connect \n");
318 apacket *cp = get_apacket();
319 cp->msg.command = A_CNXN;
320 cp->msg.arg0 = A_VERSION;
321 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700322 cp->msg.data_length = fill_connect_data((char *)cp->data,
323 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800324 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700325}
326
327static void send_auth_request(atransport *t)
328{
329 D("Calling send_auth_request\n");
330 apacket *p;
331 int ret;
332
333 ret = adb_auth_generate_token(t->token, sizeof(t->token));
334 if (ret != sizeof(t->token)) {
335 D("Error generating token ret=%d\n", ret);
336 return;
337 }
338
339 p = get_apacket();
340 memcpy(p->data, t->token, ret);
341 p->msg.command = A_AUTH;
342 p->msg.arg0 = ADB_AUTH_TOKEN;
343 p->msg.data_length = ret;
344 send_packet(p, t);
345}
346
347static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
348{
349 D("Calling send_auth_response\n");
350 apacket *p = get_apacket();
351 int ret;
352
353 ret = adb_auth_sign(t->key, token, token_size, p->data);
354 if (!ret) {
355 D("Error signing the token\n");
356 put_apacket(p);
357 return;
358 }
359
360 p->msg.command = A_AUTH;
361 p->msg.arg0 = ADB_AUTH_SIGNATURE;
362 p->msg.data_length = ret;
363 send_packet(p, t);
364}
365
366static void send_auth_publickey(atransport *t)
367{
368 D("Calling send_auth_publickey\n");
369 apacket *p = get_apacket();
370 int ret;
371
372 ret = adb_auth_get_userkey(p->data, sizeof(p->data));
373 if (!ret) {
374 D("Failed to get user public key\n");
375 put_apacket(p);
376 return;
377 }
378
379 p->msg.command = A_AUTH;
380 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
381 p->msg.data_length = ret;
382 send_packet(p, t);
383}
384
385void adb_auth_verified(atransport *t)
386{
387 handle_online(t);
388 send_connect(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800389}
390
391static char *connection_state_name(atransport *t)
392{
393 if (t == NULL) {
394 return "unknown";
395 }
396
397 switch(t->connection_state) {
398 case CS_BOOTLOADER:
399 return "bootloader";
400 case CS_DEVICE:
401 return "device";
402 case CS_OFFLINE:
403 return "offline";
404 default:
405 return "unknown";
406 }
407}
408
Scott Andersone82c2db2012-05-25 14:10:02 -0700409/* qual_overwrite is used to overwrite a qualifier string. dst is a
410 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700411 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700412 */
413static void qual_overwrite(char **dst, const char *src)
414{
415 if (!dst)
416 return;
417
418 free(*dst);
419 *dst = NULL;
420
421 if (!src || !*src)
422 return;
423
424 *dst = strdup(src);
425}
426
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427void parse_banner(char *banner, atransport *t)
428{
Scott Andersone82c2db2012-05-25 14:10:02 -0700429 static const char *prop_seps = ";";
430 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700431 char *cp;
432 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800433
434 D("parse_banner: %s\n", banner);
435 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700436 cp = strchr(type, ':');
437 if (cp) {
438 *cp++ = 0;
439 /* Nothing is done with second field. */
440 cp = strchr(cp, ':');
441 if (cp) {
442 char *save;
443 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700444 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700445 while (key) {
446 cp = strchr(key, key_val_sep);
447 if (cp) {
448 *cp++ = '\0';
449 if (!strcmp(key, "ro.product.name"))
450 qual_overwrite(&t->product, cp);
451 else if (!strcmp(key, "ro.product.model"))
452 qual_overwrite(&t->model, cp);
453 else if (!strcmp(key, "ro.product.device"))
454 qual_overwrite(&t->device, cp);
455 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700456 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700457 }
458 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800459 }
460
461 if(!strcmp(type, "bootloader")){
462 D("setting connection_state to CS_BOOTLOADER\n");
463 t->connection_state = CS_BOOTLOADER;
464 update_transports();
465 return;
466 }
467
468 if(!strcmp(type, "device")) {
469 D("setting connection_state to CS_DEVICE\n");
470 t->connection_state = CS_DEVICE;
471 update_transports();
472 return;
473 }
474
475 if(!strcmp(type, "recovery")) {
476 D("setting connection_state to CS_RECOVERY\n");
477 t->connection_state = CS_RECOVERY;
478 update_transports();
479 return;
480 }
481
Doug Zongker447f0612012-01-09 14:54:53 -0800482 if(!strcmp(type, "sideload")) {
483 D("setting connection_state to CS_SIDELOAD\n");
484 t->connection_state = CS_SIDELOAD;
485 update_transports();
486 return;
487 }
488
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489 t->connection_state = CS_HOST;
490}
491
492void handle_packet(apacket *p, atransport *t)
493{
494 asocket *s;
495
Viral Mehta899913f2010-06-16 18:41:28 +0530496 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
497 ((char*) (&(p->msg.command)))[1],
498 ((char*) (&(p->msg.command)))[2],
499 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500 print_packet("recv", p);
501
502 switch(p->msg.command){
503 case A_SYNC:
504 if(p->msg.arg0){
505 send_packet(p, t);
506 if(HOST) send_connect(t);
507 } else {
508 t->connection_state = CS_OFFLINE;
509 handle_offline(t);
510 send_packet(p, t);
511 }
512 return;
513
514 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
515 /* XXX verify version, etc */
516 if(t->connection_state != CS_OFFLINE) {
517 t->connection_state = CS_OFFLINE;
518 handle_offline(t);
519 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700520
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800521 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700522
523 if (HOST || !auth_enabled) {
524 handle_online(t);
525 if(!HOST) send_connect(t);
526 } else {
527 send_auth_request(t);
528 }
529 break;
530
531 case A_AUTH:
532 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
533 t->key = adb_auth_nextkey(t->key);
534 if (t->key) {
535 send_auth_response(p->data, p->msg.data_length, t);
536 } else {
537 /* No more private keys to try, send the public key */
538 send_auth_publickey(t);
539 }
540 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
541 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
542 adb_auth_verified(t);
543 t->failed_auth_attempts = 0;
544 } else {
545 if (t->failed_auth_attempts++ > 10)
546 adb_sleep_ms(1000);
547 send_auth_request(t);
548 }
549 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
550 adb_auth_confirm_key(p->data, p->msg.data_length, t);
551 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800552 break;
553
554 case A_OPEN: /* OPEN(local-id, 0, "destination") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700555 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556 char *name = (char*) p->data;
557 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
558 s = create_local_service_socket(name);
559 if(s == 0) {
560 send_close(0, p->msg.arg0, t);
561 } else {
562 s->peer = create_remote_socket(p->msg.arg0, t);
563 s->peer->peer = s;
564 send_ready(s->id, s->peer->id, t);
565 s->ready(s);
566 }
567 }
568 break;
569
570 case A_OKAY: /* READY(local-id, remote-id, "") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700571 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800572 if((s = find_local_socket(p->msg.arg1))) {
573 if(s->peer == 0) {
574 s->peer = create_remote_socket(p->msg.arg0, t);
575 s->peer->peer = s;
576 }
577 s->ready(s);
578 }
579 }
580 break;
581
582 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700583 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800584 if((s = find_local_socket(p->msg.arg1))) {
585 s->close(s);
586 }
587 }
588 break;
589
590 case A_WRTE:
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700591 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800592 if((s = find_local_socket(p->msg.arg1))) {
593 unsigned rid = p->msg.arg0;
594 p->len = p->msg.data_length;
595
596 if(s->enqueue(s, p) == 0) {
597 D("Enqueue the socket\n");
598 send_ready(s->id, rid, t);
599 }
600 return;
601 }
602 }
603 break;
604
605 default:
606 printf("handle_packet: what is %08x?!\n", p->msg.command);
607 }
608
609 put_apacket(p);
610}
611
612alistener listener_list = {
613 .next = &listener_list,
614 .prev = &listener_list,
615};
616
617static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
618{
619 asocket *s;
620
621 if(ev & FDE_READ) {
622 struct sockaddr addr;
623 socklen_t alen;
624 int fd;
625
626 alen = sizeof(addr);
627 fd = adb_socket_accept(_fd, &addr, &alen);
628 if(fd < 0) return;
629
630 adb_socket_setbufsize(fd, CHUNK_SIZE);
631
632 s = create_local_socket(fd);
633 if(s) {
634 connect_to_smartsocket(s);
635 return;
636 }
637
638 adb_close(fd);
639 }
640}
641
642static void listener_event_func(int _fd, unsigned ev, void *_l)
643{
644 alistener *l = _l;
645 asocket *s;
646
647 if(ev & FDE_READ) {
648 struct sockaddr addr;
649 socklen_t alen;
650 int fd;
651
652 alen = sizeof(addr);
653 fd = adb_socket_accept(_fd, &addr, &alen);
654 if(fd < 0) return;
655
656 s = create_local_socket(fd);
657 if(s) {
658 s->transport = l->transport;
659 connect_to_remote(s, l->connect_to);
660 return;
661 }
662
663 adb_close(fd);
664 }
665}
666
667static void free_listener(alistener* l)
668{
669 if (l->next) {
670 l->next->prev = l->prev;
671 l->prev->next = l->next;
672 l->next = l->prev = l;
673 }
674
675 // closes the corresponding fd
676 fdevent_remove(&l->fde);
677
678 if (l->local_name)
679 free((char*)l->local_name);
680
681 if (l->connect_to)
682 free((char*)l->connect_to);
683
684 if (l->transport) {
685 remove_transport_disconnect(l->transport, &l->disconnect);
686 }
687 free(l);
688}
689
690static void listener_disconnect(void* _l, atransport* t)
691{
692 alistener* l = _l;
693
694 free_listener(l);
695}
696
697int local_name_to_fd(const char *name)
698{
699 int port;
700
701 if(!strncmp("tcp:", name, 4)){
702 int ret;
703 port = atoi(name + 4);
704 ret = socket_loopback_server(port, SOCK_STREAM);
705 return ret;
706 }
707#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
708 // It's non-sensical to support the "reserved" space on the adb host side
709 if(!strncmp(name, "local:", 6)) {
710 return socket_local_server(name + 6,
711 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
712 } else if(!strncmp(name, "localabstract:", 14)) {
713 return socket_local_server(name + 14,
714 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
715 } else if(!strncmp(name, "localfilesystem:", 16)) {
716 return socket_local_server(name + 16,
717 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
718 }
719
720#endif
721 printf("unknown local portname '%s'\n", name);
722 return -1;
723}
724
725static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
726{
727 alistener *l;
728
729 for (l = listener_list.next; l != &listener_list; l = l->next) {
730 if (!strcmp(local_name, l->local_name) &&
731 !strcmp(connect_to, l->connect_to) &&
732 l->transport && l->transport == transport) {
733
734 listener_disconnect(l, transport);
735 return 0;
736 }
737 }
738
739 return -1;
740}
741
742static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
743{
744 alistener *l;
745
746 //printf("install_listener('%s','%s')\n", local_name, connect_to);
747
748 for(l = listener_list.next; l != &listener_list; l = l->next){
749 if(strcmp(local_name, l->local_name) == 0) {
750 char *cto;
751
752 /* can't repurpose a smartsocket */
753 if(l->connect_to[0] == '*') {
754 return -1;
755 }
756
757 cto = strdup(connect_to);
758 if(cto == 0) {
759 return -1;
760 }
761
762 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
763 free((void*) l->connect_to);
764 l->connect_to = cto;
765 if (l->transport != transport) {
766 remove_transport_disconnect(l->transport, &l->disconnect);
767 l->transport = transport;
768 add_transport_disconnect(l->transport, &l->disconnect);
769 }
770 return 0;
771 }
772 }
773
774 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
775 if((l->local_name = strdup(local_name)) == 0) goto nomem;
776 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
777
778
779 l->fd = local_name_to_fd(local_name);
780 if(l->fd < 0) {
781 free((void*) l->local_name);
782 free((void*) l->connect_to);
783 free(l);
784 printf("cannot bind '%s'\n", local_name);
785 return -2;
786 }
787
788 close_on_exec(l->fd);
789 if(!strcmp(l->connect_to, "*smartsocket*")) {
790 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
791 } else {
792 fdevent_install(&l->fde, l->fd, listener_event_func, l);
793 }
794 fdevent_set(&l->fde, FDE_READ);
795
796 l->next = &listener_list;
797 l->prev = listener_list.prev;
798 l->next->prev = l;
799 l->prev->next = l;
800 l->transport = transport;
801
802 if (transport) {
803 l->disconnect.opaque = l;
804 l->disconnect.func = listener_disconnect;
805 add_transport_disconnect(transport, &l->disconnect);
806 }
807 return 0;
808
809nomem:
810 fatal("cannot allocate listener");
811 return 0;
812}
813
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814#ifdef HAVE_WIN32_PROC
815static BOOL WINAPI ctrlc_handler(DWORD type)
816{
817 exit(STATUS_CONTROL_C_EXIT);
818 return TRUE;
819}
820#endif
821
822static void adb_cleanup(void)
823{
824 usb_cleanup();
825}
826
827void start_logging(void)
828{
829#ifdef HAVE_WIN32_PROC
830 char temp[ MAX_PATH ];
831 FILE* fnul;
832 FILE* flog;
833
834 GetTempPath( sizeof(temp) - 8, temp );
835 strcat( temp, "adb.log" );
836
837 /* Win32 specific redirections */
838 fnul = fopen( "NUL", "rt" );
839 if (fnul != NULL)
840 stdin[0] = fnul[0];
841
842 flog = fopen( temp, "at" );
843 if (flog == NULL)
844 flog = fnul;
845
846 setvbuf( flog, NULL, _IONBF, 0 );
847
848 stdout[0] = flog[0];
849 stderr[0] = flog[0];
850 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
851#else
852 int fd;
853
854 fd = unix_open("/dev/null", O_RDONLY);
855 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700856 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857
858 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
859 if(fd < 0) {
860 fd = unix_open("/dev/null", O_WRONLY);
861 }
862 dup2(fd, 1);
863 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700864 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
866#endif
867}
868
869#if !ADB_HOST
870void start_device_log(void)
871{
872 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400873 char path[PATH_MAX];
874 struct tm now;
875 time_t t;
876 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877
Mike Lockwood1f546e62009-05-25 18:17:55 -0400878 // read the trace mask from persistent property persist.adb.trace_mask
879 // give up if the property is not set or cannot be parsed
880 property_get("persist.adb.trace_mask", value, "");
881 if (sscanf(value, "%x", &adb_trace_mask) != 1)
882 return;
883
884 adb_mkdir("/data/adb", 0775);
885 tzset();
886 time(&t);
887 localtime_r(&t, &now);
888 strftime(path, sizeof(path),
889 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
890 &now);
891 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800892 if (fd < 0)
893 return;
894
895 // redirect stdout and stderr to the log file
896 dup2(fd, 1);
897 dup2(fd, 2);
898 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800899 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900
901 fd = unix_open("/dev/null", O_RDONLY);
902 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800903 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904}
905#endif
906
907#if ADB_HOST
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100908int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800909{
910#ifdef HAVE_WIN32_PROC
911 /* we need to start the server in the background */
912 /* we create a PIPE that will be used to wait for the server's "OK" */
913 /* message since the pipe handles must be inheritable, we use a */
914 /* security attribute */
915 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000916 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800917 SECURITY_ATTRIBUTES sa;
918 STARTUPINFO startup;
919 PROCESS_INFORMATION pinfo;
920 char program_path[ MAX_PATH ];
921 int ret;
922
923 sa.nLength = sizeof(sa);
924 sa.lpSecurityDescriptor = NULL;
925 sa.bInheritHandle = TRUE;
926
927 /* create pipe, and ensure its read handle isn't inheritable */
928 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
929 if (!ret) {
930 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
931 return -1;
932 }
933
934 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
935
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000936 /* Some programs want to launch an adb command and collect its output by
937 * calling CreateProcess with inheritable stdout/stderr handles, then
938 * using read() to get its output. When this happens, the stdout/stderr
939 * handles passed to the adb client process will also be inheritable.
940 * When starting the adb server here, care must be taken to reset them
941 * to non-inheritable.
942 * Otherwise, something bad happens: even if the adb command completes,
943 * the calling process is stuck while read()-ing from the stdout/stderr
944 * descriptors, because they're connected to corresponding handles in the
945 * adb server process (even if the latter never uses/writes to them).
946 */
947 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
948 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
949 if (stdout_handle != INVALID_HANDLE_VALUE) {
950 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
951 }
952 if (stderr_handle != INVALID_HANDLE_VALUE) {
953 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
954 }
955
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800956 ZeroMemory( &startup, sizeof(startup) );
957 startup.cb = sizeof(startup);
958 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
959 startup.hStdOutput = pipe_write;
960 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
961 startup.dwFlags = STARTF_USESTDHANDLES;
962
963 ZeroMemory( &pinfo, sizeof(pinfo) );
964
965 /* get path of current program */
966 GetModuleFileName( NULL, program_path, sizeof(program_path) );
967
968 ret = CreateProcess(
969 program_path, /* program path */
970 "adb fork-server server",
971 /* the fork-server argument will set the
972 debug = 2 in the child */
973 NULL, /* process handle is not inheritable */
974 NULL, /* thread handle is not inheritable */
975 TRUE, /* yes, inherit some handles */
976 DETACHED_PROCESS, /* the new process doesn't have a console */
977 NULL, /* use parent's environment block */
978 NULL, /* use parent's starting directory */
979 &startup, /* startup info, i.e. std handles */
980 &pinfo );
981
982 CloseHandle( pipe_write );
983
984 if (!ret) {
985 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
986 CloseHandle( pipe_read );
987 return -1;
988 }
989
990 CloseHandle( pinfo.hProcess );
991 CloseHandle( pinfo.hThread );
992
993 /* wait for the "OK\n" message */
994 {
995 char temp[3];
996 DWORD count;
997
998 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
999 CloseHandle( pipe_read );
1000 if ( !ret ) {
1001 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1002 return -1;
1003 }
1004 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1005 fprintf(stderr, "ADB server didn't ACK\n" );
1006 return -1;
1007 }
1008 }
1009#elif defined(HAVE_FORKEXEC)
1010 char path[PATH_MAX];
1011 int fd[2];
1012
1013 // set up a pipe so the child can tell us when it is ready.
1014 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1015 if (pipe(fd)) {
1016 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1017 return -1;
1018 }
Alexey Tarasov31664102009-10-22 02:55:00 +11001019 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020 pid_t pid = fork();
1021 if(pid < 0) return -1;
1022
1023 if (pid == 0) {
1024 // child side of the fork
1025
1026 // redirect stderr to the pipe
1027 // we use stderr instead of stdout due to stdout's buffering behavior.
1028 adb_close(fd[0]);
1029 dup2(fd[1], STDERR_FILENO);
1030 adb_close(fd[1]);
1031
1032 // child process
1033 int result = execl(path, "adb", "fork-server", "server", NULL);
1034 // this should not return
1035 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1036 } else {
1037 // parent side of the fork
1038
1039 char temp[3];
1040
1041 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1042 // wait for the "OK\n" message
1043 adb_close(fd[1]);
1044 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -07001045 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001046 adb_close(fd[0]);
1047 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -07001048 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001049 return -1;
1050 }
1051 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1052 fprintf(stderr, "ADB server didn't ACK\n" );
1053 return -1;
1054 }
1055
1056 setsid();
1057 }
1058#else
1059#error "cannot implement background server start on this platform"
1060#endif
1061 return 0;
1062}
1063#endif
1064
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001065/* Constructs a local name of form tcp:port.
1066 * target_str points to the target string, it's content will be overwritten.
1067 * target_size is the capacity of the target string.
1068 * server_port is the port number to use for the local name.
1069 */
1070void build_local_name(char* target_str, size_t target_size, int server_port)
1071{
1072 snprintf(target_str, target_size, "tcp:%d", server_port);
1073}
1074
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001075#if !ADB_HOST
1076static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -08001077#ifndef ALLOW_ADBD_ROOT
1078 return 1;
1079#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001080 int secure = 0;
1081 char value[PROPERTY_VALUE_MAX];
1082
1083 /* run adbd in secure mode if ro.secure is set and
1084 ** we are not in the emulator
1085 */
1086 property_get("ro.kernel.qemu", value, "");
1087 if (strcmp(value, "1") != 0) {
1088 property_get("ro.secure", value, "1");
1089 if (strcmp(value, "1") == 0) {
1090 // don't run as root if ro.secure is set...
1091 secure = 1;
1092
1093 // ... except we allow running as root in userdebug builds if the
1094 // service.adb.root property has been set by the "adb root" command
1095 property_get("ro.debuggable", value, "");
1096 if (strcmp(value, "1") == 0) {
1097 property_get("service.adb.root", value, "");
1098 if (strcmp(value, "1") == 0) {
1099 secure = 0;
1100 }
1101 }
1102 }
1103 }
1104 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -08001105#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001106}
1107#endif /* !ADB_HOST */
1108
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001109int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001110{
1111#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -07001112 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001113 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -07001114
1115 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001116#endif
1117
1118 atexit(adb_cleanup);
1119#ifdef HAVE_WIN32_PROC
1120 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1121#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -07001122 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001123 signal(SIGPIPE, SIG_IGN);
1124#endif
1125
1126 init_transport_registration();
1127
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001128#if ADB_HOST
1129 HOST = 1;
Xavier Ducroheta09fbd12009-05-20 17:33:53 -07001130 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001131 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001132 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001133 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001134
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001135 char local_name[30];
1136 build_local_name(local_name, sizeof(local_name), server_port);
1137 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001138 exit(1);
1139 }
1140#else
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001141 property_get("ro.adb.secure", value, "0");
1142 auth_enabled = !strcmp(value, "1");
1143 if (auth_enabled)
1144 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001145
Jeff Sharkeyd6d42862012-09-06 13:05:40 -07001146 // Our external storage path may be different than apps, since
1147 // we aren't able to bind mount after dropping root.
1148 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1149 if (NULL != adb_external_storage) {
1150 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1151 } else {
1152 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1153 " unchanged.\n");
1154 }
1155
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001156 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001157 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001158 if (should_drop_privileges()) {
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001159 struct __user_cap_header_struct header;
1160 struct __user_cap_data_struct cap;
1161
Nick Kralevich44db9902010-08-27 14:35:07 -07001162 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1163 exit(1);
1164 }
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001165
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166 /* add extra groups:
1167 ** AID_ADB to access the USB driver
1168 ** AID_LOG to read system logs (adb logcat)
1169 ** AID_INPUT to diagnose input issues (getevent)
1170 ** AID_INET to diagnose network issues (netcfg, ping)
1171 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -07001172 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001173 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -04001174 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -05001175 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -08001176 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177 */
The Android Open Source Project20155492009-03-11 12:12:01 -07001178 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001179 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1180 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -07001181 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1182 exit(1);
1183 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001184
1185 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -07001186 if (setgid(AID_SHELL) != 0) {
1187 exit(1);
1188 }
1189 if (setuid(AID_SHELL) != 0) {
1190 exit(1);
1191 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001193 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1194 header.version = _LINUX_CAPABILITY_VERSION;
1195 header.pid = 0;
1196 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1197 cap.inheritable = 0;
1198 capset(&header, &cap);
1199
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001200 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001202 char local_name[30];
1203 build_local_name(local_name, sizeof(local_name), server_port);
1204 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001205 exit(1);
1206 }
1207 }
1208
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001209 int usb = 0;
1210 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001211 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001212 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001213 usb = 1;
1214 }
1215
1216 // If one of these properties is set, also listen on that port
1217 // If one of the properties isn't set and we couldn't listen on usb,
1218 // listen on the default port.
1219 property_get("service.adb.tcp.port", value, "");
1220 if (!value[0]) {
1221 property_get("persist.adb.tcp.port", value, "");
1222 }
1223 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1224 printf("using port=%d\n", port);
1225 // listen on TCP port specified by service.adb.tcp.port property
1226 local_init(port);
1227 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001228 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001229 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001230 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001231
JP Abgrall408fa572011-03-16 15:57:42 -07001232 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001233 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001234 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001235#endif
1236
1237 if (is_daemon)
1238 {
1239 // inform our parent that we are up and running.
1240#ifdef HAVE_WIN32_PROC
1241 DWORD count;
1242 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1243#elif defined(HAVE_FORKEXEC)
1244 fprintf(stderr, "OK\n");
1245#endif
1246 start_logging();
1247 }
JP Abgrall408fa572011-03-16 15:57:42 -07001248 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001249
1250 fdevent_loop();
1251
1252 usb_cleanup();
1253
1254 return 0;
1255}
1256
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001257#if ADB_HOST
1258void connect_device(char* host, char* buffer, int buffer_size)
1259{
1260 int port, fd;
1261 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001262 char hostbuf[100];
1263 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001264
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001265 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1266 if (portstr) {
Scott Andersonc7993af2012-05-25 13:55:46 -07001267 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001268 snprintf(buffer, buffer_size, "bad host name %s", host);
1269 return;
1270 }
1271 // zero terminate the host at the point we found the colon
1272 hostbuf[portstr - host] = 0;
1273 if (sscanf(portstr + 1, "%d", &port) == 0) {
1274 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1275 return;
1276 }
1277 } else {
1278 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001279 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001280
1281 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1282 if (find_transport(serial)) {
1283 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001284 return;
1285 }
1286
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001287 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001288 if (fd < 0) {
1289 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1290 return;
1291 }
1292
1293 D("client: connected on remote on fd %d\n", fd);
1294 close_on_exec(fd);
1295 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001296 register_socket_transport(fd, serial, port, 0);
1297 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001298}
1299
1300void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1301{
1302 char* port_separator = strchr(port_spec, ',');
1303 if (!port_separator) {
1304 snprintf(buffer, buffer_size,
1305 "unable to parse '%s' as <console port>,<adb port>",
1306 port_spec);
1307 return;
1308 }
1309
1310 // Zero-terminate console port and make port_separator point to 2nd port.
1311 *port_separator++ = 0;
1312 int console_port = strtol(port_spec, NULL, 0);
1313 int adb_port = strtol(port_separator, NULL, 0);
1314 if (!(console_port > 0 && adb_port > 0)) {
1315 *(port_separator - 1) = ',';
1316 snprintf(buffer, buffer_size,
1317 "Invalid port numbers: Expected positive numbers, got '%s'",
1318 port_spec);
1319 return;
1320 }
1321
1322 /* Check if the emulator is already known.
1323 * Note: There's a small but harmless race condition here: An emulator not
1324 * present just yet could be registered by another invocation right
1325 * after doing this check here. However, local_connect protects
1326 * against double-registration too. From here, a better error message
1327 * can be produced. In the case of the race condition, the very specific
1328 * error message won't be shown, but the data doesn't get corrupted. */
1329 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1330 if (known_emulator != NULL) {
1331 snprintf(buffer, buffer_size,
1332 "Emulator on port %d already registered.", adb_port);
1333 return;
1334 }
1335
1336 /* Check if more emulators can be registered. Similar unproblematic
1337 * race condition as above. */
1338 int candidate_slot = get_available_local_transport_index();
1339 if (candidate_slot < 0) {
1340 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1341 return;
1342 }
1343
1344 /* Preconditions met, try to connect to the emulator. */
1345 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1346 snprintf(buffer, buffer_size,
1347 "Connected to emulator on ports %d,%d", console_port, adb_port);
1348 } else {
1349 snprintf(buffer, buffer_size,
1350 "Could not connect to emulator on ports %d,%d",
1351 console_port, adb_port);
1352 }
1353}
1354#endif
1355
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001356int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1357{
1358 atransport *transport = NULL;
1359 char buf[4096];
1360
1361 if(!strcmp(service, "kill")) {
1362 fprintf(stderr,"adb server killed by remote request\n");
1363 fflush(stdout);
1364 adb_write(reply_fd, "OKAY", 4);
1365 usb_cleanup();
1366 exit(0);
1367 }
1368
1369#if ADB_HOST
1370 // "transport:" is used for switching transport with a specified serial number
1371 // "transport-usb:" is used for switching transport to the only USB transport
1372 // "transport-local:" is used for switching transport to the only local transport
1373 // "transport-any:" is used for switching transport to the only transport
1374 if (!strncmp(service, "transport", strlen("transport"))) {
1375 char* error_string = "unknown failure";
1376 transport_type type = kTransportAny;
1377
1378 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1379 type = kTransportUsb;
1380 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1381 type = kTransportLocal;
1382 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1383 type = kTransportAny;
1384 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1385 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001386 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001387 }
1388
1389 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1390
1391 if (transport) {
1392 s->transport = transport;
1393 adb_write(reply_fd, "OKAY", 4);
1394 } else {
1395 sendfailmsg(reply_fd, error_string);
1396 }
1397 return 1;
1398 }
1399
1400 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001401 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001402 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001403 int use_long = !strcmp(service+7, "-l");
1404 if (use_long || service[7] == 0) {
1405 memset(buf, 0, sizeof(buf));
1406 memset(buffer, 0, sizeof(buffer));
1407 D("Getting device list \n");
1408 list_transports(buffer, sizeof(buffer), use_long);
1409 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1410 D("Wrote device list \n");
1411 writex(reply_fd, buf, strlen(buf));
1412 return 0;
1413 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001414 }
1415
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001416 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001417 if (!strncmp(service, "connect:", 8)) {
1418 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001419 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001420 if (!strncmp(host, "emu:", 4)) {
1421 connect_emulator(host + 4, buffer, sizeof(buffer));
1422 } else {
1423 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001424 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001425 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001426 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1427 writex(reply_fd, buf, strlen(buf));
1428 return 0;
1429 }
1430
1431 // remove TCP transport
1432 if (!strncmp(service, "disconnect:", 11)) {
1433 char buffer[4096];
1434 memset(buffer, 0, sizeof(buffer));
1435 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001436 if (serial[0] == 0) {
1437 // disconnect from all TCP devices
1438 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001439 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001440 char hostbuf[100];
1441 // assume port 5555 if no port is specified
1442 if (!strchr(serial, ':')) {
1443 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1444 serial = hostbuf;
1445 }
1446 atransport *t = find_transport(serial);
1447
1448 if (t) {
1449 unregister_transport(t);
1450 } else {
1451 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1452 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001453 }
1454
1455 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001456 writex(reply_fd, buf, strlen(buf));
1457 return 0;
1458 }
1459
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001460 // returns our value for ADB_SERVER_VERSION
1461 if (!strcmp(service, "version")) {
1462 char version[12];
1463 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1464 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1465 writex(reply_fd, buf, strlen(buf));
1466 return 0;
1467 }
1468
1469 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1470 char *out = "unknown";
1471 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1472 if (transport && transport->serial) {
1473 out = transport->serial;
1474 }
1475 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1476 writex(reply_fd, buf, strlen(buf));
1477 return 0;
1478 }
Scott Andersone109d262012-04-20 11:21:14 -07001479 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1480 char *out = "unknown";
1481 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1482 if (transport && transport->devpath) {
1483 out = transport->devpath;
1484 }
1485 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1486 writex(reply_fd, buf, strlen(buf));
1487 return 0;
1488 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001489 // indicates a new emulator instance has started
1490 if (!strncmp(service,"emulator:",9)) {
1491 int port = atoi(service+9);
1492 local_connect(port);
1493 /* we don't even need to send a reply */
1494 return 0;
1495 }
1496#endif // ADB_HOST
1497
1498 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1499 char *local, *remote, *err;
1500 int r;
1501 atransport *transport;
1502
1503 int createForward = strncmp(service,"kill",4);
1504
1505 local = service + (createForward ? 8 : 12);
1506 remote = strchr(local,';');
1507 if(remote == 0) {
1508 sendfailmsg(reply_fd, "malformed forward spec");
1509 return 0;
1510 }
1511
1512 *remote++ = 0;
1513 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1514 sendfailmsg(reply_fd, "malformed forward spec");
1515 return 0;
1516 }
1517
1518 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1519 if (!transport) {
1520 sendfailmsg(reply_fd, err);
1521 return 0;
1522 }
1523
1524 if (createForward) {
1525 r = install_listener(local, remote, transport);
1526 } else {
1527 r = remove_listener(local, remote, transport);
1528 }
1529 if(r == 0) {
1530 /* 1st OKAY is connect, 2nd OKAY is status */
1531 writex(reply_fd, "OKAYOKAY", 8);
1532 return 0;
1533 }
1534
1535 if (createForward) {
1536 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1537 } else {
1538 sendfailmsg(reply_fd, "cannot remove listener");
1539 }
1540 return 0;
1541 }
1542
1543 if(!strncmp(service,"get-state",strlen("get-state"))) {
1544 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1545 char *state = connection_state_name(transport);
1546 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1547 writex(reply_fd, buf, strlen(buf));
1548 return 0;
1549 }
1550 return -1;
1551}
1552
1553#if !ADB_HOST
1554int recovery_mode = 0;
1555#endif
1556
1557int main(int argc, char **argv)
1558{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001559#if ADB_HOST
1560 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001561 adb_trace_init();
1562 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001563 return adb_commandline(argc - 1, argv + 1);
1564#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001565 /* If adbd runs inside the emulator this will enable adb tracing via
1566 * adb-debug qemud service in the emulator. */
1567 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001568 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1569 adb_device_banner = "recovery";
1570 recovery_mode = 1;
1571 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001572
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001573 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001574 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001575 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001576#endif
1577}