tinywebd

view libtinyweb/src/mime.c @ 12:86f703031228

Attribution headers
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 19 Apr 2015 00:01:01 +0300
parents 0dd50a23f3dd
children
line source
1 /* tinyweb - tiny web server library and daemon
2 * Author: John Tsiombikas <nuclear@member.fsf.org>
3 *
4 * This program is placed in the public domain. Feel free to use it any
5 * way you like. Mentions and retaining this attribution header will be
6 * appreciated, but not required.
7 */
8 #include <stdlib.h>
9 #include <string.h>
10 #include "mime.h"
11 #include "rbtree.h"
13 /* TODO: do proper content detection */
14 struct mime_type {
15 const char *suffix, *type;
16 };
18 static struct mime_type def_types[] = {
19 {"txt", "text/plain"},
20 {"htm", "text/html"},
21 {"html", "text/html"},
22 {"png", "image/png"},
23 {"jpg", "image/jpeg"},
24 {"jpeg", "image/jpeg"},
25 {"gif", "image/gif"},
26 {"bmp", "image/bmp"},
27 {"cgi", 0},
28 {0, 0}
29 };
31 static int init_types(void);
32 static void del_func(struct rbnode *node, void *cls);
34 static struct rbtree *types;
36 static int init_types(void)
37 {
38 int i;
40 if(types) return 0;
42 if(!(types = rb_create(RB_KEY_STRING))) {
43 return -1;
44 }
45 rb_set_delete_func(types, del_func, 0);
47 for(i=0; def_types[i].suffix; i++) {
48 add_mime_type(def_types[i].suffix, def_types[i].type);
49 }
50 return 0;
51 }
53 static void del_func(struct rbnode *node, void *cls)
54 {
55 free(node->key);
56 free(node->data);
57 }
59 int add_mime_type(const char *suffix, const char *type)
60 {
61 init_types();
63 return rb_insert(types, strdup(suffix), type ? strdup(type) : 0);
64 }
66 const char *mime_type(const char *path)
67 {
68 const char *suffix;
70 init_types();
72 if((suffix = strrchr(path, '.'))) {
73 struct rbnode *node = rb_find(types, (void*)(suffix + 1));
74 if(node) {
75 return node->data;
76 }
77 }
78 return "text/plain";
79 }