blob: 639d1da2f9786dee3b9e535724b5f1beaed3edda [file] [log] [blame]
Arnaldo Carvalho de Melo380a71a2016-07-07 11:17:38 -03001#include <stdlib.h>
2#include "strbuf.h"
Ingo Molnar07800602009-04-20 15:00:56 +02003#include "quote.h"
Arnaldo Carvalho de Melo380a71a2016-07-07 11:17:38 -03004#include "util.h"
Ingo Molnar07800602009-04-20 15:00:56 +02005
Ingo Molnar07800602009-04-20 15:00:56 +02006/* Help to copy the thing properly quoted for the shell safety.
7 * any single quote is replaced with '\'', any exclamation point
8 * is replaced with '\!', and the whole thing is enclosed in a
9 *
10 * E.g.
11 * original sq_quote result
12 * name ==> name ==> 'name'
13 * a b ==> a b ==> 'a b'
14 * a'b ==> a'\''b ==> 'a'\''b'
15 * a!b ==> a'\!'b ==> 'a'\!'b'
16 */
17static inline int need_bs_quote(char c)
18{
19 return (c == '\'' || c == '!');
20}
21
Masami Hiramatsu70a68982016-05-10 14:47:26 +090022static int sq_quote_buf(struct strbuf *dst, const char *src)
Ingo Molnar07800602009-04-20 15:00:56 +020023{
24 char *to_free = NULL;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090025 int ret;
Ingo Molnar07800602009-04-20 15:00:56 +020026
27 if (dst->buf == src)
28 to_free = strbuf_detach(dst, NULL);
29
Masami Hiramatsu70a68982016-05-10 14:47:26 +090030 ret = strbuf_addch(dst, '\'');
31 while (!ret && *src) {
Ingo Molnar07800602009-04-20 15:00:56 +020032 size_t len = strcspn(src, "'!");
Masami Hiramatsu70a68982016-05-10 14:47:26 +090033 ret = strbuf_add(dst, src, len);
Ingo Molnar07800602009-04-20 15:00:56 +020034 src += len;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090035 while (!ret && need_bs_quote(*src))
36 ret = strbuf_addf(dst, "'\\%c\'", *src++);
Ingo Molnar07800602009-04-20 15:00:56 +020037 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090038 if (!ret)
39 ret = strbuf_addch(dst, '\'');
Ingo Molnar07800602009-04-20 15:00:56 +020040 free(to_free);
Masami Hiramatsu70a68982016-05-10 14:47:26 +090041
42 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020043}
44
Masami Hiramatsu70a68982016-05-10 14:47:26 +090045int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
Ingo Molnar07800602009-04-20 15:00:56 +020046{
Masami Hiramatsu70a68982016-05-10 14:47:26 +090047 int i, ret;
Ingo Molnar07800602009-04-20 15:00:56 +020048
49 /* Copy into destination buffer. */
Masami Hiramatsu70a68982016-05-10 14:47:26 +090050 ret = strbuf_grow(dst, 255);
51 for (i = 0; !ret && argv[i]; ++i) {
52 ret = strbuf_addch(dst, ' ');
53 if (ret)
54 break;
55 ret = sq_quote_buf(dst, argv[i]);
Ingo Molnar07800602009-04-20 15:00:56 +020056 if (maxlen && dst->len > maxlen)
57 die("Too many or long arguments");
58 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090059 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020060}