PageRenderTime 41ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/reddish/lib/sundown/html/houdini_html_e.c

https://bitbucket.org/murarth/reddish
C | 84 lines | 58 code | 13 blank | 13 comment | 10 complexity | ad4e12539e64e6e7685a89b206d2e469 MD5 | raw file
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "houdini.h"
  5. #define ESCAPE_GROW_FACTOR(x) (((x) * 12) / 10) /* this is very scientific, yes */
  6. /**
  7. * According to the OWASP rules:
  8. *
  9. * & --> &amp;
  10. * < --> &lt;
  11. * > --> &gt;
  12. * " --> &quot;
  13. * ' --> &#x27; &apos; is not recommended
  14. * / --> &#x2F; forward slash is included as it helps end an HTML entity
  15. *
  16. */
  17. static const char HTML_ESCAPE_TABLE[] = {
  18. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  19. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20. 0, 0, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 4,
  21. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 0,
  22. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  24. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  25. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  26. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  27. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  28. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  29. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  30. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  31. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  32. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  33. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  34. };
  35. static const char *HTML_ESCAPES[] = {
  36. "",
  37. "&quot;",
  38. "&amp;",
  39. "&#39;",
  40. "&#47;",
  41. "&lt;",
  42. "&gt;"
  43. };
  44. void
  45. houdini_escape_html0(struct buf *ob, const uint8_t *src, size_t size, int secure)
  46. {
  47. size_t i = 0, org, esc = 0;
  48. bufgrow(ob, ESCAPE_GROW_FACTOR(size));
  49. while (i < size) {
  50. org = i;
  51. while (i < size && (esc = HTML_ESCAPE_TABLE[src[i]]) == 0)
  52. i++;
  53. if (i > org)
  54. bufput(ob, src + org, i - org);
  55. /* escaping */
  56. if (i >= size)
  57. break;
  58. /* The forward slash is only escaped in secure mode */
  59. if (src[i] == '/' && !secure) {
  60. bufputc(ob, '/');
  61. } else {
  62. bufputs(ob, HTML_ESCAPES[esc]);
  63. }
  64. i++;
  65. }
  66. }
  67. void
  68. houdini_escape_html(struct buf *ob, const uint8_t *src, size_t size)
  69. {
  70. houdini_escape_html0(ob, src, size, 1);
  71. }