Coverage Report

Created: 2026-12-01 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httpd/server/protocol.c
Line
Count
Source
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
 * protocol.c --- routines which directly communicate with the client.
19
 *
20
 * Code originally by Rob McCool; much redone by Robert S. Thau
21
 * and the Apache Software Foundation.
22
 */
23
24
#include "apr.h"
25
#include "apr_strings.h"
26
#include "apr_buckets.h"
27
#include "apr_lib.h"
28
#include "apr_signal.h"
29
#include "apr_strmatch.h"
30
31
#define APR_WANT_STDIO          /* for sscanf */
32
#define APR_WANT_STRFUNC
33
#define APR_WANT_MEMFUNC
34
#include "apr_want.h"
35
36
#include "util_filter.h"
37
#include "ap_config.h"
38
#include "httpd.h"
39
#include "http_config.h"
40
#include "http_core.h"
41
#include "http_protocol.h"
42
#include "http_main.h"
43
#include "http_request.h"
44
#include "http_vhost.h"
45
#include "http_ssl.h"
46
#include "http_log.h"           /* For errors detected in basic auth common
47
                                 * support code... */
48
#include "mod_core.h"
49
#include "util_charset.h"
50
#include "util_ebcdic.h"
51
#include "util_time.h"
52
#include "scoreboard.h"
53
54
#if APR_HAVE_STDARG_H
55
#include <stdarg.h>
56
#endif
57
#if APR_HAVE_UNISTD_H
58
#include <unistd.h>
59
#endif
60
61
/* we know core's module_index is 0 */
62
#undef APLOG_MODULE_INDEX
63
#define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
64
65
APR_HOOK_STRUCT(
66
    APR_HOOK_LINK(pre_read_request)
67
    APR_HOOK_LINK(post_read_request)
68
    APR_HOOK_LINK(log_transaction)
69
    APR_HOOK_LINK(http_scheme)
70
    APR_HOOK_LINK(default_port)
71
    APR_HOOK_LINK(note_auth_failure)
72
    APR_HOOK_LINK(protocol_propose)
73
    APR_HOOK_LINK(protocol_switch)
74
    APR_HOOK_LINK(protocol_get)
75
)
76
77
AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
78
79
80
/* Patterns to match in ap_make_content_type() */
81
static const char *const needcset[] = {
82
    "text/plain",
83
    "text/html",
84
    NULL
85
};
86
static const apr_strmatch_pattern **needcset_patterns;
87
static const apr_strmatch_pattern *charset_pattern;
88
89
AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
90
0
{
91
0
    int i;
92
0
    for (i = 0; needcset[i]; i++) {
93
0
        continue;
94
0
    }
95
0
    needcset_patterns = (const apr_strmatch_pattern **)
96
0
        apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
97
0
    for (i = 0; needcset[i]; i++) {
98
0
        needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
99
0
    }
100
0
    needcset_patterns[i] = NULL;
101
0
    charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
102
0
}
103
104
/*
105
 * Builds the content-type that should be sent to the client from the
106
 * content-type specified.  The following rules are followed:
107
 *    - if type is NULL or "", return NULL (do not set content-type).
108
 *    - if charset adding is disabled, stop processing and return type.
109
 *    - then, if there are no parameters on type, add the default charset
110
 *    - return type
111
 */
112
AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
113
0
{
114
0
    const apr_strmatch_pattern **pcset;
115
0
    core_dir_config *conf =
116
0
        (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
117
0
    core_request_config *request_conf;
118
0
    apr_size_t type_len;
119
120
0
    if (!type || *type == '\0') {
121
0
        return NULL;
122
0
    }
123
124
0
    if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
125
0
        return type;
126
0
    }
127
128
0
    request_conf = ap_get_core_module_config(r->request_config);
129
0
    if (request_conf->suppress_charset) {
130
0
        return type;
131
0
    }
132
133
0
    type_len = strlen(type);
134
135
0
    if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
136
        /* already has parameter, do nothing */
137
        /* XXX we don't check the validity */
138
0
        ;
139
0
    }
140
0
    else {
141
        /* see if it makes sense to add the charset. At present,
142
         * we only add it if the Content-type is one of needcset[]
143
         */
144
0
        for (pcset = needcset_patterns; *pcset ; pcset++) {
145
0
            if (apr_strmatch(*pcset, type, type_len) != NULL) {
146
0
                struct iovec concat[3];
147
0
                concat[0].iov_base = (void *)type;
148
0
                concat[0].iov_len = type_len;
149
0
                concat[1].iov_base = (void *)"; charset=";
150
0
                concat[1].iov_len = sizeof("; charset=") - 1;
151
0
                concat[2].iov_base = (void *)(conf->add_default_charset_name);
152
0
                concat[2].iov_len = strlen(conf->add_default_charset_name);
153
0
                type = apr_pstrcatv(r->pool, concat, 3, NULL);
154
0
                break;
155
0
            }
156
0
        }
157
0
    }
158
159
0
    return type;
160
0
}
161
162
AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
163
0
{
164
0
    r->clength = clength;
165
0
    apr_table_setn(r->headers_out, "Content-Length",
166
0
                   apr_off_t_toa(r->pool, clength));
167
0
}
168
169
/*
170
 * Return the latest rational time from a request/mtime (modification time)
171
 * pair.  We return the mtime unless it's in the future, in which case we
172
 * return the current time.  We use the request time as a reference in order
173
 * to limit the number of calls to time().  We don't check for futurosity
174
 * unless the mtime is at least as new as the reference.
175
 */
176
AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
177
0
{
178
0
    apr_time_t now;
179
180
    /* For all static responses, it's almost certain that the file was
181
     * last modified before the beginning of the request.  So there's
182
     * no reason to call time(NULL) again.  But if the response has been
183
     * created on demand, then it might be newer than the time the request
184
     * started.  In this event we really have to call time(NULL) again
185
     * so that we can give the clients the most accurate Last-Modified.  If we
186
     * were given a time in the future, we return the current time - the
187
     * Last-Modified can't be in the future.
188
     */
189
0
    now = (mtime < r->request_time) ? r->request_time : apr_time_now();
190
0
    return (mtime > now) ? now : mtime;
191
0
}
192
193
/* Get a line from an input filter, including any continuation lines
194
 * caused by MIME folding (or broken clients) if fold != 0, and place it
195
 * in the buffer s, of size n bytes, without the ending newline.
196
 *
197
 * If s is NULL, ap_fgetline_core will allocate necessary memory from p.
198
 *
199
 * Returns APR_SUCCESS if there are no problems and sets *read to be
200
 * the full length of s.
201
 *
202
 * APR_ENOSPC is returned if there is not enough buffer space.
203
 * Other errors may be returned on other errors.
204
 *
205
 * The [CR]LF are *not* returned in the buffer.  Therefore, a *read of 0
206
 * indicates that an empty line was read.
207
 *
208
 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
209
 *        (n - 1) actual characters.
210
 *
211
 *        If no LF is detected on the last line due to a dropped connection
212
 *        or a full buffer, that's considered an error.
213
 */
214
static apr_status_t ap_fgetline_core(char **s, apr_size_t n,
215
                                     apr_size_t *read, ap_filter_t *f,
216
                                     int flags, apr_bucket_brigade *bb,
217
                                     apr_pool_t *p)
218
0
{
219
0
    apr_status_t rv;
220
0
    apr_bucket *e;
221
0
    apr_size_t bytes_handled = 0, current_alloc = 0;
222
0
    char *pos, *last_char = *s;
223
0
    int do_alloc = (*s == NULL), saw_eos = 0;
224
0
    int fold = flags & AP_GETLINE_FOLD;
225
0
    int crlf = flags & AP_GETLINE_CRLF;
226
0
    int nospc_eol = flags & AP_GETLINE_NOSPC_EOL;
227
0
    int saw_eol = 0, saw_nospc = 0;
228
0
    apr_read_type_e block;
229
230
0
    if (!n) {
231
        /* Needs room for NUL byte at least */
232
0
        *read = 0;
233
0
        return APR_BADARG;
234
0
    }
235
236
0
    block = (flags & AP_GETLINE_NONBLOCK) ? APR_NONBLOCK_READ
237
0
                                          : APR_BLOCK_READ;
238
239
    /*
240
     * Initialize last_char as otherwise a random value will be compared
241
     * against APR_ASCII_LF at the end of the loop if bb only contains
242
     * zero-length buckets.
243
     */
244
0
    if (last_char)
245
0
        *last_char = '\0';
246
247
0
    do {
248
0
        apr_brigade_cleanup(bb);
249
0
        rv = ap_get_brigade(f, bb, AP_MODE_GETLINE, block, 0);
250
0
        if (rv != APR_SUCCESS) {
251
0
            goto cleanup;
252
0
        }
253
254
        /* Something horribly wrong happened.  Someone didn't block! 
255
         * (this also happens at the end of each keepalive connection)
256
         * (this also happens when non-blocking is asked too, not that wrong)
257
         */
258
0
        if (APR_BRIGADE_EMPTY(bb)) {
259
0
            if (block != APR_NONBLOCK_READ) {
260
0
                rv = APR_EGENERAL;
261
0
            }
262
0
            else {
263
0
                rv = APR_EAGAIN;
264
0
            }
265
0
            goto cleanup;
266
0
        }
267
268
0
        for (e = APR_BRIGADE_FIRST(bb);
269
0
             e != APR_BRIGADE_SENTINEL(bb);
270
0
             e = APR_BUCKET_NEXT(e))
271
0
        {
272
0
            const char *str;
273
0
            apr_size_t len;
274
275
            /* If we see an EOS, don't bother doing anything more. */
276
0
            if (APR_BUCKET_IS_EOS(e)) {
277
0
                saw_eos = 1;
278
0
                break;
279
0
            }
280
281
0
            rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
282
0
            if (rv != APR_SUCCESS) {
283
0
                goto cleanup;
284
0
            }
285
286
0
            if (len == 0) {
287
                /* no use attempting a zero-byte alloc (hurts when
288
                 * using --with-efence --enable-pool-debug) or
289
                 * doing any of the other logic either
290
                 */
291
0
                continue;
292
0
            }
293
294
            /* Would this overrun our buffer?  If so, we'll die. */
295
0
            if (n < bytes_handled + len) {
296
                /* Before we die, let's fill the buffer up to its limit (i.e.
297
                 * fall through with the remaining length, if any), setting
298
                 * saw_eol on LF to stop the outer loop appropriately; we may
299
                 * come back here once the buffer is filled (no LF seen), and
300
                 * either be done at that time or continue to wait for LF here
301
                 * if nospc_eol is set.
302
                 *
303
                 * But there is also a corner cases which we want to address,
304
                 * namely if the buffer is overrun by the final LF only (i.e.
305
                 * the CR fits in); this is not really an overrun since we'll
306
                 * strip the CR finally (and use it for NUL byte), but anyway
307
                 * we have to handle the case so that it's not returned to the
308
                 * caller as part of the truncated line (it's not!). This is
309
                 * easier to consider that LF is out of counting and thus fall
310
                 * through with no error (saw_eol is set to 2 so that we later
311
                 * ignore LF handling already done here), while folding and
312
                 * nospc_eol logics continue to work (or fail) appropriately.
313
                 */
314
0
                saw_eol = (str[len - 1] == APR_ASCII_LF);
315
0
                if (/* First time around */
316
0
                    saw_eol && !saw_nospc
317
                    /*  Single LF completing the buffered CR, */
318
0
                    && ((len == 1 && ((*s)[bytes_handled - 1] == APR_ASCII_CR))
319
                    /*  or trailing CRLF overuns by LF only */
320
0
                        || (len > 1 && str[len - 2] == APR_ASCII_CR
321
0
                            && n - bytes_handled + 1 == len))) {
322
                    /* In both cases *last_char is (to be) the CR stripped by
323
                     * later 'bytes_handled = last_char - *s'.
324
                     */
325
0
                    saw_eol = 2;
326
0
                }
327
0
                else {
328
                    /* In any other case we'd lose data. */
329
0
                    rv = APR_ENOSPC;
330
0
                    saw_nospc = 1;
331
0
                }
332
0
                len = n - bytes_handled;
333
0
                if (!len) {
334
0
                    if (saw_eol) {
335
0
                        break;
336
0
                    }
337
0
                    if (nospc_eol) {
338
0
                        continue;
339
0
                    }
340
0
                    goto cleanup;
341
0
                }
342
0
            }
343
344
            /* Do we have to handle the allocation ourselves? */
345
0
            if (do_alloc) {
346
                /* We'll assume the common case where one bucket is enough. */
347
0
                if (!*s) {
348
0
                    current_alloc = len;
349
0
                    *s = apr_palloc(p, current_alloc + 1);
350
0
                }
351
0
                else if (bytes_handled + len > current_alloc) {
352
                    /* Increase the buffer size */
353
0
                    apr_size_t new_size = current_alloc * 2;
354
0
                    char *new_buffer;
355
356
0
                    if (bytes_handled + len > new_size) {
357
0
                        new_size = (bytes_handled + len) * 2;
358
0
                    }
359
360
0
                    new_buffer = apr_palloc(p, new_size + 1);
361
362
                    /* Copy what we already had. */
363
0
                    memcpy(new_buffer, *s, bytes_handled);
364
0
                    current_alloc = new_size;
365
0
                    *s = new_buffer;
366
0
                }
367
0
            }
368
369
            /* Just copy the rest of the data to the end of the old buffer. */
370
0
            pos = *s + bytes_handled;
371
0
            memcpy(pos, str, len);
372
0
            last_char = pos + len - 1;
373
374
            /* We've now processed that new data - update accordingly. */
375
0
            bytes_handled += len;
376
0
        }
377
378
        /* If we got a full line of input, stop reading */
379
0
        if (last_char && (*last_char == APR_ASCII_LF)) {
380
0
            saw_eol = 1;
381
0
        }
382
0
    } while (!saw_eol);
383
384
0
    if (rv != APR_SUCCESS) {
385
        /* End of line after APR_ENOSPC above */
386
0
        goto cleanup;
387
0
    }
388
389
    /* Now terminate the string at the end of the line;
390
     * if the last-but-one character is a CR, terminate there.
391
     * LF is handled above (not accounted) when saw_eol == 2,
392
     * the last char is CR to terminate at still.
393
     */
394
0
    if (saw_eol < 2) {
395
0
        if (last_char > *s && last_char[-1] == APR_ASCII_CR) {
396
0
            last_char--;
397
0
        }
398
0
        else if (crlf) {
399
0
            rv = APR_EINVAL;
400
0
            goto cleanup;
401
0
        }
402
0
    }
403
0
    bytes_handled = last_char - *s;
404
405
    /* If we're folding, we have more work to do.
406
     *
407
     * Note that if an EOS was seen, we know we can't have another line.
408
     */
409
0
    if (fold && bytes_handled && !saw_eos) {
410
0
        for (;;) {
411
0
            const char *str;
412
0
            apr_size_t len;
413
0
            char c;
414
415
            /* Clear the temp brigade for this filter read. */
416
0
            apr_brigade_cleanup(bb);
417
418
            /* We only care about the first byte. */
419
0
            rv = ap_get_brigade(f, bb, AP_MODE_SPECULATIVE, block, 1);
420
0
            if (rv != APR_SUCCESS) {
421
0
                goto cleanup;
422
0
            }
423
424
0
            if (APR_BRIGADE_EMPTY(bb)) {
425
0
                break;
426
0
            }
427
428
0
            e = APR_BRIGADE_FIRST(bb);
429
430
            /* If we see an EOS, don't bother doing anything more. */
431
0
            if (APR_BUCKET_IS_EOS(e)) {
432
0
                break;
433
0
            }
434
435
0
            rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
436
0
            if (rv != APR_SUCCESS) {
437
0
                apr_brigade_cleanup(bb);
438
0
                goto cleanup;
439
0
            }
440
441
            /* Found one, so call ourselves again to get the next line.
442
             *
443
             * FIXME: If the folding line is completely blank, should we
444
             * stop folding?  Does that require also looking at the next
445
             * char?
446
             */
447
            /* When we call destroy, the buckets are deleted, so save that
448
             * one character we need.  This simplifies our execution paths
449
             * at the cost of one character read.
450
             */
451
0
            c = *str;
452
0
            if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
453
                /* Do we have enough space? We may be full now. */
454
0
                if (bytes_handled >= n) {
455
0
                    rv = APR_ENOSPC;
456
0
                    goto cleanup;
457
0
                }
458
0
                else {
459
0
                    apr_size_t next_size, next_len;
460
0
                    char *tmp;
461
462
                    /* If we're doing the allocations for them, we have to
463
                     * give ourselves a NULL and copy it on return.
464
                     */
465
0
                    if (do_alloc) {
466
0
                        tmp = NULL;
467
0
                    }
468
0
                    else {
469
0
                        tmp = last_char;
470
0
                    }
471
472
0
                    next_size = n - bytes_handled;
473
474
0
                    rv = ap_fgetline_core(&tmp, next_size, &next_len, f,
475
0
                                          flags & ~AP_GETLINE_FOLD, bb, p);
476
0
                    if (rv != APR_SUCCESS) {
477
0
                        goto cleanup;
478
0
                    }
479
480
0
                    if (do_alloc && next_len > 0) {
481
0
                        char *new_buffer;
482
0
                        apr_size_t new_size = bytes_handled + next_len + 1;
483
484
                        /* we need to alloc an extra byte for a null */
485
0
                        new_buffer = apr_palloc(p, new_size);
486
487
                        /* Copy what we already had. */
488
0
                        memcpy(new_buffer, *s, bytes_handled);
489
490
                        /* copy the new line, including the trailing null */
491
0
                        memcpy(new_buffer + bytes_handled, tmp, next_len);
492
0
                        *s = new_buffer;
493
0
                    }
494
495
0
                    last_char += next_len;
496
0
                    bytes_handled += next_len;
497
0
                }
498
0
            }
499
0
            else { /* next character is not tab or space */
500
0
                break;
501
0
            }
502
0
        }
503
0
    }
