summaryrefslogtreecommitdiff
path: root/src/shared/util.c
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2015-04-09 18:32:21 +0200
committerSven Eden <yamakuzure@gmx.net>2017-03-14 07:54:40 +0100
commit17384d7f95169dad5f769431374fc2c08101206d (patch)
tree9235c87659d28832379954db678d6953d197d172 /src/shared/util.c
parent425afb81685af43de63b2bb4293728a13d3a53d5 (diff)
util: add shell_maybe_quote() call for preparing a string for shell cmdline inclusion
If necessary the passed string is enclosed in "", and all special characters escapes. This also ports over usage in bus-util.c and job.c to use this, instead of a incorrect local implementation that forgets to properly escape.
Diffstat (limited to 'src/shared/util.c')
-rw-r--r--src/shared/util.c45
1 files changed, 43 insertions, 2 deletions
diff --git a/src/shared/util.c b/src/shared/util.c
index ab891fa2c..279def715 100644
--- a/src/shared/util.c
+++ b/src/shared/util.c
@@ -1353,7 +1353,8 @@ char *cescape(const char *s) {
assert(s);
- /* Does C style string escaping. */
+ /* Does C style string escaping. May be be reversed with
+ * cunescape(). */
r = new(char, strlen(s)*4 + 1);
if (!r)
@@ -1565,7 +1566,7 @@ char *xescape(const char *s, const char *bad) {
/* Escapes all chars in bad, in addition to \ and all special
* chars, in \xFF style escaping. May be reversed with
- * cunescape. */
+ * cunescape(). */
r = new(char, strlen(s) * 4 + 1);
if (!r)
@@ -7993,3 +7994,43 @@ int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char
return 0;
}
+
+char *shell_maybe_quote(const char *s) {
+ const char *p;
+ char *r, *t;
+
+ assert(s);
+
+ /* Encloses a string in double quotes if necessary to make it
+ * OK as shell string. */
+
+ for (p = s; *p; p++)
+ if (*p <= ' ' ||
+ *p >= 127 ||
+ strchr(SHELL_NEED_QUOTES, *p))
+ break;
+
+ if (!*p)
+ return strdup(s);
+
+ r = new(char, 1+strlen(s)*2+1+1);
+ if (!r)
+ return NULL;
+
+ t = r;
+ *(t++) = '"';
+ t = mempcpy(t, s, p - s);
+
+ for (; *p; p++) {
+
+ if (strchr(SHELL_NEED_ESCAPE, *p))
+ *(t++) = '\\';
+
+ *(t++) = *p;
+ }
+
+ *(t++)= '"';
+ *t = 0;
+
+ return r;
+}