From 6d41c53b61dbd433a094d4b33e86c83e12e3399b Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Sun, 6 Feb 2022 12:22:17 +0100 Subject: [PATCH] Fix adb connect parsing The function assumed that the raw output of "adb connect" was a NUL-terminated string, but it is not the case. It this output did not end with a space or a new line character, then sc_str_truncate() would write '\0' over the last character. Even worse, if the output was empty, then sc_str_truncate() would write out-of-bounds. Avoid the error-prone sc_str_truncate() util function. --- app/src/adb/adb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/adb/adb.c b/app/src/adb/adb.c index 11c1b298..3cfc5a95 100644 --- a/app/src/adb/adb.c +++ b/app/src/adb/adb.c @@ -339,7 +339,7 @@ sc_adb_connect(struct sc_intr *intr, const char *ip_port, unsigned flags) { // case of failure. As a workaround, check if its output starts with // "connected". char buf[128]; - ssize_t r = sc_pipe_read_all_intr(intr, pid, pout, buf, sizeof(buf)); + ssize_t r = sc_pipe_read_all_intr(intr, pid, pout, buf, sizeof(buf) - 1); sc_pipe_close(pout); bool ok = process_check_success_intr(intr, pid, "adb connect", flags); @@ -351,11 +351,15 @@ sc_adb_connect(struct sc_intr *intr, const char *ip_port, unsigned flags) { return false; } + assert((size_t) r < sizeof(buf)); + buf[r] = '\0'; + ok = !strncmp("connected", buf, sizeof("connected") - 1); if (!ok && !(flags & SC_ADB_NO_STDERR)) { // "adb connect" also prints errors to stdout. Since we capture it, // re-print the error to stderr. - sc_str_truncate(buf, r, "\r\n"); + size_t len = strcspn(buf, "\r\n"); + buf[len] = '\0'; fprintf(stderr, "%s\n", buf); } return ok;