string_escape.c 1.7 KB

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