Просмотр исходного кода

libdpkg: Add new str_quote_meta() function

Guillem Jover лет назад: 15
Родитель
Сommit
8578e79d03
3 измененных файлов с 51 добавлено и 0 удалено
  1. 30 0
      lib/dpkg/string.c
  2. 1 0
      lib/dpkg/string.h
  3. 20 0
      lib/dpkg/test/t-string.c

+ 30 - 0
lib/dpkg/string.c

@@ -25,6 +25,7 @@
 #include <string.h>
 
 #include <dpkg/string.h>
+#include <dpkg/dpkg.h>
 
 /**
  * Escape format characters from a string.
@@ -60,6 +61,35 @@ str_escape_fmt(char *dst, const char *src, size_t n)
 	return d;
 }
 
+/**
+ * Quote shell metacharacters in a string.
+ *
+ * This function allows passing strings to commands without splitting the
+ * arguments, like in system(3)
+ *
+ * @param src The source string to escape.
+ *
+ * @return The new allocated string.
+ */
+char *
+str_quote_meta(const char *src)
+{
+	char *new_dst, *dst;
+
+	new_dst = dst = m_malloc(strlen(src) * 2);
+
+	while (*src) {
+		if (!cisdigit(*src) && !cisalpha(*src))
+			*dst++ = '\\';
+
+		*dst++ = *src++;
+	}
+
+	*dst = '\0';
+
+	return new_dst;
+}
+
 /**
  * Check and strip possible surrounding quotes in string.
  *

+ 1 - 0
lib/dpkg/string.h

@@ -26,6 +26,7 @@
 DPKG_BEGIN_DECLS
 
 char *str_escape_fmt(char *dest, const char *src, size_t n);
+char *str_quote_meta(const char *src);
 char *str_strip_quotes(char *str);
 
 DPKG_END_DECLS

+ 20 - 0
lib/dpkg/test/t-string.c

@@ -24,6 +24,7 @@
 #include <dpkg/test.h>
 #include <dpkg/string.h>
 
+#include <stdlib.h>
 #include <string.h>
 
 static void
@@ -63,6 +64,24 @@ test_str_escape_fmt(void)
 	test_str(buf, ==, "%% end");
 }
 
+static void
+test_str_quote_meta(void)
+{
+	char *str;
+
+	str = str_quote_meta("foo bar");
+	test_str(str, ==, "foo\\ bar");
+	free(str);
+
+	str = str_quote_meta("foo?bar");
+	test_str(str, ==, "foo\\?bar");
+	free(str);
+
+	str = str_quote_meta("foo*bar");
+	test_str(str, ==, "foo\\*bar");
+	free(str);
+}
+
 static void
 test_str_strip_quotes(void)
 {
@@ -109,5 +128,6 @@ static void
 test(void)
 {
 	test_str_escape_fmt();
+	test_str_quote_meta();
 	test_str_strip_quotes();
 }