850a14175ca33c0f3b44e10419015e1c9dfef8ea
[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         const 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) &&
279                             (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH)
280                         )
281                                 uh_http_sendf(cl, req,
282                                         "<li><strong><a href='%s%s'>%s</a>/</strong><br />"
283                                         "<small>modified: %s<br />directory - %.02f kbyte"
284                                         "<br /><br /></small></li>",
285                                                 pi->name, files[i]->d_name, files[i]->d_name,
286                                                 uh_file_unix2date(s.st_mtime), s.st_size / 1024.0
287                                 );
288
289                         *pathptr = 0;
290                 }
291
292                 /* list files */
293                 for( i = 0; i < count; i++ )
294                 {
295                         strncat(filename, files[i]->d_name,
296                                 sizeof(filename) - strlen(files[i]->d_name));
297
298                         if( !stat(filename, &s) &&
299                             !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH)
300                         )
301                                 uh_http_sendf(cl, req,
302                                         "<li><strong><a href='%s%s'>%s</a></strong><br />"
303                                         "<small>modified: %s<br />%s - %.02f kbyte<br />"
304                                         "<br /></small></li>",
305                                                 pi->name, files[i]->d_name, files[i]->d_name,
306                                                 uh_file_unix2date(s.st_mtime),
307                                                 uh_file_mime_lookup(filename), s.st_size / 1024.0
308                                 );
309
310                         *pathptr = 0;
311                         free(files[i]);
312                 }
313         }
314
315         free(files);
316
317         uh_http_sendf(cl, req, "</ol><hr /></body></html>");
318         uh_http_sendf(cl, req, "");
319 }
320
321
322 void uh_file_request(struct client *cl, struct http_request *req, struct path_info *pi)
323 {
324         int fd, rlen;
325         char buf[UH_LIMIT_MSGHEAD];
326
327         /* we have a file */
328         if( (pi->stat.st_mode & S_IFREG) && ((fd = open(pi->phys, O_RDONLY)) > 0) )
329         {
330                 /* test preconditions */
331                 if(
332                         uh_file_if_modified_since(cl, req, &pi->stat)   &&
333                         uh_file_if_match(cl, req, &pi->stat)            &&
334                         uh_file_if_range(cl, req, &pi->stat)            &&
335                         uh_file_if_unmodified_since(cl, req, &pi->stat) &&
336                         uh_file_if_none_match(cl, req, &pi->stat)
337                 ) {
338                         /* write status */
339                         uh_file_response_200(cl, req, &pi->stat);
340
341                         uh_http_sendf(cl, NULL, "Content-Type: %s\r\n", uh_file_mime_lookup(pi->name));
342                         uh_http_sendf(cl, NULL, "Content-Length: %i\r\n", pi->stat.st_size);
343
344                         /* if request was HTTP 1.1 we'll respond chunked */
345                         if( (req->version > 1.0) && (req->method != UH_HTTP_MSG_HEAD) )
346                                 uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
347
348                         /* close header */
349                         uh_http_send(cl, NULL, "\r\n", -1);
350
351                         /* send body */
352                         if( req->method != UH_HTTP_MSG_HEAD )
353                         {
354                                 /* pump file data */
355                                 while( (rlen = read(fd, buf, sizeof(buf))) > 0 )
356                                 {
357                                         if( uh_http_send(cl, req, buf, rlen) < 0 )
358                                                 break;
359                                 }
360
361                                 /* send trailer in chunked mode */
362                                 uh_http_send(cl, req, "", 0);
363                         }
364                 }
365
366                 /* one of the preconditions failed, terminate opened header and exit */
367                 else
368                 {
369                         uh_http_send(cl, NULL, "\r\n", -1);
370                 }
371
372                 close(fd);
373         }
374
375         /* directory */
376         else if( (pi->stat.st_mode & S_IFDIR) && !cl->server->conf->no_dirlists )
377         {
378                 /* write status */
379                 uh_file_response_200(cl, req, NULL);
380
381                 if( req->version > 1.0 )
382                         uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
383
384                 uh_http_send(cl, NULL, "Content-Type: text/html\r\n\r\n", -1);
385
386                 /* content */
387                 uh_file_dirlist(cl, req, pi);
388         }
389
390         /* 403 */
391         else
392         {
393                 uh_http_sendhf(cl, 403, "Forbidden",
394                         "Access to this resource is forbidden");
395         }
396 }
397