504
505
0
cleanup:
506
0
    if (bytes_handled >= n) {
507
0
        bytes_handled = n - 1;
508
0
    }
509
510
0
    *read = bytes_handled;
511
0
    if (*s) {
512
        /* ensure the string is NUL terminated */
513
0
        (*s)[*read] = '\0';
514
515
        /* PR#43039: We shouldn't accept NULL bytes within the line */
516
0
        bytes_handled = strlen(*s);
517
0
        if (bytes_handled < *read) {
518
0
            ap_log_data(APLOG_MARK, APLOG_DEBUG, ap_server_conf,
519
0
                        "NULL bytes in header", *s, *read, 0);
520
0
            *read = bytes_handled;
521
0
            if (rv == APR_SUCCESS) {
522
0
                rv = APR_EINVAL;
523
0
            }
524
0
        }
525
0
    }
526
0
    return rv;
527
0
}
528
529
AP_DECLARE(apr_status_t) ap_fgetline(char **s, apr_size_t n,
530
                                     apr_size_t *read, ap_filter_t *f,
531
                                     int flags, apr_bucket_brigade *bb,
532
                                     apr_pool_t *p)
533
0
{
534
0
    apr_status_t rv;
535
    
536
0
    rv = ap_fgetline_core(s, n, read, f, flags, bb, p);
537
538
#if APR_CHARSET_EBCDIC
539
    /* On EBCDIC boxes, each complete http protocol input line needs to be
540
     * translated into the code page used by the compiler.  Since
541
     * ap_fgetline_core uses recursion, we do the translation in a wrapper
542
     * function to ensure that each input character gets translated only once.
543
     */
544
    if (*read) {
545
        ap_xlate_proto_from_ascii(*s, *read);
546
    }
547
#endif
548
549
0
    return rv;
550
0
}
551
552
/* Same as ap_fgetline(), working on r's pool and protocol input filters.
553
 * Pulls from r->proto_input_filters instead of r->input_filters for
554
 * stricter protocol adherence and better input filter behavior during
555
 * chunked trailer processing (for http).
556
 */
557
AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
558
                                     apr_size_t *read, request_rec *r,
559
                                     int flags, apr_bucket_brigade *bb)
560
0
{
561
0
    apr_status_t rv;
562
563
0
    rv = ap_fgetline_core(s, n, read, r->proto_input_filters, flags,
564
0
                          bb, r->pool);
565
#if APR_CHARSET_EBCDIC
566
    /* On EBCDIC boxes, each complete http protocol input line needs to be
567
     * translated into the code page used by the compiler.  Since
568
     * ap_fgetline_core uses recursion, we do the translation in a wrapper
569
     * function to ensure that each input character gets translated only once.
570
     */
571
    if (*read) {
572
        ap_xlate_proto_from_ascii(*s, *read);
573
    }
574
#endif
575
576
0
    return rv;
577
0
}
578
579
AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int flags)
580
0
{
581
0
    apr_status_t rv;
582
0
    apr_size_t len;
583
0
    apr_bucket_brigade *tmp_bb;
584
585
0
    if (n < 1) {
586
        /* Can't work since we always NUL terminate */
587
0
        return -1;
588
0
    }
589
590
0
    tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
591
0
    rv = ap_rgetline(&s, n, &len, r, flags, tmp_bb);
592
0
    apr_brigade_destroy(tmp_bb);
593
594
    /* Map the out-of-space condition to the old API. */
595
0
    if (rv == APR_ENOSPC) {
596
0
        return n;
597
0
    }
598
599
    /* Anything else is just bad. */
600
0
    if (rv != APR_SUCCESS) {
601
0
        return -1;
602
0
    }
603
604
0
    return (int)len;
605
0
}
606
607
/* parse_uri: break apart the uri
608
 * Side Effects:
609
 * - sets r->args to rest after '?' (or NULL if no '?')
610
 * - sets r->uri to request uri (without r->args part)
611
 * - sets r->hostname (if not set already) from request (scheme://host:port)
612
 */
613
AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
614
538
{
615
538
    int status = HTTP_OK;
616
617
538
    r->unparsed_uri = apr_pstrdup(r->pool, uri);
618
619
    /* http://issues.apache.org/bugzilla/show_bug.cgi?id=31875
620
     * http://issues.apache.org/bugzilla/show_bug.cgi?id=28450
621
     *
622
     * This is not in fact a URI, it's a path.  That matters in the
623
     * case of a leading double-slash.  We need to resolve the issue
624
     * by normalizing that out before treating it as a URI.
625
     */
626
694
    while ((uri[0] == '/') && (uri[1] == '/')) {
627
156
        ++uri ;
628
156
    }
629
538
    if (r->method_number == M_CONNECT) {
630
37
        status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
631
37
    }
632
501
    else {
633
501
        status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
634
501
    }
635
636
538
    if (status == APR_SUCCESS) {
637
        /* if it has a scheme we may need to do absoluteURI vhost stuff */
638
475
        if (r->parsed_uri.scheme
639
400
            && !ap_cstr_casecmp(r->parsed_uri.scheme, ap_http_scheme(r))) {
640
4
            r->hostname = r->parsed_uri.hostname;
641
4
        }
642
471
        else if (r->method_number == M_CONNECT) {
643
2
            r->hostname = r->parsed_uri.hostname;
644
2
        }
645
646
475
        r->args = r->parsed_uri.query;
647
475
        if (r->parsed_uri.path) {
648
199
            r->uri = r->parsed_uri.path;
649
199
        }
650
276
        else if (r->method_number == M_OPTIONS) {
651
1
            r->uri = apr_pstrdup(r->pool, "*");
652
1
        }
653
275
        else {
654
275
            r->uri = apr_pstrdup(r->pool, "/");
655
275
        }
656
657
#if defined(OS2) || defined(WIN32)
658
        /* Handle path translations for OS/2 and plug security hole.
659
         * This will prevent "http://www.wherever.com/..\..\/" from
660
         * returning a directory for the root drive.
661
         */
662
        {
663
            char *x;
664
665
            for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
666
                *x = '/';
667
        }
668
#endif /* OS2 || WIN32 */
669
475
    }
670
63
    else {
671
63
        r->args = NULL;
672
63
        r->hostname = NULL;
673
63
        r->status = HTTP_BAD_REQUEST;             /* set error status */
674
63
        r->uri = apr_pstrdup(r->pool, uri);
675
63
    }
676
538
}
677
678
/* get the length of the field name for logging, but no more than 80 bytes */
679
0
#define LOG_NAME_MAX_LEN 80
680
static int field_name_len(const char *field)
681
0
{
682
0
    const char *end = ap_strchr_c(field, ':');
683
0
    if (end == NULL || end - field > LOG_NAME_MAX_LEN)
684
0
        return LOG_NAME_MAX_LEN;
685
0
    return end - field;
686
0
}
687
688
AP_DECLARE(int) ap_parse_request_line(request_rec *r)
689
679
{
690
679
    const char *method, *uri, *protocol;
691
692
679
    return ap_h1_tokenize_request_line(r, r->the_request,
693
679
                                       &method, &uri, &protocol)
694
538
        && ap_assign_request_line(r, method, uri, protocol);
695
679
}
696
697
AP_DECLARE(int) ap_check_request_header(request_rec *r)
698
0
{
699
0
    core_server_config *conf;
700
0
    int strict_host_check;
701
0
    const char *expect;
702
0
    int access_status;
703
704
0
    conf = ap_get_core_module_config(r->server->module_config);
705
706
    /* update what we think the virtual host is based on the headers we've
707
     * now read. may update status.
708
     */
709
0
    strict_host_check = (conf->strict_host_check == AP_CORE_CONFIG_ON);
710
0
    access_status = ap_update_vhost_from_headers_ex(r, strict_host_check);
711
0
    if (strict_host_check && access_status != HTTP_OK) { 
712
0
        if (r->server == ap_server_conf) { 
713
0
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(10156)
714
0
                          "Requested hostname '%s' did not match any ServerName/ServerAlias "
715
0
                          "in the global server configuration ", r->hostname);
716
0
        }
717
0
        else { 
718
0
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(10157)
719
0
                          "Requested hostname '%s' did not match any ServerName/ServerAlias "
720
0
                          "in the matching virtual host (default vhost for "
721
0
                          "current connection is %s:%u)", 
722
0
                          r->hostname, r->server->defn_name, r->server->defn_line_number);
723
0
        }
