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 return (0);
36 if (tp->tp_puts(tp, tmp) == -1)
37 return (-1);
38 } else {
39 if (tp->tp_putc(tp, *str) == -1)
40 return (-1);
41 }
42 }
44 return (0);
45 }
47 int
48 tp_htmlescape(struct template *tp, const char *str)
49 {
50 int r;
52 for (; *str; ++str) {
53 switch (*str) {
54 case '<':
55 r = tp->tp_puts(tp, "&lt;");
56 break;
57 case '>':
58 r = tp->tp_puts(tp, "&gt;");
59 break;
60 case '&':
61 r = tp->tp_puts(tp, "&amp;");
62 break;
63 case '"':
64 r = tp->tp_puts(tp, "&quot;");
65 break;
66 case '\'':
67 r = tp->tp_puts(tp, "&apos;");
68 break;
69 default:
70 r = tp->tp_putc(tp, *str);
71 break;
72 }
74 if (r == -1)
75 return (-1);
76 }
78 return (0);
79 }
81 struct template *
82 template(void *arg, tmpl_puts putsfn, tmpl_putc putcfn)
83 {
84 struct template *tp;
86 if ((tp = calloc(1, sizeof(*tp))) == NULL)
87 return (NULL);
89 tp->tp_arg = arg;
90 tp->tp_escape = tp_htmlescape;
91 tp->tp_puts = putsfn;
92 tp->tp_putc = putcfn;
94 return (tp);
95 }
97 void
98 template_free(struct template *tp)
99 {
100 free(tp->tp_tmp);
101 free(tp);