blob: 2f305434ab92a749b89e5894c43096678c380fc9 [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>
Ray Donnellycbb98912012-11-29 01:36:08 +000028#include <stdint.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029
30#include "sysdeps.h"
31#include "adb.h"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070032#include "adb_auth.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080033
Scott Andersone82c2db2012-05-25 14:10:02 -070034#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
35
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080036#if !ADB_HOST
37#include <private/android_filesystem_config.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040038#include <linux/capability.h>
39#include <linux/prctl.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070040#include <sys/mount.h>
Xavier Ducroheta09fbd12009-05-20 17:33:53 -070041#else
42#include "usb_vendors.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043#endif
44
JP Abgrall408fa572011-03-16 15:57:42 -070045#if ADB_TRACE
46ADB_MUTEX_DEFINE( D_lock );
47#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080048
49int HOST = 0;
50
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070051static int auth_enabled = 0;
52
Scott Andersone82c2db2012-05-25 14:10:02 -070053#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054static const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070055#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080056
57void fatal(const char *fmt, ...)
58{
59 va_list ap;
60 va_start(ap, fmt);
61 fprintf(stderr, "error: ");
62 vfprintf(stderr, fmt, ap);
63 fprintf(stderr, "\n");
64 va_end(ap);
65 exit(-1);
66}
67
68void fatal_errno(const char *fmt, ...)
69{
70 va_list ap;
71 va_start(ap, fmt);
72 fprintf(stderr, "error: %s: ", strerror(errno));
73 vfprintf(stderr, fmt, ap);
74 fprintf(stderr, "\n");
75 va_end(ap);
76 exit(-1);
77}
78
79int adb_trace_mask;
80
81/* read a comma/space/colum/semi-column separated list of tags
82 * from the ADB_TRACE environment variable and build the trace
83 * mask from it. note that '1' and 'all' are special cases to
84 * enable all tracing
85 */
86void adb_trace_init(void)
87{
88 const char* p = getenv("ADB_TRACE");
89 const char* q;
90
91 static const struct {
92 const char* tag;
93 int flag;
94 } tags[] = {
95 { "1", 0 },
96 { "all", 0 },
97 { "adb", TRACE_ADB },
98 { "sockets", TRACE_SOCKETS },
99 { "packets", TRACE_PACKETS },
100 { "rwx", TRACE_RWX },
101 { "usb", TRACE_USB },
102 { "sync", TRACE_SYNC },
103 { "sysdeps", TRACE_SYSDEPS },
104 { "transport", TRACE_TRANSPORT },
105 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700106 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700107 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800108 { NULL, 0 }
109 };
110
111 if (p == NULL)
112 return;
113
114 /* use a comma/column/semi-colum/space separated list */
115 while (*p) {
116 int len, tagn;
117
118 q = strpbrk(p, " ,:;");
119 if (q == NULL) {
120 q = p + strlen(p);
121 }
122 len = q - p;
123
124 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
125 {
126 int taglen = strlen(tags[tagn].tag);
127
128 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
129 {
130 int flag = tags[tagn].flag;
131 if (flag == 0) {
132 adb_trace_mask = ~0;
133 return;
134 }
135 adb_trace_mask |= (1 << flag);
136 break;
137 }
138 }
139 p = q;
140 if (*p)
141 p++;
142 }
143}
144
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800145#if !ADB_HOST
146/*
147 * Implements ADB tracing inside the emulator.
148 */
149
150#include <stdarg.h>
151
152/*
153 * Redefine open and write for qemu_pipe.h that contains inlined references
154 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
155 */
156
157#undef open
158#undef write
159#define open adb_open
160#define write adb_write
161#include <hardware/qemu_pipe.h>
162#undef open
163#undef write
164#define open ___xxx_open
165#define write ___xxx_write
166
167/* A handle to adb-debug qemud service in the emulator. */
168int adb_debug_qemu = -1;
169
170/* Initializes connection with the adb-debug qemud service in the emulator. */
171static int adb_qemu_trace_init(void)
172{
173 char con_name[32];
174
175 if (adb_debug_qemu >= 0) {
176 return 0;
177 }
178
179 /* adb debugging QEMUD service connection request. */
180 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
181 adb_debug_qemu = qemu_pipe_open(con_name);
182 return (adb_debug_qemu >= 0) ? 0 : -1;
183}
184
185void adb_qemu_trace(const char* fmt, ...)
186{
187 va_list args;
188 va_start(args, fmt);
189 char msg[1024];
190
191 if (adb_debug_qemu >= 0) {
192 vsnprintf(msg, sizeof(msg), fmt, args);
193 adb_write(adb_debug_qemu, msg, strlen(msg));
194 }
195}
196#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800197
198apacket *get_apacket(void)
199{
200 apacket *p = malloc(sizeof(apacket));
201 if(p == 0) fatal("failed to allocate an apacket");
202 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
203 return p;
204}
205
206void put_apacket(apacket *p)
207{
208 free(p);
209}
210
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700211void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800212{
213 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700214 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800215}
216
217void handle_offline(atransport *t)
218{
219 D("adb: offline\n");
220 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700221 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223}
224
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700225#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800226#define DUMPMAX 32
227void print_packet(const char *label, apacket *p)
228{
229 char *tag;
230 char *x;
231 unsigned count;
232
233 switch(p->msg.command){
234 case A_SYNC: tag = "SYNC"; break;
235 case A_CNXN: tag = "CNXN" ; break;
236 case A_OPEN: tag = "OPEN"; break;
237 case A_OKAY: tag = "OKAY"; break;
238 case A_CLSE: tag = "CLSE"; break;
239 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700240 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800241 default: tag = "????"; break;
242 }
243
244 fprintf(stderr, "%s: %s %08x %08x %04x \"",
245 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
246 count = p->msg.data_length;
247 x = (char*) p->data;
248 if(count > DUMPMAX) {
249 count = DUMPMAX;
250 tag = "\n";
251 } else {
252 tag = "\"\n";
253 }
254 while(count-- > 0){
255 if((*x >= ' ') && (*x < 127)) {
256 fputc(*x, stderr);
257 } else {
258 fputc('.', stderr);
259 }
260 x++;
261 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700262 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263}
264#endif
265
266static void send_ready(unsigned local, unsigned remote, atransport *t)
267{
268 D("Calling send_ready \n");
269 apacket *p = get_apacket();
270 p->msg.command = A_OKAY;
271 p->msg.arg0 = local;
272 p->msg.arg1 = remote;
273 send_packet(p, t);
274}
275
276static void send_close(unsigned local, unsigned remote, atransport *t)
277{
278 D("Calling send_close \n");
279 apacket *p = get_apacket();
280 p->msg.command = A_CLSE;
281 p->msg.arg0 = local;
282 p->msg.arg1 = remote;
283 send_packet(p, t);
284}
285
Scott Andersone82c2db2012-05-25 14:10:02 -0700286static size_t fill_connect_data(char *buf, size_t bufsize)
287{
288#if ADB_HOST
289 return snprintf(buf, bufsize, "host::") + 1;
290#else
291 static const char *cnxn_props[] = {
292 "ro.product.name",
293 "ro.product.model",
294 "ro.product.device",
295 };
296 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
297 int i;
298 size_t remaining = bufsize;
299 size_t len;
300
301 len = snprintf(buf, remaining, "%s::", adb_device_banner);
302 remaining -= len;
303 buf += len;
304 for (i = 0; i < num_cnxn_props; i++) {
305 char value[PROPERTY_VALUE_MAX];
306 property_get(cnxn_props[i], value, "");
307 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
308 remaining -= len;
309 buf += len;
310 }
311
312 return bufsize - remaining + 1;
313#endif
314}
315
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800316static void send_connect(atransport *t)
317{
318 D("Calling send_connect \n");
319 apacket *cp = get_apacket();
320 cp->msg.command = A_CNXN;
321 cp->msg.arg0 = A_VERSION;
322 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700323 cp->msg.data_length = fill_connect_data((char *)cp->data,
324 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800325 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700326}
327
328static void send_auth_request(atransport *t)
329{
330 D("Calling send_auth_request\n");
331 apacket *p;
332 int ret;
333
334 ret = adb_auth_generate_token(t->token, sizeof(t->token));
335 if (ret != sizeof(t->token)) {
336 D("Error generating token ret=%d\n", ret);
337 return;
338 }
339
340 p = get_apacket();
341 memcpy(p->data, t->token, ret);
342 p->msg.command = A_AUTH;
343 p->msg.arg0 = ADB_AUTH_TOKEN;
344 p->msg.data_length = ret;
345 send_packet(p, t);
346}
347
348static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
349{
350 D("Calling send_auth_response\n");
351 apacket *p = get_apacket();
352 int ret;
353
354 ret = adb_auth_sign(t->key, token, token_size, p->data);
355 if (!ret) {
356 D("Error signing the token\n");
357 put_apacket(p);
358 return;
359 }
360
361 p->msg.command = A_AUTH;
362 p->msg.arg0 = ADB_AUTH_SIGNATURE;
363 p->msg.data_length = ret;
364 send_packet(p, t);
365}
366
367static void send_auth_publickey(atransport *t)
368{
369 D("Calling send_auth_publickey\n");
370 apacket *p = get_apacket();
371 int ret;
372
373 ret = adb_auth_get_userkey(p->data, sizeof(p->data));
374 if (!ret) {
375 D("Failed to get user public key\n");
376 put_apacket(p);
377 return;
378 }
379
380 p->msg.command = A_AUTH;
381 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
382 p->msg.data_length = ret;
383 send_packet(p, t);
384}
385
386void adb_auth_verified(atransport *t)
387{
388 handle_online(t);
389 send_connect(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800390}
391
392static char *connection_state_name(atransport *t)
393{
394 if (t == NULL) {
395 return "unknown";
396 }
397
398 switch(t->connection_state) {
399 case CS_BOOTLOADER:
400 return "bootloader";
401 case CS_DEVICE:
402 return "device";
403 case CS_OFFLINE:
404 return "offline";
405 default:
406 return "unknown";
407 }
408}
409
Scott Andersone82c2db2012-05-25 14:10:02 -0700410/* qual_overwrite is used to overwrite a qualifier string. dst is a
411 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700412 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700413 */
414static void qual_overwrite(char **dst, const char *src)
415{
416 if (!dst)
417 return;
418
419 free(*dst);
420 *dst = NULL;
421
422 if (!src || !*src)
423 return;
424
425 *dst = strdup(src);
426}
427
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800428void parse_banner(char *banner, atransport *t)
429{
Scott Andersone82c2db2012-05-25 14:10:02 -0700430 static const char *prop_seps = ";";
431 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700432 char *cp;
433 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434
435 D("parse_banner: %s\n", banner);
436 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700437 cp = strchr(type, ':');
438 if (cp) {
439 *cp++ = 0;
440 /* Nothing is done with second field. */
441 cp = strchr(cp, ':');
442 if (cp) {
443 char *save;
444 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700445 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700446 while (key) {
447 cp = strchr(key, key_val_sep);
448 if (cp) {
449 *cp++ = '\0';
450 if (!strcmp(key, "ro.product.name"))
451 qual_overwrite(&t->product, cp);
452 else if (!strcmp(key, "ro.product.model"))
453 qual_overwrite(&t->model, cp);
454 else if (!strcmp(key, "ro.product.device"))
455 qual_overwrite(&t->device, cp);
456 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700457 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700458 }
459 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460 }
461
462 if(!strcmp(type, "bootloader")){
463 D("setting connection_state to CS_BOOTLOADER\n");
464 t->connection_state = CS_BOOTLOADER;
465 update_transports();
466 return;
467 }
468
469 if(!strcmp(type, "device")) {
470 D("setting connection_state to CS_DEVICE\n");
471 t->connection_state = CS_DEVICE;
472 update_transports();
473 return;
474 }
475
476 if(!strcmp(type, "recovery")) {
477 D("setting connection_state to CS_RECOVERY\n");
478 t->connection_state = CS_RECOVERY;
479 update_transports();
480 return;
481 }
482
Doug Zongker447f0612012-01-09 14:54:53 -0800483 if(!strcmp(type, "sideload")) {
484 D("setting connection_state to CS_SIDELOAD\n");
485 t->connection_state = CS_SIDELOAD;
486 update_transports();
487 return;
488 }
489
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800490 t->connection_state = CS_HOST;
491}
492
493void handle_packet(apacket *p, atransport *t)
494{
495 asocket *s;
496
Viral Mehta899913f2010-06-16 18:41:28 +0530497 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
498 ((char*) (&(p->msg.command)))[1],
499 ((char*) (&(p->msg.command)))[2],
500 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800501 print_packet("recv", p);
502
503 switch(p->msg.command){
504 case A_SYNC:
505 if(p->msg.arg0){
506 send_packet(p, t);
507 if(HOST) send_connect(t);
508 } else {
509 t->connection_state = CS_OFFLINE;
510 handle_offline(t);
511 send_packet(p, t);
512 }
513 return;
514
515 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
516 /* XXX verify version, etc */
517 if(t->connection_state != CS_OFFLINE) {
518 t->connection_state = CS_OFFLINE;
519 handle_offline(t);
520 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700521
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700523
524 if (HOST || !auth_enabled) {
525 handle_online(t);
526 if(!HOST) send_connect(t);
527 } else {
528 send_auth_request(t);
529 }
530 break;
531
532 case A_AUTH:
533 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
534 t->key = adb_auth_nextkey(t->key);
535 if (t->key) {
536 send_auth_response(p->data, p->msg.data_length, t);
537 } else {
538 /* No more private keys to try, send the public key */
539 send_auth_publickey(t);
540 }
541 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
542 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
543 adb_auth_verified(t);
544 t->failed_auth_attempts = 0;
545 } else {
546 if (t->failed_auth_attempts++ > 10)
547 adb_sleep_ms(1000);
548 send_auth_request(t);
549 }
550 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
551 adb_auth_confirm_key(p->data, p->msg.data_length, t);
552 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553 break;
554
555 case A_OPEN: /* OPEN(local-id, 0, "destination") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700556 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 char *name = (char*) p->data;
558 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
559 s = create_local_service_socket(name);
560 if(s == 0) {
561 send_close(0, p->msg.arg0, t);
562 } else {
563 s->peer = create_remote_socket(p->msg.arg0, t);
564 s->peer->peer = s;
565 send_ready(s->id, s->peer->id, t);
566 s->ready(s);
567 }
568 }
569 break;
570
571 case A_OKAY: /* READY(local-id, remote-id, "") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700572 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573 if((s = find_local_socket(p->msg.arg1))) {
574 if(s->peer == 0) {
575 s->peer = create_remote_socket(p->msg.arg0, t);
576 s->peer->peer = s;
577 }
578 s->ready(s);
579 }
580 }
581 break;
582
583 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700584 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800585 if((s = find_local_socket(p->msg.arg1))) {
586 s->close(s);
587 }
588 }
589 break;
590
591 case A_WRTE:
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700592 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593 if((s = find_local_socket(p->msg.arg1))) {
594 unsigned rid = p->msg.arg0;
595 p->len = p->msg.data_length;
596
597 if(s->enqueue(s, p) == 0) {
598 D("Enqueue the socket\n");
599 send_ready(s->id, rid, t);
600 }
601 return;
602 }
603 }
604 break;
605
606 default:
607 printf("handle_packet: what is %08x?!\n", p->msg.command);
608 }
609
610 put_apacket(p);
611}
612
613alistener listener_list = {
614 .next = &listener_list,
615 .prev = &listener_list,
616};
617
618static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
619{
620 asocket *s;
621
622 if(ev & FDE_READ) {
623 struct sockaddr addr;
624 socklen_t alen;
625 int fd;
626
627 alen = sizeof(addr);
628 fd = adb_socket_accept(_fd, &addr, &alen);
629 if(fd < 0) return;
630
631 adb_socket_setbufsize(fd, CHUNK_SIZE);
632
633 s = create_local_socket(fd);
634 if(s) {
635 connect_to_smartsocket(s);
636 return;
637 }
638
639 adb_close(fd);
640 }
641}
642
643static void listener_event_func(int _fd, unsigned ev, void *_l)
644{
645 alistener *l = _l;
646 asocket *s;
647
648 if(ev & FDE_READ) {
649 struct sockaddr addr;
650 socklen_t alen;
651 int fd;
652
653 alen = sizeof(addr);
654 fd = adb_socket_accept(_fd, &addr, &alen);
655 if(fd < 0) return;
656
657 s = create_local_socket(fd);
658 if(s) {
659 s->transport = l->transport;
660 connect_to_remote(s, l->connect_to);
661 return;
662 }
663
664 adb_close(fd);
665 }
666}
667
668static void free_listener(alistener* l)
669{
670 if (l->next) {
671 l->next->prev = l->prev;
672 l->prev->next = l->next;
673 l->next = l->prev = l;
674 }
675
676 // closes the corresponding fd
677 fdevent_remove(&l->fde);
678
679 if (l->local_name)
680 free((char*)l->local_name);
681
682 if (l->connect_to)
683 free((char*)l->connect_to);
684
685 if (l->transport) {
686 remove_transport_disconnect(l->transport, &l->disconnect);
687 }
688 free(l);
689}
690
691static void listener_disconnect(void* _l, atransport* t)
692{
693 alistener* l = _l;
694
695 free_listener(l);
696}
697
698int local_name_to_fd(const char *name)
699{
700 int port;
701
702 if(!strncmp("tcp:", name, 4)){
703 int ret;
704 port = atoi(name + 4);
705 ret = socket_loopback_server(port, SOCK_STREAM);
706 return ret;
707 }
708#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
709 // It's non-sensical to support the "reserved" space on the adb host side
710 if(!strncmp(name, "local:", 6)) {
711 return socket_local_server(name + 6,
712 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
713 } else if(!strncmp(name, "localabstract:", 14)) {
714 return socket_local_server(name + 14,
715 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
716 } else if(!strncmp(name, "localfilesystem:", 16)) {
717 return socket_local_server(name + 16,
718 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
719 }
720
721#endif
722 printf("unknown local portname '%s'\n", name);
723 return -1;
724}
725
726static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
727{
728 alistener *l;
729
730 for (l = listener_list.next; l != &listener_list; l = l->next) {
731 if (!strcmp(local_name, l->local_name) &&
732 !strcmp(connect_to, l->connect_to) &&
733 l->transport && l->transport == transport) {
734
735 listener_disconnect(l, transport);
736 return 0;
737 }
738 }
739
740 return -1;
741}
742
743static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
744{
745 alistener *l;
746
747 //printf("install_listener('%s','%s')\n", local_name, connect_to);
748
749 for(l = listener_list.next; l != &listener_list; l = l->next){
750 if(strcmp(local_name, l->local_name) == 0) {
751 char *cto;
752
753 /* can't repurpose a smartsocket */
754 if(l->connect_to[0] == '*') {
755 return -1;
756 }
757
758 cto = strdup(connect_to);
759 if(cto == 0) {
760 return -1;
761 }
762
763 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
764 free((void*) l->connect_to);
765 l->connect_to = cto;
766 if (l->transport != transport) {
767 remove_transport_disconnect(l->transport, &l->disconnect);
768 l->transport = transport;
769 add_transport_disconnect(l->transport, &l->disconnect);
770 }
771 return 0;
772 }
773 }
774
775 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
776 if((l->local_name = strdup(local_name)) == 0) goto nomem;
777 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
778
779
780 l->fd = local_name_to_fd(local_name);
781 if(l->fd < 0) {
782 free((void*) l->local_name);
783 free((void*) l->connect_to);
784 free(l);
785 printf("cannot bind '%s'\n", local_name);
786 return -2;
787 }
788
789 close_on_exec(l->fd);
790 if(!strcmp(l->connect_to, "*smartsocket*")) {
791 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
792 } else {
793 fdevent_install(&l->fde, l->fd, listener_event_func, l);
794 }
795 fdevent_set(&l->fde, FDE_READ);
796
797 l->next = &listener_list;
798 l->prev = listener_list.prev;
799 l->next->prev = l;
800 l->prev->next = l;
801 l->transport = transport;
802
803 if (transport) {
804 l->disconnect.opaque = l;
805 l->disconnect.func = listener_disconnect;
806 add_transport_disconnect(transport, &l->disconnect);
807 }
808 return 0;
809
810nomem:
811 fatal("cannot allocate listener");
812 return 0;
813}
814
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800815#ifdef HAVE_WIN32_PROC
816static BOOL WINAPI ctrlc_handler(DWORD type)
817{
818 exit(STATUS_CONTROL_C_EXIT);
819 return TRUE;
820}
821#endif
822
823static void adb_cleanup(void)
824{
825 usb_cleanup();
826}
827
828void start_logging(void)
829{
830#ifdef HAVE_WIN32_PROC
831 char temp[ MAX_PATH ];
832 FILE* fnul;
833 FILE* flog;
834
835 GetTempPath( sizeof(temp) - 8, temp );
836 strcat( temp, "adb.log" );
837
838 /* Win32 specific redirections */
839 fnul = fopen( "NUL", "rt" );
840 if (fnul != NULL)
841 stdin[0] = fnul[0];
842
843 flog = fopen( temp, "at" );
844 if (flog == NULL)
845 flog = fnul;
846
847 setvbuf( flog, NULL, _IONBF, 0 );
848
849 stdout[0] = flog[0];
850 stderr[0] = flog[0];
851 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
852#else
853 int fd;
854
855 fd = unix_open("/dev/null", O_RDONLY);
856 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700857 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800858
859 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
860 if(fd < 0) {
861 fd = unix_open("/dev/null", O_WRONLY);
862 }
863 dup2(fd, 1);
864 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700865 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
867#endif
868}
869
870#if !ADB_HOST
871void start_device_log(void)
872{
873 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400874 char path[PATH_MAX];
875 struct tm now;
876 time_t t;
877 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878
Mike Lockwood1f546e62009-05-25 18:17:55 -0400879 // read the trace mask from persistent property persist.adb.trace_mask
880 // give up if the property is not set or cannot be parsed
881 property_get("persist.adb.trace_mask", value, "");
882 if (sscanf(value, "%x", &adb_trace_mask) != 1)
883 return;
884
885 adb_mkdir("/data/adb", 0775);
886 tzset();
887 time(&t);
888 localtime_r(&t, &now);
889 strftime(path, sizeof(path),
890 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
891 &now);
892 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800893 if (fd < 0)
894 return;
895
896 // redirect stdout and stderr to the log file
897 dup2(fd, 1);
898 dup2(fd, 2);
899 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800900 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901
902 fd = unix_open("/dev/null", O_RDONLY);
903 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800904 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800905}
906#endif
907
908#if ADB_HOST
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100909int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800910{
911#ifdef HAVE_WIN32_PROC
912 /* we need to start the server in the background */
913 /* we create a PIPE that will be used to wait for the server's "OK" */
914 /* message since the pipe handles must be inheritable, we use a */
915 /* security attribute */
916 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000917 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800918 SECURITY_ATTRIBUTES sa;
919 STARTUPINFO startup;
920 PROCESS_INFORMATION pinfo;
921 char program_path[ MAX_PATH ];
922 int ret;
923
924 sa.nLength = sizeof(sa);
925 sa.lpSecurityDescriptor = NULL;
926 sa.bInheritHandle = TRUE;
927
928 /* create pipe, and ensure its read handle isn't inheritable */
929 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
930 if (!ret) {
931 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
932 return -1;
933 }
934
935 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
936
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000937 /* Some programs want to launch an adb command and collect its output by
938 * calling CreateProcess with inheritable stdout/stderr handles, then
939 * using read() to get its output. When this happens, the stdout/stderr
940 * handles passed to the adb client process will also be inheritable.
941 * When starting the adb server here, care must be taken to reset them
942 * to non-inheritable.
943 * Otherwise, something bad happens: even if the adb command completes,
944 * the calling process is stuck while read()-ing from the stdout/stderr
945 * descriptors, because they're connected to corresponding handles in the
946 * adb server process (even if the latter never uses/writes to them).
947 */
948 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
949 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
950 if (stdout_handle != INVALID_HANDLE_VALUE) {
951 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
952 }
953 if (stderr_handle != INVALID_HANDLE_VALUE) {
954 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
955 }
956
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800957 ZeroMemory( &startup, sizeof(startup) );
958 startup.cb = sizeof(startup);
959 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
960 startup.hStdOutput = pipe_write;
961 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
962 startup.dwFlags = STARTF_USESTDHANDLES;
963
964 ZeroMemory( &pinfo, sizeof(pinfo) );
965
966 /* get path of current program */
967 GetModuleFileName( NULL, program_path, sizeof(program_path) );
968
969 ret = CreateProcess(
970 program_path, /* program path */
971 "adb fork-server server",
972 /* the fork-server argument will set the
973 debug = 2 in the child */
974 NULL, /* process handle is not inheritable */
975 NULL, /* thread handle is not inheritable */
976 TRUE, /* yes, inherit some handles */
977 DETACHED_PROCESS, /* the new process doesn't have a console */
978 NULL, /* use parent's environment block */
979 NULL, /* use parent's starting directory */
980 &startup, /* startup info, i.e. std handles */
981 &pinfo );
982
983 CloseHandle( pipe_write );
984
985 if (!ret) {
986 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
987 CloseHandle( pipe_read );
988 return -1;
989 }
990
991 CloseHandle( pinfo.hProcess );
992 CloseHandle( pinfo.hThread );
993
994 /* wait for the "OK\n" message */
995 {
996 char temp[3];
997 DWORD count;
998
999 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1000 CloseHandle( pipe_read );
1001 if ( !ret ) {
1002 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1003 return -1;
1004 }
1005 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1006 fprintf(stderr, "ADB server didn't ACK\n" );
1007 return -1;
1008 }
1009 }
1010#elif defined(HAVE_FORKEXEC)
1011 char path[PATH_MAX];
1012 int fd[2];
1013
1014 // set up a pipe so the child can tell us when it is ready.
1015 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1016 if (pipe(fd)) {
1017 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1018 return -1;
1019 }
Alexey Tarasov31664102009-10-22 02:55:00 +11001020 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001021 pid_t pid = fork();
1022 if(pid < 0) return -1;
1023
1024 if (pid == 0) {
1025 // child side of the fork
1026
1027 // redirect stderr to the pipe
1028 // we use stderr instead of stdout due to stdout's buffering behavior.
1029 adb_close(fd[0]);
1030 dup2(fd[1], STDERR_FILENO);
1031 adb_close(fd[1]);
1032
1033 // child process
1034 int result = execl(path, "adb", "fork-server", "server", NULL);
1035 // this should not return
1036 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1037 } else {
1038 // parent side of the fork
1039
1040 char temp[3];
1041
1042 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1043 // wait for the "OK\n" message
1044 adb_close(fd[1]);
1045 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -07001046 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001047 adb_close(fd[0]);
1048 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -07001049 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001050 return -1;
1051 }
1052 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1053 fprintf(stderr, "ADB server didn't ACK\n" );
1054 return -1;
1055 }
1056
1057 setsid();
1058 }
1059#else
1060#error "cannot implement background server start on this platform"
1061#endif
1062 return 0;
1063}
1064#endif
1065
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001066/* Constructs a local name of form tcp:port.
1067 * target_str points to the target string, it's content will be overwritten.
1068 * target_size is the capacity of the target string.
1069 * server_port is the port number to use for the local name.
1070 */
1071void build_local_name(char* target_str, size_t target_size, int server_port)
1072{
1073 snprintf(target_str, target_size, "tcp:%d", server_port);
1074}
1075
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001076#if !ADB_HOST
1077static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -08001078#ifndef ALLOW_ADBD_ROOT
1079 return 1;
1080#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001081 int secure = 0;
1082 char value[PROPERTY_VALUE_MAX];
1083
1084 /* run adbd in secure mode if ro.secure is set and
1085 ** we are not in the emulator
1086 */
1087 property_get("ro.kernel.qemu", value, "");
1088 if (strcmp(value, "1") != 0) {
1089 property_get("ro.secure", value, "1");
1090 if (strcmp(value, "1") == 0) {
1091 // don't run as root if ro.secure is set...
1092 secure = 1;
1093
1094 // ... except we allow running as root in userdebug builds if the
1095 // service.adb.root property has been set by the "adb root" command
1096 property_get("ro.debuggable", value, "");
1097 if (strcmp(value, "1") == 0) {
1098 property_get("service.adb.root", value, "");
1099 if (strcmp(value, "1") == 0) {
1100 secure = 0;
1101 }
1102 }
1103 }
1104 }
1105 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -08001106#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001107}
1108#endif /* !ADB_HOST */
1109
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001110int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001111{
1112#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -07001113 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001114 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -07001115
1116 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001117#endif
1118
1119 atexit(adb_cleanup);
1120#ifdef HAVE_WIN32_PROC
1121 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1122#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -07001123 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001124 signal(SIGPIPE, SIG_IGN);
1125#endif
1126
1127 init_transport_registration();
1128
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001129#if ADB_HOST
1130 HOST = 1;
Xavier Ducroheta09fbd12009-05-20 17:33:53 -07001131 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001132 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001133 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001134 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001136 char local_name[30];
1137 build_local_name(local_name, sizeof(local_name), server_port);
1138 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001139 exit(1);
1140 }
1141#else
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001142 property_get("ro.adb.secure", value, "0");
1143 auth_enabled = !strcmp(value, "1");
1144 if (auth_enabled)
1145 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001146
Jeff Sharkeyd6d42862012-09-06 13:05:40 -07001147 // Our external storage path may be different than apps, since
1148 // we aren't able to bind mount after dropping root.
1149 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1150 if (NULL != adb_external_storage) {
1151 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1152 } else {
1153 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1154 " unchanged.\n");
1155 }
1156
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001157 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001158 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001159 if (should_drop_privileges()) {
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001160 struct __user_cap_header_struct header;
1161 struct __user_cap_data_struct cap;
1162
Nick Kralevich44db9902010-08-27 14:35:07 -07001163 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1164 exit(1);
1165 }
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001166
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001167 /* add extra groups:
1168 ** AID_ADB to access the USB driver
1169 ** AID_LOG to read system logs (adb logcat)
1170 ** AID_INPUT to diagnose input issues (getevent)
1171 ** AID_INET to diagnose network issues (netcfg, ping)
1172 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -07001173 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001174 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -04001175 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -05001176 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -08001177 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001178 */
The Android Open Source Project20155492009-03-11 12:12:01 -07001179 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001180 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1181 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -07001182 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1183 exit(1);
1184 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185
1186 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -07001187 if (setgid(AID_SHELL) != 0) {
1188 exit(1);
1189 }
1190 if (setuid(AID_SHELL) != 0) {
1191 exit(1);
1192 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001193
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001194 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1195 header.version = _LINUX_CAPABILITY_VERSION;
1196 header.pid = 0;
1197 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1198 cap.inheritable = 0;
1199 capset(&header, &cap);
1200
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001201 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001203 char local_name[30];
1204 build_local_name(local_name, sizeof(local_name), server_port);
1205 if(install_listener(local_name, "*smartsocket*", NULL)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001206 exit(1);
1207 }
1208 }
1209
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001210 int usb = 0;
1211 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001212 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001213 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001214 usb = 1;
1215 }
1216
1217 // If one of these properties is set, also listen on that port
1218 // If one of the properties isn't set and we couldn't listen on usb,
1219 // listen on the default port.
1220 property_get("service.adb.tcp.port", value, "");
1221 if (!value[0]) {
1222 property_get("persist.adb.tcp.port", value, "");
1223 }
1224 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1225 printf("using port=%d\n", port);
1226 // listen on TCP port specified by service.adb.tcp.port property
1227 local_init(port);
1228 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001229 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001230 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001231 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001232
JP Abgrall408fa572011-03-16 15:57:42 -07001233 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001234 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001235 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001236#endif
1237
1238 if (is_daemon)
1239 {
1240 // inform our parent that we are up and running.
1241#ifdef HAVE_WIN32_PROC
1242 DWORD count;
1243 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1244#elif defined(HAVE_FORKEXEC)
1245 fprintf(stderr, "OK\n");
1246#endif
1247 start_logging();
1248 }
JP Abgrall408fa572011-03-16 15:57:42 -07001249 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001250
1251 fdevent_loop();
1252
1253 usb_cleanup();
1254
1255 return 0;
1256}
1257
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001258#if ADB_HOST
1259void connect_device(char* host, char* buffer, int buffer_size)
1260{
1261 int port, fd;
1262 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001263 char hostbuf[100];
1264 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001265
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001266 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1267 if (portstr) {
Scott Andersonc7993af2012-05-25 13:55:46 -07001268 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001269 snprintf(buffer, buffer_size, "bad host name %s", host);
1270 return;
1271 }
1272 // zero terminate the host at the point we found the colon
1273 hostbuf[portstr - host] = 0;
1274 if (sscanf(portstr + 1, "%d", &port) == 0) {
1275 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1276 return;
1277 }
1278 } else {
1279 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001280 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001281
1282 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1283 if (find_transport(serial)) {
1284 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001285 return;
1286 }
1287
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001288 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001289 if (fd < 0) {
1290 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1291 return;
1292 }
1293
1294 D("client: connected on remote on fd %d\n", fd);
1295 close_on_exec(fd);
1296 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001297 register_socket_transport(fd, serial, port, 0);
1298 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001299}
1300
1301void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1302{
1303 char* port_separator = strchr(port_spec, ',');
1304 if (!port_separator) {
1305 snprintf(buffer, buffer_size,
1306 "unable to parse '%s' as <console port>,<adb port>",
1307 port_spec);
1308 return;
1309 }
1310
1311 // Zero-terminate console port and make port_separator point to 2nd port.
1312 *port_separator++ = 0;
1313 int console_port = strtol(port_spec, NULL, 0);
1314 int adb_port = strtol(port_separator, NULL, 0);
1315 if (!(console_port > 0 && adb_port > 0)) {
1316 *(port_separator - 1) = ',';
1317 snprintf(buffer, buffer_size,
1318 "Invalid port numbers: Expected positive numbers, got '%s'",
1319 port_spec);
1320 return;
1321 }
1322
1323 /* Check if the emulator is already known.
1324 * Note: There's a small but harmless race condition here: An emulator not
1325 * present just yet could be registered by another invocation right
1326 * after doing this check here. However, local_connect protects
1327 * against double-registration too. From here, a better error message
1328 * can be produced. In the case of the race condition, the very specific
1329 * error message won't be shown, but the data doesn't get corrupted. */
1330 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1331 if (known_emulator != NULL) {
1332 snprintf(buffer, buffer_size,
1333 "Emulator on port %d already registered.", adb_port);
1334 return;
1335 }
1336
1337 /* Check if more emulators can be registered. Similar unproblematic
1338 * race condition as above. */
1339 int candidate_slot = get_available_local_transport_index();
1340 if (candidate_slot < 0) {
1341 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1342 return;
1343 }
1344
1345 /* Preconditions met, try to connect to the emulator. */
1346 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1347 snprintf(buffer, buffer_size,
1348 "Connected to emulator on ports %d,%d", console_port, adb_port);
1349 } else {
1350 snprintf(buffer, buffer_size,
1351 "Could not connect to emulator on ports %d,%d",
1352 console_port, adb_port);
1353 }
1354}
1355#endif
1356
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001357int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1358{
1359 atransport *transport = NULL;
1360 char buf[4096];
1361
1362 if(!strcmp(service, "kill")) {
1363 fprintf(stderr,"adb server killed by remote request\n");
1364 fflush(stdout);
1365 adb_write(reply_fd, "OKAY", 4);
1366 usb_cleanup();
1367 exit(0);
1368 }
1369
1370#if ADB_HOST
1371 // "transport:" is used for switching transport with a specified serial number
1372 // "transport-usb:" is used for switching transport to the only USB transport
1373 // "transport-local:" is used for switching transport to the only local transport
1374 // "transport-any:" is used for switching transport to the only transport
1375 if (!strncmp(service, "transport", strlen("transport"))) {
1376 char* error_string = "unknown failure";
1377 transport_type type = kTransportAny;
1378
1379 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1380 type = kTransportUsb;
1381 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1382 type = kTransportLocal;
1383 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1384 type = kTransportAny;
1385 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1386 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001387 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001388 }
1389
1390 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1391
1392 if (transport) {
1393 s->transport = transport;
1394 adb_write(reply_fd, "OKAY", 4);
1395 } else {
1396 sendfailmsg(reply_fd, error_string);
1397 }
1398 return 1;
1399 }
1400
1401 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001402 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001403 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001404 int use_long = !strcmp(service+7, "-l");
1405 if (use_long || service[7] == 0) {
1406 memset(buf, 0, sizeof(buf));
1407 memset(buffer, 0, sizeof(buffer));
1408 D("Getting device list \n");
1409 list_transports(buffer, sizeof(buffer), use_long);
1410 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1411 D("Wrote device list \n");
1412 writex(reply_fd, buf, strlen(buf));
1413 return 0;
1414 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001415 }
1416
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001417 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001418 if (!strncmp(service, "connect:", 8)) {
1419 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001420 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001421 if (!strncmp(host, "emu:", 4)) {
1422 connect_emulator(host + 4, buffer, sizeof(buffer));
1423 } else {
1424 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001425 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001426 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001427 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1428 writex(reply_fd, buf, strlen(buf));
1429 return 0;
1430 }
1431
1432 // remove TCP transport
1433 if (!strncmp(service, "disconnect:", 11)) {
1434 char buffer[4096];
1435 memset(buffer, 0, sizeof(buffer));
1436 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001437 if (serial[0] == 0) {
1438 // disconnect from all TCP devices
1439 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001440 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001441 char hostbuf[100];
1442 // assume port 5555 if no port is specified
1443 if (!strchr(serial, ':')) {
1444 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1445 serial = hostbuf;
1446 }
1447 atransport *t = find_transport(serial);
1448
1449 if (t) {
1450 unregister_transport(t);
1451 } else {
1452 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1453 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001454 }
1455
1456 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001457 writex(reply_fd, buf, strlen(buf));
1458 return 0;
1459 }
1460
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001461 // returns our value for ADB_SERVER_VERSION
1462 if (!strcmp(service, "version")) {
1463 char version[12];
1464 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1465 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1466 writex(reply_fd, buf, strlen(buf));
1467 return 0;
1468 }
1469
1470 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1471 char *out = "unknown";
1472 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1473 if (transport && transport->serial) {
1474 out = transport->serial;
1475 }
1476 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1477 writex(reply_fd, buf, strlen(buf));
1478 return 0;
1479 }
Scott Andersone109d262012-04-20 11:21:14 -07001480 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1481 char *out = "unknown";
1482 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1483 if (transport && transport->devpath) {
1484 out = transport->devpath;
1485 }
1486 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1487 writex(reply_fd, buf, strlen(buf));
1488 return 0;
1489 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001490 // indicates a new emulator instance has started
1491 if (!strncmp(service,"emulator:",9)) {
1492 int port = atoi(service+9);
1493 local_connect(port);
1494 /* we don't even need to send a reply */
1495 return 0;
1496 }
1497#endif // ADB_HOST
1498
1499 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1500 char *local, *remote, *err;
1501 int r;
1502 atransport *transport;
1503
1504 int createForward = strncmp(service,"kill",4);
1505
1506 local = service + (createForward ? 8 : 12);
1507 remote = strchr(local,';');
1508 if(remote == 0) {
1509 sendfailmsg(reply_fd, "malformed forward spec");
1510 return 0;
1511 }
1512
1513 *remote++ = 0;
1514 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1515 sendfailmsg(reply_fd, "malformed forward spec");
1516 return 0;
1517 }
1518
1519 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1520 if (!transport) {
1521 sendfailmsg(reply_fd, err);
1522 return 0;
1523 }
1524
1525 if (createForward) {
1526 r = install_listener(local, remote, transport);
1527 } else {
1528 r = remove_listener(local, remote, transport);
1529 }
1530 if(r == 0) {
1531 /* 1st OKAY is connect, 2nd OKAY is status */
1532 writex(reply_fd, "OKAYOKAY", 8);
1533 return 0;
1534 }
1535
1536 if (createForward) {
1537 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1538 } else {
1539 sendfailmsg(reply_fd, "cannot remove listener");
1540 }
1541 return 0;
1542 }
1543
1544 if(!strncmp(service,"get-state",strlen("get-state"))) {
1545 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1546 char *state = connection_state_name(transport);
1547 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1548 writex(reply_fd, buf, strlen(buf));
1549 return 0;
1550 }
1551 return -1;
1552}
1553
1554#if !ADB_HOST
1555int recovery_mode = 0;
1556#endif
1557
1558int main(int argc, char **argv)
1559{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001560#if ADB_HOST
1561 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001562 adb_trace_init();
1563 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001564 return adb_commandline(argc - 1, argv + 1);
1565#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001566 /* If adbd runs inside the emulator this will enable adb tracing via
1567 * adb-debug qemud service in the emulator. */
1568 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001569 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1570 adb_device_banner = "recovery";
1571 recovery_mode = 1;
1572 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001573
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001574 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001575 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001576 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001577#endif
1578}