Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1#include <errno.h>
2#include <stdlib.h>
3#include "strbuf.h"
4#include "quote.h"
5#include "util.h"
6
7/* Help to copy the thing properly quoted for the shell safety.
8 * any single quote is replaced with '\'', any exclamation point
9 * is replaced with '\!', and the whole thing is enclosed in a
10 *
11 * E.g.
12 * original sq_quote result
13 * name ==> name ==> 'name'
14 * a b ==> a b ==> 'a b'
15 * a'b ==> a'\''b ==> 'a'\''b'
16 * a!b ==> a'\!'b ==> 'a'\!'b'
17 */
18static inline int need_bs_quote(char c)
19{
20 return (c == '\'' || c == '!');
21}
22
23static int sq_quote_buf(struct strbuf *dst, const char *src)
24{
25 char *to_free = NULL;
26 int ret;
27
28 if (dst->buf == src)
29 to_free = strbuf_detach(dst, NULL);
30
31 ret = strbuf_addch(dst, '\'');
32 while (!ret && *src) {
33 size_t len = strcspn(src, "'!");
34 ret = strbuf_add(dst, src, len);
35 src += len;
36 while (!ret && need_bs_quote(*src))
37 ret = strbuf_addf(dst, "'\\%c\'", *src++);
38 }
39 if (!ret)
40 ret = strbuf_addch(dst, '\'');
41 free(to_free);
42
43 return ret;
44}
45
46int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
47{
48 int i, ret;
49
50 /* Copy into destination buffer. */
51 ret = strbuf_grow(dst, 255);
52 for (i = 0; !ret && argv[i]; ++i) {
53 ret = strbuf_addch(dst, ' ');
54 if (ret)
55 break;
56 ret = sq_quote_buf(dst, argv[i]);
57 if (maxlen && dst->len > maxlen)
58 return -ENOSPC;
59 }
60 return ret;
61}