blob: 69d9d0ff886c4413575d68322df1625076f1d36b [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define TRACE_TAG TRACE_ADB
18
19#include <stdio.h>
20#include <stdlib.h>
21#include <ctype.h>
22#include <stdarg.h>
23#include <errno.h>
Scott Andersonc7993af2012-05-25 13:55:46 -070024#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <string.h>
26#include <time.h>
Mike Lockwood1f546e62009-05-25 18:17:55 -040027#include <sys/time.h>
Ray Donnellycbb98912012-11-29 01:36:08 +000028#include <stdint.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029
30#include "sysdeps.h"
31#include "adb.h"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070032#include "adb_auth.h"
Dan Alberte9fca142015-02-18 18:03:26 -080033#include "adb_listeners.h"
Dan Albert21c3eaf2015-02-18 17:20:44 -080034#include "qemu_tracing.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080035
Scott Andersone82c2db2012-05-25 14:10:02 -070036#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
37
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080038#if !ADB_HOST
Nick Kralevich893a4a42013-05-23 09:54:13 -070039#include <cutils/properties.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080040#include <private/android_filesystem_config.h>
Nick Kraleviche2864bf2013-02-28 14:12:58 -080041#include <sys/capability.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070042#include <sys/mount.h>
Elliott Hughesb4dd6ef2014-07-18 16:44:58 -070043#include <sys/prctl.h>
Nick Kralevichd49aa252014-01-18 09:25:04 -080044#include <getopt.h>
45#include <selinux/selinux.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046#endif
47
JP Abgrall408fa572011-03-16 15:57:42 -070048#if ADB_TRACE
49ADB_MUTEX_DEFINE( D_lock );
50#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080051
52int HOST = 0;
53
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070054static int auth_enabled = 0;
55
Scott Andersone82c2db2012-05-25 14:10:02 -070056#if !ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057static const char *adb_device_banner = "device";
Nick Kralevichd49aa252014-01-18 09:25:04 -080058static const char *root_seclabel = NULL;
Scott Andersone82c2db2012-05-25 14:10:02 -070059#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080060
61void fatal(const char *fmt, ...)
62{
63 va_list ap;
64 va_start(ap, fmt);
65 fprintf(stderr, "error: ");
66 vfprintf(stderr, fmt, ap);
67 fprintf(stderr, "\n");
68 va_end(ap);
69 exit(-1);
70}
71
72void fatal_errno(const char *fmt, ...)
73{
74 va_list ap;
75 va_start(ap, fmt);
76 fprintf(stderr, "error: %s: ", strerror(errno));
77 vfprintf(stderr, fmt, ap);
78 fprintf(stderr, "\n");
79 va_end(ap);
80 exit(-1);
81}
82
83int adb_trace_mask;
84
85/* read a comma/space/colum/semi-column separated list of tags
86 * from the ADB_TRACE environment variable and build the trace
87 * mask from it. note that '1' and 'all' are special cases to
88 * enable all tracing
89 */
90void adb_trace_init(void)
91{
92 const char* p = getenv("ADB_TRACE");
93 const char* q;
94
95 static const struct {
96 const char* tag;
97 int flag;
98 } tags[] = {
99 { "1", 0 },
100 { "all", 0 },
101 { "adb", TRACE_ADB },
102 { "sockets", TRACE_SOCKETS },
103 { "packets", TRACE_PACKETS },
104 { "rwx", TRACE_RWX },
105 { "usb", TRACE_USB },
106 { "sync", TRACE_SYNC },
107 { "sysdeps", TRACE_SYSDEPS },
108 { "transport", TRACE_TRANSPORT },
109 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700110 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700111 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800112 { NULL, 0 }
113 };
114
115 if (p == NULL)
116 return;
117
118 /* use a comma/column/semi-colum/space separated list */
119 while (*p) {
120 int len, tagn;
121
122 q = strpbrk(p, " ,:;");
123 if (q == NULL) {
124 q = p + strlen(p);
125 }
126 len = q - p;
127
128 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
129 {
130 int taglen = strlen(tags[tagn].tag);
131
132 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
133 {
134 int flag = tags[tagn].flag;
135 if (flag == 0) {
136 adb_trace_mask = ~0;
137 return;
138 }
139 adb_trace_mask |= (1 << flag);
140 break;
141 }
142 }
143 p = q;
144 if (*p)
145 p++;
146 }
147}
148
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149apacket *get_apacket(void)
150{
151 apacket *p = malloc(sizeof(apacket));
152 if(p == 0) fatal("failed to allocate an apacket");
153 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
154 return p;
155}
156
157void put_apacket(apacket *p)
158{
159 free(p);
160}
161
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700162void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163{
164 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700165 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800166}
167
168void handle_offline(atransport *t)
169{
170 D("adb: offline\n");
171 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700172 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800173 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800174}
175
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700176#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800177#define DUMPMAX 32
178void print_packet(const char *label, apacket *p)
179{
180 char *tag;
181 char *x;
182 unsigned count;
183
184 switch(p->msg.command){
185 case A_SYNC: tag = "SYNC"; break;
186 case A_CNXN: tag = "CNXN" ; break;
187 case A_OPEN: tag = "OPEN"; break;
188 case A_OKAY: tag = "OKAY"; break;
189 case A_CLSE: tag = "CLSE"; break;
190 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700191 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192 default: tag = "????"; break;
193 }
194
195 fprintf(stderr, "%s: %s %08x %08x %04x \"",
196 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
197 count = p->msg.data_length;
198 x = (char*) p->data;
199 if(count > DUMPMAX) {
200 count = DUMPMAX;
201 tag = "\n";
202 } else {
203 tag = "\"\n";
204 }
205 while(count-- > 0){
206 if((*x >= ' ') && (*x < 127)) {
207 fputc(*x, stderr);
208 } else {
209 fputc('.', stderr);
210 }
211 x++;
212 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700213 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214}
215#endif
216
217static void send_ready(unsigned local, unsigned remote, atransport *t)
218{
219 D("Calling send_ready \n");
220 apacket *p = get_apacket();
221 p->msg.command = A_OKAY;
222 p->msg.arg0 = local;
223 p->msg.arg1 = remote;
224 send_packet(p, t);
225}
226
227static void send_close(unsigned local, unsigned remote, atransport *t)
228{
229 D("Calling send_close \n");
230 apacket *p = get_apacket();
231 p->msg.command = A_CLSE;
232 p->msg.arg0 = local;
233 p->msg.arg1 = remote;
234 send_packet(p, t);
235}
236
Scott Andersone82c2db2012-05-25 14:10:02 -0700237static size_t fill_connect_data(char *buf, size_t bufsize)
238{
239#if ADB_HOST
240 return snprintf(buf, bufsize, "host::") + 1;
241#else
242 static const char *cnxn_props[] = {
243 "ro.product.name",
244 "ro.product.model",
245 "ro.product.device",
246 };
247 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
248 int i;
249 size_t remaining = bufsize;
250 size_t len;
251
252 len = snprintf(buf, remaining, "%s::", adb_device_banner);
253 remaining -= len;
254 buf += len;
255 for (i = 0; i < num_cnxn_props; i++) {
256 char value[PROPERTY_VALUE_MAX];
257 property_get(cnxn_props[i], value, "");
258 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
259 remaining -= len;
260 buf += len;
261 }
262
263 return bufsize - remaining + 1;
264#endif
265}
266
David 'Digit' Turner25258692013-03-21 21:07:42 +0100267#if !ADB_HOST
268static void send_msg_with_header(int fd, const char* msg, size_t msglen) {
269 char header[5];
270 if (msglen > 0xffff)
271 msglen = 0xffff;
272 snprintf(header, sizeof(header), "%04x", (unsigned)msglen);
273 writex(fd, header, 4);
274 writex(fd, msg, msglen);
275}
276#endif
277
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700278#if ADB_HOST
David 'Digit' Turner25258692013-03-21 21:07:42 +0100279static void send_msg_with_okay(int fd, const char* msg, size_t msglen) {
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100280 char header[9];
281 if (msglen > 0xffff)
282 msglen = 0xffff;
283 snprintf(header, sizeof(header), "OKAY%04x", (unsigned)msglen);
284 writex(fd, header, 8);
285 writex(fd, msg, msglen);
286}
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700287#endif // ADB_HOST
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100288
Dan Albertba3a2512015-02-18 17:47:33 -0800289void send_connect(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290{
291 D("Calling send_connect \n");
292 apacket *cp = get_apacket();
293 cp->msg.command = A_CNXN;
294 cp->msg.arg0 = A_VERSION;
295 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700296 cp->msg.data_length = fill_connect_data((char *)cp->data,
297 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800298 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700299}
300
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700301#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800302static char *connection_state_name(atransport *t)
303{
304 if (t == NULL) {
305 return "unknown";
306 }
307
308 switch(t->connection_state) {
309 case CS_BOOTLOADER:
310 return "bootloader";
311 case CS_DEVICE:
312 return "device";
trevda5ad5392013-04-17 14:34:23 +0100313 case CS_RECOVERY:
314 return "recovery";
315 case CS_SIDELOAD:
316 return "sideload";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317 case CS_OFFLINE:
318 return "offline";
Benoit Goby77e8e582013-01-15 12:36:47 -0800319 case CS_UNAUTHORIZED:
320 return "unauthorized";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800321 default:
322 return "unknown";
323 }
324}
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700325#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800326
Scott Andersone82c2db2012-05-25 14:10:02 -0700327/* qual_overwrite is used to overwrite a qualifier string. dst is a
328 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700329 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700330 */
331static void qual_overwrite(char **dst, const char *src)
332{
333 if (!dst)
334 return;
335
336 free(*dst);
337 *dst = NULL;
338
339 if (!src || !*src)
340 return;
341
342 *dst = strdup(src);
343}
344
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345void parse_banner(char *banner, atransport *t)
346{
Scott Andersone82c2db2012-05-25 14:10:02 -0700347 static const char *prop_seps = ";";
348 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700349 char *cp;
350 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351
352 D("parse_banner: %s\n", banner);
353 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700354 cp = strchr(type, ':');
355 if (cp) {
356 *cp++ = 0;
357 /* Nothing is done with second field. */
358 cp = strchr(cp, ':');
359 if (cp) {
360 char *save;
361 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700362 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700363 while (key) {
364 cp = strchr(key, key_val_sep);
365 if (cp) {
366 *cp++ = '\0';
367 if (!strcmp(key, "ro.product.name"))
368 qual_overwrite(&t->product, cp);
369 else if (!strcmp(key, "ro.product.model"))
370 qual_overwrite(&t->model, cp);
371 else if (!strcmp(key, "ro.product.device"))
372 qual_overwrite(&t->device, cp);
373 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700374 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700375 }
376 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377 }
378
379 if(!strcmp(type, "bootloader")){
380 D("setting connection_state to CS_BOOTLOADER\n");
381 t->connection_state = CS_BOOTLOADER;
382 update_transports();
383 return;
384 }
385
386 if(!strcmp(type, "device")) {
387 D("setting connection_state to CS_DEVICE\n");
388 t->connection_state = CS_DEVICE;
389 update_transports();
390 return;
391 }
392
393 if(!strcmp(type, "recovery")) {
394 D("setting connection_state to CS_RECOVERY\n");
395 t->connection_state = CS_RECOVERY;
396 update_transports();
397 return;
398 }
399
Doug Zongker447f0612012-01-09 14:54:53 -0800400 if(!strcmp(type, "sideload")) {
401 D("setting connection_state to CS_SIDELOAD\n");
402 t->connection_state = CS_SIDELOAD;
403 update_transports();
404 return;
405 }
406
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407 t->connection_state = CS_HOST;
408}
409
410void handle_packet(apacket *p, atransport *t)
411{
412 asocket *s;
413
Viral Mehta899913f2010-06-16 18:41:28 +0530414 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
415 ((char*) (&(p->msg.command)))[1],
416 ((char*) (&(p->msg.command)))[2],
417 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800418 print_packet("recv", p);
419
420 switch(p->msg.command){
421 case A_SYNC:
422 if(p->msg.arg0){
423 send_packet(p, t);
424 if(HOST) send_connect(t);
425 } else {
426 t->connection_state = CS_OFFLINE;
427 handle_offline(t);
428 send_packet(p, t);
429 }
430 return;
431
432 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
433 /* XXX verify version, etc */
434 if(t->connection_state != CS_OFFLINE) {
435 t->connection_state = CS_OFFLINE;
436 handle_offline(t);
437 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700438
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700440
441 if (HOST || !auth_enabled) {
442 handle_online(t);
443 if(!HOST) send_connect(t);
444 } else {
445 send_auth_request(t);
446 }
447 break;
448
449 case A_AUTH:
450 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
Benoit Goby77e8e582013-01-15 12:36:47 -0800451 t->connection_state = CS_UNAUTHORIZED;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700452 t->key = adb_auth_nextkey(t->key);
453 if (t->key) {
454 send_auth_response(p->data, p->msg.data_length, t);
455 } else {
456 /* No more private keys to try, send the public key */
457 send_auth_publickey(t);
458 }
459 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
460 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
461 adb_auth_verified(t);
462 t->failed_auth_attempts = 0;
463 } else {
464 if (t->failed_auth_attempts++ > 10)
465 adb_sleep_ms(1000);
466 send_auth_request(t);
467 }
468 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
469 adb_auth_confirm_key(p->data, p->msg.data_length, t);
470 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471 break;
472
473 case A_OPEN: /* OPEN(local-id, 0, "destination") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100474 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475 char *name = (char*) p->data;
476 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
477 s = create_local_service_socket(name);
478 if(s == 0) {
479 send_close(0, p->msg.arg0, t);
480 } else {
481 s->peer = create_remote_socket(p->msg.arg0, t);
482 s->peer->peer = s;
483 send_ready(s->id, s->peer->id, t);
484 s->ready(s);
485 }
486 }
487 break;
488
489 case A_OKAY: /* READY(local-id, remote-id, "") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100490 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
491 if((s = find_local_socket(p->msg.arg1, 0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492 if(s->peer == 0) {
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100493 /* On first READY message, create the connection. */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494 s->peer = create_remote_socket(p->msg.arg0, t);
495 s->peer->peer = s;
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100496 s->ready(s);
497 } else if (s->peer->id == p->msg.arg0) {
498 /* Other READY messages must use the same local-id */
499 s->ready(s);
500 } else {
501 D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s\n",
502 p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800504 }
505 }
506 break;
507
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100508 case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
509 if (t->online && p->msg.arg1 != 0) {
510 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
511 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
512 * a failed OPEN only. However, due to a bug in previous ADB
513 * versions, CLOSE(0, remote-id, "") was also used for normal
514 * CLOSE() operations.
515 *
516 * This is bad because it means a compromised adbd could
517 * send packets to close connections between the host and
518 * other devices. To avoid this, only allow this if the local
519 * socket has a peer on the same transport.
520 */
521 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
522 D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s\n",
523 p->msg.arg1, t->serial, s->peer->transport->serial);
524 } else {
525 s->close(s);
526 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527 }
528 }
529 break;
530
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100531 case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
532 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
533 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 unsigned rid = p->msg.arg0;
535 p->len = p->msg.data_length;
536
537 if(s->enqueue(s, p) == 0) {
538 D("Enqueue the socket\n");
539 send_ready(s->id, rid, t);
540 }
541 return;
542 }
543 }
544 break;
545
546 default:
547 printf("handle_packet: what is %08x?!\n", p->msg.command);
548 }
549
550 put_apacket(p);
551}
552
Yabin Cuie77b6a02014-11-11 09:24:11 -0800553#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554static BOOL WINAPI ctrlc_handler(DWORD type)
555{
556 exit(STATUS_CONTROL_C_EXIT);
557 return TRUE;
558}
559#endif
560
561static void adb_cleanup(void)
562{
563 usb_cleanup();
564}
565
566void start_logging(void)
567{
Yabin Cuie77b6a02014-11-11 09:24:11 -0800568#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800569 char temp[ MAX_PATH ];
570 FILE* fnul;
571 FILE* flog;
572
573 GetTempPath( sizeof(temp) - 8, temp );
574 strcat( temp, "adb.log" );
575
576 /* Win32 specific redirections */
577 fnul = fopen( "NUL", "rt" );
578 if (fnul != NULL)
579 stdin[0] = fnul[0];
580
581 flog = fopen( temp, "at" );
582 if (flog == NULL)
583 flog = fnul;
584
585 setvbuf( flog, NULL, _IONBF, 0 );
586
587 stdout[0] = flog[0];
588 stderr[0] = flog[0];
589 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
590#else
591 int fd;
592
593 fd = unix_open("/dev/null", O_RDONLY);
594 dup2(fd, 0);
JP Abgrall408fa572011-03-16 15:57:42 -0700595 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800596
597 fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
598 if(fd < 0) {
599 fd = unix_open("/dev/null", O_WRONLY);
600 }
601 dup2(fd, 1);
602 dup2(fd, 2);
JP Abgrall408fa572011-03-16 15:57:42 -0700603 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
605#endif
606}
607
608#if !ADB_HOST
609void start_device_log(void)
610{
611 int fd;
Mike Lockwood1f546e62009-05-25 18:17:55 -0400612 char path[PATH_MAX];
613 struct tm now;
614 time_t t;
615 char value[PROPERTY_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616
Mike Lockwood1f546e62009-05-25 18:17:55 -0400617 // read the trace mask from persistent property persist.adb.trace_mask
618 // give up if the property is not set or cannot be parsed
619 property_get("persist.adb.trace_mask", value, "");
620 if (sscanf(value, "%x", &adb_trace_mask) != 1)
621 return;
622
623 adb_mkdir("/data/adb", 0775);
624 tzset();
625 time(&t);
626 localtime_r(&t, &now);
627 strftime(path, sizeof(path),
628 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
629 &now);
630 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800631 if (fd < 0)
632 return;
633
634 // redirect stdout and stderr to the log file
635 dup2(fd, 1);
636 dup2(fd, 2);
637 fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
Benoit Goby95ef8282011-02-01 18:57:41 -0800638 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800639
640 fd = unix_open("/dev/null", O_RDONLY);
641 dup2(fd, 0);
Benoit Goby95ef8282011-02-01 18:57:41 -0800642 adb_close(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800643}
644#endif
645
646#if ADB_HOST
JP Abgrall571c1362012-12-06 18:18:12 -0800647
648#ifdef WORKAROUND_BUG6558362
649#include <sched.h>
650#define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
651void adb_set_affinity(void)
652{
653 cpu_set_t cpu_set;
654 const char* cpunum_str = getenv(AFFINITY_ENVVAR);
655 char* strtol_res;
656 int cpu_num;
657
658 if (!cpunum_str || !*cpunum_str)
659 return;
660 cpu_num = strtol(cpunum_str, &strtol_res, 0);
661 if (*strtol_res != '\0')
662 fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
663
664 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
665 D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
666 CPU_ZERO(&cpu_set);
667 CPU_SET(cpu_num, &cpu_set);
668 sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
669 sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
670 D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
671}
672#endif
673
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100674int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800675{
Yabin Cuie77b6a02014-11-11 09:24:11 -0800676#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 /* we need to start the server in the background */
678 /* we create a PIPE that will be used to wait for the server's "OK" */
679 /* message since the pipe handles must be inheritable, we use a */
680 /* security attribute */
681 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000682 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800683 SECURITY_ATTRIBUTES sa;
684 STARTUPINFO startup;
685 PROCESS_INFORMATION pinfo;
686 char program_path[ MAX_PATH ];
687 int ret;
688
689 sa.nLength = sizeof(sa);
690 sa.lpSecurityDescriptor = NULL;
691 sa.bInheritHandle = TRUE;
692
693 /* create pipe, and ensure its read handle isn't inheritable */
694 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
695 if (!ret) {
696 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
697 return -1;
698 }
699
700 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
701
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000702 /* Some programs want to launch an adb command and collect its output by
703 * calling CreateProcess with inheritable stdout/stderr handles, then
704 * using read() to get its output. When this happens, the stdout/stderr
705 * handles passed to the adb client process will also be inheritable.
706 * When starting the adb server here, care must be taken to reset them
707 * to non-inheritable.
708 * Otherwise, something bad happens: even if the adb command completes,
709 * the calling process is stuck while read()-ing from the stdout/stderr
710 * descriptors, because they're connected to corresponding handles in the
711 * adb server process (even if the latter never uses/writes to them).
712 */
713 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
714 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
715 if (stdout_handle != INVALID_HANDLE_VALUE) {
716 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
717 }
718 if (stderr_handle != INVALID_HANDLE_VALUE) {
719 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
720 }
721
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722 ZeroMemory( &startup, sizeof(startup) );
723 startup.cb = sizeof(startup);
724 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
725 startup.hStdOutput = pipe_write;
726 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
727 startup.dwFlags = STARTF_USESTDHANDLES;
728
729 ZeroMemory( &pinfo, sizeof(pinfo) );
730
731 /* get path of current program */
732 GetModuleFileName( NULL, program_path, sizeof(program_path) );
Wenhao Lia09558c2013-11-13 16:23:37 +0800733 char args[64];
734 snprintf(args, sizeof(args), "adb -P %d fork-server server", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 ret = CreateProcess(
736 program_path, /* program path */
Wenhao Lia09558c2013-11-13 16:23:37 +0800737 args,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 /* the fork-server argument will set the
739 debug = 2 in the child */
740 NULL, /* process handle is not inheritable */
741 NULL, /* thread handle is not inheritable */
742 TRUE, /* yes, inherit some handles */
743 DETACHED_PROCESS, /* the new process doesn't have a console */
744 NULL, /* use parent's environment block */
745 NULL, /* use parent's starting directory */
746 &startup, /* startup info, i.e. std handles */
747 &pinfo );
748
749 CloseHandle( pipe_write );
750
751 if (!ret) {
752 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
753 CloseHandle( pipe_read );
754 return -1;
755 }
756
757 CloseHandle( pinfo.hProcess );
758 CloseHandle( pinfo.hThread );
759
760 /* wait for the "OK\n" message */
761 {
762 char temp[3];
763 DWORD count;
764
765 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
766 CloseHandle( pipe_read );
767 if ( !ret ) {
768 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
769 return -1;
770 }
771 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
772 fprintf(stderr, "ADB server didn't ACK\n" );
773 return -1;
774 }
775 }
Yabin Cuie77b6a02014-11-11 09:24:11 -0800776#else /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800777 char path[PATH_MAX];
778 int fd[2];
779
780 // set up a pipe so the child can tell us when it is ready.
781 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
782 if (pipe(fd)) {
783 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
784 return -1;
785 }
Alexey Tarasov31664102009-10-22 02:55:00 +1100786 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800787 pid_t pid = fork();
788 if(pid < 0) return -1;
789
790 if (pid == 0) {
791 // child side of the fork
792
793 // redirect stderr to the pipe
794 // we use stderr instead of stdout due to stdout's buffering behavior.
795 adb_close(fd[0]);
796 dup2(fd[1], STDERR_FILENO);
797 adb_close(fd[1]);
798
Matt Gumbeld7b33082012-11-14 10:16:17 -0800799 char str_port[30];
800 snprintf(str_port, sizeof(str_port), "%d", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800801 // child process
Matt Gumbeld7b33082012-11-14 10:16:17 -0800802 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800803 // this should not return
804 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
805 } else {
806 // parent side of the fork
807
808 char temp[3];
809
810 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
811 // wait for the "OK\n" message
812 adb_close(fd[1]);
813 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -0700814 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800815 adb_close(fd[0]);
816 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -0700817 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818 return -1;
819 }
820 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
821 fprintf(stderr, "ADB server didn't ACK\n" );
822 return -1;
823 }
824
825 setsid();
826 }
Yabin Cuie77b6a02014-11-11 09:24:11 -0800827#endif /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 return 0;
829}
Yabin Cuie77b6a02014-11-11 09:24:11 -0800830#endif /* ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100832/* Constructs a local name of form tcp:port.
833 * target_str points to the target string, it's content will be overwritten.
834 * target_size is the capacity of the target string.
835 * server_port is the port number to use for the local name.
836 */
837void build_local_name(char* target_str, size_t target_size, int server_port)
838{
839 snprintf(target_str, target_size, "tcp:%d", server_port);
840}
841
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800842#if !ADB_HOST
Nick Kralevich080427e2013-02-15 14:39:15 -0800843
844static void drop_capabilities_bounding_set_if_needed() {
845#ifdef ALLOW_ADBD_ROOT
846 char value[PROPERTY_VALUE_MAX];
847 property_get("ro.debuggable", value, "");
848 if (strcmp(value, "1") == 0) {
849 return;
850 }
851#endif
852 int i;
853 for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
Nick Kralevichca8e66a2013-04-18 12:20:02 -0700854 if (i == CAP_SETUID || i == CAP_SETGID) {
Nick Kralevich080427e2013-02-15 14:39:15 -0800855 // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
856 continue;
857 }
858 int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
859
860 // Some kernels don't have file capabilities compiled in, and
861 // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
862 // die when we see such misconfigured kernels.
863 if ((err < 0) && (errno != EINVAL)) {
864 exit(1);
865 }
866 }
867}
868
Dan Pasanen98858812014-10-06 12:57:20 -0500869static bool should_drop_privileges() {
870#if defined(ALLOW_ADBD_ROOT)
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800871 char value[PROPERTY_VALUE_MAX];
872
Dan Pasanen98858812014-10-06 12:57:20 -0500873 // The emulator is never secure, so don't drop privileges there.
874 // TODO: this seems like a bug --- shouldn't the emulator behave like a device?
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800875 property_get("ro.kernel.qemu", value, "");
Dan Pasanen98858812014-10-06 12:57:20 -0500876 if (strcmp(value, "1") == 0) {
877 return false;
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800878 }
Dan Pasanen98858812014-10-06 12:57:20 -0500879
Dan Pasanen98858812014-10-06 12:57:20 -0500880 property_get("ro.secure", value, "1");
881 bool ro_secure = (strcmp(value, "1") == 0);
882
Elliott Hughes4c9d24a2015-02-18 16:57:30 -0800883 // Drop privileges if ro.secure is set...
884 bool drop = ro_secure;
885
Dan Pasanen98858812014-10-06 12:57:20 -0500886 property_get("ro.debuggable", value, "");
887 bool ro_debuggable = (strcmp(value, "1") == 0);
Dan Pasanen98858812014-10-06 12:57:20 -0500888 property_get("service.adb.root", value, "");
889 bool adb_root = (strcmp(value, "1") == 0);
890 bool adb_unroot = (strcmp(value, "0") == 0);
Elliott Hughes4c9d24a2015-02-18 16:57:30 -0800891
892 // ...except "adb root" lets you keep privileges in a debuggable build.
893 if (ro_debuggable && adb_root) {
894 drop = false;
Dan Pasanen98858812014-10-06 12:57:20 -0500895 }
896
Elliott Hughes4c9d24a2015-02-18 16:57:30 -0800897 // ...and "adb unroot" lets you explicitly drop privileges.
898 if (adb_unroot) {
899 drop = true;
900 }
901
902 return drop;
Dan Pasanen98858812014-10-06 12:57:20 -0500903#else
904 return true; // "adb root" not allowed, always drop privileges.
Nick Kralevich5890fe32012-01-19 13:11:35 -0800905#endif /* ALLOW_ADBD_ROOT */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800906}
907#endif /* !ADB_HOST */
908
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100909int adb_main(int is_daemon, int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800910{
911#if !ADB_HOST
Mike Lockwood2f38b692009-08-24 15:58:40 -0700912 int port;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800913 char value[PROPERTY_VALUE_MAX];
Nick Kralevicheb68fa82012-04-02 13:00:35 -0700914
915 umask(000);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800916#endif
917
918 atexit(adb_cleanup);
Yabin Cuie77b6a02014-11-11 09:24:11 -0800919#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800920 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
Yabin Cuie77b6a02014-11-11 09:24:11 -0800921#else
JP Abgrall408fa572011-03-16 15:57:42 -0700922 // No SIGCHLD. Let the service subproc handle its children.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800923 signal(SIGPIPE, SIG_IGN);
924#endif
925
926 init_transport_registration();
927
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800928#if ADB_HOST
929 HOST = 1;
JP Abgrall571c1362012-12-06 18:18:12 -0800930
931#ifdef WORKAROUND_BUG6558362
932 if(is_daemon) adb_set_affinity();
933#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800934 usb_init();
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100935 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700936 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100938 char local_name[30];
939 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100940 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800941 exit(1);
942 }
943#else
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700944 property_get("ro.adb.secure", value, "0");
945 auth_enabled = !strcmp(value, "1");
946 if (auth_enabled)
947 adb_auth_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800948
Jeff Sharkeyd6d42862012-09-06 13:05:40 -0700949 // Our external storage path may be different than apps, since
950 // we aren't able to bind mount after dropping root.
951 const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
952 if (NULL != adb_external_storage) {
953 setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
954 } else {
955 D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
956 " unchanged.\n");
957 }
958
Nick Kraleviche5cbf4e2014-06-18 11:24:27 -0700959 /* add extra groups:
960 ** AID_ADB to access the USB driver
961 ** AID_LOG to read system logs (adb logcat)
962 ** AID_INPUT to diagnose input issues (getevent)
Elliott Hughes187eade2015-02-03 11:59:22 -0800963 ** AID_INET to diagnose network issues (ping)
Nick Kraleviche5cbf4e2014-06-18 11:24:27 -0700964 ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
965 ** AID_SDCARD_R to allow reading from the SD card
966 ** AID_SDCARD_RW to allow writing to the SD card
967 ** AID_NET_BW_STATS to read out qtaguid statistics
968 */
Ajay Dudani8432ddc2014-11-21 11:57:29 -0800969 gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT,
970 AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
Nick Kraleviche5cbf4e2014-06-18 11:24:27 -0700971 AID_NET_BW_STATS };
972 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
973 exit(1);
974 }
975
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100976 /* don't listen on a port (default 5037) if running in secure mode */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800977 /* don't run as root if we are running in secure mode */
Nick Kralevichbd9206b2012-01-19 10:18:59 -0800978 if (should_drop_privileges()) {
Nick Kralevich080427e2013-02-15 14:39:15 -0800979 drop_capabilities_bounding_set_if_needed();
980
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800981 /* then switch user and group to "shell" */
Nick Kralevich44db9902010-08-27 14:35:07 -0700982 if (setgid(AID_SHELL) != 0) {
983 exit(1);
984 }
985 if (setuid(AID_SHELL) != 0) {
986 exit(1);
987 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800988
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100989 D("Local port disabled\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100991 char local_name[30];
Nick Kralevichd49aa252014-01-18 09:25:04 -0800992 if ((root_seclabel != NULL) && (is_selinux_enabled() > 0)) {
993 // b/12587913: fix setcon to allow const pointers
994 if (setcon((char *)root_seclabel) < 0) {
995 exit(1);
996 }
997 }
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100998 build_local_name(local_name, sizeof(local_name), server_port);
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100999 if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001000 exit(1);
1001 }
1002 }
1003
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001004 int usb = 0;
1005 if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001006 // listen on USB
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 usb_init();
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001008 usb = 1;
1009 }
1010
1011 // If one of these properties is set, also listen on that port
1012 // If one of the properties isn't set and we couldn't listen on usb,
1013 // listen on the default port.
1014 property_get("service.adb.tcp.port", value, "");
1015 if (!value[0]) {
1016 property_get("persist.adb.tcp.port", value, "");
1017 }
1018 if (sscanf(value, "%d", &port) == 1 && port > 0) {
1019 printf("using port=%d\n", port);
1020 // listen on TCP port specified by service.adb.tcp.port property
1021 local_init(port);
1022 } else if (!usb) {
Mike Lockwoodcef31a02009-08-26 12:50:22 -07001023 // listen on default port
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001024 local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025 }
Mike J. Chen1dd55c52012-07-20 18:16:21 -07001026
JP Abgrall408fa572011-03-16 15:57:42 -07001027 D("adb_main(): pre init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001028 init_jdwp();
JP Abgrall408fa572011-03-16 15:57:42 -07001029 D("adb_main(): post init_jdwp()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030#endif
1031
1032 if (is_daemon)
1033 {
1034 // inform our parent that we are up and running.
Yabin Cuie77b6a02014-11-11 09:24:11 -08001035#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001036 DWORD count;
1037 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
Yabin Cuie77b6a02014-11-11 09:24:11 -08001038#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001039 fprintf(stderr, "OK\n");
1040#endif
1041 start_logging();
1042 }
JP Abgrall408fa572011-03-16 15:57:42 -07001043 D("Event loop starting\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001044
1045 fdevent_loop();
1046
1047 usb_cleanup();
1048
1049 return 0;
1050}
1051
David 'Digit' Turner25258692013-03-21 21:07:42 +01001052// Try to handle a network forwarding request.
1053// This returns 1 on success, 0 on failure, and -1 to indicate this is not
1054// a forwarding-related request.
1055int handle_forward_request(const char* service, transport_type ttype, char* serial, int reply_fd)
1056{
1057 if (!strcmp(service, "list-forward")) {
1058 // Create the list of forward redirections.
1059 int buffer_size = format_listeners(NULL, 0);
1060 // Add one byte for the trailing zero.
1061 char* buffer = malloc(buffer_size + 1);
1062 if (buffer == NULL) {
1063 sendfailmsg(reply_fd, "not enough memory");
1064 return 1;
1065 }
1066 (void) format_listeners(buffer, buffer_size + 1);
1067#if ADB_HOST
1068 send_msg_with_okay(reply_fd, buffer, buffer_size);
1069#else
1070 send_msg_with_header(reply_fd, buffer, buffer_size);
1071#endif
1072 free(buffer);
1073 return 1;
1074 }
1075
1076 if (!strcmp(service, "killforward-all")) {
1077 remove_all_listeners();
1078#if ADB_HOST
1079 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
1080 adb_write(reply_fd, "OKAY", 4);
1081#endif
1082 adb_write(reply_fd, "OKAY", 4);
1083 return 1;
1084 }
1085
1086 if (!strncmp(service, "forward:",8) ||
1087 !strncmp(service, "killforward:",12)) {
1088 char *local, *remote, *err;
1089 int r;
1090 atransport *transport;
1091
1092 int createForward = strncmp(service, "kill", 4);
1093 int no_rebind = 0;
1094
1095 local = strchr(service, ':') + 1;
1096
1097 // Handle forward:norebind:<local>... here
1098 if (createForward && !strncmp(local, "norebind:", 9)) {
1099 no_rebind = 1;
1100 local = strchr(local, ':') + 1;
1101 }
1102
1103 remote = strchr(local,';');
1104
1105 if (createForward) {
1106 // Check forward: parameter format: '<local>;<remote>'
1107 if(remote == 0) {
1108 sendfailmsg(reply_fd, "malformed forward spec");
1109 return 1;
1110 }
1111
1112 *remote++ = 0;
1113 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')) {
1114 sendfailmsg(reply_fd, "malformed forward spec");
1115 return 1;
1116 }
1117 } else {
1118 // Check killforward: parameter format: '<local>'
1119 if (local[0] == 0) {
1120 sendfailmsg(reply_fd, "malformed forward spec");
1121 return 1;
1122 }
1123 }
1124
1125 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1126 if (!transport) {
1127 sendfailmsg(reply_fd, err);
1128 return 1;
1129 }
1130
1131 if (createForward) {
1132 r = install_listener(local, remote, transport, no_rebind);
1133 } else {
1134 r = remove_listener(local, transport);
1135 }
1136 if(r == 0) {
1137#if ADB_HOST
1138 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
1139 writex(reply_fd, "OKAY", 4);
1140#endif
1141 writex(reply_fd, "OKAY", 4);
1142 return 1;
1143 }
1144
1145 if (createForward) {
1146 const char* message;
1147 switch (r) {
1148 case INSTALL_STATUS_CANNOT_BIND:
1149 message = "cannot bind to socket";
1150 break;
1151 case INSTALL_STATUS_CANNOT_REBIND:
1152 message = "cannot rebind existing socket";
1153 break;
1154 default:
1155 message = "internal error";
1156 }
1157 sendfailmsg(reply_fd, message);
1158 } else {
1159 sendfailmsg(reply_fd, "cannot remove listener");
1160 }
1161 return 1;
1162 }
1163 return 0;
1164}
1165
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1167{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001168 if(!strcmp(service, "kill")) {
1169 fprintf(stderr,"adb server killed by remote request\n");
1170 fflush(stdout);
1171 adb_write(reply_fd, "OKAY", 4);
1172 usb_cleanup();
1173 exit(0);
1174 }
1175
1176#if ADB_HOST
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -07001177 atransport *transport = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001178 // "transport:" is used for switching transport with a specified serial number
1179 // "transport-usb:" is used for switching transport to the only USB transport
1180 // "transport-local:" is used for switching transport to the only local transport
1181 // "transport-any:" is used for switching transport to the only transport
1182 if (!strncmp(service, "transport", strlen("transport"))) {
1183 char* error_string = "unknown failure";
1184 transport_type type = kTransportAny;
1185
1186 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1187 type = kTransportUsb;
1188 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1189 type = kTransportLocal;
1190 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1191 type = kTransportAny;
1192 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1193 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -05001194 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001195 }
1196
1197 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1198
1199 if (transport) {
1200 s->transport = transport;
1201 adb_write(reply_fd, "OKAY", 4);
1202 } else {
1203 sendfailmsg(reply_fd, error_string);
1204 }
1205 return 1;
1206 }
1207
1208 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -07001209 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001210 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -07001211 int use_long = !strcmp(service+7, "-l");
1212 if (use_long || service[7] == 0) {
Scott Andersone109d262012-04-20 11:21:14 -07001213 memset(buffer, 0, sizeof(buffer));
1214 D("Getting device list \n");
1215 list_transports(buffer, sizeof(buffer), use_long);
Scott Andersone109d262012-04-20 11:21:14 -07001216 D("Wrote device list \n");
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001217 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
Scott Andersone109d262012-04-20 11:21:14 -07001218 return 0;
1219 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001220 }
1221
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001222 // remove TCP transport
1223 if (!strncmp(service, "disconnect:", 11)) {
1224 char buffer[4096];
1225 memset(buffer, 0, sizeof(buffer));
1226 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001227 if (serial[0] == 0) {
1228 // disconnect from all TCP devices
1229 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001230 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001231 char hostbuf[100];
1232 // assume port 5555 if no port is specified
1233 if (!strchr(serial, ':')) {
1234 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
1235 serial = hostbuf;
1236 }
1237 atransport *t = find_transport(serial);
1238
1239 if (t) {
1240 unregister_transport(t);
1241 } else {
1242 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1243 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -04001244 }
1245
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001246 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -07001247 return 0;
1248 }
1249
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001250 // returns our value for ADB_SERVER_VERSION
1251 if (!strcmp(service, "version")) {
1252 char version[12];
1253 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001254 send_msg_with_okay(reply_fd, version, strlen(version));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001255 return 0;
1256 }
1257
1258 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1259 char *out = "unknown";
1260 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1261 if (transport && transport->serial) {
1262 out = transport->serial;
1263 }
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001264 send_msg_with_okay(reply_fd, out, strlen(out));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001265 return 0;
1266 }
Scott Andersone109d262012-04-20 11:21:14 -07001267 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
1268 char *out = "unknown";
1269 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1270 if (transport && transport->devpath) {
1271 out = transport->devpath;
1272 }
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001273 send_msg_with_okay(reply_fd, out, strlen(out));
Scott Andersone109d262012-04-20 11:21:14 -07001274 return 0;
1275 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001276 // indicates a new emulator instance has started
1277 if (!strncmp(service,"emulator:",9)) {
1278 int port = atoi(service+9);
1279 local_connect(port);
1280 /* we don't even need to send a reply */
1281 return 0;
1282 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001283
1284 if(!strncmp(service,"get-state",strlen("get-state"))) {
1285 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1286 char *state = connection_state_name(transport);
Snild Dolkow2264e7c2014-01-30 10:08:38 +01001287 send_msg_with_okay(reply_fd, state, strlen(state));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001288 return 0;
1289 }
Simon Yedc22c3c2014-07-14 17:23:06 -07001290#endif // ADB_HOST
1291
1292 int ret = handle_forward_request(service, ttype, serial, reply_fd);
1293 if (ret >= 0)
1294 return ret - 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001295 return -1;
1296}
1297
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001298int main(int argc, char **argv)
1299{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001300#if ADB_HOST
1301 adb_sysdeps_init();
JP Abgrall408fa572011-03-16 15:57:42 -07001302 adb_trace_init();
1303 D("Handling commandline()\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001304 return adb_commandline(argc - 1, argv + 1);
1305#else
Vladimir Chtchetkine28781b02012-02-27 10:41:53 -08001306 /* If adbd runs inside the emulator this will enable adb tracing via
1307 * adb-debug qemud service in the emulator. */
1308 adb_qemu_trace_init();
Nick Kralevichd49aa252014-01-18 09:25:04 -08001309 while(1) {
1310 int c;
1311 int option_index = 0;
1312 static struct option opts[] = {
1313 {"root_seclabel", required_argument, 0, 's' },
1314 {"device_banner", required_argument, 0, 'b' }
1315 };
1316 c = getopt_long(argc, argv, "", opts, &option_index);
1317 if (c == -1)
1318 break;
1319 switch (c) {
1320 case 's':
1321 root_seclabel = optarg;
1322 break;
1323 case 'b':
1324 adb_device_banner = optarg;
1325 break;
1326 default:
1327 break;
1328 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001329 }
Mike Lockwood1f546e62009-05-25 18:17:55 -04001330
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001331 start_device_log();
JP Abgrall408fa572011-03-16 15:57:42 -07001332 D("Handling main()\n");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001333 return adb_main(0, DEFAULT_ADB_PORT);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001334#endif
1335}