quote.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <errno.h>
  3. #include <stdlib.h>
  4. #include "strbuf.h"
  5. #include "quote.h"
  6. #include "util.h"
  7. /* 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. */
  18. static inline int need_bs_quote(char c)
  19. {
  20. return (c == '\'' || c == '!');
  21. }
  22. static int sq_quote_buf(struct strbuf *dst, const char *src)
  23. {
  24. char *to_free = NULL;
  25. int ret;
  26. if (dst->buf == src)
  27. to_free = strbuf_detach(dst, NULL);
  28. ret = strbuf_addch(dst, '\'');
  29. while (!ret && *src) {
  30. size_t len = strcspn(src, "'!");
  31. ret = strbuf_add(dst, src, len);
  32. src += len;
  33. while (!ret && need_bs_quote(*src))
  34. ret = strbuf_addf(dst, "'\\%c\'", *src++);
  35. }
  36. if (!ret)
  37. ret = strbuf_addch(dst, '\'');
  38. free(to_free);
  39. return ret;
  40. }
  41. int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
  42. {
  43. int i, ret;
  44. /* Copy into destination buffer. */
  45. ret = strbuf_grow(dst, 255);
  46. for (i = 0; !ret && argv[i]; ++i) {
  47. ret = strbuf_addch(dst, ' ');
  48. if (ret)
  49. break;
  50. ret = sq_quote_buf(dst, argv[i]);
  51. if (maxlen && dst->len > maxlen)
  52. return -ENOSPC;
  53. }
  54. return ret;
  55. }