Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <ctype.h>
18 #include <stdio.h>
19 #include <stdlib.h>
21 #include "tmpl.h"
23 int
24 tp_urlescape(struct template *tp, const char *str)
25 {
26 int r;
27 char tmp[4];
29 for (; *str; ++str) {
30 if (iscntrl((unsigned char)*str) ||
31 isspace((unsigned char)*str) ||
32 *str == '\'' || *str == '"' || *str == '\\') {
33 r = snprintf(tmp, sizeof(tmp), "%%%2X", *str);
34 if (r < 0 || (size_t)r >= sizeof(tmp)) {
35 tp->tp_ret = -1;
36 return (-1);
37 }
38 if (tp->tp_puts(tp, tmp) == -1)
39 return (-1);
40 } else {
41 if (tp->tp_putc(tp, *str) == -1)
42 return (-1);
43 }
44 }
46 return (0);
47 }
49 int
50 tp_htmlescape(struct template *tp, const char *str)
51 {
52 int r;
54 for (; *str; ++str) {
55 switch (*str) {
56 case '<':
57 r = tp->tp_puts(tp, "&lt;");
58 break;
59 case '>':
60 r = tp->tp_puts(tp, "&gt;");
61 break;
62 case '&':
63 r = tp->tp_puts(tp, "&amp;");
64 break;
65 case '"':
66 r = tp->tp_puts(tp, "&quot;");
67 break;
68 case '\'':
69 r = tp->tp_puts(tp, "&apos;");
70 break;
71 default:
72 r = tp->tp_putc(tp, *str);
73 break;
74 }
76 if (r == -1) {
77 tp->tp_ret = -1;
78 return (-1);
79 }
80 }
82 return (0);
83 }
85 struct template *
86 template(void *arg, tmpl_puts putsfn, tmpl_putc putcfn)
87 {
88 struct template *tp;
90 if ((tp = calloc(1, sizeof(*tp))) == NULL)
91 return (NULL);
93 tp->tp_arg = arg;
94 tp->tp_escape = tp_htmlescape;
95 tp->tp_puts = putsfn;
96 tp->tp_putc = putcfn;
98 return (tp);
99 }
101 void
102 template_reset(struct template *tp)
104 tp->tp_ret = 0;