]> granicus.if.org Git - apache/blob - server/core_filters.c
Replace ap_create_core_ctx()/ap_core_ctx_get_bb() with a hook
[apache] / server / core_filters.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * @file  core_filters.c
19  * @brief Core input/output network filters.
20  */
21
22 #include "apr.h"
23 #include "apr_strings.h"
24 #include "apr_lib.h"
25 #include "apr_fnmatch.h"
26 #include "apr_hash.h"
27 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
28
29 #define APR_WANT_IOVEC
30 #define APR_WANT_STRFUNC
31 #define APR_WANT_MEMFUNC
32 #include "apr_want.h"
33
34 #include "ap_config.h"
35 #include "httpd.h"
36 #include "http_config.h"
37 #include "http_core.h"
38 #include "http_protocol.h" /* For index_of_response().  Grump. */
39 #include "http_request.h"
40 #include "http_vhost.h"
41 #include "http_main.h"     /* For the default_handler below... */
42 #include "http_log.h"
43 #include "util_md5.h"
44 #include "http_connection.h"
45 #include "apr_buckets.h"
46 #include "util_filter.h"
47 #include "util_ebcdic.h"
48 #include "mpm_common.h"
49 #include "scoreboard.h"
50 #include "mod_core.h"
51 #include "mod_proxy.h"
52 #include "ap_listen.h"
53
54 #include "mod_so.h" /* for ap_find_loaded_module_symbol */
55
56 #define AP_MIN_SENDFILE_BYTES           (256)
57
58 /**
59  * Remove all zero length buckets from the brigade.
60  */
61 #define BRIGADE_NORMALIZE(b) \
62 do { \
63     apr_bucket *e = APR_BRIGADE_FIRST(b); \
64     do {  \
65         if (e->length == 0 && !APR_BUCKET_IS_METADATA(e)) { \
66             apr_bucket *d; \
67             d = APR_BUCKET_NEXT(e); \
68             apr_bucket_delete(e); \
69             e = d; \
70         } \
71         else { \
72             e = APR_BUCKET_NEXT(e); \
73         } \
74     } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
75 } while (0)
76
77 /* we know core's module_index is 0 */
78 #undef APLOG_MODULE_INDEX
79 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
80
81 struct core_output_filter_ctx {
82     apr_bucket_brigade *buffered_bb;
83     apr_bucket_brigade *tmp_flush_bb;
84     apr_pool_t *deferred_write_pool;
85     apr_size_t bytes_written;
86 };
87
88 struct core_filter_ctx {
89     apr_bucket_brigade *b;
90     apr_bucket_brigade *tmpbb;
91 };
92
93
94 apr_status_t ap_core_input_filter(ap_filter_t *f, apr_bucket_brigade *b,
95                                   ap_input_mode_t mode, apr_read_type_e block,
96                                   apr_off_t readbytes)
97 {
98     apr_status_t rv;
99     core_net_rec *net = f->ctx;
100     core_ctx_t *ctx = net->in_ctx;
101     const char *str;
102     apr_size_t len;
103
104     if (mode == AP_MODE_INIT) {
105         /*
106          * this mode is for filters that might need to 'initialize'
107          * a connection before reading request data from a client.
108          * NNTP over SSL for example needs to handshake before the
109          * server sends the welcome message.
110          * such filters would have changed the mode before this point
111          * is reached.  however, protocol modules such as NNTP should
112          * not need to know anything about SSL.  given the example, if
113          * SSL is not in the filter chain, AP_MODE_INIT is a noop.
114          */
115         return APR_SUCCESS;
116     }
117
118     if (!ctx)
119     {
120         net->in_ctx = ctx = apr_palloc(f->c->pool, sizeof(*ctx));
121         ctx->b = apr_brigade_create(f->c->pool, f->c->bucket_alloc);
122         ctx->tmpbb = apr_brigade_create(f->c->pool, f->c->bucket_alloc);
123         /* seed the brigade with the client socket. */
124         rv = ap_run_insert_network_bucket(f->c, ctx->b, net->client_socket);
125         if (rv != APR_SUCCESS)
126             return rv;
127     }
128     else if (APR_BRIGADE_EMPTY(ctx->b)) {
129         return APR_EOF;
130     }
131
132     /* ### This is bad. */
133     BRIGADE_NORMALIZE(ctx->b);
134
135     /* check for empty brigade again *AFTER* BRIGADE_NORMALIZE()
136      * If we have lost our socket bucket (see above), we are EOF.
137      *
138      * Ideally, this should be returning SUCCESS with EOS bucket, but
139      * some higher-up APIs (spec. read_request_line via ap_rgetline)
140      * want an error code. */
141     if (APR_BRIGADE_EMPTY(ctx->b)) {
142         return APR_EOF;
143     }
144
145     if (mode == AP_MODE_GETLINE) {
146         /* we are reading a single LF line, e.g. the HTTP headers */
147         rv = apr_brigade_split_line(b, ctx->b, block, HUGE_STRING_LEN);
148         /* We should treat EAGAIN here the same as we do for EOF (brigade is
149          * empty).  We do this by returning whatever we have read.  This may
150          * or may not be bogus, but is consistent (for now) with EOF logic.
151          */
152         if (APR_STATUS_IS_EAGAIN(rv) && block == APR_NONBLOCK_READ) {
153             rv = APR_SUCCESS;
154         }
155         return rv;
156     }
157
158     /* ### AP_MODE_PEEK is a horrific name for this mode because we also
159      * eat any CRLFs that we see.  That's not the obvious intention of
160      * this mode.  Determine whether anyone actually uses this or not. */
161     if (mode == AP_MODE_EATCRLF) {
162         apr_bucket *e;
163         const char *c;
164
165         /* The purpose of this loop is to ignore any CRLF (or LF) at the end
166          * of a request.  Many browsers send extra lines at the end of POST
167          * requests.  We use the PEEK method to determine if there is more
168          * data on the socket, so that we know if we should delay sending the
169          * end of one request until we have served the second request in a
170          * pipelined situation.  We don't want to actually delay sending a
171          * response if the server finds a CRLF (or LF), becuause that doesn't
172          * mean that there is another request, just a blank line.
173          */
174         while (1) {
175             if (APR_BRIGADE_EMPTY(ctx->b))
176                 return APR_EOF;
177
178             e = APR_BRIGADE_FIRST(ctx->b);
179
180             rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
181
182             if (rv != APR_SUCCESS)
183                 return rv;
184
185             c = str;
186             while (c < str + len) {
187                 if (*c == APR_ASCII_LF)
188                     c++;
189                 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
190                     c += 2;
191                 else
192                     return APR_SUCCESS;
193             }
194
195             /* If we reach here, we were a bucket just full of CRLFs, so
196              * just toss the bucket. */
197             /* FIXME: Is this the right thing to do in the core? */
198             apr_bucket_delete(e);
199         }
200         return APR_SUCCESS;
201     }
202
203     /* If mode is EXHAUSTIVE, we want to just read everything until the end
204      * of the brigade, which in this case means the end of the socket.
205      * To do this, we attach the brigade that has currently been setaside to
206      * the brigade that was passed down, and send that brigade back.
207      *
208      * NOTE:  This is VERY dangerous to use, and should only be done with
209      * extreme caution.  FWLIW, this would be needed by an MPM like Perchild;
210      * such an MPM can easily request the socket and all data that has been
211      * read, which means that it can pass it to the correct child process.
212      */
213     if (mode == AP_MODE_EXHAUSTIVE) {
214         apr_bucket *e;
215
216         /* Tack on any buckets that were set aside. */
217         APR_BRIGADE_CONCAT(b, ctx->b);
218
219         /* Since we've just added all potential buckets (which will most
220          * likely simply be the socket bucket) we know this is the end,
221          * so tack on an EOS too. */
222         /* We have read until the brigade was empty, so we know that we
223          * must be EOS. */
224         e = apr_bucket_eos_create(f->c->bucket_alloc);
225         APR_BRIGADE_INSERT_TAIL(b, e);
226         return APR_SUCCESS;
227     }
228
229     /* read up to the amount they specified. */
230     if (mode == AP_MODE_READBYTES || mode == AP_MODE_SPECULATIVE) {
231         apr_bucket *e;
232
233         AP_DEBUG_ASSERT(readbytes > 0);
234
235         e = APR_BRIGADE_FIRST(ctx->b);
236         rv = apr_bucket_read(e, &str, &len, block);
237
238         if (APR_STATUS_IS_EAGAIN(rv) && block == APR_NONBLOCK_READ) {
239             /* getting EAGAIN for a blocking read is an error; for a
240              * non-blocking read, return an empty brigade. */
241             return APR_SUCCESS;
242         }
243         else if (rv != APR_SUCCESS) {
244             return rv;
245         }
246         else if (block == APR_BLOCK_READ && len == 0) {
247             /* We wanted to read some bytes in blocking mode.  We read
248              * 0 bytes.  Hence, we now assume we are EOS.
249              *
250              * When we are in normal mode, return an EOS bucket to the
251              * caller.
252              * When we are in speculative mode, leave ctx->b empty, so
253              * that the next call returns an EOS bucket.
254              */
255             apr_bucket_delete(e);
256
257             if (mode == AP_MODE_READBYTES) {
258                 e = apr_bucket_eos_create(f->c->bucket_alloc);
259                 APR_BRIGADE_INSERT_TAIL(b, e);
260             }
261             return APR_SUCCESS;
262         }
263
264         /* Have we read as much data as we wanted (be greedy)? */
265         if (len < readbytes) {
266             apr_size_t bucket_len;
267
268             rv = APR_SUCCESS;
269             /* We already registered the data in e in len */
270             e = APR_BUCKET_NEXT(e);
271             while ((len < readbytes) && (rv == APR_SUCCESS)
272                    && (e != APR_BRIGADE_SENTINEL(ctx->b))) {
273                 /* Check for the availability of buckets with known length */
274                 if (e->length != -1) {
275                     len += e->length;
276                     e = APR_BUCKET_NEXT(e);
277                 }
278                 else {
279                     /*
280                      * Read from bucket, but non blocking. If there isn't any
281                      * more data, well than this is fine as well, we will
282                      * not wait for more since we already got some and we are
283                      * only checking if there isn't more.
284                      */
285                     rv = apr_bucket_read(e, &str, &bucket_len,
286                                          APR_NONBLOCK_READ);
287                     if (rv == APR_SUCCESS) {
288                         len += bucket_len;
289                         e = APR_BUCKET_NEXT(e);
290                     }
291                 }
292             }
293         }
294
295         /* We can only return at most what we read. */
296         if (len < readbytes) {
297             readbytes = len;
298         }
299
300         rv = apr_brigade_partition(ctx->b, readbytes, &e);
301         if (rv != APR_SUCCESS) {
302             return rv;
303         }
304
305         /* Must do move before CONCAT */
306         ctx->tmpbb = apr_brigade_split_ex(ctx->b, e, ctx->tmpbb);
307
308         if (mode == AP_MODE_READBYTES) {
309             APR_BRIGADE_CONCAT(b, ctx->b);
310         }
311         else if (mode == AP_MODE_SPECULATIVE) {
312             apr_bucket *copy_bucket;
313
314             for (e = APR_BRIGADE_FIRST(ctx->b);
315                  e != APR_BRIGADE_SENTINEL(ctx->b);
316                  e = APR_BUCKET_NEXT(e))
317             {
318                 rv = apr_bucket_copy(e, &copy_bucket);
319                 if (rv != APR_SUCCESS) {
320                     return rv;
321                 }
322                 APR_BRIGADE_INSERT_TAIL(b, copy_bucket);
323             }
324         }
325
326         /* Take what was originally there and place it back on ctx->b */
327         APR_BRIGADE_CONCAT(ctx->b, ctx->tmpbb);
328     }
329     return APR_SUCCESS;
330 }
331
332 static void setaside_remaining_output(ap_filter_t *f,
333                                       core_output_filter_ctx_t *ctx,
334                                       apr_bucket_brigade *bb,
335                                       conn_rec *c);
336
337 static apr_status_t send_brigade_nonblocking(apr_socket_t *s,
338                                              apr_bucket_brigade *bb,
339                                              apr_size_t *bytes_written,
340                                              conn_rec *c);
341
342 static void remove_empty_buckets(apr_bucket_brigade *bb);
343
344 static apr_status_t send_brigade_blocking(apr_socket_t *s,
345                                           apr_bucket_brigade *bb,
346                                           apr_size_t *bytes_written,
347                                           conn_rec *c);
348
349 static apr_status_t writev_nonblocking(apr_socket_t *s,
350                                        struct iovec *vec, apr_size_t nvec,
351                                        apr_bucket_brigade *bb,
352                                        apr_size_t *cumulative_bytes_written,
353                                        conn_rec *c);
354
355 #if APR_HAS_SENDFILE
356 static apr_status_t sendfile_nonblocking(apr_socket_t *s,
357                                          apr_bucket *bucket,
358                                          apr_size_t *cumulative_bytes_written,
359                                          conn_rec *c);
360 #endif
361
362 /* XXX: Should these be configurable parameters? */
363 #define THRESHOLD_MIN_WRITE 4096
364 #define THRESHOLD_MAX_BUFFER 65536
365 #define MAX_REQUESTS_IN_PIPELINE 5
366
367 /* Optional function coming from mod_logio, used for logging of output
368  * traffic
369  */
370 extern APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *ap__logio_add_bytes_out;
371
372 apr_status_t ap_core_output_filter(ap_filter_t *f, apr_bucket_brigade *new_bb)
373 {
374     conn_rec *c = f->c;
375     core_net_rec *net = f->ctx;
376     core_output_filter_ctx_t *ctx = net->out_ctx;
377     apr_bucket_brigade *bb = NULL;
378     apr_bucket *bucket, *next, *flush_upto = NULL;
379     apr_size_t bytes_in_brigade, non_file_bytes_in_brigade;
380     int eor_buckets_in_brigade, morphing_bucket_in_brigade;
381     apr_status_t rv;
382
383     /* Fail quickly if the connection has already been aborted. */
384     if (c->aborted) {
385         if (new_bb != NULL) {
386             apr_brigade_cleanup(new_bb);
387         }
388         return APR_ECONNABORTED;
389     }
390
391     if (ctx == NULL) {
392         ctx = apr_pcalloc(c->pool, sizeof(*ctx));
393         net->out_ctx = (core_output_filter_ctx_t *)ctx;
394         rv = apr_socket_opt_set(net->client_socket, APR_SO_NONBLOCK, 1);
395         if (rv != APR_SUCCESS) {
396             return rv;
397         }
398         /*
399          * Need to create tmp brigade with correct lifetime. Passing
400          * NULL to apr_brigade_split_ex would result in a brigade
401          * allocated from bb->pool which might be wrong.
402          */
403         ctx->tmp_flush_bb = apr_brigade_create(c->pool, c->bucket_alloc);
404         /* same for buffered_bb and ap_save_brigade */
405         ctx->buffered_bb = apr_brigade_create(c->pool, c->bucket_alloc);
406     }
407
408     if (new_bb != NULL)
409         bb = new_bb;
410
411     if ((ctx->buffered_bb != NULL) &&
412         !APR_BRIGADE_EMPTY(ctx->buffered_bb)) {
413         if (new_bb != NULL) {
414             APR_BRIGADE_PREPEND(bb, ctx->buffered_bb);
415         }
416         else {
417             bb = ctx->buffered_bb;
418         }
419         c->data_in_output_filters = 0;
420     }
421     else if (new_bb == NULL) {
422         return APR_SUCCESS;
423     }
424
425     /* Scan through the brigade and decide whether to attempt a write,
426      * and how much to write, based on the following rules:
427      *
428      *  1) The new_bb is null: Do a nonblocking write of as much as
429      *     possible: do a nonblocking write of as much data as possible,
430      *     then save the rest in ctx->buffered_bb.  (If new_bb == NULL,
431      *     it probably means that the MPM is doing asynchronous write
432      *     completion and has just determined that this connection
433      *     is writable.)
434      *
435      *  2) Determine if and up to which bucket we need to do a blocking
436      *     write:
437      *
438      *  a) The brigade contains a flush bucket: Do a blocking write
439      *     of everything up that point.
440      *
441      *  b) The request is in CONN_STATE_HANDLER state, and the brigade
442      *     contains at least THRESHOLD_MAX_BUFFER bytes in non-file
443      *     buckets: Do blocking writes until the amount of data in the
444      *     buffer is less than THRESHOLD_MAX_BUFFER.  (The point of this
445      *     rule is to provide flow control, in case a handler is
446      *     streaming out lots of data faster than the data can be
447      *     sent to the client.)
448      *
449      *  c) The request is in CONN_STATE_HANDLER state, and the brigade
450      *     contains at least MAX_REQUESTS_IN_PIPELINE EOR buckets:
451      *     Do blocking writes until less than MAX_REQUESTS_IN_PIPELINE EOR
452      *     buckets are left. (The point of this rule is to prevent too many
453      *     FDs being kept open by pipelined requests, possibly allowing a
454      *     DoS).
455      *
456      *  d) The brigade contains a morphing bucket: If there was no other
457      *     reason to do a blocking write yet, try reading the bucket. If its
458      *     contents fit into memory before THRESHOLD_MAX_BUFFER is reached,
459      *     everything is fine. Otherwise we need to do a blocking write the
460      *     up to and including the morphing bucket, because ap_save_brigade()
461      *     would read the whole bucket into memory later on.
462      *
463      *  3) Actually do the blocking write up to the last bucket determined
464      *     by rules 2a-d. The point of doing only one flush is to make as
465      *     few calls to writev() as possible.
466      *
467      *  4) If the brigade contains at least THRESHOLD_MIN_WRITE
468      *     bytes: Do a nonblocking write of as much data as possible,
469      *     then save the rest in ctx->buffered_bb.
470      */
471
472     if (new_bb == NULL) {
473         rv = send_brigade_nonblocking(net->client_socket, bb,
474                                       &(ctx->bytes_written), c);
475         if (APR_STATUS_IS_EAGAIN(rv)) {
476             rv = APR_SUCCESS;
477         }
478         else if (rv != APR_SUCCESS) {
479             /* The client has aborted the connection */
480             c->aborted = 1;
481         }
482         setaside_remaining_output(f, ctx, bb, c);
483         return rv;
484     }
485
486     bytes_in_brigade = 0;
487     non_file_bytes_in_brigade = 0;
488     eor_buckets_in_brigade = 0;
489     morphing_bucket_in_brigade = 0;
490
491     for (bucket = APR_BRIGADE_FIRST(bb); bucket != APR_BRIGADE_SENTINEL(bb);
492          bucket = next) {
493         next = APR_BUCKET_NEXT(bucket);
494
495         if (!APR_BUCKET_IS_METADATA(bucket)) {
496             if (bucket->length == (apr_size_t)-1) {
497                 /*
498                  * A setaside of morphing buckets would read everything into
499                  * memory. Instead, we will flush everything up to and
500                  * including this bucket.
501                  */
502                 morphing_bucket_in_brigade = 1;
503             }
504             else {
505                 bytes_in_brigade += bucket->length;
506                 if (!APR_BUCKET_IS_FILE(bucket))
507                     non_file_bytes_in_brigade += bucket->length;
508             }
509         }
510         else if (AP_BUCKET_IS_EOR(bucket)) {
511             eor_buckets_in_brigade++;
512         }
513
514         if (APR_BUCKET_IS_FLUSH(bucket)
515             || non_file_bytes_in_brigade >= THRESHOLD_MAX_BUFFER
516             || morphing_bucket_in_brigade
517             || eor_buckets_in_brigade > MAX_REQUESTS_IN_PIPELINE) {
518             /* this segment of the brigade MUST be sent before returning. */
519
520             if (APLOGctrace6(c)) {
521                 char *reason = APR_BUCKET_IS_FLUSH(bucket) ?
522                                "FLUSH bucket" :
523                                (non_file_bytes_in_brigade >= THRESHOLD_MAX_BUFFER) ?
524                                "THRESHOLD_MAX_BUFFER" :
525                                morphing_bucket_in_brigade ? "morphing bucket" :
526                                "MAX_REQUESTS_IN_PIPELINE";
527                 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, c,
528                               "core_output_filter: flushing because of %s",
529                               reason);
530             }
531             /*
532              * Defer the actual blocking write to avoid doing many writes.
533              */
534             flush_upto = next;
535
536             bytes_in_brigade = 0;
537             non_file_bytes_in_brigade = 0;
538             eor_buckets_in_brigade = 0;
539             morphing_bucket_in_brigade = 0;
540         }
541     }
542
543     if (flush_upto != NULL) {
544         ctx->tmp_flush_bb = apr_brigade_split_ex(bb, flush_upto,
545                                                  ctx->tmp_flush_bb);
546         rv = send_brigade_blocking(net->client_socket, bb,
547                                    &(ctx->bytes_written), c);
548         if (rv != APR_SUCCESS) {
549             /* The client has aborted the connection */
550             c->aborted = 1;
551             return rv;
552         }
553         APR_BRIGADE_CONCAT(bb, ctx->tmp_flush_bb);
554     }
555
556     if (bytes_in_brigade >= THRESHOLD_MIN_WRITE) {
557         rv = send_brigade_nonblocking(net->client_socket, bb,
558                                       &(ctx->bytes_written), c);
559         if ((rv != APR_SUCCESS) && (!APR_STATUS_IS_EAGAIN(rv))) {
560             /* The client has aborted the connection */
561             c->aborted = 1;
562             return rv;
563         }
564     }
565
566     setaside_remaining_output(f, ctx, bb, c);
567     return APR_SUCCESS;
568 }
569
570 /*
571  * This function assumes that either ctx->buffered_bb == NULL, or
572  * ctx->buffered_bb is empty, or ctx->buffered_bb == bb
573  */
574 static void setaside_remaining_output(ap_filter_t *f,
575                                       core_output_filter_ctx_t *ctx,
576                                       apr_bucket_brigade *bb,
577                                       conn_rec *c)
578 {
579     if (bb == NULL) {
580         return;
581     }
582     remove_empty_buckets(bb);
583     if (!APR_BRIGADE_EMPTY(bb)) {
584         c->data_in_output_filters = 1;
585         if (bb != ctx->buffered_bb) {
586             if (!ctx->deferred_write_pool) {
587                 apr_pool_create(&ctx->deferred_write_pool, c->pool);
588                 apr_pool_tag(ctx->deferred_write_pool, "deferred_write");
589             }
590             ap_save_brigade(f, &(ctx->buffered_bb), &bb,
591                             ctx->deferred_write_pool);
592             apr_brigade_cleanup(bb);
593         }
594     }
595     else if (ctx->deferred_write_pool) {
596         /*
597          * There are no more requests in the pipeline. We can just clear the
598          * pool.
599          */
600         apr_pool_clear(ctx->deferred_write_pool);
601     }
602 }
603
604 #ifndef APR_MAX_IOVEC_SIZE
605 #define MAX_IOVEC_TO_WRITE 16
606 #else
607 #if APR_MAX_IOVEC_SIZE > 16
608 #define MAX_IOVEC_TO_WRITE 16
609 #else
610 #define MAX_IOVEC_TO_WRITE APR_MAX_IOVEC_SIZE
611 #endif
612 #endif
613
614 static apr_status_t send_brigade_nonblocking(apr_socket_t *s,
615                                              apr_bucket_brigade *bb,
616                                              apr_size_t *bytes_written,
617                                              conn_rec *c)
618 {
619     apr_bucket *bucket, *next;
620     apr_status_t rv;
621     struct iovec vec[MAX_IOVEC_TO_WRITE];
622     apr_size_t nvec = 0;
623
624     remove_empty_buckets(bb);
625
626     for (bucket = APR_BRIGADE_FIRST(bb);
627          bucket != APR_BRIGADE_SENTINEL(bb);
628          bucket = next) {
629         next = APR_BUCKET_NEXT(bucket);
630 #if APR_HAS_SENDFILE
631         if (APR_BUCKET_IS_FILE(bucket)) {
632             apr_bucket_file *file_bucket = (apr_bucket_file *)(bucket->data);
633             apr_file_t *fd = file_bucket->fd;
634             /* Use sendfile to send this file unless:
635              *   - the platform doesn't support sendfile,
636              *   - the file is too small for sendfile to be useful, or
637              *   - sendfile is disabled in the httpd config via "EnableSendfile off"
638              */
639
640             if ((apr_file_flags_get(fd) & APR_SENDFILE_ENABLED) &&
641                 (bucket->length >= AP_MIN_SENDFILE_BYTES)) {
642                 if (nvec > 0) {
643                     (void)apr_socket_opt_set(s, APR_TCP_NOPUSH, 1);
644                     rv = writev_nonblocking(s, vec, nvec, bb, bytes_written, c);
645                     nvec = 0;
646                     if (rv != APR_SUCCESS) {
647                         (void)apr_socket_opt_set(s, APR_TCP_NOPUSH, 0);
648                         return rv;
649                     }
650                 }
651                 rv = sendfile_nonblocking(s, bucket, bytes_written, c);
652                 if (nvec > 0) {
653                     (void)apr_socket_opt_set(s, APR_TCP_NOPUSH, 0);
654                 }
655                 if (rv != APR_SUCCESS) {
656                     return rv;
657                 }
658                 break;
659             }
660         }
661 #endif /* APR_HAS_SENDFILE */
662         /* didn't sendfile */
663         if (!APR_BUCKET_IS_METADATA(bucket)) {
664             const char *data;
665             apr_size_t length;
666             
667             /* Non-blocking read first, in case this is a morphing
668              * bucket type. */
669             rv = apr_bucket_read(bucket, &data, &length, APR_NONBLOCK_READ);
670             if (APR_STATUS_IS_EAGAIN(rv)) {
671                 /* Read would block; flush any pending data and retry. */
672                 if (nvec) {
673                     rv = writev_nonblocking(s, vec, nvec, bb, bytes_written, c);
674                     if (rv) {
675                         return rv;
676                     }
677                     nvec = 0;
678                 }
679                 
680                 rv = apr_bucket_read(bucket, &data, &length, APR_BLOCK_READ);
681             }
682             if (rv != APR_SUCCESS) {
683                 return rv;
684             }
685
686             /* reading may have split the bucket, so recompute next: */
687             next = APR_BUCKET_NEXT(bucket);
688             vec[nvec].iov_base = (char *)data;
689             vec[nvec].iov_len = length;
690             nvec++;
691             if (nvec == MAX_IOVEC_TO_WRITE) {
692                 rv = writev_nonblocking(s, vec, nvec, bb, bytes_written, c);
693                 nvec = 0;
694                 if (rv != APR_SUCCESS) {
695                     return rv;
696                 }
697                 break;
698             }
699         }
700     }
701
702     if (nvec > 0) {
703         rv = writev_nonblocking(s, vec, nvec, bb, bytes_written, c);
704         if (rv != APR_SUCCESS) {
705             return rv;
706         }
707     }
708
709     remove_empty_buckets(bb);
710
711     return APR_SUCCESS;
712 }
713
714 static void remove_empty_buckets(apr_bucket_brigade *bb)
715 {
716     apr_bucket *bucket;
717     while (((bucket = APR_BRIGADE_FIRST(bb)) != APR_BRIGADE_SENTINEL(bb)) &&
718            (APR_BUCKET_IS_METADATA(bucket) || (bucket->length == 0))) {
719         APR_BUCKET_REMOVE(bucket);
720         apr_bucket_destroy(bucket);
721     }
722 }
723
724 static apr_status_t send_brigade_blocking(apr_socket_t *s,
725                                           apr_bucket_brigade *bb,
726                                           apr_size_t *bytes_written,
727                                           conn_rec *c)
728 {
729     apr_status_t rv;
730
731     rv = APR_SUCCESS;
732     while (!APR_BRIGADE_EMPTY(bb)) {
733         rv = send_brigade_nonblocking(s, bb, bytes_written, c);
734         if (rv != APR_SUCCESS) {
735             if (APR_STATUS_IS_EAGAIN(rv)) {
736                 /* Wait until we can send more data */
737                 apr_int32_t nsds;
738                 apr_interval_time_t timeout;
739                 apr_pollfd_t pollset;
740
741                 pollset.p = c->pool;
742                 pollset.desc_type = APR_POLL_SOCKET;
743                 pollset.reqevents = APR_POLLOUT;
744                 pollset.desc.s = s;
745                 apr_socket_timeout_get(s, &timeout);
746                 rv = apr_poll(&pollset, 1, &nsds, timeout);
747                 if (rv != APR_SUCCESS) {
748                     break;
749                 }
750             }
751             else {
752                 break;
753             }
754         }
755     }
756     return rv;
757 }
758
759 static apr_status_t writev_nonblocking(apr_socket_t *s,
760                                        struct iovec *vec, apr_size_t nvec,
761                                        apr_bucket_brigade *bb,
762                                        apr_size_t *cumulative_bytes_written,
763                                        conn_rec *c)
764 {
765     apr_status_t rv = APR_SUCCESS, arv;
766     apr_size_t bytes_written = 0, bytes_to_write = 0;
767     apr_size_t i, offset;
768     apr_interval_time_t old_timeout;
769
770     arv = apr_socket_timeout_get(s, &old_timeout);
771     if (arv != APR_SUCCESS) {
772         return arv;
773     }
774     arv = apr_socket_timeout_set(s, 0);
775     if (arv != APR_SUCCESS) {
776         return arv;
777     }
778
779     for (i = 0; i < nvec; i++) {
780         bytes_to_write += vec[i].iov_len;
781     }
782     offset = 0;
783     while (bytes_written < bytes_to_write) {
784         apr_size_t n = 0;
785         rv = apr_socket_sendv(s, vec + offset, nvec - offset, &n);
786         if (n > 0) {
787             bytes_written += n;
788             for (i = offset; i < nvec; ) {
789                 apr_bucket *bucket = APR_BRIGADE_FIRST(bb);
790                 if (APR_BUCKET_IS_METADATA(bucket)) {
791                     APR_BUCKET_REMOVE(bucket);
792                     apr_bucket_destroy(bucket);
793                 }
794                 else if (n >= vec[i].iov_len) {
795                     APR_BUCKET_REMOVE(bucket);
796                     apr_bucket_destroy(bucket);
797                     offset++;
798                     n -= vec[i++].iov_len;
799                 }
800                 else {
801                     apr_bucket_split(bucket, n);
802                     APR_BUCKET_REMOVE(bucket);
803                     apr_bucket_destroy(bucket);
804                     vec[i].iov_len -= n;
805                     vec[i].iov_base = (char *) vec[i].iov_base + n;
806                     break;
807                 }
808             }
809         }
810         if (rv != APR_SUCCESS) {
811             break;
812         }
813     }
814     if ((ap__logio_add_bytes_out != NULL) && (bytes_written > 0)) {
815         ap__logio_add_bytes_out(c, bytes_written);
816     }
817     *cumulative_bytes_written += bytes_written;
818
819     arv = apr_socket_timeout_set(s, old_timeout);
820     if ((arv != APR_SUCCESS) && (rv == APR_SUCCESS)) {
821         return arv;
822     }
823     else {
824         return rv;
825     }
826 }
827
828 #if APR_HAS_SENDFILE
829
830 static apr_status_t sendfile_nonblocking(apr_socket_t *s,
831                                          apr_bucket *bucket,
832                                          apr_size_t *cumulative_bytes_written,
833                                          conn_rec *c)
834 {
835     apr_status_t rv = APR_SUCCESS;
836     apr_bucket_file *file_bucket;
837     apr_file_t *fd;
838     apr_size_t file_length;
839     apr_off_t file_offset;
840     apr_size_t bytes_written = 0;
841
842     if (!APR_BUCKET_IS_FILE(bucket)) {
843         ap_log_error(APLOG_MARK, APLOG_ERR, rv, c->base_server, APLOGNO(00006)
844                      "core_filter: sendfile_nonblocking: "
845                      "this should never happen");
846         return APR_EGENERAL;
847     }
848     file_bucket = (apr_bucket_file *)(bucket->data);
849     fd = file_bucket->fd;
850     file_length = bucket->length;
851     file_offset = bucket->start;
852
853     if (bytes_written < file_length) {
854         apr_size_t n = file_length - bytes_written;
855         apr_status_t arv;
856         apr_interval_time_t old_timeout;
857
858         arv = apr_socket_timeout_get(s, &old_timeout);
859         if (arv != APR_SUCCESS) {
860             return arv;
861         }
862         arv = apr_socket_timeout_set(s, 0);
863         if (arv != APR_SUCCESS) {
864             return arv;
865         }
866         rv = apr_socket_sendfile(s, fd, NULL, &file_offset, &n, 0);
867         if (rv == APR_SUCCESS) {
868             bytes_written += n;
869             file_offset += n;
870         }
871         arv = apr_socket_timeout_set(s, old_timeout);
872         if ((arv != APR_SUCCESS) && (rv == APR_SUCCESS)) {
873             rv = arv;
874         }
875     }
876     if ((ap__logio_add_bytes_out != NULL) && (bytes_written > 0)) {
877         ap__logio_add_bytes_out(c, bytes_written);
878     }
879     *cumulative_bytes_written += bytes_written;
880     if ((bytes_written < file_length) && (bytes_written > 0)) {
881         apr_bucket_split(bucket, bytes_written);
882         APR_BUCKET_REMOVE(bucket);
883         apr_bucket_destroy(bucket);
884     }
885     else if (bytes_written == file_length) {
886         APR_BUCKET_REMOVE(bucket);
887         apr_bucket_destroy(bucket);
888     }
889     return rv;
890 }
891
892 #endif