From fd5cdae359835518d9f9d3186340f73813e70a76 Mon Sep 17 00:00:00 2001 From: Benxi Liu Date: Thu, 1 Aug 2019 09:52:40 +0800 Subject: [PATCH] mraa: fix mraa_file_contains() and mraa_file_contains_both() These two functions may return wrong results if lines in the file contains embedded '\0' characters. For example, file "/proc/device-tree/compatible" could have multiple values in one line (corresponding to the dts), and the values are separated with '\0'. In this situation, we need to replace the embedded '\0' and check the entire line. If we don't do this, only the first value is checked by strstr(), and the function may return false even if the file contains certain content. Signed-off-by: Benxi Liu --- src/mraa.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/mraa.c b/src/mraa.c index 039d96a36..eab95a7c7 100644 --- a/src/mraa.c +++ b/src/mraa.c @@ -1068,13 +1068,23 @@ mraa_file_contains(const char* filename, const char* content) char* file = mraa_file_unglob(filename); if (file != NULL) { size_t len = 0; + size_t read = 0; char* line = NULL; FILE* fh = fopen(file, "r"); if (fh == NULL) { free(file); return 0; } - while ((getline(&line, &len, fh) != -1) && (found == 0)) { + while (((read = getline(&line, &len, fh)) != -1) && (found == 0)) { + if (strlen(line) < read) { + char* ptr = line; + while (ptr < line + read) { + if (*ptr == '\0') { + *ptr = ' '; + } + ++ptr; + } + } if (strstr(line, content)) { found = 1; break; @@ -1098,13 +1108,23 @@ mraa_file_contains_both(const char* filename, const char* content, const char* c char* file = mraa_file_unglob(filename); if (file != NULL) { size_t len = 0; + size_t read = 0; char* line = NULL; FILE* fh = fopen(file, "r"); if (fh == NULL) { free(file); return 0; } - while ((getline(&line, &len, fh) != -1) && (found == 0)) { + while (((read = getline(&line, &len, fh)) != -1) && (found == 0)) { + if (strlen(line) < read) { + char* ptr = line; + while (ptr < line + read) { + if (*ptr == '\0') { + *ptr = ' '; + } + ++ptr; + } + } if (strstr(line, content) && strstr(line, content2)) { found = 1; break;