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