blob: 41270f94e451777f77269870b5db301aee731182 [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
Nick Kralevich893a4a42013-05-23 09:54:13 -070037#include <cutils/properties.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080038#include <private/android_filesystem_config.h>
Nick Kraleviche2864bf2013-02-28 14:12:58 -080039#include <sys/capability.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040040#include <linux/prctl.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070041#include <sys/mount.h>
Xavier Ducroheta09fbd12009-05-20 17:33:53 -070042#else
43#include "usb_vendors.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044#endif
45
JP Abgrall408fa572011-03-16 15:57:42 -070046#if ADB_TRACE
47ADB_MUTEX_DEFINE( D_lock );
48#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049
50int HOST = 0;
Matt Gumbeld7b33082012-11-14 10:16:17 -080051int gListenAll = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080052
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070053static int auth_enabled = 0;
54
Scott Andersone82c2db2012-05-25 14:10:02 -070055#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080056static const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070057#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058
59void fatal(const char *fmt, ...)
60{
61 va_list ap;
62 va_start(ap, fmt);
63 fprintf(stderr, "error: ");
64 vfprintf(stderr, fmt, ap);
65 fprintf(stderr, "\n");
66 va_end(ap);
67 exit(-1);
68}
69
70void fatal_errno(const char *fmt, ...)
71{
72 va_list ap;
73 va_start(ap, fmt);
74 fprintf(stderr, "error: %s: ", strerror(errno));
75 vfprintf(stderr, fmt, ap);
76 fprintf(stderr, "\n");
77 va_end(ap);
78 exit(-1);
79}
80
81int adb_trace_mask;
82
83/* read a comma/space/colum/semi-column separated list of tags
84 * from the ADB_TRACE environment variable and build the trace
85 * mask from it. note that '1' and 'all' are special cases to
86 * enable all tracing
87 */
88void adb_trace_init(void)
89{
90 const char* p = getenv("ADB_TRACE");
91 const char* q;
92
93 static const struct {
94 const char* tag;
95 int flag;
96 } tags[] = {
97 { "1", 0 },
98 { "all", 0 },
99 { "adb", TRACE_ADB },
100 { "sockets", TRACE_SOCKETS },
101 { "packets", TRACE_PACKETS },
102 { "rwx", TRACE_RWX },
103 { "usb", TRACE_USB },
104 { "sync", TRACE_SYNC },
105 { "sysdeps", TRACE_SYSDEPS },
106 { "transport", TRACE_TRANSPORT },
107 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700108 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700109 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800110 { NULL, 0 }
111 };
112
113 if (p == NULL)
114 return;
115
116 /* use a comma/column/semi-colum/space separated list */
117 while (*p) {
118 int len, tagn;
119
120 q = strpbrk(p, " ,:;");
121 if (q == NULL) {
122 q = p + strlen(p);
123 }
124 len = q - p;
125
126 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
127 {
128 int taglen = strlen(tags[tagn].tag);
129
130 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
131 {
132 int flag = tags[tagn].flag;
133 if (flag == 0) {
134 adb_trace_mask = ~0;
135 return;
136 }
137 adb_trace_mask |= (1 << flag);
138 break;
139 }
140 }
141 p = q;
142 if (*p)
143 p++;
144 }
145}
146
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800147#if !ADB_HOST
148/*
149 * Implements ADB tracing inside the emulator.
150 */
151
152#include <stdarg.h>
153
154/*
155 * Redefine open and write for qemu_pipe.h that contains inlined references
156 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
157 */
158
159#undef open
160#undef write
161#define open adb_open
162#define write adb_write
163#include <hardware/qemu_pipe.h>
164#undef open
165#undef write
166#define open ___xxx_open
167#define write ___xxx_write
168
169/* A handle to adb-debug qemud service in the emulator. */
170int adb_debug_qemu = -1;
171
172/* Initializes connection with the adb-debug qemud service in the emulator. */
173static int adb_qemu_trace_init(void)
174{
175 char con_name[32];
176
177 if (adb_debug_qemu >= 0) {
178 return 0;
179 }
180
181 /* adb debugging QEMUD service connection request. */
182 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
183 adb_debug_qemu = qemu_pipe_open(con_name);
184 return (adb_debug_qemu >= 0) ? 0 : -1;
185}
186
187void adb_qemu_trace(const char* fmt, ...)
188{
189 va_list args;
190 va_start(args, fmt);
191 char msg[1024];
192
193 if (adb_debug_qemu >= 0) {
194 vsnprintf(msg, sizeof(msg), fmt, args);
195 adb_write(adb_debug_qemu, msg, strlen(msg));
196 }
197}
198#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800199
200apacket *get_apacket(void)
201{
202 apacket *p = malloc(sizeof(apacket));
203 if(p == 0) fatal("failed to allocate an apacket");
204 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
205 return p;
206}
207
208void put_apacket(apacket *p)
209{
210 free(p);
211}
212
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700213void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214{
215 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700216 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800217}
218
219void handle_offline(atransport *t)
220{
221 D("adb: offline\n");
222 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700223 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800224 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800225}
226
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700227#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800228#define DUMPMAX 32
229void print_packet(const char *label, apacket *p)
230{
231 char *tag;
232 char *x;
233 unsigned count;
234
235 switch(p->msg.command){
236 case A_SYNC: tag = "SYNC"; break;
237 case A_CNXN: tag = "CNXN" ; break;
238 case A_OPEN: tag = "OPEN"; break;
239 case A_OKAY: tag = "OKAY"; break;
240 case A_CLSE: tag = "CLSE"; break;
241 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700242 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800243 default: tag = "????"; break;
244 }
245
246 fprintf(stderr, "%s: %s %08x %08x %04x \"",
247 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
248 count = p->msg.data_length;
249 x = (char*) p->data;
250 if(count > DUMPMAX) {
251 count = DUMPMAX;
252 tag = "\n";
253 } else {
254 tag = "\"\n";
255 }
256 while(count-- > 0){
257 if((*x >= ' ') && (*x < 127)) {
258 fputc(*x, stderr);
259 } else {
260 fputc('.', stderr);
261 }
262 x++;
263 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700264 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800265}
266#endif
267
268static void send_ready(unsigned local, unsigned remote, atransport *t)
269{
270 D("Calling send_ready \n");
271 apacket *p = get_apacket();
272 p->msg.command = A_OKAY;
273 p->msg.arg0 = local;
274 p->msg.arg1 = remote;
275 send_packet(p, t);
276}
277
278static void send_close(unsigned local, unsigned remote, atransport *t)
279{
280 D("Calling send_close \n");
281 apacket *p = get_apacket();
282 p->msg.command = A_CLSE;
283 p->msg.arg0 = local;
284 p->msg.arg1 = remote;
285 send_packet(p, t);
286}
287
Scott Andersone82c2db2012-05-25 14:10:02 -0700288static size_t fill_connect_data(char *buf, size_t bufsize)
289{
290#if ADB_HOST
291 return snprintf(buf, bufsize, "host::") + 1;
292#else
293 static const char *cnxn_props[] = {
294 "ro.product.name",
295 "ro.product.model",
296 "ro.product.device",
297 };
298 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
299 int i;
300 size_t remaining = bufsize;
301 size_t len;
302
303 len = snprintf(buf, remaining, "%s::", adb_device_banner);
304 remaining -= len;
305 buf += len;
306 for (i = 0; i < num_cnxn_props; i++) {
307 char value[PROPERTY_VALUE_MAX];
308 property_get(cnxn_props[i], value, "");
309 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
310 remaining -= len;
311 buf += len;
312 }
313
314 return bufsize - remaining + 1;
315#endif
316}
317
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800318static void send_connect(atransport *t)
319{
320 D("Calling send_connect \n");
321 apacket *cp = get_apacket();
322 cp->msg.command = A_CNXN;
323 cp->msg.arg0 = A_VERSION;
324 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700325 cp->msg.data_length = fill_connect_data((char *)cp->data,
326 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800327 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700328}
329
Benoit Goby045a4a92013-01-15 19:59:14 -0800330void send_auth_request(atransport *t)
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700331{
332 D("Calling send_auth_request\n");
333 apacket *p;
334 int ret;
335
336 ret = adb_auth_generate_token(t->token, sizeof(t->token));
337 if (ret != sizeof(t->token)) {
338 D("Error generating token ret=%d\n", ret);
339 return;
340 }
341
342 p = get_apacket();
343 memcpy(p->data, t->token, ret);
344 p->msg.command = A_AUTH;
345 p->msg.arg0 = ADB_AUTH_TOKEN;
346 p->msg.data_length = ret;
347 send_packet(p, t);
348}
349
350static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
351{
352 D("Calling send_auth_response\n");
353 apacket *p = get_apacket();
354 int ret;
355
356 ret = adb_auth_sign(t->key, token, token_size, p->data);
357 if (!ret) {
358 D("Error signing the token\n");
359 put_apacket(p);
360 return;
361 }
362
363 p->msg.command = A_AUTH;
364 p->msg.arg0 = ADB_AUTH_SIGNATURE;
365 p->msg.data_length = ret;
366 send_packet(p, t);
367}
368
369static void send_auth_publickey(atransport *t)
370{
371 D("Calling send_auth_publickey\n");
372 apacket *p = get_apacket();
373 int ret;
374
375 ret = adb_auth_get_userkey(p->data, sizeof(p->data));
376 if (!ret) {
377 D("Failed to get user public key\n");
378 put_apacket(p);
379 return;
380 }
381
382 p->msg.command = A_AUTH;
383 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
384 p->msg.data_length = ret;
385 send_packet(p, t);
386}
387
388void adb_auth_verified(atransport *t)
389{
390 handle_online(t);
391 send_connect(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800392}
393
394static char *connection_state_name(atransport *t)
395{
396 if (t == NULL) {
397 return "unknown";
398 }
399
400 switch(t->connection_state) {
401 case CS_BOOTLOADER:
402 return "bootloader";
403 case CS_DEVICE:
404 return "device";
trevda5ad5392013-04-17 14:34:23 +0100405 case CS_RECOVERY:
406 return "recovery";
407 case CS_SIDELOAD:
408 return "sideload";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 case CS_OFFLINE:
410 return "offline";
Benoit Goby77e8e582013-01-15 12:36:47 -0800411 case CS_UNAUTHORIZED:
412 return "unauthorized";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800413 default:
414 return "unknown";
415 }
416}
417
Scott Andersone82c2db2012-05-25 14:10:02 -0700418/* qual_overwrite is used to overwrite a qualifier string. dst is a
419 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700420 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700421 */
422static void qual_overwrite(char **dst, const char *src)
423{
424 if (!dst)
425 return;
426
427 free(*dst);
428 *dst = NULL;
429
430 if (!src || !*src)
431 return;
432
433 *dst = strdup(src);
434}
435
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800436void parse_banner(char *banner, atransport *t)
437{
Scott Andersone82c2db2012-05-25 14:10:02 -0700438 static const char *prop_seps = ";";
439 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700440 char *cp;
441 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442
443 D("parse_banner: %s\n", banner);
444 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700445 cp = strchr(type, ':');
446 if (cp) {
447 *cp++ = 0;
448 /* Nothing is done with second field. */
449 cp = strchr(cp, ':');
450 if (cp) {
451 char *save;
452 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700453 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700454 while (key) {
455 cp = strchr(key, key_val_sep);
456 if (cp) {
457 *cp++ = '\0';
458 if (!strcmp(key, "ro.product.name"))
459 qual_overwrite(&t->product, cp);
460 else if (!strcmp(key, "ro.product.model"))
461 qual_overwrite(&t->model, cp);
462 else if (!strcmp(key, "ro.product.device"))
463 qual_overwrite(&t->device, cp);
464 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700465 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700466 }
467 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468 }
469
470 if(!strcmp(type, "bootloader")){
471 D("setting connection_state to CS_BOOTLOADER\n");
472 t->connection_state = CS_BOOTLOADER;
473 update_transports();
474 return;
475 }
476
477 if(!strcmp(type, "device")) {
478 D("setting connection_state to CS_DEVICE\n");
479 t->connection_state = CS_DEVICE;
480 update_transports();
481 return;
482 }
483
484 if(!strcmp(type, "recovery")) {
485 D("setting connection_state to CS_RECOVERY\n");
486 t->connection_state = CS_RECOVERY;
487 update_transports();
488 return;
489 }
490
Doug Zongker447f0612012-01-09 14:54:53 -0800491 if(!strcmp(type, "sideload")) {
492 D("setting connection_state to CS_SIDELOAD\n");
493 t->connection_state = CS_SIDELOAD;
494 update_transports();
495 return;
496 }
497
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498 t->connection_state = CS_HOST;
499}
500
501void handle_packet(apacket *p, atransport *t)
502{
503 asocket *s;
504
Viral Mehta899913f2010-06-16 18:41:28 +0530505 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
506 ((char*) (&(p->msg.command)))[1],
507 ((char*) (&(p->msg.command)))[2],
508 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800509 print_packet("recv", p);
510
511 switch(p->msg.command){
512 case A_SYNC:
513 if(p->msg.arg0){
514 send_packet(p, t);
515 if(HOST) send_connect(t);
516 } else {
517 t->connection_state = CS_OFFLINE;
518 handle_offline(t);
519 send_packet(p, t);
520 }
521 return;
522
523 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
524 /* XXX verify version, etc */
525 if(t->connection_state != CS_OFFLINE) {
526 t->connection_state = CS_OFFLINE;
527 handle_offline(t);
528 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700529
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700531
532 if (HOST || !auth_enabled) {
533 handle_online(t);
534 if(!HOST) send_connect(t);
535 } else {
536 send_auth_request(t);
537 }
538 break;
539
540 case A_AUTH:
541 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
Benoit Goby77e8e582013-01-15 12:36:47 -0800542 t->connection_state = CS_UNAUTHORIZED;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700543 t->key = adb_auth_nextkey(t->key);
544 if (t->key) {
545 send_auth_response(p->data, p->msg.data_length, t);
546 } else {
547 /* No more private keys to try, send the public key */
548 send_auth_publickey(t);
549 }
550 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
551 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
552 adb_auth_verified(t);
553 t->failed_auth_attempts = 0;
554 } else {
555 if (t->failed_auth_attempts++ > 10)
556 adb_sleep_ms(1000);
557 send_auth_request(t);
558 }
559 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
560 adb_auth_confirm_key(p->data, p->msg.data_length, t);
561 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562 break;
563
564 case A_OPEN: /* OPEN(local-id, 0, "destination") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100565 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566 char *name = (char*) p->data;
567 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
568 s = create_local_service_socket(name);
569 if(s == 0) {
570 send_close(0, p->msg.arg0, t);
571 } else {
572 s->peer = create_remote_socket(p->msg.arg0, t);
573 s->peer->peer = s;
574 send_ready(s->id, s->peer->id, t);
575 s->ready(s);
576 }
577 }
578 break;
579
580 case A_OKAY: /* READY(local-id, remote-id, "") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100581 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
582 if((s = find_local_socket(p->msg.arg1, 0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800583 if(s->peer == 0) {
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100584 /* On first READY message, create the connection. */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800585 s->peer = create_remote_socket(p->msg.arg0, t);
586 s->peer->peer = s;
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100587 s->ready(s);
588 } else if (s->peer->id == p->msg.arg0) {
589 /* Other READY messages must use the same local-id */
590 s->ready(s);
591 } else {
592 D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s\n",
593 p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800594 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 }
596 }
597 break;
598
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100599 case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
600 if (t->online && p->msg.arg1 != 0) {
601 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
602 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
603 * a failed OPEN only. However, due to a bug in previous ADB
604 * versions, CLOSE(0, remote-id, "") was also used for normal
605 * CLOSE() operations.
606 *
607 * This is bad because it means a compromised adbd could
608 * send packets to close connections between the host and
609 * other devices. To avoid this, only allow this if the local
610 * socket has a peer on the same transport.
611 */
612 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
613 D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s\n",
614 p->msg.arg1, t->serial, s->peer->transport->serial);
615 } else {
616 s->close(s);
617 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800618 }
619 }
620 break;
621
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100622 case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
623 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
624 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800625 unsigned rid = p->msg.arg0;
626 p->len = p->msg.data_length;
627
628 if(s->enqueue(s, p) == 0) {
629 D("Enqueue the socket\n");
630 send_ready(s->id, rid, t);
631 }
632 return;
633 }
634 }
635 break;
636
637 default:
638 printf("handle_packet: what is %08x?!\n", p->msg.command);
639 }
640
641 put_apacket(p);
642}
643
644alistener listener_list = {
645 .next = &listener_list,
646 .prev = &listener_list,
647};
648
649static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
650{
651 asocket *s;
652
653 if(ev & FDE_READ) {
654 struct sockaddr addr;
655 socklen_t alen;
656 int fd;
657
658 alen = sizeof(addr);
659 fd = adb_socket_accept(_fd, &addr, &alen);
660 if(fd < 0) return;
661
662 adb_socket_setbufsize(fd, CHUNK_SIZE);
663
664 s = create_local_socket(fd);
665 if(s) {
666 connect_to_smartsocket(s);
667 return;
668 }
669
670 adb_close(fd);
671 }
672}
673
674static void listener_event_func(int _fd, unsigned ev, void *_l)
675{
676 alistener *l = _l;
677 asocket *s;
678
679 if(ev & FDE_READ) {
680 struct sockaddr addr;
681 socklen_t alen;
682 int fd;
683
684 alen = sizeof(addr);
685 fd = adb_socket_accept(_fd, &addr, &alen);
686 if(fd < 0) return;
687
688 s = create_local_socket(fd);
689 if(s) {
690 s->transport = l->transport;
691 connect_to_remote(s, l->connect_to);
692 return;
693 }
694
695 adb_close(fd);
696 }
697}
698
699static void free_listener(alistener* l)
700{
701 if (l->next) {
702 l->next->prev = l->prev;
703 l->prev->next = l->next;
704 l->next = l->prev = l;
705 }
706
707 // closes the corresponding fd
708 fdevent_remove(&l->fde);
709
710 if (l->local_name)
711 free((char*)l->local_name);
712
713 if (l->connect_to)
714 free((char*)l->connect_to);
715
716 if (l->transport) {
717 remove_transport_disconnect(l->transport, &l->disconnect);
718 }
719 free(l);
720}
721
722static void listener_disconnect(void* _l, atransport* t)
723{
724 alistener* l = _l;
725
726 free_listener(l);
727}
728
729int local_name_to_fd(const char *name)
730{
731 int port;
732
733 if(!strncmp("tcp:", name, 4)){
734 int ret;
735 port = atoi(name + 4);
Matt Gumbeld7b33082012-11-14 10:16:17 -0800736
737 if (gListenAll > 0) {
738 ret = socket_inaddr_any_server(port, SOCK_STREAM);
739 } else {
740 ret = socket_loopback_server(port, SOCK_STREAM);
741 }
742
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 return ret;
744 }
745#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
746 // It's non-sensical to support the "reserved" space on the adb host side
747 if(!strncmp(name, "local:", 6)) {
748 return socket_local_server(name + 6,
749 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
750 } else if(!strncmp(name, "localabstract:", 14)) {
751 return socket_local_server(name + 14,
752 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
753 } else if(!strncmp(name, "localfilesystem:", 16)) {
754 return socket_local_server(name + 16,
755 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
756 }
757
758#endif
759 printf("unknown local portname '%s'\n", name);
760 return -1;
761}
762
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100763// Write a single line describing a listener to a user-provided buffer.
764// Appends a trailing zero, even in case of truncation, but the function
765// returns the full line length.
766// If |buffer| is NULL, does not write but returns required size.
767static int format_listener(alistener* l, char* buffer, size_t buffer_len) {
768 // Format is simply:
769 //
770 // <device-serial> " " <local-name> " " <remote-name> "\n"
771 //
772 int local_len = strlen(l->local_name);
773 int connect_len = strlen(l->connect_to);
774 int serial_len = strlen(l->transport->serial);
775
776 if (buffer != NULL) {
777 snprintf(buffer, buffer_len, "%s %s %s\n",
778 l->transport->serial, l->local_name, l->connect_to);
779 }
780 // NOTE: snprintf() on Windows returns -1 in case of truncation, so
781 // return the computed line length instead.
782 return local_len + connect_len + serial_len + 3;
783}
784
785// Write the list of current listeners (network redirections) into a
786// user-provided buffer. Appends a trailing zero, even in case of
787// trunctaion, but return the full size in bytes.
788// If |buffer| is NULL, does not write but returns required size.
789static int format_listeners(char* buf, size_t buflen)
790{
791 alistener* l;
792 int result = 0;
793 for (l = listener_list.next; l != &listener_list; l = l->next) {
794 // Ignore special listeners like those for *smartsocket*
795 if (l->connect_to[0] == '*')
796 continue;
797 int len = format_listener(l, buf, buflen);
798 // Ensure there is space for the trailing zero.
799 result += len;
800 if (buf != NULL) {
801 buf += len;
802 buflen -= len;
803 if (buflen <= 0)
804 break;
805 }
806 }
807 return result;
808}
809
810static int remove_listener(const char *local_name, atransport* transport)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800811{
812 alistener *l;
813
814 for (l = listener_list.next; l != &listener_list; l = l->next) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100815 if (!strcmp(local_name, l->local_name)) {
816 listener_disconnect(l, l->transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800817 return 0;
818 }
819 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 return -1;
821}
822
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100823static void remove_all_listeners(void)
824{
825 alistener *l, *l_next;
826 for (l = listener_list.next; l != &listener_list; l = l_next) {
827 l_next = l->next;
828 // Never remove smart sockets.
829 if (l->connect_to[0] == '*')
830 continue;
831 listener_disconnect(l, l->transport);
832 }
833}
834
835// error/status codes for install_listener.
836typedef enum {
837 INSTALL_STATUS_OK = 0,
838 INSTALL_STATUS_INTERNAL_ERROR = -1,
839 INSTALL_STATUS_CANNOT_BIND = -2,
840 INSTALL_STATUS_CANNOT_REBIND = -3,
841} install_status_t;
842
843static install_status_t install_listener(const char *local_name,
844 const char *connect_to,
845 atransport* transport,
846 int no_rebind)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847{
848 alistener *l;
849
850 //printf("install_listener('%s','%s')\n", local_name, connect_to);
851
852 for(l = listener_list.next; l != &listener_list; l = l->next){
853 if(strcmp(local_name, l->local_name) == 0) {
854 char *cto;
855
856 /* can't repurpose a smartsocket */
857 if(l->connect_to[0] == '*') {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100858 return INSTALL_STATUS_INTERNAL_ERROR;
859 }
860
861 /* can't repurpose a listener if 'no_rebind' is true */
862 if (no_rebind) {
863 return INSTALL_STATUS_CANNOT_REBIND;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800864 }
865
866 cto = strdup(connect_to);
867 if(cto == 0) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100868 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800869 }
870
871 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
872 free((void*) l->connect_to);
873 l->connect_to = cto;
874 if (l->transport != transport) {
875 remove_transport_disconnect(l->transport, &l->disconnect);
876 l->transport = transport;
877 add_transport_disconnect(l->transport, &l->disconnect);
878 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100879 return INSTALL_STATUS_OK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800880 }
881 }
882
883 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
884 if((l->local_name = strdup(local_name)) == 0) goto nomem;
885 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
886
887
888 l->fd = local_name_to_fd(local_name);
889 if(l->fd < 0) {
890 free((void*) l->local_name);
891 free((void*) l->connect_to);
892 free(l);
893 printf("cannot bind '%s'\n", local_name);
894 return -2;
895 }
896
897 close_on_exec(l->fd);
898 if(!strcmp(l->connect_to, "*smartsocket*")) {
899 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
900 } else {
901 fdevent_install(&l->fde, l->fd, listener_event_func, l);
902 }
903 fdevent_set(&l->fde, FDE_READ);
904
905 l->next = &listener_list;
906 l->prev = listener_list.prev;
907 l->next->prev = l;
908 l->prev->next = l;
909 l->transport = transport;
910
911 if (transport) {
912 l->disconnect.opaque = l;
913 l->disconnect.func = listener_disconnect;
914 add_transport_disconnect(transport, &l->disconnect);
915 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100916 return INSTALL_STATUS_OK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800917
918nomem:
919 fatal("cannot allocate listener");
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100920 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800921}
922
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800923#ifdef HAVE_WIN32_PROC
924static BOOL WINAPI ctrlc_handler(DWORD type)
925{
926 exit(STATUS_CONTROL_C_EXIT);
927 return TRUE;
928}
929#endif
930
931static void adb_cleanup(void)
932{
933 usb_cleanup();
934}
935
936void start_logging(void)
937{
938#ifdef HAVE_WIN32_PROC
939 char temp[ MAX_PATH ];
940 FILE* fnul;
941 FILE* flog;
942
943 GetTempPath( sizeof(temp) - 8, temp );
944 strcat( temp, "adb.log" );
945
946 /* Win32 specific redirections */
947 fnul = fopen( "NUL", "rt" );
948 if (fnul != NULL)
949 stdin[0] = fnul[0];
950
951 flog = fopen( temp, "at" );
952 if (flog == NULL)
953 flog = fnul;
954
955 setvbuf( flog, NULL, _IONBF, 0 );
956
957 stdout[0] = flog[0];
958 stderr[0] = flog[0];
959 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
960#else
961 int fd;
962
963 fd = unix_open("/dev/null", O_RDONLY);
964 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700965 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966
967 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
968 if(fd < 0) {
969 fd = unix_open("/dev/null", O_WRONLY);
970 }
971 dup2(fd, 1);
972 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700973 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800974 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
975#endif
976}
977
978#if !ADB_HOST
979void start_device_log(void)
980{
981 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400982 char path[PATH_MAX];
983 struct tm now;
984 time_t t;
985 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800986
Mike Lockwood1f546e62009-05-25 18:17:55 -0400987 // read the trace mask from persistent property persist.adb.trace_mask
988 // give up if the property is not set or cannot be parsed
989 property_get("persist.adb.trace_mask", value, "");
990 if (sscanf(value, "%x", &adb_trace_mask) != 1)
991 return;
992
993 adb_mkdir("/data/adb", 0775);
994 tzset();
995 time(&t);
996 localtime_r(&t, &now);
997 strftime(path, sizeof(path),
998 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
999 &now);
1000 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001001 if (fd < 0)
1002 return;
1003
1004 // redirect stdout and stderr to the log file
1005 dup2(fd, 1);
1006 dup2(fd, 2);
1007 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -08001008 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009
1010 fd = unix_open("/dev/null", O_RDONLY);
1011 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -08001012 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013}
1014#endif
1015
1016#if ADB_HOST
JP Abgrall571c1362012-12-06 18:18:12 -08001017
1018#ifdef WORKAROUND_BUG6558362
1019#include <sched.h>
1020#define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
1021void adb_set_affinity(void)
1022{
1023 cpu_set_t cpu_set;
1024 const char* cpunum_str = getenv(AFFINITY_ENVVAR);
1025 char* strtol_res;
1026 int cpu_num;
1027
1028 if (!cpunum_str || !*cpunum_str)
1029 return;
1030 cpu_num = strtol(cpunum_str, &strtol_res, 0);
1031 if (*strtol_res != '\0')
1032 fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
1033
1034 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1035 D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1036 CPU_ZERO(&cpu_set);
1037 CPU_SET(cpu_num, &cpu_set);
1038 sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
1039 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1040 D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1041}
1042#endif
1043
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001044int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001045{
1046#ifdef HAVE_WIN32_PROC
1047 /* we need to start the server in the background */
1048 /* we create a PIPE that will be used to wait for the server's "OK" */
1049 /* message since the pipe handles must be inheritable, we use a */
1050 /* security attribute */
1051 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +00001052 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001053 SECURITY_ATTRIBUTES sa;
1054 STARTUPINFO startup;
1055 PROCESS_INFORMATION pinfo;
1056 char program_path[ MAX_PATH ];
1057 int ret;
1058
1059 sa.nLength = sizeof(sa);
1060 sa.lpSecurityDescriptor = NULL;
1061 sa.bInheritHandle = TRUE;
1062
1063 /* create pipe, and ensure its read handle isn't inheritable */
1064 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1065 if (!ret) {
1066 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1067 return -1;
1068 }
1069
1070 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1071
Ray Donnelly267aa8b2012-11-29 01:18:50 +00001072 /* Some programs want to launch an adb command and collect its output by
1073 * calling CreateProcess with inheritable stdout/stderr handles, then
1074 * using read() to get its output. When this happens, the stdout/stderr
1075 * handles passed to the adb client process will also be inheritable.
1076 * When starting the adb server here, care must be taken to reset them
1077 * to non-inheritable.
1078 * Otherwise, something bad happens: even if the adb command completes,
1079 * the calling process is stuck while read()-ing from the stdout/stderr
1080 * descriptors, because they're connected to corresponding handles in the
1081 * adb server process (even if the latter never uses/writes to them).
1082 */
1083 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
1084 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
1085 if (stdout_handle != INVALID_HANDLE_VALUE) {
1086 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
1087 }
1088 if (stderr_handle != INVALID_HANDLE_VALUE) {
1089 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
1090 }
1091
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001092 ZeroMemory( &startup, sizeof(startup) );
1093 startup.cb = sizeof(startup);
1094 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1095 startup.hStdOutput = pipe_write;
1096 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1097 startup.dwFlags = STARTF_USESTDHANDLES;
1098
1099 ZeroMemory( &pinfo, sizeof(pinfo) );
1100
1101 /* get path of current program */
1102 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1103
1104 ret = CreateProcess(
1105 program_path, /* program path */
1106 "adb fork-server server",
1107 /* the fork-server argument will set the
1108 debug = 2 in the child */
1109 NULL, /* process handle is not inheritable */
1110 NULL, /* thread handle is not inheritable */
1111 TRUE, /* yes, inherit some handles */
1112 DETACHED_PROCESS, /* the new process doesn't have a console */
1113 NULL, /* use parent's environment block */
1114 NULL, /* use parent's starting directory */
1115 &startup, /* startup info, i.e. std handles */
1116 &pinfo );
1117
1118 CloseHandle( pipe_write );
1119
1120 if (!ret) {
1121 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1122 CloseHandle( pipe_read );
1123 return -1;
1124 }
1125
1126 CloseHandle( pinfo.hProcess );
1127 CloseHandle( pinfo.hThread );
1128
1129 /* wait for the "OK\n" message */
1130 {
1131 char temp[3];
1132 DWORD count;
1133
1134 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1135 CloseHandle( pipe_read );
1136 if ( !ret ) {
1137 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1138 return -1;
1139 }
1140 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1141 fprintf(stderr, "ADB server didn't ACK\n" );
1142 return -1;
1143 }
1144 }
1145#elif defined(HAVE_FORKEXEC)
1146 char path[PATH_MAX];
1147 int fd[2];
1148
1149 // set up a pipe so the child can tell us when it is ready.
1150 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1151 if (pipe(fd)) {
1152 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1153 return -1;
1154 }
Alexey Tarasov31664102009-10-22 02:55:00 +11001155 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001156 pid_t pid = fork();
1157 if(pid < 0) return -1;
1158
1159 if (pid == 0) {
1160 // child side of the fork
1161
1162 // redirect stderr to the pipe
1163 // we use stderr instead of stdout due to stdout's buffering behavior.
1164 adb_close(fd[0]);
1165 dup2(fd[1], STDERR_FILENO);
1166 adb_close(fd[1]);
1167
Matt Gumbeld7b33082012-11-14 10:16:17 -08001168 char str_port[30];
1169 snprintf(str_port, sizeof(str_port), "%d", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001170 // child process
Matt Gumbeld7b33082012-11-14 10:16:17 -08001171 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001172 // this should not return
1173 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1174 } else {
1175 // parent side of the fork
1176
1177 char temp[3];
1178
1179 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1180 // wait for the "OK\n" message
1181 adb_close(fd[1]);
1182 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -07001183 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001184 adb_close(fd[0]);
1185 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -07001186 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187 return -1;
1188 }
1189 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1190 fprintf(stderr, "ADB server didn't ACK\n" );
1191 return -1;
1192 }
1193
1194 setsid();
1195 }
1196#else
1197#error "cannot implement background server start on this platform"
1198#endif
1199 return 0;
1200}
1201#endif
1202
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001203/* Constructs a local name of form tcp:port.
1204 * target_str points to the target string, it's content will be overwritten.
1205 * target_size is the capacity of the target string.
1206 * server_port is the port number to use for the local name.
1207 */
1208void build_local_name(char* target_str, size_t target_size, int server_port)
1209{
1210 snprintf(target_str, target_size, "tcp:%d", server_port);
1211}
1212
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001213#if !ADB_HOST
Nick Kralevich080427e2013-02-15 14:39:15 -08001214
1215static void drop_capabilities_bounding_set_if_needed() {
1216#ifdef ALLOW_ADBD_ROOT
1217 char value[PROPERTY_VALUE_MAX];
1218 property_get("ro.debuggable", value, "");
1219 if (strcmp(value, "1") == 0) {
1220 return;
1221 }
1222#endif
1223 int i;
1224 for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
Nick Kralevichca8e66a2013-04-18 12:20:02 -07001225 if (i == CAP_SETUID || i == CAP_SETGID) {
Nick Kralevich080427e2013-02-15 14:39:15 -08001226 // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
1227 continue;
1228 }
1229 int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
1230
1231 // Some kernels don't have file capabilities compiled in, and
1232 // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
1233 // die when we see such misconfigured kernels.
1234 if ((err < 0) && (errno != EINVAL)) {
1235 exit(1);
1236 }
1237 }
1238}
1239
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001240static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -08001241#ifndef ALLOW_ADBD_ROOT
1242 return 1;
1243#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001244 int secure = 0;
1245 char value[PROPERTY_VALUE_MAX];
1246
1247 /* run adbd in secure mode if ro.secure is set and
1248 ** we are not in the emulator
1249 */
1250 property_get("ro.kernel.qemu", value, "");
1251 if (strcmp(value, "1") != 0) {
1252 property_get("ro.secure", value, "1");
1253 if (strcmp(value, "1") == 0) {
1254 // don't run as root if ro.secure is set...
1255 secure = 1;
1256
1257 // ... except we allow running as root in userdebug builds if the
1258 // service.adb.root property has been set by the "adb root" command
1259 property_get("ro.debuggable", value, "");
1260 if (strcmp(value, "1") == 0) {
1261 property_get("service.adb.root", value, "");
1262 if (strcmp(value, "1") == 0) {
1263 secure = 0;
1264 }
1265 }
1266 }
1267 }
1268 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -08001269#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001270}
1271#endif /* !ADB_HOST */
1272
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001273int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001274{
1275#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -07001276 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001277 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -07001278
1279 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001280#endif
1281
1282 atexit(adb_cleanup);
1283#ifdef HAVE_WIN32_PROC
1284 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1285#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -07001286 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001287 signal(SIGPIPE, SIG_IGN);
1288#endif
1289
1290 init_transport_registration();
1291
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001292#if ADB_HOST
1293 HOST = 1;
JP Abgrall571c1362012-12-06 18:18:12 -08001294
1295#ifdef WORKAROUND_BUG6558362
1296 if(is_daemon) adb_set_affinity();
1297#endif
Xavier Ducroheta09fbd12009-05-20 17:33:53 -07001298 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001299 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001300 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001301 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001302
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001303 char local_name[30];
1304 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001305 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001306 exit(1);
1307 }
1308#else
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001309 property_get("ro.adb.secure", value, "0");
1310 auth_enabled = !strcmp(value, "1");
1311 if (auth_enabled)
1312 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001313
Jeff Sharkeyd6d42862012-09-06 13:05:40 -07001314 // Our external storage path may be different than apps, since
1315 // we aren't able to bind mount after dropping root.
1316 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1317 if (NULL != adb_external_storage) {
1318 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1319 } else {
1320 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1321 " unchanged.\n");
1322 }
1323
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001324 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001325 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001326 if (should_drop_privileges()) {
Nick Kralevich080427e2013-02-15 14:39:15 -08001327 drop_capabilities_bounding_set_if_needed();
1328
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001329 /* add extra groups:
1330 ** AID_ADB to access the USB driver
1331 ** AID_LOG to read system logs (adb logcat)
1332 ** AID_INPUT to diagnose input issues (getevent)
1333 ** AID_INET to diagnose network issues (netcfg, ping)
1334 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -07001335 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001336 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -04001337 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -05001338 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -08001339 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001340 */
The Android Open Source Project20155492009-03-11 12:12:01 -07001341 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001342 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1343 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -07001344 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1345 exit(1);
1346 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001347
1348 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -07001349 if (setgid(AID_SHELL) != 0) {
1350 exit(1);
1351 }
1352 if (setuid(AID_SHELL) != 0) {
1353 exit(1);
1354 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001355
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001356 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001357 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001358 char local_name[30];
1359 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001360 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001361 exit(1);
1362 }
1363 }
1364
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001365 int usb = 0;
1366 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001367 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001368 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001369 usb = 1;
1370 }
1371
1372 // If one of these properties is set, also listen on that port
1373 // If one of the properties isn't set and we couldn't listen on usb,
1374 // listen on the default port.
1375 property_get("service.adb.tcp.port", value, "");
1376 if (!value[0]) {
1377 property_get("persist.adb.tcp.port", value, "");
1378 }
1379 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1380 printf("using port=%d\n", port);
1381 // listen on TCP port specified by service.adb.tcp.port property
1382 local_init(port);
1383 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001384 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001385 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001386 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001387
JP Abgrall408fa572011-03-16 15:57:42 -07001388 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001389 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001390 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001391#endif
1392
1393 if (is_daemon)
1394 {
1395 // inform our parent that we are up and running.
1396#ifdef HAVE_WIN32_PROC
1397 DWORD count;
1398 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1399#elif defined(HAVE_FORKEXEC)
1400 fprintf(stderr, "OK\n");
1401#endif
1402 start_logging();
1403 }
JP Abgrall408fa572011-03-16 15:57:42 -07001404 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001405
1406 fdevent_loop();
1407
1408 usb_cleanup();
1409
1410 return 0;
1411}
1412
1413int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1414{
1415 atransport *transport = NULL;
1416 char buf[4096];
1417
1418 if(!strcmp(service, "kill")) {
1419 fprintf(stderr,"adb server killed by remote request\n");
1420 fflush(stdout);
1421 adb_write(reply_fd, "OKAY", 4);
1422 usb_cleanup();
1423 exit(0);
1424 }
1425
1426#if ADB_HOST
1427 // "transport:" is used for switching transport with a specified serial number
1428 // "transport-usb:" is used for switching transport to the only USB transport
1429 // "transport-local:" is used for switching transport to the only local transport
1430 // "transport-any:" is used for switching transport to the only transport
1431 if (!strncmp(service, "transport", strlen("transport"))) {
1432 char* error_string = "unknown failure";
1433 transport_type type = kTransportAny;
1434
1435 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1436 type = kTransportUsb;
1437 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1438 type = kTransportLocal;
1439 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1440 type = kTransportAny;
1441 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1442 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001443 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001444 }
1445
1446 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1447
1448 if (transport) {
1449 s->transport = transport;
1450 adb_write(reply_fd, "OKAY", 4);
1451 } else {
1452 sendfailmsg(reply_fd, error_string);
1453 }
1454 return 1;
1455 }
1456
1457 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001458 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001459 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001460 int use_long = !strcmp(service+7, "-l");
1461 if (use_long || service[7] == 0) {
1462 memset(buf, 0, sizeof(buf));
1463 memset(buffer, 0, sizeof(buffer));
1464 D("Getting device list \n");
1465 list_transports(buffer, sizeof(buffer), use_long);
1466 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1467 D("Wrote device list \n");
1468 writex(reply_fd, buf, strlen(buf));
1469 return 0;
1470 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001471 }
1472
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001473 // remove TCP transport
1474 if (!strncmp(service, "disconnect:", 11)) {
1475 char buffer[4096];
1476 memset(buffer, 0, sizeof(buffer));
1477 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001478 if (serial[0] == 0) {
1479 // disconnect from all TCP devices
1480 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001481 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001482 char hostbuf[100];
1483 // assume port 5555 if no port is specified
1484 if (!strchr(serial, ':')) {
1485 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1486 serial = hostbuf;
1487 }
1488 atransport *t = find_transport(serial);
1489
1490 if (t) {
1491 unregister_transport(t);
1492 } else {
1493 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1494 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001495 }
1496
1497 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001498 writex(reply_fd, buf, strlen(buf));
1499 return 0;
1500 }
1501
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001502 // returns our value for ADB_SERVER_VERSION
1503 if (!strcmp(service, "version")) {
1504 char version[12];
1505 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1506 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1507 writex(reply_fd, buf, strlen(buf));
1508 return 0;
1509 }
1510
1511 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1512 char *out = "unknown";
1513 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1514 if (transport && transport->serial) {
1515 out = transport->serial;
1516 }
1517 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1518 writex(reply_fd, buf, strlen(buf));
1519 return 0;
1520 }
Scott Andersone109d262012-04-20 11:21:14 -07001521 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1522 char *out = "unknown";
1523 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1524 if (transport && transport->devpath) {
1525 out = transport->devpath;
1526 }
1527 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1528 writex(reply_fd, buf, strlen(buf));
1529 return 0;
1530 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001531 // indicates a new emulator instance has started
1532 if (!strncmp(service,"emulator:",9)) {
1533 int port = atoi(service+9);
1534 local_connect(port);
1535 /* we don't even need to send a reply */
1536 return 0;
1537 }
1538#endif // ADB_HOST
1539
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001540 if(!strcmp(service,"list-forward")) {
1541 // Create the list of forward redirections.
1542 char header[9];
1543 int buffer_size = format_listeners(NULL, 0);
1544 // Add one byte for the trailing zero.
1545 char* buffer = malloc(buffer_size+1);
1546 (void) format_listeners(buffer, buffer_size+1);
1547 snprintf(header, sizeof header, "OKAY%04x", buffer_size);
1548 writex(reply_fd, header, 8);
1549 writex(reply_fd, buffer, buffer_size);
1550 free(buffer);
1551 return 0;
1552 }
1553
1554 if (!strcmp(service,"killforward-all")) {
1555 remove_all_listeners();
1556 adb_write(reply_fd, "OKAYOKAY", 8);
1557 return 0;
1558 }
1559
1560 if(!strncmp(service,"forward:",8) ||
1561 !strncmp(service,"killforward:",12)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001562 char *local, *remote, *err;
1563 int r;
1564 atransport *transport;
1565
1566 int createForward = strncmp(service,"kill",4);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001567 int no_rebind = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001568
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001569 local = strchr(service, ':') + 1;
1570
1571 // Handle forward:norebind:<local>... here
1572 if (createForward && !strncmp(local, "norebind:", 9)) {
1573 no_rebind = 1;
1574 local = strchr(local, ':') + 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001575 }
1576
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001577 remote = strchr(local,';');
1578
1579 if (createForward) {
1580 // Check forward: parameter format: '<local>;<remote>'
1581 if(remote == 0) {
1582 sendfailmsg(reply_fd, "malformed forward spec");
1583 return 0;
1584 }
1585
1586 *remote++ = 0;
1587 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1588 sendfailmsg(reply_fd, "malformed forward spec");
1589 return 0;
1590 }
1591 } else {
1592 // Check killforward: parameter format: '<local>'
1593 if (local[0] == 0) {
1594 sendfailmsg(reply_fd, "malformed forward spec");
1595 return 0;
1596 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001597 }
1598
1599 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1600 if (!transport) {
1601 sendfailmsg(reply_fd, err);
1602 return 0;
1603 }
1604
1605 if (createForward) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001606 r = install_listener(local, remote, transport, no_rebind);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001607 } else {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001608 r = remove_listener(local, transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001609 }
1610 if(r == 0) {
1611 /* 1st OKAY is connect, 2nd OKAY is status */
1612 writex(reply_fd, "OKAYOKAY", 8);
1613 return 0;
1614 }
1615
1616 if (createForward) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001617 const char* message;
1618 switch (r) {
1619 case INSTALL_STATUS_CANNOT_BIND:
1620 message = "cannot bind to socket";
1621 break;
1622 case INSTALL_STATUS_CANNOT_REBIND:
1623 message = "cannot rebind existing socket";
1624 break;
1625 default:
1626 message = "internal error";
1627 }
1628 sendfailmsg(reply_fd, message);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001629 } else {
1630 sendfailmsg(reply_fd, "cannot remove listener");
1631 }
1632 return 0;
1633 }
1634
1635 if(!strncmp(service,"get-state",strlen("get-state"))) {
1636 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1637 char *state = connection_state_name(transport);
1638 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1639 writex(reply_fd, buf, strlen(buf));
1640 return 0;
1641 }
1642 return -1;
1643}
1644
1645#if !ADB_HOST
1646int recovery_mode = 0;
1647#endif
1648
1649int main(int argc, char **argv)
1650{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001651#if ADB_HOST
1652 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001653 adb_trace_init();
1654 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001655 return adb_commandline(argc - 1, argv + 1);
1656#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001657 /* If adbd runs inside the emulator this will enable adb tracing via
1658 * adb-debug qemud service in the emulator. */
1659 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001660 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1661 adb_device_banner = "recovery";
1662 recovery_mode = 1;
1663 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001664
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001665 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001666 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001667 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001668#endif
1669}