1 /*
2 * tvheadend, HTML/XML helper routines
3 * Copyright (C) 2012 Adam Sutton
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <string.h>
20
21 #include "webui/webui.h"
22 #include "hts_strtab.h"
23
24 /* Escape chars */
25 static struct {
26 char chr;
27 const char *esc;
28 } html_esc_codes[] = {
29 { '>', ">" },
30 { '<', "<" },
31 { '&', "&" },
32 { '\'', "'" },
33 { '"', ""e;" }
34 };
35
html_escape_char(const char chr)36 static const char *html_escape_char ( const char chr )
37 {
38 int i;
39 for ( i = 0; i < sizeof(html_esc_codes) / sizeof(html_esc_codes[0]); i++ ) {
40 if (html_esc_codes[i].chr == chr) return html_esc_codes[i].esc;
41 }
42 return NULL;
43 }
44
45 /**
46 * Escape characters that will interfere with xml.
47 * Count how many bytes str would contain if it would be rss escapped
48 */
49 size_t
html_escaped_len(const char * src)50 html_escaped_len(const char *src)
51 {
52 size_t len = 0;
53 const char *esc;
54 while (*src) {
55 if ((esc = html_escape_char(*src))) {
56 len += strlen(esc);
57 } else {
58 len++;
59 }
60 src++;
61 }
62 return len;
63 }
64
65 /*
66 * http (xml) escape a string
67 */
68 const char*
html_escape(char * dst,const char * src,size_t len)69 html_escape(char *dst, const char *src, size_t len)
70 {
71 const char *esc;
72 len--; // for NUL
73 while (*src && len) {
74 if ((esc = html_escape_char(*src))) {
75 while (*esc && len) {
76 *dst = *esc;
77 len--; dst++; esc++;
78 }
79 } else {
80 *dst = *src;
81 dst++; len--;
82 }
83 src++;
84 }
85 *dst = '\0';
86
87 return dst;
88 }
89