1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define TRACE_TAG ADB
18 
19 #include "sysdeps.h"
20 #include "adb.h"
21 
22 #include <ctype.h>
23 #include <errno.h>
24 #include <stdarg.h>
25 #include <stddef.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/time.h>
31 #include <time.h>
32 
33 #include <chrono>
34 #include <string>
35 #include <thread>
36 #include <vector>
37 
38 #include <android-base/errors.h>
39 #include <android-base/file.h>
40 #include <android-base/logging.h>
41 #include <android-base/macros.h>
42 #include <android-base/parsenetaddress.h>
43 #include <android-base/quick_exit.h>
44 #include <android-base/stringprintf.h>
45 #include <android-base/strings.h>
46 
47 #include "adb_auth.h"
48 #include "adb_io.h"
49 #include "adb_listeners.h"
50 #include "adb_utils.h"
51 #include "transport.h"
52 
53 #if !ADB_HOST
54 #include <sys/capability.h>
55 #include <sys/mount.h>
56 #include <android-base/properties.h>
57 using namespace std::chrono_literals;
58 #endif
59 
adb_version()60 std::string adb_version() {
61     // Don't change the format of this --- it's parsed by ddmlib.
62     return android::base::StringPrintf("Android Debug Bridge version %d.%d.%d\n"
63                                        "Revision %s\n",
64                                        ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION,
65                                        ADB_REVISION);
66 }
67 
fatal(const char * fmt,...)68 void fatal(const char *fmt, ...) {
69     va_list ap;
70     va_start(ap, fmt);
71     char buf[1024];
72     vsnprintf(buf, sizeof(buf), fmt, ap);
73 
74 #if ADB_HOST
75     fprintf(stderr, "error: %s\n", buf);
76 #else
77     LOG(ERROR) << "error: " << buf;
78 #endif
79 
80     va_end(ap);
81     abort();
82 }
83 
fatal_errno(const char * fmt,...)84 void fatal_errno(const char* fmt, ...) {
85     int err = errno;
86     va_list ap;
87     va_start(ap, fmt);
88     char buf[1024];
89     vsnprintf(buf, sizeof(buf), fmt, ap);
90 
91 #if ADB_HOST
92     fprintf(stderr, "error: %s: %s\n", buf, strerror(err));
93 #else
94     LOG(ERROR) << "error: " << buf << ": " << strerror(err);
95 #endif
96 
97     va_end(ap);
98     abort();
99 }
100 
calculate_apacket_checksum(const apacket * p)101 uint32_t calculate_apacket_checksum(const apacket* p) {
102     const unsigned char* x = reinterpret_cast<const unsigned char*>(p->data);
103     uint32_t sum = 0;
104     size_t count = p->msg.data_length;
105 
106     while (count-- > 0) {
107         sum += *x++;
108     }
109 
110     return sum;
111 }
112 
get_apacket(void)113 apacket* get_apacket(void)
114 {
115     apacket* p = reinterpret_cast<apacket*>(malloc(sizeof(apacket)));
116     if (p == nullptr) {
117       fatal("failed to allocate an apacket");
118     }
119 
120     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
121     return p;
122 }
123 
put_apacket(apacket * p)124 void put_apacket(apacket *p)
125 {
126     free(p);
127 }
128 
handle_online(atransport * t)129 void handle_online(atransport *t)
130 {
131     D("adb: online");
132     t->online = 1;
133 }
134 
handle_offline(atransport * t)135 void handle_offline(atransport *t)
136 {
137     D("adb: offline");
138     //Close the associated usb
139     t->online = 0;
140 
141     // This is necessary to avoid a race condition that occurred when a transport closes
142     // while a client socket is still active.
143     close_all_sockets(t);
144 
145     t->RunDisconnects();
146 }
147 
148 #if DEBUG_PACKETS
149 #define DUMPMAX 32
print_packet(const char * label,apacket * p)150 void print_packet(const char *label, apacket *p)
151 {
152     char *tag;
153     char *x;
154     unsigned count;
155 
156     switch(p->msg.command){
157     case A_SYNC: tag = "SYNC"; break;
158     case A_CNXN: tag = "CNXN" ; break;
159     case A_OPEN: tag = "OPEN"; break;
160     case A_OKAY: tag = "OKAY"; break;
161     case A_CLSE: tag = "CLSE"; break;
162     case A_WRTE: tag = "WRTE"; break;
163     case A_AUTH: tag = "AUTH"; break;
164     default: tag = "????"; break;
165     }
166 
167     fprintf(stderr, "%s: %s %08x %08x %04x \"",
168             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
169     count = p->msg.data_length;
170     x = (char*) p->data;
171     if(count > DUMPMAX) {
172         count = DUMPMAX;
173         tag = "\n";
174     } else {
175         tag = "\"\n";
176     }
177     while(count-- > 0){
178         if((*x >= ' ') && (*x < 127)) {
179             fputc(*x, stderr);
180         } else {
181             fputc('.', stderr);
182         }
183         x++;
184     }
185     fputs(tag, stderr);
186 }
187 #endif
188 
send_ready(unsigned local,unsigned remote,atransport * t)189 static void send_ready(unsigned local, unsigned remote, atransport *t)
190 {
191     D("Calling send_ready");
192     apacket *p = get_apacket();
193     p->msg.command = A_OKAY;
194     p->msg.arg0 = local;
195     p->msg.arg1 = remote;
196     send_packet(p, t);
197 }
198 
send_close(unsigned local,unsigned remote,atransport * t)199 static void send_close(unsigned local, unsigned remote, atransport *t)
200 {
201     D("Calling send_close");
202     apacket *p = get_apacket();
203     p->msg.command = A_CLSE;
204     p->msg.arg0 = local;
205     p->msg.arg1 = remote;
206     send_packet(p, t);
207 }
208 
get_connection_string()209 std::string get_connection_string() {
210     std::vector<std::string> connection_properties;
211 
212 #if !ADB_HOST
213     static const char* cnxn_props[] = {
214         "ro.product.name",
215         "ro.product.model",
216         "ro.product.device",
217     };
218 
219     for (const auto& prop : cnxn_props) {
220         std::string value = std::string(prop) + "=" + android::base::GetProperty(prop, "");
221         connection_properties.push_back(value);
222     }
223 #endif
224 
225     connection_properties.push_back(android::base::StringPrintf(
226         "features=%s", FeatureSetToString(supported_features()).c_str()));
227 
228     return android::base::StringPrintf(
229         "%s::%s", adb_device_banner,
230         android::base::Join(connection_properties, ';').c_str());
231 }
232 
send_connect(atransport * t)233 void send_connect(atransport* t) {
234     D("Calling send_connect");
235     apacket* cp = get_apacket();
236     cp->msg.command = A_CNXN;
237     cp->msg.arg0 = t->get_protocol_version();
238     cp->msg.arg1 = t->get_max_payload();
239 
240     std::string connection_str = get_connection_string();
241     // Connect and auth packets are limited to MAX_PAYLOAD_V1 because we don't
242     // yet know how much data the other size is willing to accept.
243     if (connection_str.length() > MAX_PAYLOAD_V1) {
244         LOG(FATAL) << "Connection banner is too long (length = "
245                    << connection_str.length() << ")";
246     }
247 
248     memcpy(cp->data, connection_str.c_str(), connection_str.length());
249     cp->msg.data_length = connection_str.length();
250 
251     send_packet(cp, t);
252 }
253 
254 // qual_overwrite is used to overwrite a qualifier string.  dst is a
255 // pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
256 // was malloc'ed and needs to freed.  *dst will be set to a dup of src.
257 // TODO: switch to std::string for these atransport fields instead.
qual_overwrite(char ** dst,const std::string & src)258 static void qual_overwrite(char** dst, const std::string& src) {
259     free(*dst);
260     *dst = strdup(src.c_str());
261 }
262 
parse_banner(const std::string & banner,atransport * t)263 void parse_banner(const std::string& banner, atransport* t) {
264     D("parse_banner: %s", banner.c_str());
265 
266     // The format is something like:
267     // "device::ro.product.name=x;ro.product.model=y;ro.product.device=z;".
268     std::vector<std::string> pieces = android::base::Split(banner, ":");
269 
270     // Reset the features list or else if the server sends no features we may
271     // keep the existing feature set (http://b/24405971).
272     t->SetFeatures("");
273 
274     if (pieces.size() > 2) {
275         const std::string& props = pieces[2];
276         for (const auto& prop : android::base::Split(props, ";")) {
277             // The list of properties was traditionally ;-terminated rather than ;-separated.
278             if (prop.empty()) continue;
279 
280             std::vector<std::string> key_value = android::base::Split(prop, "=");
281             if (key_value.size() != 2) continue;
282 
283             const std::string& key = key_value[0];
284             const std::string& value = key_value[1];
285             if (key == "ro.product.name") {
286                 qual_overwrite(&t->product, value);
287             } else if (key == "ro.product.model") {
288                 qual_overwrite(&t->model, value);
289             } else if (key == "ro.product.device") {
290                 qual_overwrite(&t->device, value);
291             } else if (key == "features") {
292                 t->SetFeatures(value);
293             }
294         }
295     }
296 
297     const std::string& type = pieces[0];
298     if (type == "bootloader") {
299         D("setting connection_state to kCsBootloader");
300         t->connection_state = kCsBootloader;
301         update_transports();
302     } else if (type == "device") {
303         D("setting connection_state to kCsDevice");
304         t->connection_state = kCsDevice;
305         update_transports();
306     } else if (type == "recovery") {
307         D("setting connection_state to kCsRecovery");
308         t->connection_state = kCsRecovery;
309         update_transports();
310     } else if (type == "sideload") {
311         D("setting connection_state to kCsSideload");
312         t->connection_state = kCsSideload;
313         update_transports();
314     } else {
315         D("setting connection_state to kCsHost");
316         t->connection_state = kCsHost;
317     }
318 }
319 
handle_new_connection(atransport * t,apacket * p)320 static void handle_new_connection(atransport* t, apacket* p) {
321     if (t->connection_state != kCsOffline) {
322         t->connection_state = kCsOffline;
323         handle_offline(t);
324     }
325 
326     t->update_version(p->msg.arg0, p->msg.arg1);
327     std::string banner(reinterpret_cast<const char*>(p->data),
328                        p->msg.data_length);
329     parse_banner(banner, t);
330 
331 #if ADB_HOST
332     handle_online(t);
333 #else
334     if (!auth_required) {
335         handle_online(t);
336         send_connect(t);
337     } else {
338         send_auth_request(t);
339     }
340 #endif
341 }
342 
handle_packet(apacket * p,atransport * t)343 void handle_packet(apacket *p, atransport *t)
344 {
345     D("handle_packet() %c%c%c%c", ((char*) (&(p->msg.command)))[0],
346             ((char*) (&(p->msg.command)))[1],
347             ((char*) (&(p->msg.command)))[2],
348             ((char*) (&(p->msg.command)))[3]);
349     print_packet("recv", p);
350 
351     switch(p->msg.command){
352     case A_SYNC:
353         if (p->msg.arg0){
354             send_packet(p, t);
355 #if ADB_HOST
356             send_connect(t);
357 #endif
358         } else {
359             t->connection_state = kCsOffline;
360             handle_offline(t);
361             send_packet(p, t);
362         }
363         return;
364 
365     case A_CNXN:  // CONNECT(version, maxdata, "system-id-string")
366         handle_new_connection(t, p);
367         break;
368 
369     case A_AUTH:
370         switch (p->msg.arg0) {
371 #if ADB_HOST
372             case ADB_AUTH_TOKEN:
373                 t->connection_state = kCsUnauthorized;
374                 send_auth_response(p->data, p->msg.data_length, t);
375                 break;
376 #else
377             case ADB_AUTH_SIGNATURE:
378                 if (adbd_auth_verify(t->token, sizeof(t->token), p->data, p->msg.data_length)) {
379                     adbd_auth_verified(t);
380                     t->failed_auth_attempts = 0;
381                 } else {
382                     if (t->failed_auth_attempts++ > 256) std::this_thread::sleep_for(1s);
383                     send_auth_request(t);
384                 }
385                 break;
386 
387             case ADB_AUTH_RSAPUBLICKEY:
388                 adbd_auth_confirm_key(p->data, p->msg.data_length, t);
389                 break;
390 #endif
391             default:
392                 t->connection_state = kCsOffline;
393                 handle_offline(t);
394                 break;
395         }
396         break;
397 
398     case A_OPEN: /* OPEN(local-id, 0, "destination") */
399         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
400             char *name = (char*) p->data;
401             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
402             asocket* s = create_local_service_socket(name, t);
403             if (s == nullptr) {
404                 send_close(0, p->msg.arg0, t);
405             } else {
406                 s->peer = create_remote_socket(p->msg.arg0, t);
407                 s->peer->peer = s;
408                 send_ready(s->id, s->peer->id, t);
409                 s->ready(s);
410             }
411         }
412         break;
413 
414     case A_OKAY: /* READY(local-id, remote-id, "") */
415         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
416             asocket* s = find_local_socket(p->msg.arg1, 0);
417             if (s) {
418                 if(s->peer == 0) {
419                     /* On first READY message, create the connection. */
420                     s->peer = create_remote_socket(p->msg.arg0, t);
421                     s->peer->peer = s;
422                     s->ready(s);
423                 } else if (s->peer->id == p->msg.arg0) {
424                     /* Other READY messages must use the same local-id */
425                     s->ready(s);
426                 } else {
427                     D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s",
428                       p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
429                 }
430             } else {
431                 // When receiving A_OKAY from device for A_OPEN request, the host server may
432                 // have closed the local socket because of client disconnection. Then we need
433                 // to send A_CLSE back to device to close the service on device.
434                 send_close(p->msg.arg1, p->msg.arg0, t);
435             }
436         }
437         break;
438 
439     case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
440         if (t->online && p->msg.arg1 != 0) {
441             asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
442             if (s) {
443                 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
444                  * a failed OPEN only. However, due to a bug in previous ADB
445                  * versions, CLOSE(0, remote-id, "") was also used for normal
446                  * CLOSE() operations.
447                  *
448                  * This is bad because it means a compromised adbd could
449                  * send packets to close connections between the host and
450                  * other devices. To avoid this, only allow this if the local
451                  * socket has a peer on the same transport.
452                  */
453                 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
454                     D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s",
455                       p->msg.arg1, t->serial, s->peer->transport->serial);
456                 } else {
457                     s->close(s);
458                 }
459             }
460         }
461         break;
462 
463     case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
464         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
465             asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
466             if (s) {
467                 unsigned rid = p->msg.arg0;
468                 p->len = p->msg.data_length;
469 
470                 if (s->enqueue(s, p) == 0) {
471                     D("Enqueue the socket");
472                     send_ready(s->id, rid, t);
473                 }
474                 return;
475             }
476         }
477         break;
478 
479     default:
480         printf("handle_packet: what is %08x?!\n", p->msg.command);
481     }
482 
483     put_apacket(p);
484 }
485 
486 #if ADB_HOST
487 
488 #ifdef _WIN32
489 
490 // Try to make a handle non-inheritable and if there is an error, don't output
491 // any error info, but leave GetLastError() for the caller to read. This is
492 // convenient if the caller is expecting that this may fail and they'd like to
493 // ignore such a failure.
_try_make_handle_noninheritable(HANDLE h)494 static bool _try_make_handle_noninheritable(HANDLE h) {
495     if (h != INVALID_HANDLE_VALUE && h != NULL) {
496         return SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0) ? true : false;
497     }
498 
499     return true;
500 }
501 
502 // Try to make a handle non-inheritable with the expectation that this should
503 // succeed, so if this fails, output error info.
_make_handle_noninheritable(HANDLE h)504 static bool _make_handle_noninheritable(HANDLE h) {
505     if (!_try_make_handle_noninheritable(h)) {
506         // Show the handle value to give us a clue in case we have problems
507         // with pseudo-handle values.
508         fprintf(stderr, "Cannot make handle 0x%p non-inheritable: %s\n",
509                 h, android::base::SystemErrorCodeToString(GetLastError()).c_str());
510         return false;
511     }
512 
513     return true;
514 }
515 
516 // Create anonymous pipe, preventing inheritance of the read pipe and setting
517 // security of the write pipe to sa.
_create_anonymous_pipe(unique_handle * pipe_read_out,unique_handle * pipe_write_out,SECURITY_ATTRIBUTES * sa)518 static bool _create_anonymous_pipe(unique_handle* pipe_read_out,
519                                    unique_handle* pipe_write_out,
520                                    SECURITY_ATTRIBUTES* sa) {
521     HANDLE pipe_read_raw = NULL;
522     HANDLE pipe_write_raw = NULL;
523     if (!CreatePipe(&pipe_read_raw, &pipe_write_raw, sa, 0)) {
524         fprintf(stderr, "Cannot create pipe: %s\n",
525                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
526         return false;
527     }
528 
529     unique_handle pipe_read(pipe_read_raw);
530     pipe_read_raw = NULL;
531     unique_handle pipe_write(pipe_write_raw);
532     pipe_write_raw = NULL;
533 
534     if (!_make_handle_noninheritable(pipe_read.get())) {
535         return false;
536     }
537 
538     *pipe_read_out = std::move(pipe_read);
539     *pipe_write_out = std::move(pipe_write);
540 
541     return true;
542 }
543 
544 // Read from a pipe (that we take ownership of) and write the result to stdout/stderr. Return on
545 // error or when the pipe is closed. Internally makes inheritable handles, so this should not be
546 // called if subprocesses may be started concurrently.
_redirect_pipe_thread(HANDLE h,DWORD nStdHandle)547 static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
548     // Take ownership of the HANDLE and close when we're done.
549     unique_handle   read_pipe(h);
550     const char*     output_name = nStdHandle == STD_OUTPUT_HANDLE ? "stdout" : "stderr";
551     const int       original_fd = fileno(nStdHandle == STD_OUTPUT_HANDLE ? stdout : stderr);
552     std::unique_ptr<FILE, decltype(&fclose)> stream(nullptr, fclose);
553 
554     if (original_fd == -1) {
555         fprintf(stderr, "Failed to get file descriptor for %s: %s\n", output_name, strerror(errno));
556         return EXIT_FAILURE;
557     }
558 
559     // If fileno() is -2, stdout/stderr is not associated with an output stream, so we should read,
560     // but don't write. Otherwise, make a FILE* identical to stdout/stderr except that it is in
561     // binary mode with no CR/LR translation since we're reading raw.
562     if (original_fd >= 0) {
563         // This internally makes a duplicate file handle that is inheritable, so callers should not
564         // call this function if subprocesses may be started concurrently.
565         const int fd = dup(original_fd);
566         if (fd == -1) {
567             fprintf(stderr, "Failed to duplicate file descriptor for %s: %s\n", output_name,
568                     strerror(errno));
569             return EXIT_FAILURE;
570         }
571 
572         // Note that although we call fdopen() below with a binary flag, it may not adhere to that
573         // flag, so we have to set the mode manually.
574         if (_setmode(fd, _O_BINARY) == -1) {
575             fprintf(stderr, "Failed to set binary mode for duplicate of %s: %s\n", output_name,
576                     strerror(errno));
577             unix_close(fd);
578             return EXIT_FAILURE;
579         }
580 
581         stream.reset(fdopen(fd, "wb"));
582         if (stream.get() == nullptr) {
583             fprintf(stderr, "Failed to open duplicate stream for %s: %s\n", output_name,
584                     strerror(errno));
585             unix_close(fd);
586             return EXIT_FAILURE;
587         }
588 
589         // Unbuffer the stream because it will be buffered by default and we want subprocess output
590         // to be shown immediately.
591         if (setvbuf(stream.get(), NULL, _IONBF, 0) == -1) {
592             fprintf(stderr, "Failed to unbuffer %s: %s\n", output_name, strerror(errno));
593             return EXIT_FAILURE;
594         }
595 
596         // fd will be closed when stream is closed.
597     }
598 
599     while (true) {
600         char    buf[64 * 1024];
601         DWORD   bytes_read = 0;
602         if (!ReadFile(read_pipe.get(), buf, sizeof(buf), &bytes_read, NULL)) {
603             const DWORD err = GetLastError();
604             // ERROR_BROKEN_PIPE is expected when the subprocess closes
605             // the other end of the pipe.
606             if (err == ERROR_BROKEN_PIPE) {
607                 return EXIT_SUCCESS;
608             } else {
609                 fprintf(stderr, "Failed to read from %s: %s\n", output_name,
610                         android::base::SystemErrorCodeToString(err).c_str());
611                 return EXIT_FAILURE;
612             }
613         }
614 
615         // Don't try to write if our stdout/stderr was not setup by the parent process.
616         if (stream) {
617             // fwrite() actually calls adb_fwrite() which can write UTF-8 to the console.
618             const size_t bytes_written = fwrite(buf, 1, bytes_read, stream.get());
619             if (bytes_written != bytes_read) {
620                 fprintf(stderr, "Only wrote %zu of %lu bytes to %s\n", bytes_written, bytes_read,
621                         output_name);
622                 return EXIT_FAILURE;
623             }
624         }
625     }
626 }
627 
_redirect_stdout_thread(HANDLE h)628 static unsigned __stdcall _redirect_stdout_thread(HANDLE h) {
629     adb_thread_setname("stdout redirect");
630     return _redirect_pipe_thread(h, STD_OUTPUT_HANDLE);
631 }
632 
_redirect_stderr_thread(HANDLE h)633 static unsigned __stdcall _redirect_stderr_thread(HANDLE h) {
634     adb_thread_setname("stderr redirect");
635     return _redirect_pipe_thread(h, STD_ERROR_HANDLE);
636 }
637 
638 #endif
639 
launch_server(const std::string & socket_spec)640 int launch_server(const std::string& socket_spec) {
641 #if defined(_WIN32)
642     /* we need to start the server in the background                    */
643     /* we create a PIPE that will be used to wait for the server's "OK" */
644     /* message since the pipe handles must be inheritable, we use a     */
645     /* security attribute                                               */
646     SECURITY_ATTRIBUTES   sa;
647     sa.nLength = sizeof(sa);
648     sa.lpSecurityDescriptor = NULL;
649     sa.bInheritHandle = TRUE;
650 
651     // Redirect stdin to Windows /dev/null. If we instead pass an original
652     // stdin/stdout/stderr handle and it is a console handle, when the adb
653     // server starts up, the C Runtime will see a console handle for a process
654     // that isn't connected to a console and it will configure
655     // stdin/stdout/stderr to be closed. At that point, freopen() could be used
656     // to reopen stderr/out, but it would take more massaging to fixup the file
657     // descriptor number that freopen() uses. It's simplest to avoid all of this
658     // complexity by just redirecting stdin to `nul' and then the C Runtime acts
659     // as expected.
660     unique_handle   nul_read(CreateFileW(L"nul", GENERIC_READ,
661             FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
662             FILE_ATTRIBUTE_NORMAL, NULL));
663     if (nul_read.get() == INVALID_HANDLE_VALUE) {
664         fprintf(stderr, "Cannot open 'nul': %s\n",
665                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
666         return -1;
667     }
668 
669     // Create pipes with non-inheritable read handle, inheritable write handle. We need to connect
670     // the subprocess to pipes instead of just letting the subprocess inherit our existing
671     // stdout/stderr handles because a DETACHED_PROCESS cannot write to a console that it is not
672     // attached to.
673     unique_handle   ack_read, ack_write;
674     if (!_create_anonymous_pipe(&ack_read, &ack_write, &sa)) {
675         return -1;
676     }
677     unique_handle   stdout_read, stdout_write;
678     if (!_create_anonymous_pipe(&stdout_read, &stdout_write, &sa)) {
679         return -1;
680     }
681     unique_handle   stderr_read, stderr_write;
682     if (!_create_anonymous_pipe(&stderr_read, &stderr_write, &sa)) {
683         return -1;
684     }
685 
686     /* Some programs want to launch an adb command and collect its output by
687      * calling CreateProcess with inheritable stdout/stderr handles, then
688      * using read() to get its output. When this happens, the stdout/stderr
689      * handles passed to the adb client process will also be inheritable.
690      * When starting the adb server here, care must be taken to reset them
691      * to non-inheritable.
692      * Otherwise, something bad happens: even if the adb command completes,
693      * the calling process is stuck while read()-ing from the stdout/stderr
694      * descriptors, because they're connected to corresponding handles in the
695      * adb server process (even if the latter never uses/writes to them).
696      * Note that even if we don't pass these handles in the STARTUPINFO struct,
697      * if they're marked inheritable, they're still inherited, requiring us to
698      * deal with this.
699      *
700      * If we're still having problems with inheriting random handles in the
701      * future, consider using PROC_THREAD_ATTRIBUTE_HANDLE_LIST to explicitly
702      * specify which handles should be inherited: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/16/10248328.aspx
703      *
704      * Older versions of Windows return console pseudo-handles that cannot be
705      * made non-inheritable, so ignore those failures.
706      */
707     _try_make_handle_noninheritable(GetStdHandle(STD_INPUT_HANDLE));
708     _try_make_handle_noninheritable(GetStdHandle(STD_OUTPUT_HANDLE));
709     _try_make_handle_noninheritable(GetStdHandle(STD_ERROR_HANDLE));
710 
711     STARTUPINFOW    startup;
712     ZeroMemory( &startup, sizeof(startup) );
713     startup.cb = sizeof(startup);
714     startup.hStdInput  = nul_read.get();
715     startup.hStdOutput = stdout_write.get();
716     startup.hStdError  = stderr_write.get();
717     startup.dwFlags    = STARTF_USESTDHANDLES;
718 
719     // Verify that the pipe_write handle value can be passed on the command line
720     // as %d and that the rest of adb code can pass it around in an int.
721     const int ack_write_as_int = cast_handle_to_int(ack_write.get());
722     if (cast_int_to_handle(ack_write_as_int) != ack_write.get()) {
723         // If this fires, either handle values are larger than 32-bits or else
724         // there is a bug in our casting.
725         // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
726         fprintf(stderr, "Cannot fit pipe handle value into 32-bits: 0x%p\n",
727                 ack_write.get());
728         return -1;
729     }
730 
731     // get path of current program
732     WCHAR       program_path[MAX_PATH];
733     const DWORD module_result = GetModuleFileNameW(NULL, program_path,
734                                                    arraysize(program_path));
735     if ((module_result >= arraysize(program_path)) || (module_result == 0)) {
736         // String truncation or some other error.
737         fprintf(stderr, "Cannot get executable path: %s\n",
738                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
739         return -1;
740     }
741 
742     WCHAR   args[64];
743     snwprintf(args, arraysize(args), L"adb -L %s fork-server server --reply-fd %d",
744               socket_spec.c_str(), ack_write_as_int);
745 
746     PROCESS_INFORMATION   pinfo;
747     ZeroMemory(&pinfo, sizeof(pinfo));
748 
749     if (!CreateProcessW(
750             program_path,                              /* program path  */
751             args,
752                                     /* the fork-server argument will set the
753                                        debug = 2 in the child           */
754             NULL,                   /* process handle is not inheritable */
755             NULL,                    /* thread handle is not inheritable */
756             TRUE,                          /* yes, inherit some handles */
757             DETACHED_PROCESS, /* the new process doesn't have a console */
758             NULL,                     /* use parent's environment block */
759             NULL,                    /* use parent's starting directory */
760             &startup,                 /* startup info, i.e. std handles */
761             &pinfo )) {
762         fprintf(stderr, "Cannot create process: %s\n",
763                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
764         return -1;
765     }
766 
767     unique_handle   process_handle(pinfo.hProcess);
768     pinfo.hProcess = NULL;
769 
770     // Close handles that we no longer need to complete the rest.
771     CloseHandle(pinfo.hThread);
772     pinfo.hThread = NULL;
773 
774     nul_read.reset();
775     ack_write.reset();
776     stdout_write.reset();
777     stderr_write.reset();
778 
779     // Start threads to read from subprocess stdout/stderr and write to ours to make subprocess
780     // errors easier to diagnose. Note that the threads internally create inheritable handles, but
781     // that is ok because we've already spawned the subprocess.
782 
783     // In the past, reading from a pipe before the child process's C Runtime
784     // started up and called GetFileType() caused a hang: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/02/10243553.aspx#10244216
785     // This is reportedly fixed in Windows Vista: https://support.microsoft.com/en-us/kb/2009703
786     // I was unable to reproduce the problem on Windows XP. It sounds like a
787     // Windows Update may have fixed this: https://www.duckware.com/tech/peeknamedpipe.html
788     unique_handle   stdout_thread(reinterpret_cast<HANDLE>(
789             _beginthreadex(NULL, 0, _redirect_stdout_thread, stdout_read.get(),
790                            0, NULL)));
791     if (stdout_thread.get() == nullptr) {
792         fprintf(stderr, "Cannot create thread: %s\n", strerror(errno));
793         return -1;
794     }
795     stdout_read.release();  // Transfer ownership to new thread
796 
797     unique_handle   stderr_thread(reinterpret_cast<HANDLE>(
798             _beginthreadex(NULL, 0, _redirect_stderr_thread, stderr_read.get(),
799                            0, NULL)));
800     if (stderr_thread.get() == nullptr) {
801         fprintf(stderr, "Cannot create thread: %s\n", strerror(errno));
802         return -1;
803     }
804     stderr_read.release();  // Transfer ownership to new thread
805 
806     bool    got_ack = false;
807 
808     // Wait for the "OK\n" message, for the pipe to be closed, or other error.
809     {
810         char    temp[3];
811         DWORD   count = 0;
812 
813         if (ReadFile(ack_read.get(), temp, sizeof(temp), &count, NULL)) {
814             const CHAR  expected[] = "OK\n";
815             const DWORD expected_length = arraysize(expected) - 1;
816             if (count == expected_length &&
817                 memcmp(temp, expected, expected_length) == 0) {
818                 got_ack = true;
819             } else {
820                 fprintf(stderr, "ADB server didn't ACK\n");
821             }
822         } else {
823             const DWORD err = GetLastError();
824             // If the ACK was not written and the process exited, GetLastError()
825             // is probably ERROR_BROKEN_PIPE, in which case that info is not
826             // useful to the user.
827             fprintf(stderr, "could not read ok from ADB Server%s\n",
828                     err == ERROR_BROKEN_PIPE ? "" :
829                     android::base::StringPrintf(": %s",
830                             android::base::SystemErrorCodeToString(err).c_str()).c_str());
831         }
832     }
833 
834     // Always try to wait a bit for threads reading stdout/stderr to finish.
835     // If the process started ok, it should close the pipes causing the threads
836     // to finish. If the process had an error, it should exit, also causing
837     // the pipes to be closed. In that case we want to read all of the output
838     // and write it out so that the user can diagnose failures.
839     const DWORD     thread_timeout_ms = 15 * 1000;
840     const HANDLE    threads[] = { stdout_thread.get(), stderr_thread.get() };
841     const DWORD     wait_result = WaitForMultipleObjects(arraysize(threads),
842             threads, TRUE, thread_timeout_ms);
843     if (wait_result == WAIT_TIMEOUT) {
844         // Threads did not finish after waiting a little while. Perhaps the
845         // server didn't close pipes, or it is hung.
846         fprintf(stderr, "Timed-out waiting for threads to finish reading from "
847                 "ADB Server\n");
848         // Process handles are signaled when the process exits, so if we wait
849         // on the handle for 0 seconds and it returns 'timeout', that means that
850         // the process is still running.
851         if (WaitForSingleObject(process_handle.get(), 0) == WAIT_TIMEOUT) {
852             // We could TerminateProcess(), but that seems somewhat presumptive.
853             fprintf(stderr, "ADB Server is running: process id %lu\n",
854                     pinfo.dwProcessId);
855         }
856         return -1;
857     }
858 
859     if (wait_result != WAIT_OBJECT_0) {
860         fprintf(stderr, "Unexpected result waiting for threads: %lu: %s\n",
861                 wait_result, android::base::SystemErrorCodeToString(GetLastError()).c_str());
862         return -1;
863     }
864 
865     // For now ignore the thread exit codes and assume they worked properly.
866 
867     if (!got_ack) {
868         return -1;
869     }
870 #else /* !defined(_WIN32) */
871     // set up a pipe so the child can tell us when it is ready.
872     // fd[0] will be parent's end, and the child will write on fd[1]
873     int fd[2];
874     if (pipe(fd)) {
875         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
876         return -1;
877     }
878 
879     std::string path = android::base::GetExecutablePath();
880 
881     pid_t pid = fork();
882     if (pid < 0) return -1;
883 
884     if (pid == 0) {
885         // child side of the fork
886 
887         adb_close(fd[0]);
888 
889         char reply_fd[30];
890         snprintf(reply_fd, sizeof(reply_fd), "%d", fd[1]);
891         // child process
892         int result = execl(path.c_str(), "adb", "-L", socket_spec.c_str(), "fork-server", "server",
893                            "--reply-fd", reply_fd, NULL);
894         // this should not return
895         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
896     } else  {
897         // parent side of the fork
898 
899         char  temp[3];
900 
901         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
902         // wait for the "OK\n" message
903         adb_close(fd[1]);
904         int ret = adb_read(fd[0], temp, 3);
905         int saved_errno = errno;
906         adb_close(fd[0]);
907         if (ret < 0) {
908             fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
909             return -1;
910         }
911         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
912             fprintf(stderr, "ADB server didn't ACK\n" );
913             return -1;
914         }
915     }
916 #endif /* !defined(_WIN32) */
917     return 0;
918 }
919 #endif /* ADB_HOST */
920 
921 // Try to handle a network forwarding request.
922 // This returns 1 on success, 0 on failure, and -1 to indicate this is not
923 // a forwarding-related request.
handle_forward_request(const char * service,TransportType type,const char * serial,int reply_fd)924 int handle_forward_request(const char* service, TransportType type, const char* serial, int reply_fd)
925 {
926     if (!strcmp(service, "list-forward")) {
927         // Create the list of forward redirections.
928         std::string listeners = format_listeners();
929 #if ADB_HOST
930         SendOkay(reply_fd);
931 #endif
932         return SendProtocolString(reply_fd, listeners);
933     }
934 
935     if (!strcmp(service, "killforward-all")) {
936         remove_all_listeners();
937 #if ADB_HOST
938         /* On the host: 1st OKAY is connect, 2nd OKAY is status */
939         SendOkay(reply_fd);
940 #endif
941         SendOkay(reply_fd);
942         return 1;
943     }
944 
945     if (!strncmp(service, "forward:", 8) || !strncmp(service, "killforward:", 12)) {
946         // killforward:local
947         // forward:(norebind:)?local;remote
948         bool kill_forward = false;
949         bool no_rebind = false;
950         if (android::base::StartsWith(service, "killforward:")) {
951             kill_forward = true;
952             service += 12;
953         } else {
954             service += 8;   // skip past "forward:"
955             if (android::base::StartsWith(service, "norebind:")) {
956                 no_rebind = true;
957                 service += 9;
958             }
959         }
960 
961         std::vector<std::string> pieces = android::base::Split(service, ";");
962 
963         if (kill_forward) {
964             // Check killforward: parameter format: '<local>'
965             if (pieces.size() != 1 || pieces[0].empty()) {
966                 SendFail(reply_fd, android::base::StringPrintf("bad killforward: %s", service));
967                 return 1;
968             }
969         } else {
970             // Check forward: parameter format: '<local>;<remote>'
971             if (pieces.size() != 2 || pieces[0].empty() || pieces[1].empty() || pieces[1][0] == '*') {
972                 SendFail(reply_fd, android::base::StringPrintf("bad forward: %s", service));
973                 return 1;
974             }
975         }
976 
977         std::string error_msg;
978         atransport* transport = acquire_one_transport(type, serial, nullptr, &error_msg);
979         if (!transport) {
980             SendFail(reply_fd, error_msg);
981             return 1;
982         }
983 
984         std::string error;
985         InstallStatus r;
986         int resolved_tcp_port = 0;
987         if (kill_forward) {
988             r = remove_listener(pieces[0].c_str(), transport);
989         } else {
990             r = install_listener(pieces[0], pieces[1].c_str(), transport, no_rebind,
991                                  &resolved_tcp_port, &error);
992         }
993         if (r == INSTALL_STATUS_OK) {
994 #if ADB_HOST
995             // On the host: 1st OKAY is connect, 2nd OKAY is status.
996             SendOkay(reply_fd);
997 #endif
998             SendOkay(reply_fd);
999 
1000             // If a TCP port was resolved, send the actual port number back.
1001             if (resolved_tcp_port != 0) {
1002                 SendProtocolString(reply_fd, android::base::StringPrintf("%d", resolved_tcp_port));
1003             }
1004 
1005             return 1;
1006         }
1007 
1008         std::string message;
1009         switch (r) {
1010           case INSTALL_STATUS_OK: message = "success (!)"; break;
1011           case INSTALL_STATUS_INTERNAL_ERROR: message = "internal error"; break;
1012           case INSTALL_STATUS_CANNOT_BIND:
1013             message = android::base::StringPrintf("cannot bind listener: %s",
1014                                                   error.c_str());
1015             break;
1016           case INSTALL_STATUS_CANNOT_REBIND:
1017             message = android::base::StringPrintf("cannot rebind existing socket");
1018             break;
1019           case INSTALL_STATUS_LISTENER_NOT_FOUND:
1020             message = android::base::StringPrintf("listener '%s' not found", service);
1021             break;
1022         }
1023         SendFail(reply_fd, message);
1024         return 1;
1025     }
1026     return 0;
1027 }
1028 
1029 #if ADB_HOST
SendOkay(int fd,const std::string & s)1030 static int SendOkay(int fd, const std::string& s) {
1031     SendOkay(fd);
1032     SendProtocolString(fd, s);
1033     return 0;
1034 }
1035 #endif
1036 
handle_host_request(const char * service,TransportType type,const char * serial,int reply_fd,asocket * s)1037 int handle_host_request(const char* service, TransportType type,
1038                         const char* serial, int reply_fd, asocket* s) {
1039     if (strcmp(service, "kill") == 0) {
1040         fprintf(stderr, "adb server killed by remote request\n");
1041         fflush(stdout);
1042         SendOkay(reply_fd);
1043 
1044         // On Windows, if the process exits with open sockets that
1045         // shutdown(SD_SEND) has not been called on, TCP RST segments will be
1046         // sent to the peers which will cause their next recv() to error-out
1047         // with WSAECONNRESET. In the case of this code, that means the client
1048         // may not read the OKAY sent above.
1049         adb_shutdown(reply_fd);
1050 
1051         android::base::quick_exit(0);
1052     }
1053 
1054 #if ADB_HOST
1055     // "transport:" is used for switching transport with a specified serial number
1056     // "transport-usb:" is used for switching transport to the only USB transport
1057     // "transport-local:" is used for switching transport to the only local transport
1058     // "transport-any:" is used for switching transport to the only transport
1059     if (!strncmp(service, "transport", strlen("transport"))) {
1060         TransportType type = kTransportAny;
1061 
1062         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1063             type = kTransportUsb;
1064         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1065             type = kTransportLocal;
1066         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1067             type = kTransportAny;
1068         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1069             service += strlen("transport:");
1070             serial = service;
1071         }
1072 
1073         std::string error;
1074         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
1075         if (t != nullptr) {
1076             s->transport = t;
1077             SendOkay(reply_fd);
1078         } else {
1079             SendFail(reply_fd, error);
1080         }
1081         return 1;
1082     }
1083 
1084     // return a list of all connected devices
1085     if (!strncmp(service, "devices", 7)) {
1086         bool long_listing = (strcmp(service+7, "-l") == 0);
1087         if (long_listing || service[7] == 0) {
1088             D("Getting device list...");
1089             std::string device_list = list_transports(long_listing);
1090             D("Sending device list...");
1091             return SendOkay(reply_fd, device_list);
1092         }
1093         return 1;
1094     }
1095 
1096     if (!strcmp(service, "reconnect-offline")) {
1097         std::string response;
1098         close_usb_devices([&response](const atransport* transport) {
1099             switch (transport->connection_state) {
1100                 case kCsOffline:
1101                 case kCsUnauthorized:
1102                     response += "reconnecting ";
1103                     if (transport->serial) {
1104                         response += transport->serial;
1105                     } else {
1106                         response += "<unknown>";
1107                     }
1108                     response += "\n";
1109                     return true;
1110                 default:
1111                     return false;
1112             }
1113         });
1114         if (!response.empty()) {
1115             response.resize(response.size() - 1);
1116         }
1117         SendOkay(reply_fd, response);
1118         return 0;
1119     }
1120 
1121     if (!strcmp(service, "features")) {
1122         std::string error;
1123         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
1124         if (t != nullptr) {
1125             SendOkay(reply_fd, FeatureSetToString(t->features()));
1126         } else {
1127             SendFail(reply_fd, error);
1128         }
1129         return 0;
1130     }
1131 
1132 #if ADB_HOST
1133     if (!strcmp(service, "host-features")) {
1134         FeatureSet features = supported_features();
1135         // Abuse features to report libusb status.
1136         if (should_use_libusb()) {
1137             features.insert(kFeatureLibusb);
1138         }
1139         SendOkay(reply_fd, FeatureSetToString(features));
1140         return 0;
1141     }
1142 #endif
1143 
1144     // remove TCP transport
1145     if (!strncmp(service, "disconnect:", 11)) {
1146         const std::string address(service + 11);
1147         if (address.empty()) {
1148             kick_all_tcp_devices();
1149             return SendOkay(reply_fd, "disconnected everything");
1150         }
1151 
1152         std::string serial;
1153         std::string host;
1154         int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
1155         std::string error;
1156         if (!android::base::ParseNetAddress(address, &host, &port, &serial, &error)) {
1157             return SendFail(reply_fd, android::base::StringPrintf("couldn't parse '%s': %s",
1158                                                                   address.c_str(), error.c_str()));
1159         }
1160         atransport* t = find_transport(serial.c_str());
1161         if (t == nullptr) {
1162             return SendFail(reply_fd, android::base::StringPrintf("no such device '%s'",
1163                                                                   serial.c_str()));
1164         }
1165         kick_transport(t);
1166         return SendOkay(reply_fd, android::base::StringPrintf("disconnected %s", address.c_str()));
1167     }
1168 
1169     // Returns our value for ADB_SERVER_VERSION.
1170     if (!strcmp(service, "version")) {
1171         return SendOkay(reply_fd, android::base::StringPrintf("%04x", ADB_SERVER_VERSION));
1172     }
1173 
1174     // These always report "unknown" rather than the actual error, for scripts.
1175     if (!strcmp(service, "get-serialno")) {
1176         std::string error;
1177         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
1178         if (t) {
1179             return SendOkay(reply_fd, t->serial ? t->serial : "unknown");
1180         } else {
1181             return SendFail(reply_fd, error);
1182         }
1183     }
1184     if (!strcmp(service, "get-devpath")) {
1185         std::string error;
1186         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
1187         if (t) {
1188             return SendOkay(reply_fd, t->devpath ? t->devpath : "unknown");
1189         } else {
1190             return SendFail(reply_fd, error);
1191         }
1192     }
1193     if (!strcmp(service, "get-state")) {
1194         std::string error;
1195         atransport* t = acquire_one_transport(type, serial, nullptr, &error);
1196         if (t) {
1197             return SendOkay(reply_fd, t->connection_state_name());
1198         } else {
1199             return SendFail(reply_fd, error);
1200         }
1201     }
1202 
1203     // Indicates a new emulator instance has started.
1204     if (!strncmp(service, "emulator:", 9)) {
1205         int  port = atoi(service+9);
1206         local_connect(port);
1207         /* we don't even need to send a reply */
1208         return 0;
1209     }
1210 
1211     if (!strcmp(service, "reconnect")) {
1212         if (s->transport != nullptr) {
1213             kick_transport(s->transport);
1214         }
1215         return SendOkay(reply_fd, "done");
1216     }
1217 #endif // ADB_HOST
1218 
1219     int ret = handle_forward_request(service, type, serial, reply_fd);
1220     if (ret >= 0)
1221       return ret - 1;
1222     return -1;
1223 }
1224