[core] http_response_send_file() shared code (#2017)
[lighttpd.git] / src / http-header-glue.c
blob15ea829199ee3c21fdcf560999103bd11750d045
1 #include "first.h"
3 #include "base.h"
4 #include "array.h"
5 #include "buffer.h"
6 #include "log.h"
7 #include "etag.h"
8 #include "http_chunk.h"
9 #include "response.h"
10 #include "stat_cache.h"
12 #include <string.h>
13 #include <errno.h>
15 #include <time.h>
18 * This was 'borrowed' from tcpdump.
21 * This is fun.
23 * In older BSD systems, socket addresses were fixed-length, and
24 * "sizeof (struct sockaddr)" gave the size of the structure.
25 * All addresses fit within a "struct sockaddr".
27 * In newer BSD systems, the socket address is variable-length, and
28 * there's an "sa_len" field giving the length of the structure;
29 * this allows socket addresses to be longer than 2 bytes of family
30 * and 14 bytes of data.
32 * Some commercial UNIXes use the old BSD scheme, some use the RFC 2553
33 * variant of the old BSD scheme (with "struct sockaddr_storage" rather
34 * than "struct sockaddr"), and some use the new BSD scheme.
36 * Some versions of GNU libc use neither scheme, but has an "SA_LEN()"
37 * macro that determines the size based on the address family. Other
38 * versions don't have "SA_LEN()" (as it was in drafts of RFC 2553
39 * but not in the final version). On the latter systems, we explicitly
40 * check the AF_ type to determine the length; we assume that on
41 * all those systems we have "struct sockaddr_storage".
44 #ifdef HAVE_IPV6
45 # ifndef SA_LEN
46 # ifdef HAVE_SOCKADDR_SA_LEN
47 # define SA_LEN(addr) ((addr)->sa_len)
48 # else /* HAVE_SOCKADDR_SA_LEN */
49 # ifdef HAVE_STRUCT_SOCKADDR_STORAGE
50 static size_t get_sa_len(const struct sockaddr *addr) {
51 switch (addr->sa_family) {
53 # ifdef AF_INET
54 case AF_INET:
55 return (sizeof (struct sockaddr_in));
56 # endif
58 # ifdef AF_INET6
59 case AF_INET6:
60 return (sizeof (struct sockaddr_in6));
61 # endif
63 default:
64 return (sizeof (struct sockaddr));
68 # define SA_LEN(addr) (get_sa_len(addr))
69 # else /* HAVE_SOCKADDR_STORAGE */
70 # define SA_LEN(addr) (sizeof (struct sockaddr))
71 # endif /* HAVE_SOCKADDR_STORAGE */
72 # endif /* HAVE_SOCKADDR_SA_LEN */
73 # endif /* SA_LEN */
74 #endif
79 int response_header_insert(server *srv, connection *con, const char *key, size_t keylen, const char *value, size_t vallen) {
80 data_string *ds;
82 UNUSED(srv);
84 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
85 ds = data_response_init();
87 buffer_copy_string_len(ds->key, key, keylen);
88 buffer_copy_string_len(ds->value, value, vallen);
90 array_insert_unique(con->response.headers, (data_unset *)ds);
92 return 0;
95 int response_header_overwrite(server *srv, connection *con, const char *key, size_t keylen, const char *value, size_t vallen) {
96 data_string *ds;
98 UNUSED(srv);
100 /* if there already is a key by this name overwrite the value */
101 if (NULL != (ds = (data_string *)array_get_element(con->response.headers, key))) {
102 buffer_copy_string(ds->value, value);
104 return 0;
107 return response_header_insert(srv, con, key, keylen, value, vallen);
110 int response_header_append(server *srv, connection *con, const char *key, size_t keylen, const char *value, size_t vallen) {
111 data_string *ds;
113 UNUSED(srv);
115 /* if there already is a key by this name append the value */
116 if (NULL != (ds = (data_string *)array_get_element(con->response.headers, key))) {
117 buffer_append_string_len(ds->value, CONST_STR_LEN(", "));
118 buffer_append_string_len(ds->value, value, vallen);
119 return 0;
122 return response_header_insert(srv, con, key, keylen, value, vallen);
125 int http_response_redirect_to_directory(server *srv, connection *con) {
126 buffer *o;
128 o = buffer_init();
130 buffer_copy_buffer(o, con->uri.scheme);
131 buffer_append_string_len(o, CONST_STR_LEN("://"));
132 if (!buffer_is_empty(con->uri.authority)) {
133 buffer_append_string_buffer(o, con->uri.authority);
134 } else {
135 /* get the name of the currently connected socket */
136 struct hostent *he;
137 #ifdef HAVE_IPV6
138 char hbuf[256];
139 #endif
140 sock_addr our_addr;
141 socklen_t our_addr_len;
143 our_addr_len = sizeof(our_addr);
145 if (-1 == getsockname(con->fd, (struct sockaddr *)&our_addr, &our_addr_len)
146 || our_addr_len > sizeof(our_addr)) {
147 con->http_status = 500;
149 log_error_write(srv, __FILE__, __LINE__, "ss",
150 "can't get sockname", strerror(errno));
152 buffer_free(o);
153 return 0;
157 /* Lookup name: secondly try to get hostname for bind address */
158 switch(our_addr.plain.sa_family) {
159 #ifdef HAVE_IPV6
160 case AF_INET6:
161 if (0 != getnameinfo((const struct sockaddr *)(&our_addr.ipv6),
162 SA_LEN((const struct sockaddr *)&our_addr.ipv6),
163 hbuf, sizeof(hbuf), NULL, 0, 0)) {
165 char dst[INET6_ADDRSTRLEN];
167 log_error_write(srv, __FILE__, __LINE__,
168 "SSS", "NOTICE: getnameinfo failed: ",
169 strerror(errno), ", using ip-address instead");
171 buffer_append_string(o,
172 inet_ntop(AF_INET6, (char *)&our_addr.ipv6.sin6_addr,
173 dst, sizeof(dst)));
174 } else {
175 buffer_append_string(o, hbuf);
177 break;
178 #endif
179 case AF_INET:
180 if (NULL == (he = gethostbyaddr((char *)&our_addr.ipv4.sin_addr, sizeof(struct in_addr), AF_INET))) {
181 log_error_write(srv, __FILE__, __LINE__,
182 "SdS", "NOTICE: gethostbyaddr failed: ",
183 h_errno, ", using ip-address instead");
185 buffer_append_string(o, inet_ntoa(our_addr.ipv4.sin_addr));
186 } else {
187 buffer_append_string(o, he->h_name);
189 break;
190 default:
191 log_error_write(srv, __FILE__, __LINE__,
192 "S", "ERROR: unsupported address-type");
194 buffer_free(o);
195 return -1;
199 unsigned short default_port = 80;
200 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
201 default_port = 443;
203 if (default_port != srv->srvconf.port) {
204 buffer_append_string_len(o, CONST_STR_LEN(":"));
205 buffer_append_int(o, srv->srvconf.port);
209 buffer_append_string_encoded(o, CONST_BUF_LEN(con->uri.path), ENCODING_REL_URI);
210 buffer_append_string_len(o, CONST_STR_LEN("/"));
211 if (!buffer_string_is_empty(con->uri.query)) {
212 buffer_append_string_len(o, CONST_STR_LEN("?"));
213 buffer_append_string_buffer(o, con->uri.query);
216 response_header_insert(srv, con, CONST_STR_LEN("Location"), CONST_BUF_LEN(o));
218 con->http_status = 301;
219 con->file_finished = 1;
221 buffer_free(o);
223 return 0;
226 buffer * strftime_cache_get(server *srv, time_t last_mod) {
227 struct tm *tm;
228 size_t i;
230 for (i = 0; i < FILE_CACHE_MAX; i++) {
231 /* found cache-entry */
232 if (srv->mtime_cache[i].mtime == last_mod) return srv->mtime_cache[i].str;
234 /* found empty slot */
235 if (srv->mtime_cache[i].mtime == 0) break;
238 if (i == FILE_CACHE_MAX) {
239 i = 0;
242 srv->mtime_cache[i].mtime = last_mod;
243 buffer_string_prepare_copy(srv->mtime_cache[i].str, 1023);
244 tm = gmtime(&(srv->mtime_cache[i].mtime));
245 buffer_append_strftime(srv->mtime_cache[i].str, "%a, %d %b %Y %H:%M:%S GMT", tm);
247 return srv->mtime_cache[i].str;
251 int http_response_handle_cachable(server *srv, connection *con, buffer *mtime) {
252 int head_or_get =
253 ( HTTP_METHOD_GET == con->request.http_method
254 || HTTP_METHOD_HEAD == con->request.http_method);
255 UNUSED(srv);
258 * 14.26 If-None-Match
259 * [...]
260 * If none of the entity tags match, then the server MAY perform the
261 * requested method as if the If-None-Match header field did not exist,
262 * but MUST also ignore any If-Modified-Since header field(s) in the
263 * request. That is, if no entity tags match, then the server MUST NOT
264 * return a 304 (Not Modified) response.
267 if (con->request.http_if_none_match) {
268 /* use strong etag checking for now: weak comparison must not be used
269 * for ranged requests
271 if (etag_is_equal(con->physical.etag, con->request.http_if_none_match, 0)) {
272 if (head_or_get) {
273 con->http_status = 304;
274 return HANDLER_FINISHED;
275 } else {
276 con->http_status = 412;
277 con->mode = DIRECT;
278 return HANDLER_FINISHED;
281 } else if (con->request.http_if_modified_since && head_or_get) {
282 /* last-modified handling */
283 size_t used_len;
284 char *semicolon;
286 if (NULL == (semicolon = strchr(con->request.http_if_modified_since, ';'))) {
287 used_len = strlen(con->request.http_if_modified_since);
288 } else {
289 used_len = semicolon - con->request.http_if_modified_since;
292 if (0 == strncmp(con->request.http_if_modified_since, mtime->ptr, used_len)) {
293 if ('\0' == mtime->ptr[used_len]) con->http_status = 304;
294 return HANDLER_FINISHED;
295 } else {
296 char buf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")];
297 time_t t_header, t_file;
298 struct tm tm;
300 /* convert to timestamp */
301 if (used_len >= sizeof(buf)) return HANDLER_GO_ON;
303 strncpy(buf, con->request.http_if_modified_since, used_len);
304 buf[used_len] = '\0';
306 if (NULL == strptime(buf, "%a, %d %b %Y %H:%M:%S GMT", &tm)) {
308 * parsing failed, let's get out of here
310 return HANDLER_GO_ON;
312 tm.tm_isdst = 0;
313 t_header = mktime(&tm);
315 strptime(mtime->ptr, "%a, %d %b %Y %H:%M:%S GMT", &tm);
316 tm.tm_isdst = 0;
317 t_file = mktime(&tm);
319 if (t_file > t_header) return HANDLER_GO_ON;
321 con->http_status = 304;
322 return HANDLER_FINISHED;
326 return HANDLER_GO_ON;
330 static int http_response_parse_range(server *srv, connection *con, buffer *path, stat_cache_entry *sce) {
331 int multipart = 0;
332 int error;
333 off_t start, end;
334 const char *s, *minus;
335 char *boundary = "fkj49sn38dcn3";
336 data_string *ds;
337 buffer *content_type = NULL;
339 start = 0;
340 end = sce->st.st_size - 1;
342 con->response.content_length = 0;
344 if (NULL != (ds = (data_string *)array_get_element(con->response.headers, "Content-Type"))) {
345 content_type = ds->value;
348 for (s = con->request.http_range, error = 0;
349 !error && *s && NULL != (minus = strchr(s, '-')); ) {
350 char *err;
351 off_t la, le;
353 if (s == minus) {
354 /* -<stop> */
356 le = strtoll(s, &err, 10);
358 if (le == 0) {
359 /* RFC 2616 - 14.35.1 */
361 con->http_status = 416;
362 error = 1;
363 } else if (*err == '\0') {
364 /* end */
365 s = err;
367 end = sce->st.st_size - 1;
368 start = sce->st.st_size + le;
369 } else if (*err == ',') {
370 multipart = 1;
371 s = err + 1;
373 end = sce->st.st_size - 1;
374 start = sce->st.st_size + le;
375 } else {
376 error = 1;
379 } else if (*(minus+1) == '\0' || *(minus+1) == ',') {
380 /* <start>- */
382 la = strtoll(s, &err, 10);
384 if (err == minus) {
385 /* ok */
387 if (*(err + 1) == '\0') {
388 s = err + 1;
390 end = sce->st.st_size - 1;
391 start = la;
393 } else if (*(err + 1) == ',') {
394 multipart = 1;
395 s = err + 2;
397 end = sce->st.st_size - 1;
398 start = la;
399 } else {
400 error = 1;
402 } else {
403 /* error */
404 error = 1;
406 } else {
407 /* <start>-<stop> */
409 la = strtoll(s, &err, 10);
411 if (err == minus) {
412 le = strtoll(minus+1, &err, 10);
414 /* RFC 2616 - 14.35.1 */
415 if (la > le) {
416 error = 1;
419 if (*err == '\0') {
420 /* ok, end*/
421 s = err;
423 end = le;
424 start = la;
425 } else if (*err == ',') {
426 multipart = 1;
427 s = err + 1;
429 end = le;
430 start = la;
431 } else {
432 /* error */
434 error = 1;
436 } else {
437 /* error */
439 error = 1;
443 if (!error) {
444 if (start < 0) start = 0;
446 /* RFC 2616 - 14.35.1 */
447 if (end > sce->st.st_size - 1) end = sce->st.st_size - 1;
449 if (start > sce->st.st_size - 1) {
450 error = 1;
452 con->http_status = 416;
456 if (!error) {
457 if (multipart) {
458 /* write boundary-header */
459 buffer *b = buffer_init();
461 buffer_copy_string_len(b, CONST_STR_LEN("\r\n--"));
462 buffer_append_string(b, boundary);
464 /* write Content-Range */
465 buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Range: bytes "));
466 buffer_append_int(b, start);
467 buffer_append_string_len(b, CONST_STR_LEN("-"));
468 buffer_append_int(b, end);
469 buffer_append_string_len(b, CONST_STR_LEN("/"));
470 buffer_append_int(b, sce->st.st_size);
472 buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Type: "));
473 buffer_append_string_buffer(b, content_type);
475 /* write END-OF-HEADER */
476 buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));
478 con->response.content_length += buffer_string_length(b);
479 chunkqueue_append_buffer(con->write_queue, b);
480 buffer_free(b);
483 chunkqueue_append_file(con->write_queue, path, start, end - start + 1);
484 con->response.content_length += end - start + 1;
488 /* something went wrong */
489 if (error) return -1;
491 if (multipart) {
492 /* add boundary end */
493 buffer *b = buffer_init();
495 buffer_copy_string_len(b, "\r\n--", 4);
496 buffer_append_string(b, boundary);
497 buffer_append_string_len(b, "--\r\n", 4);
499 con->response.content_length += buffer_string_length(b);
500 chunkqueue_append_buffer(con->write_queue, b);
501 buffer_free(b);
503 /* set header-fields */
505 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("multipart/byteranges; boundary="));
506 buffer_append_string(srv->tmp_buf, boundary);
508 /* overwrite content-type */
509 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(srv->tmp_buf));
510 } else {
511 /* add Content-Range-header */
513 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("bytes "));
514 buffer_append_int(srv->tmp_buf, start);
515 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("-"));
516 buffer_append_int(srv->tmp_buf, end);
517 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("/"));
518 buffer_append_int(srv->tmp_buf, sce->st.st_size);
520 response_header_insert(srv, con, CONST_STR_LEN("Content-Range"), CONST_BUF_LEN(srv->tmp_buf));
523 /* ok, the file is set-up */
524 return 0;
528 void http_response_send_file (server *srv, connection *con, buffer *path) {
529 stat_cache_entry *sce = NULL;
530 buffer *mtime = NULL;
531 data_string *ds;
532 int allow_caching = 1;
534 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, path, &sce)) {
535 con->http_status = (errno == ENOENT) ? 404 : 403;
537 log_error_write(srv, __FILE__, __LINE__, "sbsb",
538 "not a regular file:", con->uri.path,
539 "->", path);
541 return;
544 /* we only handline regular files */
545 #ifdef HAVE_LSTAT
546 if ((sce->is_symlink == 1) && !con->conf.follow_symlink) {
547 con->http_status = 403;
549 if (con->conf.log_request_handling) {
550 log_error_write(srv, __FILE__, __LINE__, "s", "-- access denied due symlink restriction");
551 log_error_write(srv, __FILE__, __LINE__, "sb", "Path :", path);
554 return;
556 #endif
557 if (!S_ISREG(sce->st.st_mode)) {
558 con->http_status = 403;
560 if (con->conf.log_file_not_found) {
561 log_error_write(srv, __FILE__, __LINE__, "sbsb",
562 "not a regular file:", con->uri.path,
563 "->", sce->name);
566 return;
569 /* mod_compress might set several data directly, don't overwrite them */
571 /* set response content-type, if not set already */
573 if (NULL == array_get_element(con->response.headers, "Content-Type")) {
574 if (buffer_string_is_empty(sce->content_type)) {
575 /* we are setting application/octet-stream, but also announce that
576 * this header field might change in the seconds few requests
578 * This should fix the aggressive caching of FF and the script download
579 * seen by the first installations
581 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("application/octet-stream"));
583 allow_caching = 0;
584 } else {
585 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
589 if (con->conf.range_requests) {
590 response_header_overwrite(srv, con, CONST_STR_LEN("Accept-Ranges"), CONST_STR_LEN("bytes"));
593 if (allow_caching) {
594 if (con->etag_flags != 0 && !buffer_string_is_empty(sce->etag)) {
595 if (NULL == array_get_element(con->response.headers, "ETag")) {
596 /* generate e-tag */
597 etag_mutate(con->physical.etag, sce->etag);
599 response_header_overwrite(srv, con, CONST_STR_LEN("ETag"), CONST_BUF_LEN(con->physical.etag));
603 /* prepare header */
604 if (NULL == (ds = (data_string *)array_get_element(con->response.headers, "Last-Modified"))) {
605 mtime = strftime_cache_get(srv, sce->st.st_mtime);
606 response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), CONST_BUF_LEN(mtime));
607 } else {
608 mtime = ds->value;
611 if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, mtime)) {
612 return;
616 if (con->request.http_range && con->conf.range_requests && con->http_status < 300) {
617 int do_range_request = 1;
618 /* check if we have a conditional GET */
620 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "If-Range"))) {
621 /* if the value is the same as our ETag, we do a Range-request,
622 * otherwise a full 200 */
624 if (ds->value->ptr[0] == '"') {
626 * client wants a ETag
628 if (!con->physical.etag) {
629 do_range_request = 0;
630 } else if (!buffer_is_equal(ds->value, con->physical.etag)) {
631 do_range_request = 0;
633 } else if (!mtime) {
635 * we don't have a Last-Modified and can match the If-Range:
637 * sending all
639 do_range_request = 0;
640 } else if (!buffer_is_equal(ds->value, mtime)) {
641 do_range_request = 0;
645 if (do_range_request) {
646 /* content prepared, I'm done */
647 con->file_finished = 1;
649 if (0 == http_response_parse_range(srv, con, path, sce)) {
650 con->http_status = 206;
652 return;
656 /* if we are still here, prepare body */
658 /* we add it here for all requests
659 * the HEAD request will drop it afterwards again
661 if (0 == sce->st.st_size || 0 == http_chunk_append_file(srv, con, path)) {
662 con->http_status = 200;
663 con->file_finished = 1;
664 } else {
665 con->http_status = 403;