blob: 82efb12b592cd98607658df699994dfebc154447 [file] [log] [blame]
rjw2e8229f2022-02-15 21:08:12 +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>
24#include <stddef.h>
25#include <string.h>
26#include <time.h>
27#include <sys/time.h>
28#include <stdint.h>
29#include <grp.h> //For setgroups
30
31#include "sysdeps.h"
32#include "adb.h"
33#include "adb_auth.h"
34#include "transport_pcie.h"
35
36#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
37
38#if !ADB_HOST
39#include <cutils/properties.h>
40#include <private/android_filesystem_config.h>
41//#include <sys/capability.h>
42#include <sys/mount.h>
43#include <sys/prctl.h>
44#include <getopt.h>
45//#include <selinux/selinux.h>
46#endif
47
48#if ADB_TRACE
49ADB_MUTEX_DEFINE( D_lock );
50#endif
51
52int HOST = 0;
53int gListenAll = 0;
54
55static int auth_enabled = 0;
56
57#if !ADB_HOST
58static const char *adb_device_banner = "device";
59static const char *root_seclabel = NULL;
60#endif
61
62void fatal(const char *fmt, ...)
63{
64 va_list ap;
65 va_start(ap, fmt);
66 fprintf(stderr, "error: ");
67 vfprintf(stderr, fmt, ap);
68 fprintf(stderr, "\n");
69 va_end(ap);
70 exit(-1);
71}
72
73void fatal_errno(const char *fmt, ...)
74{
75 va_list ap;
76 va_start(ap, fmt);
77 fprintf(stderr, "error: %s: ", strerror(errno));
78 vfprintf(stderr, fmt, ap);
79 fprintf(stderr, "\n");
80 va_end(ap);
81 exit(-1);
82}
83
84int adb_trace_mask;
85
86/* read a comma/space/colum/semi-column separated list of tags
87 * from the ADB_TRACE environment variable and build the trace
88 * mask from it. note that '1' and 'all' are special cases to
89 * enable all tracing
90 */
91void adb_trace_init(void)
92{
93 const char* p = getenv("ADB_TRACE");
94 const char* q;
95
96 static const struct {
97 const char* tag;
98 int flag;
99 } tags[] = {
100 { "1", 0 },
101 { "all", 0 },
102 { "adb", TRACE_ADB },
103 { "sockets", TRACE_SOCKETS },
104 { "packets", TRACE_PACKETS },
105 { "rwx", TRACE_RWX },
106 { "usb", TRACE_USB },
107 { "sync", TRACE_SYNC },
108 { "sysdeps", TRACE_SYSDEPS },
109 { "transport", TRACE_TRANSPORT },
110 { "jdwp", TRACE_JDWP },
111 { "services", TRACE_SERVICES },
112 { "auth", TRACE_AUTH },
113 { NULL, 0 }
114 };
115
116 if (p == NULL)
117 return;
118
119 /* use a comma/column/semi-colum/space separated list */
120 while (*p) {
121 int len, tagn;
122
123 q = strpbrk(p, " ,:;");
124 if (q == NULL) {
125 q = p + strlen(p);
126 }
127 len = q - p;
128
129 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
130 {
131 int taglen = strlen(tags[tagn].tag);
132
133 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
134 {
135 int flag = tags[tagn].flag;
136 if (flag == 0) {
137 adb_trace_mask = ~0;
138 return;
139 }
140 adb_trace_mask |= (1 << flag);
141 break;
142 }
143 }
144 p = q;
145 if (*p)
146 p++;
147 }
148}
149
150#if !ADB_HOST && !ADB_NON_ANDROID
151/*
152 * Implements ADB tracing inside the emulator.
153 */
154
155#include <stdarg.h>
156
157/*
158 * Redefine open and write for qemu_pipe.h that contains inlined references
159 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
160 */
161
162#undef open
163#undef write
164#define open adb_open
165#define write adb_write
166#include <hardware/qemu_pipe.h>
167#undef open
168#undef write
169#define open ___xxx_open
170#define write ___xxx_write
171
172/* A handle to adb-debug qemud service in the emulator. */
173int adb_debug_qemu = -1;
174
175/* Initializes connection with the adb-debug qemud service in the emulator. */
176static int adb_qemu_trace_init(void)
177{
178 char con_name[32];
179
180 if (adb_debug_qemu >= 0) {
181 return 0;
182 }
183
184 /* adb debugging QEMUD service connection request. */
185 snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
186 adb_debug_qemu = qemu_pipe_open(con_name);
187 return (adb_debug_qemu >= 0) ? 0 : -1;
188}
189
190void adb_qemu_trace(const char* fmt, ...)
191{
192 va_list args;
193 va_start(args, fmt);
194 char msg[1024];
195
196 if (adb_debug_qemu >= 0) {
197 vsnprintf(msg, sizeof(msg), fmt, args);
198 adb_write(adb_debug_qemu, msg, strlen(msg));
199 }
200}
201#endif /* !ADB_HOST */
202
203apacket *get_apacket(void)
204{
205 apacket *p = malloc(sizeof(apacket));
206 if(p == 0) fatal("failed to allocate an apacket");
207 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
208 return p;
209}
210
211void put_apacket(apacket *p)
212{
213 free(p);
214}
215
216void handle_online(atransport *t)
217{
218 D("adb: online\n");
219 t->online = 1;
220#if ADB_HOST && ADB_OVER_PCIE
221#endif
222}
223
224void handle_offline(atransport *t)
225{
226 D("adb: offline\n");
227 //Close the associated usb
228 t->online = 0;
229 run_transport_disconnects(t);
230}
231
232#if DEBUG_PACKETS
233#define DUMPMAX 32
234void print_packet(const char *label, apacket *p)
235{
236 char *tag;
237 char *x;
238 unsigned count;
239
240 switch(p->msg.command){
241 case A_SYNC: tag = "SYNC"; break;
242 case A_CNXN: tag = "CNXN" ; break;
243 case A_OPEN: tag = "OPEN"; break;
244 case A_OKAY: tag = "OKAY"; break;
245 case A_CLSE: tag = "CLSE"; break;
246 case A_WRTE: tag = "WRTE"; break;
247 case A_AUTH: tag = "AUTH"; break;
248 default: tag = "????"; break;
249 }
250
251 fprintf(stderr, "%s: %s %08x %08x %04x \"",
252 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
253 count = p->msg.data_length;
254 x = (char*) p->data;
255 if(count > DUMPMAX) {
256 count = DUMPMAX;
257 tag = "\n";
258 } else {
259 tag = "\"\n";
260 }
261 while(count-- > 0){
262 if((*x >= ' ') && (*x < 127)) {
263 fputc(*x, stderr);
264 } else {
265 fputc('.', stderr);
266 }
267 x++;
268 }
269 fputs(tag, stderr);
270}
271#endif
272
273static void send_ready(unsigned local, unsigned remote, atransport *t)
274{
275 D("Calling send_ready \n");
276 apacket *p = get_apacket();
277 p->msg.command = A_OKAY;
278 p->msg.arg0 = local;
279 p->msg.arg1 = remote;
280 send_packet(p, t);
281}
282
283static void send_close(unsigned local, unsigned remote, atransport *t)
284{
285 D("Calling send_close \n");
286 apacket *p = get_apacket();
287 p->msg.command = A_CLSE;
288 p->msg.arg0 = local;
289 p->msg.arg1 = remote;
290 send_packet(p, t);
291}
292
293#if (!ADB_HOST && ADB_OVER_PCIE)
294static size_t fill_connect_data(atransport *t, char *buf, size_t bufsize)
295{
296 struct pcie_info *info;
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
304 if (t->pcie && t->pcie->info) {
305 info = t->pcie->info;
306 D("device: 0x%x\n", info->device);
307 D("vendor: 0x%x\n", info->vendor);
308 D("class: 0x%x\n", info->class);
309
310 len = snprintf(buf, remaining, "device=%x;vendor=%x;class=%x;",
311 info->device, info->vendor, info->class);
312 remaining -= len;
313 buf += len;
314 }
315
316 return bufsize - remaining + 1;
317}
318#else
319
320#if !ADB_HOST
321static const char *cnxn_props[] = {
322 "ro.product.name",
323 "ro.product.model",
324 "ro.product.device",
325};
326#endif
327
328static size_t fill_connect_data(char *buf, size_t bufsize)
329{
330#if ADB_HOST
331 return snprintf(buf, bufsize, "host::") + 1;
332#else
333 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
334 int i;
335 size_t remaining = bufsize;
336 size_t len;
337
338 len = snprintf(buf, remaining, "%s::", adb_device_banner);
339 remaining -= len;
340 buf += len;
341 for (i = 0; i < num_cnxn_props; i++) {
342 char value[PROPERTY_VALUE_MAX];
343 property_get(cnxn_props[i], value, "");
344 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
345 remaining -= len;
346 buf += len;
347 }
348
349 return bufsize - remaining + 1;
350#endif
351}
352#endif /* ADB_OVER_PCIE */
353
354#if !ADB_HOST
355static void send_msg_with_header(int fd, const char* msg, size_t msglen) {
356 char header[5];
357 if (msglen > 0xffff)
358 msglen = 0xffff;
359 snprintf(header, sizeof(header), "%04x", (unsigned)msglen);
360 writex(fd, header, 4);
361 writex(fd, msg, msglen);
362}
363#endif
364
365#if ADB_HOST
366static void send_msg_with_okay(int fd, const char* msg, size_t msglen) {
367 char header[9];
368 if (msglen > 0xffff)
369 msglen = 0xffff;
370 snprintf(header, sizeof(header), "OKAY%04x", (unsigned)msglen);
371 writex(fd, header, 8);
372 writex(fd, msg, msglen);
373}
374#endif // ADB_HOST
375
376static void send_connect(atransport *t)
377{
378 D("Calling send_connect \n");
379 apacket *cp = get_apacket();
380 cp->msg.command = A_CNXN;
381 cp->msg.arg0 = A_VERSION;
382 cp->msg.arg1 = MAX_PAYLOAD;
383#if (!ADB_HOST && ADB_OVER_PCIE)
384 cp->msg.data_length = fill_connect_data(t, (char *)cp->data,
385 sizeof(cp->data));
386#else
387 cp->msg.data_length = fill_connect_data((char *)cp->data,
388 sizeof(cp->data));
389#endif
390 send_packet(cp, t);
391}
392
393void send_auth_request(atransport *t)
394{
395 D("Calling send_auth_request\n");
396 apacket *p;
397 int ret;
398
399 ret = adb_auth_generate_token(t->token, sizeof(t->token));
400 if (ret != sizeof(t->token)) {
401 D("Error generating token ret=%d\n", ret);
402 return;
403 }
404
405 p = get_apacket();
406 memcpy(p->data, t->token, ret);
407 p->msg.command = A_AUTH;
408 p->msg.arg0 = ADB_AUTH_TOKEN;
409 p->msg.data_length = ret;
410 send_packet(p, t);
411}
412
413static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
414{
415 D("Calling send_auth_response\n");
416 apacket *p = get_apacket();
417 int ret;
418
419 ret = adb_auth_sign(t->key, token, token_size, p->data);
420 if (!ret) {
421 D("Error signing the token\n");
422 put_apacket(p);
423 return;
424 }
425
426 p->msg.command = A_AUTH;
427 p->msg.arg0 = ADB_AUTH_SIGNATURE;
428 p->msg.data_length = ret;
429 send_packet(p, t);
430}
431
432static void send_auth_publickey(atransport *t)
433{
434 D("Calling send_auth_publickey\n");
435 apacket *p = get_apacket();
436 int ret;
437
438 ret = adb_auth_get_userkey(p->data, sizeof(p->data));
439 if (!ret) {
440 D("Failed to get user public key\n");
441 put_apacket(p);
442 return;
443 }
444
445 p->msg.command = A_AUTH;
446 p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
447 p->msg.data_length = ret;
448 send_packet(p, t);
449}
450
451void adb_auth_verified(atransport *t)
452{
453 handle_online(t);
454 send_connect(t);
455}
456
457#if ADB_HOST
458static char *connection_state_name(atransport *t)
459{
460 if (t == NULL) {
461 return "unknown";
462 }
463
464 switch(t->connection_state) {
465 case CS_BOOTLOADER:
466 return "bootloader";
467 case CS_DEVICE:
468 return "device";
469 case CS_RECOVERY:
470 return "recovery";
471 case CS_SIDELOAD:
472 return "sideload";
473 case CS_OFFLINE:
474 return "offline";
475 case CS_UNAUTHORIZED:
476 return "unauthorized";
477 default:
478 return "unknown";
479 }
480}
481#endif // ADB_HOST
482
483/* qual_overwrite is used to overwrite a qualifier string. dst is a
484 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
485 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
486 */
487static void qual_overwrite(char **dst, const char *src)
488{
489 if (!dst)
490 return;
491
492 free(*dst);
493 *dst = NULL;
494
495 if (!src || !*src)
496 return;
497
498 *dst = strdup(src);
499}
500
501void parse_banner(char *banner, atransport *t)
502{
503 static const char *prop_seps = ";";
504 static const char key_val_sep = '=';
505 char *cp;
506 char *type;
507
508 D("parse_banner: %s\n", banner);
509 type = banner;
510 cp = strchr(type, ':');
511 if (cp) {
512 *cp++ = 0;
513 /* Nothing is done with second field. */
514 cp = strchr(cp, ':');
515 if (cp) {
516#if ADB_OVER_PCIE
517 static const char *dev_info[] = {
518 "device",
519 "vendor",
520 "class",
521 };
522
523 char *save;
524 char *key;
525 key = adb_strtok_r(cp + 1, prop_seps, &save);
526 while (key) {
527 cp = strchr(key, key_val_sep);
528 if (cp) {
529 *cp++ = '\0';
530 if (!strcmp(key, dev_info[0]))
531 t->device = cp;
532 else if (!strcmp(key, dev_info[1]))
533 t->product = cp;
534 else if (!strcmp(key, dev_info[2]))
535 t->serial = cp;
536 }
537 key = adb_strtok_r(NULL, prop_seps, &save);
538 }
539#else
540 static const char **dev_info = cnxn_props;
541 char *save;
542 char *key;
543 key = adb_strtok_r(cp + 1, prop_seps, &save);
544 while (key) {
545 cp = strchr(key, key_val_sep);
546 if (cp) {
547 *cp++ = '\0';
548 if (!strcmp(key, dev_info[0]))
549 qual_overwrite(&t->product, cp);
550 else if (!strcmp(key, dev_info[1]))
551 qual_overwrite(&t->model, cp);
552 else if (!strcmp(key, dev_info[2]))
553 qual_overwrite(&t->device, cp);
554 }
555 key = adb_strtok_r(NULL, prop_seps, &save);
556 }
557#endif
558 }
559 }
560
561 if(!strcmp(type, "bootloader")){
562 D("setting connection_state to CS_BOOTLOADER\n");
563 t->connection_state = CS_BOOTLOADER;
564 update_transports();
565 return;
566 }
567
568 if(!strcmp(type, "device")) {
569 D("setting connection_state to CS_DEVICE\n");
570 t->connection_state = CS_DEVICE;
571 update_transports();
572 return;
573 }
574
575 if(!strcmp(type, "recovery")) {
576 D("setting connection_state to CS_RECOVERY\n");
577 t->connection_state = CS_RECOVERY;
578 update_transports();
579 return;
580 }
581
582 if(!strcmp(type, "sideload")) {
583 D("setting connection_state to CS_SIDELOAD\n");
584 t->connection_state = CS_SIDELOAD;
585 update_transports();
586 return;
587 }
588
589 t->connection_state = CS_HOST;
590}
591
592void handle_packet(apacket *p, atransport *t)
593{
594 asocket *s;
595
596 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
597 ((char*) (&(p->msg.command)))[1],
598 ((char*) (&(p->msg.command)))[2],
599 ((char*) (&(p->msg.command)))[3]);
600 print_packet("recv", p);
601
602 switch(p->msg.command){
603 case A_SYNC:
604 if(p->msg.arg0){
605 send_packet(p, t);
606 if(HOST) send_connect(t);
607 } else {
608 t->connection_state = CS_OFFLINE;
609 handle_offline(t);
610 send_packet(p, t);
611 }
612 return;
613
614 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
615 /* XXX verify version, etc */
616 if(t->connection_state != CS_OFFLINE) {
617 t->connection_state = CS_OFFLINE;
618 handle_offline(t);
619 }
620
621 parse_banner((char*) p->data, t);
622
623 if (HOST || !auth_enabled) {
624 handle_online(t);
625 if(!HOST) send_connect(t);
626 } else {
627 send_auth_request(t);
628 }
629 break;
630
631 case A_AUTH:
632 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
633 t->connection_state = CS_UNAUTHORIZED;
634 t->key = adb_auth_nextkey(t->key);
635 if (t->key) {
636 send_auth_response(p->data, p->msg.data_length, t);
637 } else {
638 /* No more private keys to try, send the public key */
639 send_auth_publickey(t);
640 }
641 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
642 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
643 adb_auth_verified(t);
644 t->failed_auth_attempts = 0;
645 } else {
646 if (t->failed_auth_attempts++ > 10)
647 adb_sleep_ms(1000);
648 send_auth_request(t);
649 }
650 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
651 adb_auth_confirm_key(p->data, p->msg.data_length, t);
652 }
653 break;
654
655 case A_OPEN: /* OPEN(local-id, 0, "destination") */
656 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
657 char *name = (char*) p->data;
658 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
659 s = create_local_service_socket(name);
660 if(s == 0) {
661 send_close(0, p->msg.arg0, t);
662 } else {
663 s->peer = create_remote_socket(p->msg.arg0, t);
664 s->peer->peer = s;
665 send_ready(s->id, s->peer->id, t);
666 s->ready(s);
667 }
668 }
669 break;
670
671 case A_OKAY: /* READY(local-id, remote-id, "") */
672 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
673 if((s = find_local_socket(p->msg.arg1, 0))) {
674 if(s->peer == 0) {
675 /* On first READY message, create the connection. */
676 s->peer = create_remote_socket(p->msg.arg0, t);
677 s->peer->peer = s;
678 s->ready(s);
679 } else if (s->peer->id == p->msg.arg0) {
680 /* Other READY messages must use the same local-id */
681 s->ready(s);
682 } else {
683 D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s\n",
684 p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
685 }
686 }
687 }
688 break;
689
690 case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
691 if (t->online && p->msg.arg1 != 0) {
692 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
693 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
694 * a failed OPEN only. However, due to a bug in previous ADB
695 * versions, CLOSE(0, remote-id, "") was also used for normal
696 * CLOSE() operations.
697 *
698 * This is bad because it means a compromised adbd could
699 * send packets to close connections between the host and
700 * other devices. To avoid this, only allow this if the local
701 * socket has a peer on the same transport.
702 */
703 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
704 D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s\n",
705 p->msg.arg1, t->serial, s->peer->transport->serial);
706 } else {
707 s->close(s);
708 }
709 }
710 }
711 break;
712
713 case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
714 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
715 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
716 unsigned rid = p->msg.arg0;
717 p->len = p->msg.data_length;
718
719 if(s->enqueue(s, p) == 0) {
720 D("Enqueue the socket\n");
721 send_ready(s->id, rid, t);
722 }
723 return;
724 }
725 }
726 break;
727
728 default:
729 printf("handle_packet: what is %08x?!\n", p->msg.command);
730 }
731
732 put_apacket(p);
733}
734
735alistener listener_list = {
736 .next = &listener_list,
737 .prev = &listener_list,
738};
739
740static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
741{
742 asocket *s;
743
744 if(ev & FDE_READ) {
745 struct sockaddr addr;
746 socklen_t alen;
747 int fd;
748
749 alen = sizeof(addr);
750 fd = adb_socket_accept(_fd, &addr, &alen);
751 if(fd < 0) return;
752
753 adb_socket_setbufsize(fd, CHUNK_SIZE);
754
755 s = create_local_socket(fd);
756 if(s) {
757 connect_to_smartsocket(s);
758 return;
759 }
760
761 adb_close(fd);
762 }
763}
764
765static void listener_event_func(int _fd, unsigned ev, void *_l)
766{
767 alistener *l = _l;
768 asocket *s;
769
770 if(ev & FDE_READ) {
771 struct sockaddr addr;
772 socklen_t alen;
773 int fd;
774
775 alen = sizeof(addr);
776 fd = adb_socket_accept(_fd, &addr, &alen);
777 if(fd < 0) return;
778
779 s = create_local_socket(fd);
780 if(s) {
781 s->transport = l->transport;
782 connect_to_remote(s, l->connect_to);
783 return;
784 }
785
786 adb_close(fd);
787 }
788}
789
790static void free_listener(alistener* l)
791{
792 if (l->next) {
793 l->next->prev = l->prev;
794 l->prev->next = l->next;
795 l->next = l->prev = l;
796 }
797
798 // closes the corresponding fd
799 fdevent_remove(&l->fde);
800
801 if (l->local_name)
802 free((char*)l->local_name);
803
804 if (l->connect_to)
805 free((char*)l->connect_to);
806
807 if (l->transport) {
808 remove_transport_disconnect(l->transport, &l->disconnect);
809 }
810 free(l);
811}
812
813static void listener_disconnect(void* _l, atransport* t)
814{
815 alistener* l = _l;
816
817 free_listener(l);
818}
819
820int local_name_to_fd(const char *name)
821{
822 int port;
823
824 if(!strncmp("tcp:", name, 4)){
825 int ret;
826 port = atoi(name + 4);
827
828 if (gListenAll > 0) {
829 ret = socket_inaddr_any_server(port, SOCK_STREAM);
830 } else {
831 ret = socket_loopback_server(port, SOCK_STREAM);
832 }
833
834 return ret;
835 }
836#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
837 // It's non-sensical to support the "reserved" space on the adb host side
838 if(!strncmp(name, "local:", 6)) {
839 return socket_local_server(name + 6,
840 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
841 } else if(!strncmp(name, "localabstract:", 14)) {
842 return socket_local_server(name + 14,
843 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
844 } else if(!strncmp(name, "localfilesystem:", 16)) {
845 return socket_local_server(name + 16,
846 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
847 }
848
849#endif
850 printf("unknown local portname '%s'\n", name);
851 return -1;
852}
853
854// Write a single line describing a listener to a user-provided buffer.
855// Appends a trailing zero, even in case of truncation, but the function
856// returns the full line length.
857// If |buffer| is NULL, does not write but returns required size.
858static int format_listener(alistener* l, char* buffer, size_t buffer_len) {
859 // Format is simply:
860 //
861 // <device-serial> " " <local-name> " " <remote-name> "\n"
862 //
863 int local_len = strlen(l->local_name);
864 int connect_len = strlen(l->connect_to);
865 int serial_len = strlen(l->transport->serial);
866
867 if (buffer != NULL) {
868 snprintf(buffer, buffer_len, "%s %s %s\n",
869 l->transport->serial, l->local_name, l->connect_to);
870 }
871 // NOTE: snprintf() on Windows returns -1 in case of truncation, so
872 // return the computed line length instead.
873 return local_len + connect_len + serial_len + 3;
874}
875
876// Write the list of current listeners (network redirections) into a
877// user-provided buffer. Appends a trailing zero, even in case of
878// trunctaion, but return the full size in bytes.
879// If |buffer| is NULL, does not write but returns required size.
880static int format_listeners(char* buf, size_t buflen)
881{
882 alistener* l;
883 int result = 0;
884 for (l = listener_list.next; l != &listener_list; l = l->next) {
885 // Ignore special listeners like those for *smartsocket*
886 if (l->connect_to[0] == '*')
887 continue;
888 int len = format_listener(l, buf, buflen);
889 // Ensure there is space for the trailing zero.
890 result += len;
891 if (buf != NULL) {
892 buf += len;
893 buflen -= len;
894 if (buflen <= 0)
895 break;
896 }
897 }
898 return result;
899}
900
901static int remove_listener(const char *local_name, atransport* transport)
902{
903 alistener *l;
904
905 for (l = listener_list.next; l != &listener_list; l = l->next) {
906 if (!strcmp(local_name, l->local_name)) {
907 listener_disconnect(l, l->transport);
908 return 0;
909 }
910 }
911 return -1;
912}
913
914static void remove_all_listeners(void)
915{
916 alistener *l, *l_next;
917 for (l = listener_list.next; l != &listener_list; l = l_next) {
918 l_next = l->next;
919 // Never remove smart sockets.
920 if (l->connect_to[0] == '*')
921 continue;
922 listener_disconnect(l, l->transport);
923 }
924}
925
926// error/status codes for install_listener.
927typedef enum {
928 INSTALL_STATUS_OK = 0,
929 INSTALL_STATUS_INTERNAL_ERROR = -1,
930 INSTALL_STATUS_CANNOT_BIND = -2,
931 INSTALL_STATUS_CANNOT_REBIND = -3,
932} install_status_t;
933
934static install_status_t install_listener(const char *local_name,
935 const char *connect_to,
936 atransport* transport,
937 int no_rebind)
938{
939 alistener *l;
940
941 //printf("install_listener('%s','%s')\n", local_name, connect_to);
942
943 for(l = listener_list.next; l != &listener_list; l = l->next){
944 if(strcmp(local_name, l->local_name) == 0) {
945 char *cto;
946
947 /* can't repurpose a smartsocket */
948 if(l->connect_to[0] == '*') {
949 return INSTALL_STATUS_INTERNAL_ERROR;
950 }
951
952 /* can't repurpose a listener if 'no_rebind' is true */
953 if (no_rebind) {
954 return INSTALL_STATUS_CANNOT_REBIND;
955 }
956
957 cto = strdup(connect_to);
958 if(cto == 0) {
959 return INSTALL_STATUS_INTERNAL_ERROR;
960 }
961
962 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
963 free((void*) l->connect_to);
964 l->connect_to = cto;
965 if (l->transport != transport) {
966 remove_transport_disconnect(l->transport, &l->disconnect);
967 l->transport = transport;
968 add_transport_disconnect(l->transport, &l->disconnect);
969 }
970 return INSTALL_STATUS_OK;
971 }
972 }
973
974 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
975 if((l->local_name = strdup(local_name)) == 0) goto nomem;
976 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
977
978
979 l->fd = local_name_to_fd(local_name);
980 if(l->fd < 0) {
981 free((void*) l->local_name);
982 free((void*) l->connect_to);
983 free(l);
984 printf("cannot bind '%s'\n", local_name);
985 return -2;
986 }
987
988 close_on_exec(l->fd);
989 if(!strcmp(l->connect_to, "*smartsocket*")) {
990 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
991 } else {
992 fdevent_install(&l->fde, l->fd, listener_event_func, l);
993 }
994 fdevent_set(&l->fde, FDE_READ);
995
996 l->next = &listener_list;
997 l->prev = listener_list.prev;
998 l->next->prev = l;
999 l->prev->next = l;
1000 l->transport = transport;
1001
1002 if (transport) {
1003 l->disconnect.opaque = l;
1004 l->disconnect.func = listener_disconnect;
1005 add_transport_disconnect(transport, &l->disconnect);
1006 }
1007 return INSTALL_STATUS_OK;
1008
1009nomem:
1010 fatal("cannot allocate listener");
1011 return INSTALL_STATUS_INTERNAL_ERROR;
1012}
1013
1014#if defined(_WIN32)
1015static BOOL WINAPI ctrlc_handler(DWORD type)
1016{
1017 exit(STATUS_CONTROL_C_EXIT);
1018 return TRUE;
1019}
1020#endif
1021
1022static void adb_cleanup(void)
1023{
1024#ifndef ADB_OVER_PCIE
1025 usb_cleanup();
1026#endif
1027}
1028
1029void start_logging(void)
1030{
1031#if defined(_WIN32)
1032 char temp[ MAX_PATH ];
1033 FILE* fnul;
1034 FILE* flog;
1035
1036 GetTempPath( sizeof(temp) - 8, temp );
1037 strcat( temp, "adb.log" );
1038
1039 /* Win32 specific redirections */
1040 fnul = fopen( "NUL", "rt" );
1041 if (fnul != NULL)
1042 stdin[0] = fnul[0];
1043
1044 flog = fopen( temp, "at" );
1045 if (flog == NULL)
1046 flog = fnul;
1047
1048 setvbuf( flog, NULL, _IONBF, 0 );
1049
1050 stdout[0] = flog[0];
1051 stderr[0] = flog[0];
1052 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
1053#else
1054 int fd;
1055
1056 fd = unix_open("/dev/null", O_RDONLY);
1057 dup2(fd, 0);
1058 adb_close(fd);
1059
1060 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1061 if(fd < 0) {
1062 fd = unix_open("/dev/null", O_WRONLY);
1063 }
1064 dup2(fd, 1);
1065 dup2(fd, 2);
1066 adb_close(fd);
1067 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
1068#endif
1069}
1070
1071#if !ADB_HOST
1072void start_device_log(void)
1073{
1074 int fd;
1075 char path[PATH_MAX];
1076 struct tm now;
1077 time_t t;
1078 char value[PROPERTY_VALUE_MAX];
1079
1080 // read the trace mask from persistent property persist.adb.trace_mask
1081 // give up if the property is not set or cannot be parsed
1082 property_get("persist.adb.trace_mask", value, "");
1083 if (sscanf(value, "%x", &adb_trace_mask) != 1)
1084 return;
1085
1086 adb_mkdir("/tmp/adb", 0775);
1087 tzset();
1088 time(&t);
1089 localtime_r(&t, &now);
1090 strftime(path, sizeof(path),
1091 "/tmp/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
1092 &now);
1093 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1094 if (fd < 0)
1095 return;
1096
1097 // redirect stdout and stderr to the log file
1098 dup2(fd, 1);
1099 dup2(fd, 2);
1100 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
1101 adb_close(fd);
1102
1103 fd = unix_open("/dev/null", O_RDONLY);
1104 dup2(fd, 0);
1105 adb_close(fd);
1106}
1107#endif
1108
1109#if ADB_HOST
1110
1111#ifdef WORKAROUND_BUG6558362
1112#include <sched.h>
1113#define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
1114void adb_set_affinity(void)
1115{
1116 cpu_set_t cpu_set;
1117 const char* cpunum_str = getenv(AFFINITY_ENVVAR);
1118 char* strtol_res;
1119 int cpu_num;
1120
1121 if (!cpunum_str || !*cpunum_str)
1122 return;
1123 cpu_num = strtol(cpunum_str, &strtol_res, 0);
1124 if (*strtol_res != '\0')
1125 fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
1126
1127 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1128 D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1129 CPU_ZERO(&cpu_set);
1130 CPU_SET(cpu_num, &cpu_set);
1131 sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
1132 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
1133 D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
1134}
1135#endif
1136
1137int launch_server(int server_port)
1138{
1139#if defined(_WIN32)
1140 /* we need to start the server in the background */
1141 /* we create a PIPE that will be used to wait for the server's "OK" */
1142 /* message since the pipe handles must be inheritable, we use a */
1143 /* security attribute */
1144 HANDLE pipe_read, pipe_write;
1145 HANDLE stdout_handle, stderr_handle;
1146 SECURITY_ATTRIBUTES sa;
1147 STARTUPINFO startup;
1148 PROCESS_INFORMATION pinfo;
1149 char program_path[ MAX_PATH ];
1150 int ret;
1151
1152 sa.nLength = sizeof(sa);
1153 sa.lpSecurityDescriptor = NULL;
1154 sa.bInheritHandle = TRUE;
1155
1156 /* create pipe, and ensure its read handle isn't inheritable */
1157 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1158 if (!ret) {
1159 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1160 return -1;
1161 }
1162
1163 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1164
1165 /* Some programs want to launch an adb command and collect its output by
1166 * calling CreateProcess with inheritable stdout/stderr handles, then
1167 * using read() to get its output. When this happens, the stdout/stderr
1168 * handles passed to the adb client process will also be inheritable.
1169 * When starting the adb server here, care must be taken to reset them
1170 * to non-inheritable.
1171 * Otherwise, something bad happens: even if the adb command completes,
1172 * the calling process is stuck while read()-ing from the stdout/stderr
1173 * descriptors, because they're connected to corresponding handles in the
1174 * adb server process (even if the latter never uses/writes to them).
1175 */
1176 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
1177 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
1178 if (stdout_handle != INVALID_HANDLE_VALUE) {
1179 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
1180 }
1181 if (stderr_handle != INVALID_HANDLE_VALUE) {
1182 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
1183 }
1184
1185 ZeroMemory( &startup, sizeof(startup) );
1186 startup.cb = sizeof(startup);
1187 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1188 startup.hStdOutput = pipe_write;
1189 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1190 startup.dwFlags = STARTF_USESTDHANDLES;
1191
1192 ZeroMemory( &pinfo, sizeof(pinfo) );
1193
1194 /* get path of current program */
1195 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1196
1197 ret = CreateProcess(
1198 program_path, /* program path */
1199 "adb fork-server server",
1200 /* the fork-server argument will set the
1201 debug = 2 in the child */
1202 NULL, /* process handle is not inheritable */
1203 NULL, /* thread handle is not inheritable */
1204 TRUE, /* yes, inherit some handles */
1205 DETACHED_PROCESS, /* the new process doesn't have a console */
1206 NULL, /* use parent's environment block */
1207 NULL, /* use parent's starting directory */
1208 &startup, /* startup info, i.e. std handles */
1209 &pinfo );
1210
1211 CloseHandle( pipe_write );
1212
1213 if (!ret) {
1214 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1215 CloseHandle( pipe_read );
1216 return -1;
1217 }
1218
1219 CloseHandle( pinfo.hProcess );
1220 CloseHandle( pinfo.hThread );
1221
1222 /* wait for the "OK\n" message */
1223 {
1224 char temp[3];
1225 DWORD count;
1226
1227 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1228 CloseHandle( pipe_read );
1229 if ( !ret ) {
1230 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
1231 return -1;
1232 }
1233 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1234 fprintf(stderr, "ADB server didn't ACK\n" );
1235 return -1;
1236 }
1237 }
1238#else /* !defined(_WIN32) */
1239 char path[PATH_MAX];
1240 int fd[2];
1241
1242 // set up a pipe so the child can tell us when it is ready.
1243 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1244 if (pipe(fd)) {
1245 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1246 return -1;
1247 }
1248 get_my_path(path, PATH_MAX);
1249 pid_t pid = fork();
1250 if(pid < 0) return -1;
1251
1252 if (pid == 0) {
1253 // child side of the fork
1254
1255 // redirect stderr to the pipe
1256 // we use stderr instead of stdout due to stdout's buffering behavior.
1257 adb_close(fd[0]);
1258 dup2(fd[1], STDERR_FILENO);
1259 adb_close(fd[1]);
1260
1261 char str_port[30];
1262 snprintf(str_port, sizeof(str_port), "%d", server_port);
1263 // child process
1264 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
1265 // this should not return
1266 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1267 } else {
1268 // parent side of the fork
1269
1270 char temp[3];
1271
1272 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1273 // wait for the "OK\n" message
1274 adb_close(fd[1]);
1275 int ret = adb_read(fd[0], temp, 3);
1276 int saved_errno = errno;
1277 adb_close(fd[0]);
1278 if (ret < 0) {
1279 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
1280 return -1;
1281 }
1282 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1283 fprintf(stderr, "ADB server didn't ACK\n" );
1284 return -1;
1285 }
1286
1287 setsid();
1288 }
1289#endif /* !defined(_WIN32) */
1290 return 0;
1291}
1292#endif /* ADB_HOST */
1293
1294/* Constructs a local name of form tcp:port.
1295 * target_str points to the target string, it's content will be overwritten.
1296 * target_size is the capacity of the target string.
1297 * server_port is the port number to use for the local name.
1298 */
1299void build_local_name(char* target_str, size_t target_size, int server_port)
1300{
1301 snprintf(target_str, target_size, "tcp:%d", server_port);
1302}
1303
1304#if !ADB_HOST
1305
1306static void drop_capabilities_bounding_set_if_needed() {
1307#ifdef ALLOW_ADBD_ROOT
1308 char value[PROPERTY_VALUE_MAX];
1309 property_get("ro.debuggable", value, "");
1310 if (strcmp(value, "1") == 0) {
1311 return;
1312 }
1313#endif
1314 int i;
1315 for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
1316 if (i == CAP_SETUID || i == CAP_SETGID) {
1317 // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
1318 continue;
1319 }
1320 int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
1321
1322 // Some kernels don't have file capabilities compiled in, and
1323 // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
1324 // die when we see such misconfigured kernels.
1325 if ((err < 0) && (errno != EINVAL)) {
1326 exit(1);
1327 }
1328 }
1329}
1330
1331static int should_drop_privileges() {
1332#ifndef ALLOW_ADBD_ROOT
1333 return 1;
1334#else /* ALLOW_ADBD_ROOT */
1335#ifdef ADB_NON_ANDROID
1336 return 0;
1337#endif /* ADB_NON_ANDROID */
1338 int secure = 0;
1339 char value[PROPERTY_VALUE_MAX];
1340
1341 /* run adbd in secure mode if ro.secure is set and
1342 ** we are not in the emulator
1343 */
1344 property_get("ro.kernel.qemu", value, "");
1345 if (strcmp(value, "1") != 0) {
1346 property_get("ro.secure", value, "1");
1347 if (strcmp(value, "1") == 0) {
1348 // don't run as root if ro.secure is set...
1349 secure = 1;
1350
1351 // ... except we allow running as root in userdebug builds if the
1352 // service.adb.root property has been set by the "adb root" command
1353 property_get("ro.debuggable", value, "");
1354 if (strcmp(value, "1") == 0) {
1355 property_get("service.adb.root", value, "");
1356 if (strcmp(value, "1") == 0) {
1357 secure = 0;
1358 }
1359 }
1360 }
1361 }
1362 return secure;
1363#endif /* ALLOW_ADBD_ROOT */
1364}
1365#endif /* !ADB_HOST */
1366
1367int adb_main(int is_daemon, int server_port)
1368{
1369#if !ADB_HOST
1370 int port;
1371 char value[PROPERTY_VALUE_MAX];
1372
1373 umask(000);
1374#endif
1375
1376 atexit(adb_cleanup);
1377#if defined(_WIN32)
1378 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1379#else
1380 // No SIGCHLD. Let the service subproc handle its children.
1381 signal(SIGPIPE, SIG_IGN);
1382#endif
1383
1384 init_transport_registration();
1385
1386#if ADB_HOST
1387 HOST = 1;
1388
1389#ifdef WORKAROUND_BUG6558362
1390 if(is_daemon) adb_set_affinity();
1391#endif
1392
1393#if ADB_OVER_PCIE
1394 fprintf(stderr, "adb path: %s\n", PCIE_ADB_PATH);
1395 pcie_host_init();
1396#else
1397 usb_init();
1398#endif
1399 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
1400 adb_auth_init();
1401
1402 char local_name[30];
1403 build_local_name(local_name, sizeof(local_name), server_port);
1404 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
1405 exit(1);
1406 }
1407#else
1408 property_get("ro.adb.secure", value, "0");
1409 auth_enabled = !strcmp(value, "1");
1410 if (auth_enabled)
1411 adb_auth_init();
1412
1413 // Our external storage path may be different than apps, since
1414 // we aren't able to bind mount after dropping root.
1415 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
1416 if (NULL != adb_external_storage) {
1417 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
1418 } else {
1419 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
1420 " unchanged.\n");
1421 }
1422
1423 /* add extra groups:
1424 ** AID_ADB to access the USB driver
1425 ** AID_LOG to read system logs (adb logcat)
1426 ** AID_INPUT to diagnose input issues (getevent)
1427 ** AID_INET to diagnose network issues (netcfg, ping)
1428 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
1429 ** AID_SDCARD_R to allow reading from the SD card
1430 ** AID_SDCARD_RW to allow writing to the SD card
1431 ** AID_NET_BW_STATS to read out qtaguid statistics
1432 */
1433 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT,
1434 AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
1435 AID_NET_BW_STATS };
1436 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1437 exit(1);
1438 }
1439
1440 /* don't listen on a port (default 5037) if running in secure mode */
1441 /* don't run as root if we are running in secure mode */
1442 if (should_drop_privileges()) {
1443 drop_capabilities_bounding_set_if_needed();
1444
1445 /* then switch user and group to "shell" */
1446 if (setgid(AID_SHELL) != 0) {
1447 exit(1);
1448 }
1449 if (setuid(AID_SHELL) != 0) {
1450 exit(1);
1451 }
1452
1453 D("Local port disabled\n");
1454 } else {
1455#ifndef ADB_NON_ANDROID
1456 char local_name[30];
1457 if ((root_seclabel != NULL) && (is_selinux_enabled() > 0)) {
1458 // b/12587913: fix setcon to allow const pointers
1459 if (setcon((char *)root_seclabel) < 0) {
1460 exit(1);
1461 }
1462 }
1463 build_local_name(local_name, sizeof(local_name), server_port);
1464 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
1465 exit(1);
1466 }
1467#endif
1468 }
1469
1470 int usb = 0;
1471#ifdef ADB_OVER_PCIE
1472 fprintf(stderr, "adbd path: %s\n", PCIE_ADB_PATH);
1473 if (access(PCIE_ADB_PATH, F_OK) == 0) {
1474 pcie_init();
1475 usb = 1;
1476 }
1477#else
1478 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
1479 // listen on USB
1480 usb_init();
1481 usb = 1;
1482 }
1483#endif
1484
1485 // If one of these properties is set, also listen on that port
1486 // If one of the properties isn't set and we couldn't listen on usb,
1487 // listen on the default port.
1488 property_get("service.adb.tcp.port", value, "");
1489 if (!value[0]) {
1490 property_get("persist.adb.tcp.port", value, "");
1491 }
1492 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1493 printf("using port=%d\n", port);
1494 // listen on TCP port specified by service.adb.tcp.port property
1495 local_init(port);
1496 } else if (!usb) {
1497 // listen on default port
1498 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
1499 }
1500
1501 D("adb_main(): pre init_jdwp()\n");
1502 init_jdwp();
1503 D("adb_main(): post init_jdwp()\n");
1504#endif
1505
1506 if (is_daemon)
1507 {
1508 // inform our parent that we are up and running.
1509#if defined(_WIN32)
1510 DWORD count;
1511 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1512#else
1513 fprintf(stderr, "OK\n");
1514#endif
1515 start_logging();
1516 }
1517 D("Event loop starting\n");
1518
1519 fdevent_loop();
1520
1521#ifndef ADB_OVER_PCIE
1522 usb_cleanup();
1523#endif
1524
1525 return 0;
1526}
1527
1528// Try to handle a network forwarding request.
1529// This returns 1 on success, 0 on failure, and -1 to indicate this is not
1530// a forwarding-related request.
1531int handle_forward_request(const char* service, transport_type ttype, char* serial, int reply_fd)
1532{
1533 if (!strcmp(service, "list-forward")) {
1534 // Create the list of forward redirections.
1535 int buffer_size = format_listeners(NULL, 0);
1536 // Add one byte for the trailing zero.
1537 char* buffer = malloc(buffer_size + 1);
1538 if (buffer == NULL) {
1539 sendfailmsg(reply_fd, "not enough memory");
1540 return 1;
1541 }
1542 (void) format_listeners(buffer, buffer_size + 1);
1543#if ADB_HOST
1544 send_msg_with_okay(reply_fd, buffer, buffer_size);
1545#else
1546 send_msg_with_header(reply_fd, buffer, buffer_size);
1547#endif
1548 free(buffer);
1549 return 1;
1550 }
1551
1552 if (!strcmp(service, "killforward-all")) {
1553 remove_all_listeners();
1554#if ADB_HOST
1555 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
1556 adb_write(reply_fd, "OKAY", 4);
1557#endif
1558 adb_write(reply_fd, "OKAY", 4);
1559 return 1;
1560 }
1561
1562 if (!strncmp(service, "forward:",8) ||
1563 !strncmp(service, "killforward:",12)) {
1564 char *local, *remote, *err;
1565 int r;
1566 atransport *transport;
1567
1568 int createForward = strncmp(service, "kill", 4);
1569 int no_rebind = 0;
1570
1571 local = strchr(service, ':') + 1;
1572
1573 // Handle forward:norebind:<local>... here
1574 if (createForward && !strncmp(local, "norebind:", 9)) {
1575 no_rebind = 1;
1576 local = strchr(local, ':') + 1;
1577 }
1578
1579 remote = strchr(local,';');
1580
1581 if (createForward) {
1582 // Check forward: parameter format: '<local>;<remote>'
1583 if(remote == 0) {
1584 sendfailmsg(reply_fd, "malformed forward spec");
1585 return 1;
1586 }
1587
1588 *remote++ = 0;
1589 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')) {
1590 sendfailmsg(reply_fd, "malformed forward spec");
1591 return 1;
1592 }
1593 } else {
1594 // Check killforward: parameter format: '<local>'
1595 if (local[0] == 0) {
1596 sendfailmsg(reply_fd, "malformed forward spec");
1597 return 1;
1598 }
1599 }
1600
1601 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1602 if (!transport) {
1603 sendfailmsg(reply_fd, err);
1604 return 1;
1605 }
1606
1607 if (createForward) {
1608 r = install_listener(local, remote, transport, no_rebind);
1609 } else {
1610 r = remove_listener(local, transport);
1611 }
1612 if(r == 0) {
1613#if ADB_HOST
1614 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
1615 writex(reply_fd, "OKAY", 4);
1616#endif
1617 writex(reply_fd, "OKAY", 4);
1618 return 1;
1619 }
1620
1621 if (createForward) {
1622 const char* message;
1623 switch (r) {
1624 case INSTALL_STATUS_CANNOT_BIND:
1625 message = "cannot bind to socket";
1626 break;
1627 case INSTALL_STATUS_CANNOT_REBIND:
1628 message = "cannot rebind existing socket";
1629 break;
1630 default:
1631 message = "internal error";
1632 }
1633 sendfailmsg(reply_fd, message);
1634 } else {
1635 sendfailmsg(reply_fd, "cannot remove listener");
1636 }
1637 return 1;
1638 }
1639 return 0;
1640}
1641
1642int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1643{
1644 if(!strcmp(service, "kill")) {
1645 fprintf(stderr,"adb server killed by remote request\n");
1646 fflush(stdout);
1647 adb_write(reply_fd, "OKAY", 4);
1648#ifndef ADB_OVER_PCIE
1649 usb_cleanup();
1650#endif
1651 exit(0);
1652 }
1653
1654#if ADB_HOST
1655 atransport *transport = NULL;
1656 // "transport:" is used for switching transport with a specified serial number
1657 // "transport-usb:" is used for switching transport to the only USB transport
1658 // "transport-local:" is used for switching transport to the only local transport
1659 // "transport-any:" is used for switching transport to the only transport
1660 if (!strncmp(service, "transport", strlen("transport"))) {
1661 char* error_string = "unknown failure";
1662 transport_type type = kTransportAny;
1663
1664 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1665 type = kTransportUsb;
1666 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1667 type = kTransportLocal;
1668 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1669 type = kTransportAny;
1670 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1671 service += strlen("transport:");
1672 serial = service;
1673 }
1674
1675 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1676
1677 if (transport) {
1678 s->transport = transport;
1679 adb_write(reply_fd, "OKAY", 4);
1680 } else {
1681 sendfailmsg(reply_fd, error_string);
1682 }
1683 return 1;
1684 }
1685
1686 // return a list of all connected devices
1687 if (!strncmp(service, "devices", 7)) {
1688 char buffer[4096];
1689 int use_long = !strcmp(service+7, "-l");
1690 if (use_long || service[7] == 0) {
1691 memset(buffer, 0, sizeof(buffer));
1692 D("Getting device list \n");
1693 list_transports(buffer, sizeof(buffer), use_long);
1694 D("Wrote device list \n");
1695 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
1696 return 0;
1697 }
1698 }
1699
1700 // remove TCP transport
1701 if (!strncmp(service, "disconnect:", 11)) {
1702 char buffer[4096];
1703 memset(buffer, 0, sizeof(buffer));
1704 char* serial = service + 11;
1705 if (serial[0] == 0) {
1706 // disconnect from all TCP devices
1707 unregister_all_tcp_transports();
1708 } else {
1709 char hostbuf[100];
1710 // assume port 5555 if no port is specified
1711 if (!strchr(serial, ':')) {
1712 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1713 serial = hostbuf;
1714 }
1715 atransport *t = find_transport(serial);
1716
1717 if (t) {
1718 unregister_transport(t);
1719 } else {
1720 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1721 }
1722 }
1723
1724 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
1725 return 0;
1726 }
1727
1728 // returns our value for ADB_SERVER_VERSION
1729 if (!strcmp(service, "version")) {
1730 char version[12];
1731 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1732 send_msg_with_okay(reply_fd, version, strlen(version));
1733 return 0;
1734 }
1735
1736 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1737 char *out = "unknown";
1738 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1739 if (transport && transport->serial) {
1740 out = transport->serial;
1741 }
1742 send_msg_with_okay(reply_fd, out, strlen(out));
1743 return 0;
1744 }
1745 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1746 char *out = "unknown";
1747 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1748 if (transport && transport->devpath) {
1749 out = transport->devpath;
1750 }
1751 send_msg_with_okay(reply_fd, out, strlen(out));
1752 return 0;
1753 }
1754 // indicates a new emulator instance has started
1755 if (!strncmp(service,"emulator:",9)) {
1756 int port = atoi(service+9);
1757 local_connect(port);
1758 /* we don't even need to send a reply */
1759 return 0;
1760 }
1761
1762 if(!strncmp(service,"get-state",strlen("get-state"))) {
1763 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1764 char *state = connection_state_name(transport);
1765 send_msg_with_okay(reply_fd, state, strlen(state));
1766 return 0;
1767 }
1768#endif // ADB_HOST
1769
1770 int ret = handle_forward_request(service, ttype, serial, reply_fd);
1771 if (ret >= 0)
1772 return ret - 1;
1773 return -1;
1774}
1775
1776int main(int argc, char **argv)
1777{
1778#if ADB_HOST
1779 adb_sysdeps_init();
1780 adb_trace_init();
1781 D("Handling commandline()\n");
1782 return adb_commandline(argc - 1, argv + 1);
1783#else
1784 /* If adbd runs inside the emulator this will enable adb tracing via
1785 * adb-debug qemud service in the emulator. */
1786 //adb_qemu_trace_init();
1787 D("main()\n");
1788 while(1) {
1789 int c;
1790 int option_index = 0;
1791 static struct option opts[] = {
1792 {"root_seclabel", required_argument, 0, 's' },
1793 {"device_banner", required_argument, 0, 'b' }
1794 };
1795 c = getopt_long(argc, argv, "", opts, &option_index);
1796 if (c == -1)
1797 break;
1798 switch (c) {
1799 case 's':
1800 root_seclabel = optarg;
1801 break;
1802 case 'b':
1803 adb_device_banner = optarg;
1804 break;
1805 default:
1806 break;
1807 }
1808 }
1809
1810 start_device_log();
1811 D("Handling main()\n");
1812 return adb_main(0, DEFAULT_ADB_PORT);
1813#endif
1814}