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 = 16;
29 conf.mimes.t = calloc(conf.mimes.cap, sizeof(struct etm));
30 if (conf.mimes.t == NULL)
31 fatal("calloc: %s", strerror(errno));
32 }
34 /* register mime for the given extension */
35 void
36 add_mime(const char *mime, const char *ext)
37 {
38 if (conf.mimes.len == conf.mimes.cap) {
39 conf.mimes.cap *= 1.5;
40 conf.mimes.t = realloc(conf.mimes.t,
41 conf.mimes.cap * sizeof(struct etm));
42 if (conf.mimes.t == NULL)
43 fatal("realloc: %s", strerror(errno));
44 }
46 conf.mimes.t[conf.mimes.len].mime = mime;
47 conf.mimes.t[conf.mimes.len].ext = ext;
48 conf.mimes.len++;
49 }
51 /* load a default set of common mime-extension associations */
52 void
53 load_default_mime()
54 {
55 struct etm *i, m[] = {
56 {"application/pdf", "pdf"},
57 {"image/gif", "gif"},
58 {"image/jpeg", "jpg"},
59 {"image/jpeg", "jpeg"},
60 {"image/png", "png"},
61 {"image/svg+xml", "svg"},
62 {"text/gemini", "gemini"},
63 {"text/gemini", "gmi"},
64 {"text/markdown", "markdown"},
65 {"text/markdown", "md"},
66 {"text/plain", "txt"},
67 {"text/xml", "xml"},
68 {NULL, NULL}
69 };
71 for (i = m; i->mime != NULL; ++i)
72 add_mime(i->mime, i->ext);
73 }
75 static const char *
76 path_ext(const char *path)
77 {
78 const char *end;
80 end = path + strlen(path)-1;
81 for (; end != path; --end) {
82 if (*end == '.')
83 return end+1;
84 if (*end == '/')
85 break;
86 }
88 return NULL;
89 }
91 const char *
92 mime(struct vhost *host, const char *path)
93 {
94 const char *def, *ext;
95 struct etm *t;
97 if ((def = host->default_mime) == NULL)
98 def = "application/octet-stream";
100 if ((ext = path_ext(path)) == NULL)
101 return def;
103 for (t = conf.mimes.t; t->mime != NULL; ++t)
104 if (!strcmp(ext, t->ext))
105 return t->mime;
107 return def;