724
0
        r->status = access_status;
725
0
    }
726
0
    if (r->status != HTTP_OK) { 
727
0
        return 0;
728
0
    }
729
730
0
    if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
731
0
        || ((r->proto_num == HTTP_VERSION(1, 1))
732
0
            && !apr_table_get(r->headers_in, "Host"))) {
733
        /*
734
         * Client sent us an HTTP/1.1 or later request without telling us the
735
         * hostname, either with a full URL or a Host: header. We therefore
736
         * need to (as per the 1.1 spec) send an error.  As a special case,
737
         * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
738
         * a Host: header, and the server MUST respond with 400 if it doesn't.
739
         */
740
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00569)
741
0
                      "client sent HTTP/1.1 request without hostname "
742
0
                      "(see RFC2616 section 14.23): %s", r->uri);
743
0
        r->status = HTTP_BAD_REQUEST;
744
0
        return 0;
745
0
    }
746
747
    /* we may have switched to another server */
748
0
    conf = ap_get_core_module_config(r->server->module_config);
749
750
0
    if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
751
0
        && (expect[0] != '\0')) {
752
        /*
753
         * The Expect header field was added to HTTP/1.1 after RFC 2068
754
         * as a means to signal when a 100 response is desired and,
755
         * unfortunately, to signal a poor man's mandatory extension that
756
         * the server must understand or return 417 Expectation Failed.
757
         */
758
0
        if (ap_cstr_casecmp(expect, "100-continue") == 0) {
759
0
            r->expecting_100 = 1;
760
0
        }
761
0
        else if (conf->http_expect_strict == AP_HTTP_EXPECT_STRICT_DISABLE) {
762
0
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02595)
763
0
                          "client sent an unrecognized expectation value "
764
0
                          "of Expect (not fatal): %s", expect);
765
0
        }
766
0
        else {
767
0
            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00570)
768
0
                          "client sent an unrecognized expectation value "
769
0
                          "of Expect: %s", expect);
770
0
            r->status = HTTP_EXPECTATION_FAILED;
771
0
            return 0;
772
0
        }
773
0
    }
774
775
0
    return 1;
776
0
}
777
778
static int table_do_fn_check_lengths(void *r_, const char *key,
779
                                     const char *value)
780
0
{
781
0
    request_rec *r = r_;
782
0
    if (value == NULL || r->server->limit_req_fieldsize >= strlen(value) )
783
0
        return 1;
784
785
0
    r->status = HTTP_BAD_REQUEST;
786
0
    apr_table_setn(r->notes, "error-notes",
787
0
                   "Size of a request header field exceeds server limit.");
788
0
    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00560) "Request "
789
0
                  "header exceeds LimitRequestFieldSize after merging: %.*s",
790
0
                  field_name_len(key), key);
791
0
    return 0;
792
0
}
793
794
AP_DECLARE(void) ap_get_mime_headers_core(request_rec *r, apr_bucket_brigade *bb)
795
0
{
796
0
    char *last_field = NULL;
797
0
    apr_size_t last_len = 0;
798
0
    apr_size_t alloc_len = 0;
799
0
    char *field;
800
0
    char *value;
801
0
    apr_size_t len;
802
0
    int fields_read = 0;
803
0
    char *tmp_field;
804
0
    core_server_config *conf = ap_get_core_module_config(r->server->module_config);
805
0
    int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
806
807
    /*
808
     * Read header lines until we get the empty separator line, a read error,
809
     * the connection closes (EOF), reach the server limit, or we timeout.
810
     */
811
0
    while(1) {
812
0
        apr_status_t rv;
813
814
0
        field = NULL;
815
0
        rv = ap_rgetline(&field, r->server->limit_req_fieldsize + 2,
816
0
                         &len, r, strict ? AP_GETLINE_CRLF : 0, bb);
817
818
0
        if (rv != APR_SUCCESS) {
819
0
            if (APR_STATUS_IS_TIMEUP(rv)) {
820
0
                r->status = HTTP_REQUEST_TIME_OUT;
821
0
            }
822
0
            else {
823
0
                r->status = HTTP_BAD_REQUEST;
824
0
            }
825
826
            /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
827
             * finding the end-of-line.  This is only going to happen if it
828
             * exceeds the configured limit for a field size.
829
             */
830
0
            if (rv == APR_ENOSPC) {
831
0
                apr_table_setn(r->notes, "error-notes",
832
0
                               "Size of a request header field "
833
0
                               "exceeds server limit.");
834
0
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00561)
835
0
                              "Request header exceeds LimitRequestFieldSize%s"
836
0
                              "%.*s",
837
0
                              (field && *field) ? ": " : "",
838
0
                              (field) ? field_name_len(field) : 0,
839
0
                              (field) ? field : "");
840
0
            }
841
0
            return;
842
0
        }
843
844
        /* For all header values, and all obs-fold lines, the presence of
845
         * additional whitespace is a no-op, so collapse trailing whitespace
846
         * to save buffer allocation and optimize copy operations.
847
         * Do not remove the last single whitespace under any condition.
848
         */
849
0
        while (len > 1 && (field[len-1] == '\t' || field[len-1] == ' ')) {
850
0
            field[--len] = '\0';
851
0
        } 
852
853
0
        if (*field == '\t' || *field == ' ') {
854
855
            /* Append any newly-read obs-fold line onto the preceding
856
             * last_field line we are processing
857
             */
858
0
            apr_size_t fold_len;
859
860
0
            if (last_field == NULL) {
861
0
                r->status = HTTP_BAD_REQUEST;
862
0
                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03442)
863
0
                              "Line folding encountered before first"
864
0
                              " header line");
865
0
                return;
866
0
            }
867
868
0
            if (field[1] == '\0') {
869
0
                r->status = HTTP_BAD_REQUEST;
870
0
                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03443)
871
0
                              "Empty folded line encountered");
872
0
                return;
873
0
            }
874
875
            /* Leading whitespace on an obs-fold line can be
876
             * similarly discarded */
877
0
            while (field[1] == '\t' || field[1] == ' ') {
878
0
                ++field; --len;
879
0
            }
880
881
            /* This line is a continuation of the preceding line(s),
882
             * so append it to the line that we've set aside.
883
             * Note: this uses a power-of-two allocator to avoid
884
             * doing O(n) allocs and using O(n^2) space for
885
             * continuations that span many many lines.
886
             */
887
0
            fold_len = last_len + len + 1; /* trailing null */
888
889
0
            if (fold_len >= (apr_size_t)(r->server->limit_req_fieldsize)) {
890
0
                r->status = HTTP_BAD_REQUEST;
891
                /* report what we have accumulated so far before the
892
                 * overflow (last_field) as the field with the problem
893
                 */
894
0
                apr_table_setn(r->notes, "error-notes",
895
0
                               "Size of a request header field "
896
0
                               "exceeds server limit.");
897
0
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00562)
898
0
                              "Request header exceeds LimitRequestFieldSize "
899
0
                              "after folding: %.*s",
900
0
                              field_name_len(last_field), last_field);
901
0
                return;
902
0
            }
903
904
0
            if (fold_len > alloc_len) {
905
0
                char *fold_buf;
906
0
                alloc_len += alloc_len;
907
0
                if (fold_len > alloc_len) {
908
0
                    alloc_len = fold_len;
909
0
                }
910
0
                fold_buf = (char *)apr_palloc(r->pool, alloc_len);
911
0
                memcpy(fold_buf, last_field, last_len);
912
0
                last_field = fold_buf;
913
0
            }
914
0
            memcpy(last_field + last_len, field, len +1); /* +1 for nul */
915
            /* Replace obs-fold w/ SP per RFC 7230 3.2.4 */
916
0
            last_field[last_len] = ' ';
917
0
            last_len += len;
918
919
            /* We've appended this obs-fold line to last_len, proceed to
920
             * read the next input line
921
             */
922
0
            continue;
923
0
        }
924
0
        else if (last_field != NULL) {
925
926
            /* Process the previous last_field header line with all obs-folded
927
             * segments already concatenated (this is not operating on the
928
             * most recently read input line).
929
             */
930
931
0
            if (r->server->limit_req_fields
932
0
                    && (++fields_read > r->server->limit_req_fields)) {
933
0
                r->status = HTTP_BAD_REQUEST;
934
0
                apr_table_setn(r->notes, "error-notes",
935
0
                               "The number of request header fields "
936
0
                               "exceeds this server's limit.");
937
0
                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00563)
938
0
                              "Number of request headers exceeds "
939
0
                              "LimitRequestFields");
940
0
                return;
941
0
            }
942
943
0
            if (!strict)
944
0
            {
945
                /* Not Strict ('Unsafe' mode), using the legacy parser */
946
947
0
                if (!(value = strchr(last_field, ':'))) { /* Find ':' or */
948
0
                    r->status = HTTP_BAD_REQUEST;   /* abort bad request */
949
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00564)
950
0
                                  "Request header field is missing ':' "
951
0
                                  "separator: %.*s", (int)LOG_NAME_MAX_LEN,
952
0
                                  last_field);
953
0
                    return;
954
0
                }
955
956
0
                if (value == last_field) {
957
0
                    r->status = HTTP_BAD_REQUEST;
958
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03453)
959
0
                                  "Request header field name was empty");
960
0
                    return;
961
0
                }
962
963
0
                *value++ = '\0'; /* NUL-terminate at colon */
964
965
0
                if (strpbrk(last_field, "\t\n\v\f\r ")) {
966
0
                    r->status = HTTP_BAD_REQUEST;
967
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03452)
968
0
                                  "Request header field name presented"
969
0
                                  " invalid whitespace");
970
0
                    return;
971
0
                }
972
973
0
                while (*value == ' ' || *value == '\t') {
974
0
                     ++value;            /* Skip to start of value   */
975
0
                }
976
977
0
                if (strpbrk(value, "\n\v\f\r")) {
978
0
                    r->status = HTTP_BAD_REQUEST;
979
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03451)
980
0
                                  "Request header field value presented"
981
0
                                  " bad whitespace");
982
0
                    return;
983
0
                }
984
0
            }
985
0
            else /* Using strict RFC7230 parsing */
986
0
            {
987
                /* Ensure valid token chars before ':' per RFC 7230 3.2.4 */
988
0
                value = (char *)ap_scan_http_token(last_field);
989
0
                if ((value == last_field) || *value != ':') {
990
0
                    r->status = HTTP_BAD_REQUEST;
991
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02426)
992
0
                                  "Request header field name is malformed: "
993
0
                                  "%.*s", (int)LOG_NAME_MAX_LEN, last_field);
994
0
                    return;
995
0
                }
996
997
0
                *value++ = '\0'; /* NUL-terminate last_field name at ':' */
998
999
0
                while (*value == ' ' || *value == '\t') {
1000
0
                    ++value;     /* Skip LWS of value */
1001
0
                }
1002
1003
                /* Find invalid, non-HT ctrl char, or the trailing NULL */
1004
0
                tmp_field = (char *)ap_scan_http_field_content(value);
1005
1006
                /* Reject value for all garbage input (CTRLs excluding HT)
1007
                 * e.g. only VCHAR / SP / HT / obs-text are allowed per
1008
                 * RFC7230 3.2.6 - leave all more explicit rule enforcement
1009
                 * for specific header handler logic later in the cycle
1010
                 */
1011
0
                if (*tmp_field != '\0') {
1012
0
                    r->status = HTTP_BAD_REQUEST;
1013
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02427)
1014
0
                                  "Request header value is malformed: "
1015
0
                                  "%.*s", (int)LOG_NAME_MAX_LEN, value);
1016
0
                    return;
1017
0
                }
1018
0
            }
1019
1020
0
            apr_table_addn(r->headers_in, last_field, value);
1021
1022
            /* This last_field header is now stored in headers_in,
1023
             * resume processing of the current input line.
1024
             */
1025
0
        }
1026
1027
        /* Found the terminating empty end-of-headers line, stop. */
1028
0
        if (len == 0) {
1029
0
            break;
1030
0
        }
