quote.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "cache.h"
  2. #include "quote.h"
  3. /* Help to copy the thing properly quoted for the shell safety.
  4. * any single quote is replaced with '\'', any exclamation point
  5. * is replaced with '\!', and the whole thing is enclosed in a
  6. *
  7. * E.g.
  8. * original sq_quote result
  9. * name ==> name ==> 'name'
  10. * a b ==> a b ==> 'a b'
  11. * a'b ==> a'\''b ==> 'a'\''b'
  12. * a!b ==> a'\!'b ==> 'a'\!'b'
  13. */
  14. static inline int need_bs_quote(char c)
  15. {
  16. return (c == '\'' || c == '!');
  17. }
  18. static void sq_quote_buf(struct strbuf *dst, const char *src)
  19. {
  20. char *to_free = NULL;
  21. if (dst->buf == src)
  22. to_free = strbuf_detach(dst, NULL);
  23. strbuf_addch(dst, '\'');
  24. while (*src) {
  25. size_t len = strcspn(src, "'!");
  26. strbuf_add(dst, src, len);
  27. src += len;
  28. while (need_bs_quote(*src)) {
  29. strbuf_addstr(dst, "'\\");
  30. strbuf_addch(dst, *src++);
  31. strbuf_addch(dst, '\'');
  32. }
  33. }
  34. strbuf_addch(dst, '\'');
  35. free(to_free);
  36. }
  37. void sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
  38. {
  39. int i;
  40. /* Copy into destination buffer. */
  41. strbuf_grow(dst, 255);
  42. for (i = 0; argv[i]; ++i) {
  43. strbuf_addch(dst, ' ');
  44. sq_quote_buf(dst, argv[i]);
  45. if (maxlen && dst->len > maxlen)
  46. die("Too many or long arguments");
  47. }
  48. }