string_escape.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * string_escape.c
  3. */
  4. #include "private.h"
  5. #include <stdlib.h>
  6. #include <string.h>
  7. /*
  8. * These are the escape characters which are used by default when
  9. * expanding variables. These characters will be backslash escaped
  10. * to prevent them from being interpreted in a script.
  11. *
  12. * This is a security feature to prevent users from arbitarily setting
  13. * parameters to contain special sequences.
  14. */
  15. static const char *default_escape_chars = "`|$<>&()#;";
  16. /*--------------------------------------------------------- */
  17. char *lub_string_ndecode(const char *string, unsigned int len)
  18. {
  19. const char *s = string;
  20. char *res, *p;
  21. int esc = 0;
  22. if (!string)
  23. return NULL;
  24. /* Allocate enough memory for result */
  25. p = res = malloc(len + 1);
  26. while (*s && (s < (string +len))) {
  27. if (!esc) {
  28. if ('\\' == *s)
  29. esc = 1;
  30. else
  31. *p = *s;
  32. } else {
  33. switch (*s) {
  34. case 'r':
  35. case 'n':
  36. *p = '\n';
  37. break;
  38. case 't':
  39. *p = '\t';
  40. break;
  41. default:
  42. *p = *s;
  43. break;
  44. }
  45. esc = 0;
  46. }
  47. if (!esc)
  48. p++;
  49. s++;
  50. }
  51. *p = '\0';
  52. return res;
  53. }
  54. /*--------------------------------------------------------- */
  55. inline char *lub_string_decode(const char *string)
  56. {
  57. return lub_string_ndecode(string, strlen(string));
  58. }
  59. /*----------------------------------------------------------- */
  60. /*
  61. * This needs to escape any dangerous characters within the command line
  62. * to prevent gaining access to the underlying system shell.
  63. */
  64. char *lub_string_encode(const char *string, const char *escape_chars)
  65. {
  66. char *result = NULL;
  67. const char *p;
  68. if (NULL == escape_chars) {
  69. escape_chars = default_escape_chars;
  70. }
  71. for (p = string; p && *p; p++) {
  72. /* find any special characters and prefix them with '\' */
  73. size_t len = strcspn(p, escape_chars);
  74. lub_string_catn(&result, p, len);
  75. p += len;
  76. if (*p) {
  77. lub_string_catn(&result, "\\", 1);
  78. lub_string_catn(&result, p, 1);
  79. } else {
  80. break;
  81. }
  82. }
  83. return result;
  84. }
  85. /*--------------------------------------------------------- */