string_escape.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. return lub_string_dup(string);
  64. if (string && !(*string)) /* Empty string */
  65. return lub_string_dup(string);
  66. for (p = string; p && *p; p++) {
  67. /* find any special characters and prefix them with '\' */
  68. size_t len = strcspn(p, escape_chars);
  69. lub_string_catn(&result, p, len);
  70. p += len;
  71. if (*p) {
  72. lub_string_catn(&result, "\\", 1);
  73. lub_string_catn(&result, p, 1);
  74. } else {
  75. break;
  76. }
  77. }
  78. return result;
  79. }
  80. /*--------------------------------------------------------- */