blob: 1ba8920151d8919e3d8b7b2a1236d7a82d27a939 [file] [log] [blame]
Arnaldo Carvalho de Meloa43783a2017-04-18 10:46:11 -03001#include <errno.h>
Arnaldo Carvalho de Melo380a71a2016-07-07 11:17:38 -03002#include <stdlib.h>
3#include "strbuf.h"
Ingo Molnar07800602009-04-20 15:00:56 +02004#include "quote.h"
Arnaldo Carvalho de Melo380a71a2016-07-07 11:17:38 -03005#include "util.h"
Ingo Molnar07800602009-04-20 15:00:56 +02006
Ingo Molnar07800602009-04-20 15:00:56 +02007/* 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
Masami Hiramatsu70a68982016-05-10 14:47:26 +090023static int sq_quote_buf(struct strbuf *dst, const char *src)
Ingo Molnar07800602009-04-20 15:00:56 +020024{
25 char *to_free = NULL;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090026 int ret;
Ingo Molnar07800602009-04-20 15:00:56 +020027
28 if (dst->buf == src)
29 to_free = strbuf_detach(dst, NULL);
30
Masami Hiramatsu70a68982016-05-10 14:47:26 +090031 ret = strbuf_addch(dst, '\'');
32 while (!ret && *src) {
Ingo Molnar07800602009-04-20 15:00:56 +020033 size_t len = strcspn(src, "'!");
Masami Hiramatsu70a68982016-05-10 14:47:26 +090034 ret = strbuf_add(dst, src, len);
Ingo Molnar07800602009-04-20 15:00:56 +020035 src += len;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090036 while (!ret && need_bs_quote(*src))
37 ret = strbuf_addf(dst, "'\\%c\'", *src++);
Ingo Molnar07800602009-04-20 15:00:56 +020038 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090039 if (!ret)
40 ret = strbuf_addch(dst, '\'');
Ingo Molnar07800602009-04-20 15:00:56 +020041 free(to_free);
Masami Hiramatsu70a68982016-05-10 14:47:26 +090042
43 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020044}
45
Masami Hiramatsu70a68982016-05-10 14:47:26 +090046int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
Ingo Molnar07800602009-04-20 15:00:56 +020047{
Masami Hiramatsu70a68982016-05-10 14:47:26 +090048 int i, ret;
Ingo Molnar07800602009-04-20 15:00:56 +020049
50 /* Copy into destination buffer. */
Masami Hiramatsu70a68982016-05-10 14:47:26 +090051 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]);
Ingo Molnar07800602009-04-20 15:00:56 +020057 if (maxlen && dst->len > maxlen)
Arnaldo Carvalho de Meloe7b32d12016-10-14 17:57:11 -030058 return -ENOSPC;
Ingo Molnar07800602009-04-20 15:00:56 +020059 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090060 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020061}