blob: b7359d4f870beabf9755f6ea12393e6d6c258f33 [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>
Nick Kraleviche2864bf2013-02-28 14:12:58 -080038#include <sys/capability.h>
Mike Lockwood5f4b0512009-08-04 20:37:51 -040039#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;
Matt Gumbeld7b33082012-11-14 10:16:17 -080050int gListenAll = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080051
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070052static int auth_enabled = 0;
53
Scott Andersone82c2db2012-05-25 14:10:02 -070054#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080055static const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070056#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
58void fatal(const char *fmt, ...)
59{
60 va_list ap;
61 va_start(ap, fmt);
62 fprintf(stderr, "error: ");
63 vfprintf(stderr, fmt, ap);
64 fprintf(stderr, "\n");
65 va_end(ap);
66 exit(-1);
67}
68
69void fatal_errno(const char *fmt, ...)
70{
71 va_list ap;
72 va_start(ap, fmt);
73 fprintf(stderr, "error: %s: ", strerror(errno));
74 vfprintf(stderr, fmt, ap);
75 fprintf(stderr, "\n");
76 va_end(ap);
77 exit(-1);
78}
79
80int adb_trace_mask;
81
82/* read a comma/space/colum/semi-column separated list of tags
83 * from the ADB_TRACE environment variable and build the trace
84 * mask from it. note that '1' and 'all' are special cases to
85 * enable all tracing
86 */
87void adb_trace_init(void)
88{
89 const char* p = getenv("ADB_TRACE");
90 const char* q;
91
92 static const struct {
93 const char* tag;
94 int flag;
95 } tags[] = {
96 { "1", 0 },
97 { "all", 0 },
98 { "adb", TRACE_ADB },
99 { "sockets", TRACE_SOCKETS },
100 { "packets", TRACE_PACKETS },
101 { "rwx", TRACE_RWX },
102 { "usb", TRACE_USB },
103 { "sync", TRACE_SYNC },
104 { "sysdeps", TRACE_SYSDEPS },
105 { "transport", TRACE_TRANSPORT },
106 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700107 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700108 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800109 { NULL, 0 }
110 };
111
112 if (p == NULL)
113 return;
114
115 /* use a comma/column/semi-colum/space separated list */
116 while (*p) {
117 int len, tagn;
118
119 q = strpbrk(p, " ,:;");
120 if (q == NULL) {
121 q = p + strlen(p);
122 }
123 len = q - p;
124
125 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
126 {
127 int taglen = strlen(tags[tagn].tag);
128
129 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
130 {
131 int flag = tags[tagn].flag;
132 if (flag == 0) {
133 adb_trace_mask = ~0;
134 return;
135 }
136 adb_trace_mask |= (1 << flag);
137 break;
138 }
139 }
140 p = q;
141 if (*p)
142 p++;
143 }
144}
145
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -0800146#if !ADB_HOST
147/*
148 * Implements ADB tracing inside the emulator.
149 */
150
151#include <stdarg.h>
152
153/*
154 * Redefine open and write for qemu_pipe.h that contains inlined references
155 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
156 */
157
158#undef open
159#undef write
160#define open adb_open
161#define write adb_write
162#include <hardware/qemu_pipe.h>
163#undef open
164#undef write
165#define open ___xxx_open
166#define write ___xxx_write
167
168/* A handle to adb-debug qemud service in the emulator. */
169int adb_debug_qemu = -1;
170
171/* Initializes connection with the adb-debug qemud service in the emulator. */
172static int adb_qemu_trace_init(void)
173{
174 char con_name[32];
175
176 if (adb_debug_qemu >= 0) {
177 return 0;
178 }
179
180 /* adb debugging QEMUD service connection request. */
181 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
182 adb_debug_qemu = qemu_pipe_open(con_name);
183 return (adb_debug_qemu >= 0) ? 0 : -1;
184}
185
186void adb_qemu_trace(const char* fmt, ...)
187{
188 va_list args;
189 va_start(args, fmt);
190 char msg[1024];
191
192 if (adb_debug_qemu >= 0) {
193 vsnprintf(msg, sizeof(msg), fmt, args);
194 adb_write(adb_debug_qemu, msg, strlen(msg));
195 }
196}
197#endif /* !ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800198
199apacket *get_apacket(void)
200{
201 apacket *p = malloc(sizeof(apacket));
202 if(p == 0) fatal("failed to allocate an apacket");
203 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
204 return p;
205}
206
207void put_apacket(apacket *p)
208{
209 free(p);
210}
211
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700212void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800213{
214 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700215 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800216}
217
218void handle_offline(atransport *t)
219{
220 D("adb: offline\n");
221 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700222 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800224}
225
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700226#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800227#define DUMPMAX 32
228void print_packet(const char *label, apacket *p)
229{
230 char *tag;
231 char *x;
232 unsigned count;
233
234 switch(p->msg.command){
235 case A_SYNC: tag = "SYNC"; break;
236 case A_CNXN: tag = "CNXN" ; break;
237 case A_OPEN: tag = "OPEN"; break;
238 case A_OKAY: tag = "OKAY"; break;
239 case A_CLSE: tag = "CLSE"; break;
240 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700241 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242 default: tag = "????"; break;
243 }
244
245 fprintf(stderr, "%s: %s %08x %08x %04x \"",
246 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
247 count = p->msg.data_length;
248 x = (char*) p->data;
249 if(count > DUMPMAX) {
250 count = DUMPMAX;
251 tag = "\n";
252 } else {
253 tag = "\"\n";
254 }
255 while(count-- > 0){
256 if((*x >= ' ') && (*x < 127)) {
257 fputc(*x, stderr);
258 } else {
259 fputc('.', stderr);
260 }
261 x++;
262 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700263 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264}
265#endif
266
267static void send_ready(unsigned local, unsigned remote, atransport *t)
268{
269 D("Calling send_ready \n");
270 apacket *p = get_apacket();
271 p->msg.command = A_OKAY;
272 p->msg.arg0 = local;
273 p->msg.arg1 = remote;
274 send_packet(p, t);
275}
276
277static void send_close(unsigned local, unsigned remote, atransport *t)
278{
279 D("Calling send_close \n");
280 apacket *p = get_apacket();
281 p->msg.command = A_CLSE;
282 p->msg.arg0 = local;
283 p->msg.arg1 = remote;
284 send_packet(p, t);
285}
286
Scott Andersone82c2db2012-05-25 14:10:02 -0700287static size_t fill_connect_data(char *buf, size_t bufsize)
288{
289#if ADB_HOST
290 return snprintf(buf, bufsize, "host::") + 1;
291#else
292 static const char *cnxn_props[] = {
293 "ro.product.name",
294 "ro.product.model",
295 "ro.product.device",
296 };
297 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
298 int i;
299 size_t remaining = bufsize;
300 size_t len;
301
302 len = snprintf(buf, remaining, "%s::", adb_device_banner);
303 remaining -= len;
304 buf += len;
305 for (i = 0; i < num_cnxn_props; i++) {
306 char value[PROPERTY_VALUE_MAX];
307 property_get(cnxn_props[i], value, "");
308 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
309 remaining -= len;
310 buf += len;
311 }
312
313 return bufsize - remaining + 1;
314#endif
315}
316
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317static void send_connect(atransport *t)
318{
319 D("Calling send_connect \n");
320 apacket *cp = get_apacket();
321 cp->msg.command = A_CNXN;
322 cp->msg.arg0 = A_VERSION;
323 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700324 cp->msg.data_length = fill_connect_data((char *)cp->data,
325 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800326 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700327}
328
Benoit Goby045a4a92013-01-15 19:59:14 -0800329void send_auth_request(atransport *t)
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700330{
331 D("Calling send_auth_request\n");
332 apacket *p;
333 int ret;
334
335 ret = adb_auth_generate_token(t->token, sizeof(t->token));
336 if (ret != sizeof(t->token)) {
337 D("Error generating token ret=%d\n", ret);
338 return;
339 }
340
341 p = get_apacket();
342 memcpy(p->data, t->token, ret);
343 p->msg.command = A_AUTH;
344 p->msg.arg0 = ADB_AUTH_TOKEN;
345 p->msg.data_length = ret;
346 send_packet(p, t);
347}
348
349static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
350{
351 D("Calling send_auth_response\n");
352 apacket *p = get_apacket();
353 int ret;
354
355 ret = adb_auth_sign(t->key, token, token_size, p->data);
356 if (!ret) {
357 D("Error signing the token\n");
358 put_apacket(p);
359 return;
360 }
361
362 p->msg.command = A_AUTH;
363 p->msg.arg0 = ADB_AUTH_SIGNATURE;
364 p->msg.data_length = ret;
365 send_packet(p, t);
366}
367
368static void send_auth_publickey(atransport *t)
369{
370 D("Calling send_auth_publickey\n");
371 apacket *p = get_apacket();
372 int ret;
373
374 ret = adb_auth_get_userkey(p->data, sizeof(p->data));
375 if (!ret) {
376 D("Failed to get user public key\n");
377 put_apacket(p);
378 return;
379 }
380
381 p->msg.command = A_AUTH;
382 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
383 p->msg.data_length = ret;
384 send_packet(p, t);
385}
386
387void adb_auth_verified(atransport *t)
388{
389 handle_online(t);
390 send_connect(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391}
392
393static char *connection_state_name(atransport *t)
394{
395 if (t == NULL) {
396 return "unknown";
397 }
398
399 switch(t->connection_state) {
400 case CS_BOOTLOADER:
401 return "bootloader";
402 case CS_DEVICE:
403 return "device";
trevda5ad5392013-04-17 14:34:23 +0100404 case CS_RECOVERY:
405 return "recovery";
406 case CS_SIDELOAD:
407 return "sideload";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800408 case CS_OFFLINE:
409 return "offline";
Benoit Goby77e8e582013-01-15 12:36:47 -0800410 case CS_UNAUTHORIZED:
411 return "unauthorized";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412 default:
413 return "unknown";
414 }
415}
416
Scott Andersone82c2db2012-05-25 14:10:02 -0700417/* qual_overwrite is used to overwrite a qualifier string. dst is a
418 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700419 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700420 */
421static void qual_overwrite(char **dst, const char *src)
422{
423 if (!dst)
424 return;
425
426 free(*dst);
427 *dst = NULL;
428
429 if (!src || !*src)
430 return;
431
432 *dst = strdup(src);
433}
434
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800435void parse_banner(char *banner, atransport *t)
436{
Scott Andersone82c2db2012-05-25 14:10:02 -0700437 static const char *prop_seps = ";";
438 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700439 char *cp;
440 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441
442 D("parse_banner: %s\n", banner);
443 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700444 cp = strchr(type, ':');
445 if (cp) {
446 *cp++ = 0;
447 /* Nothing is done with second field. */
448 cp = strchr(cp, ':');
449 if (cp) {
450 char *save;
451 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700452 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700453 while (key) {
454 cp = strchr(key, key_val_sep);
455 if (cp) {
456 *cp++ = '\0';
457 if (!strcmp(key, "ro.product.name"))
458 qual_overwrite(&t->product, cp);
459 else if (!strcmp(key, "ro.product.model"))
460 qual_overwrite(&t->model, cp);
461 else if (!strcmp(key, "ro.product.device"))
462 qual_overwrite(&t->device, cp);
463 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700464 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700465 }
466 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800467 }
468
469 if(!strcmp(type, "bootloader")){
470 D("setting connection_state to CS_BOOTLOADER\n");
471 t->connection_state = CS_BOOTLOADER;
472 update_transports();
473 return;
474 }
475
476 if(!strcmp(type, "device")) {
477 D("setting connection_state to CS_DEVICE\n");
478 t->connection_state = CS_DEVICE;
479 update_transports();
480 return;
481 }
482
483 if(!strcmp(type, "recovery")) {
484 D("setting connection_state to CS_RECOVERY\n");
485 t->connection_state = CS_RECOVERY;
486 update_transports();
487 return;
488 }
489
Doug Zongker447f0612012-01-09 14:54:53 -0800490 if(!strcmp(type, "sideload")) {
491 D("setting connection_state to CS_SIDELOAD\n");
492 t->connection_state = CS_SIDELOAD;
493 update_transports();
494 return;
495 }
496
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497 t->connection_state = CS_HOST;
498}
499
500void handle_packet(apacket *p, atransport *t)
501{
502 asocket *s;
503
Viral Mehta899913f2010-06-16 18:41:28 +0530504 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
505 ((char*) (&(p->msg.command)))[1],
506 ((char*) (&(p->msg.command)))[2],
507 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508 print_packet("recv", p);
509
510 switch(p->msg.command){
511 case A_SYNC:
512 if(p->msg.arg0){
513 send_packet(p, t);
514 if(HOST) send_connect(t);
515 } else {
516 t->connection_state = CS_OFFLINE;
517 handle_offline(t);
518 send_packet(p, t);
519 }
520 return;
521
522 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
523 /* XXX verify version, etc */
524 if(t->connection_state != CS_OFFLINE) {
525 t->connection_state = CS_OFFLINE;
526 handle_offline(t);
527 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700528
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800529 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700530
531 if (HOST || !auth_enabled) {
532 handle_online(t);
533 if(!HOST) send_connect(t);
534 } else {
535 send_auth_request(t);
536 }
537 break;
538
539 case A_AUTH:
540 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
Benoit Goby77e8e582013-01-15 12:36:47 -0800541 t->connection_state = CS_UNAUTHORIZED;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700542 t->key = adb_auth_nextkey(t->key);
543 if (t->key) {
544 send_auth_response(p->data, p->msg.data_length, t);
545 } else {
546 /* No more private keys to try, send the public key */
547 send_auth_publickey(t);
548 }
549 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
550 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
551 adb_auth_verified(t);
552 t->failed_auth_attempts = 0;
553 } else {
554 if (t->failed_auth_attempts++ > 10)
555 adb_sleep_ms(1000);
556 send_auth_request(t);
557 }
558 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
559 adb_auth_confirm_key(p->data, p->msg.data_length, t);
560 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561 break;
562
563 case A_OPEN: /* OPEN(local-id, 0, "destination") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700564 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565 char *name = (char*) p->data;
566 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
567 s = create_local_service_socket(name);
568 if(s == 0) {
569 send_close(0, p->msg.arg0, t);
570 } else {
571 s->peer = create_remote_socket(p->msg.arg0, t);
572 s->peer->peer = s;
573 send_ready(s->id, s->peer->id, t);
574 s->ready(s);
575 }
576 }
577 break;
578
579 case A_OKAY: /* READY(local-id, remote-id, "") */
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700580 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800581 if((s = find_local_socket(p->msg.arg1))) {
582 if(s->peer == 0) {
583 s->peer = create_remote_socket(p->msg.arg0, t);
584 s->peer->peer = s;
585 }
586 s->ready(s);
587 }
588 }
589 break;
590
591 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
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 s->close(s);
595 }
596 }
597 break;
598
599 case A_WRTE:
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700600 if (t->online) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601 if((s = find_local_socket(p->msg.arg1))) {
602 unsigned rid = p->msg.arg0;
603 p->len = p->msg.data_length;
604
605 if(s->enqueue(s, p) == 0) {
606 D("Enqueue the socket\n");
607 send_ready(s->id, rid, t);
608 }
609 return;
610 }
611 }
612 break;
613
614 default:
615 printf("handle_packet: what is %08x?!\n", p->msg.command);
616 }
617
618 put_apacket(p);
619}
620
621alistener listener_list = {
622 .next = &listener_list,
623 .prev = &listener_list,
624};
625
626static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
627{
628 asocket *s;
629
630 if(ev & FDE_READ) {
631 struct sockaddr addr;
632 socklen_t alen;
633 int fd;
634
635 alen = sizeof(addr);
636 fd = adb_socket_accept(_fd, &addr, &alen);
637 if(fd < 0) return;
638
639 adb_socket_setbufsize(fd, CHUNK_SIZE);
640
641 s = create_local_socket(fd);
642 if(s) {
643 connect_to_smartsocket(s);
644 return;
645 }
646
647 adb_close(fd);
648 }
649}
650
651static void listener_event_func(int _fd, unsigned ev, void *_l)
652{
653 alistener *l = _l;
654 asocket *s;
655
656 if(ev & FDE_READ) {
657 struct sockaddr addr;
658 socklen_t alen;
659 int fd;
660
661 alen = sizeof(addr);
662 fd = adb_socket_accept(_fd, &addr, &alen);
663 if(fd < 0) return;
664
665 s = create_local_socket(fd);
666 if(s) {
667 s->transport = l->transport;
668 connect_to_remote(s, l->connect_to);
669 return;
670 }
671
672 adb_close(fd);
673 }
674}
675
676static void free_listener(alistener* l)
677{
678 if (l->next) {
679 l->next->prev = l->prev;
680 l->prev->next = l->next;
681 l->next = l->prev = l;
682 }
683
684 // closes the corresponding fd
685 fdevent_remove(&l->fde);
686
687 if (l->local_name)
688 free((char*)l->local_name);
689
690 if (l->connect_to)
691 free((char*)l->connect_to);
692
693 if (l->transport) {
694 remove_transport_disconnect(l->transport, &l->disconnect);
695 }
696 free(l);
697}
698
699static void listener_disconnect(void* _l, atransport* t)
700{
701 alistener* l = _l;
702
703 free_listener(l);
704}
705
706int local_name_to_fd(const char *name)
707{
708 int port;
709
710 if(!strncmp("tcp:", name, 4)){
711 int ret;
712 port = atoi(name + 4);
Matt Gumbeld7b33082012-11-14 10:16:17 -0800713
714 if (gListenAll > 0) {
715 ret = socket_inaddr_any_server(port, SOCK_STREAM);
716 } else {
717 ret = socket_loopback_server(port, SOCK_STREAM);
718 }
719
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720 return ret;
721 }
722#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
723 // It's non-sensical to support the "reserved" space on the adb host side
724 if(!strncmp(name, "local:", 6)) {
725 return socket_local_server(name + 6,
726 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
727 } else if(!strncmp(name, "localabstract:", 14)) {
728 return socket_local_server(name + 14,
729 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
730 } else if(!strncmp(name, "localfilesystem:", 16)) {
731 return socket_local_server(name + 16,
732 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
733 }
734
735#endif
736 printf("unknown local portname '%s'\n", name);
737 return -1;
738}
739
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100740// Write a single line describing a listener to a user-provided buffer.
741// Appends a trailing zero, even in case of truncation, but the function
742// returns the full line length.
743// If |buffer| is NULL, does not write but returns required size.
744static int format_listener(alistener* l, char* buffer, size_t buffer_len) {
745 // Format is simply:
746 //
747 // <device-serial> " " <local-name> " " <remote-name> "\n"
748 //
749 int local_len = strlen(l->local_name);
750 int connect_len = strlen(l->connect_to);
751 int serial_len = strlen(l->transport->serial);
752
753 if (buffer != NULL) {
754 snprintf(buffer, buffer_len, "%s %s %s\n",
755 l->transport->serial, l->local_name, l->connect_to);
756 }
757 // NOTE: snprintf() on Windows returns -1 in case of truncation, so
758 // return the computed line length instead.
759 return local_len + connect_len + serial_len + 3;
760}
761
762// Write the list of current listeners (network redirections) into a
763// user-provided buffer. Appends a trailing zero, even in case of
764// trunctaion, but return the full size in bytes.
765// If |buffer| is NULL, does not write but returns required size.
766static int format_listeners(char* buf, size_t buflen)
767{
768 alistener* l;
769 int result = 0;
770 for (l = listener_list.next; l != &listener_list; l = l->next) {
771 // Ignore special listeners like those for *smartsocket*
772 if (l->connect_to[0] == '*')
773 continue;
774 int len = format_listener(l, buf, buflen);
775 // Ensure there is space for the trailing zero.
776 result += len;
777 if (buf != NULL) {
778 buf += len;
779 buflen -= len;
780 if (buflen <= 0)
781 break;
782 }
783 }
784 return result;
785}
786
787static int remove_listener(const char *local_name, atransport* transport)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800788{
789 alistener *l;
790
791 for (l = listener_list.next; l != &listener_list; l = l->next) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100792 if (!strcmp(local_name, l->local_name)) {
793 listener_disconnect(l, l->transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794 return 0;
795 }
796 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800797 return -1;
798}
799
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100800static void remove_all_listeners(void)
801{
802 alistener *l, *l_next;
803 for (l = listener_list.next; l != &listener_list; l = l_next) {
804 l_next = l->next;
805 // Never remove smart sockets.
806 if (l->connect_to[0] == '*')
807 continue;
808 listener_disconnect(l, l->transport);
809 }
810}
811
812// error/status codes for install_listener.
813typedef enum {
814 INSTALL_STATUS_OK = 0,
815 INSTALL_STATUS_INTERNAL_ERROR = -1,
816 INSTALL_STATUS_CANNOT_BIND = -2,
817 INSTALL_STATUS_CANNOT_REBIND = -3,
818} install_status_t;
819
820static install_status_t install_listener(const char *local_name,
821 const char *connect_to,
822 atransport* transport,
823 int no_rebind)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824{
825 alistener *l;
826
827 //printf("install_listener('%s','%s')\n", local_name, connect_to);
828
829 for(l = listener_list.next; l != &listener_list; l = l->next){
830 if(strcmp(local_name, l->local_name) == 0) {
831 char *cto;
832
833 /* can't repurpose a smartsocket */
834 if(l->connect_to[0] == '*') {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100835 return INSTALL_STATUS_INTERNAL_ERROR;
836 }
837
838 /* can't repurpose a listener if 'no_rebind' is true */
839 if (no_rebind) {
840 return INSTALL_STATUS_CANNOT_REBIND;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841 }
842
843 cto = strdup(connect_to);
844 if(cto == 0) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100845 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800846 }
847
848 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
849 free((void*) l->connect_to);
850 l->connect_to = cto;
851 if (l->transport != transport) {
852 remove_transport_disconnect(l->transport, &l->disconnect);
853 l->transport = transport;
854 add_transport_disconnect(l->transport, &l->disconnect);
855 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100856 return INSTALL_STATUS_OK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 }
858 }
859
860 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
861 if((l->local_name = strdup(local_name)) == 0) goto nomem;
862 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
863
864
865 l->fd = local_name_to_fd(local_name);
866 if(l->fd < 0) {
867 free((void*) l->local_name);
868 free((void*) l->connect_to);
869 free(l);
870 printf("cannot bind '%s'\n", local_name);
871 return -2;
872 }
873
874 close_on_exec(l->fd);
875 if(!strcmp(l->connect_to, "*smartsocket*")) {
876 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
877 } else {
878 fdevent_install(&l->fde, l->fd, listener_event_func, l);
879 }
880 fdevent_set(&l->fde, FDE_READ);
881
882 l->next = &listener_list;
883 l->prev = listener_list.prev;
884 l->next->prev = l;
885 l->prev->next = l;
886 l->transport = transport;
887
888 if (transport) {
889 l->disconnect.opaque = l;
890 l->disconnect.func = listener_disconnect;
891 add_transport_disconnect(transport, &l->disconnect);
892 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100893 return INSTALL_STATUS_OK;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800894
895nomem:
896 fatal("cannot allocate listener");
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100897 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898}
899
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900#ifdef HAVE_WIN32_PROC
901static BOOL WINAPI ctrlc_handler(DWORD type)
902{
903 exit(STATUS_CONTROL_C_EXIT);
904 return TRUE;
905}
906#endif
907
908static void adb_cleanup(void)
909{
910 usb_cleanup();
911}
912
913void start_logging(void)
914{
915#ifdef HAVE_WIN32_PROC
916 char temp[ MAX_PATH ];
917 FILE* fnul;
918 FILE* flog;
919
920 GetTempPath( sizeof(temp) - 8, temp );
921 strcat( temp, "adb.log" );
922
923 /* Win32 specific redirections */
924 fnul = fopen( "NUL", "rt" );
925 if (fnul != NULL)
926 stdin[0] = fnul[0];
927
928 flog = fopen( temp, "at" );
929 if (flog == NULL)
930 flog = fnul;
931
932 setvbuf( flog, NULL, _IONBF, 0 );
933
934 stdout[0] = flog[0];
935 stderr[0] = flog[0];
936 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
937#else
938 int fd;
939
940 fd = unix_open("/dev/null", O_RDONLY);
941 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700942 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800943
944 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
945 if(fd < 0) {
946 fd = unix_open("/dev/null", O_WRONLY);
947 }
948 dup2(fd, 1);
949 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700950 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800951 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
952#endif
953}
954
955#if !ADB_HOST
956void start_device_log(void)
957{
958 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400959 char path[PATH_MAX];
960 struct tm now;
961 time_t t;
962 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800963
Mike Lockwood1f546e62009-05-25 18:17:55 -0400964 // read the trace mask from persistent property persist.adb.trace_mask
965 // give up if the property is not set or cannot be parsed
966 property_get("persist.adb.trace_mask", value, "");
967 if (sscanf(value, "%x", &adb_trace_mask) != 1)
968 return;
969
970 adb_mkdir("/data/adb", 0775);
971 tzset();
972 time(&t);
973 localtime_r(&t, &now);
974 strftime(path, sizeof(path),
975 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
976 &now);
977 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800978 if (fd < 0)
979 return;
980
981 // redirect stdout and stderr to the log file
982 dup2(fd, 1);
983 dup2(fd, 2);
984 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800985 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800986
987 fd = unix_open("/dev/null", O_RDONLY);
988 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800989 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990}
991#endif
992
993#if ADB_HOST
JP Abgrall571c1362012-12-06 18:18:12 -0800994
995#ifdef WORKAROUND_BUG6558362
996#include <sched.h>
997#define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
998void adb_set_affinity(void)
999{
1000 cpu_set_t cpu_set;
1001 const char* cpunum_str = getenv(AFFINITY_ENVVAR);
1002 char* strtol_res;
1003 int cpu_num;
1004
1005 if (!cpunum_str || !*cpunum_str)
1006 return;
1007 cpu_num = strtol(cpunum_str, &strtol_res, 0);
1008 if (*strtol_res != '\0')
1009 fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
1010
1011 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1012 D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1013 CPU_ZERO(&cpu_set);
1014 CPU_SET(cpu_num, &cpu_set);
1015 sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
1016 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1017 D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1018}
1019#endif
1020
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001021int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001022{
1023#ifdef HAVE_WIN32_PROC
1024 /* we need to start the server in the background */
1025 /* we create a PIPE that will be used to wait for the server's "OK" */
1026 /* message since the pipe handles must be inheritable, we use a */
1027 /* security attribute */
1028 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +00001029 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030 SECURITY_ATTRIBUTES sa;
1031 STARTUPINFO startup;
1032 PROCESS_INFORMATION pinfo;
1033 char program_path[ MAX_PATH ];
1034 int ret;
1035
1036 sa.nLength = sizeof(sa);
1037 sa.lpSecurityDescriptor = NULL;
1038 sa.bInheritHandle = TRUE;
1039
1040 /* create pipe, and ensure its read handle isn't inheritable */
1041 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1042 if (!ret) {
1043 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1044 return -1;
1045 }
1046
1047 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1048
Ray Donnelly267aa8b2012-11-29 01:18:50 +00001049 /* Some programs want to launch an adb command and collect its output by
1050 * calling CreateProcess with inheritable stdout/stderr handles, then
1051 * using read() to get its output. When this happens, the stdout/stderr
1052 * handles passed to the adb client process will also be inheritable.
1053 * When starting the adb server here, care must be taken to reset them
1054 * to non-inheritable.
1055 * Otherwise, something bad happens: even if the adb command completes,
1056 * the calling process is stuck while read()-ing from the stdout/stderr
1057 * descriptors, because they're connected to corresponding handles in the
1058 * adb server process (even if the latter never uses/writes to them).
1059 */
1060 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
1061 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
1062 if (stdout_handle != INVALID_HANDLE_VALUE) {
1063 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
1064 }
1065 if (stderr_handle != INVALID_HANDLE_VALUE) {
1066 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
1067 }
1068
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001069 ZeroMemory( &startup, sizeof(startup) );
1070 startup.cb = sizeof(startup);
1071 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1072 startup.hStdOutput = pipe_write;
1073 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1074 startup.dwFlags = STARTF_USESTDHANDLES;
1075
1076 ZeroMemory( &pinfo, sizeof(pinfo) );
1077
1078 /* get path of current program */
1079 GetModuleFileName( NULL, program_path, sizeof(program_path) );
Wenhao Lia09558c2013-11-13 16:23:37 +08001080 char args[64];
1081 snprintf(args, sizeof(args), "adb -P %d fork-server server", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001082 ret = CreateProcess(
1083 program_path, /* program path */
Wenhao Lia09558c2013-11-13 16:23:37 +08001084 args,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001085 /* the fork-server argument will set the
1086 debug = 2 in the child */
1087 NULL, /* process handle is not inheritable */
1088 NULL, /* thread handle is not inheritable */
1089 TRUE, /* yes, inherit some handles */
1090 DETACHED_PROCESS, /* the new process doesn't have a console */
1091 NULL, /* use parent's environment block */
1092 NULL, /* use parent's starting directory */
1093 &startup, /* startup info, i.e. std handles */
1094 &pinfo );
1095
1096 CloseHandle( pipe_write );
1097
1098 if (!ret) {
1099 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1100 CloseHandle( pipe_read );
1101 return -1;
1102 }
1103
1104 CloseHandle( pinfo.hProcess );
1105 CloseHandle( pinfo.hThread );
1106
1107 /* wait for the "OK\n" message */
1108 {
1109 char temp[3];
1110 DWORD count;
1111
1112 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1113 CloseHandle( pipe_read );
1114 if ( !ret ) {
1115 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1116 return -1;
1117 }
1118 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1119 fprintf(stderr, "ADB server didn't ACK\n" );
1120 return -1;
1121 }
1122 }
1123#elif defined(HAVE_FORKEXEC)
1124 char path[PATH_MAX];
1125 int fd[2];
1126
1127 // set up a pipe so the child can tell us when it is ready.
1128 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1129 if (pipe(fd)) {
1130 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1131 return -1;
1132 }
Alexey Tarasov31664102009-10-22 02:55:00 +11001133 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001134 pid_t pid = fork();
1135 if(pid < 0) return -1;
1136
1137 if (pid == 0) {
1138 // child side of the fork
1139
1140 // redirect stderr to the pipe
1141 // we use stderr instead of stdout due to stdout's buffering behavior.
1142 adb_close(fd[0]);
1143 dup2(fd[1], STDERR_FILENO);
1144 adb_close(fd[1]);
1145
Matt Gumbeld7b33082012-11-14 10:16:17 -08001146 char str_port[30];
1147 snprintf(str_port, sizeof(str_port), "%d", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001148 // child process
Matt Gumbeld7b33082012-11-14 10:16:17 -08001149 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001150 // this should not return
1151 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1152 } else {
1153 // parent side of the fork
1154
1155 char temp[3];
1156
1157 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1158 // wait for the "OK\n" message
1159 adb_close(fd[1]);
1160 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -07001161 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 adb_close(fd[0]);
1163 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -07001164 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165 return -1;
1166 }
1167 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1168 fprintf(stderr, "ADB server didn't ACK\n" );
1169 return -1;
1170 }
1171
1172 setsid();
1173 }
1174#else
1175#error "cannot implement background server start on this platform"
1176#endif
1177 return 0;
1178}
1179#endif
1180
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001181/* Constructs a local name of form tcp:port.
1182 * target_str points to the target string, it's content will be overwritten.
1183 * target_size is the capacity of the target string.
1184 * server_port is the port number to use for the local name.
1185 */
1186void build_local_name(char* target_str, size_t target_size, int server_port)
1187{
1188 snprintf(target_str, target_size, "tcp:%d", server_port);
1189}
1190
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001191#if !ADB_HOST
Nick Kralevich080427e2013-02-15 14:39:15 -08001192
1193static void drop_capabilities_bounding_set_if_needed() {
1194#ifdef ALLOW_ADBD_ROOT
1195 char value[PROPERTY_VALUE_MAX];
1196 property_get("ro.debuggable", value, "");
1197 if (strcmp(value, "1") == 0) {
1198 return;
1199 }
1200#endif
1201 int i;
1202 for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
Nick Kralevich4c609e92013-02-27 13:15:02 -08001203 if ((i == CAP_SETUID) || (i == CAP_SETGID)) {
Nick Kralevich080427e2013-02-15 14:39:15 -08001204 // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
1205 continue;
1206 }
1207 int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
1208
1209 // Some kernels don't have file capabilities compiled in, and
1210 // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
1211 // die when we see such misconfigured kernels.
1212 if ((err < 0) && (errno != EINVAL)) {
1213 exit(1);
1214 }
1215 }
1216}
1217
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001218static int should_drop_privileges() {
Nick Kralevich5890fe32012-01-19 13:11:35 -08001219#ifndef ALLOW_ADBD_ROOT
1220 return 1;
1221#else /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001222 int secure = 0;
1223 char value[PROPERTY_VALUE_MAX];
1224
1225 /* run adbd in secure mode if ro.secure is set and
1226 ** we are not in the emulator
1227 */
1228 property_get("ro.kernel.qemu", value, "");
1229 if (strcmp(value, "1") != 0) {
1230 property_get("ro.secure", value, "1");
1231 if (strcmp(value, "1") == 0) {
1232 // don't run as root if ro.secure is set...
1233 secure = 1;
1234
1235 // ... except we allow running as root in userdebug builds if the
1236 // service.adb.root property has been set by the "adb root" command
1237 property_get("ro.debuggable", value, "");
1238 if (strcmp(value, "1") == 0) {
1239 property_get("service.adb.root", value, "");
1240 if (strcmp(value, "1") == 0) {
1241 secure = 0;
1242 }
1243 }
1244 }
1245 }
1246 return secure;
Nick Kralevich5890fe32012-01-19 13:11:35 -08001247#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001248}
1249#endif /* !ADB_HOST */
1250
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001251int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001252{
1253#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -07001254 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001255 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -07001256
1257 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001258#endif
1259
1260 atexit(adb_cleanup);
1261#ifdef HAVE_WIN32_PROC
1262 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1263#elif defined(HAVE_FORKEXEC)
JP Abgrall408fa572011-03-16 15:57:42 -07001264 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001265 signal(SIGPIPE, SIG_IGN);
1266#endif
1267
1268 init_transport_registration();
1269
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001270#if ADB_HOST
1271 HOST = 1;
JP Abgrall571c1362012-12-06 18:18:12 -08001272
1273#ifdef WORKAROUND_BUG6558362
1274 if(is_daemon) adb_set_affinity();
1275#endif
Xavier Ducroheta09fbd12009-05-20 17:33:53 -07001276 usb_vendors_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001277 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001278 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001279 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001280
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001281 char local_name[30];
1282 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001283 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001284 exit(1);
1285 }
1286#else
Benoit Gobyd5fcafa2012-04-12 12:23:49 -07001287 property_get("ro.adb.secure", value, "0");
1288 auth_enabled = !strcmp(value, "1");
1289 if (auth_enabled)
1290 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001291
Jeff Sharkeyd6d42862012-09-06 13:05:40 -07001292 // Our external storage path may be different than apps, since
1293 // we aren't able to bind mount after dropping root.
1294 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1295 if (NULL != adb_external_storage) {
1296 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1297 } else {
1298 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1299 " unchanged.\n");
1300 }
1301
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001302 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001303 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -08001304 if (should_drop_privileges()) {
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001305 struct __user_cap_header_struct header;
Nick Kralevich109f4e12013-02-14 15:47:14 -08001306 struct __user_cap_data_struct cap[2];
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001307
Nick Kralevich44db9902010-08-27 14:35:07 -07001308 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1309 exit(1);
1310 }
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001311
Nick Kralevich080427e2013-02-15 14:39:15 -08001312 drop_capabilities_bounding_set_if_needed();
1313
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001314 /* add extra groups:
1315 ** AID_ADB to access the USB driver
1316 ** AID_LOG to read system logs (adb logcat)
1317 ** AID_INPUT to diagnose input issues (getevent)
1318 ** AID_INET to diagnose network issues (netcfg, ping)
1319 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Project20155492009-03-11 12:12:01 -07001320 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001321 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwood6a3075c2009-05-25 13:52:00 -04001322 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd969faa2010-02-24 16:07:23 -05001323 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall61b90bd2011-11-09 10:30:08 -08001324 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001325 */
The Android Open Source Project20155492009-03-11 12:12:01 -07001326 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackborn50458cf2012-03-07 12:57:14 -08001327 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1328 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich44db9902010-08-27 14:35:07 -07001329 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1330 exit(1);
1331 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001332
1333 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -07001334 if (setgid(AID_SHELL) != 0) {
1335 exit(1);
1336 }
1337 if (setuid(AID_SHELL) != 0) {
1338 exit(1);
1339 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001340
Nick Kralevich109f4e12013-02-14 15:47:14 -08001341 memset(&header, 0, sizeof(header));
1342 memset(cap, 0, sizeof(cap));
1343
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001344 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
Nick Kralevich109f4e12013-02-14 15:47:14 -08001345 header.version = _LINUX_CAPABILITY_VERSION_3;
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001346 header.pid = 0;
Nick Kralevich109f4e12013-02-14 15:47:14 -08001347 cap[CAP_TO_INDEX(CAP_SYS_BOOT)].effective |= CAP_TO_MASK(CAP_SYS_BOOT);
1348 cap[CAP_TO_INDEX(CAP_SYS_BOOT)].permitted |= CAP_TO_MASK(CAP_SYS_BOOT);
1349 capset(&header, cap);
Mike Lockwood5f4b0512009-08-04 20:37:51 -04001350
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001351 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001352 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001353 char local_name[30];
1354 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001355 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001356 exit(1);
1357 }
1358 }
1359
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001360 int usb = 0;
1361 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001362 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001363 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001364 usb = 1;
1365 }
1366
1367 // If one of these properties is set, also listen on that port
1368 // If one of the properties isn't set and we couldn't listen on usb,
1369 // listen on the default port.
1370 property_get("service.adb.tcp.port", value, "");
1371 if (!value[0]) {
1372 property_get("persist.adb.tcp.port", value, "");
1373 }
1374 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1375 printf("using port=%d\n", port);
1376 // listen on TCP port specified by service.adb.tcp.port property
1377 local_init(port);
1378 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001379 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001380 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001381 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001382
JP Abgrall408fa572011-03-16 15:57:42 -07001383 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001384 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001385 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001386#endif
1387
1388 if (is_daemon)
1389 {
1390 // inform our parent that we are up and running.
1391#ifdef HAVE_WIN32_PROC
1392 DWORD count;
1393 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1394#elif defined(HAVE_FORKEXEC)
1395 fprintf(stderr, "OK\n");
1396#endif
1397 start_logging();
1398 }
JP Abgrall408fa572011-03-16 15:57:42 -07001399 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001400
1401 fdevent_loop();
1402
1403 usb_cleanup();
1404
1405 return 0;
1406}
1407
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001408#if ADB_HOST
1409void connect_device(char* host, char* buffer, int buffer_size)
1410{
1411 int port, fd;
1412 char* portstr = strchr(host, ':');
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001413 char hostbuf[100];
1414 char serial[100];
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001415
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001416 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1417 if (portstr) {
Scott Andersonc7993af2012-05-25 13:55:46 -07001418 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001419 snprintf(buffer, buffer_size, "bad host name %s", host);
1420 return;
1421 }
1422 // zero terminate the host at the point we found the colon
1423 hostbuf[portstr - host] = 0;
1424 if (sscanf(portstr + 1, "%d", &port) == 0) {
1425 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1426 return;
1427 }
1428 } else {
1429 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001430 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001431
1432 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1433 if (find_transport(serial)) {
1434 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001435 return;
1436 }
1437
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001438 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001439 if (fd < 0) {
1440 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1441 return;
1442 }
1443
1444 D("client: connected on remote on fd %d\n", fd);
1445 close_on_exec(fd);
1446 disable_tcp_nagle(fd);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001447 register_socket_transport(fd, serial, port, 0);
1448 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001449}
1450
1451void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1452{
1453 char* port_separator = strchr(port_spec, ',');
1454 if (!port_separator) {
1455 snprintf(buffer, buffer_size,
1456 "unable to parse '%s' as <console port>,<adb port>",
1457 port_spec);
1458 return;
1459 }
1460
1461 // Zero-terminate console port and make port_separator point to 2nd port.
1462 *port_separator++ = 0;
1463 int console_port = strtol(port_spec, NULL, 0);
1464 int adb_port = strtol(port_separator, NULL, 0);
1465 if (!(console_port > 0 && adb_port > 0)) {
1466 *(port_separator - 1) = ',';
1467 snprintf(buffer, buffer_size,
1468 "Invalid port numbers: Expected positive numbers, got '%s'",
1469 port_spec);
1470 return;
1471 }
1472
1473 /* Check if the emulator is already known.
1474 * Note: There's a small but harmless race condition here: An emulator not
1475 * present just yet could be registered by another invocation right
1476 * after doing this check here. However, local_connect protects
1477 * against double-registration too. From here, a better error message
1478 * can be produced. In the case of the race condition, the very specific
1479 * error message won't be shown, but the data doesn't get corrupted. */
1480 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1481 if (known_emulator != NULL) {
1482 snprintf(buffer, buffer_size,
1483 "Emulator on port %d already registered.", adb_port);
1484 return;
1485 }
1486
1487 /* Check if more emulators can be registered. Similar unproblematic
1488 * race condition as above. */
1489 int candidate_slot = get_available_local_transport_index();
1490 if (candidate_slot < 0) {
1491 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1492 return;
1493 }
1494
1495 /* Preconditions met, try to connect to the emulator. */
1496 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1497 snprintf(buffer, buffer_size,
1498 "Connected to emulator on ports %d,%d", console_port, adb_port);
1499 } else {
1500 snprintf(buffer, buffer_size,
1501 "Could not connect to emulator on ports %d,%d",
1502 console_port, adb_port);
1503 }
1504}
1505#endif
1506
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001507int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1508{
1509 atransport *transport = NULL;
1510 char buf[4096];
1511
1512 if(!strcmp(service, "kill")) {
1513 fprintf(stderr,"adb server killed by remote request\n");
1514 fflush(stdout);
1515 adb_write(reply_fd, "OKAY", 4);
1516 usb_cleanup();
1517 exit(0);
1518 }
1519
1520#if ADB_HOST
1521 // "transport:" is used for switching transport with a specified serial number
1522 // "transport-usb:" is used for switching transport to the only USB transport
1523 // "transport-local:" is used for switching transport to the only local transport
1524 // "transport-any:" is used for switching transport to the only transport
1525 if (!strncmp(service, "transport", strlen("transport"))) {
1526 char* error_string = "unknown failure";
1527 transport_type type = kTransportAny;
1528
1529 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1530 type = kTransportUsb;
1531 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1532 type = kTransportLocal;
1533 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1534 type = kTransportAny;
1535 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1536 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001537 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001538 }
1539
1540 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1541
1542 if (transport) {
1543 s->transport = transport;
1544 adb_write(reply_fd, "OKAY", 4);
1545 } else {
1546 sendfailmsg(reply_fd, error_string);
1547 }
1548 return 1;
1549 }
1550
1551 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001552 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001553 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001554 int use_long = !strcmp(service+7, "-l");
1555 if (use_long || service[7] == 0) {
1556 memset(buf, 0, sizeof(buf));
1557 memset(buffer, 0, sizeof(buffer));
1558 D("Getting device list \n");
1559 list_transports(buffer, sizeof(buffer), use_long);
1560 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1561 D("Wrote device list \n");
1562 writex(reply_fd, buf, strlen(buf));
1563 return 0;
1564 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001565 }
1566
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001567 // add a new TCP transport, device or emulator
Mike Lockwood2f38b692009-08-24 15:58:40 -07001568 if (!strncmp(service, "connect:", 8)) {
1569 char buffer[4096];
Mike Lockwood2f38b692009-08-24 15:58:40 -07001570 char* host = service + 8;
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001571 if (!strncmp(host, "emu:", 4)) {
1572 connect_emulator(host + 4, buffer, sizeof(buffer));
1573 } else {
1574 connect_device(host, buffer, sizeof(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001575 }
Stefan Hilzingerd9d1ca42010-04-26 10:17:43 +01001576 // Send response for emulator and device
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001577 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1578 writex(reply_fd, buf, strlen(buf));
1579 return 0;
1580 }
1581
1582 // remove TCP transport
1583 if (!strncmp(service, "disconnect:", 11)) {
1584 char buffer[4096];
1585 memset(buffer, 0, sizeof(buffer));
1586 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001587 if (serial[0] == 0) {
1588 // disconnect from all TCP devices
1589 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001590 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001591 char hostbuf[100];
1592 // assume port 5555 if no port is specified
1593 if (!strchr(serial, ':')) {
1594 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1595 serial = hostbuf;
1596 }
1597 atransport *t = find_transport(serial);
1598
1599 if (t) {
1600 unregister_transport(t);
1601 } else {
1602 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1603 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001604 }
1605
1606 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwood2f38b692009-08-24 15:58:40 -07001607 writex(reply_fd, buf, strlen(buf));
1608 return 0;
1609 }
1610
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001611 // returns our value for ADB_SERVER_VERSION
1612 if (!strcmp(service, "version")) {
1613 char version[12];
1614 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1615 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1616 writex(reply_fd, buf, strlen(buf));
1617 return 0;
1618 }
1619
1620 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1621 char *out = "unknown";
1622 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1623 if (transport && transport->serial) {
1624 out = transport->serial;
1625 }
1626 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1627 writex(reply_fd, buf, strlen(buf));
1628 return 0;
1629 }
Scott Andersone109d262012-04-20 11:21:14 -07001630 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1631 char *out = "unknown";
1632 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1633 if (transport && transport->devpath) {
1634 out = transport->devpath;
1635 }
1636 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1637 writex(reply_fd, buf, strlen(buf));
1638 return 0;
1639 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001640 // indicates a new emulator instance has started
1641 if (!strncmp(service,"emulator:",9)) {
1642 int port = atoi(service+9);
1643 local_connect(port);
1644 /* we don't even need to send a reply */
1645 return 0;
1646 }
1647#endif // ADB_HOST
1648
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001649 if(!strcmp(service,"list-forward")) {
1650 // Create the list of forward redirections.
1651 char header[9];
1652 int buffer_size = format_listeners(NULL, 0);
1653 // Add one byte for the trailing zero.
1654 char* buffer = malloc(buffer_size+1);
1655 (void) format_listeners(buffer, buffer_size+1);
1656 snprintf(header, sizeof header, "OKAY%04x", buffer_size);
1657 writex(reply_fd, header, 8);
1658 writex(reply_fd, buffer, buffer_size);
1659 free(buffer);
1660 return 0;
1661 }
1662
1663 if (!strcmp(service,"killforward-all")) {
1664 remove_all_listeners();
1665 adb_write(reply_fd, "OKAYOKAY", 8);
1666 return 0;
1667 }
1668
1669 if(!strncmp(service,"forward:",8) ||
1670 !strncmp(service,"killforward:",12)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001671 char *local, *remote, *err;
1672 int r;
1673 atransport *transport;
1674
1675 int createForward = strncmp(service,"kill",4);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001676 int no_rebind = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001677
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001678 local = strchr(service, ':') + 1;
1679
1680 // Handle forward:norebind:<local>... here
1681 if (createForward && !strncmp(local, "norebind:", 9)) {
1682 no_rebind = 1;
1683 local = strchr(local, ':') + 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001684 }
1685
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001686 remote = strchr(local,';');
1687
1688 if (createForward) {
1689 // Check forward: parameter format: '<local>;<remote>'
1690 if(remote == 0) {
1691 sendfailmsg(reply_fd, "malformed forward spec");
1692 return 0;
1693 }
1694
1695 *remote++ = 0;
1696 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1697 sendfailmsg(reply_fd, "malformed forward spec");
1698 return 0;
1699 }
1700 } else {
1701 // Check killforward: parameter format: '<local>'
1702 if (local[0] == 0) {
1703 sendfailmsg(reply_fd, "malformed forward spec");
1704 return 0;
1705 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001706 }
1707
1708 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1709 if (!transport) {
1710 sendfailmsg(reply_fd, err);
1711 return 0;
1712 }
1713
1714 if (createForward) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001715 r = install_listener(local, remote, transport, no_rebind);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001716 } else {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001717 r = remove_listener(local, transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001718 }
1719 if(r == 0) {
1720 /* 1st OKAY is connect, 2nd OKAY is status */
1721 writex(reply_fd, "OKAYOKAY", 8);
1722 return 0;
1723 }
1724
1725 if (createForward) {
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001726 const char* message;
1727 switch (r) {
1728 case INSTALL_STATUS_CANNOT_BIND:
1729 message = "cannot bind to socket";
1730 break;
1731 case INSTALL_STATUS_CANNOT_REBIND:
1732 message = "cannot rebind existing socket";
1733 break;
1734 default:
1735 message = "internal error";
1736 }
1737 sendfailmsg(reply_fd, message);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001738 } else {
1739 sendfailmsg(reply_fd, "cannot remove listener");
1740 }
1741 return 0;
1742 }
1743
1744 if(!strncmp(service,"get-state",strlen("get-state"))) {
1745 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1746 char *state = connection_state_name(transport);
1747 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1748 writex(reply_fd, buf, strlen(buf));
1749 return 0;
1750 }
1751 return -1;
1752}
1753
1754#if !ADB_HOST
1755int recovery_mode = 0;
1756#endif
1757
1758int main(int argc, char **argv)
1759{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001760#if ADB_HOST
1761 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001762 adb_trace_init();
1763 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001764 return adb_commandline(argc - 1, argv + 1);
1765#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001766 /* If adbd runs inside the emulator this will enable adb tracing via
1767 * adb-debug qemud service in the emulator. */
1768 adb_qemu_trace_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001769 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1770 adb_device_banner = "recovery";
1771 recovery_mode = 1;
1772 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001773
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001774 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001775 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001776 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001777#endif
1778}