[package] uhttpd:
[openwrt.git] / package / uhttpd / src / uhttpd-file.c
1 /*
2  * uhttpd - Tiny single-threaded httpd - Static file handler
3  *
4  *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */
18
19 #define _XOPEN_SOURCE 500       /* strptime() */
20 #define _BSD_SOURCE                     /* scandir(), timegm() */
21
22 #include "uhttpd.h"
23 #include "uhttpd-utils.h"
24 #include "uhttpd-file.h"
25
26 #include "uhttpd-mimetypes.h"
27
28
29 static const char * uh_file_mime_lookup(const char *path)
30 {
31         struct mimetype *m = &uh_mime_types[0];
32         char *e;
33
34         while( m->extn )
35         {
36                 e = &path[strlen(path)-1];
37
38                 while( e >= path )
39                 {
40                         if( (*e == '.') && !strcasecmp(&e[1], m->extn) )
41                                 return m->mime;
42
43                         e--;
44                 }
45
46                 m++;
47         }
48
49         return "application/octet-stream";
50 }
51
52 static const char * uh_file_mktag(struct stat *s)
53 {
54         static char tag[128];
55
56         snprintf(tag, sizeof(tag), "\"%x-%x-%x\"",
57                 (unsigned int) s->st_ino,
58                 (unsigned int) s->st_size,
59                 (unsigned int) s->st_mtime
60         );
61
62         return tag;
63 }
64
65 static time_t uh_file_date2unix(const char *date)
66 {
67         struct tm t;
68
69         memset(&t, 0, sizeof(t));
70
71         if( strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL )
72                 return timegm(&t);
73
74         return 0;
75 }
76
77 static char * uh_file_unix2date(time_t ts)
78 {
79         static char str[128];
80         struct tm *t = gmtime(&ts);
81
82         strftime(str, sizeof(str), "%a, %d %b %Y %H:%M:%S GMT", t);
83
84         return str;
85 }
86
87 static char * uh_file_header_lookup(struct http_request *req, const char *name)
88 {
89         int i;
90
91         foreach_header(i, req->headers)
92         {
93                 if( ! strcasecmp(req->headers[i], name) )
94                         return req->headers[i+1];
95         }
96
97         return NULL;
98 }
99
100 static void uh_file_response_ok_hdrs(struct client *cl, struct http_request *req, struct stat *s)
101 {
102         uh_http_sendf(cl, NULL, "Connection: close\r\n");
103
104         if( s )
105         {
106                 uh_http_sendf(cl, NULL, "ETag: %s\r\n", uh_file_mktag(s));
107                 uh_http_sendf(cl, NULL, "Last-Modified: %s\r\n", uh_file_unix2date(s->st_mtime));
108         }
109
110         uh_http_sendf(cl, NULL, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
111 }
112
113 static void uh_file_response_200(struct client *cl, struct http_request *req, struct stat *s)
114 {
115         uh_http_sendf(cl, NULL, "HTTP/%.1f 200 OK\r\n", req->version);
116         uh_file_response_ok_hdrs(cl, req, s);
117 }
118
119 static void uh_file_response_304(struct client *cl, struct http_request *req, struct stat *s)
120 {
121         uh_http_sendf(cl, NULL, "HTTP/%.1f 304 Not Modified\r\n", req->version);
122         uh_file_response_ok_hdrs(cl, req, s);
123 }
124
125 static void uh_file_response_412(struct client *cl, struct http_request *req)
126 {
127         uh_http_sendf(cl, NULL,
128                 "HTTP/%.1f 412 Precondition Failed\r\n"
129                 "Connection: close\r\n", req->version);
130 }
131
132 static int uh_file_if_match(struct client *cl, struct http_request *req, struct stat *s)
133 {
134         const char *tag = uh_file_mktag(s);
135         char *hdr = uh_file_header_lookup(req, "If-Match");
136         char *p;
137         int i;
138
139         if( hdr )
140         {
141                 p = &hdr[0];
142
143                 for( i = 0; i < strlen(hdr); i++ )
144                 {
145                         if( (hdr[i] == ' ') || (hdr[i] == ',') )
146                         {
147                                 hdr[i++] = 0;
148                                 p = &hdr[i];
149                         }
150                         else if( !strcmp(p, "*") || !strcmp(p, tag) )
151                         {
152                                 return 1;
153                         }
154                 }
155
156                 uh_file_response_412(cl, req);
157                 return 0;
158         }
159
160         return 1;
161 }
162
163 static int uh_file_if_modified_since(struct client *cl, struct http_request *req, struct stat *s)
164 {
165         char *hdr = uh_file_header_lookup(req, "If-Modified-Since");
166
167         if( hdr )
168         {
169                 if( uh_file_date2unix(hdr) < s->st_mtime )
170                 {
171                         return 1;
172                 }
173                 else
174                 {
175                         uh_file_response_304(cl, req, s);
176                         return 0;
177                 }
178         }
179
180         return 1;
181 }
182
183 static int uh_file_if_none_match(struct client *cl, struct http_request *req, struct stat *s)
184 {
185         const char *tag = uh_file_mktag(s);
186         char *hdr = uh_file_header_lookup(req, "If-None-Match");
187         char *p;
188         int i;
189
190         if( hdr )
191         {
192                 p = &hdr[0];
193
194                 for( i = 0; i < strlen(hdr); i++ )
195                 {
196                         if( (hdr[i] == ' ') || (hdr[i] == ',') )
197                         {
198                                 hdr[i++] = 0;
199                                 p = &hdr[i];
200                         }
201                         else if( !strcmp(p, "*") || !strcmp(p, tag) )
202                         {
203                                 if( (req->method == UH_HTTP_MSG_GET) ||
204                                     (req->method == UH_HTTP_MSG_HEAD) )
205                                         uh_file_response_304(cl, req, s);
206                                 else
207                                         uh_file_response_412(cl, req);
208
209                                 return 0;
210                         }
211                 }
212         }
213
214         return 1;
215 }
216
217 static int uh_file_if_range(struct client *cl, struct http_request *req, struct stat *s)
218 {
219         char *hdr = uh_file_header_lookup(req, "If-Range");
220
221         if( hdr )
222         {
223                 uh_file_response_412(cl, req);
224                 return 0;
225         }
226
227         return 1;
228 }
229
230 static int uh_file_if_unmodified_since(struct client *cl, struct http_request *req, struct stat *s)
231 {
232         char *hdr = uh_file_header_lookup(req, "If-Unmodified-Since");
233
234         if( hdr )
235         {
236                 if( uh_file_date2unix(hdr) <= s->st_mtime )
237                 {
238                         uh_file_response_412(cl, req);
239                         return 0;
240                 }
241         }
242
243         return 1;
244 }
245
246
247 static int uh_file_scandir_filter_dir(const struct dirent *e)
248 {
249         return strcmp(e->d_name, ".") ? 1 : 0;
250 }
251
252 static void uh_file_dirlist(struct client *cl, struct http_request *req, struct path_info *pi)
253 {
254         int i, count;
255         char filename[PATH_MAX];
256         char *pathptr;
257         struct dirent **files = NULL;
258         struct stat s;
259
260         uh_http_sendf(cl, req,
261                 "<html><head><title>Index of %s</title></head>"
262                 "<body><h1>Index of %s</h1><hr /><ol>",
263                         pi->name, pi->name
264         );
265
266         if( (count = scandir(pi->phys, &files, uh_file_scandir_filter_dir, alphasort)) > 0 )
267         {
268                 memset(filename, 0, sizeof(filename));
269                 memcpy(filename, pi->phys, sizeof(filename));
270                 pathptr = &filename[strlen(filename)];
271
272                 /* list subdirs */
273                 for( i = 0; i < count; i++ )
274                 {
275                         strncat(filename, files[i]->d_name,
276                                 sizeof(filename) - strlen(files[i]->d_name));
277
278                         if( !stat(filename, &s) && (s.st_mode & S_IFDIR) )
279                                 uh_http_sendf(cl, req,
280                                         "<li><strong><a href='%s%s'>%s</a>/</strong><br />"
281                                         "<small>modified: %s<br />directory - %.02f kbyte"
282                                         "<br /><br /></small></li>",
283                                                 pi->name, files[i]->d_name, files[i]->d_name,
284                                                 uh_file_unix2date(s.st_mtime), s.st_size / 1024.0
285                                 );
286
287                         *pathptr = 0;
288                 }
289
290                 /* list files */
291                 for( i = 0; i < count; i++ )
292                 {
293                         strncat(filename, files[i]->d_name,
294                                 sizeof(filename) - strlen(files[i]->d_name));
295
296                         if( !stat(filename, &s) && !(s.st_mode & S_IFDIR) )
297                                 uh_http_sendf(cl, req,
298                                         "<li><strong><a href='%s%s'>%s</a></strong><br />"
299                                         "<small>modified: %s<br />%s - %.02f kbyte<br />"
300                                         "<br /></small></li>",
301                                                 pi->name, files[i]->d_name, files[i]->d_name,
302                                                 uh_file_unix2date(s.st_mtime),
303                                                 uh_file_mime_lookup(filename), s.st_size / 1024.0
304                                 );
305
306                         *pathptr = 0;
307                         free(files[i]);
308                 }
309         }
310
311         free(files);
312
313         uh_http_sendf(cl, req, "</ol><hr /></body></html>");
314         uh_http_sendf(cl, req, "");
315 }
316
317
318 void uh_file_request(struct client *cl, struct http_request *req, struct path_info *pi)
319 {
320         int fd, rlen;
321         char buf[UH_LIMIT_MSGHEAD];
322
323         /* we have a file */
324         if( (pi->stat.st_mode & S_IFREG) && ((fd = open(pi->phys, O_RDONLY)) > 0) )
325         {
326                 /* test preconditions */
327                 if(
328                         uh_file_if_modified_since(cl, req, &pi->stat)   &&
329                         uh_file_if_match(cl, req, &pi->stat)            &&
330                         uh_file_if_range(cl, req, &pi->stat)            &&
331                         uh_file_if_unmodified_since(cl, req, &pi->stat) &&
332                         uh_file_if_none_match(cl, req, &pi->stat)
333                 ) {
334                         /* write status */
335                         uh_file_response_200(cl, req, &pi->stat);
336
337                         uh_http_sendf(cl, NULL, "Content-Type: %s\r\n", uh_file_mime_lookup(pi->name));
338                         uh_http_sendf(cl, NULL, "Content-Length: %i\r\n", pi->stat.st_size);
339
340                         /* if request was HTTP 1.1 we'll respond chunked */
341                         if( (req->version > 1.0) && (req->method != UH_HTTP_MSG_HEAD) )
342                                 uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
343
344                         /* close header */
345                         uh_http_send(cl, NULL, "\r\n", -1);
346
347                         /* send body */
348                         if( req->method != UH_HTTP_MSG_HEAD )
349                         {
350                                 /* pump file data */
351                                 while( (rlen = read(fd, buf, sizeof(buf))) > 0 )
352                                 {
353                                         if( uh_http_send(cl, req, buf, rlen) < 0 )
354                                                 break;
355                                 }
356
357                                 /* send trailer in chunked mode */
358                                 uh_http_send(cl, req, "", 0);
359                         }
360                 }
361
362                 /* one of the preconditions failed, terminate opened header and exit */
363                 else
364                 {
365                         uh_http_send(cl, NULL, "\r\n", -1);
366                 }
367
368                 close(fd);
369         }
370
371         /* directory */
372         else if( pi->stat.st_mode & S_IFDIR )
373         {
374                 /* write status */
375                 uh_file_response_200(cl, req, NULL);
376
377                 if( req->version > 1.0 )
378                         uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
379
380                 uh_http_send(cl, NULL, "Content-Type: text/html\r\n\r\n", -1);
381
382                 /* content */
383                 uh_file_dirlist(cl, req, pi);
384         }
385
386         /* 403 */
387         else
388         {
389                 uh_http_sendhf(cl, 403, "Forbidden",
390                         "Access to this resource is forbidden");
391         }
392 }
393