mime: rewrite detection function
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
parent
790d2498cb
commit
73f199be3f
62
shared.c
62
shared.c
@ -563,49 +563,39 @@ char *expand_macros(const char *txt)
|
|||||||
|
|
||||||
char *get_mimetype_for_filename(const char *filename)
|
char *get_mimetype_for_filename(const char *filename)
|
||||||
{
|
{
|
||||||
static const char *delimiters;
|
char *ext, *mimetype, *token, line[1024];
|
||||||
char *ext = NULL, *iterate, *mimetype = NULL, *token;
|
FILE *file;
|
||||||
char line[1024];
|
|
||||||
FILE *fd;
|
|
||||||
struct string_list_item *mime;
|
struct string_list_item *mime;
|
||||||
|
|
||||||
if (filename == NULL)
|
if (!filename)
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
ext = strrchr(filename, '.');
|
ext = strrchr(filename, '.');
|
||||||
|
if (!ext)
|
||||||
|
return NULL;
|
||||||
|
++ext;
|
||||||
|
if (!ext[0])
|
||||||
|
return NULL;
|
||||||
|
mime = string_list_lookup(&ctx.cfg.mimetypes, ext);
|
||||||
|
if (mime)
|
||||||
|
return xstrdup(mime->util);
|
||||||
|
|
||||||
if (ext && *(++ext)) {
|
if (!ctx.cfg.mimetype_file)
|
||||||
mime = string_list_lookup(&ctx.cfg.mimetypes, ext);
|
return NULL;
|
||||||
if (mime) {
|
file = fopen(ctx.cfg.mimetype_file, "r");
|
||||||
/* We could just pass the pointer here, but would have to care
|
if (!file)
|
||||||
* whether or not to free the memory. Instead just dup. */
|
return NULL;
|
||||||
mimetype = xstrdup(mime->util);
|
while (fgets(line, sizeof(line), file)) {
|
||||||
} else if (ctx.cfg.mimetype_file != NULL) {
|
if (!line[0] || line[0] == '#')
|
||||||
fd = fopen(ctx.cfg.mimetype_file, "r");
|
continue;
|
||||||
if (fd == NULL)
|
mimetype = strtok(line, " \t\r\n");
|
||||||
return NULL;
|
while ((token = strtok(NULL, " \t\r\n"))) {
|
||||||
|
if (!strcasecmp(ext, token)) {
|
||||||
delimiters = " \t\r\n";
|
fclose(file);
|
||||||
|
return xstrdup(mimetype);
|
||||||
/* loop over all lines in the file */
|
|
||||||
while (mimetype == NULL && fgets(line, sizeof(line), fd)) {
|
|
||||||
iterate = strtok(line, delimiters);
|
|
||||||
|
|
||||||
/* skip empty lines and comment lines */
|
|
||||||
if (iterate == NULL || (iterate[0] == '#'))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
/* loop over all extensions of mimetype */
|
|
||||||
while ((token = strtok(NULL, delimiters))) {
|
|
||||||
if (strcasecmp(ext, token) == 0) {
|
|
||||||
mimetype = xstrdup(iterate);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
fclose(fd);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fclose(file);
|
||||||
return mimetype;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user