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