blob: 9c0bd8c26ff74fa445700748387557fb302711e9 [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 Albert76649012015-02-24 15:51:19 -080034#include "transport.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>
Nick Kraleviche2864bf2013-02-28 14:12:58 -080040#include <sys/capability.h>
Jeff Sharkey885342a2012-08-14 21:00:22 -070041#include <sys/mount.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#endif
43
JP Abgrall408fa572011-03-16 15:57:42 -070044#if ADB_TRACE
45ADB_MUTEX_DEFINE( D_lock );
46#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047
48int HOST = 0;
49
Scott Andersone82c2db2012-05-25 14:10:02 -070050#if !ADB_HOST
Dan Albertbd0b7502015-02-18 18:22:45 -080051const char *adb_device_banner = "device";
Scott Andersone82c2db2012-05-25 14:10:02 -070052#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080053
54void fatal(const char *fmt, ...)
55{
56 va_list ap;
57 va_start(ap, fmt);
58 fprintf(stderr, "error: ");
59 vfprintf(stderr, fmt, ap);
60 fprintf(stderr, "\n");
61 va_end(ap);
62 exit(-1);
63}
64
65void fatal_errno(const char *fmt, ...)
66{
67 va_list ap;
68 va_start(ap, fmt);
69 fprintf(stderr, "error: %s: ", strerror(errno));
70 vfprintf(stderr, fmt, ap);
71 fprintf(stderr, "\n");
72 va_end(ap);
73 exit(-1);
74}
75
76int adb_trace_mask;
77
78/* read a comma/space/colum/semi-column separated list of tags
79 * from the ADB_TRACE environment variable and build the trace
80 * mask from it. note that '1' and 'all' are special cases to
81 * enable all tracing
82 */
83void adb_trace_init(void)
84{
85 const char* p = getenv("ADB_TRACE");
86 const char* q;
87
88 static const struct {
89 const char* tag;
90 int flag;
91 } tags[] = {
92 { "1", 0 },
93 { "all", 0 },
94 { "adb", TRACE_ADB },
95 { "sockets", TRACE_SOCKETS },
96 { "packets", TRACE_PACKETS },
97 { "rwx", TRACE_RWX },
98 { "usb", TRACE_USB },
99 { "sync", TRACE_SYNC },
100 { "sysdeps", TRACE_SYSDEPS },
101 { "transport", TRACE_TRANSPORT },
102 { "jdwp", TRACE_JDWP },
JP Abgrall408fa572011-03-16 15:57:42 -0700103 { "services", TRACE_SERVICES },
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700104 { "auth", TRACE_AUTH },
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800105 { NULL, 0 }
106 };
107
108 if (p == NULL)
109 return;
110
111 /* use a comma/column/semi-colum/space separated list */
112 while (*p) {
113 int len, tagn;
114
115 q = strpbrk(p, " ,:;");
116 if (q == NULL) {
117 q = p + strlen(p);
118 }
119 len = q - p;
120
121 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
122 {
123 int taglen = strlen(tags[tagn].tag);
124
125 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
126 {
127 int flag = tags[tagn].flag;
128 if (flag == 0) {
129 adb_trace_mask = ~0;
130 return;
131 }
132 adb_trace_mask |= (1 << flag);
133 break;
134 }
135 }
136 p = q;
137 if (*p)
138 p++;
139 }
140}
141
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800142apacket *get_apacket(void)
143{
144 apacket *p = malloc(sizeof(apacket));
145 if(p == 0) fatal("failed to allocate an apacket");
146 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
147 return p;
148}
149
150void put_apacket(apacket *p)
151{
152 free(p);
153}
154
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700155void handle_online(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800156{
157 D("adb: online\n");
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700158 t->online = 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800159}
160
161void handle_offline(atransport *t)
162{
163 D("adb: offline\n");
164 //Close the associated usb
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700165 t->online = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800166 run_transport_disconnects(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167}
168
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700169#if DEBUG_PACKETS
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800170#define DUMPMAX 32
171void print_packet(const char *label, apacket *p)
172{
173 char *tag;
174 char *x;
175 unsigned count;
176
177 switch(p->msg.command){
178 case A_SYNC: tag = "SYNC"; break;
179 case A_CNXN: tag = "CNXN" ; break;
180 case A_OPEN: tag = "OPEN"; break;
181 case A_OKAY: tag = "OKAY"; break;
182 case A_CLSE: tag = "CLSE"; break;
183 case A_WRTE: tag = "WRTE"; break;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700184 case A_AUTH: tag = "AUTH"; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800185 default: tag = "????"; break;
186 }
187
188 fprintf(stderr, "%s: %s %08x %08x %04x \"",
189 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
190 count = p->msg.data_length;
191 x = (char*) p->data;
192 if(count > DUMPMAX) {
193 count = DUMPMAX;
194 tag = "\n";
195 } else {
196 tag = "\"\n";
197 }
198 while(count-- > 0){
199 if((*x >= ' ') && (*x < 127)) {
200 fputc(*x, stderr);
201 } else {
202 fputc('.', stderr);
203 }
204 x++;
205 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700206 fputs(tag, stderr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207}
208#endif
209
210static void send_ready(unsigned local, unsigned remote, atransport *t)
211{
212 D("Calling send_ready \n");
213 apacket *p = get_apacket();
214 p->msg.command = A_OKAY;
215 p->msg.arg0 = local;
216 p->msg.arg1 = remote;
217 send_packet(p, t);
218}
219
220static void send_close(unsigned local, unsigned remote, atransport *t)
221{
222 D("Calling send_close \n");
223 apacket *p = get_apacket();
224 p->msg.command = A_CLSE;
225 p->msg.arg0 = local;
226 p->msg.arg1 = remote;
227 send_packet(p, t);
228}
229
Scott Andersone82c2db2012-05-25 14:10:02 -0700230static size_t fill_connect_data(char *buf, size_t bufsize)
231{
232#if ADB_HOST
233 return snprintf(buf, bufsize, "host::") + 1;
234#else
235 static const char *cnxn_props[] = {
236 "ro.product.name",
237 "ro.product.model",
238 "ro.product.device",
239 };
240 static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
241 int i;
242 size_t remaining = bufsize;
243 size_t len;
244
245 len = snprintf(buf, remaining, "%s::", adb_device_banner);
246 remaining -= len;
247 buf += len;
248 for (i = 0; i < num_cnxn_props; i++) {
249 char value[PROPERTY_VALUE_MAX];
250 property_get(cnxn_props[i], value, "");
251 len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
252 remaining -= len;
253 buf += len;
254 }
255
256 return bufsize - remaining + 1;
257#endif
258}
259
David 'Digit' Turner25258692013-03-21 21:07:42 +0100260#if !ADB_HOST
261static void send_msg_with_header(int fd, const char* msg, size_t msglen) {
262 char header[5];
263 if (msglen > 0xffff)
264 msglen = 0xffff;
265 snprintf(header, sizeof(header), "%04x", (unsigned)msglen);
266 writex(fd, header, 4);
267 writex(fd, msg, msglen);
268}
269#endif
270
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700271#if ADB_HOST
David 'Digit' Turner25258692013-03-21 21:07:42 +0100272static void send_msg_with_okay(int fd, const char* msg, size_t msglen) {
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100273 char header[9];
274 if (msglen > 0xffff)
275 msglen = 0xffff;
276 snprintf(header, sizeof(header), "OKAY%04x", (unsigned)msglen);
277 writex(fd, header, 8);
278 writex(fd, msg, msglen);
279}
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700280#endif // ADB_HOST
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100281
Dan Albertba3a2512015-02-18 17:47:33 -0800282void send_connect(atransport *t)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283{
284 D("Calling send_connect \n");
285 apacket *cp = get_apacket();
286 cp->msg.command = A_CNXN;
287 cp->msg.arg0 = A_VERSION;
288 cp->msg.arg1 = MAX_PAYLOAD;
Scott Andersone82c2db2012-05-25 14:10:02 -0700289 cp->msg.data_length = fill_connect_data((char *)cp->data,
290 sizeof(cp->data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800291 send_packet(cp, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700292}
293
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700294#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295static char *connection_state_name(atransport *t)
296{
297 if (t == NULL) {
298 return "unknown";
299 }
300
301 switch(t->connection_state) {
302 case CS_BOOTLOADER:
303 return "bootloader";
304 case CS_DEVICE:
305 return "device";
trevda5ad5392013-04-17 14:34:23 +0100306 case CS_RECOVERY:
307 return "recovery";
308 case CS_SIDELOAD:
309 return "sideload";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800310 case CS_OFFLINE:
311 return "offline";
Benoit Goby77e8e582013-01-15 12:36:47 -0800312 case CS_UNAUTHORIZED:
313 return "unauthorized";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800314 default:
315 return "unknown";
316 }
317}
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700318#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800319
Scott Andersone82c2db2012-05-25 14:10:02 -0700320/* qual_overwrite is used to overwrite a qualifier string. dst is a
321 * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700322 * was malloc'ed and needs to freed. *dst will be set to a dup of src.
Scott Andersone82c2db2012-05-25 14:10:02 -0700323 */
324static void qual_overwrite(char **dst, const char *src)
325{
326 if (!dst)
327 return;
328
329 free(*dst);
330 *dst = NULL;
331
332 if (!src || !*src)
333 return;
334
335 *dst = strdup(src);
336}
337
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800338void parse_banner(char *banner, atransport *t)
339{
Scott Andersone82c2db2012-05-25 14:10:02 -0700340 static const char *prop_seps = ";";
341 static const char key_val_sep = '=';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700342 char *cp;
343 char *type;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800344
345 D("parse_banner: %s\n", banner);
346 type = banner;
Scott Andersone82c2db2012-05-25 14:10:02 -0700347 cp = strchr(type, ':');
348 if (cp) {
349 *cp++ = 0;
350 /* Nothing is done with second field. */
351 cp = strchr(cp, ':');
352 if (cp) {
353 char *save;
354 char *key;
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700355 key = adb_strtok_r(cp + 1, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700356 while (key) {
357 cp = strchr(key, key_val_sep);
358 if (cp) {
359 *cp++ = '\0';
360 if (!strcmp(key, "ro.product.name"))
361 qual_overwrite(&t->product, cp);
362 else if (!strcmp(key, "ro.product.model"))
363 qual_overwrite(&t->model, cp);
364 else if (!strcmp(key, "ro.product.device"))
365 qual_overwrite(&t->device, cp);
366 }
Scott Anderson1b7a7e82012-06-05 17:54:27 -0700367 key = adb_strtok_r(NULL, prop_seps, &save);
Scott Andersone82c2db2012-05-25 14:10:02 -0700368 }
369 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800370 }
371
372 if(!strcmp(type, "bootloader")){
373 D("setting connection_state to CS_BOOTLOADER\n");
374 t->connection_state = CS_BOOTLOADER;
375 update_transports();
376 return;
377 }
378
379 if(!strcmp(type, "device")) {
380 D("setting connection_state to CS_DEVICE\n");
381 t->connection_state = CS_DEVICE;
382 update_transports();
383 return;
384 }
385
386 if(!strcmp(type, "recovery")) {
387 D("setting connection_state to CS_RECOVERY\n");
388 t->connection_state = CS_RECOVERY;
389 update_transports();
390 return;
391 }
392
Doug Zongker447f0612012-01-09 14:54:53 -0800393 if(!strcmp(type, "sideload")) {
394 D("setting connection_state to CS_SIDELOAD\n");
395 t->connection_state = CS_SIDELOAD;
396 update_transports();
397 return;
398 }
399
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800400 t->connection_state = CS_HOST;
401}
402
403void handle_packet(apacket *p, atransport *t)
404{
405 asocket *s;
406
Viral Mehta899913f2010-06-16 18:41:28 +0530407 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
408 ((char*) (&(p->msg.command)))[1],
409 ((char*) (&(p->msg.command)))[2],
410 ((char*) (&(p->msg.command)))[3]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800411 print_packet("recv", p);
412
413 switch(p->msg.command){
414 case A_SYNC:
415 if(p->msg.arg0){
416 send_packet(p, t);
417 if(HOST) send_connect(t);
418 } else {
419 t->connection_state = CS_OFFLINE;
420 handle_offline(t);
421 send_packet(p, t);
422 }
423 return;
424
425 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
426 /* XXX verify version, etc */
427 if(t->connection_state != CS_OFFLINE) {
428 t->connection_state = CS_OFFLINE;
429 handle_offline(t);
430 }
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700431
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800432 parse_banner((char*) p->data, t);
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700433
434 if (HOST || !auth_enabled) {
435 handle_online(t);
436 if(!HOST) send_connect(t);
437 } else {
438 send_auth_request(t);
439 }
440 break;
441
442 case A_AUTH:
443 if (p->msg.arg0 == ADB_AUTH_TOKEN) {
Benoit Goby77e8e582013-01-15 12:36:47 -0800444 t->connection_state = CS_UNAUTHORIZED;
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700445 t->key = adb_auth_nextkey(t->key);
446 if (t->key) {
447 send_auth_response(p->data, p->msg.data_length, t);
448 } else {
449 /* No more private keys to try, send the public key */
450 send_auth_publickey(t);
451 }
452 } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
453 if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
454 adb_auth_verified(t);
455 t->failed_auth_attempts = 0;
456 } else {
457 if (t->failed_auth_attempts++ > 10)
458 adb_sleep_ms(1000);
459 send_auth_request(t);
460 }
461 } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
462 adb_auth_confirm_key(p->data, p->msg.data_length, t);
463 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464 break;
465
466 case A_OPEN: /* OPEN(local-id, 0, "destination") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100467 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468 char *name = (char*) p->data;
469 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
470 s = create_local_service_socket(name);
471 if(s == 0) {
472 send_close(0, p->msg.arg0, t);
473 } else {
474 s->peer = create_remote_socket(p->msg.arg0, t);
475 s->peer->peer = s;
476 send_ready(s->id, s->peer->id, t);
477 s->ready(s);
478 }
479 }
480 break;
481
482 case A_OKAY: /* READY(local-id, remote-id, "") */
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100483 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
484 if((s = find_local_socket(p->msg.arg1, 0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800485 if(s->peer == 0) {
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100486 /* On first READY message, create the connection. */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487 s->peer = create_remote_socket(p->msg.arg0, t);
488 s->peer->peer = s;
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100489 s->ready(s);
490 } else if (s->peer->id == p->msg.arg0) {
491 /* Other READY messages must use the same local-id */
492 s->ready(s);
493 } else {
494 D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s\n",
495 p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497 }
498 }
499 break;
500
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100501 case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
502 if (t->online && p->msg.arg1 != 0) {
503 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
504 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
505 * a failed OPEN only. However, due to a bug in previous ADB
506 * versions, CLOSE(0, remote-id, "") was also used for normal
507 * CLOSE() operations.
508 *
509 * This is bad because it means a compromised adbd could
510 * send packets to close connections between the host and
511 * other devices. To avoid this, only allow this if the local
512 * socket has a peer on the same transport.
513 */
514 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
515 D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s\n",
516 p->msg.arg1, t->serial, s->peer->transport->serial);
517 } else {
518 s->close(s);
519 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800520 }
521 }
522 break;
523
David 'Digit' Turner818d6412013-12-13 14:09:44 +0100524 case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
525 if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
526 if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527 unsigned rid = p->msg.arg0;
528 p->len = p->msg.data_length;
529
530 if(s->enqueue(s, p) == 0) {
531 D("Enqueue the socket\n");
532 send_ready(s->id, rid, t);
533 }
534 return;
535 }
536 }
537 break;
538
539 default:
540 printf("handle_packet: what is %08x?!\n", p->msg.command);
541 }
542
543 put_apacket(p);
544}
545
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546#if ADB_HOST
JP Abgrall571c1362012-12-06 18:18:12 -0800547
Stefan Hilzingera84a42e2010-04-19 12:21:12 +0100548int launch_server(int server_port)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800549{
Yabin Cuie77b6a02014-11-11 09:24:11 -0800550#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551 /* we need to start the server in the background */
552 /* we create a PIPE that will be used to wait for the server's "OK" */
553 /* message since the pipe handles must be inheritable, we use a */
554 /* security attribute */
555 HANDLE pipe_read, pipe_write;
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000556 HANDLE stdout_handle, stderr_handle;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 SECURITY_ATTRIBUTES sa;
558 STARTUPINFO startup;
559 PROCESS_INFORMATION pinfo;
560 char program_path[ MAX_PATH ];
561 int ret;
562
563 sa.nLength = sizeof(sa);
564 sa.lpSecurityDescriptor = NULL;
565 sa.bInheritHandle = TRUE;
566
567 /* create pipe, and ensure its read handle isn't inheritable */
568 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
569 if (!ret) {
570 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
571 return -1;
572 }
573
574 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
575
Ray Donnelly267aa8b2012-11-29 01:18:50 +0000576 /* Some programs want to launch an adb command and collect its output by
577 * calling CreateProcess with inheritable stdout/stderr handles, then
578 * using read() to get its output. When this happens, the stdout/stderr
579 * handles passed to the adb client process will also be inheritable.
580 * When starting the adb server here, care must be taken to reset them
581 * to non-inheritable.
582 * Otherwise, something bad happens: even if the adb command completes,
583 * the calling process is stuck while read()-ing from the stdout/stderr
584 * descriptors, because they're connected to corresponding handles in the
585 * adb server process (even if the latter never uses/writes to them).
586 */
587 stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
588 stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
589 if (stdout_handle != INVALID_HANDLE_VALUE) {
590 SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
591 }
592 if (stderr_handle != INVALID_HANDLE_VALUE) {
593 SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
594 }
595
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800596 ZeroMemory( &startup, sizeof(startup) );
597 startup.cb = sizeof(startup);
598 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
599 startup.hStdOutput = pipe_write;
600 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
601 startup.dwFlags = STARTF_USESTDHANDLES;
602
603 ZeroMemory( &pinfo, sizeof(pinfo) );
604
605 /* get path of current program */
606 GetModuleFileName( NULL, program_path, sizeof(program_path) );
Wenhao Lia09558c2013-11-13 16:23:37 +0800607 char args[64];
608 snprintf(args, sizeof(args), "adb -P %d fork-server server", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609 ret = CreateProcess(
610 program_path, /* program path */
Wenhao Lia09558c2013-11-13 16:23:37 +0800611 args,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800612 /* the fork-server argument will set the
613 debug = 2 in the child */
614 NULL, /* process handle is not inheritable */
615 NULL, /* thread handle is not inheritable */
616 TRUE, /* yes, inherit some handles */
617 DETACHED_PROCESS, /* the new process doesn't have a console */
618 NULL, /* use parent's environment block */
619 NULL, /* use parent's starting directory */
620 &startup, /* startup info, i.e. std handles */
621 &pinfo );
622
623 CloseHandle( pipe_write );
624
625 if (!ret) {
626 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
627 CloseHandle( pipe_read );
628 return -1;
629 }
630
631 CloseHandle( pinfo.hProcess );
632 CloseHandle( pinfo.hThread );
633
634 /* wait for the "OK\n" message */
635 {
636 char temp[3];
637 DWORD count;
638
639 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
640 CloseHandle( pipe_read );
641 if ( !ret ) {
642 fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
643 return -1;
644 }
645 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
646 fprintf(stderr, "ADB server didn't ACK\n" );
647 return -1;
648 }
649 }
Yabin Cuie77b6a02014-11-11 09:24:11 -0800650#else /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800651 char path[PATH_MAX];
652 int fd[2];
653
654 // set up a pipe so the child can tell us when it is ready.
655 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
656 if (pipe(fd)) {
657 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
658 return -1;
659 }
Alexey Tarasov31664102009-10-22 02:55:00 +1100660 get_my_path(path, PATH_MAX);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800661 pid_t pid = fork();
662 if(pid < 0) return -1;
663
664 if (pid == 0) {
665 // child side of the fork
666
667 // redirect stderr to the pipe
668 // we use stderr instead of stdout due to stdout's buffering behavior.
669 adb_close(fd[0]);
670 dup2(fd[1], STDERR_FILENO);
671 adb_close(fd[1]);
672
Matt Gumbeld7b33082012-11-14 10:16:17 -0800673 char str_port[30];
674 snprintf(str_port, sizeof(str_port), "%d", server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800675 // child process
Matt Gumbeld7b33082012-11-14 10:16:17 -0800676 int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 // this should not return
678 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
679 } else {
680 // parent side of the fork
681
682 char temp[3];
683
684 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
685 // wait for the "OK\n" message
686 adb_close(fd[1]);
687 int ret = adb_read(fd[0], temp, 3);
JP Abgrall408fa572011-03-16 15:57:42 -0700688 int saved_errno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689 adb_close(fd[0]);
690 if (ret < 0) {
JP Abgrall408fa572011-03-16 15:57:42 -0700691 fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800692 return -1;
693 }
694 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
695 fprintf(stderr, "ADB server didn't ACK\n" );
696 return -1;
697 }
698
699 setsid();
700 }
Yabin Cuie77b6a02014-11-11 09:24:11 -0800701#endif /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800702 return 0;
703}
Yabin Cuie77b6a02014-11-11 09:24:11 -0800704#endif /* ADB_HOST */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800705
David 'Digit' Turner25258692013-03-21 21:07:42 +0100706// Try to handle a network forwarding request.
707// This returns 1 on success, 0 on failure, and -1 to indicate this is not
708// a forwarding-related request.
709int handle_forward_request(const char* service, transport_type ttype, char* serial, int reply_fd)
710{
711 if (!strcmp(service, "list-forward")) {
712 // Create the list of forward redirections.
713 int buffer_size = format_listeners(NULL, 0);
714 // Add one byte for the trailing zero.
715 char* buffer = malloc(buffer_size + 1);
716 if (buffer == NULL) {
717 sendfailmsg(reply_fd, "not enough memory");
718 return 1;
719 }
720 (void) format_listeners(buffer, buffer_size + 1);
721#if ADB_HOST
722 send_msg_with_okay(reply_fd, buffer, buffer_size);
723#else
724 send_msg_with_header(reply_fd, buffer, buffer_size);
725#endif
726 free(buffer);
727 return 1;
728 }
729
730 if (!strcmp(service, "killforward-all")) {
731 remove_all_listeners();
732#if ADB_HOST
733 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
734 adb_write(reply_fd, "OKAY", 4);
735#endif
736 adb_write(reply_fd, "OKAY", 4);
737 return 1;
738 }
739
740 if (!strncmp(service, "forward:",8) ||
741 !strncmp(service, "killforward:",12)) {
742 char *local, *remote, *err;
743 int r;
744 atransport *transport;
745
746 int createForward = strncmp(service, "kill", 4);
747 int no_rebind = 0;
748
749 local = strchr(service, ':') + 1;
750
751 // Handle forward:norebind:<local>... here
752 if (createForward && !strncmp(local, "norebind:", 9)) {
753 no_rebind = 1;
754 local = strchr(local, ':') + 1;
755 }
756
757 remote = strchr(local,';');
758
759 if (createForward) {
760 // Check forward: parameter format: '<local>;<remote>'
761 if(remote == 0) {
762 sendfailmsg(reply_fd, "malformed forward spec");
763 return 1;
764 }
765
766 *remote++ = 0;
767 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')) {
768 sendfailmsg(reply_fd, "malformed forward spec");
769 return 1;
770 }
771 } else {
772 // Check killforward: parameter format: '<local>'
773 if (local[0] == 0) {
774 sendfailmsg(reply_fd, "malformed forward spec");
775 return 1;
776 }
777 }
778
779 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
780 if (!transport) {
781 sendfailmsg(reply_fd, err);
782 return 1;
783 }
784
785 if (createForward) {
786 r = install_listener(local, remote, transport, no_rebind);
787 } else {
788 r = remove_listener(local, transport);
789 }
790 if(r == 0) {
791#if ADB_HOST
792 /* On the host: 1st OKAY is connect, 2nd OKAY is status */
793 writex(reply_fd, "OKAY", 4);
794#endif
795 writex(reply_fd, "OKAY", 4);
796 return 1;
797 }
798
799 if (createForward) {
800 const char* message;
801 switch (r) {
802 case INSTALL_STATUS_CANNOT_BIND:
803 message = "cannot bind to socket";
804 break;
805 case INSTALL_STATUS_CANNOT_REBIND:
806 message = "cannot rebind existing socket";
807 break;
808 default:
809 message = "internal error";
810 }
811 sendfailmsg(reply_fd, message);
812 } else {
813 sendfailmsg(reply_fd, "cannot remove listener");
814 }
815 return 1;
816 }
817 return 0;
818}
819
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
821{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 if(!strcmp(service, "kill")) {
823 fprintf(stderr,"adb server killed by remote request\n");
824 fflush(stdout);
825 adb_write(reply_fd, "OKAY", 4);
826 usb_cleanup();
827 exit(0);
828 }
829
830#if ADB_HOST
Chih-Hung Hsiehf787b382014-09-05 15:38:15 -0700831 atransport *transport = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800832 // "transport:" is used for switching transport with a specified serial number
833 // "transport-usb:" is used for switching transport to the only USB transport
834 // "transport-local:" is used for switching transport to the only local transport
835 // "transport-any:" is used for switching transport to the only transport
836 if (!strncmp(service, "transport", strlen("transport"))) {
837 char* error_string = "unknown failure";
838 transport_type type = kTransportAny;
839
840 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
841 type = kTransportUsb;
842 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
843 type = kTransportLocal;
844 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
845 type = kTransportAny;
846 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
847 service += strlen("transport:");
Tom Marlin3175c8e2011-07-27 12:56:14 -0500848 serial = service;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849 }
850
851 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
852
853 if (transport) {
854 s->transport = transport;
855 adb_write(reply_fd, "OKAY", 4);
856 } else {
857 sendfailmsg(reply_fd, error_string);
858 }
859 return 1;
860 }
861
862 // return a list of all connected devices
Scott Andersone109d262012-04-20 11:21:14 -0700863 if (!strncmp(service, "devices", 7)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800864 char buffer[4096];
Scott Andersone109d262012-04-20 11:21:14 -0700865 int use_long = !strcmp(service+7, "-l");
866 if (use_long || service[7] == 0) {
Scott Andersone109d262012-04-20 11:21:14 -0700867 memset(buffer, 0, sizeof(buffer));
868 D("Getting device list \n");
869 list_transports(buffer, sizeof(buffer), use_long);
Scott Andersone109d262012-04-20 11:21:14 -0700870 D("Wrote device list \n");
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100871 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
Scott Andersone109d262012-04-20 11:21:14 -0700872 return 0;
873 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800874 }
875
Mike Lockwood74d7ff82009-10-11 23:04:18 -0400876 // remove TCP transport
877 if (!strncmp(service, "disconnect:", 11)) {
878 char buffer[4096];
879 memset(buffer, 0, sizeof(buffer));
880 char* serial = service + 11;
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400881 if (serial[0] == 0) {
882 // disconnect from all TCP devices
883 unregister_all_tcp_transports();
Mike Lockwood74d7ff82009-10-11 23:04:18 -0400884 } else {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400885 char hostbuf[100];
886 // assume port 5555 if no port is specified
887 if (!strchr(serial, ':')) {
888 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
889 serial = hostbuf;
890 }
891 atransport *t = find_transport(serial);
892
893 if (t) {
894 unregister_transport(t);
895 } else {
896 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
897 }
Mike Lockwood74d7ff82009-10-11 23:04:18 -0400898 }
899
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100900 send_msg_with_okay(reply_fd, buffer, strlen(buffer));
Mike Lockwood2f38b692009-08-24 15:58:40 -0700901 return 0;
902 }
903
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904 // returns our value for ADB_SERVER_VERSION
905 if (!strcmp(service, "version")) {
906 char version[12];
907 snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100908 send_msg_with_okay(reply_fd, version, strlen(version));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800909 return 0;
910 }
911
912 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
913 char *out = "unknown";
914 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
915 if (transport && transport->serial) {
916 out = transport->serial;
917 }
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100918 send_msg_with_okay(reply_fd, out, strlen(out));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800919 return 0;
920 }
Scott Andersone109d262012-04-20 11:21:14 -0700921 if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
922 char *out = "unknown";
923 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
924 if (transport && transport->devpath) {
925 out = transport->devpath;
926 }
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100927 send_msg_with_okay(reply_fd, out, strlen(out));
Scott Andersone109d262012-04-20 11:21:14 -0700928 return 0;
929 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800930 // indicates a new emulator instance has started
931 if (!strncmp(service,"emulator:",9)) {
932 int port = atoi(service+9);
933 local_connect(port);
934 /* we don't even need to send a reply */
935 return 0;
936 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937
938 if(!strncmp(service,"get-state",strlen("get-state"))) {
939 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
940 char *state = connection_state_name(transport);
Snild Dolkow2264e7c2014-01-30 10:08:38 +0100941 send_msg_with_okay(reply_fd, state, strlen(state));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942 return 0;
943 }
Simon Yedc22c3c2014-07-14 17:23:06 -0700944#endif // ADB_HOST
945
946 int ret = handle_forward_request(service, ttype, serial, reply_fd);
947 if (ret >= 0)
948 return ret - 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949 return -1;
950}