uhttpd: add "Connection: close" headers, mandatory according to HTTP/1.1 spec
[project/luci.git] / contrib / package / uhttpd / src / uhttpd-file.c
1 /*
2  * uhttpd - Tiny non-forking 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 *p, *pd, *ps;
33
34         ps = strrchr(path, '/');
35         pd = strrchr(path, '.');
36
37         /* use either slash or dot as separator, whatever comes last */
38         p = (ps && pd && (ps > pd)) ? ps : pd;
39
40         if( (p != NULL) && (*(++p) != 0) )
41         {
42                 while( m->extn )
43                 {
44                         if( ! strcasecmp(p, m->extn) )
45                                 return m->mime;
46
47                         m++;
48                 }
49         }
50
51         return "application/octet-stream";
52 }
53
54 static const char * uh_file_mktag(struct stat *s)
55 {
56         static char tag[128];
57
58         snprintf(tag, sizeof(tag), "\"%x-%x-%x\"",
59                 (unsigned int) s->st_ino,
60                 (unsigned int) s->st_size,
61                 (unsigned int) s->st_mtime
62         );
63
64         return tag;
65 }
66
67 static time_t uh_file_date2unix(const char *date)
68 {
69         struct tm t;
70
71         memset(&t, 0, sizeof(t));
72
73         if( strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL )
74                 return timegm(&t);
75
76         return 0;
77 }
78
79 static char * uh_file_unix2date(time_t ts)
80 {
81         static char str[128];
82         struct tm *t = gmtime(&ts);
83
84         strftime(str, sizeof(str), "%a, %d %b %Y %H:%M:%S GMT", t);
85
86         return str;
87 }
88
89 static char * uh_file_header_lookup(struct http_request *req, const char *name)
90 {
91         int i;
92
93         foreach_header(i, req->headers)
94         {
95                 if( ! strcasecmp(req->headers[i], name) )
96                         return req->headers[i+1];
97         }
98
99         return NULL;
100 }
101
102 static void uh_file_response_ok_hdrs(struct client *cl, struct http_request *req, struct stat *s)
103 {
104         uh_http_sendf(cl, NULL, "Connection: close\r\n");
105
106         if( s )
107         {
108                 uh_http_sendf(cl, NULL, "ETag: %s\r\n", uh_file_mktag(s));
109                 uh_http_sendf(cl, NULL, "Last-Modified: %s\r\n", uh_file_unix2date(s->st_mtime));
110         }
111
112         uh_http_sendf(cl, NULL, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
113 }
114
115 static void uh_file_response_200(struct client *cl, struct http_request *req, struct stat *s)
116 {
117         uh_http_sendf(cl, NULL, "HTTP/%.1f 200 OK\r\n", req->version);
118         uh_file_response_ok_hdrs(cl, req, s);
119 }
120
121 static void uh_file_response_304(struct client *cl, struct http_request *req, struct stat *s)
122 {
123         uh_http_sendf(cl, NULL, "HTTP/%.1f 304 Not Modified\r\n", req->version);
124         uh_file_response_ok_hdrs(cl, req, s);
125 }
126
127 static void uh_file_response_412(struct client *cl, struct http_request *req)
128 {
129         uh_http_sendf(cl, NULL,
130                 "HTTP/%.1f 412 Precondition Failed\r\n"
131                 "Connection: close\r\n", req->version);
132 }
133
134 static int uh_file_if_match(struct client *cl, struct http_request *req, struct stat *s)
135 {
136         const char *tag = uh_file_mktag(s);
137         char *hdr = uh_file_header_lookup(req, "If-Match");
138         char *p;
139         int i;
140
141         if( hdr )
142         {
143                 p = &hdr[0];
144
145                 for( i = 0; i < strlen(hdr); i++ )
146                 {
147                         if( (hdr[i] == ' ') || (hdr[i] == ',') )
148                         {
149                                 hdr[i++] = 0;
150                                 p = &hdr[i];
151                         }
152                         else if( !strcmp(p, "*") || !strcmp(p, tag) )
153                         {
154                                 return 1;
155                         }
156                 }
157
158                 uh_file_response_412(cl, req);
159                 return 0;
160         }
161
162         return 1;
163 }
164
165 static int uh_file_if_modified_since(struct client *cl, struct http_request *req, struct stat *s)
166 {
167         char *hdr = uh_file_header_lookup(req, "If-Modified-Since");
168
169         if( hdr )
170         {
171                 if( uh_file_date2unix(hdr) < s->st_mtime )
172                 {
173                         return 1;
174                 }
175                 else
176                 {
177                         uh_file_response_304(cl, req, s);
178                         return 0;
179                 }
180         }
181
182         return 1;
183 }
184
185 static int uh_file_if_none_match(struct client *cl, struct http_request *req, struct stat *s)
186 {
187         const char *tag = uh_file_mktag(s);
188         char *hdr = uh_file_header_lookup(req, "If-None-Match");
189         char *p;
190         int i;
191
192         if( hdr )
193         {
194                 p = &hdr[0];
195
196                 for( i = 0; i < strlen(hdr); i++ )
197                 {
198                         if( (hdr[i] == ' ') || (hdr[i] == ',') )
199                         {
200                                 hdr[i++] = 0;
201                                 p = &hdr[i];
202                         }
203                         else if( !strcmp(p, "*") || !strcmp(p, tag) )
204                         {
205                                 if( (req->method == UH_HTTP_MSG_GET) ||
206                                     (req->method == UH_HTTP_MSG_HEAD) )
207                                         uh_file_response_304(cl, req, s);
208                                 else
209                                         uh_file_response_412(cl, req);
210
211                                 return 0;
212                         }
213                 }
214         }
215
216         return 1;
217 }
218
219 static int uh_file_if_range(struct client *cl, struct http_request *req, struct stat *s)
220 {
221         char *hdr = uh_file_header_lookup(req, "If-Range");
222
223         if( hdr )
224         {
225                 uh_file_response_412(cl, req);
226                 return 0;
227         }
228
229         return 1;
230 }
231
232 static int uh_file_if_unmodified_since(struct client *cl, struct http_request *req, struct stat *s)
233 {
234         char *hdr = uh_file_header_lookup(req, "If-Unmodified-Since");
235
236         if( hdr )
237         {
238                 if( uh_file_date2unix(hdr) <= s->st_mtime )
239                 {
240                         uh_file_response_412(cl, req);
241                         return 0;
242                 }
243         }
244
245         return 1;
246 }
247
248
249 static int uh_file_scandir_filter_dir(const struct dirent *e)
250 {
251         return strcmp(e->d_name, ".") ? 1 : 0;
252 }
253
254 static void uh_file_dirlist(struct client *cl, struct http_request *req, struct path_info *pi)
255 {
256         int i, count;
257         char filename[PATH_MAX];
258         char *pathptr;
259         struct dirent **files = NULL;
260         struct stat s;
261
262         uh_http_sendf(cl, req,
263                 "<html><head><title>Index of %s</title></head>"
264                 "<body><h1>Index of %s</h1><hr /><ol>",
265                         pi->name, pi->name
266         );
267
268         if( (count = scandir(pi->phys, &files, uh_file_scandir_filter_dir, alphasort)) > 0 )
269         {
270                 memset(filename, 0, sizeof(filename));
271                 memcpy(filename, pi->phys, sizeof(filename));
272                 pathptr = &filename[strlen(filename)];
273
274                 /* list subdirs */
275                 for( i = 0; i < count; i++ )
276                 {
277                         strncat(filename, files[i]->d_name,
278                                 sizeof(filename) - strlen(files[i]->d_name));
279
280                         if( !stat(filename, &s) && (s.st_mode & S_IFDIR) )
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) && !(s.st_mode & S_IFDIR) )
299                                 uh_http_sendf(cl, req,
300                                         "<li><strong><a href='%s%s'>%s</a></strong><br />"
301                                         "<small>modified: %s<br />%s - %.02f kbyte<br />"
302                                         "<br /></small></li>",
303                                                 pi->name, files[i]->d_name, files[i]->d_name,
304                                                 uh_file_unix2date(s.st_mtime),
305                                                 uh_file_mime_lookup(filename), s.st_size / 1024.0
306                                 );
307
308                         *pathptr = 0;
309                         free(files[i]);
310                 }
311         }
312
313         free(files);
314
315         uh_http_sendf(cl, req, "</ol><hr /></body></html>");
316         uh_http_sendf(cl, req, "");
317 }
318
319
320 void uh_file_request(struct client *cl, struct http_request *req, struct path_info *pi)
321 {
322         int fd, rlen;
323         char buf[UH_LIMIT_MSGHEAD];
324
325         /* we have a file */
326         if( (pi->stat.st_mode & S_IFREG) && ((fd = open(pi->phys, O_RDONLY)) > 0) )
327         {
328                 /* test preconditions */
329                 if(
330                         uh_file_if_modified_since(cl, req, &pi->stat)   &&
331                         uh_file_if_match(cl, req, &pi->stat)            &&
332                         uh_file_if_range(cl, req, &pi->stat)            &&
333                         uh_file_if_unmodified_since(cl, req, &pi->stat) &&
334                         uh_file_if_none_match(cl, req, &pi->stat)
335                 ) {
336                         /* write status */
337                         uh_file_response_200(cl, req, &pi->stat);
338
339                         uh_http_sendf(cl, NULL, "Content-Type: %s\r\n", uh_file_mime_lookup(pi->name));
340                         uh_http_sendf(cl, NULL, "Content-Length: %i\r\n", pi->stat.st_size);
341
342                         /* if request was HTTP 1.1 we'll respond chunked */
343                         if( (req->version > 1.0) && (req->method != UH_HTTP_MSG_HEAD) )
344                                 uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
345
346                         /* close header */
347                         uh_http_send(cl, NULL, "\r\n", -1);
348
349                         /* send body */
350                         if( req->method != UH_HTTP_MSG_HEAD )
351                         {
352                                 /* pump file data */
353                                 while( (rlen = read(fd, buf, sizeof(buf))) > 0 )
354                                 {
355                                         if( uh_http_send(cl, req, buf, rlen) < 0 )
356                                                 break;
357                                 }
358
359                                 /* send trailer in chunked mode */
360                                 uh_http_send(cl, req, "", 0);
361                         }
362                 }
363
364                 /* one of the preconditions failed, terminate opened header and exit */
365                 else
366                 {
367                         uh_http_send(cl, NULL, "\r\n", -1);
368                 }
369
370                 close(fd);
371         }
372
373         /* directory */
374         else if( pi->stat.st_mode & S_IFDIR )
375         {
376                 /* write status */
377                 uh_file_response_200(cl, req, NULL);
378
379                 if( req->version > 1.0 )
380                         uh_http_send(cl, NULL, "Transfer-Encoding: chunked\r\n", -1);
381
382                 uh_http_send(cl, NULL, "Content-Type: text/html\r\n\r\n", -1);
383
384                 /* content */
385                 uh_file_dirlist(cl, req, pi);
386         }
387
388         /* 403 */
389         else
390         {
391                 uh_http_sendhf(cl, 403, "Forbidden",
392                         "Access to this resource is forbidden");
393         }
394 }
395