1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9
10 #include "httpd.h"
11
12 /* ----------------------------------------------------------------- */
13
14 struct MIME {
15 char ext[8];
16 char type[64];
17 };
18
19 static char *mime_default;
20 static struct MIME *mime_types;
21 static int mime_count;
22
23 /* ----------------------------------------------------------------- */
24
25 static void
add_mime(char * ext,char * type)26 add_mime(char *ext, char *type)
27 {
28 if (0 == (mime_count % 64))
29 mime_types = realloc(mime_types,(mime_count+64)*sizeof(struct MIME));
30 strcpy(mime_types[mime_count].ext, ext);
31 strcpy(mime_types[mime_count].type,type);
32 mime_count++;
33 }
34
35 char*
get_mime(char * file)36 get_mime(char *file)
37 {
38 int i;
39 char *ext;
40
41 ext = strrchr(file,'.');
42 if (NULL == ext)
43 return mime_default;
44 ext++;
45 for (i = 0; i < mime_count; i++) {
46 if (0 == strcasecmp(ext,mime_types[i].ext))
47 return mime_types[i].type;
48 }
49 return mime_default;
50 }
51
52 void
init_mime(char * file,char * def)53 init_mime(char *file,char *def)
54 {
55 FILE *fp;
56 char line[128], type[64], ext[8];
57 int len,off;
58
59 mime_default = strdup(def);
60 if (NULL == (fp = fopen(file,"r"))) {
61 fprintf(stderr,"open %s: %s\n",file,strerror(errno));
62 return;
63 }
64 while (NULL != fgets(line,127,fp)) {
65 if (line[0] == '#')
66 continue;
67 if (1 != sscanf(line,"%63s%n",type,&len))
68 continue;
69 off = len;
70 for (;;) {
71 if (1 != sscanf(line+off,"%7s%n",ext,&len))
72 break;
73 off += len;
74 add_mime(ext,type);
75 }
76 }
77 fclose(fp);
78 }
79