8 #include "http_chunk.h"
10 #include "stat_cache.h"
18 * This was 'borrowed' from tcpdump.
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".
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
) {
55 return (sizeof (struct sockaddr_in
));
60 return (sizeof (struct sockaddr_in6
));
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 */
79 int response_header_insert(server
*srv
, connection
*con
, const char *key
, size_t keylen
, const char *value
, size_t vallen
) {
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
);
95 int response_header_overwrite(server
*srv
, connection
*con
, const char *key
, size_t keylen
, const char *value
, size_t vallen
) {
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
);
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
) {
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
);
122 return response_header_insert(srv
, con
, key
, keylen
, value
, vallen
);
125 int http_response_redirect_to_directory(server
*srv
, connection
*con
) {
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
);
135 /* get the name of the currently connected socket */
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
));
157 /* Lookup name: secondly try to get hostname for bind address */
158 switch(our_addr
.plain
.sa_family
) {
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
,
175 buffer_append_string(o
, hbuf
);
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
));
187 buffer_append_string(o
, he
->h_name
);
191 log_error_write(srv
, __FILE__
, __LINE__
,
192 "S", "ERROR: unsupported address-type");
199 unsigned short default_port
= 80;
200 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
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;
226 buffer
* strftime_cache_get(server
*srv
, time_t last_mod
) {
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
) {
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
) {
253 ( HTTP_METHOD_GET
== con
->request
.http_method
254 || HTTP_METHOD_HEAD
== con
->request
.http_method
);
258 * 14.26 If-None-Match
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)) {
273 con
->http_status
= 304;
274 return HANDLER_FINISHED
;
276 con
->http_status
= 412;
278 return HANDLER_FINISHED
;
281 } else if (con
->request
.http_if_modified_since
&& head_or_get
) {
282 /* last-modified handling */
286 if (NULL
== (semicolon
= strchr(con
->request
.http_if_modified_since
, ';'))) {
287 used_len
= strlen(con
->request
.http_if_modified_since
);
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
;
296 char buf
[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")];
297 time_t t_header
, t_file
;
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
;
313 t_header
= mktime(&tm
);
315 strptime(mtime
->ptr
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
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
) {
334 const char *s
, *minus
;
335 char *boundary
= "fkj49sn38dcn3";
337 buffer
*content_type
= NULL
;
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
, '-')); ) {
356 le
= strtoll(s
, &err
, 10);
359 /* RFC 2616 - 14.35.1 */
361 con
->http_status
= 416;
363 } else if (*err
== '\0') {
367 end
= sce
->st
.st_size
- 1;
368 start
= sce
->st
.st_size
+ le
;
369 } else if (*err
== ',') {
373 end
= sce
->st
.st_size
- 1;
374 start
= sce
->st
.st_size
+ le
;
379 } else if (*(minus
+1) == '\0' || *(minus
+1) == ',') {
382 la
= strtoll(s
, &err
, 10);
387 if (*(err
+ 1) == '\0') {
390 end
= sce
->st
.st_size
- 1;
393 } else if (*(err
+ 1) == ',') {
397 end
= sce
->st
.st_size
- 1;
409 la
= strtoll(s
, &err
, 10);
412 le
= strtoll(minus
+1, &err
, 10);
414 /* RFC 2616 - 14.35.1 */
425 } else if (*err
== ',') {
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) {
452 con
->http_status
= 416;
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
);
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;
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
);
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
));
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 */
528 void http_response_send_file (server
*srv
, connection
*con
, buffer
*path
) {
529 stat_cache_entry
*sce
= NULL
;
530 buffer
*mtime
= NULL
;
532 int allow_caching
= (0 == con
->http_status
|| 200 == con
->http_status
);
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
,
544 /* we only handline regular files */
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
);
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
,
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"));
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"));
594 if (con
->etag_flags
!= 0 && !buffer_string_is_empty(sce
->etag
)) {
595 if (NULL
== array_get_element(con
->response
.headers
, "ETag")) {
597 etag_mutate(con
->physical
.etag
, sce
->etag
);
599 response_header_overwrite(srv
, con
, CONST_STR_LEN("ETag"), CONST_BUF_LEN(con
->physical
.etag
));
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
));
611 if (HANDLER_FINISHED
== http_response_handle_cachable(srv
, con
, mtime
)) {
616 if (con
->request
.http_range
&& con
->conf
.range_requests
617 && (200 == con
->http_status
|| 0 == con
->http_status
)
618 && NULL
== array_get_element(con
->response
.headers
, "Content-Encoding")) {
619 int do_range_request
= 1;
620 /* check if we have a conditional GET */
622 if (NULL
!= (ds
= (data_string
*)array_get_element(con
->request
.headers
, "If-Range"))) {
623 /* if the value is the same as our ETag, we do a Range-request,
624 * otherwise a full 200 */
626 if (ds
->value
->ptr
[0] == '"') {
628 * client wants a ETag
630 if (!con
->physical
.etag
) {
631 do_range_request
= 0;
632 } else if (!buffer_is_equal(ds
->value
, con
->physical
.etag
)) {
633 do_range_request
= 0;
637 * we don't have a Last-Modified and can match the If-Range:
641 do_range_request
= 0;
642 } else if (!buffer_is_equal(ds
->value
, mtime
)) {
643 do_range_request
= 0;
647 if (do_range_request
) {
648 /* content prepared, I'm done */
649 con
->file_finished
= 1;
651 if (0 == http_response_parse_range(srv
, con
, path
, sce
)) {
652 con
->http_status
= 206;
658 /* if we are still here, prepare body */
660 /* we add it here for all requests
661 * the HEAD request will drop it afterwards again
663 if (0 == sce
->st
.st_size
|| 0 == http_chunk_append_file(srv
, con
, path
)) {
664 con
->http_status
= 200;
665 con
->file_finished
= 1;
667 con
->http_status
= 403;
671 void http_response_xsendfile (server
*srv
, connection
*con
, buffer
*path
, const array
*xdocroot
) {
672 const int status
= con
->http_status
;
675 /* reset Content-Length, if set by backend
676 * Content-Length might later be set to size of X-Sendfile static file,
677 * determined by open(), fstat() to reduces race conditions if the file
678 * is modified between stat() (stat_cache_get_entry()) and open(). */
679 if (con
->parsed_response
& HTTP_CONTENT_LENGTH
) {
680 data_string
*ds
= (data_string
*) array_get_element(con
->response
.headers
, "Content-Length");
681 if (ds
) buffer_reset(ds
->value
);
682 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
683 con
->response
.content_length
= -1;
686 buffer_urldecode_path(path
);
687 buffer_path_simplify(path
, path
);
688 if (con
->conf
.force_lowercase_filenames
) {
689 buffer_to_lower(path
);
692 /* check that path is under xdocroot(s)
693 * - xdocroot should have trailing slash appended at config time
694 * - con->conf.force_lowercase_filenames is not a server-wide setting,
695 * and so can not be definitively applied to xdocroot at config time*/
696 if (xdocroot
->used
) {
697 size_t i
, xlen
= buffer_string_length(path
);
698 for (i
= 0; i
< xdocroot
->used
; ++i
) {
699 data_string
*ds
= (data_string
*)xdocroot
->data
[i
];
700 size_t dlen
= buffer_string_length(ds
->value
);
702 && (!con
->conf
.force_lowercase_filenames
703 ? 0 == memcmp(path
->ptr
, ds
->value
->ptr
, dlen
)
704 : 0 == strncasecmp(path
->ptr
, ds
->value
->ptr
, dlen
))) {
708 if (i
== xdocroot
->used
) {
709 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
710 "X-Sendfile (", path
,
711 ") not under configured x-sendfile-docroot(s)");
712 con
->http_status
= 403;
717 if (valid
) http_response_send_file(srv
, con
, path
);
719 if (con
->http_status
>= 400 && status
< 300) {
721 } else if (0 != status
&& 200 != status
) {
722 con
->http_status
= status
;