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