Blob


1 /*
2 * Copyright (c) 2021 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 "compat.h"
19 #include <ctype.h>
20 #include <fnmatch.h>
21 #include <string.h>
23 #include "parser.h"
24 #include "telescope.h"
26 static int check_for_utf8(char*);
28 static struct parser_table {
29 const char *mediatype;
30 void (*parserinit)(struct parser*);
31 } ptable[] = {
32 { "text/gemini", gemtext_initparser },
33 { "text/x-patch", textpatch_initparser },
34 { "text/*", textplain_initparser },
35 { NULL, NULL}
36 };
38 static int
39 check_for_utf8(char *b)
40 {
41 for (;;) {
42 while (*b != '\0' && isspace(*b))
43 b++;
44 if (*b == '\0')
45 break;
46 if (!has_prefix(b, "charset=")) {
47 while (*b != '\0' && *b != ';')
48 b++;
49 if (*b == '\0')
50 break;
51 b++;
52 continue;
53 }
55 /* is charset= */
56 b += strlen("charset=");
57 /* TODO: improve the matching */
58 return has_prefix(b, "ASCII") || has_prefix(b, "ascii") ||
59 has_prefix(b, "UTF-8") || has_prefix(b, "utf-8");
60 }
62 return 1;
63 }
65 int
66 setup_parser_for(struct tab *tab)
67 {
68 char *b, buf[GEMINI_URL_LEN] = {0};
69 struct parser_table *t;
71 memcpy(buf, tab->meta, sizeof(tab->meta));
73 for (b = buf; *b != ';' && *b != '\0'; ++b)
74 ;
76 if (*b == ';') {
77 *b = '\0';
78 ++b;
79 }
81 if (!check_for_utf8(b))
82 return 0;
84 for (t = ptable; t->mediatype != NULL; ++t) {
85 if (!fnmatch(t->mediatype, buf, 0)) {
86 t->parserinit(&tab->buffer.page);
87 return 1;
88 }
89 }
91 return 0;
92 }