string_escape.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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_decode(const char *string)
  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(strlen(string) + 1);
  26. while (*s) {
  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. /* Optimize the memory allocated for result */
  53. p = lub_string_dup(res);
  54. free(res);
  55. return p;
  56. }
  57. /*----------------------------------------------------------- */
  58. /*
  59. * This needs to escape any dangerous characters within the command line
  60. * to prevent gaining access to the underlying system shell.
  61. */
  62. char *lub_string_encode(const char *string, const char *escape_chars)
  63. {
  64. char *result = NULL;
  65. const char *p;
  66. if (NULL == escape_chars) {
  67. escape_chars = default_escape_chars;
  68. }
  69. for (p = string; p && *p; p++) {
  70. /* find any special characters and prefix them with '\' */
  71. size_t len = strcspn(p, escape_chars);
  72. lub_string_catn(&result, p, len);
  73. p += len;
  74. if (*p) {
  75. lub_string_catn(&result, "\\", 1);
  76. lub_string_catn(&result, p, 1);
  77. } else {
  78. break;
  79. }
  80. }
  81. return result;
  82. }
  83. /*--------------------------------------------------------- */