tinywebd
diff libtinyweb/src/mime.c @ 10:0dd50a23f3dd
separated all the tinyweb functionality out as a library
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sat, 18 Apr 2015 22:47:57 +0300 |
parents | src/mime.c@0244b08cc9d3 |
children | 86f703031228 |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/libtinyweb/src/mime.c Sat Apr 18 22:47:57 2015 +0300 1.3 @@ -0,0 +1,72 @@ 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 + {0, 0} 1.25 +}; 1.26 + 1.27 +static int init_types(void); 1.28 +static void del_func(struct rbnode *node, void *cls); 1.29 + 1.30 +static struct rbtree *types; 1.31 + 1.32 +static int init_types(void) 1.33 +{ 1.34 + int i; 1.35 + 1.36 + if(types) return 0; 1.37 + 1.38 + if(!(types = rb_create(RB_KEY_STRING))) { 1.39 + return -1; 1.40 + } 1.41 + rb_set_delete_func(types, del_func, 0); 1.42 + 1.43 + for(i=0; def_types[i].suffix; i++) { 1.44 + add_mime_type(def_types[i].suffix, def_types[i].type); 1.45 + } 1.46 + return 0; 1.47 +} 1.48 + 1.49 +static void del_func(struct rbnode *node, void *cls) 1.50 +{ 1.51 + free(node->key); 1.52 + free(node->data); 1.53 +} 1.54 + 1.55 +int add_mime_type(const char *suffix, const char *type) 1.56 +{ 1.57 + init_types(); 1.58 + 1.59 + return rb_insert(types, strdup(suffix), type ? strdup(type) : 0); 1.60 +} 1.61 + 1.62 +const char *mime_type(const char *path) 1.63 +{ 1.64 + const char *suffix; 1.65 + 1.66 + init_types(); 1.67 + 1.68 + if((suffix = strrchr(path, '.'))) { 1.69 + struct rbnode *node = rb_find(types, (void*)(suffix + 1)); 1.70 + if(node) { 1.71 + return node->data; 1.72 + } 1.73 + } 1.74 + return "text/plain"; 1.75 +}