~ubuntu-branches/ubuntu/feisty/apache2/feisty

« back to all changes in this revision

Viewing changes to modules/ssl/ssl_engine_io.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Barth
  • Date: 2006-12-09 21:05:45 UTC
  • mfrom: (0.6.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20061209210545-h70s0xaqc2v8vqr2
Tags: 2.2.3-3.2
* Non-maintainer upload.
* 043_ajp_connection_reuse: Patch from upstream Bugzilla, fixing a critical
  issue with regard to connection reuse in mod_proxy_ajp.
  Closes: #396265

Show diffs side-by-side

added added

removed removed

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