]> xenbits.xensource.com Git - libvirt.git/commitdiff
Add virBufferEscapeShell
authorGuido Günther <agx@sigxcpu.org>
Thu, 28 Jul 2011 13:25:00 +0000 (15:25 +0200)
committerGuido Günther <agx@sigxcpu.org>
Thu, 13 Oct 2011 21:41:31 +0000 (23:41 +0200)
Escape strings so they're safe to pass to the shell. It's based on
virsh's cmdEcho.

src/libvirt_private.syms
src/util/buf.c
src/util/buf.h

index 4f965185d880f2ab523857fc842c9b3eb94b2e10..189c5975fd10d36a536ffb0789fbe0db85d012b6 100644 (file)
@@ -27,6 +27,7 @@ virBufferContentAndReset;
 virBufferError;
 virBufferEscape;
 virBufferEscapeSexpr;
+virBufferEscapeShell;
 virBufferEscapeString;
 virBufferFreeAndReset;
 virBufferStrcat;
index fa12855a72d2b9c202ab58c0178bb216892951c4..34347b5dd5c43e287956f8d71e139e178d94b899 100644 (file)
@@ -485,6 +485,60 @@ virBufferURIEncodeString (virBufferPtr buf, const char *str)
     buf->content[buf->use] = '\0';
 }
 
+/**
+ * virBufferEscapeShell:
+ * @buf:  the buffer to append to
+ * @str:  an unquoted string
+ *
+ * Quotes a string so that the shell (/bin/sh) will interpret the
+ * quoted string to mean str.
+ */
+void
+virBufferEscapeShell(virBufferPtr buf, const char *str)
+{
+    int len;
+    char *escaped, *out;
+    const char *cur;
+
+    if ((buf == NULL) || (str == NULL))
+        return;
+
+    if (buf->error)
+        return;
+
+    /* Only quote if str includes shell metacharacters. */
+    if (!strpbrk(str, "\r\t\n !\"#$&'()*;<>?[\\]^`{|}~")) {
+        virBufferAdd(buf, str, -1);
+        return;
+    }
+
+    len = strlen(str);
+    if (xalloc_oversized(4, len) ||
+        VIR_ALLOC_N(escaped, 4 * len + 3) < 0) {
+        virBufferSetError(buf);
+        return;
+    }
+
+    cur = str;
+    out = escaped;
+
+    *out++ = '\'';
+    while (*cur != 0) {
+        *out++ = *cur++;
+        if (*cur == '\'') {
+            /* Replace literal ' with a close ', a \', and a open ' */
+            *out++ = '\\';
+            *out++ = '\'';
+            *out++ = '\'';
+        }
+    }
+    *out++ = '\'';
+    *out = 0;
+
+    virBufferAdd(buf, escaped, -1);
+    VIR_FREE(escaped);
+}
+
 /**
  * virBufferStrcat:
  * @buf:  the buffer to dump
index e545ed902da17a96b3374454a0e2e8f5df5c8d4b..1d0e790b618237c549483b7b95b569d0faf422fe 100644 (file)
@@ -52,6 +52,7 @@ void virBufferEscapeString(const virBufferPtr buf, const char *format, const cha
 void virBufferEscapeSexpr(const virBufferPtr buf, const char *format, const char *str);
 void virBufferEscape(const virBufferPtr buf, const char *toescape, const char *format, const char *str);
 void virBufferURIEncodeString (const virBufferPtr buf, const char *str);
+void virBufferEscapeShell(virBufferPtr buf, const char *str);
 
 # define virBufferAddLit(buf_, literal_string_) \
   virBufferAdd (buf_, "" literal_string_ "", sizeof literal_string_ - 1)