blob: c6d4ee2de752dbc5d44d90cf0e35a96f560d660b [file] [log] [blame]
Ingo Molnar07800602009-04-20 15:00:56 +02001#include "cache.h"
2#include "quote.h"
3
Ingo Molnar07800602009-04-20 15:00:56 +02004/* Help to copy the thing properly quoted for the shell safety.
5 * any single quote is replaced with '\'', any exclamation point
6 * is replaced with '\!', and the whole thing is enclosed in a
7 *
8 * E.g.
9 * original sq_quote result
10 * name ==> name ==> 'name'
11 * a b ==> a b ==> 'a b'
12 * a'b ==> a'\''b ==> 'a'\''b'
13 * a!b ==> a'\!'b ==> 'a'\!'b'
14 */
15static inline int need_bs_quote(char c)
16{
17 return (c == '\'' || c == '!');
18}
19
Masami Hiramatsu70a68982016-05-10 14:47:26 +090020static int sq_quote_buf(struct strbuf *dst, const char *src)
Ingo Molnar07800602009-04-20 15:00:56 +020021{
22 char *to_free = NULL;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090023 int ret;
Ingo Molnar07800602009-04-20 15:00:56 +020024
25 if (dst->buf == src)
26 to_free = strbuf_detach(dst, NULL);
27
Masami Hiramatsu70a68982016-05-10 14:47:26 +090028 ret = strbuf_addch(dst, '\'');
29 while (!ret && *src) {
Ingo Molnar07800602009-04-20 15:00:56 +020030 size_t len = strcspn(src, "'!");
Masami Hiramatsu70a68982016-05-10 14:47:26 +090031 ret = strbuf_add(dst, src, len);
Ingo Molnar07800602009-04-20 15:00:56 +020032 src += len;
Masami Hiramatsu70a68982016-05-10 14:47:26 +090033 while (!ret && need_bs_quote(*src))
34 ret = strbuf_addf(dst, "'\\%c\'", *src++);
Ingo Molnar07800602009-04-20 15:00:56 +020035 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090036 if (!ret)
37 ret = strbuf_addch(dst, '\'');
Ingo Molnar07800602009-04-20 15:00:56 +020038 free(to_free);
Masami Hiramatsu70a68982016-05-10 14:47:26 +090039
40 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020041}
42
Masami Hiramatsu70a68982016-05-10 14:47:26 +090043int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
Ingo Molnar07800602009-04-20 15:00:56 +020044{
Masami Hiramatsu70a68982016-05-10 14:47:26 +090045 int i, ret;
Ingo Molnar07800602009-04-20 15:00:56 +020046
47 /* Copy into destination buffer. */
Masami Hiramatsu70a68982016-05-10 14:47:26 +090048 ret = strbuf_grow(dst, 255);
49 for (i = 0; !ret && argv[i]; ++i) {
50 ret = strbuf_addch(dst, ' ');
51 if (ret)
52 break;
53 ret = sq_quote_buf(dst, argv[i]);
Ingo Molnar07800602009-04-20 15:00:56 +020054 if (maxlen && dst->len > maxlen)
55 die("Too many or long arguments");
56 }
Masami Hiramatsu70a68982016-05-10 14:47:26 +090057 return ret;
Ingo Molnar07800602009-04-20 15:00:56 +020058}