1031
1032
        /* Keep track of this new header line so that we can extend it across
1033
         * any obs-fold or parse it on the next loop iteration. We referenced
1034
         * our previously allocated buffer in r->headers_in,
1035
         * so allocate a fresh buffer if required.
1036
         */
1037
0
        alloc_len = 0;
1038
0
        last_field = field;
1039
0
        last_len = len;
1040
0
    }
1041
1042
    /* Combine multiple message-header fields with the same
1043
     * field-name, following RFC 2616, 4.2.
1044
     */
1045
0
    apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
1046
1047
    /* enforce LimitRequestFieldSize for merged headers */
1048
0
    apr_table_do(table_do_fn_check_lengths, r, r->headers_in, NULL);
1049
0
}
1050
1051
AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
1052
0
{
1053
0
    apr_bucket_brigade *tmp_bb;
1054
0
    tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1055
0
    ap_get_mime_headers_core(r, tmp_bb);
1056
0
    apr_brigade_destroy(tmp_bb);
1057
0
}
1058
1059
AP_DECLARE(request_rec *) ap_create_request(conn_rec *conn)
1060
679
{
1061
679
    request_rec *r;
1062
679
    apr_pool_t *p;
1063
1064
679
    apr_pool_create(&p, conn->pool);
1065
679
    apr_pool_tag(p, "request");
1066
679
    r = apr_pcalloc(p, sizeof(request_rec));
1067
679
    AP_READ_REQUEST_ENTRY((intptr_t)r, (uintptr_t)conn);
1068
679
    r->pool            = p;
1069
679
    r->connection      = conn;
1070
679
    r->server          = conn->base_server;
1071
1072
679
    r->user            = NULL;
1073
679
    r->ap_auth_type    = NULL;
1074
1075
679
    r->allowed_methods = ap_make_method_list(p, 2);
1076
1077
679
    r->headers_in      = apr_table_make(r->pool, 25);
1078
679
    r->trailers_in     = apr_table_make(r->pool, 5);
1079
679
    r->subprocess_env  = apr_table_make(r->pool, 25);
1080
679
    r->headers_out     = apr_table_make(r->pool, 12);
1081
679
    r->err_headers_out = apr_table_make(r->pool, 5);
1082
679
    r->trailers_out    = apr_table_make(r->pool, 5);
1083
679
    r->notes           = apr_table_make(r->pool, 5);
1084
1085
679
    r->request_config  = ap_create_request_config(r->pool);
1086
    /* Must be set before we run create request hook */
1087
1088
679
    r->proto_output_filters = conn->output_filters;
1089
679
    r->output_filters  = r->proto_output_filters;
1090
679
    r->proto_input_filters = conn->input_filters;
1091
679
    r->input_filters   = r->proto_input_filters;
1092
679
    ap_run_create_request(r);
1093
679
    r->per_dir_config  = r->server->lookup_defaults;
1094
1095
679
    r->sent_bodyct     = 0;                      /* bytect isn't for body */
1096
1097
679
    r->read_length     = 0;
1098
679
    r->read_body       = REQUEST_NO_BODY;
1099
1100
679
    r->status          = HTTP_OK;  /* Until further notice */
1101
679
    r->header_only     = 0;
1102
679
    r->the_request     = NULL;
1103
1104
    /* Begin by presuming any module can make its own path_info assumptions,
1105
     * until some module interjects and changes the value.
1106
     */
1107
679
    r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
1108
1109
679
    r->useragent_addr = conn->client_addr;
1110
679
    r->useragent_ip = conn->client_ip;
1111
1112
679
    return r;
1113
679
}
1114
1115
/* Apply the server's timeout/config to the connection/request. */
1116
static void apply_server_config(request_rec *r)
1117
0
{
1118
0
    apr_socket_t *csd;
1119
1120
0
    csd = ap_get_conn_socket(r->connection);
1121
0
    apr_socket_timeout_set(csd, r->server->timeout);
1122
1123
0
    r->per_dir_config = r->server->lookup_defaults;
1124
0
}
1125
1126
typedef enum {
1127
    http_error_none,
1128
    http_error_badprotocol,
1129
    http_error_reject09,
1130
    http_error_badmethod09,
1131
} http_error;
1132
1133
static http_error r_assign_protocol(request_rec *r,
1134
                                    const char *protocol,
1135
                                    int strict)
1136
538
{
1137
538
    int proto_num;
1138
538
    http_error error = http_error_none;
1139
1140
538
    if (protocol[0] == 'H' && protocol[1] == 'T'
1141
109
            && protocol[2] == 'T' && protocol[3] == 'P'
1142
60
            && protocol[4] == '/' && apr_isdigit(protocol[5])
1143
43
            && protocol[6] == '.' && apr_isdigit(protocol[7])
1144
28
            && !protocol[8] && protocol[5] != '0') {
1145
15
        r->assbackwards = 0;
1146
15
        proto_num = HTTP_VERSION(protocol[5] - '0', protocol[7] - '0');
1147
15
    }
1148
523
    else if ((protocol[0] == 'H' || protocol[0] == 'h')
1149
163
                 && (protocol[1] == 'T' || protocol[1] == 't')
1150
128
                 && (protocol[2] == 'T' || protocol[2] == 't')
1151
101
                 && (protocol[3] == 'P' || protocol[3] == 'p')
1152
72
                 && protocol[4] == '/' && apr_isdigit(protocol[5])
1153
51
                 && protocol[6] == '.' && apr_isdigit(protocol[7])
1154
31
                 && !protocol[8] && protocol[5] != '0') {
1155
14
        r->assbackwards = 0;
1156
14
        proto_num = HTTP_VERSION(protocol[5] - '0', protocol[7] - '0');
1157
14
        if (strict && error == http_error_none)
1158
13
            error = http_error_badprotocol;
1159
1
        else
1160
1
            protocol = apr_psprintf(r->pool, "HTTP/%d.%d", HTTP_VERSION_MAJOR(proto_num),
1161
1
                                    HTTP_VERSION_MINOR(proto_num));
1162
14
    }
1163
509
    else if (protocol[0]) {
1164
185
        proto_num = HTTP_VERSION(0, 9);
1165
185
        if (error == http_error_none)
1166
185
            error = http_error_badprotocol;
1167
185
    }
1168
324
    else {
1169
324
        r->assbackwards = 1;
1170
324
        protocol = "HTTP/0.9";
1171
324
        proto_num = HTTP_VERSION(0, 9);
1172
324
    }
1173
538
    r->protocol = protocol;
1174
538
    r->proto_num = proto_num;
1175
538
    return error;
1176
538
}
1177
1178
AP_DECLARE(int) ap_assign_request_line(request_rec *r,
1179
                                       const char *method, const char *uri,
1180
                                       const char *protocol)
1181
538
{
1182
538
    core_server_config *conf = ap_get_core_module_config(r->server->module_config);
1183
538
    int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
1184
538
    http_error error = r_assign_protocol(r, protocol, strict);
1185
1186
538
    ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1187
538
                  "assigned protocol: %s, error=%d", r->protocol, error);
1188
1189
    /* Determine the method_number and parse the uri prior to invoking error
1190
     * handling, such that these fields are available for substitution
1191
     */
1192
538
    r->method = method;
1193
538
    r->method_number = ap_method_number_of(r->method);
1194
538
    if (r->method_number == M_GET && r->method[0] == 'H')
1195
1
        r->header_only = 1;
1196
1197
    /* For internal integrity and palloc efficiency, reconstruct the_request
1198
     * in one palloc, using only single SP characters, per spec.
1199
     */
1200
538
    r->the_request = apr_pstrcat(r->pool, r->method, *uri ? " " : NULL, uri,
1201
538
                                 *r->protocol ? " " : NULL, r->protocol, NULL);
1202
538
    ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1203
538
                  "assigned request_line: %s, error=%d", r->the_request, error);
1204
1205
538
    ap_parse_uri(r, uri);
1206
538
    if (r->status == HTTP_OK
1207
475
            && (r->parsed_uri.path != NULL)
1208
199
            && (r->parsed_uri.path[0] != '/')
1209
63
            && (r->method_number != M_OPTIONS
1210
62
                || strcmp(r->parsed_uri.path, "*") != 0)) {
1211
        /* Invalid request-target per RFC 7230 section 5.3 */
1212
62
        r->status = HTTP_BAD_REQUEST;
1213
62
    }
1214
1215
538
    ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1216
538
                  "parsed uri: r->status=%d, error=%d", r->status, error);
1217
    /* With the request understood, we can consider HTTP/0.9 specific errors */
1218
538
    if (r->proto_num == HTTP_VERSION(0, 9) && error == http_error_none) {
1219
324
        if (conf->http09_enable == AP_HTTP09_DISABLE)
1220
1
            error = http_error_reject09;
1221
323
        else if (strict && (r->method_number != M_GET || r->header_only))
1222
307
            error = http_error_badmethod09;
1223
324
    }
1224
1225
    /* Now that the method, uri and protocol are all processed,
1226
     * we can safely resume any deferred error reporting
1227
     */
1228
538
    if (error != http_error_none) {
1229
506
        switch (error) {
1230
198
        case http_error_badprotocol:
1231
198
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(10388)
1232
198
                          "HTTP Request: Unrecognized protocol '%.*s' "
1233
198
                          "(perhaps whitespace was injected?)",
1234
198
                          field_name_len(r->protocol), r->protocol);
1235
198
            break;
1236
1
        case http_error_reject09:
1237
1
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)
1238
1
                          "HTTP Request: Rejected HTTP/0.9 request");
1239
1
            break;
1240
307
        case http_error_badmethod09:
1241
307
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03444)
1242
307
                          "HTTP Request: Invalid method token: '%.*s'"
1243
307
                          " (only GET is allowed for HTTP/0.9 requests)",
1244
307
                          field_name_len(r->method), r->method);
1245
307
            break;
1246
0
        default:
1247
0
            break;
1248
506
        }
1249
506
        r->status = HTTP_BAD_REQUEST;
1250
506
        goto failed;
1251
506
    }
1252
1253
32
    if (conf->http_methods == AP_HTTP_METHODS_REGISTERED
1254
7
            && r->method_number == M_INVALID) {
1255
1
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)
1256
1
                      "HTTP Request Line; Unrecognized HTTP method: '%.*s' "
1257
1
                      "(disallowed by RegisteredMethods)",
1258
1
                      field_name_len(r->method), r->method);
1259
1
        r->status = HTTP_NOT_IMPLEMENTED;
1260
        /* This can't happen in an HTTP/0.9 request, we verified GET above */
1261
1
        goto failed;
1262
1
    }
1263
1264
31
    if (r->status != HTTP_OK) {
1265
11
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03450)
1266
11
                      "HTTP Request Line; Unable to parse URI: '%.*s'",
1267
11
                      field_name_len(r->uri), r->uri);
1268
11
        goto failed;
1269
11
    }
1270
1271
20
    if (strict) {
1272
13
        if (r->parsed_uri.fragment) {
1273
            /* RFC3986 3.5: no fragment */
1274
3
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)
1275
3
                          "HTTP Request Line; URI must not contain a fragment");
1276
3
            r->status = HTTP_BAD_REQUEST;
1277
3
            goto failed;
1278
3
        }
1279
10
        if (r->parsed_uri.user || r->parsed_uri.password) {
1280
5
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)
1281
5
                          "HTTP Request Line; URI must not contain a "
1282
5
                          "username/password");
1283
5
            r->status = HTTP_BAD_REQUEST;
1284
5
            goto failed;
1285
5
        }
1286
10
    }
1287
12
    return 1;
1288
1289
526
failed:
1290
526
    if (error != http_error_none && r->proto_num == HTTP_VERSION(0, 9)) {
1291
        /* Send all parsing and protocol error response with 1.x behavior,
1292
         * and reserve 505 errors for actual HTTP protocols presented.
1293
         * As called out in RFC7230 3.5, any errors parsing the protocol
1294
         * from the request line are nearly always misencoded HTTP/1.x
1295
         * requests. Only a valid 0.9 request with no parsing errors
1296
         * at all may be treated as a simple request, if allowed.
1297
         */
1298
493
        r->assbackwards = 0;
1299
493
        r->connection->keepalive = AP_CONN_CLOSE;
1300
493
        r->proto_num = HTTP_VERSION(1, 0);
1301
493
        r->protocol  = "HTTP/1.0";
1302
493
    }
1303
526
    return 0;
