quote.c 1.4 KB

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