string_escape.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. */ *p = *s;
  40. esc = 0;
  41. }
  42. if (!esc)
  43. p++;
  44. s++;
  45. }
  46. *p = '\0';
  47. return res;
  48. }
  49. /*--------------------------------------------------------- */
  50. inline char *lub_string_decode(const char *string)
  51. {
  52. return lub_string_ndecode(string, strlen(string));
  53. }
  54. /*----------------------------------------------------------- */
  55. /*
  56. * This needs to escape any dangerous characters within the command line
  57. * to prevent gaining access to the underlying system shell.
  58. */
  59. char *lub_string_encode(const char *string, const char *escape_chars)
  60. {
  61. char *result = NULL;
  62. const char *p;
  63. if (!escape_chars)
  64. return lub_string_dup(string);
  65. if (string && !(*string)) /* Empty string */
  66. return lub_string_dup(string);
  67. for (p = string; p && *p; p++) {
  68. /* find any special characters and prefix them with '\' */
  69. size_t len = strcspn(p, escape_chars);
  70. lub_string_catn(&result, p, len);
  71. p += len;
  72. if (*p) {
  73. lub_string_catn(&result, "\\", 1);
  74. lub_string_catn(&result, p, 1);
  75. } else {
  76. break;
  77. }
  78. }
  79. return result;
  80. }
  81. /*--------------------------------------------------------- */