2 b2b17923 2022-12-17 op * Copyright (c) 2022 Omar Polo <op@openbsd.org>
4 2c02675e 2022-12-14 op * Permission to use, copy, modify, and distribute this software for any
5 2c02675e 2022-12-14 op * purpose with or without fee is hereby granted, provided that the above
6 2c02675e 2022-12-14 op * copyright notice and this permission notice appear in all copies.
8 2c02675e 2022-12-14 op * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 2c02675e 2022-12-14 op * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 2c02675e 2022-12-14 op * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 2c02675e 2022-12-14 op * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 2c02675e 2022-12-14 op * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 2c02675e 2022-12-14 op * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 2c02675e 2022-12-14 op * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 2c02675e 2022-12-14 op #include <ctype.h>
18 2c02675e 2022-12-14 op #include <stdio.h>
19 2c02675e 2022-12-14 op #include <stdlib.h>
21 2c02675e 2022-12-14 op #include "tmpl.h"
24 2c02675e 2022-12-14 op tp_urlescape(struct template *tp, const char *str)
29 2c02675e 2022-12-14 op if (str == NULL)
32 2c02675e 2022-12-14 op for (; *str; ++str) {
33 2c02675e 2022-12-14 op if (iscntrl((unsigned char)*str) ||
34 2c02675e 2022-12-14 op isspace((unsigned char)*str) ||
35 2c02675e 2022-12-14 op *str == '\'' || *str == '"' || *str == '\\') {
36 2c02675e 2022-12-14 op r = snprintf(tmp, sizeof(tmp), "%%%2X", *str);
37 2c02675e 2022-12-14 op if (r < 0 || (size_t)r >= sizeof(tmp))
39 2c02675e 2022-12-14 op if (tp->tp_puts(tp, tmp) == -1)
42 2c02675e 2022-12-14 op if (tp->tp_putc(tp, *str) == -1)
51 2c02675e 2022-12-14 op tp_htmlescape(struct template *tp, const char *str)
55 2c02675e 2022-12-14 op if (str == NULL)
58 2c02675e 2022-12-14 op for (; *str; ++str) {
59 2c02675e 2022-12-14 op switch (*str) {
61 2c02675e 2022-12-14 op r = tp->tp_puts(tp, "<");
64 2c02675e 2022-12-14 op r = tp->tp_puts(tp, ">");
67 2c02675e 2022-12-14 op r = tp->tp_puts(tp, "&");
70 2c02675e 2022-12-14 op r = tp->tp_puts(tp, """);
73 2c02675e 2022-12-14 op r = tp->tp_puts(tp, "'");
76 2c02675e 2022-12-14 op r = tp->tp_putc(tp, *str);
87 2c02675e 2022-12-14 op struct template *
88 2c02675e 2022-12-14 op template(void *arg, tmpl_puts putsfn, tmpl_putc putcfn)
90 2c02675e 2022-12-14 op struct template *tp;
92 2c02675e 2022-12-14 op if ((tp = calloc(1, sizeof(*tp))) == NULL)
93 2c02675e 2022-12-14 op return (NULL);
95 2c02675e 2022-12-14 op tp->tp_arg = arg;
96 2c02675e 2022-12-14 op tp->tp_escape = tp_htmlescape;
97 2c02675e 2022-12-14 op tp->tp_puts = putsfn;
98 2c02675e 2022-12-14 op tp->tp_putc = putcfn;
104 2c02675e 2022-12-14 op template_free(struct template *tp)
106 2c02675e 2022-12-14 op free(tp->tp_tmp);