blob: 949e5ea4237552ebf13e3d6d441b42e3dad6352d [file] [log] [blame]
The Android Open Source Project9ca14dc2009-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 Andersona40781d2012-05-25 13:55:46 -070024#include <stddef.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <string.h>
26#include <time.h>
Mike Lockwood4ac1e282009-05-25 18:17:55 -040027#include <sys/time.h>
Ray Donnellydccbca22012-11-29 01:36:08 +000028#include <stdint.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080029
30#include "sysdeps.h"
31#include "adb.h"
Benoit Goby2cc19e42012-04-12 12:23:49 -070032#include "adb_auth.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080033
Scott Andersonfa020922012-05-25 14:10:02 -070034#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
35
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080036#if !ADB_HOST
37#include <private/android_filesystem_config.h>
Mike Lockwooda91f54c2009-08-04 20:37:51 -040038#include <linux/capability.h>
39#include <linux/prctl.h>
Jeff Sharkey11987252012-08-14 21:00:22 -070040#include <sys/mount.h>
Xavier Ducrohet2ef5fc22009-05-20 17:33:53 -070041#else
42#include "usb_vendors.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080043#endif
44
JP Abgrall2e5dd6e2011-03-16 15:57:42 -070045#if ADB_TRACE
46ADB_MUTEX_DEFINE( D_lock );
47#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080048
49int HOST = 0;
Matt Gumbel411775c2012-11-14 10:16:17 -080050int gListenAll = 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080051
Benoit Goby2cc19e42012-04-12 12:23:49 -070052static int auth_enabled = 0;
53
Scott Andersonfa020922012-05-25 14:10:02 -070054#if !ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080055static const char *adb_device_banner = "device";
Scott Andersonfa020922012-05-25 14:10:02 -070056#endif
The Android Open Source Project9ca14dc2009-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 Abgrall2e5dd6e2011-03-16 15:57:42 -0700107 { "services", TRACE_SERVICES },
Benoit Goby2cc19e42012-04-12 12:23:49 -0700108 { "auth", TRACE_AUTH },
The Android Open Source Project9ca14dc2009-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 Chtchetkine32a15712012-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 Project9ca14dc2009-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 Goby2cc19e42012-04-12 12:23:49 -0700212void handle_online(atransport *t)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800213{
214 D("adb: online\n");
Benoit Goby2cc19e42012-04-12 12:23:49 -0700215 t->online = 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800216}
217
218void handle_offline(atransport *t)
219{
220 D("adb: offline\n");
221 //Close the associated usb
Benoit Goby2cc19e42012-04-12 12:23:49 -0700222 t->online = 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800223 run_transport_disconnects(t);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800224}
225
Benoit Goby2cc19e42012-04-12 12:23:49 -0700226#if DEBUG_PACKETS
The Android Open Source Project9ca14dc2009-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 Goby2cc19e42012-04-12 12:23:49 -0700241 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Project9ca14dc2009-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 Goby2cc19e42012-04-12 12:23:49 -0700263 fputs(tag, stderr);
The Android Open Source Project9ca14dc2009-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 Andersonfa020922012-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 Project9ca14dc2009-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 Andersonfa020922012-05-25 14:10:02 -0700324 cp->msg.data_length = fill_connect_data((char *)cp->data,
325 sizeof(cp->data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800326 send_packet(cp, t);
Benoit Goby2cc19e42012-04-12 12:23:49 -0700327}
328
329static void send_auth_request(atransport *t)
330{
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 Project9ca14dc2009-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";
404 case CS_OFFLINE:
405 return "offline";
Nick Kralevich23b39f02013-02-15 10:22:08 -0800406 case CS_UNAUTHORIZED:
407 return "unauthorized";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800408 default:
409 return "unknown";
410 }
411}
412
Scott Andersonfa020922012-05-25 14:10:02 -0700413/* qual_overwrite is used to overwrite a qualifier string. dst is a
414 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson27042382012-05-30 18:11:27 -0700415 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersonfa020922012-05-25 14:10:02 -0700416 */
417static void qual_overwrite(char **dst, const char *src)
418{
419 if (!dst)
420 return;
421
422 free(*dst);
423 *dst = NULL;
424
425 if (!src || !*src)
426 return;
427
428 *dst = strdup(src);
429}
430
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800431void parse_banner(char *banner, atransport *t)
432{
Scott Andersonfa020922012-05-25 14:10:02 -0700433 static const char *prop_seps = ";";
434 static const char key_val_sep = '=';
Scott Anderson27042382012-05-30 18:11:27 -0700435 char *cp;
436 char *type;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800437
438 D("parse_banner: %s\n", banner);
439 type = banner;
Scott Andersonfa020922012-05-25 14:10:02 -0700440 cp = strchr(type, ':');
441 if (cp) {
442 *cp++ = 0;
443 /* Nothing is done with second field. */
444 cp = strchr(cp, ':');
445 if (cp) {
446 char *save;
447 char *key;
Scott Anderson0fa59782012-06-05 17:54:27 -0700448 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersonfa020922012-05-25 14:10:02 -0700449 while (key) {
450 cp = strchr(key, key_val_sep);
451 if (cp) {
452 *cp++ = '\0';
453 if (!strcmp(key, "ro.product.name"))
454 qual_overwrite(&t->product, cp);
455 else if (!strcmp(key, "ro.product.model"))
456 qual_overwrite(&t->model, cp);
457 else if (!strcmp(key, "ro.product.device"))
458 qual_overwrite(&t->device, cp);
459 }
Scott Anderson0fa59782012-06-05 17:54:27 -0700460 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersonfa020922012-05-25 14:10:02 -0700461 }
462 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800463 }
464
465 if(!strcmp(type, "bootloader")){
466 D("setting connection_state to CS_BOOTLOADER\n");
467 t->connection_state = CS_BOOTLOADER;
468 update_transports();
469 return;
470 }
471
472 if(!strcmp(type, "device")) {
473 D("setting connection_state to CS_DEVICE\n");
474 t->connection_state = CS_DEVICE;
475 update_transports();
476 return;
477 }
478
479 if(!strcmp(type, "recovery")) {
480 D("setting connection_state to CS_RECOVERY\n");
481 t->connection_state = CS_RECOVERY;
482 update_transports();
483 return;
484 }
485
Doug Zongker6b217ed2012-01-09 14:54:53 -0800486 if(!strcmp(type, "sideload")) {
487 D("setting connection_state to CS_SIDELOAD\n");
488 t->connection_state = CS_SIDELOAD;
489 update_transports();
490 return;
491 }
492
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800493 t->connection_state = CS_HOST;
494}
495
496void handle_packet(apacket *p, atransport *t)
497{
498 asocket *s;
499
Viral Mehta841f9a72010-06-16 18:41:28 +0530500 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
501 ((char*) (&(p->msg.command)))[1],
502 ((char*) (&(p->msg.command)))[2],
503 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800504 print_packet("recv", p);
505
506 switch(p->msg.command){
507 case A_SYNC:
508 if(p->msg.arg0){
509 send_packet(p, t);
510 if(HOST) send_connect(t);
511 } else {
512 t->connection_state = CS_OFFLINE;
513 handle_offline(t);
514 send_packet(p, t);
515 }
516 return;
517
518 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
519 /* XXX verify version, etc */
520 if(t->connection_state != CS_OFFLINE) {
521 t->connection_state = CS_OFFLINE;
522 handle_offline(t);
523 }
Benoit Goby2cc19e42012-04-12 12:23:49 -0700524
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800525 parse_banner((char*) p->data, t);
Benoit Goby2cc19e42012-04-12 12:23:49 -0700526
527 if (HOST || !auth_enabled) {
528 handle_online(t);
529 if(!HOST) send_connect(t);
530 } else {
531 send_auth_request(t);
532 }
533 break;
534
535 case A_AUTH:
536 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
Nick Kralevich23b39f02013-02-15 10:22:08 -0800537 t->connection_state = CS_UNAUTHORIZED;
Benoit Goby2cc19e42012-04-12 12:23:49 -0700538 t->key = adb_auth_nextkey(t->key);
539 if (t->key) {
540 send_auth_response(p->data, p->msg.data_length, t);
541 } else {
542 /* No more private keys to try, send the public key */
543 send_auth_publickey(t);
544 }
545 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
546 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
547 adb_auth_verified(t);
548 t->failed_auth_attempts = 0;
549 } else {
550 if (t->failed_auth_attempts++ > 10)
551 adb_sleep_ms(1000);
552 send_auth_request(t);
553 }
554 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
555 adb_auth_confirm_key(p->data, p->msg.data_length, t);
556 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800557 break;
558
559 case A_OPEN: /* OPEN(local-id, 0, "destination") */
Benoit Goby2cc19e42012-04-12 12:23:49 -0700560 if (t->online) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800561 char *name = (char*) p->data;
562 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
563 s = create_local_service_socket(name);
564 if(s == 0) {
565 send_close(0, p->msg.arg0, t);
566 } else {
567 s->peer = create_remote_socket(p->msg.arg0, t);
568 s->peer->peer = s;
569 send_ready(s->id, s->peer->id, t);
570 s->ready(s);
571 }
572 }
573 break;
574
575 case A_OKAY: /* READY(local-id, remote-id, "") */
Benoit Goby2cc19e42012-04-12 12:23:49 -0700576 if (t->online) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800577 if((s = find_local_socket(p->msg.arg1))) {
578 if(s->peer == 0) {
579 s->peer = create_remote_socket(p->msg.arg0, t);
580 s->peer->peer = s;
581 }
582 s->ready(s);
583 }
584 }
585 break;
586
587 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
Benoit Goby2cc19e42012-04-12 12:23:49 -0700588 if (t->online) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800589 if((s = find_local_socket(p->msg.arg1))) {
590 s->close(s);
591 }
592 }
593 break;
594
595 case A_WRTE:
Benoit Goby2cc19e42012-04-12 12:23:49 -0700596 if (t->online) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800597 if((s = find_local_socket(p->msg.arg1))) {
598 unsigned rid = p->msg.arg0;
599 p->len = p->msg.data_length;
600
601 if(s->enqueue(s, p) == 0) {
602 D("Enqueue the socket\n");
603 send_ready(s->id, rid, t);
604 }
605 return;
606 }
607 }
608 break;
609
610 default:
611 printf("handle_packet: what is %08x?!\n", p->msg.command);
612 }
613
614 put_apacket(p);
615}
616
617alistener listener_list = {
618 .next = &listener_list,
619 .prev = &listener_list,
620};
621
622static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
623{
624 asocket *s;
625
626 if(ev & FDE_READ) {
627 struct sockaddr addr;
628 socklen_t alen;
629 int fd;
630
631 alen = sizeof(addr);
632 fd = adb_socket_accept(_fd, &addr, &alen);
633 if(fd < 0) return;
634
635 adb_socket_setbufsize(fd, CHUNK_SIZE);
636
637 s = create_local_socket(fd);
638 if(s) {
639 connect_to_smartsocket(s);
640 return;
641 }
642
643 adb_close(fd);
644 }
645}
646
647static void listener_event_func(int _fd, unsigned ev, void *_l)
648{
649 alistener *l = _l;
650 asocket *s;
651
652 if(ev & FDE_READ) {
653 struct sockaddr addr;
654 socklen_t alen;
655 int fd;
656
657 alen = sizeof(addr);
658 fd = adb_socket_accept(_fd, &addr, &alen);
659 if(fd < 0) return;
660
661 s = create_local_socket(fd);
662 if(s) {
663 s->transport = l->transport;
664 connect_to_remote(s, l->connect_to);
665 return;
666 }
667
668 adb_close(fd);
669 }
670}
671
672static void free_listener(alistener* l)
673{
674 if (l->next) {
675 l->next->prev = l->prev;
676 l->prev->next = l->next;
677 l->next = l->prev = l;
678 }
679
680 // closes the corresponding fd
681 fdevent_remove(&l->fde);
682
683 if (l->local_name)
684 free((char*)l->local_name);
685
686 if (l->connect_to)
687 free((char*)l->connect_to);
688
689 if (l->transport) {
690 remove_transport_disconnect(l->transport, &l->disconnect);
691 }
692 free(l);
693}
694
695static void listener_disconnect(void* _l, atransport* t)
696{
697 alistener* l = _l;
698
699 free_listener(l);
700}
701
702int local_name_to_fd(const char *name)
703{
704 int port;
705
706 if(!strncmp("tcp:", name, 4)){
707 int ret;
708 port = atoi(name + 4);
Matt Gumbel411775c2012-11-14 10:16:17 -0800709
710 if (gListenAll > 0) {
711 ret = socket_inaddr_any_server(port, SOCK_STREAM);
712 } else {
713 ret = socket_loopback_server(port, SOCK_STREAM);
714 }
715
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716 return ret;
717 }
718#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
719 // It's non-sensical to support the "reserved" space on the adb host side
720 if(!strncmp(name, "local:", 6)) {
721 return socket_local_server(name + 6,
722 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
723 } else if(!strncmp(name, "localabstract:", 14)) {
724 return socket_local_server(name + 14,
725 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
726 } else if(!strncmp(name, "localfilesystem:", 16)) {
727 return socket_local_server(name + 16,
728 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
729 }
730
731#endif
732 printf("unknown local portname '%s'\n", name);
733 return -1;
734}
735
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100736// Write a single line describing a listener to a user-provided buffer.
737// Appends a trailing zero, even in case of truncation, but the function
738// returns the full line length.
739// If |buffer| is NULL, does not write but returns required size.
740static int format_listener(alistener* l, char* buffer, size_t buffer_len) {
741 // Format is simply:
742 //
743 // <device-serial> " " <local-name> " " <remote-name> "\n"
744 //
745 int local_len = strlen(l->local_name);
746 int connect_len = strlen(l->connect_to);
747 int serial_len = strlen(l->transport->serial);
748
749 if (buffer != NULL) {
750 snprintf(buffer, buffer_len, "%s %s %s\n",
751 l->transport->serial, l->local_name, l->connect_to);
752 }
753 // NOTE: snprintf() on Windows returns -1 in case of truncation, so
754 // return the computed line length instead.
755 return local_len + connect_len + serial_len + 3;
756}
757
758// Write the list of current listeners (network redirections) into a
759// user-provided buffer. Appends a trailing zero, even in case of
760// trunctaion, but return the full size in bytes.
761// If |buffer| is NULL, does not write but returns required size.
762static int format_listeners(char* buf, size_t buflen)
763{
764 alistener* l;
765 int result = 0;
766 for (l = listener_list.next; l != &listener_list; l = l->next) {
767 // Ignore special listeners like those for *smartsocket*
768 if (l->connect_to[0] == '*')
769 continue;
770 int len = format_listener(l, buf, buflen);
771 // Ensure there is space for the trailing zero.
772 result += len;
773 if (buf != NULL) {
774 buf += len;
775 buflen -= len;
776 if (buflen <= 0)
777 break;
778 }
779 }
780 return result;
781}
782
783static int remove_listener(const char *local_name, atransport* transport)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800784{
785 alistener *l;
786
787 for (l = listener_list.next; l != &listener_list; l = l->next) {
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100788 if (!strcmp(local_name, l->local_name)) {
789 listener_disconnect(l, l->transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800790 return 0;
791 }
792 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793 return -1;
794}
795
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100796static void remove_all_listeners(void)
797{
798 alistener *l, *l_next;
799 for (l = listener_list.next; l != &listener_list; l = l_next) {
800 l_next = l->next;
801 // Never remove smart sockets.
802 if (l->connect_to[0] == '*')
803 continue;
804 listener_disconnect(l, l->transport);
805 }
806}
807
808// error/status codes for install_listener.
809typedef enum {
810 INSTALL_STATUS_OK = 0,
811 INSTALL_STATUS_INTERNAL_ERROR = -1,
812 INSTALL_STATUS_CANNOT_BIND = -2,
813 INSTALL_STATUS_CANNOT_REBIND = -3,
814} install_status_t;
815
816static install_status_t install_listener(const char *local_name,
817 const char *connect_to,
818 atransport* transport,
819 int no_rebind)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800820{
821 alistener *l;
822
823 //printf("install_listener('%s','%s')\n", local_name, connect_to);
824
825 for(l = listener_list.next; l != &listener_list; l = l->next){
826 if(strcmp(local_name, l->local_name) == 0) {
827 char *cto;
828
829 /* can't repurpose a smartsocket */
830 if(l->connect_to[0] == '*') {
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100831 return INSTALL_STATUS_INTERNAL_ERROR;
832 }
833
834 /* can't repurpose a listener if 'no_rebind' is true */
835 if (no_rebind) {
836 return INSTALL_STATUS_CANNOT_REBIND;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800837 }
838
839 cto = strdup(connect_to);
840 if(cto == 0) {
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100841 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800842 }
843
844 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
845 free((void*) l->connect_to);
846 l->connect_to = cto;
847 if (l->transport != transport) {
848 remove_transport_disconnect(l->transport, &l->disconnect);
849 l->transport = transport;
850 add_transport_disconnect(l->transport, &l->disconnect);
851 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100852 return INSTALL_STATUS_OK;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800853 }
854 }
855
856 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
857 if((l->local_name = strdup(local_name)) == 0) goto nomem;
858 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
859
860
861 l->fd = local_name_to_fd(local_name);
862 if(l->fd < 0) {
863 free((void*) l->local_name);
864 free((void*) l->connect_to);
865 free(l);
866 printf("cannot bind '%s'\n", local_name);
867 return -2;
868 }
869
870 close_on_exec(l->fd);
871 if(!strcmp(l->connect_to, "*smartsocket*")) {
872 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
873 } else {
874 fdevent_install(&l->fde, l->fd, listener_event_func, l);
875 }
876 fdevent_set(&l->fde, FDE_READ);
877
878 l->next = &listener_list;
879 l->prev = listener_list.prev;
880 l->next->prev = l;
881 l->prev->next = l;
882 l->transport = transport;
883
884 if (transport) {
885 l->disconnect.opaque = l;
886 l->disconnect.func = listener_disconnect;
887 add_transport_disconnect(transport, &l->disconnect);
888 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100889 return INSTALL_STATUS_OK;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800890
891nomem:
892 fatal("cannot allocate listener");
David 'Digit' Turner6c489802012-11-14 15:01:55 +0100893 return INSTALL_STATUS_INTERNAL_ERROR;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800894}
895
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800896#ifdef HAVE_WIN32_PROC
897static BOOL WINAPI ctrlc_handler(DWORD type)
898{
899 exit(STATUS_CONTROL_C_EXIT);
900 return TRUE;
901}
902#endif
903
904static void adb_cleanup(void)
905{
906 usb_cleanup();
907}
908
909void start_logging(void)
910{
911#ifdef HAVE_WIN32_PROC
912 char temp[ MAX_PATH ];
913 FILE* fnul;
914 FILE* flog;
915
916 GetTempPath( sizeof(temp) - 8, temp );
917 strcat( temp, "adb.log" );
918
919 /* Win32 specific redirections */
920 fnul = fopen( "NUL", "rt" );
921 if (fnul != NULL)
922 stdin[0] = fnul[0];
923
924 flog = fopen( temp, "at" );
925 if (flog == NULL)
926 flog = fnul;
927
928 setvbuf( flog, NULL, _IONBF, 0 );
929
930 stdout[0] = flog[0];
931 stderr[0] = flog[0];
932 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
933#else
934 int fd;
935
936 fd = unix_open("/dev/null", O_RDONLY);
937 dup2(fd, 0);
JP Abgrall2e5dd6e2011-03-16 15:57:42 -0700938 adb_close(fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800939
940 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
941 if(fd < 0) {
942 fd = unix_open("/dev/null", O_WRONLY);
943 }
944 dup2(fd, 1);
945 dup2(fd, 2);
JP Abgrall2e5dd6e2011-03-16 15:57:42 -0700946 adb_close(fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800947 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
948#endif
949}
950
951#if !ADB_HOST
952void start_device_log(void)
953{
954 int fd;
Mike Lockwood4ac1e282009-05-25 18:17:55 -0400955 char path[PATH_MAX];
956 struct tm now;
957 time_t t;
958 char value[PROPERTY_VALUE_MAX];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800959
Mike Lockwood4ac1e282009-05-25 18:17:55 -0400960 // read the trace mask from persistent property persist.adb.trace_mask
961 // give up if the property is not set or cannot be parsed
962 property_get("persist.adb.trace_mask", value, "");
963 if (sscanf(value, "%x", &adb_trace_mask) != 1)
964 return;
965
966 adb_mkdir("/data/adb", 0775);
967 tzset();
968 time(&t);
969 localtime_r(&t, &now);
970 strftime(path, sizeof(path),
971 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
972 &now);
973 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800974 if (fd < 0)
975 return;
976
977 // redirect stdout and stderr to the log file
978 dup2(fd, 1);
979 dup2(fd, 2);
980 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Gobyf4ded742011-02-01 18:57:41 -0800981 adb_close(fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800982
983 fd = unix_open("/dev/null", O_RDONLY);
984 dup2(fd, 0);
Benoit Gobyf4ded742011-02-01 18:57:41 -0800985 adb_close(fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800986}
987#endif
988
989#if ADB_HOST
Nick Kralevich23b39f02013-02-15 10:22:08 -0800990
991#ifdef WORKAROUND_BUG6558362
992#include <sched.h>
993#define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
994void adb_set_affinity(void)
995{
996 cpu_set_t cpu_set;
997 const char* cpunum_str = getenv(AFFINITY_ENVVAR);
998 char* strtol_res;
999 int cpu_num;
1000
1001 if (!cpunum_str || !*cpunum_str)
1002 return;
1003 cpu_num = strtol(cpunum_str, &strtol_res, 0);
1004 if (*strtol_res != '\0')
1005 fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
1006
1007 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1008 D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1009 CPU_ZERO(&cpu_set);
1010 CPU_SET(cpu_num, &cpu_set);
1011 sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
1012 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1013 D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1014}
1015#endif
1016
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001017int launch_server(int server_port)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001018{
1019#ifdef HAVE_WIN32_PROC
1020 /* we need to start the server in the background */
1021 /* we create a PIPE that will be used to wait for the server's "OK" */
1022 /* message since the pipe handles must be inheritable, we use a */
1023 /* security attribute */
1024 HANDLE pipe_read, pipe_write;
Ray Donnellyc0324702012-11-29 01:18:50 +00001025 HANDLE stdout_handle, stderr_handle;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001026 SECURITY_ATTRIBUTES sa;
1027 STARTUPINFO startup;
1028 PROCESS_INFORMATION pinfo;
1029 char program_path[ MAX_PATH ];
1030 int ret;
1031
1032 sa.nLength = sizeof(sa);
1033 sa.lpSecurityDescriptor = NULL;
1034 sa.bInheritHandle = TRUE;
1035
1036 /* create pipe, and ensure its read handle isn't inheritable */
1037 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1038 if (!ret) {
1039 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1040 return -1;
1041 }
1042
1043 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1044
Ray Donnellyc0324702012-11-29 01:18:50 +00001045 /* Some programs want to launch an adb command and collect its output by
1046 * calling CreateProcess with inheritable stdout/stderr handles, then
1047 * using read() to get its output. When this happens, the stdout/stderr
1048 * handles passed to the adb client process will also be inheritable.
1049 * When starting the adb server here, care must be taken to reset them
1050 * to non-inheritable.
1051 * Otherwise, something bad happens: even if the adb command completes,
1052 * the calling process is stuck while read()-ing from the stdout/stderr
1053 * descriptors, because they're connected to corresponding handles in the
1054 * adb server process (even if the latter never uses/writes to them).
1055 */
1056 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
1057 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
1058 if (stdout_handle != INVALID_HANDLE_VALUE) {
1059 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
1060 }
1061 if (stderr_handle != INVALID_HANDLE_VALUE) {
1062 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
1063 }
1064
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001065 ZeroMemory( &startup, sizeof(startup) );
1066 startup.cb = sizeof(startup);
1067 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1068 startup.hStdOutput = pipe_write;
1069 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1070 startup.dwFlags = STARTF_USESTDHANDLES;
1071
1072 ZeroMemory( &pinfo, sizeof(pinfo) );
1073
1074 /* get path of current program */
1075 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1076
1077 ret = CreateProcess(
1078 program_path, /* program path */
1079 "adb fork-server server",
1080 /* the fork-server argument will set the
1081 debug = 2 in the child */
1082 NULL, /* process handle is not inheritable */
1083 NULL, /* thread handle is not inheritable */
1084 TRUE, /* yes, inherit some handles */
1085 DETACHED_PROCESS, /* the new process doesn't have a console */
1086 NULL, /* use parent's environment block */
1087 NULL, /* use parent's starting directory */
1088 &startup, /* startup info, i.e. std handles */
1089 &pinfo );
1090
1091 CloseHandle( pipe_write );
1092
1093 if (!ret) {
1094 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1095 CloseHandle( pipe_read );
1096 return -1;
1097 }
1098
1099 CloseHandle( pinfo.hProcess );
1100 CloseHandle( pinfo.hThread );
1101
1102 /* wait for the "OK\n" message */
1103 {
1104 char temp[3];
1105 DWORD count;
1106
1107 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1108 CloseHandle( pipe_read );
1109 if ( !ret ) {
1110 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1111 return -1;
1112 }
1113 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1114 fprintf(stderr, "ADB server didn't ACK\n" );
1115 return -1;
1116 }
1117 }
1118#elif defined(HAVE_FORKEXEC)
1119 char path[PATH_MAX];
1120 int fd[2];
1121
1122 // set up a pipe so the child can tell us when it is ready.
1123 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1124 if (pipe(fd)) {
1125 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1126 return -1;
1127 }
Alexey Tarasov857f17a2009-10-22 02:55:00 +11001128 get_my_path(path, PATH_MAX);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001129 pid_t pid = fork();
1130 if(pid < 0) return -1;
1131
1132 if (pid == 0) {
1133 // child side of the fork
1134
1135 // redirect stderr to the pipe
1136 // we use stderr instead of stdout due to stdout's buffering behavior.
1137 adb_close(fd[0]);
1138 dup2(fd[1], STDERR_FILENO);
1139 adb_close(fd[1]);
1140
Matt Gumbel411775c2012-11-14 10:16:17 -08001141 char str_port[30];
1142 snprintf(str_port, sizeof(str_port), "%d", server_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001143 // child process
Matt Gumbel411775c2012-11-14 10:16:17 -08001144 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001145 // this should not return
1146 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1147 } else {
1148 // parent side of the fork
1149
1150 char temp[3];
1151
1152 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1153 // wait for the "OK\n" message
1154 adb_close(fd[1]);
1155 int ret = adb_read(fd[0], temp, 3);
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001156 int saved_errno = errno;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001157 adb_close(fd[0]);
1158 if (ret < 0) {
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001159 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001160 return -1;
1161 }
1162 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1163 fprintf(stderr, "ADB server didn't ACK\n" );
1164 return -1;
1165 }
1166
1167 setsid();
1168 }
1169#else
1170#error "cannot implement background server start on this platform"
1171#endif
1172 return 0;
1173}
1174#endif
1175
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001176/* Constructs a local name of form tcp:port.
1177 * target_str points to the target string, it's content will be overwritten.
1178 * target_size is the capacity of the target string.
1179 * server_port is the port number to use for the local name.
1180 */
1181void build_local_name(char* target_str, size_t target_size, int server_port)
1182{
1183 snprintf(target_str, target_size, "tcp:%d", server_port);
1184}
1185
Nick Kralevichcdcc02e2012-01-19 10:18:59 -08001186#if !ADB_HOST
Nick Kralevich62160b62013-02-15 14:39:15 -08001187
1188static void drop_capabilities_bounding_set_if_needed() {
1189#ifdef ALLOW_ADBD_ROOT
1190 char value[PROPERTY_VALUE_MAX];
1191 property_get("ro.debuggable", value, "");
1192 if (strcmp(value, "1") == 0) {
1193 return;
1194 }
1195#endif
1196 int i;
1197 for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
1198 if ((i == CAP_NET_RAW) || (i == CAP_SETUID) || (i == CAP_SETGID)) {
1199 // CAP_NET_RAW needed by /system/bin/ping
1200 // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
1201 continue;
1202 }
1203 int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
1204
1205 // Some kernels don't have file capabilities compiled in, and
1206 // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
1207 // die when we see such misconfigured kernels.
1208 if ((err < 0) && (errno != EINVAL)) {
1209 exit(1);
1210 }
1211 }
1212}
1213
Nick Kralevichcdcc02e2012-01-19 10:18:59 -08001214static int should_drop_privileges() {
Nick Kralevich09264032012-01-19 13:11:35 -08001215#ifndef ALLOW_ADBD_ROOT
1216 return 1;
1217#else /* ALLOW_ADBD_ROOT */
Nick Kralevichcdcc02e2012-01-19 10:18:59 -08001218 int secure = 0;
1219 char value[PROPERTY_VALUE_MAX];
1220
1221 /* run adbd in secure mode if ro.secure is set and
1222 ** we are not in the emulator
1223 */
1224 property_get("ro.kernel.qemu", value, "");
1225 if (strcmp(value, "1") != 0) {
1226 property_get("ro.secure", value, "1");
1227 if (strcmp(value, "1") == 0) {
1228 // don't run as root if ro.secure is set...
1229 secure = 1;
1230
1231 // ... except we allow running as root in userdebug builds if the
1232 // service.adb.root property has been set by the "adb root" command
1233 property_get("ro.debuggable", value, "");
1234 if (strcmp(value, "1") == 0) {
1235 property_get("service.adb.root", value, "");
1236 if (strcmp(value, "1") == 0) {
1237 secure = 0;
1238 }
1239 }
1240 }
1241 }
1242 return secure;
Nick Kralevich09264032012-01-19 13:11:35 -08001243#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichcdcc02e2012-01-19 10:18:59 -08001244}
1245#endif /* !ADB_HOST */
1246
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001247int adb_main(int is_daemon, int server_port)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001248{
1249#if !ADB_HOST
Mike Lockwoodb51ae572009-08-24 15:58:40 -07001250 int port;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001251 char value[PROPERTY_VALUE_MAX];
Nick Kralevichb024cab2012-04-02 13:00:35 -07001252
1253 umask(000);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001254#endif
1255
1256 atexit(adb_cleanup);
1257#ifdef HAVE_WIN32_PROC
1258 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1259#elif defined(HAVE_FORKEXEC)
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001260 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001261 signal(SIGPIPE, SIG_IGN);
1262#endif
1263
1264 init_transport_registration();
1265
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001266#if ADB_HOST
1267 HOST = 1;
Nick Kralevich23b39f02013-02-15 10:22:08 -08001268
1269#ifdef WORKAROUND_BUG6558362
1270 if(is_daemon) adb_set_affinity();
1271#endif
Xavier Ducrohet2ef5fc22009-05-20 17:33:53 -07001272 usb_vendors_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001273 usb_init();
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001274 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Goby2cc19e42012-04-12 12:23:49 -07001275 adb_auth_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001276
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001277 char local_name[30];
1278 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001279 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001280 exit(1);
1281 }
1282#else
Benoit Goby2cc19e42012-04-12 12:23:49 -07001283 property_get("ro.adb.secure", value, "0");
1284 auth_enabled = !strcmp(value, "1");
1285 if (auth_enabled)
1286 adb_auth_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001287
Jeff Sharkey41f55bb2012-09-06 13:05:40 -07001288 // Our external storage path may be different than apps, since
1289 // we aren't able to bind mount after dropping root.
1290 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1291 if (NULL != adb_external_storage) {
1292 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1293 } else {
1294 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1295 " unchanged.\n");
1296 }
1297
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001298 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001299 /* don't run as root if we are running in secure mode */
Nick Kralevichcdcc02e2012-01-19 10:18:59 -08001300 if (should_drop_privileges()) {
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001301 struct __user_cap_header_struct header;
Nick Kralevich8128d7b2013-02-14 15:47:14 -08001302 struct __user_cap_data_struct cap[2];
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001303
Nick Kralevich4ffc2eb2010-08-27 14:35:07 -07001304 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1305 exit(1);
1306 }
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001307
Nick Kralevich62160b62013-02-15 14:39:15 -08001308 drop_capabilities_bounding_set_if_needed();
1309
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001310 /* add extra groups:
1311 ** AID_ADB to access the USB driver
1312 ** AID_LOG to read system logs (adb logcat)
1313 ** AID_INPUT to diagnose input issues (getevent)
1314 ** AID_INET to diagnose network issues (netcfg, ping)
1315 ** AID_GRAPHICS to access the frame buffer
The Android Open Source Projectfbc34f32009-03-11 12:12:01 -07001316 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
Dianne Hackbornf45fb1d2012-03-07 12:57:14 -08001317 ** AID_SDCARD_R to allow reading from the SD card
Mike Lockwoodf022e612009-05-25 13:52:00 -04001318 ** AID_SDCARD_RW to allow writing to the SD card
Mike Lockwoodd49e9eb2010-02-24 16:07:23 -05001319 ** AID_MOUNT to allow unmounting the SD card before rebooting
JP Abgrall6e1eb042011-11-09 10:30:08 -08001320 ** AID_NET_BW_STATS to read out qtaguid statistics
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001321 */
The Android Open Source Projectfbc34f32009-03-11 12:12:01 -07001322 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
Dianne Hackbornf45fb1d2012-03-07 12:57:14 -08001323 AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1324 AID_MOUNT, AID_NET_BW_STATS };
Nick Kralevich4ffc2eb2010-08-27 14:35:07 -07001325 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1326 exit(1);
1327 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001328
1329 /* then switch user and group to "shell" */
Nick Kralevich4ffc2eb2010-08-27 14:35:07 -07001330 if (setgid(AID_SHELL) != 0) {
1331 exit(1);
1332 }
1333 if (setuid(AID_SHELL) != 0) {
1334 exit(1);
1335 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001336
Nick Kralevich8128d7b2013-02-14 15:47:14 -08001337 memset(&header, 0, sizeof(header));
1338 memset(cap, 0, sizeof(cap));
1339
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001340 /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
Nick Kralevich8128d7b2013-02-14 15:47:14 -08001341 header.version = _LINUX_CAPABILITY_VERSION_3;
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001342 header.pid = 0;
Nick Kralevich8128d7b2013-02-14 15:47:14 -08001343 cap[CAP_TO_INDEX(CAP_SYS_BOOT)].effective |= CAP_TO_MASK(CAP_SYS_BOOT);
1344 cap[CAP_TO_INDEX(CAP_SYS_BOOT)].permitted |= CAP_TO_MASK(CAP_SYS_BOOT);
1345 capset(&header, cap);
Mike Lockwooda91f54c2009-08-04 20:37:51 -04001346
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001347 D("Local port disabled\n");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001348 } else {
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001349 char local_name[30];
1350 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001351 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001352 exit(1);
1353 }
1354 }
1355
Mike J. Chen9acc2ee2012-07-20 18:16:21 -07001356 int usb = 0;
1357 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwooda8b38752009-08-26 12:50:22 -07001358 // listen on USB
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001359 usb_init();
Mike J. Chen9acc2ee2012-07-20 18:16:21 -07001360 usb = 1;
1361 }
1362
1363 // If one of these properties is set, also listen on that port
1364 // If one of the properties isn't set and we couldn't listen on usb,
1365 // listen on the default port.
1366 property_get("service.adb.tcp.port", value, "");
1367 if (!value[0]) {
1368 property_get("persist.adb.tcp.port", value, "");
1369 }
1370 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1371 printf("using port=%d\n", port);
1372 // listen on TCP port specified by service.adb.tcp.port property
1373 local_init(port);
1374 } else if (!usb) {
Mike Lockwooda8b38752009-08-26 12:50:22 -07001375 // listen on default port
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001376 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001377 }
Mike J. Chen9acc2ee2012-07-20 18:16:21 -07001378
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001379 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001380 init_jdwp();
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001381 D("adb_main(): post init_jdwp()\n");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001382#endif
1383
1384 if (is_daemon)
1385 {
1386 // inform our parent that we are up and running.
1387#ifdef HAVE_WIN32_PROC
1388 DWORD count;
1389 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1390#elif defined(HAVE_FORKEXEC)
1391 fprintf(stderr, "OK\n");
1392#endif
1393 start_logging();
1394 }
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001395 D("Event loop starting\n");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001396
1397 fdevent_loop();
1398
1399 usb_cleanup();
1400
1401 return 0;
1402}
1403
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001404#if ADB_HOST
1405void connect_device(char* host, char* buffer, int buffer_size)
1406{
1407 int port, fd;
1408 char* portstr = strchr(host, ':');
Mike Lockwood01c2c302010-05-24 10:44:35 -04001409 char hostbuf[100];
1410 char serial[100];
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001411
Mike Lockwood01c2c302010-05-24 10:44:35 -04001412 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1413 if (portstr) {
Scott Andersona40781d2012-05-25 13:55:46 -07001414 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
Mike Lockwood01c2c302010-05-24 10:44:35 -04001415 snprintf(buffer, buffer_size, "bad host name %s", host);
1416 return;
1417 }
1418 // zero terminate the host at the point we found the colon
1419 hostbuf[portstr - host] = 0;
1420 if (sscanf(portstr + 1, "%d", &port) == 0) {
1421 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1422 return;
1423 }
1424 } else {
1425 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001426 }
Mike Lockwood01c2c302010-05-24 10:44:35 -04001427
1428 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1429 if (find_transport(serial)) {
1430 snprintf(buffer, buffer_size, "already connected to %s", serial);
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001431 return;
1432 }
1433
Mike Lockwood01c2c302010-05-24 10:44:35 -04001434 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001435 if (fd < 0) {
1436 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1437 return;
1438 }
1439
1440 D("client: connected on remote on fd %d\n", fd);
1441 close_on_exec(fd);
1442 disable_tcp_nagle(fd);
Mike Lockwood01c2c302010-05-24 10:44:35 -04001443 register_socket_transport(fd, serial, port, 0);
1444 snprintf(buffer, buffer_size, "connected to %s", serial);
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001445}
1446
1447void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1448{
1449 char* port_separator = strchr(port_spec, ',');
1450 if (!port_separator) {
1451 snprintf(buffer, buffer_size,
1452 "unable to parse '%s' as <console port>,<adb port>",
1453 port_spec);
1454 return;
1455 }
1456
1457 // Zero-terminate console port and make port_separator point to 2nd port.
1458 *port_separator++ = 0;
1459 int console_port = strtol(port_spec, NULL, 0);
1460 int adb_port = strtol(port_separator, NULL, 0);
1461 if (!(console_port > 0 && adb_port > 0)) {
1462 *(port_separator - 1) = ',';
1463 snprintf(buffer, buffer_size,
1464 "Invalid port numbers: Expected positive numbers, got '%s'",
1465 port_spec);
1466 return;
1467 }
1468
1469 /* Check if the emulator is already known.
1470 * Note: There's a small but harmless race condition here: An emulator not
1471 * present just yet could be registered by another invocation right
1472 * after doing this check here. However, local_connect protects
1473 * against double-registration too. From here, a better error message
1474 * can be produced. In the case of the race condition, the very specific
1475 * error message won't be shown, but the data doesn't get corrupted. */
1476 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1477 if (known_emulator != NULL) {
1478 snprintf(buffer, buffer_size,
1479 "Emulator on port %d already registered.", adb_port);
1480 return;
1481 }
1482
1483 /* Check if more emulators can be registered. Similar unproblematic
1484 * race condition as above. */
1485 int candidate_slot = get_available_local_transport_index();
1486 if (candidate_slot < 0) {
1487 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1488 return;
1489 }
1490
1491 /* Preconditions met, try to connect to the emulator. */
1492 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1493 snprintf(buffer, buffer_size,
1494 "Connected to emulator on ports %d,%d", console_port, adb_port);
1495 } else {
1496 snprintf(buffer, buffer_size,
1497 "Could not connect to emulator on ports %d,%d",
1498 console_port, adb_port);
1499 }
1500}
1501#endif
1502
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001503int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1504{
1505 atransport *transport = NULL;
1506 char buf[4096];
1507
1508 if(!strcmp(service, "kill")) {
1509 fprintf(stderr,"adb server killed by remote request\n");
1510 fflush(stdout);
1511 adb_write(reply_fd, "OKAY", 4);
1512 usb_cleanup();
1513 exit(0);
1514 }
1515
1516#if ADB_HOST
1517 // "transport:" is used for switching transport with a specified serial number
1518 // "transport-usb:" is used for switching transport to the only USB transport
1519 // "transport-local:" is used for switching transport to the only local transport
1520 // "transport-any:" is used for switching transport to the only transport
1521 if (!strncmp(service, "transport", strlen("transport"))) {
1522 char* error_string = "unknown failure";
1523 transport_type type = kTransportAny;
1524
1525 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1526 type = kTransportUsb;
1527 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1528 type = kTransportLocal;
1529 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1530 type = kTransportAny;
1531 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1532 service += strlen("transport:");
Tom Marlin851ee3a2011-07-27 12:56:14 -05001533 serial = service;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001534 }
1535
1536 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1537
1538 if (transport) {
1539 s->transport = transport;
1540 adb_write(reply_fd, "OKAY", 4);
1541 } else {
1542 sendfailmsg(reply_fd, error_string);
1543 }
1544 return 1;
1545 }
1546
1547 // return a list of all connected devices
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001548 if (!strncmp(service, "devices", 7)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001549 char buffer[4096];
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001550 int use_long = !strcmp(service+7, "-l");
1551 if (use_long || service[7] == 0) {
1552 memset(buf, 0, sizeof(buf));
1553 memset(buffer, 0, sizeof(buffer));
1554 D("Getting device list \n");
1555 list_transports(buffer, sizeof(buffer), use_long);
1556 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1557 D("Wrote device list \n");
1558 writex(reply_fd, buf, strlen(buf));
1559 return 0;
1560 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001561 }
1562
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001563 // add a new TCP transport, device or emulator
Mike Lockwoodb51ae572009-08-24 15:58:40 -07001564 if (!strncmp(service, "connect:", 8)) {
1565 char buffer[4096];
Mike Lockwoodb51ae572009-08-24 15:58:40 -07001566 char* host = service + 8;
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001567 if (!strncmp(host, "emu:", 4)) {
1568 connect_emulator(host + 4, buffer, sizeof(buffer));
1569 } else {
1570 connect_device(host, buffer, sizeof(buffer));
Mike Lockwoodb51ae572009-08-24 15:58:40 -07001571 }
Stefan Hilzinger1ec03422010-04-26 10:17:43 +01001572 // Send response for emulator and device
Mike Lockwood5f2c4a12009-10-11 23:04:18 -04001573 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1574 writex(reply_fd, buf, strlen(buf));
1575 return 0;
1576 }
1577
1578 // remove TCP transport
1579 if (!strncmp(service, "disconnect:", 11)) {
1580 char buffer[4096];
1581 memset(buffer, 0, sizeof(buffer));
1582 char* serial = service + 11;
Mike Lockwood01c2c302010-05-24 10:44:35 -04001583 if (serial[0] == 0) {
1584 // disconnect from all TCP devices
1585 unregister_all_tcp_transports();
Mike Lockwood5f2c4a12009-10-11 23:04:18 -04001586 } else {
Mike Lockwood01c2c302010-05-24 10:44:35 -04001587 char hostbuf[100];
1588 // assume port 5555 if no port is specified
1589 if (!strchr(serial, ':')) {
1590 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1591 serial = hostbuf;
1592 }
1593 atransport *t = find_transport(serial);
1594
1595 if (t) {
1596 unregister_transport(t);
1597 } else {
1598 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1599 }
Mike Lockwood5f2c4a12009-10-11 23:04:18 -04001600 }
1601
1602 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
Mike Lockwoodb51ae572009-08-24 15:58:40 -07001603 writex(reply_fd, buf, strlen(buf));
1604 return 0;
1605 }
1606
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001607 // returns our value for ADB_SERVER_VERSION
1608 if (!strcmp(service, "version")) {
1609 char version[12];
1610 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1611 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1612 writex(reply_fd, buf, strlen(buf));
1613 return 0;
1614 }
1615
1616 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1617 char *out = "unknown";
1618 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1619 if (transport && transport->serial) {
1620 out = transport->serial;
1621 }
1622 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1623 writex(reply_fd, buf, strlen(buf));
1624 return 0;
1625 }
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001626 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1627 char *out = "unknown";
1628 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1629 if (transport && transport->devpath) {
1630 out = transport->devpath;
1631 }
1632 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1633 writex(reply_fd, buf, strlen(buf));
1634 return 0;
1635 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001636 // indicates a new emulator instance has started
1637 if (!strncmp(service,"emulator:",9)) {
1638 int port = atoi(service+9);
1639 local_connect(port);
1640 /* we don't even need to send a reply */
1641 return 0;
1642 }
1643#endif // ADB_HOST
1644
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001645 if(!strcmp(service,"list-forward")) {
1646 // Create the list of forward redirections.
1647 char header[9];
1648 int buffer_size = format_listeners(NULL, 0);
1649 // Add one byte for the trailing zero.
1650 char* buffer = malloc(buffer_size+1);
1651 (void) format_listeners(buffer, buffer_size+1);
1652 snprintf(header, sizeof header, "OKAY%04x", buffer_size);
1653 writex(reply_fd, header, 8);
1654 writex(reply_fd, buffer, buffer_size);
1655 free(buffer);
1656 return 0;
1657 }
1658
1659 if (!strcmp(service,"killforward-all")) {
1660 remove_all_listeners();
1661 adb_write(reply_fd, "OKAYOKAY", 8);
1662 return 0;
1663 }
1664
1665 if(!strncmp(service,"forward:",8) ||
1666 !strncmp(service,"killforward:",12)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001667 char *local, *remote, *err;
1668 int r;
1669 atransport *transport;
1670
1671 int createForward = strncmp(service,"kill",4);
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001672 int no_rebind = 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001673
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001674 local = strchr(service, ':') + 1;
1675
1676 // Handle forward:norebind:<local>... here
1677 if (createForward && !strncmp(local, "norebind:", 9)) {
1678 no_rebind = 1;
1679 local = strchr(local, ':') + 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001680 }
1681
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001682 remote = strchr(local,';');
1683
1684 if (createForward) {
1685 // Check forward: parameter format: '<local>;<remote>'
1686 if(remote == 0) {
1687 sendfailmsg(reply_fd, "malformed forward spec");
1688 return 0;
1689 }
1690
1691 *remote++ = 0;
1692 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1693 sendfailmsg(reply_fd, "malformed forward spec");
1694 return 0;
1695 }
1696 } else {
1697 // Check killforward: parameter format: '<local>'
1698 if (local[0] == 0) {
1699 sendfailmsg(reply_fd, "malformed forward spec");
1700 return 0;
1701 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001702 }
1703
1704 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1705 if (!transport) {
1706 sendfailmsg(reply_fd, err);
1707 return 0;
1708 }
1709
1710 if (createForward) {
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001711 r = install_listener(local, remote, transport, no_rebind);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001712 } else {
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001713 r = remove_listener(local, transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001714 }
1715 if(r == 0) {
1716 /* 1st OKAY is connect, 2nd OKAY is status */
1717 writex(reply_fd, "OKAYOKAY", 8);
1718 return 0;
1719 }
1720
1721 if (createForward) {
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001722 const char* message;
1723 switch (r) {
1724 case INSTALL_STATUS_CANNOT_BIND:
1725 message = "cannot bind to socket";
1726 break;
1727 case INSTALL_STATUS_CANNOT_REBIND:
1728 message = "cannot rebind existing socket";
1729 break;
1730 default:
1731 message = "internal error";
1732 }
1733 sendfailmsg(reply_fd, message);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001734 } else {
1735 sendfailmsg(reply_fd, "cannot remove listener");
1736 }
1737 return 0;
1738 }
1739
1740 if(!strncmp(service,"get-state",strlen("get-state"))) {
1741 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1742 char *state = connection_state_name(transport);
1743 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1744 writex(reply_fd, buf, strlen(buf));
1745 return 0;
1746 }
1747 return -1;
1748}
1749
1750#if !ADB_HOST
1751int recovery_mode = 0;
1752#endif
1753
1754int main(int argc, char **argv)
1755{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001756#if ADB_HOST
1757 adb_sysdeps_init();
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001758 adb_trace_init();
1759 D("Handling commandline()\n");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001760 return adb_commandline(argc - 1, argv + 1);
1761#else
Vladimir Chtchetkine32a15712012-02-27 10:41:53 -08001762 /* If adbd runs inside the emulator this will enable adb tracing via
1763 * adb-debug qemud service in the emulator. */
1764 adb_qemu_trace_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001765 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1766 adb_device_banner = "recovery";
1767 recovery_mode = 1;
1768 }
Mike Lockwood4ac1e282009-05-25 18:17:55 -04001769
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001770 start_device_log();
JP Abgrall2e5dd6e2011-03-16 15:57:42 -07001771 D("Handling main()\n");
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001772 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001773#endif
1774}