source: mod_gnutls/src/gnutls_io.c @ fcb122d

asynciodebian/masterdebian/stretch-backportsjessie-backportsmainmsvaproxy-ticketupstream
Last change on this file since fcb122d was fcb122d, checked in by Paul Querna <chip@…>, 18 years ago

checkpoint the work so far. The DBM cache needs a little more work.

  • Property mode set to 100644
File size: 19.4 KB
Line 
1/**
2 *  Copyright 2004-2005 Paul Querna
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  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#include "mod_gnutls.h"
19
20/**
21 * Describe how the GnuTLS Filter system works here
22 *  - Basicly the same as what mod_ssl does with OpenSSL.
23 *
24 */
25
26#define HTTP_ON_HTTPS_PORT \
27    "GET /" CRLF
28
29#define HTTP_ON_HTTPS_PORT_BUCKET(alloc) \
30    apr_bucket_immortal_create(HTTP_ON_HTTPS_PORT, \
31                               sizeof(HTTP_ON_HTTPS_PORT) - 1, \
32                               alloc)
33
34static apr_status_t gnutls_io_filter_error(ap_filter_t * f,
35                                           apr_bucket_brigade * bb,
36                                           apr_status_t status)
37{
38    mod_gnutls_handle_t *ctxt = (mod_gnutls_handle_t *) f->ctx;
39    apr_bucket *bucket;
40
41    switch (status) {
42    case HTTP_BAD_REQUEST:
43        /* log the situation */
44        ap_log_error(APLOG_MARK, APLOG_INFO, 0,
45                     f->c->base_server,
46                     "GnuTLS handshake failed: HTTP spoken on HTTPS port; "
47                     "trying to send HTML error page");
48
49        ctxt->status = -1;
50
51        /* fake the request line */
52        bucket = HTTP_ON_HTTPS_PORT_BUCKET(f->c->bucket_alloc);
53        break;
54
55    default:
56        return status;
57    }
58
59    APR_BRIGADE_INSERT_TAIL(bb, bucket);
60    bucket = apr_bucket_eos_create(f->c->bucket_alloc);
61    APR_BRIGADE_INSERT_TAIL(bb, bucket);
62
63    return APR_SUCCESS;
64}
65
66static int char_buffer_read(mod_gnutls_char_buffer_t * buffer, char *in,
67                            int inl)
68{
69    if (!buffer->length) {
70        return 0;
71    }
72
73    if (buffer->length > inl) {
74        /* we have have enough to fill the caller's buffer */
75        memcpy(in, buffer->value, inl);
76        buffer->value += inl;
77        buffer->length -= inl;
78    }
79    else {
80        /* swallow remainder of the buffer */
81        memcpy(in, buffer->value, buffer->length);
82        inl = buffer->length;
83        buffer->value = NULL;
84        buffer->length = 0;
85    }
86
87    return inl;
88}
89
90static int char_buffer_write(mod_gnutls_char_buffer_t * buffer, char *in,
91                             int inl)
92{
93    buffer->value = in;
94    buffer->length = inl;
95    return inl;
96}
97
98/**
99 * From mod_ssl / ssl_engine_io.c
100 * This function will read from a brigade and discard the read buckets as it
101 * proceeds.  It will read at most *len bytes.
102 */
103static apr_status_t brigade_consume(apr_bucket_brigade * bb,
104                                    apr_read_type_e block,
105                                    char *c, apr_size_t * len)
106{
107    apr_size_t actual = 0;
108    apr_status_t status = APR_SUCCESS;
109
110    while (!APR_BRIGADE_EMPTY(bb)) {
111        apr_bucket *b = APR_BRIGADE_FIRST(bb);
112        const char *str;
113        apr_size_t str_len;
114        apr_size_t consume;
115
116        /* Justin points out this is an http-ism that might
117         * not fit if brigade_consume is added to APR.  Perhaps
118         * apr_bucket_read(eos_bucket) should return APR_EOF?
119         * Then this becomes mainline instead of a one-off.
120         */
121        if (APR_BUCKET_IS_EOS(b)) {
122            status = APR_EOF;
123            break;
124        }
125
126        /* The reason I'm not offering brigade_consume yet
127         * across to apr-util is that the following call
128         * illustrates how borked that API really is.  For
129         * this sort of case (caller provided buffer) it
130         * would be much more trivial for apr_bucket_consume
131         * to do all the work that follows, based on the
132         * particular characteristics of the bucket we are
133         * consuming here.
134         */
135        status = apr_bucket_read(b, &str, &str_len, block);
136
137        if (status != APR_SUCCESS) {
138            if (APR_STATUS_IS_EOF(status)) {
139                /* This stream bucket was consumed */
140                apr_bucket_delete(b);
141                continue;
142            }
143            break;
144        }
145
146        if (str_len > 0) {
147            /* Do not block once some data has been consumed */
148            block = APR_NONBLOCK_READ;
149
150            /* Assure we don't overflow. */
151            consume = (str_len + actual > *len) ? *len - actual : str_len;
152
153            memcpy(c, str, consume);
154
155            c += consume;
156            actual += consume;
157
158            if (consume >= b->length) {
159                /* This physical bucket was consumed */
160                apr_bucket_delete(b);
161            }
162            else {
163                /* Only part of this physical bucket was consumed */
164                b->start += consume;
165                b->length -= consume;
166            }
167        }
168        else if (b->length == 0) {
169            apr_bucket_delete(b);
170        }
171
172        /* This could probably be actual == *len, but be safe from stray
173         * photons. */
174        if (actual >= *len) {
175            break;
176        }
177    }
178
179    *len = actual;
180    return status;
181}
182
183
184static apr_status_t gnutls_io_input_read(mod_gnutls_handle_t * ctxt,
185                                         char *buf, apr_size_t * len)
186{
187    apr_size_t wanted = *len;
188    apr_size_t bytes = 0;
189    int rc;
190
191    *len = 0;
192
193    /* If we have something leftover from last time, try that first. */
194    if ((bytes = char_buffer_read(&ctxt->input_cbuf, buf, wanted))) {
195        *len = bytes;
196        if (ctxt->input_mode == AP_MODE_SPECULATIVE) {
197            /* We want to rollback this read. */
198            if (ctxt->input_cbuf.length > 0) {
199                ctxt->input_cbuf.value -= bytes;
200                ctxt->input_cbuf.length += bytes;
201            }
202            else {
203                char_buffer_write(&ctxt->input_cbuf, buf, (int) bytes);
204            }
205            return APR_SUCCESS;
206        }
207        /* This could probably be *len == wanted, but be safe from stray
208         * photons.
209         */
210        if (*len >= wanted) {
211            return APR_SUCCESS;
212        }
213        if (ctxt->input_mode == AP_MODE_GETLINE) {
214            if (memchr(buf, APR_ASCII_LF, *len)) {
215                return APR_SUCCESS;
216            }
217        }
218        else {
219            /* Down to a nonblock pattern as we have some data already
220             */
221            ctxt->input_block = APR_NONBLOCK_READ;
222        }
223    }
224
225    while (1) {
226
227        rc = gnutls_record_recv(ctxt->session, buf + bytes, wanted - bytes);
228
229        if (rc > 0) {
230            *len += rc;
231            if (ctxt->input_mode == AP_MODE_SPECULATIVE) {
232                /* We want to rollback this read. */
233                char_buffer_write(&ctxt->input_cbuf, buf, rc);
234            }
235            return ctxt->input_rc;
236        }
237        else if (rc == 0) {
238            /* If EAGAIN, we will loop given a blocking read,
239             * otherwise consider ourselves at EOF.
240             */
241            if (APR_STATUS_IS_EAGAIN(ctxt->input_rc)
242                || APR_STATUS_IS_EINTR(ctxt->input_rc)) {
243                /* Already read something, return APR_SUCCESS instead.
244                 * On win32 in particular, but perhaps on other kernels,
245                 * a blocking call isn't 'always' blocking.
246                 */
247                if (*len > 0) {
248                    ctxt->input_rc = APR_SUCCESS;
249                    break;
250                }
251                if (ctxt->input_block == APR_NONBLOCK_READ) {
252                    break;
253                }
254            }
255            else {
256                if (*len > 0) {
257                    ctxt->input_rc = APR_SUCCESS;
258                }
259                else {
260                    ctxt->input_rc = APR_EOF;
261                }
262                break;
263            }
264        }
265        else {                  /* (rc < 0) */
266
267            if (rc == GNUTLS_E_REHANDSHAKE) {
268                /* A client has asked for a new Hankshake. Currently, we don't do it */
269                ap_log_error(APLOG_MARK, APLOG_INFO, ctxt->input_rc,
270                             ctxt->c->base_server,
271                             "GnuTLS: Error reading data. Client Requested a New Handshake."
272                             " (%d) '%s'", rc, gnutls_strerror(rc));
273            }
274            else {
275                /* Some Other Error. Report it. Die. */
276                if(gnutls_error_is_fatal(rc)) {
277                    ap_log_error(APLOG_MARK, APLOG_INFO, ctxt->input_rc,
278                                 ctxt->c->base_server,
279                                 "GnuTLS: Error reading data. (%d) '%s'", rc,
280                                 gnutls_strerror(rc));
281                }
282                else if(*len > 0) {
283                    ctxt->input_rc = APR_SUCCESS;
284                    break;
285                }
286            }
287
288            if (ctxt->input_rc == APR_SUCCESS) {
289                ctxt->input_rc = APR_EGENERAL;
290            }
291            break;
292        }
293    }
294    return ctxt->input_rc;
295}
296
297static apr_status_t gnutls_io_input_getline(mod_gnutls_handle_t * ctxt,
298                                            char *buf, apr_size_t * len)
299{
300    const char *pos = NULL;
301    apr_status_t status;
302    apr_size_t tmplen = *len, buflen = *len, offset = 0;
303
304    *len = 0;
305
306    while (tmplen > 0) {
307        status = gnutls_io_input_read(ctxt, buf + offset, &tmplen);
308
309        if (status != APR_SUCCESS) {
310            return status;
311        }
312
313        *len += tmplen;
314
315        if ((pos = memchr(buf, APR_ASCII_LF, *len))) {
316            break;
317        }
318
319        offset += tmplen;
320        tmplen = buflen - offset;
321    }
322
323    if (pos) {
324        char *value;
325        int length;
326        apr_size_t bytes = pos - buf;
327
328        bytes += 1;
329        value = buf + bytes;
330        length = *len - bytes;
331
332        char_buffer_write(&ctxt->input_cbuf, value, length);
333
334        *len = bytes;
335    }
336
337    return APR_SUCCESS;
338}
339
340
341static void gnutls_do_handshake(mod_gnutls_handle_t * ctxt)
342{
343    int ret;
344
345    if (ctxt->status != 0) {
346        return;
347    }
348
349tryagain:
350
351    ret = gnutls_handshake(ctxt->session);
352    if (ret < 0) {
353        if (ret == GNUTLS_E_WARNING_ALERT_RECEIVED
354            || ret == GNUTLS_E_FATAL_ALERT_RECEIVED) {
355            ret = gnutls_alert_get(ctxt->session);
356            ap_log_error(APLOG_MARK, APLOG_ERR, 0, ctxt->c->base_server,
357                         "GnuTLS: Hanshake Alert (%d) '%s'.\n", ret,
358                         gnutls_alert_get_name(ret));
359        }
360   
361        if (!gnutls_error_is_fatal(ret)) {
362            ap_log_error(APLOG_MARK, APLOG_INFO, 0, ctxt->c->base_server,
363                     "GnuTLS: Non-Fatal Handshake Error: (%d) '%s'", ret,
364                      gnutls_strerror(ret));
365            goto tryagain;
366        }
367
368        ap_log_error(APLOG_MARK, APLOG_ERR, 0, ctxt->c->base_server,
369                     "GnuTLS: Handshake Failed (%d) '%s'", ret,
370                      gnutls_strerror(ret));
371        ctxt->status = -1;
372        gnutls_alert_send(ctxt->session, GNUTLS_AL_FATAL, 
373                          gnutls_error_to_alert(ret, NULL));
374        gnutls_deinit(ctxt->session);
375        return;
376    }
377    else {
378        ctxt->status = 1;
379        return;             /* all done with the handshake */
380    }
381}
382
383
384apr_status_t mod_gnutls_filter_input(ap_filter_t* f,
385                                     apr_bucket_brigade * bb,
386                                     ap_input_mode_t mode,
387                                     apr_read_type_e block,
388                                     apr_off_t readbytes)
389{
390    apr_status_t status = APR_SUCCESS;
391    mod_gnutls_handle_t *ctxt = (mod_gnutls_handle_t *) f->ctx;
392    apr_size_t len = sizeof(ctxt->input_buffer);
393
394    if (f->c->aborted) {
395        apr_bucket *bucket = apr_bucket_eos_create(f->c->bucket_alloc);
396        APR_BRIGADE_INSERT_TAIL(bb, bucket);
397        return APR_ECONNABORTED;
398    }
399
400    if (ctxt->status == 0) {
401        gnutls_do_handshake(ctxt);
402    }
403
404    if (ctxt->status < 0) {
405        return ap_get_brigade(f->next, bb, mode, block, readbytes);
406    }
407
408    /* XXX: we don't currently support anything other than these modes. */
409    if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE &&
410        mode != AP_MODE_SPECULATIVE && mode != AP_MODE_INIT) {
411        return APR_ENOTIMPL;
412    }
413
414    ctxt->input_mode = mode;
415    ctxt->input_block = block;
416
417    if (ctxt->input_mode == AP_MODE_READBYTES ||
418        ctxt->input_mode == AP_MODE_SPECULATIVE) {
419        /* Err. This is bad. readbytes *can* be a 64bit int! len.. is NOT */
420        if (readbytes < len) {
421            len = (apr_size_t) readbytes;
422        }
423        status = gnutls_io_input_read(ctxt, ctxt->input_buffer, &len);
424    }
425    else if (ctxt->input_mode == AP_MODE_GETLINE) {
426        status = gnutls_io_input_getline(ctxt, ctxt->input_buffer, &len);
427    }
428    else {
429        /* We have no idea what you are talking about, so return an error. */
430        return APR_ENOTIMPL;
431    }
432
433    if (status != APR_SUCCESS) {
434        return gnutls_io_filter_error(f, bb, status);
435    }
436
437    /* Create a transient bucket out of the decrypted data. */
438    if (len > 0) {
439        apr_bucket *bucket =
440            apr_bucket_transient_create(ctxt->input_buffer, len,
441                                        f->c->bucket_alloc);
442        APR_BRIGADE_INSERT_TAIL(bb, bucket);
443    }
444
445    return status;
446}
447
448apr_status_t mod_gnutls_filter_output(ap_filter_t * f,
449                                      apr_bucket_brigade * bb)
450{
451    apr_size_t ret;
452    mod_gnutls_handle_t *ctxt = (mod_gnutls_handle_t *) f->ctx;
453    apr_status_t status = APR_SUCCESS;
454    apr_read_type_e rblock = APR_NONBLOCK_READ;
455
456    if (f->c->aborted) {
457        apr_brigade_cleanup(bb);
458        return APR_ECONNABORTED;
459    }
460
461    if (ctxt->status == 0) {
462        gnutls_do_handshake(ctxt);
463    }
464
465    if (ctxt->status < 0) {
466        return ap_pass_brigade(f->next, bb);
467    }
468
469    while (!APR_BRIGADE_EMPTY(bb)) {
470        apr_bucket *bucket = APR_BRIGADE_FIRST(bb);
471        if (AP_BUCKET_IS_EOC(bucket)) {
472
473            gnutls_bye(ctxt->session, GNUTLS_SHUT_WR);
474            gnutls_deinit(ctxt->session);
475
476            if ((status = ap_pass_brigade(f->next, bb)) != APR_SUCCESS) {
477                return status;
478            }
479            break;
480
481        } else if (APR_BUCKET_IS_FLUSH(bucket) || APR_BUCKET_IS_EOS(bucket)) {
482
483            if ((status = ap_pass_brigade(f->next, bb)) != APR_SUCCESS) {
484                return status;
485            }
486            break;
487        }
488        else {
489            /* filter output */
490            const char *data;
491            apr_size_t len;
492
493            status = apr_bucket_read(bucket, &data, &len, rblock);
494
495            if (APR_STATUS_IS_EAGAIN(status)) {
496                rblock = APR_BLOCK_READ;
497                continue;       /* and try again with a blocking read. */
498            }
499
500            rblock = APR_NONBLOCK_READ;
501
502            if (!APR_STATUS_IS_EOF(status) && (status != APR_SUCCESS)) {
503                break;
504            }
505
506            do {
507                ret = gnutls_record_send(ctxt->session, data, len);
508            }
509            while(ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
510
511            if (ret < 0) {
512                /* error sending output */
513                ap_log_error(APLOG_MARK, APLOG_INFO, ctxt->output_rc,
514                             ctxt->c->base_server,
515                             "GnuTLS: Error writing data."
516                             " (%d) '%s'", ret, gnutls_strerror(ret));
517                if (ctxt->output_rc == APR_SUCCESS) {
518                    ctxt->output_rc = APR_EGENERAL;
519                }
520            }
521            else if (ret != len) {
522                /* Not able to send the entire bucket,
523                   split it and send it again. */
524                apr_bucket_split(bucket, ret);
525            }
526
527            apr_bucket_delete(bucket);
528
529            if (ctxt->output_rc != APR_SUCCESS) {
530                break;
531            }
532        }
533    }
534
535    return status;
536}
537
538ssize_t mod_gnutls_transport_read(gnutls_transport_ptr_t ptr,
539                                  void *buffer, size_t len)
540{
541    mod_gnutls_handle_t *ctxt = ptr;
542    apr_status_t rc;
543    apr_size_t in = len;
544    apr_read_type_e block = ctxt->input_block;
545
546    ctxt->input_rc = APR_SUCCESS;
547
548    /* If Len = 0, we don't do anything. */
549    if (!len)
550        return 0;
551
552    if (!ctxt->input_bb) {
553        ctxt->input_rc = APR_EOF;
554        return -1;
555    }
556
557    if (APR_BRIGADE_EMPTY(ctxt->input_bb)) {
558
559        rc = ap_get_brigade(ctxt->input_filter->next, ctxt->input_bb,
560                            AP_MODE_READBYTES, ctxt->input_block, in);
561
562        /* Not a problem, there was simply no data ready yet.
563         */
564        if (APR_STATUS_IS_EAGAIN(rc) || APR_STATUS_IS_EINTR(rc)
565            || (rc == APR_SUCCESS && APR_BRIGADE_EMPTY(ctxt->input_bb))) {
566            return 0;
567        }
568
569        if (rc != APR_SUCCESS) {
570            /* Unexpected errors discard the brigade */
571            apr_brigade_cleanup(ctxt->input_bb);
572            ctxt->input_bb = NULL;
573            return -1;
574        }
575    }
576
577    ctxt->input_rc = brigade_consume(ctxt->input_bb, block, buffer, &len);
578
579    if (ctxt->input_rc == APR_SUCCESS) {
580        return (ssize_t) len;
581    }
582
583    if (APR_STATUS_IS_EAGAIN(ctxt->input_rc)
584        || APR_STATUS_IS_EINTR(ctxt->input_rc)) {
585        return (ssize_t) len;
586    }
587
588    /* Unexpected errors and APR_EOF clean out the brigade.
589     * Subsequent calls will return APR_EOF.
590     */
591    apr_brigade_cleanup(ctxt->input_bb);
592    ctxt->input_bb = NULL;
593
594    if (APR_STATUS_IS_EOF(ctxt->input_rc) && len) {
595        /* Provide the results of this read pass,
596         * without resetting the BIO retry_read flag
597         */
598        return (ssize_t) len;
599    }
600
601    return -1;
602}
603
604
605static ssize_t write_flush(mod_gnutls_handle_t * ctxt)
606{
607    apr_bucket *e;
608
609    if (!(ctxt->output_blen || ctxt->output_length)) {
610        ctxt->output_rc = APR_SUCCESS;
611        return 1;
612    }
613
614    if (ctxt->output_blen) {
615        e = apr_bucket_transient_create(ctxt->output_buffer,
616                                        ctxt->output_blen,
617                                        ctxt->output_bb->bucket_alloc);
618        /* we filled this buffer first so add it to the
619         * head of the brigade
620         */
621        APR_BRIGADE_INSERT_HEAD(ctxt->output_bb, e);
622        ctxt->output_blen = 0;
623    }
624
625    ctxt->output_length = 0;
626    e = apr_bucket_flush_create(ctxt->output_bb->bucket_alloc);
627    APR_BRIGADE_INSERT_TAIL(ctxt->output_bb, e);
628
629    ctxt->output_rc = ap_pass_brigade(ctxt->output_filter->next,
630                                      ctxt->output_bb);
631    /* create new brigade ready for next time through */
632    ctxt->output_bb =
633        apr_brigade_create(ctxt->c->pool, ctxt->c->bucket_alloc);
634    return (ctxt->output_rc == APR_SUCCESS) ? 1 : -1;
635}
636
637ssize_t mod_gnutls_transport_write(gnutls_transport_ptr_t ptr,
638                                   const void *buffer, size_t len)
639{
640    mod_gnutls_handle_t *ctxt = ptr;
641
642        /* pass along the encrypted data
643         * need to flush since we're using SSL's malloc-ed buffer
644         * which will be overwritten once we leave here
645         */
646        apr_bucket *bucket = apr_bucket_transient_create(buffer, len,
647                                                         ctxt->output_bb->
648                                                         bucket_alloc);
649
650        ctxt->output_length += len;
651        APR_BRIGADE_INSERT_TAIL(ctxt->output_bb, bucket);
652
653        if (write_flush(ctxt) < 0) {
654            return -1;
655        }
656    return len;
657}
Note: See TracBrowser for help on using the repository browser.