upload http
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / modules / ssl / ssl_engine_io.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  *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
19  * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
20  * | | | | | | (_) | (_| |   \__ \__ \ |
21  * |_| |_| |_|\___/ \__,_|___|___/___/_|
22  *                      |_____|
23  *  ssl_engine_io.c
24  *  I/O Functions
25  */
26                              /* ``MY HACK: This universe.
27                                   Just one little problem:
28                                   core keeps dumping.''
29                                             -- Unknown    */
30 #include "mod_ssl.h"
31
32 /*  _________________________________________________________________
33 **
34 **  I/O Hooks
35 **  _________________________________________________________________
36 */
37
38 /* This file is designed to be the bridge between OpenSSL and httpd.
39  * However, we really don't expect anyone (let alone ourselves) to
40  * remember what is in this file.  So, first, a quick overview.
41  *
42  * In this file, you will find:
43  * - ssl_io_filter_input    (Apache input filter)
44  * - ssl_io_filter_output   (Apache output filter)
45  *
46  * - bio_filter_in_*        (OpenSSL input filter)
47  * - bio_filter_out_*       (OpenSSL output filter)
48  *
49  * The input chain is roughly:
50  *
51  * ssl_io_filter_input->ssl_io_input_read->SSL_read->...
52  * ...->bio_filter_in_read->ap_get_brigade/next-httpd-filter
53  *
54  * In mortal terminology, we do the following:
55  * - Receive a request for data to the SSL input filter
56  * - Call a helper function once we know we should perform a read
57  * - Call OpenSSL's SSL_read()
58  * - SSL_read() will then call bio_filter_in_read
59  * - bio_filter_in_read will then try to fetch data from the next httpd filter
60  * - bio_filter_in_read will flatten that data and return it to SSL_read
61  * - SSL_read will then decrypt the data
62  * - ssl_io_input_read will then receive decrypted data as a char* and
63  *   ensure that there were no read errors
64  * - The char* is placed in a brigade and returned
65  *
66  * Since connection-level input filters in httpd need to be able to
67  * handle AP_MODE_GETLINE calls (namely identifying LF-terminated strings), 
68  * ssl_io_input_getline which will handle this special case.
69  *
70  * Due to AP_MODE_GETLINE and AP_MODE_SPECULATIVE, we may sometimes have 
71  * 'leftover' decoded data which must be setaside for the next read.  That
72  * is currently handled by the char_buffer_{read|write} functions.  So,
73  * ssl_io_input_read may be able to fulfill reads without invoking
74  * SSL_read().
75  *
76  * Note that the filter context of ssl_io_filter_input and bio_filter_in_*
77  * are shared as bio_filter_in_ctx_t.
78  *
79  * Note that the filter is by choice limited to reading at most
80  * AP_IOBUFSIZE (8192 bytes) per call.
81  *
82  */
83
84 /* this custom BIO allows us to hook SSL_write directly into 
85  * an apr_bucket_brigade and use transient buckets with the SSL
86  * malloc-ed buffer, rather than copying into a mem BIO.
87  * also allows us to pass the brigade as data is being written
88  * rather than buffering up the entire response in the mem BIO.
89  *
90  * when SSL needs to flush (e.g. SSL_accept()), it will call BIO_flush()
91  * which will trigger a call to bio_filter_out_ctrl() -> bio_filter_out_flush().
92  * so we only need to flush the output ourselves if we receive an
93  * EOS or FLUSH bucket. this was not possible with the mem BIO where we
94  * had to flush all over the place not really knowing when it was required
95  * to do so.
96  */
97
98 typedef struct {
99     SSL                *pssl;
100     BIO                *pbioRead;
101     BIO                *pbioWrite;
102     ap_filter_t        *pInputFilter;
103     ap_filter_t        *pOutputFilter;
104     int                nobuffer; /* non-zero to prevent buffering */
105     SSLConnRec         *config;
106 } ssl_filter_ctx_t;
107
108 typedef struct {
109     ssl_filter_ctx_t *filter_ctx;
110     conn_rec *c;
111     apr_bucket_brigade *bb;
112     apr_size_t length;
113     char buffer[AP_IOBUFSIZE];
114     apr_size_t blen;
115     apr_status_t rc;
116 } bio_filter_out_ctx_t;
117
118 static bio_filter_out_ctx_t *bio_filter_out_ctx_new(ssl_filter_ctx_t *filter_ctx,
119                                                     conn_rec *c)
120 {
121     bio_filter_out_ctx_t *outctx = apr_palloc(c->pool, sizeof(*outctx));
122
123     outctx->filter_ctx = filter_ctx;
124     outctx->c = c;
125     outctx->bb = apr_brigade_create(c->pool, c->bucket_alloc);
126     outctx->blen = 0;
127     outctx->length = 0;
128
129     return outctx;
130 }
131
132 static int bio_filter_out_flush(BIO *bio)
133 {
134     bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)(bio->ptr);
135     apr_bucket *e;
136
137     if (!(outctx->blen || outctx->length)) {
138         outctx->rc = APR_SUCCESS;
139         return 1;
140     }
141
142     if (outctx->blen) {
143         e = apr_bucket_transient_create(outctx->buffer, outctx->blen,
144                                         outctx->bb->bucket_alloc);
145         /* we filled this buffer first so add it to the 
146          * head of the brigade
147          */
148         APR_BRIGADE_INSERT_HEAD(outctx->bb, e);
149         outctx->blen = 0;
150     }
151
152     outctx->length = 0;
153     e = apr_bucket_flush_create(outctx->bb->bucket_alloc);
154     APR_BRIGADE_INSERT_TAIL(outctx->bb, e);
155
156     outctx->rc = ap_pass_brigade(outctx->filter_ctx->pOutputFilter->next,
157                                  outctx->bb);
158     /* Fail if the connection was reset: */
159     if (outctx->rc == APR_SUCCESS && outctx->c->aborted) {
160         outctx->rc = APR_ECONNRESET;
161     }
162     return (outctx->rc == APR_SUCCESS) ? 1 : -1;
163 }
164
165 static int bio_filter_create(BIO *bio)
166 {
167     bio->shutdown = 1;
168     bio->init = 1;
169     bio->num = -1;
170     bio->ptr = NULL;
171
172     return 1;
173 }
174
175 static int bio_filter_destroy(BIO *bio)
176 {
177     if (bio == NULL) {
178         return 0;
179     }
180
181     /* nothing to free here.
182      * apache will destroy the bucket brigade for us
183      */
184     return 1;
185 }
186         
187 static int bio_filter_out_read(BIO *bio, char *out, int outl)
188 {
189     /* this is never called */
190     return -1;
191 }
192
193 static int bio_filter_out_write(BIO *bio, const char *in, int inl)
194 {
195     bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)(bio->ptr);
196     
197     /* Abort early if the client has initiated a renegotiation. */
198     if (outctx->filter_ctx->config->reneg_state == RENEG_ABORT) {
199         outctx->rc = APR_ECONNABORTED;
200         return -1;
201     }
202     
203     /* when handshaking we'll have a small number of bytes.
204      * max size SSL will pass us here is about 16k.
205      * (16413 bytes to be exact)
206      */
207     BIO_clear_retry_flags(bio);
208
209     if (!outctx->length && (inl + outctx->blen < sizeof(outctx->buffer)) &&
210         !outctx->filter_ctx->nobuffer) {
211         /* the first two SSL_writes (of 1024 and 261 bytes)
212          * need to be in the same packet (vec[0].iov_base)
213          */
214         /* XXX: could use apr_brigade_write() to make code look cleaner
215          * but this way we avoid the malloc(APR_BUCKET_BUFF_SIZE)
216          * and free() of it later
217          */
218         memcpy(&outctx->buffer[outctx->blen], in, inl);
219         outctx->blen += inl;
220     }
221     else {
222         /* pass along the encrypted data
223          * need to flush since we're using SSL's malloc-ed buffer 
224          * which will be overwritten once we leave here
225          */
226         apr_bucket *bucket = apr_bucket_transient_create(in, inl,
227                                              outctx->bb->bucket_alloc);
228
229         outctx->length += inl;
230         APR_BRIGADE_INSERT_TAIL(outctx->bb, bucket);
231
232         if (bio_filter_out_flush(bio) < 0) {
233             return -1;
234         }
235     }
236
237     return inl;
238 }
239
240 static long bio_filter_out_ctrl(BIO *bio, int cmd, long num, void *ptr)
241 {
242     long ret = 1;
243     char **pptr;
244
245     bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)(bio->ptr);
246
247     switch (cmd) {
248       case BIO_CTRL_RESET:
249         outctx->blen = outctx->length = 0;
250         break;
251       case BIO_CTRL_EOF:
252         ret = (long)((outctx->blen + outctx->length) == 0);
253         break;
254       case BIO_C_SET_BUF_MEM_EOF_RETURN:
255         outctx->blen = outctx->length = (apr_size_t)num;
256         break;
257       case BIO_CTRL_INFO:
258         ret = (long)(outctx->blen + outctx->length);
259         if (ptr) {
260             pptr = (char **)ptr;
261             *pptr = (char *)&(outctx->buffer[0]);
262         }
263         break;
264       case BIO_CTRL_GET_CLOSE:
265         ret = (long)bio->shutdown;
266         break;
267       case BIO_CTRL_SET_CLOSE:
268         bio->shutdown = (int)num;
269         break;
270       case BIO_CTRL_WPENDING:
271         ret = 0L;
272         break;
273       case BIO_CTRL_PENDING:
274         ret = (long)(outctx->blen + outctx->length);
275         break;
276       case BIO_CTRL_FLUSH:
277         ret = bio_filter_out_flush(bio);
278         break;
279       case BIO_CTRL_DUP:
280         ret = 1;
281         break;
282         /* N/A */
283       case BIO_C_SET_BUF_MEM:
284       case BIO_C_GET_BUF_MEM_PTR:
285         /* we don't care */
286       case BIO_CTRL_PUSH:
287       case BIO_CTRL_POP:
288       default:
289         ret = 0;
290         break;
291     }
292
293     return ret;
294 }
295
296 static int bio_filter_out_gets(BIO *bio, char *buf, int size)
297 {
298     /* this is never called */
299     return -1;
300 }
301
302 static int bio_filter_out_puts(BIO *bio, const char *str)
303 {
304     /* this is never called */
305     return -1;
306 }
307
308 static BIO_METHOD bio_filter_out_method = {
309     BIO_TYPE_MEM,
310     "APR output filter",
311     bio_filter_out_write,
312     bio_filter_out_read,     /* read is never called */
313     bio_filter_out_puts,     /* puts is never called */
314     bio_filter_out_gets,     /* gets is never called */
315     bio_filter_out_ctrl,
316     bio_filter_create,
317     bio_filter_destroy,
318 #ifdef OPENSSL_VERSION_NUMBER
319     NULL /* sslc does not have the callback_ctrl field */
320 #endif
321 };
322
323 typedef struct {
324     int length;
325     char *value;
326 } char_buffer_t;
327
328 typedef struct {
329     SSL *ssl;
330     BIO *bio_out;
331     ap_filter_t *f;
332     apr_status_t rc;
333     ap_input_mode_t mode;
334     apr_read_type_e block;
335     apr_bucket_brigade *bb;
336     char_buffer_t cbuf;
337     apr_pool_t *pool;
338     char buffer[AP_IOBUFSIZE];
339     ssl_filter_ctx_t *filter_ctx;
340 } bio_filter_in_ctx_t;
341
342 /*
343  * this char_buffer api might seem silly, but we don't need to copy
344  * any of this data and we need to remember the length.
345  */
346
347 /* Copy up to INL bytes from the char_buffer BUFFER into IN.  Note
348  * that due to the strange way this API is designed/used, the
349  * char_buffer object is used to cache a segment of inctx->buffer, and
350  * then this function called to copy (part of) that segment to the
351  * beginning of inctx->buffer.  So the segments to copy cannot be
352  * presumed to be non-overlapping, and memmove must be used. */
353 static int char_buffer_read(char_buffer_t *buffer, char *in, int inl)
354 {
355     if (!buffer->length) {
356         return 0;
357     }
358
359     if (buffer->length > inl) {
360         /* we have have enough to fill the caller's buffer */
361         memmove(in, buffer->value, inl);
362         buffer->value += inl;
363         buffer->length -= inl;
364     }
365     else {
366         /* swallow remainder of the buffer */
367         memmove(in, buffer->value, buffer->length);
368         inl = buffer->length;
369         buffer->value = NULL;
370         buffer->length = 0;
371     }
372
373     return inl;
374 }
375
376 static int char_buffer_write(char_buffer_t *buffer, char *in, int inl)
377 {
378     buffer->value = in;
379     buffer->length = inl;
380     return inl;
381 }
382
383 /* This function will read from a brigade and discard the read buckets as it
384  * proceeds.  It will read at most *len bytes.
385  */
386 static apr_status_t brigade_consume(apr_bucket_brigade *bb,
387                                     apr_read_type_e block,
388                                     char *c, apr_size_t *len)
389 {
390     apr_size_t actual = 0;
391     apr_status_t status = APR_SUCCESS;
392  
393     while (!APR_BRIGADE_EMPTY(bb)) {
394         apr_bucket *b = APR_BRIGADE_FIRST(bb);
395         const char *str;
396         apr_size_t str_len;
397         apr_size_t consume;
398
399         /* Justin points out this is an http-ism that might
400          * not fit if brigade_consume is added to APR.  Perhaps
401          * apr_bucket_read(eos_bucket) should return APR_EOF?
402          * Then this becomes mainline instead of a one-off.
403          */
404         if (APR_BUCKET_IS_EOS(b)) {
405             status = APR_EOF;
406             break;
407         }
408
409         /* The reason I'm not offering brigade_consume yet
410          * across to apr-util is that the following call
411          * illustrates how borked that API really is.  For
412          * this sort of case (caller provided buffer) it
413          * would be much more trivial for apr_bucket_consume
414          * to do all the work that follows, based on the
415          * particular characteristics of the bucket we are 
416          * consuming here.
417          */
418         status = apr_bucket_read(b, &str, &str_len, block);
419         
420         if (status != APR_SUCCESS) {
421             if (APR_STATUS_IS_EOF(status)) {
422                 /* This stream bucket was consumed */
423                 apr_bucket_delete(b);
424                 continue;
425             }
426             break;
427         }
428
429         if (str_len > 0) {
430             /* Do not block once some data has been consumed */
431             block = APR_NONBLOCK_READ;
432
433             /* Assure we don't overflow. */
434             consume = (str_len + actual > *len) ? *len - actual : str_len;
435
436             memcpy(c, str, consume);
437
438             c += consume;
439             actual += consume;
440
441             if (consume >= b->length) {
442                 /* This physical bucket was consumed */
443                 apr_bucket_delete(b);
444             }
445             else {
446                 /* Only part of this physical bucket was consumed */
447                 b->start += consume;
448                 b->length -= consume;
449             }
450         }
451         else if (b->length == 0) {
452             apr_bucket_delete(b);
453         }
454
455         /* This could probably be actual == *len, but be safe from stray
456          * photons. */
457         if (actual >= *len) {
458             break;
459         }
460     }
461
462     *len = actual;
463     return status;
464 }
465
466 /*
467  * this is the function called by SSL_read()
468  */
469 static int bio_filter_in_read(BIO *bio, char *in, int inlen)
470 {
471     apr_size_t inl = inlen;
472     bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)(bio->ptr);
473     apr_read_type_e block = inctx->block;
474     SSLConnRec *sslconn = myConnConfig(inctx->f->c);
475
476     inctx->rc = APR_SUCCESS;
477
478     /* OpenSSL catches this case, so should we. */
479     if (!in)
480         return 0;
481
482     /* Abort early if the client has initiated a renegotiation. */
483     if (inctx->filter_ctx->config->reneg_state == RENEG_ABORT) {
484         inctx->rc = APR_ECONNABORTED;
485         return -1;
486     }
487
488     /* XXX: flush here only required for SSLv2;
489      * OpenSSL calls BIO_flush() at the appropriate times for
490      * the other protocols.
491      */
492     if ((SSL_version(inctx->ssl) == SSL2_VERSION) || sslconn->is_proxy) {
493         if (bio_filter_out_flush(inctx->bio_out) < 0) {
494             bio_filter_out_ctx_t *outctx = 
495                    (bio_filter_out_ctx_t *)(inctx->bio_out->ptr);
496             inctx->rc = outctx->rc;
497             return -1;
498         }
499     }
500
501     BIO_clear_retry_flags(bio);
502
503     if (!inctx->bb) {
504         inctx->rc = APR_EOF;
505         return -1;
506     }
507
508     if (APR_BRIGADE_EMPTY(inctx->bb)) {
509
510         inctx->rc = ap_get_brigade(inctx->f->next, inctx->bb,
511                                    AP_MODE_READBYTES, block, 
512                                    inl);
513
514         /* Not a problem, there was simply no data ready yet.
515          */
516         if (APR_STATUS_IS_EAGAIN(inctx->rc) || APR_STATUS_IS_EINTR(inctx->rc)
517                || (inctx->rc == APR_SUCCESS && APR_BRIGADE_EMPTY(inctx->bb))) {
518             BIO_set_retry_read(bio);
519             return 0;
520         }
521
522         if (inctx->rc != APR_SUCCESS) {
523             /* Unexpected errors discard the brigade */
524             apr_brigade_cleanup(inctx->bb);
525             inctx->bb = NULL;
526             return -1;
527         }
528     }
529
530     inctx->rc = brigade_consume(inctx->bb, block, in, &inl);
531
532     if (inctx->rc == APR_SUCCESS) {
533         return (int)inl;
534     }
535
536     if (APR_STATUS_IS_EAGAIN(inctx->rc) 
537             || APR_STATUS_IS_EINTR(inctx->rc)) {
538         BIO_set_retry_read(bio);
539         return (int)inl;
540     }
541         
542     /* Unexpected errors and APR_EOF clean out the brigade.
543      * Subsequent calls will return APR_EOF.
544      */
545     apr_brigade_cleanup(inctx->bb);
546     inctx->bb = NULL;
547
548     if (APR_STATUS_IS_EOF(inctx->rc) && inl) {
549         /* Provide the results of this read pass,
550          * without resetting the BIO retry_read flag
551          */
552         return (int)inl;
553     }
554
555     return -1;
556 }
557
558
559 static BIO_METHOD bio_filter_in_method = {
560     BIO_TYPE_MEM,
561     "APR input filter",
562     NULL,                       /* write is never called */
563     bio_filter_in_read,
564     NULL,                       /* puts is never called */
565     NULL,                       /* gets is never called */
566     NULL,                       /* ctrl is never called */
567     bio_filter_create,
568     bio_filter_destroy,
569 #ifdef OPENSSL_VERSION_NUMBER
570     NULL /* sslc does not have the callback_ctrl field */
571 #endif
572 };
573
574
575 static apr_status_t ssl_io_input_read(bio_filter_in_ctx_t *inctx,
576                                       char *buf,
577                                       apr_size_t *len)
578 {
579     apr_size_t wanted = *len;
580     apr_size_t bytes = 0;
581     int rc;
582
583     *len = 0;
584
585     /* If we have something leftover from last time, try that first. */
586     if ((bytes = char_buffer_read(&inctx->cbuf, buf, wanted))) {
587         *len = bytes;
588         if (inctx->mode == AP_MODE_SPECULATIVE) {
589             /* We want to rollback this read. */
590             if (inctx->cbuf.length > 0) {
591                 inctx->cbuf.value -= bytes;
592                 inctx->cbuf.length += bytes;
593             } else {
594                 char_buffer_write(&inctx->cbuf, buf, (int)bytes);
595             }
596             return APR_SUCCESS;
597         }
598         /* This could probably be *len == wanted, but be safe from stray
599          * photons.
600          */
601         if (*len >= wanted) {
602             return APR_SUCCESS;
603         }
604         if (inctx->mode == AP_MODE_GETLINE) {
605             if (memchr(buf, APR_ASCII_LF, *len)) {
606                 return APR_SUCCESS;
607             }
608         }
609         else {
610             /* Down to a nonblock pattern as we have some data already
611              */
612             inctx->block = APR_NONBLOCK_READ;
613         }
614     }
615
616     while (1) {
617
618         if (!inctx->filter_ctx->pssl) {
619             /* Ensure a non-zero error code is returned */
620             if (inctx->rc == APR_SUCCESS) {
621                 inctx->rc = APR_EGENERAL;
622             }
623             break;
624         }
625
626         /* SSL_read may not read because we haven't taken enough data
627          * from the stack.  This is where we want to consider all of
628          * the blocking and SPECULATIVE semantics
629          */
630         rc = SSL_read(inctx->filter_ctx->pssl, buf + bytes, wanted - bytes);
631
632         if (rc > 0) {
633             *len += rc;
634             if (inctx->mode == AP_MODE_SPECULATIVE) {
635                 /* We want to rollback this read. */
636                 char_buffer_write(&inctx->cbuf, buf, rc);
637             }
638             return inctx->rc;
639         }
640         else if (rc == 0) {
641             /* If EAGAIN, we will loop given a blocking read,
642              * otherwise consider ourselves at EOF.
643              */
644             if (APR_STATUS_IS_EAGAIN(inctx->rc)
645                     || APR_STATUS_IS_EINTR(inctx->rc)) {
646                 /* Already read something, return APR_SUCCESS instead. 
647                  * On win32 in particular, but perhaps on other kernels,
648                  * a blocking call isn't 'always' blocking.
649                  */
650                 if (*len > 0) {
651                     inctx->rc = APR_SUCCESS;
652                     break;
653                 }
654                 if (inctx->block == APR_NONBLOCK_READ) {
655                     break;
656                 }
657             }
658             else {
659                 if (*len > 0) {
660                     inctx->rc = APR_SUCCESS;
661                 }
662                 else {
663                     inctx->rc = APR_EOF;
664                 }
665                 break;
666             }
667         }
668         else /* (rc < 0) */ {
669             int ssl_err = SSL_get_error(inctx->filter_ctx->pssl, rc);
670             conn_rec *c = (conn_rec*)SSL_get_app_data(inctx->filter_ctx->pssl);
671
672             if (ssl_err == SSL_ERROR_WANT_READ) {
673                 /*
674                  * If OpenSSL wants to read more, and we were nonblocking,
675                  * report as an EAGAIN.  Otherwise loop, pulling more
676                  * data from network filter.
677                  *
678                  * (This is usually the case when the client forces an SSL
679                  * renegotation which is handled implicitly by OpenSSL.)
680                  */
681                 inctx->rc = APR_EAGAIN;
682
683                 if (*len > 0) {
684                     inctx->rc = APR_SUCCESS;
685                     break;
686                 }
687                 if (inctx->block == APR_NONBLOCK_READ) {
688                     break;
689                 }
690                 continue;  /* Blocking and nothing yet?  Try again. */
691             }
692             else if (ssl_err == SSL_ERROR_SYSCALL) {
693                 if (APR_STATUS_IS_EAGAIN(inctx->rc)
694                         || APR_STATUS_IS_EINTR(inctx->rc)) {
695                     /* Already read something, return APR_SUCCESS instead. */
696                     if (*len > 0) {
697                         inctx->rc = APR_SUCCESS;
698                         break;
699                     }
700                     if (inctx->block == APR_NONBLOCK_READ) {
701                         break;
702                     }
703                     continue;  /* Blocking and nothing yet?  Try again. */
704                 }
705                 else {
706                     ap_log_error(APLOG_MARK, APLOG_INFO, inctx->rc, c->base_server,
707                                 "SSL input filter read failed.");
708                 }
709             }
710             else /* if (ssl_err == SSL_ERROR_SSL) */ {
711                 /*
712                  * Log SSL errors and any unexpected conditions.
713                  */
714                 ap_log_error(APLOG_MARK, APLOG_INFO, inctx->rc, c->base_server,
715                             "SSL library error %d reading data", ssl_err);
716                 ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
717
718             }
719             if (inctx->rc == APR_SUCCESS) {
720                 inctx->rc = APR_EGENERAL;
721             }
722             break;
723         }
724     }
725     return inctx->rc;
726 }
727
728 static apr_status_t ssl_io_input_getline(bio_filter_in_ctx_t *inctx,
729                                          char *buf,
730                                          apr_size_t *len)
731 {
732     const char *pos = NULL;
733     apr_status_t status;
734     apr_size_t tmplen = *len, buflen = *len, offset = 0;
735
736     *len = 0;
737
738     /*
739      * in most cases we get all the headers on the first SSL_read.
740      * however, in certain cases SSL_read will only get a partial
741      * chunk of the headers, so we try to read until LF is seen.
742      */
743
744     while (tmplen > 0) {
745         status = ssl_io_input_read(inctx, buf + offset, &tmplen);
746         
747         if (status != APR_SUCCESS) {
748             return status;
749         }
750
751         *len += tmplen;
752
753         if ((pos = memchr(buf, APR_ASCII_LF, *len))) {
754             break;
755         }
756
757         offset += tmplen;
758         tmplen = buflen - offset;
759     }
760
761     if (pos) {
762         char *value;
763         int length;
764         apr_size_t bytes = pos - buf;
765
766         bytes += 1;
767         value = buf + bytes;
768         length = *len - bytes;
769
770         char_buffer_write(&inctx->cbuf, value, length);
771
772         *len = bytes;
773     }
774
775     return APR_SUCCESS;
776 }
777
778
779 static apr_status_t ssl_filter_write(ap_filter_t *f,
780                                      const char *data,
781                                      apr_size_t len)
782 {
783     ssl_filter_ctx_t *filter_ctx = f->ctx;
784     bio_filter_out_ctx_t *outctx;
785     int res;
786
787     /* write SSL */
788     if (filter_ctx->pssl == NULL) {
789         return APR_EGENERAL;
790     }
791
792     outctx = (bio_filter_out_ctx_t *)filter_ctx->pbioWrite->ptr;
793     res = SSL_write(filter_ctx->pssl, (unsigned char *)data, len);
794
795     if (res < 0) {
796         int ssl_err = SSL_get_error(filter_ctx->pssl, res);
797         conn_rec *c = (conn_rec*)SSL_get_app_data(outctx->filter_ctx->pssl);
798
799         if (ssl_err == SSL_ERROR_WANT_WRITE) {
800             /*
801              * If OpenSSL wants to write more, and we were nonblocking,
802              * report as an EAGAIN.  Otherwise loop, pushing more
803              * data at the network filter.
804              *
805              * (This is usually the case when the client forces an SSL
806              * renegotation which is handled implicitly by OpenSSL.)
807              */
808             outctx->rc = APR_EAGAIN;
809         }
810         else if (ssl_err == SSL_ERROR_SYSCALL) {
811             ap_log_error(APLOG_MARK, APLOG_INFO, outctx->rc, c->base_server,
812                         "SSL output filter write failed.");
813         }
814         else /* if (ssl_err == SSL_ERROR_SSL) */ {
815             /*
816              * Log SSL errors
817              */
818             ap_log_error(APLOG_MARK, APLOG_INFO, outctx->rc, c->base_server,
819                          "SSL library error %d writing data", ssl_err);
820             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
821         }
822         if (outctx->rc == APR_SUCCESS) {
823             outctx->rc = APR_EGENERAL;
824         }
825     }
826     else if ((apr_size_t)res != len) {
827         conn_rec *c = f->c;
828         char *reason = "reason unknown";
829
830         /* XXX: probably a better way to determine this */
831         if (SSL_total_renegotiations(filter_ctx->pssl)) {
832             reason = "likely due to failed renegotiation";
833         }
834
835         ap_log_error(APLOG_MARK, APLOG_INFO, outctx->rc, c->base_server,
836                      "failed to write %d of %d bytes (%s)",
837                      len - (apr_size_t)res, len, reason);
838
839         outctx->rc = APR_EGENERAL;
840     }
841     return outctx->rc;
842 }
843
844 /* Just use a simple request.  Any request will work for this, because
845  * we use a flag in the conn_rec->conn_vector now.  The fake request just
846  * gets the request back to the Apache core so that a response can be sent.
847  *
848  * To avoid calling back for more data from the socket, use an HTTP/0.9
849  * request, and tack on an EOS bucket.
850  */
851 #define HTTP_ON_HTTPS_PORT \
852     "GET /" CRLF
853
854 #define HTTP_ON_HTTPS_PORT_BUCKET(alloc) \
855     apr_bucket_immortal_create(HTTP_ON_HTTPS_PORT, \
856                                sizeof(HTTP_ON_HTTPS_PORT) - 1, \
857                                alloc)
858
859 static void ssl_io_filter_disable(SSLConnRec *sslconn, ap_filter_t *f)
860 {
861     bio_filter_in_ctx_t *inctx = f->ctx;
862     SSL_free(inctx->ssl);
863     sslconn->ssl = NULL;
864     inctx->ssl = NULL;
865     inctx->filter_ctx->pssl = NULL;
866 }
867
868 static apr_status_t ssl_io_filter_error(ap_filter_t *f,
869                                         apr_bucket_brigade *bb,
870                                         apr_status_t status)
871 {
872     SSLConnRec *sslconn = myConnConfig(f->c);
873     apr_bucket *bucket;
874
875     switch (status) {
876       case HTTP_BAD_REQUEST:
877             /* log the situation */
878             ap_log_error(APLOG_MARK, APLOG_INFO, 0,
879                          f->c->base_server,
880                          "SSL handshake failed: HTTP spoken on HTTPS port; "
881                          "trying to send HTML error page");
882             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, f->c->base_server);
883
884             sslconn->non_ssl_request = 1;
885             ssl_io_filter_disable(sslconn, f);
886
887             /* fake the request line */
888             bucket = HTTP_ON_HTTPS_PORT_BUCKET(f->c->bucket_alloc);
889             break;
890
891       default:
892         return status;
893     }
894
895     APR_BRIGADE_INSERT_TAIL(bb, bucket);
896     bucket = apr_bucket_eos_create(f->c->bucket_alloc);
897     APR_BRIGADE_INSERT_TAIL(bb, bucket);
898
899     return APR_SUCCESS;
900 }
901
902 static const char ssl_io_filter[] = "SSL/TLS Filter";
903 static const char ssl_io_buffer[] = "SSL/TLS Buffer";
904
905 /*
906  *  Close the SSL part of the socket connection
907  *  (called immediately _before_ the socket is closed)
908  *  or called with 
909  */
910 static apr_status_t ssl_filter_io_shutdown(ssl_filter_ctx_t *filter_ctx,
911                                            conn_rec *c,
912                                            int abortive)
913 {
914     SSL *ssl = filter_ctx->pssl;
915     const char *type = "";
916     SSLConnRec *sslconn = myConnConfig(c);
917     int shutdown_type;
918
919     if (!ssl) {
920         return APR_SUCCESS;
921     }
922
923     /*
924      * Now close the SSL layer of the connection. We've to take
925      * the TLSv1 standard into account here:
926      *
927      * | 7.2.1. Closure alerts
928      * |
929      * | The client and the server must share knowledge that the connection is
930      * | ending in order to avoid a truncation attack. Either party may
931      * | initiate the exchange of closing messages.
932      * |
933      * | close_notify
934      * |     This message notifies the recipient that the sender will not send
935      * |     any more messages on this connection. The session becomes
936      * |     unresumable if any connection is terminated without proper
937      * |     close_notify messages with level equal to warning.
938      * |
939      * | Either party may initiate a close by sending a close_notify alert.
940      * | Any data received after a closure alert is ignored.
941      * |
942      * | Each party is required to send a close_notify alert before closing
943      * | the write side of the connection. It is required that the other party
944      * | respond with a close_notify alert of its own and close down the
945      * | connection immediately, discarding any pending writes. It is not
946      * | required for the initiator of the close to wait for the responding
947      * | close_notify alert before closing the read side of the connection.
948      *
949      * This means we've to send a close notify message, but haven't to wait
950      * for the close notify of the client. Actually we cannot wait for the
951      * close notify of the client because some clients (including Netscape
952      * 4.x) don't send one, so we would hang.
953      */
954
955     /*
956      * exchange close notify messages, but allow the user
957      * to force the type of handshake via SetEnvIf directive
958      */
959     if (abortive) {
960         shutdown_type = SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN;
961         type = "abortive";
962     }
963     else switch (sslconn->shutdown_type) {
964       case SSL_SHUTDOWN_TYPE_UNCLEAN:
965         /* perform no close notify handshake at all
966            (violates the SSL/TLS standard!) */
967         shutdown_type = SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN;
968         type = "unclean";
969         break;
970       case SSL_SHUTDOWN_TYPE_ACCURATE:
971         /* send close notify and wait for clients close notify
972            (standard compliant, but usually causes connection hangs) */
973         shutdown_type = 0;
974         type = "accurate";
975         break;
976       default:
977         /*
978          * case SSL_SHUTDOWN_TYPE_UNSET:
979          * case SSL_SHUTDOWN_TYPE_STANDARD:
980          */
981         /* send close notify, but don't wait for clients close notify
982            (standard compliant and safe, so it's the DEFAULT!) */
983         shutdown_type = SSL_RECEIVED_SHUTDOWN;
984         type = "standard";
985         break;
986     }
987
988     SSL_set_shutdown(ssl, shutdown_type);
989     SSL_smart_shutdown(ssl);
990
991     /* and finally log the fact that we've closed the connection */
992     if (c->base_server->loglevel >= APLOG_INFO) {
993         ap_log_error(APLOG_MARK, APLOG_INFO, 0, c->base_server,
994                      "Connection to child %ld closed with %s shutdown"
995                      "(server %s, client %s)",
996                      c->id, type,
997                      ssl_util_vhostid(c->pool, c->base_server),
998                      c->remote_ip ? c->remote_ip : "unknown");
999     }
1000
1001     /* deallocate the SSL connection */
1002     if (sslconn->client_cert) {
1003         X509_free(sslconn->client_cert);
1004         sslconn->client_cert = NULL;
1005     }
1006     SSL_free(ssl);
1007     sslconn->ssl = NULL;
1008     filter_ctx->pssl = NULL; /* so filters know we've been shutdown */
1009
1010     if (abortive) {
1011         /* prevent any further I/O */
1012         c->aborted = 1;
1013     }
1014
1015     return APR_SUCCESS;
1016 }
1017
1018 static apr_status_t ssl_io_filter_cleanup(void *data)
1019 {
1020     ssl_filter_ctx_t *filter_ctx = data;
1021
1022     if (filter_ctx->pssl) {
1023         conn_rec *c = (conn_rec *)SSL_get_app_data(filter_ctx->pssl);
1024         SSLConnRec *sslconn = myConnConfig(c);
1025
1026         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1027                      "SSL connection destroyed without being closed");
1028
1029         SSL_free(filter_ctx->pssl);
1030         sslconn->ssl = filter_ctx->pssl = NULL;
1031     }
1032   
1033     return APR_SUCCESS;
1034 }
1035
1036 /*
1037  * The hook is NOT registered with ap_hook_process_connection. Instead, it is
1038  * called manually from the churn () before it tries to read any data.
1039  * There is some problem if I accept conn_rec *. Still investigating..
1040  * Adv. if conn_rec * can be accepted is we can hook this function using the
1041  * ap_hook_process_connection hook.
1042  */
1043 static int ssl_io_filter_connect(ssl_filter_ctx_t *filter_ctx)
1044 {
1045     conn_rec *c         = (conn_rec *)SSL_get_app_data(filter_ctx->pssl);
1046     SSLConnRec *sslconn = myConnConfig(c);
1047     SSLSrvConfigRec *sc = mySrvConfig(c->base_server);
1048     X509 *cert;
1049     int n;
1050     int ssl_err;
1051     long verify_result;
1052
1053     if (SSL_is_init_finished(filter_ctx->pssl)) {
1054         return APR_SUCCESS;
1055     }
1056
1057     if (sslconn->is_proxy) {
1058         if ((n = SSL_connect(filter_ctx->pssl)) <= 0) {
1059             ap_log_error(APLOG_MARK, APLOG_INFO, 0,
1060                          c->base_server,
1061                          "SSL Proxy connect failed");
1062             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
1063             return ssl_filter_io_shutdown(filter_ctx, c, 1);
1064         }
1065
1066         return APR_SUCCESS;
1067     }
1068
1069     if ((n = SSL_accept(filter_ctx->pssl)) <= 0) {
1070         bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)
1071                                      (filter_ctx->pbioRead->ptr);
1072         bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)
1073                                        (filter_ctx->pbioWrite->ptr);
1074         apr_status_t rc = inctx->rc ? inctx->rc : outctx->rc ;
1075         ssl_err = SSL_get_error(filter_ctx->pssl, n);
1076         
1077         if (ssl_err == SSL_ERROR_ZERO_RETURN) {
1078             /*
1079              * The case where the connection was closed before any data
1080              * was transferred. That's not a real error and can occur
1081              * sporadically with some clients.
1082              */
1083             ap_log_error(APLOG_MARK, APLOG_INFO, rc,
1084                          c->base_server,
1085                          "SSL handshake stopped: connection was closed");
1086         }
1087         else if (ssl_err == SSL_ERROR_WANT_READ) {
1088             /*
1089              * This is in addition to what was present earlier. It is 
1090              * borrowed from openssl_state_machine.c [mod_tls].
1091              * TBD.
1092              */
1093             outctx->rc = APR_EAGAIN;
1094             return SSL_ERROR_WANT_READ;
1095         }
1096         else if (ERR_GET_LIB(ERR_peek_error()) == ERR_LIB_SSL &&
1097                  ERR_GET_REASON(ERR_peek_error()) == SSL_R_HTTP_REQUEST) {
1098             /*
1099              * The case where OpenSSL has recognized a HTTP request:
1100              * This means the client speaks plain HTTP on our HTTPS port.
1101              * ssl_io_filter_error will disable the ssl filters when it
1102              * sees this status code.
1103              */
1104             return HTTP_BAD_REQUEST;
1105         }
1106         else if (ssl_err == SSL_ERROR_SYSCALL) {
1107             ap_log_error(APLOG_MARK, APLOG_INFO, rc, c->base_server,
1108                          "SSL handshake interrupted by system "
1109                          "[Hint: Stop button pressed in browser?!]");
1110         }
1111         else /* if (ssl_err == SSL_ERROR_SSL) */ {
1112             /*
1113              * Log SSL errors and any unexpected conditions.
1114              */
1115             ap_log_error(APLOG_MARK, APLOG_INFO, rc, c->base_server,
1116                          "SSL library error %d in handshake "
1117                          "(server %s, client %s)", ssl_err,
1118                          ssl_util_vhostid(c->pool, c->base_server),
1119                          c->remote_ip ? c->remote_ip : "unknown");
1120             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
1121
1122         }
1123         if (inctx->rc == APR_SUCCESS) {
1124             inctx->rc = APR_EGENERAL;
1125         }
1126
1127         return ssl_filter_io_shutdown(filter_ctx, c, 1);
1128     }
1129
1130     /*
1131      * Check for failed client authentication
1132      */
1133     verify_result = SSL_get_verify_result(filter_ctx->pssl);
1134
1135     if ((verify_result != X509_V_OK) ||
1136         sslconn->verify_error)
1137     {
1138         if (ssl_verify_error_is_optional(verify_result) &&
1139             (sc->server->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
1140         {
1141             /* leaving this log message as an error for the moment,
1142              * according to the mod_ssl docs:
1143              * "level optional_no_ca is actually against the idea
1144              *  of authentication (but can be used to establish 
1145              * SSL test pages, etc.)"
1146              * optional_no_ca doesn't appear to work as advertised
1147              * in 1.x
1148              */
1149             ap_log_error(APLOG_MARK, APLOG_INFO, 0,
1150                          c->base_server,
1151                          "SSL client authentication failed, "
1152                          "accepting certificate based on "
1153                          "\"SSLVerifyClient optional_no_ca\" "
1154                          "configuration");
1155             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
1156         }
1157         else {
1158             const char *error = sslconn->verify_error ?
1159                 sslconn->verify_error :
1160                 X509_verify_cert_error_string(verify_result);
1161
1162             ap_log_error(APLOG_MARK, APLOG_INFO, 0,
1163                          c->base_server,
1164                          "SSL client authentication failed: %s",
1165                          error ? error : "unknown");
1166             ssl_log_ssl_error(APLOG_MARK, APLOG_INFO, c->base_server);
1167
1168             return ssl_filter_io_shutdown(filter_ctx, c, 1);
1169         }
1170     }
1171
1172     /*
1173      * Remember the peer certificate's DN
1174      */
1175     if ((cert = SSL_get_peer_certificate(filter_ctx->pssl))) {
1176         if (sslconn->client_cert) {
1177             X509_free(sslconn->client_cert);
1178         }
1179         sslconn->client_cert = cert;
1180         sslconn->client_dn = NULL;
1181     }
1182
1183     /*
1184      * Make really sure that when a peer certificate
1185      * is required we really got one... (be paranoid)
1186      */
1187     if ((sc->server->auth.verify_mode == SSL_CVERIFY_REQUIRE) &&
1188         !sslconn->client_cert)
1189     {
1190         ap_log_error(APLOG_MARK, APLOG_INFO, 0, c->base_server,
1191                      "No acceptable peer certificate available");
1192
1193         return ssl_filter_io_shutdown(filter_ctx, c, 1);
1194     }
1195
1196     return APR_SUCCESS;
1197 }
1198
1199 static apr_status_t ssl_io_filter_input(ap_filter_t *f,
1200                                         apr_bucket_brigade *bb,
1201                                         ap_input_mode_t mode,
1202                                         apr_read_type_e block,
1203                                         apr_off_t readbytes)
1204 {
1205     apr_status_t status;
1206     bio_filter_in_ctx_t *inctx = f->ctx;
1207
1208     apr_size_t len = sizeof(inctx->buffer);
1209     int is_init = (mode == AP_MODE_INIT);
1210
1211     if (f->c->aborted) {
1212         /* XXX: Ok, if we aborted, we ARE at the EOS.  We also have
1213          * aborted.  This 'double protection' is probably redundant,
1214          * but also effective against just about anything.
1215          */
1216         apr_bucket *bucket = apr_bucket_eos_create(f->c->bucket_alloc);
1217         APR_BRIGADE_INSERT_TAIL(bb, bucket);
1218         return APR_ECONNABORTED;
1219     }
1220
1221     if (!inctx->ssl) {
1222         return ap_get_brigade(f->next, bb, mode, block, readbytes);
1223     }
1224
1225     /* XXX: we don't currently support anything other than these modes. */
1226     if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE && 
1227         mode != AP_MODE_SPECULATIVE && mode != AP_MODE_INIT) {
1228         return APR_ENOTIMPL;
1229     }
1230
1231     inctx->mode = mode;
1232     inctx->block = block;
1233
1234     /* XXX: we could actually move ssl_io_filter_connect to an
1235      * ap_hook_process_connection but would still need to call it for
1236      * AP_MODE_INIT for protocols that may upgrade the connection
1237      * rather than have SSLEngine On configured.
1238      */
1239     if ((status = ssl_io_filter_connect(inctx->filter_ctx)) != APR_SUCCESS) {
1240         return ssl_io_filter_error(f, bb, status);
1241     }
1242
1243     if (is_init) {
1244         /* protocol module needs to handshake before sending
1245          * data to client (e.g. NNTP or FTP)
1246          */
1247         return APR_SUCCESS;
1248     }
1249
1250     if (inctx->mode == AP_MODE_READBYTES || 
1251         inctx->mode == AP_MODE_SPECULATIVE) {
1252         /* Protected from truncation, readbytes < MAX_SIZE_T 
1253          * FIXME: No, it's *not* protected.  -- jre */
1254         if (readbytes < len) {
1255             len = (apr_size_t)readbytes;
1256         }
1257         status = ssl_io_input_read(inctx, inctx->buffer, &len);
1258     }
1259     else if (inctx->mode == AP_MODE_GETLINE) {
1260         status = ssl_io_input_getline(inctx, inctx->buffer, &len);
1261     }
1262     else {
1263         /* We have no idea what you are talking about, so return an error. */
1264         status = APR_ENOTIMPL;
1265     }
1266
1267     /* It is possible for mod_ssl's BIO to be used outside of the
1268      * direct control of mod_ssl's input or output filter -- notably,
1269      * when mod_ssl initiates a renegotiation.  Switching the BIO mode
1270      * back to "blocking" here ensures such operations don't fail with
1271      * SSL_ERROR_WANT_READ. */
1272     inctx->block = APR_BLOCK_READ;
1273
1274     /* Handle custom errors. */
1275     if (status != APR_SUCCESS) {
1276         return ssl_io_filter_error(f, bb, status);
1277     }
1278
1279     /* Create a transient bucket out of the decrypted data. */
1280     if (len > 0) {
1281         apr_bucket *bucket =
1282             apr_bucket_transient_create(inctx->buffer, len, f->c->bucket_alloc);
1283         APR_BRIGADE_INSERT_TAIL(bb, bucket);
1284     }
1285
1286     return APR_SUCCESS;
1287 }
1288
1289 static apr_status_t ssl_io_filter_output(ap_filter_t *f,
1290                                          apr_bucket_brigade *bb)
1291 {
1292     apr_status_t status = APR_SUCCESS;
1293     ssl_filter_ctx_t *filter_ctx = f->ctx;
1294     bio_filter_in_ctx_t *inctx;
1295     bio_filter_out_ctx_t *outctx;
1296     apr_read_type_e rblock = APR_NONBLOCK_READ;
1297
1298     if (f->c->aborted) {
1299         apr_brigade_cleanup(bb);
1300         return APR_ECONNABORTED;
1301     }
1302
1303     if (!filter_ctx->pssl) {
1304         /* ssl_filter_io_shutdown was called */
1305         return ap_pass_brigade(f->next, bb);
1306     }
1307
1308     inctx = (bio_filter_in_ctx_t *)filter_ctx->pbioRead->ptr;
1309     outctx = (bio_filter_out_ctx_t *)filter_ctx->pbioWrite->ptr;
1310
1311     /* When we are the writer, we must initialize the inctx
1312      * mode so that we block for any required ssl input, because
1313      * output filtering is always nonblocking.
1314      */
1315     inctx->mode = AP_MODE_READBYTES;
1316     inctx->block = APR_BLOCK_READ;
1317
1318     if ((status = ssl_io_filter_connect(filter_ctx)) != APR_SUCCESS) {
1319         return ssl_io_filter_error(f, bb, status);
1320     }
1321
1322     while (!APR_BRIGADE_EMPTY(bb)) {
1323         apr_bucket *bucket = APR_BRIGADE_FIRST(bb);
1324
1325         /* If it is a flush or EOS, we need to pass this down. 
1326          * These types do not require translation by OpenSSL.  
1327          */
1328         if (APR_BUCKET_IS_EOS(bucket) || APR_BUCKET_IS_FLUSH(bucket)) {
1329             if (bio_filter_out_flush(filter_ctx->pbioWrite) < 0) {
1330                 status = outctx->rc;
1331                 break;
1332             }
1333
1334             if (APR_BUCKET_IS_EOS(bucket)) {
1335                 /*
1336                  * By definition, nothing can come after EOS.
1337                  * which also means we can pass the rest of this brigade
1338                  * without creating a new one since it only contains the
1339                  * EOS bucket.
1340                  */
1341
1342                 if ((status = ap_pass_brigade(f->next, bb)) != APR_SUCCESS) {
1343                     return status;
1344                 }
1345                 break;
1346             }
1347             else {
1348                 /* bio_filter_out_flush() already passed down a flush bucket
1349                  * if there was any data to be flushed.
1350                  */
1351                 apr_bucket_delete(bucket);
1352             }
1353         }
1354         else if (AP_BUCKET_IS_EOC(bucket)) {
1355             /* The special "EOC" bucket means a shutdown is needed;
1356              * - turn off buffering in bio_filter_out_write
1357              * - issue the SSL_shutdown
1358              */
1359             filter_ctx->nobuffer = 1;
1360             status = ssl_filter_io_shutdown(filter_ctx, f->c, 0);
1361             if (status != APR_SUCCESS) {
1362                 ap_log_error(APLOG_MARK, APLOG_INFO, status, NULL,
1363                              "SSL filter error shutting down I/O");
1364             }
1365             if ((status = ap_pass_brigade(f->next, bb)) != APR_SUCCESS) {
1366                 return status;
1367             }
1368             break;
1369         }
1370         else {
1371             /* filter output */
1372             const char *data;
1373             apr_size_t len;
1374             
1375             status = apr_bucket_read(bucket, &data, &len, rblock);
1376
1377             if (APR_STATUS_IS_EAGAIN(status)) {
1378                 /* No data available: flush... */
1379                 if (bio_filter_out_flush(filter_ctx->pbioWrite) < 0) {
1380                     status = outctx->rc;
1381                     break;
1382                 }
1383                 rblock = APR_BLOCK_READ;
1384                 continue; /* and try again with a blocking read. */
1385             }
1386
1387             rblock = APR_NONBLOCK_READ;
1388
1389             if (!APR_STATUS_IS_EOF(status) && (status != APR_SUCCESS)) {
1390                 break;
1391             }
1392
1393             status = ssl_filter_write(f, data, len);
1394             apr_bucket_delete(bucket);
1395
1396             if (status != APR_SUCCESS) {
1397                 break;
1398             }
1399         }
1400     }
1401
1402     return status;
1403 }
1404
1405 /* 128K maximum buffer size by default. */
1406 #ifndef SSL_MAX_IO_BUFFER
1407 #define SSL_MAX_IO_BUFFER (128 * 1024)
1408 #endif
1409
1410 struct modssl_buffer_ctx {
1411     apr_bucket_brigade *bb;
1412     apr_pool_t *pool;
1413 };
1414
1415 int ssl_io_buffer_fill(request_rec *r)
1416 {
1417     conn_rec *c = r->connection;
1418     struct modssl_buffer_ctx *ctx;
1419     apr_bucket_brigade *tempb;
1420     apr_off_t total = 0; /* total length buffered */
1421     int eos = 0; /* non-zero once EOS is seen */
1422     
1423     /* Create the context which will be passed to the input filter;
1424      * containing a setaside pool and a brigade which constrain the
1425      * lifetime of the buffered data. */
1426     ctx = apr_palloc(r->pool, sizeof *ctx);
1427     apr_pool_create(&ctx->pool, r->pool);
1428     ctx->bb = apr_brigade_create(ctx->pool, c->bucket_alloc);
1429
1430     /* ... and a temporary brigade. */
1431     tempb = apr_brigade_create(r->pool, c->bucket_alloc);
1432
1433     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "filling buffer");
1434
1435     do {
1436         apr_status_t rv;
1437         apr_bucket *e, *next;
1438
1439         /* The request body is read from the protocol-level input
1440          * filters; the buffering filter will reinject it from that
1441          * level, allowing content/resource filters to run later, if
1442          * necessary. */
1443
1444         rv = ap_get_brigade(r->proto_input_filters, tempb, AP_MODE_READBYTES,
1445                             APR_BLOCK_READ, 8192);
1446         if (rv) {
1447             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1448                           "could not read request body for SSL buffer");
1449             return HTTP_INTERNAL_SERVER_ERROR;
1450         }
1451         
1452         /* Iterate through the returned brigade: setaside each bucket
1453          * into the context's pool and move it into the brigade. */
1454         for (e = APR_BRIGADE_FIRST(tempb); 
1455              e != APR_BRIGADE_SENTINEL(tempb) && !eos; e = next) {
1456             const char *data;
1457             apr_size_t len;
1458
1459             next = APR_BUCKET_NEXT(e);
1460
1461             if (APR_BUCKET_IS_EOS(e)) {
1462                 eos = 1;
1463             } else if (!APR_BUCKET_IS_METADATA(e)) {
1464                 rv = apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1465                 if (rv != APR_SUCCESS) {
1466                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1467                                   "could not read bucket for SSL buffer");
1468                     return HTTP_INTERNAL_SERVER_ERROR;
1469                 }
1470                 total += len;
1471             }
1472                 
1473             rv = apr_bucket_setaside(e, ctx->pool);
1474             if (rv != APR_SUCCESS) {
1475                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1476                               "could not setaside bucket for SSL buffer");
1477                 return HTTP_INTERNAL_SERVER_ERROR;
1478             }
1479             
1480             APR_BUCKET_REMOVE(e);
1481             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1482         }
1483
1484         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, 
1485                       "total of %" APR_OFF_T_FMT " bytes in buffer, eos=%d",
1486                       total, eos);
1487
1488         /* Fail if this exceeds the maximum buffer size. */
1489         if (total > SSL_MAX_IO_BUFFER) {
1490             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1491                           "request body exceeds maximum size for SSL buffer");
1492             return HTTP_REQUEST_ENTITY_TOO_LARGE;
1493         }
1494
1495     } while (!eos);
1496
1497     apr_brigade_destroy(tempb);
1498
1499     /* Insert the filter which will supply the buffered data. */
1500     ap_add_input_filter(ssl_io_buffer, ctx, r, c);
1501
1502     return 0;
1503 }
1504
1505 /* This input filter supplies the buffered request body to the caller
1506  * from the brigade stored in f->ctx. */
1507 static apr_status_t ssl_io_filter_buffer(ap_filter_t *f,
1508                                          apr_bucket_brigade *bb,
1509                                          ap_input_mode_t mode,
1510                                          apr_read_type_e block,
1511                                          apr_off_t bytes)
1512 {
1513     struct modssl_buffer_ctx *ctx = f->ctx;
1514     apr_status_t rv;
1515
1516     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, f->r,
1517                   "read from buffered SSL brigade, mode %d, "
1518                   "%" APR_OFF_T_FMT " bytes",
1519                   mode, bytes);
1520
1521     if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) {
1522         return APR_ENOTIMPL;
1523     }
1524
1525     if (mode == AP_MODE_READBYTES) {
1526         apr_bucket *e;
1527
1528         /* Partition the buffered brigade. */
1529         rv = apr_brigade_partition(ctx->bb, bytes, &e);
1530         if (rv && rv != APR_INCOMPLETE) {
1531             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, f->r,
1532                           "could not partition buffered SSL brigade");
1533             ap_remove_input_filter(f);
1534             return rv;
1535         }
1536
1537         /* If the buffered brigade contains less then the requested
1538          * length, just pass it all back. */
1539         if (rv == APR_INCOMPLETE) {
1540             APR_BRIGADE_CONCAT(bb, ctx->bb);
1541         } else {
1542             apr_bucket *d = APR_BRIGADE_FIRST(ctx->bb);
1543
1544             e = APR_BUCKET_PREV(e);
1545             
1546             /* Unsplice the partitioned segment and move it into the
1547              * passed-in brigade; no convenient way to do this with
1548              * the APR_BRIGADE_* macros. */
1549             APR_RING_UNSPLICE(d, e, link);
1550             APR_RING_SPLICE_HEAD(&bb->list, d, e, apr_bucket, link);
1551
1552             APR_BRIGADE_CHECK_CONSISTENCY(bb);
1553             APR_BRIGADE_CHECK_CONSISTENCY(ctx->bb);
1554         }
1555     }
1556     else {
1557         /* Split a line into the passed-in brigade. */
1558         rv = apr_brigade_split_line(bb, ctx->bb, mode, bytes);
1559
1560         if (rv) {
1561             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, f->r,
1562                           "could not split line from buffered SSL brigade");
1563             ap_remove_input_filter(f);
1564             return rv;
1565         }
1566     }
1567
1568     if (APR_BRIGADE_EMPTY(ctx->bb)) {
1569         apr_bucket *e = APR_BRIGADE_LAST(bb);
1570         
1571         /* Ensure that the brigade is terminated by an EOS if the
1572          * buffered request body has been entirely consumed. */
1573         if (e == APR_BRIGADE_SENTINEL(bb) || !APR_BUCKET_IS_EOS(e)) {
1574             e = apr_bucket_eos_create(f->c->bucket_alloc);
1575             APR_BRIGADE_INSERT_TAIL(bb, e);
1576         }
1577
1578         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, f->r,
1579                       "buffered SSL brigade now exhausted; removing filter");
1580         ap_remove_input_filter(f);
1581     }
1582
1583     return APR_SUCCESS;
1584 }
1585
1586 static void ssl_io_input_add_filter(ssl_filter_ctx_t *filter_ctx, conn_rec *c,
1587                                     SSL *ssl)
1588 {
1589     bio_filter_in_ctx_t *inctx;
1590
1591     inctx = apr_palloc(c->pool, sizeof(*inctx));
1592
1593     filter_ctx->pInputFilter = ap_add_input_filter(ssl_io_filter, inctx, NULL, c);
1594
1595     filter_ctx->pbioRead = BIO_new(&bio_filter_in_method);
1596     filter_ctx->pbioRead->ptr = (void *)inctx;
1597
1598     inctx->ssl = ssl;
1599     inctx->bio_out = filter_ctx->pbioWrite;
1600     inctx->f = filter_ctx->pInputFilter;
1601     inctx->rc = APR_SUCCESS;
1602     inctx->mode = AP_MODE_READBYTES;
1603     inctx->cbuf.length = 0;
1604     inctx->bb = apr_brigade_create(c->pool, c->bucket_alloc);
1605     inctx->block = APR_BLOCK_READ;
1606     inctx->pool = c->pool;
1607     inctx->filter_ctx = filter_ctx;
1608 }
1609
1610 void ssl_io_filter_init(conn_rec *c, SSL *ssl)
1611 {
1612     ssl_filter_ctx_t *filter_ctx;
1613
1614     filter_ctx = apr_palloc(c->pool, sizeof(ssl_filter_ctx_t));
1615
1616     filter_ctx->config          = myConnConfig(c);
1617
1618     filter_ctx->nobuffer        = 0;
1619     filter_ctx->pOutputFilter   = ap_add_output_filter(ssl_io_filter,
1620                                                    filter_ctx, NULL, c);
1621
1622     filter_ctx->pbioWrite       = BIO_new(&bio_filter_out_method);
1623     filter_ctx->pbioWrite->ptr  = (void *)bio_filter_out_ctx_new(filter_ctx, c);
1624
1625     ssl_io_input_add_filter(filter_ctx, c, ssl);
1626
1627     SSL_set_bio(ssl, filter_ctx->pbioRead, filter_ctx->pbioWrite);
1628     filter_ctx->pssl            = ssl;
1629
1630     apr_pool_cleanup_register(c->pool, (void*)filter_ctx,
1631                               ssl_io_filter_cleanup, apr_pool_cleanup_null);
1632
1633     if (c->base_server->loglevel >= APLOG_DEBUG) {
1634         BIO_set_callback(SSL_get_rbio(ssl), ssl_io_data_cb);
1635         BIO_set_callback_arg(SSL_get_rbio(ssl), (void *)ssl);
1636     }
1637
1638     return;
1639 }
1640
1641 void ssl_io_filter_register(apr_pool_t *p)
1642 {
1643     ap_register_input_filter  (ssl_io_filter, ssl_io_filter_input,  NULL, AP_FTYPE_CONNECTION + 5);
1644     ap_register_output_filter (ssl_io_filter, ssl_io_filter_output, NULL, AP_FTYPE_CONNECTION + 5);
1645     
1646     ap_register_input_filter  (ssl_io_buffer, ssl_io_filter_buffer, NULL, AP_FTYPE_PROTOCOL - 1);
1647
1648     return;
1649 }
1650
1651 /*  _________________________________________________________________
1652 **
1653 **  I/O Data Debugging
1654 **  _________________________________________________________________
1655 */
1656
1657 #define DUMP_WIDTH 16
1658
1659 static void ssl_io_data_dump(server_rec *srvr,
1660                              MODSSL_BIO_CB_ARG_TYPE *s,
1661                              long len)
1662 {
1663     char buf[256];
1664     char tmp[64];
1665     int i, j, rows, trunc;
1666     unsigned char ch;
1667
1668     trunc = 0;
1669     for(; (len > 0) && ((s[len-1] == ' ') || (s[len-1] == '\0')); len--)
1670         trunc++;
1671     rows = (len / DUMP_WIDTH);
1672     if ((rows * DUMP_WIDTH) < len)
1673         rows++;
1674     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, srvr,
1675             "+-------------------------------------------------------------------------+");
1676     for(i = 0 ; i< rows; i++) {
1677         apr_snprintf(tmp, sizeof(tmp), "| %04x: ", i * DUMP_WIDTH);
1678         apr_cpystrn(buf, tmp, sizeof(buf));
1679         for (j = 0; j < DUMP_WIDTH; j++) {
1680             if (((i * DUMP_WIDTH) + j) >= len)
1681                 apr_cpystrn(buf+strlen(buf), "   ", sizeof(buf)-strlen(buf));
1682             else {
1683                 ch = ((unsigned char)*((char *)(s) + i * DUMP_WIDTH + j)) & 0xff;
1684                 apr_snprintf(tmp, sizeof(tmp), "%02x%c", ch , j==7 ? '-' : ' ');
1685                 apr_cpystrn(buf+strlen(buf), tmp, sizeof(buf)-strlen(buf));
1686             }
1687         }
1688         apr_cpystrn(buf+strlen(buf), " ", sizeof(buf)-strlen(buf));
1689         for (j = 0; j < DUMP_WIDTH; j++) {
1690             if (((i * DUMP_WIDTH) + j) >= len)
1691                 apr_cpystrn(buf+strlen(buf), " ", sizeof(buf)-strlen(buf));
1692             else {
1693                 ch = ((unsigned char)*((char *)(s) + i * DUMP_WIDTH + j)) & 0xff;
1694                 apr_snprintf(tmp, sizeof(tmp), "%c", ((ch >= ' ') && (ch <= '~')) ? ch : '.');
1695                 apr_cpystrn(buf+strlen(buf), tmp, sizeof(buf)-strlen(buf));
1696             }
1697         }
1698         apr_cpystrn(buf+strlen(buf), " |", sizeof(buf)-strlen(buf));
1699         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, srvr,
1700                      "%s", buf);
1701     }
1702     if (trunc > 0)
1703         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, srvr,
1704                 "| %04ld - <SPACES/NULS>", len + trunc);
1705     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, srvr,
1706             "+-------------------------------------------------------------------------+");
1707     return;
1708 }
1709
1710 long ssl_io_data_cb(BIO *bio, int cmd,
1711                     MODSSL_BIO_CB_ARG_TYPE *argp,
1712                     int argi, long argl, long rc)
1713 {
1714     SSL *ssl;
1715     conn_rec *c;
1716     server_rec *s;
1717
1718     if ((ssl = (SSL *)BIO_get_callback_arg(bio)) == NULL)
1719         return rc;
1720     if ((c = (conn_rec *)SSL_get_app_data(ssl)) == NULL)
1721         return rc;
1722     s = c->base_server;
1723
1724     if (   cmd == (BIO_CB_WRITE|BIO_CB_RETURN)
1725         || cmd == (BIO_CB_READ |BIO_CB_RETURN) ) {
1726         if (rc >= 0) {
1727             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1728                     "%s: %s %ld/%d bytes %s BIO#%pp [mem: %pp] %s",
1729                     SSL_LIBRARY_NAME,
1730                     (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "write" : "read"),
1731                     rc, argi, (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "to" : "from"),
1732                     bio, argp,
1733                     (argp != NULL ? "(BIO dump follows)" : "(Oops, no memory buffer?)"));
1734             if (argp != NULL)
1735                 ssl_io_data_dump(s, argp, rc);
1736         }
1737         else {
1738             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1739                     "%s: I/O error, %d bytes expected to %s on BIO#%pp [mem: %pp]",
1740                     SSL_LIBRARY_NAME, argi,
1741                     (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "write" : "read"),
1742                     bio, argp);
1743         }
1744     }
1745     return rc;
1746 }