taskrambler  0.1.9
Web server and task management solution.
mime_type.c
Go to the documentation of this file.
1 /**
2  * \file
3  *
4  * \author Georg Hopp
5  *
6  * \copyright
7  * Copyright © 2012 Georg Hopp
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 #include <unistd.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <fcntl.h>
27 
28 // for fopen
29 #include <stdio.h>
30 
31 #include "hash.h"
32 
33 #include "class.h"
34 #include "commons.h"
35 
36 Hash mime_types = NULL;
37 
38 void
40 {
41  if (0 == access(CONFIGDIR "/mime.types", O_RDONLY)) {
42  FILE * handle = fopen(CONFIGDIR "/mime.types", "r");
43 
44  if (NULL != handle) {
45  char buffer[512];
46 
47  buffer[511] = '\0';
48  mime_types = new(Hash);
49 
50  while (NULL != fgets(buffer, 511, handle)) {
51  char * tmp;
52  char * key = buffer;
53  char * value;
54  size_t nkey;
55  size_t nvalue;
56 
57  tmp = memchr(key, ' ', 512);
58 
59  if (NULL != tmp) {
60  *tmp = '\0';
61  }
62  nkey = tmp - buffer;
63 
64  value = tmp + 1;
65  for (; *value == ' ' && value < buffer+511; value++);
66 
67  nvalue = strlen(value);
68 
69  if ('\n' == value[nvalue-1]) {
70  nvalue--;
71  value[nvalue] = '\0';
72  }
73 
75  new(HashValue, key, nkey, value, nvalue));
76  }
77 
78  fclose(handle);
79  }
80  }
81 }
82 
83 char *
84 getMimeType(const char * ext, size_t len)
85 {
86  HashValue type;
87 
88  if (NULL == mime_types) {
89  readMimeTypes();
90 
91  if (NULL == mime_types) {
92  return NULL;
93  }
94  }
95 
96  type = hashGet(mime_types, ext, len);
97 
98  if (NULL == type) {
99  return NULL;
100  }
101 
102  return (char *)type->value;
103 }
104 
105 void
107 {
108  delete(mime_types);
109 }
110 
111 // vim: set ts=4 sw=4:
void readMimeTypes(void)
Definition: mime_type.c:39
void * hashGet(Hash, const char *, size_t)
Definition: hash/get.c:51
void * hashAdd(Hash, void *)
Definition: add.c:48
char * getMimeType(const char *ext, size_t len)
Definition: mime_type.c:84
void clearMimeTypes(void)
Definition: mime_type.c:106
Hash mime_types
Definition: mime_type.c:36