1304
1305
20
}
1306
1307
AP_DECLARE(request_rec *) ap_read_request(conn_rec *conn)
1308
0
{
1309
0
    int access_status;
1310
0
    apr_bucket_brigade *tmp_bb;
1311
0
    apr_bucket *e, *bdata = NULL, *berr = NULL;
1312
0
    ap_bucket_request *breq = NULL;
1313
0
    const char *method, *uri, *protocol;
1314
0
    apr_table_t *headers;
1315
0
    apr_status_t rv;
1316
1317
0
    request_rec *r = ap_create_request(conn);
1318
1319
0
    tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1320
0
    conn->keepalive = AP_CONN_UNKNOWN;
1321
1322
0
    ap_run_pre_read_request(r, conn);
1323
1324
0
    r->request_time = apr_time_now();
1325
0
    rv = ap_get_brigade(r->proto_input_filters, tmp_bb, AP_MODE_READBYTES, APR_BLOCK_READ, 0);
1326
0
    if (rv != APR_SUCCESS || APR_BRIGADE_EMPTY(tmp_bb)) {
1327
        /* Not worth dying with. */
1328
0
        conn->keepalive = AP_CONN_CLOSE;
1329
0
        apr_pool_destroy(r->pool);
1330
0
        goto ignore;
1331
0
    }
1332
1333
0
    for (e = APR_BRIGADE_FIRST(tmp_bb);
1334
0
         e != APR_BRIGADE_SENTINEL(tmp_bb);
1335
0
         e = APR_BUCKET_NEXT(e))
1336
0
    {
1337
0
        if (AP_BUCKET_IS_REQUEST(e)) {
1338
0
            if (!breq) breq = e->data;
1339
0
        }
1340
0
        else if (AP_BUCKET_IS_ERROR(e)) {
1341
0
            if (!berr) berr = e;
1342
0
        }
1343
0
        else if (!APR_BUCKET_IS_METADATA(e) && e->length != 0) {
1344
0
            if (!bdata) bdata = e;
1345
0
            break;
1346
0
        }
1347
0
    }
1348
1349
0
    if (!breq && !berr) {
1350
0
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10389)
1351
0
                      "request failed: neither request bucket nor error at start of input");
1352
0
        access_status = HTTP_INTERNAL_SERVER_ERROR;
1353
0
        goto die_unusable_input;
1354
0
    }
1355
1356
0
    if (breq) {
1357
        /* If there is a request, we always process it, as it defines
1358
         * the context in which a potential error bucket is handled. */
1359
0
        if (apr_pool_is_ancestor(r->pool, breq->pool)) {
1360
0
            method = breq->method;
1361
0
            uri = breq->uri;
1362
0
            protocol = breq->protocol;
1363
0
            headers = breq->headers;
1364
0
        }
1365
0
        else {
1366
0
            method = apr_pstrdup(r->pool, breq->method);
1367
0
            uri = apr_pstrdup(r->pool, breq->uri);
1368
0
            protocol = apr_pstrdup(r->pool, breq->protocol);
1369
0
            headers = breq->headers? apr_table_clone(r->pool, breq->headers) : NULL;
1370
0
        }
1371
1372
0
        if (!method || !uri || !protocol) {
1373
0
            access_status = berr? ((ap_bucket_error *)(berr->data))->status :
1374
0
                                  HTTP_INTERNAL_SERVER_ERROR;
1375
0
            goto die_unusable_input;
1376
0
        }
1377
1378
0
        if (headers) {
1379
0
            r->headers_in = headers;
1380
0
        }
1381
1382
0
        ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1383
0
                      "checking request: %s %s %s",
1384
0
                      method, uri, protocol);
1385
1386
0
        if (!ap_assign_request_line(r, method, uri, protocol)) {
1387
0
            apr_brigade_cleanup(tmp_bb);
1388
0
            switch (r->status) {
1389
0
            case HTTP_REQUEST_URI_TOO_LARGE:
1390
0
            case HTTP_BAD_REQUEST:
1391
0
            case HTTP_VERSION_NOT_SUPPORTED:
1392
0
            case HTTP_NOT_IMPLEMENTED:
1393
0
                if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
1394
0
                    ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00565)
1395
0
                                  "request failed: client's request-line exceeds LimitRequestLine (longer than %d)",
1396
0
                                  r->server->limit_req_line);
1397
0
                }
1398
0
                else if (!strcmp("-", r->method)) {
1399
0
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00566)
1400
0
                                  "request failed: malformed request line");
1401
0
                }
1402
0
                access_status = r->status;
1403
0
                goto die_unusable_input;
1404
1405
0
            case HTTP_REQUEST_TIME_OUT:
1406
                /* Just log, no further action on this connection. */
1407
0
                ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, NULL);
1408
0
                if (!r->connection->keepalives)
1409
0
                    ap_run_log_transaction(r);
1410
0
                break;
1411
0
            }
1412
            /* Not worth dying with. */
1413
0
            conn->keepalive = AP_CONN_CLOSE;
1414
0
            apr_pool_destroy(r->pool);
1415
0
            goto ignore;
1416
0
        }
1417
0
    }
1418
1419
0
    if (berr) {
1420
0
        access_status = ((ap_bucket_error *)(berr->data))->status;
1421
0
        goto die_unusable_input;
1422
0
    }
1423
0
    else if (bdata) {
1424
        /* Since processing of a request body depends on knowing the request, we
1425
         * cannot handle any data here. For example, chunked-encoding filters are
1426
         * added after the request is read, so any data buckets here will not
1427
         * have been de-chunked.
1428
         */
1429
0
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10391)
1430
0
                      "request failed: seeing DATA bucket(len=%d) of request "
1431
0
                      "body, too early to process", (int)bdata->length);
1432
0
        access_status = HTTP_INTERNAL_SERVER_ERROR;
1433
0
        goto die_unusable_input;
1434
0
    }
1435
1436
0
    apr_brigade_cleanup(tmp_bb);
1437
1438
    /* We may have been in keep_alive_timeout mode, so toggle back
1439
     * to the normal timeout mode as we fetch the header lines,
1440
     * as necessary.
1441
     */
1442
0
    apply_server_config(r);
1443
1444
0
    if (!r->assbackwards) {
1445
0
        const char *clen = apr_table_get(r->headers_in, "Content-Length");
1446
0
        if (clen) {
1447
0
            apr_off_t cl;
1448
1449
0
            if (!ap_parse_strict_length(&cl, clen)) {
1450
0
                ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(10242)
1451
0
                              "client sent invalid Content-Length "
1452
0
                              "(%s): %s", clen, r->uri);
1453
0
                access_status = HTTP_BAD_REQUEST;
1454
0
                goto die_unusable_input;
1455
0
            }
1456
0
        }
1457
0
    }
1458
1459
    /*
1460
     * Add HTTP_IN here to ensure that content and HEADERS buckets are processed
1461
     * accordingly, e.g. populating r->trailers_in for example.
1462
     */
1463
0
    ap_add_input_filter_handle(ap_http_input_filter_handle,
1464
0
                               NULL, r, r->connection);
1465
1466
    /* Validate Host/Expect headers and select vhost. */
1467
0
    if (!ap_check_request_header(r)) {
1468
        /* we may have switched to another server still */
1469
0
        apply_server_config(r);
1470
0
        access_status = r->status;
1471
0
        goto die_before_hooks;
1472
0
    }
1473
1474
    /* we may have switched to another server */
1475
0
    apply_server_config(r);
1476
1477
0
    if ((access_status = ap_post_read_request(r))) {
1478
0
        goto die;
1479
0
    }
1480
1481
0
    AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method,
1482
0
                            (char *)r->uri, (char *)r->server->defn_name,
1483
0
                            r->status);
1484
0
    return r;
1485
1486
    /* Everything falls through on failure */
1487
1488
0
die_unusable_input:
1489
    /* Input filters are in an undeterminate state, cleanup (including
1490
     * CORE_IN's socket) such that any further attempt to read is EOF.
1491
     */
1492
0
    {
1493
0
        ap_filter_t *f = conn->input_filters;
1494
0
        while (f) {
1495
0
            ap_filter_reinstate_brigade(f, tmp_bb, NULL);
1496
0
            apr_brigade_cleanup(tmp_bb);
1497
0
            if (f->frec == ap_core_input_filter_handle) {
1498
0
                break;
1499
0
            }
1500
0
            ap_remove_input_filter(f);
1501
0
            f = f->next;
1502
0
        }
1503
0
        conn->input_filters = r->input_filters = f;
1504
0
        conn->keepalive = AP_CONN_CLOSE;
1505
0
    }
1506
1507
0
die_before_hooks:
1508
    /* First call to ap_die() (non recursive) */
1509
0
    r->status = HTTP_OK;
1510
1511
0
die:
1512
0
    ap_die(access_status, r);
1513
1514
    /* ap_die() sent the response through the output filters, we must now
1515
     * end the request with an EOR bucket for stream/pipeline accounting.
1516
     */
1517
0
    {
1518
0
        apr_bucket_brigade *eor_bb;
1519
0
        eor_bb = ap_acquire_brigade(conn);
1520
0
        APR_BRIGADE_INSERT_TAIL(eor_bb,
1521
0
                                ap_bucket_eor_create(conn->bucket_alloc, r));
1522
0
        ap_pass_brigade(conn->output_filters, eor_bb);
1523
0
        ap_release_brigade(conn, eor_bb);
1524
0
    }
1525
1526
0
ignore:
1527
0
    r = NULL;
1528
0
    AP_READ_REQUEST_FAILURE((uintptr_t)r);
1529
0
    return NULL;
1530
0
}
1531
1532
AP_DECLARE(int) ap_post_read_request(request_rec *r)
1533
0
{
1534
0
    int status;
1535
1536
0
    if ((status = ap_run_post_read_request(r))) {
1537
0
        return status;
1538
0
    }
1539
1540
    /* Enforce http(s) only scheme for non-forward-proxy requests */
1541
0
    if (!r->proxyreq
1542
0
            && r->parsed_uri.scheme
1543
0
            && (ap_cstr_casecmpn(r->parsed_uri.scheme, "http", 4) != 0
1544
0
                || (r->parsed_uri.scheme[4] != '\0'
1545
0
                    && (apr_tolower(r->parsed_uri.scheme[4]) != 's'
1546
0
                        || r->parsed_uri.scheme[5] != '\0')))) {
1547
0
        return HTTP_BAD_REQUEST;
1548
0
    }
1549
1550
0
    return OK;
1551
0
}
1552
1553
/* if a request with a body creates a subrequest, remove original request's
1554
 * input headers which pertain to the body which has already been read.
1555
 * out-of-line helper function for ap_set_sub_req_protocol.
1556
 */
1557
1558
static void strip_headers_request_body(request_rec *rnew)
1559
0
{
1560
0
    apr_table_unset(rnew->headers_in, "Content-Encoding");
1561
0
    apr_table_unset(rnew->headers_in, "Content-Language");
1562
0
    apr_table_unset(rnew->headers_in, "Content-Length");
1563
0
    apr_table_unset(rnew->headers_in, "Content-Location");
1564
0
    apr_table_unset(rnew->headers_in, "Content-MD5");
1565
0
    apr_table_unset(rnew->headers_in, "Content-Range");
1566
0
    apr_table_unset(rnew->headers_in, "Content-Type");
1567
0
    apr_table_unset(rnew->headers_in, "Expires");
1568
0
    apr_table_unset(rnew->headers_in, "Last-Modified");
1569
0
    apr_table_unset(rnew->headers_in, "Transfer-Encoding");
1570
0
}
1571
1572
/*
1573
 * A couple of other functions which initialize some of the fields of
1574
 * a request structure, as appropriate for adjuncts of one kind or another
1575
 * to a request in progress.  Best here, rather than elsewhere, since
1576
 * *someone* has to set the protocol-specific fields...
1577
 */
1578
1579
AP_DECLARE(void) ap_set_sub_req_protocol(request_rec *rnew,
1580
                                         const request_rec *r)
