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 <errno.h>
18 #include <stdlib.h>
19 #include <string.h>
21 #include "gmid.h"
23 void
24 init_mime(void)
25 {
26 conf.mimes.len = 0;
27 conf.mimes.cap = 2;
29 conf.mimes.t = calloc(conf.mimes.cap, sizeof(struct etm));
30 if (conf.mimes.t == NULL)
31 fatal("calloc: %s", strerror(errno));
33 conf.mimes.def = strdup("application/octet-stream");
34 if (conf.mimes.def == NULL)
35 fatal("strdup: %s", strerror(errno));
37 }
39 void
40 set_default_mime(const char *m)
41 {
42 free(conf.mimes.def);
43 if ((conf.mimes.def = strdup(m)) == NULL)
44 fatal("strdup: %s", strerror(errno));
45 }
47 /* register mime for the given extension */
48 void
49 add_mime(const char *mime, const char *ext)
50 {
51 if (conf.mimes.len == conf.mimes.cap) {
52 conf.mimes.cap *= 1.5;
53 conf.mimes.t = realloc(conf.mimes.t,
54 conf.mimes.cap * sizeof(struct etm));
55 if (conf.mimes.t == NULL)
56 fatal("realloc: %s", strerror(errno));
57 }
59 conf.mimes.t[conf.mimes.len].mime = mime;
60 conf.mimes.t[conf.mimes.len].ext = ext;
61 conf.mimes.len++;
62 }
64 /* load a default set of common mime-extension associations */
65 void
66 load_default_mime()
67 {
68 struct etm *i, m[] = {
69 {"application/pdf", "pdf"},
70 {"image/gif", "gif"},
71 {"image/jpeg", "jpg"},
72 {"image/jpeg", "jpeg"},
73 {"image/png", "png"},
74 {"image/svg+xml", "svg"},
75 {"text/gemini", "gemini"},
76 {"text/gemini", "gmi"},
77 {"text/markdown", "markdown"},
78 {"text/markdown", "md"},
79 {"text/plain", "txt"},
80 {"text/xml", "xml"},
81 {NULL, NULL}
82 };
84 for (i = m; i->mime != NULL; ++i)
85 add_mime(i->mime, i->ext);
86 }
88 static const char *
89 path_ext(const char *path)
90 {
91 const char *end;
93 end = path + strlen(path)-1;
94 for (; end != path; --end) {
95 if (*end == '.')
96 return end+1;
97 if (*end == '/')
98 break;
99 }
101 return NULL;
104 const char *
105 mime(const char *path)
107 const char *ext;
108 struct etm *t;
110 if ((ext = path_ext(path)) == NULL)
111 return conf.mimes.def;
113 for (t = conf.mimes.t; t->mime != NULL; ++t)
114 if (!strcmp(ext, t->ext))
115 return t->mime;
117 return conf.mimes.def;