tinywebd

view src/mime.c @ 7:5ec50ca0d071

separated the server code
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 17 Apr 2015 11:45:08 +0300
parents 4f191dbfac7e
children 0244b08cc9d3
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 ,
22 {0, 0}
23 };
25 static int init_types(void);
26 static void del_func(struct rbnode *node, void *cls);
28 static struct rbtree *types;
30 static int init_types(void)
31 {
32 int i;
34 if(types) return 0;
36 if((types = rb_create(RB_KEY_STRING))) {
37 return -1;
38 }
39 rb_set_delete_func(types, del_func, 0);
41 for(i=0; def_types[i].suffix; i++) {
42 add_mime_type(def_types[i].suffix, def_types[i].type);
43 }
44 return 0;
45 }
47 static void del_func(struct rbnode *node, void *cls)
48 {
49 free(node->key);
50 free(node->data);
51 }
53 int add_mime_type(const char *suffix, const char *type)
54 {
55 init_types();
57 return rb_insert(types, strdup(suffix), strdup(type));
58 }
60 const char *mime_type(const char *path)
61 {
62 const char *suffix;
64 init_types();
66 if((suffix = strrchr(path, '.'))) {
67 struct rbnode *node = rb_find(types, (void*)(suffix + 1));
68 if(node) {
69 return node->data;
70 }
71 }
72 return "text/plain";
73 }