1
0

string_escape.c 2.1 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 *
  18. lub_string_decode(const char *string)
  19. {
  20. const char *s = string;
  21. char *res, *p;
  22. int esc = 0;
  23. if (!string)
  24. return NULL;
  25. /* Allocate enough memory for result */
  26. p = res = malloc(strlen(string) + 1);
  27. while (*s) {
  28. if (!esc) {
  29. if ('\\' == *s)
  30. esc = 1;
  31. else
  32. *p = *s;
  33. } else {
  34. switch (*s) {
  35. case 'r':
  36. case 'n':
  37. *p = '\n';
  38. break;
  39. case 't':
  40. *p = '\t';
  41. break;
  42. default:
  43. *p = *s;
  44. break;
  45. }
  46. esc = 0;
  47. }
  48. if (!esc)
  49. p++;
  50. s++;
  51. }
  52. *p = '\0';
  53. /* Optimize the memory allocated for result */
  54. p = lub_string_dup(res);
  55. free(res);
  56. return p;
  57. }
  58. /*----------------------------------------------------------- */
  59. /*
  60. * This needs to escape any dangerous characters within the command line
  61. * to prevent gaining access to the underlying system shell.
  62. */
  63. char *lub_string_encode(const char *string, const char *escape_chars)
  64. {
  65. char *result = NULL;
  66. const char *p;
  67. if (NULL == escape_chars) {
  68. escape_chars = default_escape_chars;
  69. }
  70. for (p = string; p && *p; p++)
  71. {
  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. /*--------------------------------------------------------- */