string_escape.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * string_escape.c
  3. */
  4. #include "private.h"
  5. #include <stdlib.h>
  6. #include <string.h>
  7. const char *lub_string_esc_default = "`|$<>&()#;";
  8. const char *lub_string_esc_regex = "^$.*+[](){}";
  9. const char *lub_string_esc_quoted = "\\\"";
  10. /*--------------------------------------------------------- */
  11. char *lub_string_ndecode(const char *string, unsigned int len)
  12. {
  13. const char *s = string;
  14. char *res, *p;
  15. int esc = 0;
  16. if (!string)
  17. return NULL;
  18. /* Allocate enough memory for result */
  19. p = res = malloc(len + 1);
  20. while (*s && (s < (string +len))) {
  21. if (!esc) {
  22. if ('\\' == *s)
  23. esc = 1;
  24. else
  25. *p = *s;
  26. } else {
  27. switch (*s) {
  28. case 'r':
  29. case 'n':
  30. *p = '\n';
  31. break;
  32. case 't':
  33. *p = '\t';
  34. break;
  35. default:
  36. *p = *s;
  37. break;
  38. }
  39. esc = 0;
  40. }
  41. if (!esc)
  42. p++;
  43. s++;
  44. }
  45. *p = '\0';
  46. return res;
  47. }
  48. /*--------------------------------------------------------- */
  49. inline char *lub_string_decode(const char *string)
  50. {
  51. return lub_string_ndecode(string, strlen(string));
  52. }
  53. /*----------------------------------------------------------- */
  54. /*
  55. * This needs to escape any dangerous characters within the command line
  56. * to prevent gaining access to the underlying system shell.
  57. */
  58. char *lub_string_encode(const char *string, const char *escape_chars)
  59. {
  60. char *result = NULL;
  61. const char *p;
  62. if (!escape_chars)
  63. lub_string_dup(string);
  64. for (p = string; p && *p; p++) {
  65. /* find any special characters and prefix them with '\' */
  66. size_t len = strcspn(p, escape_chars);
  67. lub_string_catn(&result, p, len);
  68. p += len;
  69. if (*p) {
  70. lub_string_catn(&result, "\\", 1);
  71. lub_string_catn(&result, p, 1);
  72. } else {
  73. break;
  74. }
  75. }
  76. return result;
  77. }
  78. /*--------------------------------------------------------- */