quote.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 int sq_quote_buf(struct strbuf *dst, const char *src)
  19. {
  20. char *to_free = NULL;
  21. int ret;
  22. if (dst->buf == src)
  23. to_free = strbuf_detach(dst, NULL);
  24. ret = strbuf_addch(dst, '\'');
  25. while (!ret && *src) {
  26. size_t len = strcspn(src, "'!");
  27. ret = strbuf_add(dst, src, len);
  28. src += len;
  29. while (!ret && need_bs_quote(*src))
  30. ret = strbuf_addf(dst, "'\\%c\'", *src++);
  31. }
  32. if (!ret)
  33. ret = strbuf_addch(dst, '\'');
  34. free(to_free);
  35. return ret;
  36. }
  37. int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
  38. {
  39. int i, ret;
  40. /* Copy into destination buffer. */
  41. ret = strbuf_grow(dst, 255);
  42. for (i = 0; !ret && argv[i]; ++i) {
  43. ret = strbuf_addch(dst, ' ');
  44. if (ret)
  45. break;
  46. ret = sq_quote_buf(dst, argv[i]);
  47. if (maxlen && dst->len > maxlen)
  48. die("Too many or long arguments");
  49. }
  50. return ret;
  51. }