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 "gmid.h"
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <string.h>
23 void
24 init_mime(struct mime *mime)
25 {
26 mime->len = 0;
27 mime->cap = 16;
29 mime->t = calloc(mime->cap, sizeof(struct etm));
30 if (mime->t == NULL)
31 fatal("calloc: %s", strerror(errno));
32 }
34 /* register mime for the given extension */
35 void
36 add_mime(struct mime *mime, const char *mt, const char *ext)
37 {
38 size_t oldcap;
40 if (mime->len == mime->cap) {
41 oldcap = mime->cap;
42 mime->cap *= 1.5;
43 mime->t = recallocarray(mime->t, oldcap, mime->cap,
44 sizeof(struct etm));
45 if (mime->t == NULL)
46 err(1, "recallocarray");
47 }
49 mime->t[mime->len].mime = mt;
50 mime->t[mime->len].ext = ext;
51 mime->len++;
52 }
54 /* load a default set of common mime-extension associations */
55 void
56 load_default_mime(struct mime *mime)
57 {
58 struct etm *i, m[] = {
59 {"application/pdf", "pdf"},
60 {"image/gif", "gif"},
61 {"image/jpeg", "jpg"},
62 {"image/jpeg", "jpeg"},
63 {"image/png", "png"},
64 {"image/svg+xml", "svg"},
65 {"text/gemini", "gemini"},
66 {"text/gemini", "gmi"},
67 {"text/markdown", "markdown"},
68 {"text/markdown", "md"},
69 {"text/plain", "txt"},
70 {"text/x-patch", "diff"},
71 {"text/x-patch", "patch"},
72 {"text/xml", "xml"},
73 {NULL, NULL}
74 };
76 for (i = m; i->mime != NULL; ++i)
77 add_mime(mime, i->mime, i->ext);
78 }
80 static const char *
81 path_ext(const char *path)
82 {
83 const char *end;
85 end = path + strlen(path)-1;
86 for (; end != path; --end) {
87 if (*end == '.')
88 return end+1;
89 if (*end == '/')
90 break;
91 }
93 return NULL;
94 }
96 const char *
97 mime(struct vhost *host, const char *path)
98 {
99 const char *def, *ext;
100 struct etm *t;
102 def = vhost_default_mime(host, path);
104 if ((ext = path_ext(path)) == NULL)
105 return def;
107 for (t = conf.mime.t; t->mime != NULL; ++t)
108 if (!strcmp(ext, t->ext))
109 return t->mime;
111 return def;