tinywebd

view 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 source
1 #include <stdlib.h>
2 #include <string.h>
3 #include "mime.h"
4 #include "rbtree.h"
6 /* TODO: do proper content detection */
7 struct mime_type {
8 const char *suffix, *type;
9 };
11 static struct mime_type def_types[] = {
12 {"txt", "text/plain"},
13 {"htm", "text/html"},
14 {"html", "text/html"},
15 {"png", "image/png"},
16 {"jpg", "image/jpeg"},
17 {"jpeg", "image/jpeg"},
18 {"gif", "image/gif"},
19 {"bmp", "image/bmp"},
20 {"cgi", 0},
21 {0, 0}
22 };
24 static int init_types(void);
25 static void del_func(struct rbnode *node, void *cls);
27 static struct rbtree *types;
29 static int init_types(void)
30 {
31 int i;
33 if(types) return 0;
35 if(!(types = rb_create(RB_KEY_STRING))) {
36 return -1;
37 }
38 rb_set_delete_func(types, del_func, 0);
40 for(i=0; def_types[i].suffix; i++) {
41 add_mime_type(def_types[i].suffix, def_types[i].type);
42 }
43 return 0;
44 }
46 static void del_func(struct rbnode *node, void *cls)
47 {
48 free(node->key);
49 free(node->data);
50 }
52 int add_mime_type(const char *suffix, const char *type)
53 {
54 init_types();
56 return rb_insert(types, strdup(suffix), type ? strdup(type) : 0);
57 }
59 const char *mime_type(const char *path)
60 {
61 const char *suffix;
63 init_types();
65 if((suffix = strrchr(path, '.'))) {
66 struct rbnode *node = rb_find(types, (void*)(suffix + 1));
67 if(node) {
68 return node->data;
69 }
70 }
71 return "text/plain";
72 }