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 struct etm { /* extension to mime */
24 const char *mime;
25 const char *ext;
26 };
28 struct mimes {
29 struct etm *t;
30 size_t len;
31 size_t cap;
32 };
34 struct mimes mimes;
36 void
37 init_mime(void)
38 {
39 mimes.len = 0;
40 mimes.cap = 2;
42 if ((mimes.t = calloc(mimes.cap, sizeof(struct etm))) == NULL)
43 fatal("calloc: %s", strerror(errno));
44 }
46 /* register mime for the given extension */
47 void
48 add_mime(const char *mime, const char *ext)
49 {
50 if (mimes.len == mimes.cap) {
51 mimes.cap *= 1.5;
52 mimes.t = realloc(mimes.t, mimes.cap * sizeof(struct etm));
53 if (mimes.t == NULL)
54 fatal("realloc: %s", strerror(errno));
55 }
57 mimes.t[mimes.len].mime = mime;
58 mimes.t[mimes.len].ext = ext;
59 mimes.len++;
60 }
62 /* load a default set of common mime-extension associations */
63 void
64 load_default_mime()
65 {
66 struct etm *i, m[] = {
67 {"application/pdf", "pdf"},
68 {"image/gif", "gif"},
69 {"image/jpeg", "jpg"},
70 {"image/jpeg", "jpeg"},
71 {"image/png", "png"},
72 {"image/svg+xml", "svg"},
73 {"text/gemini", "gemini"},
74 {"text/gemini", "gmi"},
75 {"text/markdown", "markdown"},
76 {"text/markdown", "md"},
77 {"text/plain", "txt"},
78 {"text/xml", "xml"},
79 {NULL, NULL}
80 };
82 for (i = m; i->mime != NULL; ++i)
83 add_mime(i->mime, i->ext);
84 }
86 static const char *
87 path_ext(const char *path)
88 {
89 const char *end;
91 end = path + strlen(path)-1;
92 for (; end != path; --end) {
93 if (*end == '.')
94 return end+1;
95 if (*end == '/')
96 break;
97 }
99 return NULL;
102 const char *
103 mime(const char *path)
105 const char *ext, *def = "application/octet-stream";
106 struct etm *t;
108 if ((ext = path_ext(path)) == NULL)
109 return def;
111 for (t = mimes.t; t->mime != NULL; ++t)
112 if (!strcmp(ext, t->ext))
113 return t->mime;
115 return def;