aboutsummaryrefslogtreecommitdiff
path: root/mime.c
diff options
context:
space:
mode:
authorOmar Polo <op@omarpolo.com>2022-04-08 13:44:49 +0000
committerOmar Polo <op@omarpolo.com>2022-04-08 13:44:49 +0000
commitd8d170aa5ee1498babee095078b3888f1525a2b3 (patch)
tree7b025561608a276e18b63bf6955bb34a2d948fac /mime.c
parentaa6b8cf8ac4d93444bc2b4076b98621968bfc6ab (diff)
allow add_mime to fail
add_mime nows allocate dinamically copies of the passed strings, so that we can actually free what we parse from the config file. This matters a lot especially with lengthy `types' block: strings that reach the internal mapping are never free'd, so every manual addition is leaked.
Diffstat (limited to 'mime.c')
-rw-r--r--mime.c59
1 files changed, 45 insertions, 14 deletions
diff --git a/mime.c b/mime.c
index 398d561..715bec5 100644
--- a/mime.c
+++ b/mime.c
@@ -32,30 +32,44 @@ init_mime(struct mime *mime)
}
/* register mime for the given extension */
-void
+int
add_mime(struct mime *mime, const char *mt, const char *ext)
{
- size_t oldcap;
+ char *mimetype, *extension;
+ struct etm *t;
+ size_t newcap;
if (mime->len == mime->cap) {
- oldcap = mime->cap;
- mime->cap *= 1.5;
- mime->t = recallocarray(mime->t, oldcap, mime->cap,
+ newcap = mime->cap * 1.5;
+ t = recallocarray(mime->t, mime->cap, newcap,
sizeof(struct etm));
- if (mime->t == NULL)
- err(1, "recallocarray");
+ if (t == NULL)
+ return -1;
+ mime->t = t;
+ mime->cap = newcap;
+ }
+
+ if ((mimetype = strdup(mt)) == NULL)
+ return -1;
+ if ((extension = strdup(ext)) == NULL) {
+ free(mimetype);
+ return -1;
}
- mime->t[mime->len].mime = mt;
- mime->t[mime->len].ext = ext;
+ mime->t[mime->len].mime = mimetype;
+ mime->t[mime->len].ext = extension;
mime->len++;
+ return 0;
}
/* load a default set of common mime-extension associations */
-void
+int
load_default_mime(struct mime *mime)
{
- const struct etm *i, m[] = {
+ const struct mapping {
+ const char *mime;
+ const char *ext;
+ } m[] = {
{"application/pdf", "pdf"},
{"image/gif", "gif"},
{"image/jpeg", "jpg"},
@@ -71,10 +85,14 @@ load_default_mime(struct mime *mime)
{"text/x-patch", "patch"},
{"text/xml", "xml"},
{NULL, NULL}
- };
+ }, *i;
+
+ for (i = m; i->mime != NULL; ++i) {
+ if (add_mime(mime, i->mime, i->ext) == -1)
+ return -1;
+ }
- for (i = m; i->mime != NULL; ++i)
- add_mime(mime, i->mime, i->ext);
+ return 0;
}
static const char *
@@ -110,3 +128,16 @@ mime(struct vhost *host, const char *path)
return def;
}
+
+void
+free_mime(struct mime *m)
+{
+ struct etm *t;
+
+ for (t = m->t; t->mime != NULL; ++t) {
+ free(t->mime);
+ free(t->ext);
+ }
+
+ free(m->t);
+}