1581
0
{
1582
0
    rnew->the_request     = r->the_request;  /* Keep original request-line */
1583
1584
0
    rnew->assbackwards    = 1;   /* Don't send headers from this. */
1585
0
    rnew->no_local_copy   = 1;   /* Don't try to send HTTP_NOT_MODIFIED for a
1586
                                  * fragment. */
1587
0
    rnew->method          = "GET";
1588
0
    rnew->method_number   = M_GET;
1589
0
    rnew->protocol        = "INCLUDED";
1590
1591
0
    rnew->status          = HTTP_OK;
1592
1593
0
    rnew->headers_in      = apr_table_copy(rnew->pool, r->headers_in);
1594
0
    rnew->trailers_in     = apr_table_copy(rnew->pool, r->trailers_in);
1595
1596
    /* did the original request have a body?  (e.g. POST w/SSI tags)
1597
     * if so, make sure the subrequest doesn't inherit body headers
1598
     */
1599
0
    if (!r->kept_body && (apr_table_get(r->headers_in, "Content-Length")
1600
0
        || apr_table_get(r->headers_in, "Transfer-Encoding"))) {
1601
0
        strip_headers_request_body(rnew);
1602
0
    }
1603
0
    rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
1604
0
    rnew->headers_out     = apr_table_make(rnew->pool, 5);
1605
0
    rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1606
0
    rnew->trailers_out    = apr_table_make(rnew->pool, 5);
1607
0
    rnew->notes           = apr_table_make(rnew->pool, 5);
1608
1609
0
    rnew->expecting_100   = r->expecting_100;
1610
0
    rnew->read_length     = r->read_length;
1611
0
    rnew->read_body       = REQUEST_NO_BODY;
1612
1613
0
    rnew->main = (request_rec *) r;
1614
0
}
1615
1616
static void end_output_stream(request_rec *r, int status)
1617
0
{
1618
0
    conn_rec *c = r->connection;
1619
0
    apr_bucket_brigade *bb;
1620
0
    apr_bucket *b;
1621
1622
0
    bb = apr_brigade_create(r->pool, c->bucket_alloc);
1623
0
    if (status != OK) {
1624
0
        b = ap_bucket_error_create(status, NULL, r->pool, c->bucket_alloc);
1625
0
        APR_BRIGADE_INSERT_TAIL(bb, b);
1626
0
    }
1627
0
    b = apr_bucket_eos_create(c->bucket_alloc);
1628
0
    APR_BRIGADE_INSERT_TAIL(bb, b);
1629
1630
0
    ap_pass_brigade(r->output_filters, bb);
1631
0
    apr_brigade_cleanup(bb);
1632
0
}
1633
1634
AP_DECLARE(void) ap_finalize_sub_req_protocol(request_rec *sub)
1635
0
{
1636
    /* tell the filter chain there is no more content coming */
1637
0
    if (!sub->eos_sent) {
1638
0
        end_output_stream(sub, OK);
1639
0
    }
1640
0
}
1641
1642
/* finalize_request_protocol is called at completion of sending the
1643
 * response.  Its sole purpose is to send the terminating protocol
1644
 * information for any wrappers around the response message body
1645
 * (i.e., transfer encodings).  It should have been named finalize_response.
1646
 */
1647
AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1648
0
{
1649
0
    int status = ap_discard_request_body(r);
1650
1651
    /* tell the filter chain there is no more content coming */
1652
0
    if (!r->eos_sent) {
1653
0
        end_output_stream(r, status);
1654
0
    }
1655
0
}
1656
1657
/*
1658
 * Support for the Basic authentication protocol, and a bit for Digest.
1659
 */
1660
AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1661
0
{
1662
0
    const char *type = ap_auth_type(r);
1663
0
    if (type) {
1664
0
        ap_run_note_auth_failure(r, type);
1665
0
    }
1666
0
    else {
1667
0
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00571)
1668
0
                      "need AuthType to note auth failure: %s", r->uri);
1669
0
    }
1670
0
}
1671
1672
AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1673
0
{
1674
0
    ap_note_auth_failure(r);
1675
0
}
1676
1677
AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1678
0
{
1679
0
    ap_note_auth_failure(r);
1680
0
}
1681
1682
AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1683
0
{
1684
0
    const char *t, *auth_line;
1685
1686
0
    if (!(t = ap_auth_type(r)) || ap_cstr_casecmp(t, "Basic"))
1687
0
        return DECLINED;
1688
1689
0
    if (!ap_auth_name(r)) {
1690
0
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00572) 
1691
0
                      "need AuthName: %s", r->uri);
1692
0
        return HTTP_INTERNAL_SERVER_ERROR;
1693
0
    }
1694
1695
0
    auth_line = apr_table_get(r->headers_in,
1696
0
                              (PROXYREQ_PROXY == r->proxyreq)
1697
0
                                  ? "Proxy-Authorization" : "Authorization");
1698
1699
0
    if (!auth_line) {
1700
0
        ap_note_auth_failure(r);
1701
0
        return HTTP_UNAUTHORIZED;
1702
0
    }
1703
1704
0
    if (ap_cstr_casecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1705
        /* Client tried to authenticate using wrong auth scheme */
1706
0
        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00573)
1707
0
                      "client used wrong authentication scheme: %s", r->uri);
1708
0
        ap_note_auth_failure(r);
1709
0
        return HTTP_UNAUTHORIZED;
1710
0
    }
1711
1712
0
    while (*auth_line == ' ' || *auth_line == '\t') {
1713
0
        auth_line++;
1714
0
    }
1715
1716
0
    t = ap_pbase64decode(r->pool, auth_line);
1717
0
    r->user = ap_getword_nulls (r->pool, &t, ':');
1718
0
    apr_table_setn(r->notes, AP_GET_BASIC_AUTH_PW_NOTE, "1");
1719
0
    r->ap_auth_type = "Basic";
1720
1721
0
    *pw = t;
1722
1723
0
    return OK;
1724
0
}
1725
1726
AP_DECLARE(apr_status_t) ap_get_basic_auth_components(const request_rec *r,
1727
                                                      const char **username,
1728
                                                      const char **password)
1729
0
{
1730
0
    const char *auth_header;
1731
0
    const char *credentials;
1732
0
    const char *decoded;
1733
0
    const char *user;
1734
1735
0
    auth_header = (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization"
1736
0
                                                  : "Authorization";
1737
0
    credentials = apr_table_get(r->headers_in, auth_header);
1738
1739
0
    if (!credentials) {
1740
        /* No auth header. */
1741
0
        return APR_EINVAL;
1742
0
    }
1743
1744
0
    if (ap_cstr_casecmp(ap_getword(r->pool, &credentials, ' '), "Basic")) {
1745
        /* These aren't Basic credentials. */
1746
0
        return APR_EINVAL;
1747
0
    }
1748
1749
0
    while (*credentials == ' ' || *credentials == '\t') {
1750
0
        credentials++;
1751
0
    }
1752
1753
    /* XXX Our base64 decoding functions don't actually error out if the string
1754
     * we give it isn't base64; they'll just silently stop and hand us whatever
1755
     * they've parsed up to that point.
1756
     *
1757
     * Since this function is supposed to be a drop-in replacement for the
1758
     * deprecated ap_get_basic_auth_pw(), don't fix this for 2.4.x.
1759
     */
1760
0
    decoded = ap_pbase64decode(r->pool, credentials);
1761
0
    user = ap_getword_nulls(r->pool, &decoded, ':');
1762
1763
0
    if (username) {
1764
0
        *username = user;
1765
0
    }
1766
0
    if (password) {
1767
0
        *password = decoded;
1768
0
    }
1769
1770
0
    return APR_SUCCESS;
1771
0
}
1772
1773
struct content_length_ctx {
1774
    int data_sent;  /* true if the C-L filter has already sent at
1775
                     * least one bucket on to the next output filter
1776
                     * for this request
1777
                     */
1778
    apr_bucket_brigade *tmpbb;
1779
};
1780
1781
/* This filter computes the content length, but it also computes the number
1782
 * of bytes sent to the client.  This means that this filter will always run
1783
 * through all of the buckets in all brigades
1784
 */
1785
AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(
1786
    ap_filter_t *f,
1787
    apr_bucket_brigade *b)
1788
0
{
1789
0
    request_rec *r = f->r;
1790
0
    struct content_length_ctx *ctx;
1791
0
    apr_bucket *e;
1792
0
    int eos = 0;
1793
0
    apr_read_type_e eblock = APR_NONBLOCK_READ;
1794
1795
0
    ctx = f->ctx;
1796
0
    if (!ctx) {
1797
0
        f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
1798
0
        ctx->data_sent = 0;
1799
0
        ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1800
0
    }
1801
1802
    /* Loop through the brigade to count the length. To avoid
1803
     * arbitrary memory consumption with morphing bucket types, this
1804
     * loop will stop and pass on the brigade when necessary. */
1805
0
    e = APR_BRIGADE_FIRST(b);
1806
0
    while (e != APR_BRIGADE_SENTINEL(b)) {
1807
0
        apr_status_t rv;
1808
1809
0
        if (APR_BUCKET_IS_EOS(e)) {
1810
0
            eos = 1;
1811
0
            break;
1812
0
        }
1813
        /* For a flush bucket, fall through to pass the brigade and
1814
         * flush now. */
1815
0
        else if (APR_BUCKET_IS_FLUSH(e)) {
1816
0
            e = APR_BUCKET_NEXT(e);
1817
0
        }
1818
        /* For metadata bucket types other than FLUSH, loop. */
1819
0
        else if (APR_BUCKET_IS_METADATA(e)) {
1820
0
            e = APR_BUCKET_NEXT(e);
1821
0
            continue;
1822
0
        }
1823
        /* For determinate length data buckets, count the length and
1824
         * continue. */
1825
0
        else if (e->length != (apr_size_t)-1) {
1826
0
            r->bytes_sent += e->length;
1827
0
            e = APR_BUCKET_NEXT(e);
1828
0
            continue;
1829
0
        }
1830
        /* For indeterminate length data buckets, perform one read. */
1831
0
        else /* e->length == (apr_size_t)-1 */ {
1832
0
            apr_size_t len;
1833
0
            const char *ignored;
1834
        
1835
0
            rv = apr_bucket_read(e, &ignored, &len, eblock);
1836
0
            if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1837
0
                ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00574)
1838
0
                              "ap_content_length_filter: "
1839
0
                              "apr_bucket_read() failed");
1840
0
                return rv;
1841
0
            }
1842
0
            if (rv == APR_SUCCESS) {
1843
0
                eblock = APR_NONBLOCK_READ;
1844
0
                e = APR_BUCKET_NEXT(e);
1845
0
                r->bytes_sent += len;
1846
0
            }
1847
0
            else if (APR_STATUS_IS_EAGAIN(rv)) {
1848
0
                apr_bucket *flush;
1849
1850
                /* Next read must block. */
1851
0
                eblock = APR_BLOCK_READ;
1852
1853
                /* Ensure the last bucket to pass down is a flush if
1854
                 * the next read will block. */
1855
0
                flush = apr_bucket_flush_create(f->c->bucket_alloc);
1856
0
                APR_BUCKET_INSERT_BEFORE(e, flush);
1857
0
            }
1858
0
        }
1859
1860
        /* Optimization: if the next bucket is EOS (directly after a
1861
         * bucket morphed to the heap, or a flush), short-cut to
1862
         * handle EOS straight away - allowing C-L to be determined
1863
         * for content which is already entirely in memory. */
1864
0
        if (e != APR_BRIGADE_SENTINEL(b) && APR_BUCKET_IS_EOS(e)) {
1865
0
            continue;
1866
0
        }
1867
1868
        /* On reaching here, pass on everything in the brigade up to
1869
         * this point. */
1870
0
        apr_brigade_split_ex(b, e, ctx->tmpbb);
1871
        
1872
0
        rv = ap_pass_brigade(f->next, b);
1873
0
        if (rv != APR_SUCCESS) {
1874
0
            return rv;
1875
0
        }
1876
0
        else if (f->c->aborted) {
1877
0
            return APR_ECONNABORTED;
1878
0
        }
1879
0
        apr_brigade_cleanup(b);
1880
0
        APR_BRIGADE_CONCAT(b, ctx->tmpbb);
1881
0
        e = APR_BRIGADE_FIRST(b);
1882
        
1883
0
        ctx->data_sent = 1;
1884
0
    }
1885
1886
    /* If we've now seen the entire response and it's otherwise
1887
     * okay to set the C-L in the response header, then do so now.
1888
     *
1889
     * We can only set a C-L in the response header if we haven't already
1890
     * sent any buckets on to the next output filter for this request.
1891
     */
1892
0
    if (ctx->data_sent == 0 && eos) {
1893
0
        core_server_config *conf =
1894
0
            ap_get_core_module_config(r->server->module_config);
1895
1896
        /* This is a hack, but I can't find anyway around it.  The idea is that
1897
         * we don't want to send out 0 Content-Lengths if it is a HEAD request.
1898
         * [Unless the corresponding body (for a GET) would really be empty!]
1899
         * This happens when modules try to outsmart the server, and return
1900
         * if they see a HEAD request.  Apache 1.3 handlers were supposed to
1901
         * just return in that situation, and the core handled the HEAD.  From
1902
         * 2.0, if a handler returns, then the core sends an EOS bucket down
1903
         * the filter stack, and this content-length filter computes a length
1904
         * of zero and we would end up sending a zero C-L to the client.
1905
         * We can't just remove the this C-L filter, because well behaved 2.0+
1906
         * handlers will send their data down the stack, and we will compute
1907
         * a real C-L for the head request. RBB
1908
         *
1909
         * Allow modification of this behavior through the
1910
         * HttpContentLengthHeadZero directive.
1911
         *
1912
         * The default (unset) behavior is to squelch the C-L in this case.
1913
         */
1914
1915
        /* don't whack the C-L if it has already been set for a HEAD
1916
         * by something like proxy.  the brigade only has an EOS bucket
1917
         * in this case, making r->bytes_sent zero, and either there is
1918
         * an existing C-L we want to preserve, or r->sent_bodyct is not
1919
         * zero (the empty body is being sent) thus we don't want to add
1920
         * a C-L of zero (the backend did not provide it, neither do we).
1921
         *
1922
         * if r->bytes_sent > 0 we have a (temporary) body whose length may
1923
         * have been changed by a filter.  the C-L header might not have been
1924
         * updated so we do it here.  long term it would be cleaner to have
1925
         * such filters update or remove the C-L header, and just use it
1926
         * if present.
1927
         */
1928
0
        if (!((r->header_only || AP_STATUS_IS_HEADER_ONLY(r->status))
1929
0
              && !r->bytes_sent
1930
0
              && (r->sent_bodyct
1931
0
                  || conf->http_cl_head_zero != AP_HTTP_CL_HEAD_ZERO_ENABLE
1932
0
                  || apr_table_get(r->headers_out, "Content-Length")))) {
1933
0
            ap_set_content_length(r, r->bytes_sent);
1934
0
        }
1935
0
    }
