From 53caaffdf4a6b64c52f1215577c48835c2f9c9a0 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Thu, 11 Jul 2019 14:50:26 +0200 Subject: [PATCH] string-util: readd string_erase() This was dropped in 8e27167cc9b8beda2bf49789b15f0b0301b95d17, but is actually useful for some usecases still. --- src/basic/string-util.c | 10 ++++++++++ src/basic/string-util.h | 2 ++ src/test/test-string-util.c | 24 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/src/basic/string-util.c b/src/basic/string-util.c index 8e6aa63806..b477a51534 100644 --- a/src/basic/string-util.c +++ b/src/basic/string-util.c @@ -1064,3 +1064,13 @@ bool string_is_safe(const char *p) { return true; } + +char* string_erase(char *x) { + if (!x) + return NULL; + + /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we + * used them. */ + explicit_bzero_safe(x, strlen(x)); + return x; +} diff --git a/src/basic/string-util.h b/src/basic/string-util.h index 04cc82b386..f10af9ad2f 100644 --- a/src/basic/string-util.h +++ b/src/basic/string-util.h @@ -278,3 +278,5 @@ static inline char* str_realloc(char **p) { return (*p = t); } + +char* string_erase(char *x); diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index 8ea3994366..7a05afb4ac 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -9,6 +9,29 @@ #include "utf8.h" #include "util.h" +static void test_string_erase(void) { + char *x; + + x = strdupa(""); + assert_se(streq(string_erase(x), "")); + + x = strdupa("1"); + assert_se(streq(string_erase(x), "")); + + x = strdupa("123456789"); + assert_se(streq(string_erase(x), "")); + + assert_se(x[1] == '\0'); + assert_se(x[2] == '\0'); + assert_se(x[3] == '\0'); + assert_se(x[4] == '\0'); + assert_se(x[5] == '\0'); + assert_se(x[6] == '\0'); + assert_se(x[7] == '\0'); + assert_se(x[8] == '\0'); + assert_se(x[9] == '\0'); +} + static void test_free_and_strndup_one(char **t, const char *src, size_t l, const char *expected, bool change) { int r; @@ -543,6 +566,7 @@ static void test_memory_startswith_no_case(void) { int main(int argc, char *argv[]) { test_setup_logging(LOG_DEBUG); + test_string_erase(); test_free_and_strndup(); test_ascii_strcasecmp_n(); test_ascii_strcasecmp_nn();