From: Zbigniew Jędrzejewski-Szmek Date: Wed, 3 Mar 2021 12:40:51 +0000 (+0100) Subject: basic/escape: add mode where empty arguments are still shown as "" X-Git-Tag: v249-rc1~274^2~18 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=1129cd8a71680f72b9c65b1bf83b96f9581454a3;p=thirdparty%2Fsystemd.git basic/escape: add mode where empty arguments are still shown as "" For variables, FOO= is OK. But when quoting positional arguments, we want to use something with quotes ("", '', or even $'') for an empty string. --- diff --git a/src/basic/escape.c b/src/basic/escape.c index 7a9a3b56166..2de275f04e1 100644 --- a/src/basic/escape.c +++ b/src/basic/escape.c @@ -504,6 +504,9 @@ char* shell_maybe_quote(const char *s, ShellEscapeFlags flags) { * string. Note that we treat benign UTF-8 characters as needing * escaping too, but that should be OK. */ + if (FLAGS_SET(flags, SHELL_ESCAPE_EMPTY) && isempty(s)) + return strdup("\"\""); /* We don't use $'' here in the POSIX mode. "" is fine too. */ + for (p = s; *p; p++) if (*p <= ' ' || *p >= 127 || diff --git a/src/basic/escape.h b/src/basic/escape.h index 7ecae49e10d..3cb107ae902 100644 --- a/src/basic/escape.h +++ b/src/basic/escape.h @@ -38,6 +38,7 @@ typedef enum ShellEscapeFlags { * Tabs and newlines are escaped. */ SHELL_ESCAPE_POSIX = 1 << 1, /* Use POSIX shell escape syntax (a string enclosed in $'') instead of plain quotes. */ + SHELL_ESCAPE_EMPTY = 1 << 2, /* Format empty arguments as "". */ } ShellEscapeFlags; char* cescape(const char *s); diff --git a/src/test/test-escape.c b/src/test/test-escape.c index 1e653688420..854a55174b9 100644 --- a/src/test/test-escape.c +++ b/src/test/test-escape.c @@ -140,7 +140,9 @@ static void test_shell_maybe_quote_one(const char *s, ShellEscapeFlags flags, co static void test_shell_maybe_quote(void) { test_shell_maybe_quote_one("", 0, ""); + test_shell_maybe_quote_one("", SHELL_ESCAPE_EMPTY, "\"\""); test_shell_maybe_quote_one("", SHELL_ESCAPE_POSIX, ""); + test_shell_maybe_quote_one("", SHELL_ESCAPE_POSIX | SHELL_ESCAPE_EMPTY, "\"\""); test_shell_maybe_quote_one("\\", 0, "\"\\\\\""); test_shell_maybe_quote_one("\\", SHELL_ESCAPE_POSIX, "$'\\\\'"); test_shell_maybe_quote_one("\"", 0, "\"\\\"\""); @@ -156,7 +158,9 @@ static void test_shell_maybe_quote(void) { test_shell_maybe_quote_one("foo \"bar\" waldo", 0, "\"foo \\\"bar\\\" waldo\""); test_shell_maybe_quote_one("foo \"bar\" waldo", SHELL_ESCAPE_POSIX, "$'foo \"bar\" waldo'"); test_shell_maybe_quote_one("foo$bar", 0, "\"foo\\$bar\""); + test_shell_maybe_quote_one("foo$bar", SHELL_ESCAPE_EMPTY, "\"foo\\$bar\""); test_shell_maybe_quote_one("foo$bar", SHELL_ESCAPE_POSIX, "$'foo$bar'"); + test_shell_maybe_quote_one("foo$bar", SHELL_ESCAPE_POSIX | SHELL_ESCAPE_EMPTY, "$'foo$bar'"); /* Note that current users disallow control characters, so this "test" * is here merely to establish current behaviour. If control characters