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 "telescope.h"
19 #include <ctype.h>
20 #include <fnmatch.h>
21 #include <string.h>
23 static int check_for_utf8(char*);
25 static struct parser_table {
26 const char *mediatype;
27 void (*parserinit)(struct parser*);
28 } ptable[] = {
29 { "text/gemini", gemtext_initparser },
30 { "text/*", textplain_initparser },
31 { NULL, NULL}
32 };
34 static int
35 check_for_utf8(char *b)
36 {
37 for (;;) {
38 while (*b != '\0' && isspace(*b))
39 b++;
40 if (*b == '\0')
41 break;
42 if (!has_prefix(b, "charset=")) {
43 while (*b != '\0' && *b != ';')
44 b++;
45 if (*b == '\0')
46 break;
47 b++;
48 continue;
49 }
51 /* is charset= */
52 b += strlen("charset=");
53 /* TODO: improve the matching */
54 return has_prefix(b, "ASCII") || has_prefix(b, "ascii") ||
55 has_prefix(b, "UTF-8") || has_prefix(b, "utf-8");
56 }
58 return 1;
59 }
61 int
62 setup_parser_for(struct tab *tab)
63 {
64 char *b, buf[GEMINI_URL_LEN] = {0};
65 struct parser_table *t;
67 memcpy(buf, tab->meta, sizeof(tab->meta));
69 for (b = buf; *b != ';' && *b != '\0'; ++b)
70 ;
72 if (*b == ';') {
73 *b = '\0';
74 ++b;
75 }
77 if (!check_for_utf8(b))
78 return 0;
80 for (t = ptable; t->mediatype != NULL; ++t) {
81 if (!fnmatch(t->mediatype, buf, 0)) {
82 t->parserinit(&tab->page);
83 return 1;
84 }
85 }
87 return 0;
88 }