aboutsummaryrefslogtreecommitdiff
path: root/src/html/houdini_html_u.c
blob: 49b4956b7381b355bc9eb3b1c45deae2e7b5aa04 (plain)
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "houdini.h"
  5. #include "utf8.h"
  6. #include "html_unescape.h"
  7. size_t
  8. houdini_unescape_ent(strbuf *ob, const uint8_t *src, size_t size)
  9. {
  10. size_t i = 0;
  11. if (size > 3 && src[0] == '#') {
  12. int codepoint = 0;
  13. if (_isdigit(src[1])) {
  14. for (i = 1; i < size && _isdigit(src[i]); ++i) {
  15. int cp = (codepoint * 10) + (src[i] - '0');
  16. if (cp < codepoint)
  17. return 0;
  18. codepoint = cp;
  19. }
  20. }
  21. else if (src[1] == 'x' || src[1] == 'X') {
  22. for (i = 2; i < size && _isxdigit(src[i]); ++i) {
  23. int cp = (codepoint * 16) + ((src[i] | 32) % 39 - 9);
  24. if (cp < codepoint)
  25. return 0;
  26. codepoint = cp;
  27. }
  28. }
  29. if (i < size && src[i] == ';' && codepoint) {
  30. utf8proc_encode_char(codepoint, ob);
  31. return i + 1;
  32. }
  33. }
  34. else {
  35. if (size > MAX_WORD_LENGTH)
  36. size = MAX_WORD_LENGTH;
  37. for (i = MIN_WORD_LENGTH; i < size; ++i) {
  38. if (src[i] == ' ')
  39. break;
  40. if (src[i] == ';') {
  41. const struct html_ent *entity = find_entity((char *)src, i);
  42. if (entity != NULL) {
  43. strbuf_put(ob, entity->utf8, entity->utf8_len);
  44. return i + 1;
  45. }
  46. break;
  47. }
  48. }
  49. }
  50. return 0;
  51. }
  52. int
  53. houdini_unescape_html(strbuf *ob, const uint8_t *src, size_t size)
  54. {
  55. size_t i = 0, org, ent;
  56. while (i < size) {
  57. org = i;
  58. while (i < size && src[i] != '&')
  59. i++;
  60. if (likely(i > org)) {
  61. if (unlikely(org == 0)) {
  62. if (i >= size)
  63. return 0;
  64. strbuf_grow(ob, HOUDINI_UNESCAPED_SIZE(size));
  65. }
  66. strbuf_put(ob, src + org, i - org);
  67. }
  68. /* escaping */
  69. if (i >= size)
  70. break;
  71. i++;
  72. ent = houdini_unescape_ent(ob, src + i, size - i);
  73. i += ent;
  74. /* not really an entity */
  75. if (ent == 0)
  76. strbuf_putc(ob, '&');
  77. }
  78. return 1;
  79. }
  80. void houdini_unescape_html_f(strbuf *ob, const uint8_t *src, size_t size)
  81. {
  82. if (!houdini_unescape_html(ob, src, size))
  83. strbuf_put(ob, src, size);
  84. }