tinywebd

diff src/mime.c @ 6:4f191dbfac7e

commited a bunch of missing files from previous commits
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 17 Apr 2015 01:57:25 +0300
parents
children 5ec50ca0d071
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/mime.c	Fri Apr 17 01:57:25 2015 +0300
     1.3 @@ -0,0 +1,73 @@
     1.4 +#include <stdlib.h>
     1.5 +#include <string.h>
     1.6 +#include "mime.h"
     1.7 +#include "rbtree.h"
     1.8 +
     1.9 +/* TODO: do proper content detection */
    1.10 +struct mime_type {
    1.11 +	const char *suffix, *type;
    1.12 +};
    1.13 +
    1.14 +static struct mime_type def_types[] = {
    1.15 +	{"txt", "text/plain"},
    1.16 +	{"htm", "text/html"},
    1.17 +	{"html", "text/html"},
    1.18 +	{"png", "image/png"},
    1.19 +	{"jpg", "image/jpeg"},
    1.20 +	{"jpeg", "image/jpeg"},
    1.21 +	{"gif", "image/gif"},
    1.22 +	{"bmp", "image/bmp"},
    1.23 +	{"cgi", 0}
    1.24 +,
    1.25 +	{0, 0}
    1.26 +};
    1.27 +
    1.28 +static int init_types(void);
    1.29 +static void del_func(struct rbnode *node, void *cls);
    1.30 +
    1.31 +static struct rbtree *types;
    1.32 +
    1.33 +static int init_types(void)
    1.34 +{
    1.35 +	int i;
    1.36 +
    1.37 +	if(types) return 0;
    1.38 +
    1.39 +	if(rb_init(types, RB_KEY_STRING) == -1) {
    1.40 +		return -1;
    1.41 +	}
    1.42 +	rb_set_delete_func(types, del_func, 0);
    1.43 +
    1.44 +	for(i=0; def_types[i].suffix; i++) {
    1.45 +		add_mime_type(def_types[i].suffix, def_types[i].type);
    1.46 +	}
    1.47 +	return 0;
    1.48 +}
    1.49 +
    1.50 +static void del_func(struct rbnode *node, void *cls)
    1.51 +{
    1.52 +	free(node->key);
    1.53 +	free(node->data);
    1.54 +}
    1.55 +
    1.56 +int add_mime_type(const char *suffix, const char *type)
    1.57 +{
    1.58 +	init_types();
    1.59 +
    1.60 +	return rb_insert(types, strdup(suffix), strdup(type));
    1.61 +}
    1.62 +
    1.63 +const char *mime_type(const char *path)
    1.64 +{
    1.65 +	const char *suffix;
    1.66 +
    1.67 +	init_types();
    1.68 +
    1.69 +	if((suffix = strrchr(path, '.'))) {
    1.70 +		struct rbnode *node = rb_find(types, (void*)(suffix + 1));
    1.71 +		if(node) {
    1.72 +			return node->data;
    1.73 +		}
    1.74 +	}
    1.75 +	return "text/plain";
    1.76 +}