2
* Copyright (C) 2007 The Android Open Source Project
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
8
* http://www.apache.org/licenses/LICENSE-2.0
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.
17
#define TRACE_TAG TRACE_ADB
32
#include <private/android_filesystem_config.h>
33
#include <linux/capability.h>
34
#include <linux/prctl.h>
36
#include "usb_vendors.h"
40
ADB_MUTEX_DEFINE( D_lock );
45
static const char *adb_device_banner = "device";
47
void fatal(const char *fmt, ...)
51
fprintf(stderr, "error: ");
52
vfprintf(stderr, fmt, ap);
53
fprintf(stderr, "\n");
58
void fatal_errno(const char *fmt, ...)
62
fprintf(stderr, "error: %s: ", strerror(errno));
63
vfprintf(stderr, fmt, ap);
64
fprintf(stderr, "\n");
71
/* read a comma/space/colum/semi-column separated list of tags
72
* from the ADB_TRACE environment variable and build the trace
73
* mask from it. note that '1' and 'all' are special cases to
76
void adb_trace_init(void)
78
const char* p = getenv("ADB_TRACE");
88
{ "sockets", TRACE_SOCKETS },
89
{ "packets", TRACE_PACKETS },
92
{ "sync", TRACE_SYNC },
93
{ "sysdeps", TRACE_SYSDEPS },
94
{ "transport", TRACE_TRANSPORT },
95
{ "jdwp", TRACE_JDWP },
96
{ "services", TRACE_SERVICES },
103
/* use a comma/column/semi-colum/space separated list */
107
q = strpbrk(p, " ,:;");
113
for (tagn = 0; tags[tagn].tag != NULL; tagn++)
115
int taglen = strlen(tags[tagn].tag);
117
if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
119
int flag = tags[tagn].flag;
124
adb_trace_mask |= (1 << flag);
136
* Implements ADB tracing inside the emulator.
142
* Redefine open and write for qemu_pipe.h that contains inlined references
143
* to those routines. We will redifine them back after qemu_pipe.h inclusion.
148
#define open adb_open
149
#define write adb_write
150
#include <hardware/qemu_pipe.h>
153
#define open ___xxx_open
154
#define write ___xxx_write
156
/* A handle to adb-debug qemud service in the emulator. */
157
int adb_debug_qemu = -1;
159
/* Initializes connection with the adb-debug qemud service in the emulator. */
160
static int adb_qemu_trace_init(void)
164
if (adb_debug_qemu >= 0) {
168
/* adb debugging QEMUD service connection request. */
169
snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
170
adb_debug_qemu = qemu_pipe_open(con_name);
171
return (adb_debug_qemu >= 0) ? 0 : -1;
174
void adb_qemu_trace(const char* fmt, ...)
180
if (adb_debug_qemu >= 0) {
181
vsnprintf(msg, sizeof(msg), fmt, args);
182
adb_write(adb_debug_qemu, msg, strlen(msg));
185
#endif /* !ADB_HOST */
187
apacket *get_apacket(void)
189
apacket *p = malloc(sizeof(apacket));
190
if(p == 0) fatal("failed to allocate an apacket");
191
memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
195
void put_apacket(apacket *p)
200
void handle_online(void)
205
void handle_offline(atransport *t)
208
//Close the associated usb
209
run_transport_disconnects(t);
214
void print_packet(const char *label, apacket *p)
220
switch(p->msg.command){
221
case A_SYNC: tag = "SYNC"; break;
222
case A_CNXN: tag = "CNXN" ; break;
223
case A_OPEN: tag = "OPEN"; break;
224
case A_OKAY: tag = "OKAY"; break;
225
case A_CLSE: tag = "CLSE"; break;
226
case A_WRTE: tag = "WRTE"; break;
227
default: tag = "????"; break;
230
fprintf(stderr, "%s: %s %08x %08x %04x \"",
231
label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
232
count = p->msg.data_length;
234
if(count > DUMPMAX) {
241
if((*x >= ' ') && (*x < 127)) {
248
fprintf(stderr, tag);
252
static void send_ready(unsigned local, unsigned remote, atransport *t)
254
D("Calling send_ready \n");
255
apacket *p = get_apacket();
256
p->msg.command = A_OKAY;
258
p->msg.arg1 = remote;
262
static void send_close(unsigned local, unsigned remote, atransport *t)
264
D("Calling send_close \n");
265
apacket *p = get_apacket();
266
p->msg.command = A_CLSE;
268
p->msg.arg1 = remote;
272
static void send_connect(atransport *t)
274
D("Calling send_connect \n");
275
apacket *cp = get_apacket();
276
cp->msg.command = A_CNXN;
277
cp->msg.arg0 = A_VERSION;
278
cp->msg.arg1 = MAX_PAYLOAD;
279
snprintf((char*) cp->data, sizeof cp->data, "%s::",
280
HOST ? "host" : adb_device_banner);
281
cp->msg.data_length = strlen((char*) cp->data) + 1;
284
/* XXX why sleep here? */
285
// allow the device some time to respond to the connect message
290
static char *connection_state_name(atransport *t)
296
switch(t->connection_state) {
308
void parse_banner(char *banner, atransport *t)
310
char *type, *product, *end;
312
D("parse_banner: %s\n", banner);
314
product = strchr(type, ':');
321
/* remove trailing ':' */
322
end = strchr(product, ':');
325
/* save product name in device structure */
326
if (t->product == NULL) {
327
t->product = strdup(product);
328
} else if (strcmp(product, t->product) != 0) {
330
t->product = strdup(product);
333
if(!strcmp(type, "bootloader")){
334
D("setting connection_state to CS_BOOTLOADER\n");
335
t->connection_state = CS_BOOTLOADER;
340
if(!strcmp(type, "device")) {
341
D("setting connection_state to CS_DEVICE\n");
342
t->connection_state = CS_DEVICE;
347
if(!strcmp(type, "recovery")) {
348
D("setting connection_state to CS_RECOVERY\n");
349
t->connection_state = CS_RECOVERY;
354
if(!strcmp(type, "sideload")) {
355
D("setting connection_state to CS_SIDELOAD\n");
356
t->connection_state = CS_SIDELOAD;
361
t->connection_state = CS_HOST;
364
void handle_packet(apacket *p, atransport *t)
368
D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
369
((char*) (&(p->msg.command)))[1],
370
((char*) (&(p->msg.command)))[2],
371
((char*) (&(p->msg.command)))[3]);
372
print_packet("recv", p);
374
switch(p->msg.command){
378
if(HOST) send_connect(t);
380
t->connection_state = CS_OFFLINE;
386
case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
387
/* XXX verify version, etc */
388
if(t->connection_state != CS_OFFLINE) {
389
t->connection_state = CS_OFFLINE;
392
parse_banner((char*) p->data, t);
394
if(!HOST) send_connect(t);
397
case A_OPEN: /* OPEN(local-id, 0, "destination") */
398
if(t->connection_state != CS_OFFLINE) {
399
char *name = (char*) p->data;
400
name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
401
s = create_local_service_socket(name);
403
send_close(0, p->msg.arg0, t);
405
s->peer = create_remote_socket(p->msg.arg0, t);
407
send_ready(s->id, s->peer->id, t);
413
case A_OKAY: /* READY(local-id, remote-id, "") */
414
if(t->connection_state != CS_OFFLINE) {
415
if((s = find_local_socket(p->msg.arg1))) {
417
s->peer = create_remote_socket(p->msg.arg0, t);
425
case A_CLSE: /* CLOSE(local-id, remote-id, "") */
426
if(t->connection_state != CS_OFFLINE) {
427
if((s = find_local_socket(p->msg.arg1))) {
434
if(t->connection_state != CS_OFFLINE) {
435
if((s = find_local_socket(p->msg.arg1))) {
436
unsigned rid = p->msg.arg0;
437
p->len = p->msg.data_length;
439
if(s->enqueue(s, p) == 0) {
440
D("Enqueue the socket\n");
441
send_ready(s->id, rid, t);
449
printf("handle_packet: what is %08x?!\n", p->msg.command);
455
alistener listener_list = {
456
.next = &listener_list,
457
.prev = &listener_list,
460
static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
465
struct sockaddr addr;
470
fd = adb_socket_accept(_fd, &addr, &alen);
473
adb_socket_setbufsize(fd, CHUNK_SIZE);
475
s = create_local_socket(fd);
477
connect_to_smartsocket(s);
485
static void listener_event_func(int _fd, unsigned ev, void *_l)
491
struct sockaddr addr;
496
fd = adb_socket_accept(_fd, &addr, &alen);
499
s = create_local_socket(fd);
501
s->transport = l->transport;
502
connect_to_remote(s, l->connect_to);
510
static void free_listener(alistener* l)
513
l->next->prev = l->prev;
514
l->prev->next = l->next;
515
l->next = l->prev = l;
518
// closes the corresponding fd
519
fdevent_remove(&l->fde);
522
free((char*)l->local_name);
525
free((char*)l->connect_to);
528
remove_transport_disconnect(l->transport, &l->disconnect);
533
static void listener_disconnect(void* _l, atransport* t)
540
int local_name_to_fd(const char *name)
544
if(!strncmp("tcp:", name, 4)){
546
port = atoi(name + 4);
547
ret = socket_loopback_server(port, SOCK_STREAM);
550
#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
551
// It's non-sensical to support the "reserved" space on the adb host side
552
if(!strncmp(name, "local:", 6)) {
553
return socket_local_server(name + 6,
554
ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
555
} else if(!strncmp(name, "localabstract:", 14)) {
556
return socket_local_server(name + 14,
557
ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
558
} else if(!strncmp(name, "localfilesystem:", 16)) {
559
return socket_local_server(name + 16,
560
ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
564
printf("unknown local portname '%s'\n", name);
568
static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
572
for (l = listener_list.next; l != &listener_list; l = l->next) {
573
if (!strcmp(local_name, l->local_name) &&
574
!strcmp(connect_to, l->connect_to) &&
575
l->transport && l->transport == transport) {
577
listener_disconnect(l, transport);
585
static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
589
//printf("install_listener('%s','%s')\n", local_name, connect_to);
591
for(l = listener_list.next; l != &listener_list; l = l->next){
592
if(strcmp(local_name, l->local_name) == 0) {
595
/* can't repurpose a smartsocket */
596
if(l->connect_to[0] == '*') {
600
cto = strdup(connect_to);
605
//printf("rebinding '%s' to '%s'\n", local_name, connect_to);
606
free((void*) l->connect_to);
608
if (l->transport != transport) {
609
remove_transport_disconnect(l->transport, &l->disconnect);
610
l->transport = transport;
611
add_transport_disconnect(l->transport, &l->disconnect);
617
if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
618
if((l->local_name = strdup(local_name)) == 0) goto nomem;
619
if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
622
l->fd = local_name_to_fd(local_name);
624
free((void*) l->local_name);
625
free((void*) l->connect_to);
627
printf("cannot bind '%s'\n", local_name);
631
close_on_exec(l->fd);
632
if(!strcmp(l->connect_to, "*smartsocket*")) {
633
fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
635
fdevent_install(&l->fde, l->fd, listener_event_func, l);
637
fdevent_set(&l->fde, FDE_READ);
639
l->next = &listener_list;
640
l->prev = listener_list.prev;
643
l->transport = transport;
646
l->disconnect.opaque = l;
647
l->disconnect.func = listener_disconnect;
648
add_transport_disconnect(transport, &l->disconnect);
653
fatal("cannot allocate listener");
657
#ifdef HAVE_WIN32_PROC
658
static BOOL WINAPI ctrlc_handler(DWORD type)
660
exit(STATUS_CONTROL_C_EXIT);
665
static void adb_cleanup(void)
670
void start_logging(void)
672
#ifdef HAVE_WIN32_PROC
673
char temp[ MAX_PATH ];
677
GetTempPath( sizeof(temp) - 8, temp );
678
strcat( temp, "adb.log" );
680
/* Win32 specific redirections */
681
fnul = fopen( "NUL", "rt" );
685
flog = fopen( temp, "at" );
689
setvbuf( flog, NULL, _IONBF, 0 );
693
fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
697
fd = unix_open("/dev/null", O_RDONLY);
701
fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
703
fd = unix_open("/dev/null", O_WRONLY);
708
fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
713
void start_device_log(void)
719
char value[PROPERTY_VALUE_MAX];
721
// read the trace mask from persistent property persist.adb.trace_mask
722
// give up if the property is not set or cannot be parsed
723
property_get("persist.adb.trace_mask", value, "");
724
if (sscanf(value, "%x", &adb_trace_mask) != 1)
727
adb_mkdir("/data/adb", 0775);
730
localtime_r(&t, &now);
731
strftime(path, sizeof(path),
732
"/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
734
fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
738
// redirect stdout and stderr to the log file
741
fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
744
fd = unix_open("/dev/null", O_RDONLY);
751
int launch_server(int server_port)
753
#ifdef HAVE_WIN32_PROC
754
/* we need to start the server in the background */
755
/* we create a PIPE that will be used to wait for the server's "OK" */
756
/* message since the pipe handles must be inheritable, we use a */
757
/* security attribute */
758
HANDLE pipe_read, pipe_write;
759
SECURITY_ATTRIBUTES sa;
761
PROCESS_INFORMATION pinfo;
762
char program_path[ MAX_PATH ];
765
sa.nLength = sizeof(sa);
766
sa.lpSecurityDescriptor = NULL;
767
sa.bInheritHandle = TRUE;
769
/* create pipe, and ensure its read handle isn't inheritable */
770
ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
772
fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
776
SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
778
ZeroMemory( &startup, sizeof(startup) );
779
startup.cb = sizeof(startup);
780
startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
781
startup.hStdOutput = pipe_write;
782
startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
783
startup.dwFlags = STARTF_USESTDHANDLES;
785
ZeroMemory( &pinfo, sizeof(pinfo) );
787
/* get path of current program */
788
GetModuleFileName( NULL, program_path, sizeof(program_path) );
791
program_path, /* program path */
792
"adb fork-server server",
793
/* the fork-server argument will set the
794
debug = 2 in the child */
795
NULL, /* process handle is not inheritable */
796
NULL, /* thread handle is not inheritable */
797
TRUE, /* yes, inherit some handles */
798
DETACHED_PROCESS, /* the new process doesn't have a console */
799
NULL, /* use parent's environment block */
800
NULL, /* use parent's starting directory */
801
&startup, /* startup info, i.e. std handles */
804
CloseHandle( pipe_write );
807
fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
808
CloseHandle( pipe_read );
812
CloseHandle( pinfo.hProcess );
813
CloseHandle( pinfo.hThread );
815
/* wait for the "OK\n" message */
820
ret = ReadFile( pipe_read, temp, 3, &count, NULL );
821
CloseHandle( pipe_read );
823
fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
826
if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
827
fprintf(stderr, "ADB server didn't ACK\n" );
831
#elif defined(HAVE_FORKEXEC)
835
// set up a pipe so the child can tell us when it is ready.
836
// fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
838
fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
841
get_my_path(path, PATH_MAX);
843
if(pid < 0) return -1;
846
// child side of the fork
848
// redirect stderr to the pipe
849
// we use stderr instead of stdout due to stdout's buffering behavior.
851
dup2(fd[1], STDERR_FILENO);
855
int result = execl(path, "adb", "fork-server", "server", NULL);
856
// this should not return
857
fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
859
// parent side of the fork
863
temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
864
// wait for the "OK\n" message
866
int ret = adb_read(fd[0], temp, 3);
867
int saved_errno = errno;
870
fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
873
if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
874
fprintf(stderr, "ADB server didn't ACK\n" );
881
#error "cannot implement background server start on this platform"
887
/* Constructs a local name of form tcp:port.
888
* target_str points to the target string, it's content will be overwritten.
889
* target_size is the capacity of the target string.
890
* server_port is the port number to use for the local name.
892
void build_local_name(char* target_str, size_t target_size, int server_port)
894
snprintf(target_str, target_size, "tcp:%d", server_port);
898
static int should_drop_privileges() {
899
#ifndef ALLOW_ADBD_ROOT
901
#else /* ALLOW_ADBD_ROOT */
903
char value[PROPERTY_VALUE_MAX];
905
/* run adbd in secure mode if ro.secure is set and
906
** we are not in the emulator
908
property_get("ro.kernel.qemu", value, "");
909
if (strcmp(value, "1") != 0) {
910
property_get("ro.secure", value, "1");
911
if (strcmp(value, "1") == 0) {
912
// don't run as root if ro.secure is set...
915
// ... except we allow running as root in userdebug builds if the
916
// service.adb.root property has been set by the "adb root" command
917
property_get("ro.debuggable", value, "");
918
if (strcmp(value, "1") == 0) {
919
property_get("service.adb.root", value, "");
920
if (strcmp(value, "1") == 0) {
927
#endif /* ALLOW_ADBD_ROOT */
929
#endif /* !ADB_HOST */
931
int adb_main(int is_daemon, int server_port)
935
char value[PROPERTY_VALUE_MAX];
941
#ifdef HAVE_WIN32_PROC
942
SetConsoleCtrlHandler( ctrlc_handler, TRUE );
943
#elif defined(HAVE_FORKEXEC)
944
// No SIGCHLD. Let the service subproc handle its children.
945
signal(SIGPIPE, SIG_IGN);
948
init_transport_registration();
955
local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
958
build_local_name(local_name, sizeof(local_name), server_port);
959
if(install_listener(local_name, "*smartsocket*", NULL)) {
964
/* don't listen on a port (default 5037) if running in secure mode */
965
/* don't run as root if we are running in secure mode */
966
if (should_drop_privileges()) {
967
struct __user_cap_header_struct header;
968
struct __user_cap_data_struct cap;
970
if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
975
** AID_ADB to access the USB driver
976
** AID_LOG to read system logs (adb logcat)
977
** AID_INPUT to diagnose input issues (getevent)
978
** AID_INET to diagnose network issues (netcfg, ping)
979
** AID_GRAPHICS to access the frame buffer
980
** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
981
** AID_SDCARD_R to allow reading from the SD card
982
** AID_SDCARD_RW to allow writing to the SD card
983
** AID_MOUNT to allow unmounting the SD card before rebooting
984
** AID_NET_BW_STATS to read out qtaguid statistics
986
gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
987
AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
988
AID_MOUNT, AID_NET_BW_STATS };
989
if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
993
/* then switch user and group to "shell" */
994
if (setgid(AID_SHELL) != 0) {
997
if (setuid(AID_SHELL) != 0) {
1001
/* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1002
header.version = _LINUX_CAPABILITY_VERSION;
1004
cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1005
cap.inheritable = 0;
1006
capset(&header, &cap);
1008
D("Local port disabled\n");
1010
char local_name[30];
1011
build_local_name(local_name, sizeof(local_name), server_port);
1012
if(install_listener(local_name, "*smartsocket*", NULL)) {
1017
/* for the device, start the usb transport if the
1018
** android usb device exists and the "service.adb.tcp.port" and
1019
** "persist.adb.tcp.port" properties are not set.
1020
** Otherwise start the network transport.
1022
property_get("service.adb.tcp.port", value, "");
1024
property_get("persist.adb.tcp.port", value, "");
1025
if (sscanf(value, "%d", &port) == 1 && port > 0) {
1026
// listen on TCP port specified by service.adb.tcp.port property
1028
} else if (access("/dev/android_adb", F_OK) == 0) {
1032
// listen on default port
1033
local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
1035
D("adb_main(): pre init_jdwp()\n");
1037
D("adb_main(): post init_jdwp()\n");
1042
// inform our parent that we are up and running.
1043
#ifdef HAVE_WIN32_PROC
1045
WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1046
#elif defined(HAVE_FORKEXEC)
1047
fprintf(stderr, "OK\n");
1051
D("Event loop starting\n");
1061
void connect_device(char* host, char* buffer, int buffer_size)
1064
char* portstr = strchr(host, ':');
1068
strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1070
if (portstr - host >= sizeof(hostbuf)) {
1071
snprintf(buffer, buffer_size, "bad host name %s", host);
1074
// zero terminate the host at the point we found the colon
1075
hostbuf[portstr - host] = 0;
1076
if (sscanf(portstr + 1, "%d", &port) == 0) {
1077
snprintf(buffer, buffer_size, "bad port number %s", portstr);
1081
port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
1084
snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1085
if (find_transport(serial)) {
1086
snprintf(buffer, buffer_size, "already connected to %s", serial);
1090
fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1092
snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
1096
D("client: connected on remote on fd %d\n", fd);
1098
disable_tcp_nagle(fd);
1099
register_socket_transport(fd, serial, port, 0);
1100
snprintf(buffer, buffer_size, "connected to %s", serial);
1103
void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1105
char* port_separator = strchr(port_spec, ',');
1106
if (!port_separator) {
1107
snprintf(buffer, buffer_size,
1108
"unable to parse '%s' as <console port>,<adb port>",
1113
// Zero-terminate console port and make port_separator point to 2nd port.
1114
*port_separator++ = 0;
1115
int console_port = strtol(port_spec, NULL, 0);
1116
int adb_port = strtol(port_separator, NULL, 0);
1117
if (!(console_port > 0 && adb_port > 0)) {
1118
*(port_separator - 1) = ',';
1119
snprintf(buffer, buffer_size,
1120
"Invalid port numbers: Expected positive numbers, got '%s'",
1125
/* Check if the emulator is already known.
1126
* Note: There's a small but harmless race condition here: An emulator not
1127
* present just yet could be registered by another invocation right
1128
* after doing this check here. However, local_connect protects
1129
* against double-registration too. From here, a better error message
1130
* can be produced. In the case of the race condition, the very specific
1131
* error message won't be shown, but the data doesn't get corrupted. */
1132
atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
1133
if (known_emulator != NULL) {
1134
snprintf(buffer, buffer_size,
1135
"Emulator on port %d already registered.", adb_port);
1139
/* Check if more emulators can be registered. Similar unproblematic
1140
* race condition as above. */
1141
int candidate_slot = get_available_local_transport_index();
1142
if (candidate_slot < 0) {
1143
snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1147
/* Preconditions met, try to connect to the emulator. */
1148
if (!local_connect_arbitrary_ports(console_port, adb_port)) {
1149
snprintf(buffer, buffer_size,
1150
"Connected to emulator on ports %d,%d", console_port, adb_port);
1152
snprintf(buffer, buffer_size,
1153
"Could not connect to emulator on ports %d,%d",
1154
console_port, adb_port);
1159
int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1161
atransport *transport = NULL;
1164
if(!strcmp(service, "kill")) {
1165
fprintf(stderr,"adb server killed by remote request\n");
1167
adb_write(reply_fd, "OKAY", 4);
1173
// "transport:" is used for switching transport with a specified serial number
1174
// "transport-usb:" is used for switching transport to the only USB transport
1175
// "transport-local:" is used for switching transport to the only local transport
1176
// "transport-any:" is used for switching transport to the only transport
1177
if (!strncmp(service, "transport", strlen("transport"))) {
1178
char* error_string = "unknown failure";
1179
transport_type type = kTransportAny;
1181
if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1182
type = kTransportUsb;
1183
} else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1184
type = kTransportLocal;
1185
} else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1186
type = kTransportAny;
1187
} else if (!strncmp(service, "transport:", strlen("transport:"))) {
1188
service += strlen("transport:");
1192
transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1195
s->transport = transport;
1196
adb_write(reply_fd, "OKAY", 4);
1198
sendfailmsg(reply_fd, error_string);
1203
// return a list of all connected devices
1204
if (!strcmp(service, "devices")) {
1206
memset(buf, 0, sizeof(buf));
1207
memset(buffer, 0, sizeof(buffer));
1208
D("Getting device list \n");
1209
list_transports(buffer, sizeof(buffer));
1210
snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1211
D("Wrote device list \n");
1212
writex(reply_fd, buf, strlen(buf));
1216
// add a new TCP transport, device or emulator
1217
if (!strncmp(service, "connect:", 8)) {
1219
char* host = service + 8;
1220
if (!strncmp(host, "emu:", 4)) {
1221
connect_emulator(host + 4, buffer, sizeof(buffer));
1223
connect_device(host, buffer, sizeof(buffer));
1225
// Send response for emulator and device
1226
snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1227
writex(reply_fd, buf, strlen(buf));
1231
// remove TCP transport
1232
if (!strncmp(service, "disconnect:", 11)) {
1234
memset(buffer, 0, sizeof(buffer));
1235
char* serial = service + 11;
1236
if (serial[0] == 0) {
1237
// disconnect from all TCP devices
1238
unregister_all_tcp_transports();
1241
// assume port 5555 if no port is specified
1242
if (!strchr(serial, ':')) {
1243
snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1246
atransport *t = find_transport(serial);
1249
unregister_transport(t);
1251
snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1255
snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1256
writex(reply_fd, buf, strlen(buf));
1260
// returns our value for ADB_SERVER_VERSION
1261
if (!strcmp(service, "version")) {
1263
snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
1264
snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1265
writex(reply_fd, buf, strlen(buf));
1269
if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1270
char *out = "unknown";
1271
transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1272
if (transport && transport->serial) {
1273
out = transport->serial;
1275
snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1276
writex(reply_fd, buf, strlen(buf));
1279
// indicates a new emulator instance has started
1280
if (!strncmp(service,"emulator:",9)) {
1281
int port = atoi(service+9);
1282
local_connect(port);
1283
/* we don't even need to send a reply */
1288
if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1289
char *local, *remote, *err;
1291
atransport *transport;
1293
int createForward = strncmp(service,"kill",4);
1295
local = service + (createForward ? 8 : 12);
1296
remote = strchr(local,';');
1298
sendfailmsg(reply_fd, "malformed forward spec");
1303
if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1304
sendfailmsg(reply_fd, "malformed forward spec");
1308
transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1310
sendfailmsg(reply_fd, err);
1314
if (createForward) {
1315
r = install_listener(local, remote, transport);
1317
r = remove_listener(local, remote, transport);
1320
/* 1st OKAY is connect, 2nd OKAY is status */
1321
writex(reply_fd, "OKAYOKAY", 8);
1325
if (createForward) {
1326
sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1328
sendfailmsg(reply_fd, "cannot remove listener");
1333
if(!strncmp(service,"get-state",strlen("get-state"))) {
1334
transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1335
char *state = connection_state_name(transport);
1336
snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1337
writex(reply_fd, buf, strlen(buf));
1344
int recovery_mode = 0;
1347
int main(int argc, char **argv)
1352
D("Handling commandline()\n");
1353
return adb_commandline(argc - 1, argv + 1);
1355
/* If adbd runs inside the emulator this will enable adb tracing via
1356
* adb-debug qemud service in the emulator. */
1357
adb_qemu_trace_init();
1358
if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1359
adb_device_banner = "recovery";
1364
D("Handling main()\n");
1365
return adb_main(0, DEFAULT_ADB_PORT);