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