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