1936
1937
0
    ctx->data_sent = 1;
1938
0
    return ap_pass_brigade(f->next, b);
1939
0
}
1940
1941
/*
1942
 * Send the body of a response to the client.
1943
 */
1944
AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1945
                                    apr_off_t offset, apr_size_t len,
1946
                                    apr_size_t *nbytes)
1947
0
{
1948
0
    conn_rec *c = r->connection;
1949
0
    apr_bucket_brigade *bb = NULL;
1950
0
    apr_status_t rv;
1951
1952
0
    bb = apr_brigade_create(r->pool, c->bucket_alloc);
1953
1954
0
    apr_brigade_insert_file(bb, fd, offset, len, r->pool);
1955
1956
0
    rv = ap_pass_brigade(r->output_filters, bb);
1957
0
    if (rv != APR_SUCCESS) {
1958
0
        *nbytes = 0; /* no way to tell how many were actually sent */
1959
0
    }
1960
0
    else {
1961
0
        *nbytes = len;
1962
0
    }
1963
1964
0
    return rv;
1965
0
}
1966
1967
#if APR_HAS_MMAP
1968
/* send data from an in-memory buffer */
1969
AP_DECLARE(apr_size_t) ap_send_mmap(apr_mmap_t *mm,
1970
                                    request_rec *r,
1971
                                    apr_size_t offset,
1972
                                    apr_size_t length)
1973
0
{
1974
0
    conn_rec *c = r->connection;
1975
0
    apr_bucket_brigade *bb = NULL;
1976
0
    apr_bucket *b;
1977
1978
0
    bb = apr_brigade_create(r->pool, c->bucket_alloc);
1979
0
    b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1980
0
    APR_BRIGADE_INSERT_TAIL(bb, b);
1981
0
    ap_pass_brigade(r->output_filters, bb);
1982
1983
0
    return mm->size; /* XXX - change API to report apr_status_t? */
1984
0
}
1985
#endif /* APR_HAS_MMAP */
1986
1987
typedef struct {
1988
    apr_bucket_brigade *bb;
1989
    apr_bucket_brigade *tmpbb;
1990
} old_write_filter_ctx;
1991
1992
AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1993
    ap_filter_t *f, apr_bucket_brigade *bb)
1994
0
{
1995
0
    old_write_filter_ctx *ctx = f->ctx;
1996
1997
0
    AP_DEBUG_ASSERT(ctx);
1998
1999
0
    if (ctx->bb != NULL) {
2000
        /* whatever is coming down the pipe (we don't care), we
2001
         * can simply insert our buffered data at the front and
2002
         * pass the whole bundle down the chain.
2003
         */
2004
0
        APR_BRIGADE_PREPEND(bb, ctx->bb);
2005
0
    }
2006
2007
0
    return ap_pass_brigade(f->next, bb);
2008
0
}
2009
2010
static ap_filter_t *insert_old_write_filter(request_rec *r)
2011
0
{
2012
0
    ap_filter_t *f;
2013
0
    old_write_filter_ctx *ctx;
2014
2015
    /* future optimization: record some flags in the request_rec to
2016
     * say whether we've added our filter, and whether it is first.
2017
     */
2018
2019
    /* this will typically exit on the first test */
2020
0
    for (f = r->output_filters; f != NULL; f = f->next) {
2021
0
        if (ap_old_write_func == f->frec)
2022
0
            break;
2023
0
    }
2024
2025
0
    if (f == NULL) {
2026
        /* our filter hasn't been added yet */
2027
0
        ctx = apr_pcalloc(r->pool, sizeof(*ctx));
2028
0
        ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2029
2030
0
        ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
2031
0
        f = r->output_filters;
2032
0
    }
2033
2034
0
    return f;
2035
0
}
2036
2037
static apr_status_t buffer_output(request_rec *r,
2038
                                  const char *str, apr_size_t len)
2039
0
{
2040
0
    conn_rec *c = r->connection;
2041
0
    ap_filter_t *f;
2042
0
    old_write_filter_ctx *ctx;
2043
2044
0
    if (len == 0)
2045
0
        return APR_SUCCESS;
2046
2047
0
    f = insert_old_write_filter(r);
2048
0
    ctx = f->ctx;
2049
2050
    /* if the first filter is not our buffering filter, then we have to
2051
     * deliver the content through the normal filter chain
2052
     */
2053
0
    if (f != r->output_filters) {
2054
0
        apr_status_t rv;
2055
0
        apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
2056
0
        APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
2057
2058
0
        rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
2059
0
        apr_brigade_cleanup(ctx->tmpbb);
2060
0
        return rv;
2061
0
    }
2062
2063
0
    if (ctx->bb == NULL) {
2064
0
        ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
2065
0
    }
2066
2067
0
    return ap_fwrite(f->next, ctx->bb, str, len);
2068
0
}
2069
2070
AP_DECLARE(int) ap_rputc(int c, request_rec *r)
2071
0
{
2072
0
    char c2 = (char)c;
2073
2074
0
    if (r->connection->aborted) {
2075
0
        return -1;
2076
0
    }
2077
2078
0
    if (buffer_output(r, &c2, 1) != APR_SUCCESS)
2079
0
        return -1;
2080
2081
0
    return c;
2082
0
}
2083
2084
AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
2085
0
{
2086
0
    if (nbyte < 0)
2087
0
        return -1;
2088
2089
0
    if (r->connection->aborted)
2090
0
        return -1;
2091
2092
0
    if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
2093
0
        return -1;
2094
2095
0
    return nbyte;
2096
0
}
2097
2098
struct ap_vrprintf_data {
2099
    apr_vformatter_buff_t vbuff;
2100
    request_rec *r;
2101
    char *buff;
2102
};
2103
2104
/* Flush callback for apr_vformatter; returns -1 on error. */
2105
static int r_flush(apr_vformatter_buff_t *buff)
2106
0
{
2107
    /* callback function passed to ap_vformatter to be called when
2108
     * vformatter needs to write into buff and buff.curpos > buff.endpos */
2109
2110
    /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
2111
     * "downcast" to an ap_vrprintf_data */
2112
0
    struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
2113
2114
0
    if (vd->r->connection->aborted)
2115
0
        return -1;
2116
2117
    /* r_flush is called when vbuff is completely full */
2118
0
    if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
2119
0
        return -1;
2120
0
    }
2121
2122
    /* reset the buffer position */
2123
0
    vd->vbuff.curpos = vd->buff;
2124
0
    vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
2125
2126
0
    return 0;
2127
0
}
2128
2129
AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
2130
0
{
2131
0
    int written;
2132
0
    struct ap_vrprintf_data vd;
2133
0
    char vrprintf_buf[AP_IOBUFSIZE];
2134
2135
0
    vd.vbuff.curpos = vrprintf_buf;
2136
0
    vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
2137
0
    vd.r = r;
2138
0
    vd.buff = vrprintf_buf;
2139
2140
0
    if (r->connection->aborted)
2141
0
        return -1;
2142
2143
0
    written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
2144
2145
0
    if (written != -1) {
2146
0
        int n = vd.vbuff.curpos - vrprintf_buf;
2147
2148
        /* last call to buffer_output, to finish clearing the buffer */
2149
0
        if (buffer_output(r, vrprintf_buf, n) != APR_SUCCESS)
2150
0
            return -1;
2151
2152
0
        written += n;
2153
0
    }
2154
2155
0
    return written;
2156
0
}
2157
2158
AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
2159
0
{
2160
0
    va_list va;
2161
0
    int n;
2162
2163
0
    if (r->connection->aborted)
2164
0
        return -1;
2165
2166
0
    va_start(va, fmt);
2167
0
    n = ap_vrprintf(r, fmt, va);
2168
0
    va_end(va);
2169
2170
0
    return n;
2171
0
}
2172
2173
AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
2174
0
{
2175
0
    va_list va;
2176
0
    const char *s;
2177
0
    apr_size_t len;
2178
0
    apr_size_t written = 0;
2179
2180
0
    if (r->connection->aborted)
2181
0
        return -1;
2182
2183
    /* ### TODO: if the total output is large, put all the strings
2184
     * ### into a single brigade, rather than flushing each time we
2185
     * ### fill the buffer
2186
     */
2187
0
    va_start(va, r);
2188
0
    while (1) {
2189
0
        s = va_arg(va, const char *);
2190
0
        if (s == NULL)
2191
0
            break;
2192
2193
0
        len = strlen(s);
2194
0
        if (buffer_output(r, s, len) != APR_SUCCESS) {
2195
0
            va_end(va);
2196
0
            return -1;
2197
0
        }
2198
2199
0
        written += len;
2200
0
    }
2201
0
    va_end(va);
2202
2203
0
    return written;
2204
0
}
2205
2206
AP_DECLARE(int) ap_rflush(request_rec *r)
2207
0
{
2208
0
    conn_rec *c = r->connection;
2209
0
    apr_bucket *b;
2210
0
    ap_filter_t *f;
2211
0
    old_write_filter_ctx *ctx;
2212
0
    apr_status_t rv;
2213
2214
0
    f = insert_old_write_filter(r);
2215
0
    ctx = f->ctx;
2216
2217
0
    b = apr_bucket_flush_create(c->bucket_alloc);
2218
0
    APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
2219
2220
0
    rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
2221
0
    apr_brigade_cleanup(ctx->tmpbb);
2222
0
    if (rv != APR_SUCCESS)
2223
0
        return -1;
2224
2225
0
    return 0;
2226
0
}
2227
2228
/*
2229
 * This function sets the Last-Modified output header field to the value
2230
 * of the mtime field in the request structure - rationalized to keep it from
2231
 * being in the future.
2232
 */
2233
AP_DECLARE(void) ap_set_last_modified(request_rec *r)
2234
0
{
2235
0
    if (!r->assbackwards) {
2236
0
        apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
2237
0
        char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
2238
2239
0
        apr_rfc822_date(datestr, mod_time);
2240
0
        apr_table_setn(r->headers_out, "Last-Modified", datestr);
2241
0
    }
2242
0
}
2243
2244
typedef struct hdr_ptr {
2245
    ap_filter_t *f;
2246
    apr_bucket_brigade *bb;
2247
} hdr_ptr;
2248
2249
 
2250
AP_DECLARE(void) ap_set_std_response_headers(request_rec *r)
2251
0
{
2252
0
    const char *server = NULL, *date;
2253
0
    char *s;
2254
2255
    /* Before generating a response, we make sure that `Date` and `Server`
2256
     * headers are present. When proxying requests, we preserver existing
2257
     * values and replace them otherwise.
2258
     */
2259
0
    if (r->proxyreq != PROXYREQ_NONE) {
2260
0
        date = apr_table_get(r->headers_out, "Date");
2261
0
        if (!date) {
2262
0
            s = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
2263
0
            ap_recent_rfc822_date(s, r->request_time);
2264
0
            date = s;
2265
0
        }
2266
0
        server = apr_table_get(r->headers_out, "Server");
2267
0
    }
2268
0
    else {
2269
0
        s = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
2270
0
        ap_recent_rfc822_date(s, r->request_time);
2271
0
        date = s;
2272
0
    }
2273
2274
0
    apr_table_setn(r->headers_out, "Date", date);
2275
2276
0
    if (!server)
2277
0
        server = ap_get_server_banner();
2278
0
    if (server && *server)
2279
0
        apr_table_setn(r->headers_out, "Server", server);
2280
0
}
2281
2282
AP_DECLARE(void) ap_send_interim_response(request_rec *r, int send_headers)
2283
0
{
2284
0
    request_rec *rr;
2285
0
    apr_bucket *b;
2286
0
    apr_bucket_brigade *bb;
2287
0
    const char *reason = NULL;
2288
2289
0
    if (r->proto_num < HTTP_VERSION(1,1)) {
2290
        /* don't send interim response to HTTP/1.0 Client */
2291
0
        return;
2292
0
    }
2293
0
    if (!ap_is_HTTP_INFO(r->status)) {
2294
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00575)
2295
0
                      "Status is %d - not sending interim response", r->status);
