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