2296
0
        return;
2297
0
    }
2298
0
    if (r->status == HTTP_CONTINUE) {
2299
0
        if (!r->expecting_100) {
2300
            /*
2301
             * Don't send 100-Continue when there was no Expect: 100-continue
2302
             * in the request headers. For origin servers this is a SHOULD NOT
2303
             * for proxies it is a MUST NOT according to RFC 2616 8.2.3
2304
             */
2305
0
            return;
2306
0
        }
2307
2308
        /* if we send an interim response, we're no longer in a state of
2309
         * expecting one.  Also, this could feasibly be in a subrequest,
2310
         * so we need to propagate the fact that we responded.
2311
         */
2312
0
        for (rr = r; rr != NULL; rr = rr->main) {
2313
0
            rr->expecting_100 = 0;
2314
0
        }
2315
0
    }
2316
2317
0
    ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2318
0
                  "ap_send_interim_response: send %d", r->status);
2319
0
    bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2320
0
    if (send_headers) {
2321
0
        ap_set_std_response_headers(r);
2322
0
    }
2323
0
    if (r->status_line && strlen(r->status_line) > 4) {
2324
0
        reason = r->status_line + 4;
2325
        /* Reject control characters in the reason phrase to prevent
2326
         * forwarding backend-controlled bare CR in the status line. */
2327
0
        if (*ap_scan_http_field_content(reason)) {
2328
0
            reason = NULL;
2329
0
        }
2330
0
    }
2331
0
    b = ap_bucket_response_create(r->status, reason,
2332
0
                                  send_headers? r->headers_out : NULL,
2333
0
                                  r->notes, r->pool, r->connection->bucket_alloc);
2334
0
    APR_BRIGADE_INSERT_TAIL(bb, b);
2335
0
    if (send_headers) {
2336
0
        apr_table_clear(r->headers_out);
2337
0
    }
2338
0
    b = apr_bucket_flush_create(r->connection->bucket_alloc);
2339
0
    APR_BRIGADE_INSERT_TAIL(bb, b);
2340
0
    ap_pass_brigade(r->proto_output_filters, bb);
2341
0
    apr_brigade_destroy(bb);
2342
0
}
2343
2344
/*
2345
 * Compare two protocol identifier. Result is similar to strcmp():
2346
 * 0 gives same precedence, >0 means proto1 is preferred.
2347
 */
2348
static int protocol_cmp(const apr_array_header_t *preferences,
2349
                        const char *proto1,
2350
                        const char *proto2)
2351
0
{
2352
0
    if (preferences && preferences->nelts > 0) {
2353
0
        int index1 = ap_array_str_index(preferences, proto1, 0);
2354
0
        int index2 = ap_array_str_index(preferences, proto2, 0);
2355
0
        if (index2 > index1) {
2356
0
            return (index1 >= 0) ? 1 : -1;
2357
0
        }
2358
0
        else if (index1 > index2) {
2359
0
            return (index2 >= 0) ? -1 : 1;
2360
0
        }
2361
0
    }
2362
    /* both have the same index (maybe -1 or no pref configured) and we compare
2363
     * the names so that spdy3 gets precedence over spdy2. That makes
2364
     * the outcome at least deterministic. */
2365
0
    return strcmp(proto1, proto2);
2366
0
}
2367
2368
AP_DECLARE(const char *) ap_get_protocol(conn_rec *c)
2369
0
{
2370
0
    const char *protocol = ap_run_protocol_get(c);
2371
0
    return protocol? protocol : AP_PROTOCOL_HTTP1;
2372
0
}
2373
2374
AP_DECLARE(apr_status_t) ap_get_protocol_upgrades(conn_rec *c, request_rec *r, 
2375
                                                  server_rec *s, int report_all, 
2376
                                                  const apr_array_header_t **pupgrades)
2377
0
{
2378
0
    apr_pool_t *pool = r? r->pool : c->pool;
2379
0
    core_server_config *conf;
2380
0
    const char *existing;
2381
0
    apr_array_header_t *upgrades = NULL;
2382
2383
0
    if (!s) {
2384
0
        s = (r? r->server : c->base_server);
2385
0
    }
2386
0
    conf = ap_get_core_module_config(s->module_config);
2387
    
2388
0
    if (conf->protocols->nelts > 0) {
2389
0
        existing = ap_get_protocol(c);
2390
0
        if (conf->protocols->nelts > 1 
2391
0
            || !ap_array_str_contains(conf->protocols, existing)) {
2392
0
            int i;
2393
            
2394
            /* possibly more than one choice or one, but not the
2395
             * existing. (TODO: maybe 426 and Upgrade then?) */
2396
0
            upgrades = apr_array_make(pool, conf->protocols->nelts + 1, 
2397
0
                                      sizeof(char *));
2398
0
            for (i = 0; i < conf->protocols->nelts; i++) {
2399
0
                const char *p = APR_ARRAY_IDX(conf->protocols, i, char *);
2400
                /* RFC 9113, Section 3.3: HTTP/2 over TLS is negotiated
2401
                 * exclusively via ALPN; 'h2' must never be offered through
2402
                 * the HTTP/1.1 Upgrade mechanism on a TLS connection. */
2403
0
                if (!strcmp("h2", p) && ap_ssl_conn_is_ssl(c)) {
2404
0
                    continue;
2405
0
                }
2406
0
                if (strcmp(existing, p)) {
2407
                    /* not the one we have and possible, add in this order */
2408
0
                    APR_ARRAY_PUSH(upgrades, const char*) = p;
2409
0
                }
2410
0
                else if (!report_all) {
2411
0
                    break;
2412
0
                }
2413
0
            }
2414
0
        }
2415
0
    }
2416
    
2417
0
    *pupgrades = upgrades;
2418
0
    return APR_SUCCESS;
2419
0
}
2420
2421
AP_DECLARE(const char *) ap_select_protocol(conn_rec *c, request_rec *r, 
2422
                                            server_rec *s,
2423
                                            const apr_array_header_t *choices)
2424
0
{
2425
0
    apr_pool_t *pool = r? r->pool : c->pool;
2426
0
    core_server_config *conf;
2427
0
    const char *protocol = NULL, *existing;
2428
0
    apr_array_header_t *proposals;
2429
2430
0
    if (!s) {
2431
0
        s = (r? r->server : c->base_server);
2432
0
    }
2433
0
    conf = ap_get_core_module_config(s->module_config);
2434
    
2435
0
    if (APLOGcdebug(c)) {
2436
0
        const char *p = apr_array_pstrcat(pool, conf->protocols, ',');
2437
0
        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03155) 
2438
0
                      "select protocol from %s, choices=%s for server %s", 
2439
0
                      p, apr_array_pstrcat(pool, choices, ','),
2440
0
                      s->server_hostname);
2441
0
    }
2442
2443
0
    if (conf->protocols->nelts <= 0) {
2444
        /* nothing configured, by default, we only allow http/1.1 here.
2445
         * For now...
2446
         */
2447
0
        if (ap_array_str_contains(choices, AP_PROTOCOL_HTTP1)) {
2448
0
            return AP_PROTOCOL_HTTP1;
2449
0
        }
2450
0
        else {
2451
0
            return NULL;
2452
0
        }
2453
0
    }
2454
2455
0
    proposals = apr_array_make(pool, choices->nelts + 1, sizeof(char *));
2456
0
    ap_run_protocol_propose(c, r, s, choices, proposals);
2457
2458
    /* If the existing protocol has not been proposed, but is a choice,
2459
     * add it to the proposals implicitly.
2460
     */
2461
0
    existing = ap_get_protocol(c);
2462
0
    if (!ap_array_str_contains(proposals, existing)
2463
0
        && ap_array_str_contains(choices, existing)) {
2464
0
        APR_ARRAY_PUSH(proposals, const char*) = existing;
2465
0
    }
2466
2467
0
    if (proposals->nelts > 0) {
2468
0
        int i;
2469
0
        const apr_array_header_t *prefs = NULL;
2470
2471
        /* Default for protocols_honor_order is 'on' or != 0 */
2472
0
        if (conf->protocols_honor_order == 0 && choices->nelts > 0) {
2473
0
            prefs = choices;
2474
0
        }
2475
0
        else {
2476
0
            prefs = conf->protocols;
2477
0
        }
2478
2479
        /* Select the most preferred protocol */
2480
0
        if (APLOGcdebug(c)) {
2481
0
            ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03156) 
2482
0
                          "select protocol, proposals=%s preferences=%s configured=%s", 
2483
0
                          apr_array_pstrcat(pool, proposals, ','),
2484
0
                          apr_array_pstrcat(pool, prefs, ','),
2485
0
                          apr_array_pstrcat(pool, conf->protocols, ','));
2486
0
        }
2487
0
        for (i = 0; i < proposals->nelts; ++i) {
2488
0
            const char *p = APR_ARRAY_IDX(proposals, i, const char *);
2489
0
            if (!ap_array_str_contains(conf->protocols, p)) {
2490
                /* not a configured protocol here */
2491
0
                continue;
2492
0
            }
2493
0
            else if (!protocol 
2494
0
                     || (protocol_cmp(prefs, protocol, p) < 0)) {
2495
                /* none selected yet or this one has preference */
2496
0
                protocol = p;
2497
0
            }
2498
0
        }
2499
0
    }
2500
0
    if (APLOGcdebug(c)) {
2501
0
        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03157)
2502
0
                      "selected protocol=%s", 
2503
0
                      protocol? protocol : "(none)");
2504
0
    }
2505
2506
0
    return protocol;
2507
0
}
2508
2509
AP_DECLARE(apr_status_t) ap_switch_protocol(conn_rec *c, request_rec *r, 
2510
                                            server_rec *s,
2511
                                            const char *protocol)
2512
0
{
2513
0
    const char *current = ap_get_protocol(c);
2514
0
    int rc;
2515
    
2516
0
    if (!strcmp(current, protocol)) {
2517
0
        ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, c, APLOGNO(02906)
2518
0
                      "already at it, protocol_switch to %s", 
2519
0
                      protocol);
2520
0
        return APR_SUCCESS;
2521
0
    }
2522
    
2523
0
    rc = ap_run_protocol_switch(c, r, s, protocol);
2524
0
    switch (rc) {
2525
0
        case DECLINED:
2526
0
            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02907)
2527
0
                          "no implementation for protocol_switch to %s", 
2528
0
                          protocol);
2529
0
            return APR_ENOTIMPL;
2530
0
        case OK:
2531
0
        case DONE:
2532
0
            return APR_SUCCESS;
2533
0
        default:
2534
0
            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02905)
2535
0
                          "unexpected return code %d from protocol_switch to %s"
2536
0
                          , rc, protocol);
2537
0
            return APR_EOF;
2538
0
    }    
2539
0
}
2540
2541
AP_DECLARE(int) ap_is_allowed_protocol(conn_rec *c, request_rec *r,
2542
                                       server_rec *s, const char *protocol)
2543
0
{
2544
0
    core_server_config *conf;
2545
2546
0
    if (!s) {
2547
0
        s = (r? r->server : c->base_server);
2548
0
    }
2549
0
    conf = ap_get_core_module_config(s->module_config);
2550
    
2551
0
    if (conf->protocols->nelts > 0) {
2552
0
        return ap_array_str_contains(conf->protocols, protocol);
2553
0
    }
2554
0
    return !strcmp(AP_PROTOCOL_HTTP1, protocol);
2555
0
}
2556
2557
2558
AP_IMPLEMENT_HOOK_VOID(pre_read_request,
2559
                       (request_rec *r, conn_rec *c),
2560
                       (r, c))
2561
AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
2562
                          (request_rec *r), (r), OK, DECLINED)
2563
AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
2564
                          (request_rec *r), (r), OK, DECLINED)
2565
AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_scheme,
2566
                            (const request_rec *r), (r), NULL)
2567
AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
2568
                            (const request_rec *r), (r), 0)
2569
AP_IMPLEMENT_HOOK_RUN_FIRST(int, note_auth_failure,
2570
                            (request_rec *r, const char *auth_type),
2571
                            (r, auth_type), DECLINED)
2572
AP_IMPLEMENT_HOOK_RUN_ALL(int,protocol_propose,
2573
                          (conn_rec *c, request_rec *r, server_rec *s,
2574
                           const apr_array_header_t *offers,
2575
                           apr_array_header_t *proposals), 
2576
                          (c, r, s, offers, proposals), OK, DECLINED)
2577
AP_IMPLEMENT_HOOK_RUN_FIRST(int,protocol_switch,
2578
                            (conn_rec *c, request_rec *r, server_rec *s,
2579
                             const char *protocol), 
2580
                            (c, r, s, protocol), DECLINED)
2581
AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,protocol_get,
2582
                            (const conn_rec *c), (c), NULL)