Coverage Report

Created: 2025-08-26 06:24

/src/httpd/modules/http/http_protocol.c
Line
Count
Source (jump to first uncovered line)
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
 * http_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
30
#define APR_WANT_STDIO          /* for sscanf */
31
#define APR_WANT_STRFUNC
32
#define APR_WANT_MEMFUNC
33
#include "apr_want.h"
34
35
#include "util_filter.h"
36
#include "ap_config.h"
37
#include "httpd.h"
38
#include "http_config.h"
39
#include "http_core.h"
40
#include "http_protocol.h"
41
#include "http_main.h"
42
#include "http_request.h"
43
#include "http_vhost.h"
44
#include "http_log.h"           /* For errors detected in basic auth common
45
                                 * support code... */
46
#include "apr_date.h"           /* For apr_date_parse_http and APR_DATE_BAD */
47
#include "util_charset.h"
48
#include "util_ebcdic.h"
49
#include "util_time.h"
50
#include "ap_mpm.h"
51
52
#include "mod_core.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
APLOG_USE_MODULE(http);
62
63
/* New Apache routine to map status codes into array indices
64
 *  e.g.  100 -> 0,  101 -> 1,  200 -> 2 ...
65
 * The number of status lines must equal the value of
66
 * RESPONSE_CODES (httpd.h) and must be listed in order.
67
 * No gaps are allowed between X00 and the largest Xnn
68
 * for any X (see ap_index_of_response).
69
 * When adding a new code here, add a define to httpd.h
70
 * as well.
71
 */
72
73
static const char * const status_lines[RESPONSE_CODES] =
74
{
75
    "100 Continue",
76
    "101 Switching Protocols",
77
    "102 Processing",
78
    "103 Early Hints",
79
0
#define LEVEL_200  4
80
    "200 OK",
81
    "201 Created",
82
    "202 Accepted",
83
    "203 Non-Authoritative Information",
84
    "204 No Content",
85
    "205 Reset Content",
86
    "206 Partial Content",
87
    "207 Multi-Status",
88
    "208 Already Reported",
89
    NULL, /* 209 */
90
    NULL, /* 210 */
91
    NULL, /* 211 */
92
    NULL, /* 212 */
93
    NULL, /* 213 */
94
    NULL, /* 214 */
95
    NULL, /* 215 */
96
    NULL, /* 216 */
97
    NULL, /* 217 */
98
    NULL, /* 218 */
99
    NULL, /* 219 */
100
    NULL, /* 220 */
101
    NULL, /* 221 */
102
    NULL, /* 222 */
103
    NULL, /* 223 */
104
    NULL, /* 224 */
105
    NULL, /* 225 */
106
    "226 IM Used",
107
0
#define LEVEL_300 31
108
    "300 Multiple Choices",
109
    "301 Moved Permanently",
110
    "302 Found",
111
    "303 See Other",
112
    "304 Not Modified",
113
    "305 Use Proxy",
114
    NULL, /* 306 */
115
    "307 Temporary Redirect",
116
    "308 Permanent Redirect",
117
0
#define LEVEL_400 40
118
    "400 Bad Request",
119
    "401 Unauthorized",
120
    "402 Payment Required",
121
    "403 Forbidden",
122
    "404 Not Found",
123
    "405 Method Not Allowed",
124
    "406 Not Acceptable",
125
    "407 Proxy Authentication Required",
126
    "408 Request Timeout",
127
    "409 Conflict",
128
    "410 Gone",
129
    "411 Length Required",
130
    "412 Precondition Failed",
131
    "413 Request Entity Too Large",
132
    "414 Request-URI Too Long",
133
    "415 Unsupported Media Type",
134
    "416 Requested Range Not Satisfiable",
135
    "417 Expectation Failed",
136
    "418 I'm A Teapot",
137
    NULL, /* 419 */
138
    NULL, /* 420 */
139
    "421 Misdirected Request",
140
    "422 Unprocessable Entity",
141
    "423 Locked",
142
    "424 Failed Dependency",
143
    "425 Too Early",
144
    "426 Upgrade Required",
145
    NULL, /* 427 */
146
    "428 Precondition Required",
147
    "429 Too Many Requests",
148
    NULL, /* 430 */
149
    "431 Request Header Fields Too Large",
150
    NULL, /* 432 */
151
    NULL, /* 433 */
152
    NULL, /* 434 */
153
    NULL, /* 435 */
154
    NULL, /* 436 */
155
    NULL, /* 437 */
156
    NULL, /* 438 */
157
    NULL, /* 439 */
158
    NULL, /* 440 */
159
    NULL, /* 441 */
160
    NULL, /* 442 */
161
    NULL, /* 443 */
162
    NULL, /* 444 */
163
    NULL, /* 445 */
164
    NULL, /* 446 */
165
    NULL, /* 447 */
166
    NULL, /* 448 */
167
    NULL, /* 449 */
168
    NULL, /* 450 */
169
    "451 Unavailable For Legal Reasons",
170
0
#define LEVEL_500 92
171
    "500 Internal Server Error",
172
    "501 Not Implemented",
173
    "502 Bad Gateway",
174
    "503 Service Unavailable",
175
    "504 Gateway Timeout",
176
    "505 HTTP Version Not Supported",
177
    "506 Variant Also Negotiates",
178
    "507 Insufficient Storage",
179
    "508 Loop Detected",
180
    NULL, /* 509 */
181
    "510 Not Extended",
182
    "511 Network Authentication Required"
183
};
184
185
APR_HOOK_STRUCT(
186
    APR_HOOK_LINK(insert_error_filter)
187
)
188
189
AP_IMPLEMENT_HOOK_VOID(insert_error_filter, (request_rec *r), (r))
190
191
/* The index of the first bit field that is used to index into a limit
192
 * bitmask. M_INVALID + 1 to METHOD_NUMBER_LAST.
193
 */
194
0
#define METHOD_NUMBER_FIRST (M_INVALID + 1)
195
196
/* The max method number. Method numbers are used to shift bitmasks,
197
 * so this cannot exceed 63, and all bits high is equal to -1, which is a
198
 * special flag, so the last bit used has index 62.
199
 */
200
0
#define METHOD_NUMBER_LAST  62
201
202
static int is_mpm_running(void)
203
0
{
204
0
    int mpm_state = 0;
205
206
0
    if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state)) {
207
0
      return 0;
208
0
    }
209
210
0
    if (mpm_state == AP_MPMQ_STOPPING) {
211
0
      return 0;
212
0
    }
213
214
0
    return 1;
215
0
}
216
217
int ap_h1_set_keepalive(request_rec *r, ap_bucket_response *resp)
218
0
{
219
0
    int ka_sent, left = 0, wimpy;
220
0
    const char *conn;
221
222
0
    if (r->proto_num >= HTTP_VERSION(2,0)) {
223
0
        goto update_keepalives;
224
0
    }
225
226
0
    ka_sent = 0;
227
0
    left = r->server->keep_alive_max - r->connection->keepalives;
228
0
    wimpy = ap_find_token(r->pool,
229
0
                          apr_table_get(resp->headers, "Connection"),
230
0
                          "close");
231
0
    conn = apr_table_get(r->headers_in, "Connection");
232
233
    /* The following convoluted conditional determines whether or not
234
     * the current connection should remain persistent after this response
235
     * (a.k.a. HTTP Keep-Alive) and whether or not the output message
236
     * body should use the HTTP/1.1 chunked transfer-coding.  In English,
237
     *
238
     *   IF  we have not marked this connection as errored;
239
     *   and the client isn't expecting 100-continue (PR47087 - more
240
     *       input here could be the client continuing when we're
241
     *       closing the request).
242
     *   and the response body has a defined length due to the status code
243
     *       being 304 or 204, the request method being HEAD, already
244
     *       having defined Content-Length or Transfer-Encoding: chunked, or
245
     *       the request version being HTTP/1.1 and thus capable of being set
246
     *       as chunked [we know the (r->chunked = 1) side-effect is ugly];
247
     *   and the server configuration enables keep-alive;
248
     *   and the server configuration has a reasonable inter-request timeout;
249
     *   and there is no maximum # requests or the max hasn't been reached;
250
     *   and the response status does not require a close;
251
     *   and the response generator has not already indicated close;
252
     *   and the client did not request non-persistence (Connection: close);
253
     *   and    we haven't been configured to ignore the buggy twit
254
     *       or they're a buggy twit coming through a HTTP/1.1 proxy
255
     *   and    the client is requesting an HTTP/1.0-style keep-alive
256
     *       or the client claims to be HTTP/1.1 compliant (perhaps a proxy);
257
     *   and this MPM process is not already exiting
258
     *   THEN we can be persistent, which requires more headers be output.
259
     *
260
     * Note that the condition evaluation order is extremely important.
261
     */
262
0
    if ((r->connection->keepalive != AP_CONN_CLOSE)
263
0
        && !r->expecting_100
264
0
        && (r->header_only
265
0
            || AP_STATUS_IS_HEADER_ONLY(resp->status)
266
0
            || apr_table_get(resp->headers, "Content-Length")
267
0
            || ap_is_chunked(r->pool,
268
0
                             apr_table_get(resp->headers, "Transfer-Encoding"))
269
0
            || ((r->proto_num >= HTTP_VERSION(1,1))
270
0
                && (r->chunked = 1))) /* THIS CODE IS CORRECT, see above. */
271
0
        && r->server->keep_alive
272
0
        && (r->server->keep_alive_timeout > 0)
273
0
        && ((r->server->keep_alive_max == 0)
274
0
            || (left > 0))
275
0
        && !ap_status_drops_connection(resp->status)
276
0
        && !wimpy
277
0
        && !ap_find_token(r->pool, conn, "close")
278
0
        && (!apr_table_get(r->subprocess_env, "nokeepalive")
279
0
            || apr_table_get(r->headers_in, "Via"))
280
0
        && ((ka_sent = ap_find_token(r->pool, conn, "keep-alive"))
281
0
            || (r->proto_num >= HTTP_VERSION(1,1)))
282
0
        && is_mpm_running()) {
283
284
0
        r->connection->keepalive = AP_CONN_KEEPALIVE;
285
0
        r->connection->keepalives++;
286
287
        /* If they sent a Keep-Alive token, send one back */
288
0
        if (ka_sent) {
289
0
            if (r->server->keep_alive_max) {
290
0
                apr_table_setn(resp->headers, "Keep-Alive",
291
0
                       apr_psprintf(r->pool, "timeout=%d, max=%d",
292
0
                            (int)apr_time_sec(r->server->keep_alive_timeout),
293
0
                            left));
294
0
            }
295
0
            else {
296
0
                apr_table_setn(resp->headers, "Keep-Alive",
297
0
                      apr_psprintf(r->pool, "timeout=%d",
298
0
                            (int)apr_time_sec(r->server->keep_alive_timeout)));
299
0
            }
300
0
            apr_table_mergen(resp->headers, "Connection", "Keep-Alive");
301
0
        }
302
303
0
        return 1;
304
0
    }
305
306
    /* Otherwise, we need to indicate that we will be closing this
307
     * connection immediately after the current response.
308
     *
309
     * We only really need to send "close" to HTTP/1.1 clients, but we
310
     * always send it anyway, because a broken proxy may identify itself
311
     * as HTTP/1.0, but pass our request along with our HTTP/1.1 tag
312
     * to a HTTP/1.1 client. Better safe than sorry.
313
     */
314
0
    if (!wimpy) {
315
0
        apr_table_mergen(resp->headers, "Connection", "close");
316
0
    }
317
318
0
update_keepalives:
319
    /*
320
     * If we had previously been a keepalive connection and this
321
     * is the last one, then bump up the number of keepalives
322
     * we've had
323
     */
324
0
    if ((r->connection->keepalive != AP_CONN_CLOSE)
325
0
        && r->server->keep_alive_max
326
0
        && !left) {
327
0
        r->connection->keepalives++;
328
0
    }
329
0
    r->connection->keepalive = AP_CONN_CLOSE;
330
331
0
    return 0;
332
0
}
333
334
AP_DECLARE(int) ap_set_keepalive(request_rec *r)
335
0
{
336
0
    ap_bucket_response resp;
337
338
0
    memset(&resp, 0, sizeof(resp));
339
0
    resp.status = r->status;
340
0
    resp.headers = r->headers_out;
341
0
    resp.notes = r->notes;
342
0
    return ap_h1_set_keepalive(r, &resp);
343
0
}
344
345
AP_DECLARE(ap_condition_e) ap_condition_if_match(request_rec *r,
346
        apr_table_t *headers)
347
0
{
348
0
    const char *if_match, *etag;
349
350
    /* A server MUST use the strong comparison function (see section 13.3.3)
351
     * to compare the entity tags in If-Match.
352
     */
353
0
    if ((if_match = apr_table_get(r->headers_in, "If-Match")) != NULL) {
354
0
        if (if_match[0] == '*'
355
0
                || ((etag = apr_table_get(headers, "ETag")) != NULL
356
0
                        && ap_find_etag_strong(r->pool, if_match, etag))) {
357
0
            return AP_CONDITION_STRONG;
358
0
        }
359
0
        else {
360
0
            return AP_CONDITION_NOMATCH;
361
0
        }
362
0
    }
363
364
0
    return AP_CONDITION_NONE;
365
0
}
366
367
AP_DECLARE(ap_condition_e) ap_condition_if_unmodified_since(request_rec *r,
368
        apr_table_t *headers)
369
0
{
370
0
    const char *if_unmodified;
371
372
0
    if_unmodified = apr_table_get(r->headers_in, "If-Unmodified-Since");
373
0
    if (if_unmodified) {
374
0
        apr_int64_t mtime, reqtime;
375
376
0
        apr_time_t ius = apr_time_sec(apr_date_parse_http(if_unmodified));
377
378
        /* All of our comparisons must be in seconds, because that's the
379
         * highest time resolution the HTTP specification allows.
380
         */
381
0
        mtime = apr_time_sec(apr_date_parse_http(
382
0
                        apr_table_get(headers, "Last-Modified")));
383
0
        if (mtime == APR_DATE_BAD) {
384
0
            mtime = apr_time_sec(r->mtime ? r->mtime : apr_time_now());
385
0
        }
386
387
0
        reqtime = apr_time_sec(apr_date_parse_http(
388
0
                        apr_table_get(headers, "Date")));
389
0
        if (!reqtime) {
390
0
            reqtime = apr_time_sec(r->request_time);
391
0
        }
392
393
0
        if ((ius != APR_DATE_BAD) && (mtime > ius)) {
394
0
            if (reqtime < mtime + 60) {
395
0
                if (apr_table_get(r->headers_in, "Range")) {
396
                    /* weak matches not allowed with Range requests */
397
0
                    return AP_CONDITION_NOMATCH;
398
0
                }
399
0
                else {
400
0
                    return AP_CONDITION_WEAK;
401
0
                }
402
0
            }
403
0
            else {
404
0
                return AP_CONDITION_STRONG;
405
0
            }
406
0
        }
407
0
        else {
408
0
            return AP_CONDITION_NOMATCH;
409
0
        }
410
0
    }
411
412
0
    return AP_CONDITION_NONE;
413
0
}
414
415
AP_DECLARE(ap_condition_e) ap_condition_if_none_match(request_rec *r,
416
        apr_table_t *headers)
417
0
{
418
0
    const char *if_nonematch, *etag;
419
420
0
    if_nonematch = apr_table_get(r->headers_in, "If-None-Match");
421
0
    if (if_nonematch != NULL) {
422
423
0
        if (if_nonematch[0] == '*') {
424
0
            return AP_CONDITION_STRONG;
425
0
        }
426
427
        /* See section 13.3.3 for rules on how to determine if two entities tags
428
         * match. The weak comparison function can only be used with GET or HEAD
429
         * requests.
430
         */
431
0
        if (r->method_number == M_GET) {
432
0
            if ((etag = apr_table_get(headers, "ETag")) != NULL) {
433
0
                if (apr_table_get(r->headers_in, "Range")) {
434
0
                    if (ap_find_etag_strong(r->pool, if_nonematch, etag)) {
435
0
                        return AP_CONDITION_STRONG;
436
0
                    }
437
0
                }
438
0
                else {
439
0
                    if (ap_find_etag_weak(r->pool, if_nonematch, etag)) {
440
0
                        return AP_CONDITION_WEAK;
441
0
                    }
442
0
                }
443
0
            }
444
0
        }
445
446
0
        else if ((etag = apr_table_get(headers, "ETag")) != NULL
447
0
                && ap_find_etag_strong(r->pool, if_nonematch, etag)) {
448
0
            return AP_CONDITION_STRONG;
449
0
        }
450
0
        return AP_CONDITION_NOMATCH;
451
0
    }
452
453
0
    return AP_CONDITION_NONE;
454
0
}
455
456
AP_DECLARE(ap_condition_e) ap_condition_if_modified_since(request_rec *r,
457
        apr_table_t *headers)
458
0
{
459
0
    const char *if_modified_since;
460
461
0
    if ((if_modified_since = apr_table_get(r->headers_in, "If-Modified-Since"))
462
0
            != NULL) {
463
0
        apr_int64_t mtime;
464
0
        apr_int64_t ims, reqtime;
465
466
        /* All of our comparisons must be in seconds, because that's the
467
         * highest time resolution the HTTP specification allows.
468
         */
469
470
0
        mtime = apr_time_sec(apr_date_parse_http(
471
0
                        apr_table_get(headers, "Last-Modified")));
472
0
        if (mtime == APR_DATE_BAD) {
473
0
            mtime = apr_time_sec(r->mtime ? r->mtime : apr_time_now());
474
0
        }
475
476
0
        reqtime = apr_time_sec(apr_date_parse_http(
477
0
                        apr_table_get(headers, "Date")));
478
0
        if (!reqtime) {
479
0
            reqtime = apr_time_sec(r->request_time);
480
0
        }
481
482
0
        ims = apr_time_sec(apr_date_parse_http(if_modified_since));
483
484
0
        if (ims >= mtime && ims <= reqtime) {
485
0
            if (reqtime < mtime + 60) {
486
0
                if (apr_table_get(r->headers_in, "Range")) {
487
                    /* weak matches not allowed with Range requests */
488
0
                    return AP_CONDITION_NOMATCH;
489
0
                }
490
0
                else {
491
0
                    return AP_CONDITION_WEAK;
492
0
                }
493
0
            }
494
0
            else {
495
0
                return AP_CONDITION_STRONG;
496
0
            }
497
0
        }
498
0
        else {
499
0
            return AP_CONDITION_NOMATCH;
500
0
        }
501
0
    }
502
503
0
    return AP_CONDITION_NONE;
504
0
}
505
506
AP_DECLARE(ap_condition_e) ap_condition_if_range(request_rec *r,
507
        apr_table_t *headers)
508
0
{
509
0
    const char *if_range, *etag;
510
511
0
    if ((if_range = apr_table_get(r->headers_in, "If-Range"))
512
0
            && apr_table_get(r->headers_in, "Range")) {
513
0
        if (if_range[0] == '"') {
514
515
0
            if ((etag = apr_table_get(headers, "ETag"))
516
0
                    && !strcmp(if_range, etag)) {
517
0
                return AP_CONDITION_STRONG;
518
0
            }
519
0
            else {
520
0
                return AP_CONDITION_NOMATCH;
521
0
            }
522
523
0
        }
524
0
        else {
525
0
            apr_int64_t mtime;
526
0
            apr_int64_t rtime, reqtime;
527
528
            /* All of our comparisons must be in seconds, because that's the
529
             * highest time resolution the HTTP specification allows.
530
             */
531
532
0
            mtime = apr_time_sec(apr_date_parse_http(
533
0
                            apr_table_get(headers, "Last-Modified")));
534
0
            if (mtime == APR_DATE_BAD) {
535
0
                mtime = apr_time_sec(r->mtime ? r->mtime : apr_time_now());
536
0
            }
537
538
0
            reqtime = apr_time_sec(apr_date_parse_http(
539
0
                            apr_table_get(headers, "Date")));
540
0
            if (!reqtime) {
541
0
                reqtime = apr_time_sec(r->request_time);
542
0
            }
543
544
0
            rtime = apr_time_sec(apr_date_parse_http(if_range));
545
546
0
            if (rtime == mtime) {
547
0
                if (reqtime < mtime + 60) {
548
                    /* weak matches not allowed with Range requests */
549
0
                    return AP_CONDITION_NOMATCH;
550
0
                }
551
0
                else {
552
0
                    return AP_CONDITION_STRONG;
553
0
                }
554
0
            }
555
0
            else {
556
0
                return AP_CONDITION_NOMATCH;
557
0
            }
558
0
        }
559
0
    }
560
561
0
    return AP_CONDITION_NONE;
562
0
}
563
564
AP_DECLARE(int) ap_meets_conditions(request_rec *r)
565
0
{
566
0
    int not_modified = -1; /* unset by default */
567
0
    ap_condition_e cond;
568
569
    /* Check for conditional requests --- note that we only want to do
570
     * this if we are successful so far and we are not processing a
571
     * subrequest or an ErrorDocument.
572
     *
573
     * The order of the checks is important, since ETag checks are supposed
574
     * to be more accurate than checks relative to the modification time.
575
     * However, not all documents are guaranteed to *have* ETags, and some
576
     * might have Last-Modified values w/o ETags, so this gets a little
577
     * complicated.
578
     */
579
580
0
    if (!ap_is_HTTP_SUCCESS(r->status) || r->no_local_copy) {
581
0
        return OK;
582
0
    }
583
584
    /* If an If-Match request-header field was given
585
     * AND the field value is not "*" (meaning match anything)
586
     * AND if our strong ETag does not match any entity tag in that field,
587
     *     respond with a status of 412 (Precondition Failed).
588
     */
589
0
    cond = ap_condition_if_match(r, r->headers_out);
590
0
    if (AP_CONDITION_NOMATCH == cond) {
591
0
        return HTTP_PRECONDITION_FAILED;
592
0
    }
593
594
    /* Else if a valid If-Unmodified-Since request-header field was given
595
     * AND the requested resource has been modified since the time
596
     * specified in this field, then the server MUST
597
     *     respond with a status of 412 (Precondition Failed).
598
     */
599
0
    cond = ap_condition_if_unmodified_since(r, r->headers_out);
600
0
    if (AP_CONDITION_NOMATCH == cond) {
601
0
        not_modified = 0;
602
0
    }
603
0
    else if (cond >= AP_CONDITION_WEAK) {
604
0
        return HTTP_PRECONDITION_FAILED;
605
0
    }
606
607
    /* If an If-None-Match request-header field was given
608
     * AND the field value is "*" (meaning match anything)
609
     *     OR our ETag matches any of the entity tags in that field, fail.
610
     *
611
     * If the request method was GET or HEAD, failure means the server
612
     *    SHOULD respond with a 304 (Not Modified) response.
613
     * For all other request methods, failure means the server MUST
614
     *    respond with a status of 412 (Precondition Failed).
615
     *
616
     * GET or HEAD allow weak etag comparison, all other methods require
617
     * strong comparison.  We can only use weak if it's not a range request.
618
     */
619
0
    cond = ap_condition_if_none_match(r, r->headers_out);
620
0
    if (AP_CONDITION_NOMATCH == cond) {
621
0
        not_modified = 0;
622
0
    }
623
0
    else if (cond >= AP_CONDITION_WEAK) {
624
0
        if (r->method_number == M_GET) {
625
0
            if (not_modified) {
626
0
                not_modified = 1;
627
0
            }
628
0
        }
629
0
        else {
630
0
            return HTTP_PRECONDITION_FAILED;
631
0
        }
632
0
    }
633
634
    /* If a valid If-Modified-Since request-header field was given
635
     * AND it is a GET or HEAD request
636
     * AND the requested resource has not been modified since the time
637
     * specified in this field, then the server MUST
638
     *    respond with a status of 304 (Not Modified).
639
     * A date later than the server's current request time is invalid.
640
     */
641
0
    cond = ap_condition_if_modified_since(r, r->headers_out);
642
0
    if (AP_CONDITION_NOMATCH == cond) {
643
0
        not_modified = 0;
644
0
    }
645
0
    else if (cond >= AP_CONDITION_WEAK) {
646
0
        if (r->method_number == M_GET) {
647
0
            if (not_modified) {
648
0
                not_modified = 1;
649
0
            }
650
0
        }
651
0
    }
652
653
    /* If an If-Range and an Range header is present, we must return
654
     * 200 OK. The byterange filter will convert it to a range response.
655
     */
656
0
    cond = ap_condition_if_range(r, r->headers_out);
657
0
    if (cond > AP_CONDITION_NONE) {
658
0
        return OK;
659
0
    }
660
661
0
    if (not_modified == 1) {
662
0
        return HTTP_NOT_MODIFIED;
663
0
    }
664
665
0
    return OK;
666
0
}
667
668
/**
669
 * Singleton registry of additional methods. This maps new method names
670
 * such as "MYGET" to methnums, which are int offsets into bitmasks.
671
 *
672
 * This follows the same technique as standard M_GET, M_POST, etc. These
673
 * are dynamically assigned when modules are loaded and <Limit GET MYGET>
674
 * directives are processed.
675
 */
676
static apr_hash_t *methods_registry = NULL;
677
static int cur_method_number = METHOD_NUMBER_FIRST;
678
679
/* internal function to register one method/number pair */
680
static void register_one_method(apr_pool_t *p, const char *methname,
681
                                int methnum)
682
0
{
683
0
    int *pnum = apr_palloc(p, sizeof(*pnum));
684
685
0
    *pnum = methnum;
686
0
    apr_hash_set(methods_registry, methname, APR_HASH_KEY_STRING, pnum);
687
0
}
688
689
/* This internal function is used to clear the method registry
690
 * and reset the cur_method_number counter.
691
 */
692
static apr_status_t ap_method_registry_destroy(void *notused)
693
0
{
694
0
    methods_registry = NULL;
695
0
    cur_method_number = METHOD_NUMBER_FIRST;
696
0
    return APR_SUCCESS;
697
0
}
698
699
AP_DECLARE(void) ap_method_registry_init(apr_pool_t *p)
700
0
{
701
0
    methods_registry = apr_hash_make(p);
702
0
    apr_pool_cleanup_register(p, NULL,
703
0
                              ap_method_registry_destroy,
704
0
                              apr_pool_cleanup_null);
705
706
    /* put all the standard methods into the registry hash to ease the
707
     * mapping operations between name and number
708
     * HEAD is a special-instance of the GET method and shares the same ID
709
     */
710
0
    register_one_method(p, "GET", M_GET);
711
0
    register_one_method(p, "HEAD", M_GET);
712
0
    register_one_method(p, "PUT", M_PUT);
713
0
    register_one_method(p, "POST", M_POST);
714
0
    register_one_method(p, "DELETE", M_DELETE);
715
0
    register_one_method(p, "CONNECT", M_CONNECT);
716
0
    register_one_method(p, "OPTIONS", M_OPTIONS);
717
0
    register_one_method(p, "TRACE", M_TRACE);
718
0
    register_one_method(p, "PATCH", M_PATCH);
719
0
    register_one_method(p, "PROPFIND", M_PROPFIND);
720
0
    register_one_method(p, "PROPPATCH", M_PROPPATCH);
721
0
    register_one_method(p, "MKCOL", M_MKCOL);
722
0
    register_one_method(p, "COPY", M_COPY);
723
0
    register_one_method(p, "MOVE", M_MOVE);
724
0
    register_one_method(p, "LOCK", M_LOCK);
725
0
    register_one_method(p, "UNLOCK", M_UNLOCK);
726
0
    register_one_method(p, "VERSION-CONTROL", M_VERSION_CONTROL);
727
0
    register_one_method(p, "CHECKOUT", M_CHECKOUT);
728
0
    register_one_method(p, "UNCHECKOUT", M_UNCHECKOUT);
729
0
    register_one_method(p, "CHECKIN", M_CHECKIN);
730
0
    register_one_method(p, "UPDATE", M_UPDATE);
731
0
    register_one_method(p, "LABEL", M_LABEL);
732
0
    register_one_method(p, "REPORT", M_REPORT);
733
0
    register_one_method(p, "MKWORKSPACE", M_MKWORKSPACE);
734
0
    register_one_method(p, "MKACTIVITY", M_MKACTIVITY);
735
0
    register_one_method(p, "BASELINE-CONTROL", M_BASELINE_CONTROL);
736
0
    register_one_method(p, "MERGE", M_MERGE);
737
0
}
738
739
AP_DECLARE(int) ap_method_register(apr_pool_t *p, const char *methname)
740
0
{
741
0
    int *methnum;
742
743
0
    if (methname == NULL) {
744
0
        return M_INVALID;
745
0
    }
746
747
    /* Check if the method was previously registered.  If it was
748
     * return the associated method number.
749
     */
750
0
    methnum = (int *)apr_hash_get(methods_registry, methname,
751
0
                                  APR_HASH_KEY_STRING);
752
0
    if (methnum != NULL)
753
0
        return *methnum;
754
755
0
    if (cur_method_number > METHOD_NUMBER_LAST) {
756
        /* The method registry  has run out of dynamically
757
         * assignable method numbers. Log this and return M_INVALID.
758
         */
759
0
        ap_log_perror(APLOG_MARK, APLOG_ERR, 0, p, APLOGNO(01610)
760
0
                      "Maximum new request methods %d reached while "
761
0
                      "registering method %s.",
762
0
                      METHOD_NUMBER_LAST, methname);
763
0
        return M_INVALID;
764
0
    }
765
766
0
    register_one_method(p, methname, cur_method_number);
767
0
    return cur_method_number++;
768
0
}
769
770
/* Get the method number associated with the given string, assumed to
771
 * contain an HTTP method.  Returns M_INVALID if not recognized.
772
 *
773
 * This is the first step toward placing method names in a configurable
774
 * list.  Hopefully it (and other routines) can eventually be moved to
775
 * something like a mod_http_methods.c, complete with config stuff.
776
 */
777
AP_DECLARE(int) ap_method_number_of(const char *method)
778
0
{
779
0
    int len = strlen(method);
780
781
    /* check if the method has been dynamically registered */
782
0
    int *methnum = apr_hash_get(methods_registry, method, len);
783
784
0
    if (methnum != NULL) {
785
0
        return *methnum;
786
0
    }
787
788
0
    return M_INVALID;
789
0
}
790
791
/*
792
 * Turn a known method number into a name.
793
 */
794
AP_DECLARE(const char *) ap_method_name_of(apr_pool_t *p, int methnum)
795
0
{
796
0
    apr_hash_index_t *hi = apr_hash_first(p, methods_registry);
797
798
    /* scan through the hash table, looking for a value that matches
799
       the provided method number. */
800
0
    for (; hi; hi = apr_hash_next(hi)) {
801
0
        const void *key;
802
0
        void *val;
803
804
0
        apr_hash_this(hi, &key, NULL, &val);
805
0
        if (*(int *)val == methnum)
806
0
            return key;
807
0
    }
808
809
    /* it wasn't found in the hash */
810
0
    return NULL;
811
0
}
812
813
/* The index is found by its offset from the x00 code of each level.
814
 * Although this is fast, it will need to be replaced if some nutcase
815
 * decides to define a high-numbered code before the lower numbers.
816
 * If that sad event occurs, replace the code below with a linear search
817
 * from status_lines[shortcut[i]] to status_lines[shortcut[i+1]-1];
818
 * or use NULL to fill the gaps.
819
 */
820
static int index_of_response(int status)
821
0
{
822
0
    static int shortcut[6] = {0, LEVEL_200, LEVEL_300, LEVEL_400, LEVEL_500,
823
0
                                 RESPONSE_CODES};
824
0
    int i, pos;
825
826
0
    if (status < 100) {     /* Below 100 is illegal for HTTP status */
827
0
        return -1;
828
0
    }
829
0
    if (status > 999) {     /* Above 999 is also illegal for HTTP status */
830
0
        return -1;
831
0
    }
832
833
0
    for (i = 0; i < 5; i++) {
834
0
        status -= 100;
835
0
        if (status < 100) {
836
0
            pos = (status + shortcut[i]);
837
0
            if (pos < shortcut[i + 1] && status_lines[pos] != NULL) {
838
0
                return pos;
839
0
            }
840
0
            else {
841
0
                break;
842
0
            }
843
0
        }
844
0
    }
845
0
    return -2;              /* Status unknown (falls in gap) or above 600 */
846
0
}
847
848
AP_DECLARE(int) ap_index_of_response(int status)
849
0
{
850
0
    int index = index_of_response(status);
851
0
    return (index < 0) ? LEVEL_500 : index;
852
0
}
853
854
AP_DECLARE(const char *) ap_get_status_line_ex(apr_pool_t *p, int status)
855
0
{
856
0
    int index = index_of_response(status);
857
0
    if (index >= 0) {
858
0
        return status_lines[index];
859
0
    }
860
0
    else if (index == -2) {
861
0
        return apr_psprintf(p, "%i Status %i", status, status);
862
0
    }
863
0
    return status_lines[LEVEL_500];
864
0
}
865
866
AP_DECLARE(const char *) ap_get_status_line(int status)
867
0
{
868
0
    return status_lines[ap_index_of_response(status)];
869
0
}
870
871
/* Build the Allow field-value from the request handler method mask.
872
 */
873
static char *make_allow(request_rec *r)
874
0
{
875
0
    ap_method_mask_t mask;
876
0
    apr_array_header_t *allow = apr_array_make(r->pool, 10, sizeof(char *));
877
0
    apr_hash_index_t *hi = apr_hash_first(r->pool, methods_registry);
878
    /* For TRACE below */
879
0
    core_server_config *conf =
880
0
        ap_get_core_module_config(r->server->module_config);
881
882
0
    mask = r->allowed_methods->method_mask;
883
884
0
    for (; hi; hi = apr_hash_next(hi)) {
885
0
        const void *key;
886
0
        void *val;
887
888
0
        apr_hash_this(hi, &key, NULL, &val);
889
0
        if ((mask & (AP_METHOD_BIT << *(int *)val)) != 0) {
890
0
            APR_ARRAY_PUSH(allow, const char *) = key;
891
0
        }
892
0
    }
893
894
    /* TRACE is tested on a per-server basis */
895
0
    if (conf->trace_enable != AP_TRACE_DISABLE)
896
0
        *(const char **)apr_array_push(allow) = "TRACE";
897
898
    /* ### this is rather annoying. we should enforce registration of
899
       ### these methods */
900
0
    if ((mask & (AP_METHOD_BIT << M_INVALID))
901
0
        && (r->allowed_methods->method_list != NULL)
902
0
        && (r->allowed_methods->method_list->nelts != 0)) {
903
0
        apr_array_cat(allow, r->allowed_methods->method_list);
904
0
    }
905
906
0
    return apr_array_pstrcat(r->pool, allow, ',');
907
0
}
908
909
AP_DECLARE(int) ap_send_http_options(request_rec *r)
910
0
{
911
0
    if (r->assbackwards) {
912
0
        return DECLINED;
913
0
    }
914
915
0
    apr_table_setn(r->headers_out, "Allow", make_allow(r));
916
917
    /* the request finalization will send an EOS, which will flush all
918
     * the headers out (including the Allow header)
919
     */
920
921
0
    return OK;
922
0
}
923
924
AP_DECLARE(void) ap_set_content_type(request_rec *r, const char *ct)
925
0
{
926
0
    if (!ct) {
927
0
        r->content_type = NULL;
928
0
    }
929
0
    else if (!r->content_type || strcmp(r->content_type, ct)) {
930
0
        r->content_type = ct;
931
0
        AP_REQUEST_SET_BNOTE(r, AP_REQUEST_TRUSTED_CT, 0);
932
0
    }
933
0
}
934
AP_DECLARE(void) ap_set_content_type_ex(request_rec *r, const char *ct, int trusted)
935
0
{
936
0
    ap_set_content_type(r, ct);
937
0
    AP_REQUEST_SET_BNOTE(r, AP_REQUEST_TRUSTED_CT, trusted ? AP_REQUEST_TRUSTED_CT : 0);
938
0
}
939
940
AP_DECLARE(void) ap_set_accept_ranges(request_rec *r)
941
0
{
942
0
    core_dir_config *d = ap_get_core_module_config(r->per_dir_config);
943
0
    apr_table_setn(r->headers_out, "Accept-Ranges",
944
0
                  (d->max_ranges == AP_MAXRANGES_NORANGES) ? "none"
945
0
                                                           : "bytes");
946
0
}
947
static const char *add_optional_notes(request_rec *r,
948
                                      const char *prefix,
949
                                      const char *key,
950
                                      const char *suffix)
951
0
{
952
0
    const char *notes, *result;
953
954
0
    if ((notes = apr_table_get(r->notes, key)) == NULL) {
955
0
        result = apr_pstrcat(r->pool, prefix, suffix, NULL);
956
0
    }
957
0
    else {
958
0
        result = apr_pstrcat(r->pool, prefix, notes, suffix, NULL);
959
0
    }
960
961
0
    return result;
962
0
}
963
964
/* construct and return the default error message for a given
965
 * HTTP defined error code
966
 */
967
static const char *get_canned_error_string(int status,
968
                                           request_rec *r,
969
                                           const char *location)
970
0
{
971
0
    apr_pool_t *p = r->pool;
972
0
    const char *error_notes, *h1, *s1;
973
0
    const char *method = r->method;
974
0
    if (r->subprocess_env && apr_table_get(r->subprocess_env, "REQUEST_METHOD"))
975
0
        method =  apr_table_get(r->subprocess_env, "REQUEST_METHOD");
976
977
0
    switch (status) {
978
0
    case HTTP_MOVED_PERMANENTLY:
979
0
    case HTTP_MOVED_TEMPORARILY:
980
0
    case HTTP_TEMPORARY_REDIRECT:
981
0
    case HTTP_PERMANENT_REDIRECT:
982
0
        return(apr_pstrcat(p,
983
0
                           "<p>The document has moved <a href=\"",
984
0
                           ap_escape_html(r->pool, location),
985
0
                           "\">here</a>.</p>\n",
986
0
                           NULL));
987
0
    case HTTP_SEE_OTHER:
988
0
        return(apr_pstrcat(p,
989
0
                           "<p>The answer to your request is located "
990
0
                           "<a href=\"",
991
0
                           ap_escape_html(r->pool, location),
992
0
                           "\">here</a>.</p>\n",
993
0
                           NULL));
994
0
    case HTTP_USE_PROXY:
995
0
        return("<p>This resource is only accessible "
996
0
               "through the proxy\n"
997
0
               "<br />\nYou will need to configure "
998
0
               "your client to use that proxy.</p>\n");
999
0
    case HTTP_PROXY_AUTHENTICATION_REQUIRED:
1000
0
    case HTTP_UNAUTHORIZED:
1001
0
        return("<p>This server could not verify that you\n"
1002
0
               "are authorized to access the document\n"
1003
0
               "requested.  Either you supplied the wrong\n"
1004
0
               "credentials (e.g., bad password), or your\n"
1005
0
               "browser doesn't understand how to supply\n"
1006
0
               "the credentials required.</p>\n");
1007
0
    case HTTP_BAD_REQUEST:
1008
0
        return(add_optional_notes(r,
1009
0
                                  "<p>Your browser sent a request that "
1010
0
                                  "this server could not understand.<br />\n",
1011
0
                                  "error-notes",
1012
0
                                  "</p>\n"));
1013
0
    case HTTP_FORBIDDEN:
1014
0
        return(add_optional_notes(r, "<p>You don't have permission to access this resource.", "error-notes", "</p>\n"));
1015
0
    case HTTP_NOT_FOUND:
1016
0
        return("<p>The requested URL was not found on this server.</p>\n");
1017
0
    case HTTP_METHOD_NOT_ALLOWED:
1018
0
        return(apr_pstrcat(p,
1019
0
                           "<p>The requested method ",
1020
0
                           ap_escape_html(r->pool, method),
1021
0
                           " is not allowed for this URL.</p>\n",
1022
0
                           NULL));
1023
0
    case HTTP_NOT_ACCEPTABLE:
1024
0
        return(add_optional_notes(r, 
1025
0
            "<p>An appropriate representation of the requested resource "
1026
0
            "could not be found on this server.</p>\n",
1027
0
            "variant-list", ""));
1028
0
    case HTTP_MULTIPLE_CHOICES:
1029
0
        return(add_optional_notes(r, "", "variant-list", ""));
1030
0
    case HTTP_LENGTH_REQUIRED:
1031
0
        s1 = apr_pstrcat(p,
1032
0
                         "<p>A request of the requested method ",
1033
0
                         ap_escape_html(r->pool, method),
1034
0
                         " requires a valid Content-length.<br />\n",
1035
0
                         NULL);
1036
0
        return(add_optional_notes(r, s1, "error-notes", "</p>\n"));
1037
0
    case HTTP_PRECONDITION_FAILED:
1038
0
        return("<p>The precondition on the request "
1039
0
               "for this URL evaluated to false.</p>\n");
1040
0
    case HTTP_NOT_IMPLEMENTED:
1041
0
        s1 = apr_pstrcat(p,
1042
0
                         "<p>",
1043
0
                         ap_escape_html(r->pool, method),
1044
0
                         " not supported for current URL.<br />\n",
1045
0
                         NULL);
1046
0
        return(add_optional_notes(r, s1, "error-notes", "</p>\n"));
1047
0
    case HTTP_BAD_GATEWAY:
1048
0
        s1 = "<p>The proxy server received an invalid" CRLF
1049
0
            "response from an upstream server.<br />" CRLF;
1050
0
        return(add_optional_notes(r, s1, "error-notes", "</p>\n"));
1051
0
    case HTTP_VARIANT_ALSO_VARIES:
1052
0
        return("<p>A variant for the requested "
1053
0
               "resource\n<pre>\n"
1054
0
               "\n</pre>\nis itself a negotiable resource. "
1055
0
               "This indicates a configuration error.</p>\n");
1056
0
    case HTTP_REQUEST_TIME_OUT:
1057
0
        return("<p>Server timeout waiting for the HTTP request from the client.</p>\n");
1058
0
    case HTTP_GONE:
1059
0
        return("<p>The requested resource is no longer available on this server"
1060
0
               " and there is no forwarding address.\n"
1061
0
               "Please remove all references to this resource.</p>\n");
1062
0
    case HTTP_REQUEST_ENTITY_TOO_LARGE:
1063
0
        return(apr_pstrcat(p,
1064
0
                           "The requested resource does not allow request data with ",
1065
0
                           ap_escape_html(r->pool, method),
1066
0
                           " requests, or the amount of data provided in\n"
1067
0
                           "the request exceeds the capacity limit.\n",
1068
0
                           NULL));
1069
0
    case HTTP_REQUEST_URI_TOO_LARGE:
1070
0
        s1 = "<p>The requested URL's length exceeds the capacity\n"
1071
0
             "limit for this server.<br />\n";
1072
0
        return(add_optional_notes(r, s1, "error-notes", "</p>\n"));
1073
0
    case HTTP_UNSUPPORTED_MEDIA_TYPE:
1074
0
        return("<p>The supplied request data is not in a format\n"
1075
0
               "acceptable for processing by this resource.</p>\n");
1076
0
    case HTTP_RANGE_NOT_SATISFIABLE:
1077
0
        return("<p>None of the range-specifier values in the Range\n"
1078
0
               "request-header field overlap the current extent\n"
1079
0
               "of the selected resource.</p>\n");
1080
0
    case HTTP_EXPECTATION_FAILED:
1081
0
        s1 = apr_table_get(r->headers_in, "Expect");
1082
0
        if (s1)
1083
0
            s1 = apr_pstrcat(p,
1084
0
                     "<p>The expectation given in the Expect request-header\n"
1085
0
                     "field could not be met by this server.\n"
1086
0
                     "The client sent<pre>\n    Expect: ",
1087
0
                     ap_escape_html(r->pool, s1), "\n</pre>\n",
1088
0
                     NULL);
1089
0
        else
1090
0
            s1 = "<p>No expectation was seen, the Expect request-header \n"
1091
0
                 "field was not presented by the client.\n";
1092
0
        return add_optional_notes(r, s1, "error-notes", "</p>"
1093
0
                   "<p>Only the 100-continue expectation is supported.</p>\n");
1094
0
    case HTTP_UNPROCESSABLE_ENTITY:
1095
0
        return("<p>The server understands the media type of the\n"
1096
0
               "request entity, but was unable to process the\n"
1097
0
               "contained instructions.</p>\n");
1098
0
    case HTTP_LOCKED:
1099
0
        return("<p>The requested resource is currently locked.\n"
1100
0
               "The lock must be released or proper identification\n"
1101
0
               "given before the method can be applied.</p>\n");
1102
0
    case HTTP_FAILED_DEPENDENCY:
1103
0
        return("<p>The method could not be performed on the resource\n"
1104
0
               "because the requested action depended on another\n"
1105
0
               "action and that other action failed.</p>\n");
1106
0
    case HTTP_TOO_EARLY:
1107
0
        return("<p>The request could not be processed as TLS\n"
1108
0
               "early data and should be retried.</p>\n");
1109
0
    case HTTP_UPGRADE_REQUIRED:
1110
0
        return("<p>The requested resource can only be retrieved\n"
1111
0
               "using SSL.  The server is willing to upgrade the current\n"
1112
0
               "connection to SSL, but your client doesn't support it.\n"
1113
0
               "Either upgrade your client, or try requesting the page\n"
1114
0
               "using https://\n");
1115
0
    case HTTP_PRECONDITION_REQUIRED:
1116
0
        return("<p>The request is required to be conditional.</p>\n");
1117
0
    case HTTP_TOO_MANY_REQUESTS:
1118
0
        return("<p>The user has sent too many requests\n"
1119
0
               "in a given amount of time.</p>\n");
1120
0
    case HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE:
1121
0
        return("<p>The server refused this request because\n"
1122
0
               "the request header fields are too large.</p>\n");
1123
0
    case HTTP_INSUFFICIENT_STORAGE:
1124
0
        return("<p>The method could not be performed on the resource\n"
1125
0
               "because the server is unable to store the\n"
1126
0
               "representation needed to successfully complete the\n"
1127
0
               "request.  There is insufficient free space left in\n"
1128
0
               "your storage allocation.</p>\n");
1129
0
    case HTTP_SERVICE_UNAVAILABLE:
1130
0
        return("<p>The server is temporarily unable to service your\n"
1131
0
               "request due to maintenance downtime or capacity\n"
1132
0
               "problems. Please try again later.</p>\n");
1133
0
    case HTTP_GATEWAY_TIME_OUT:
1134
0
        return("<p>The gateway did not receive a timely response\n"
1135
0
               "from the upstream server or application.</p>\n");
1136
0
    case HTTP_LOOP_DETECTED:
1137
0
        return("<p>The server terminated an operation because\n"
1138
0
               "it encountered an infinite loop.</p>\n");
1139
0
    case HTTP_NOT_EXTENDED:
1140
0
        return("<p>A mandatory extension policy in the request is not\n"
1141
0
               "accepted by the server for this resource.</p>\n");
1142
0
    case HTTP_NETWORK_AUTHENTICATION_REQUIRED:
1143
0
        return("<p>The client needs to authenticate to gain\n"
1144
0
               "network access.</p>\n");
1145
0
    case HTTP_IM_A_TEAPOT:
1146
0
        return("<p>The resulting entity body MAY be short and\n"
1147
0
                "stout.</p>\n");
1148
0
    case HTTP_MISDIRECTED_REQUEST:
1149
0
        return("<p>The client needs a new connection for this\n"
1150
0
               "request as the requested host name does not match\n"
1151
0
               "the Server Name Indication (SNI) in use for this\n"
1152
0
               "connection.</p>\n");
1153
0
    case HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
1154
0
        return(add_optional_notes(r, 
1155
0
               "<p>Access to this URL has been denied for legal reasons.<br />\n",
1156
0
               "error-notes", "</p>\n"));
1157
0
    default:                    /* HTTP_INTERNAL_SERVER_ERROR */
1158
        /*
1159
         * This comparison to expose error-notes could be modified to
1160
         * use a configuration directive and export based on that
1161
         * directive.  For now "*" is used to designate an error-notes
1162
         * that is totally safe for any user to see (ie lacks paths,
1163
         * database passwords, etc.)
1164
         */
1165
0
        if (((error_notes = apr_table_get(r->notes,
1166
0
                                          "error-notes")) != NULL)
1167
0
            && (h1 = apr_table_get(r->notes, "verbose-error-to")) != NULL
1168
0
            && (strcmp(h1, "*") == 0)) {
1169
0
            return(apr_pstrcat(p, error_notes, "<p />\n", NULL));
1170
0
        }
1171
0
        else {
1172
0
            return(apr_pstrcat(p,
1173
0
                               "<p>The server encountered an internal "
1174
0
                               "error or\n"
1175
0
                               "misconfiguration and was unable to complete\n"
1176
0
                               "your request.</p>\n"
1177
0
                               "<p>Please contact the server "
1178
0
                               "administrator at \n ",
1179
0
                               ap_escape_html(r->pool,
1180
0
                                              r->server->server_admin),
1181
0
                               " to inform them of the time this "
1182
0
                               "error occurred,\n"
1183
0
                               " and the actions you performed just before "
1184
0
                               "this error.</p>\n"
1185
0
                               "<p>More information about this error "
1186
0
                               "may be available\n"
1187
0
                               "in the server error log.</p>\n",
1188
0
                               NULL));
1189
0
        }
1190
        /*
1191
         * It would be nice to give the user the information they need to
1192
         * fix the problem directly since many users don't have access to
1193
         * the error_log (think University sites) even though they can easily
1194
         * get this error by misconfiguring an htaccess file.  However, the
1195
         * e error notes tend to include the real file pathname in this case,
1196
         * which some people consider to be a breach of privacy.  Until we
1197
         * can figure out a way to remove the pathname, leave this commented.
1198
         *
1199
         * if ((error_notes = apr_table_get(r->notes,
1200
         *                                  "error-notes")) != NULL) {
1201
         *     return(apr_pstrcat(p, error_notes, "<p />\n", NULL);
1202
         * }
1203
         * else {
1204
         *     return "";
1205
         * }
1206
         */
1207
0
    }
1208
0
}
1209
1210
/* We should have named this send_canned_response, since it is used for any
1211
 * response that can be generated by the server from the request record.
1212
 * This includes all 204 (no content), 3xx (redirect), 4xx (client error),
1213
 * and 5xx (server error) messages that have not been redirected to another
1214
 * handler via the ErrorDocument feature.
1215
 */
1216
AP_DECLARE(void) ap_send_error_response(request_rec *r, int recursive_error)
1217
0
{
1218
0
    int status = r->status;
1219
0
    int idx = ap_index_of_response(status);
1220
0
    char *custom_response;
1221
0
    const char *location = apr_table_get(r->headers_out, "Location");
1222
1223
    /* At this point, we are starting the response over, so we have to reset
1224
     * this value.
1225
     */
1226
0
    r->eos_sent = 0;
1227
1228
    /* and we need to get rid of any RESOURCE filters that might be lurking
1229
     * around, thinking they are in the middle of the original request
1230
     */
1231
1232
0
    r->output_filters = r->proto_output_filters;
1233
1234
0
    ap_run_insert_error_filter(r);
1235
1236
    /* We need to special-case the handling of 204 and 304 responses,
1237
     * since they have specific HTTP requirements and do not include a
1238
     * message body.  Note that being assbackwards here is not an option.
1239
     */
1240
0
    if (AP_STATUS_IS_HEADER_ONLY(status)) {
1241
0
        ap_finalize_request_protocol(r);
1242
0
        return;
1243
0
    }
1244
1245
    /*
1246
     * It's possible that the Location field might be in r->err_headers_out
1247
     * instead of r->headers_out; use the latter if possible, else the
1248
     * former.
1249
     */
1250
0
    if (location == NULL) {
1251
0
        location = apr_table_get(r->err_headers_out, "Location");
1252
0
    }
1253
1254
0
    if (!r->assbackwards) {
1255
1256
        /* For all HTTP/1.x responses for which we generate the message,
1257
         * we need to avoid inheriting the "normal status" header fields
1258
         * that may have been set by the request handler before the
1259
         * error or redirect, except for Location on external redirects.
1260
         */
1261
0
        apr_table_clear(r->headers_out);
1262
1263
0
        if (ap_is_HTTP_REDIRECT(status) || (status == HTTP_CREATED)) {
1264
0
            if ((location != NULL) && *location) {
1265
0
                apr_table_setn(r->headers_out, "Location", location);
1266
0
            }
1267
0
            else {
1268
0
                location = "";   /* avoids coredump when printing, below */
1269
0
            }
1270
0
        }
1271
1272
0
        r->content_languages = NULL;
1273
0
        r->content_encoding = NULL;
1274
0
        r->clength = 0;
1275
1276
0
        if (apr_table_get(r->subprocess_env,
1277
0
                          "suppress-error-charset") != NULL) {
1278
0
            core_request_config *request_conf =
1279
0
                        ap_get_core_module_config(r->request_config);
1280
0
            request_conf->suppress_charset = 1; /* avoid adding default
1281
                                                 * charset later
1282
                                                 */
1283
0
            ap_set_content_type_ex(r, "text/html", 1);
1284
0
        }
1285
0
        else {
1286
0
            ap_set_content_type_ex(r, "text/html; charset=iso-8859-1", 1);
1287
0
        }
1288
1289
0
        if ((status == HTTP_METHOD_NOT_ALLOWED)
1290
0
            || (status == HTTP_NOT_IMPLEMENTED)) {
1291
0
            apr_table_setn(r->headers_out, "Allow", make_allow(r));
1292
0
        }
1293
1294
0
        if (r->header_only) {
1295
0
            ap_finalize_request_protocol(r);
1296
0
            return;
1297
0
        }
1298
0
    }
1299
1300
0
    if ((custom_response = ap_response_code_string(r, idx))) {
1301
        /*
1302
         * We have a custom response output. This should only be
1303
         * a text-string to write back. But if the ErrorDocument
1304
         * was a local redirect and the requested resource failed
1305
         * for any reason, the custom_response will still hold the
1306
         * redirect URL. We don't really want to output this URL
1307
         * as a text message, so first check the custom response
1308
         * string to ensure that it is a text-string (using the
1309
         * same test used in ap_die(), i.e. does it start with a ").
1310
         *
1311
         * If it's not a text string, we've got a recursive error or
1312
         * an external redirect.  If it's a recursive error, ap_die passes
1313
         * us the second error code so we can write both, and has already
1314
         * backed up to the original error.  If it's an external redirect,
1315
         * it hasn't happened yet; we may never know if it fails.
1316
         */
1317
0
        if (custom_response[0] == '\"') {
1318
0
            ap_rvputs_proto_in_ascii(r, custom_response + 1, NULL);
1319
0
            ap_finalize_request_protocol(r);
1320
0
            return;
1321
0
        }
1322
0
    }
1323
0
    {
1324
0
        const char *title = status_lines[idx];
1325
0
        const char *h1;
1326
1327
        /* Accept a status_line set by a module, but only if it begins
1328
         * with the correct 3 digit status code
1329
         */
1330
0
        if (r->status_line) {
1331
0
            char *end;
1332
0
            int len = strlen(r->status_line);
1333
0
            if (len >= 3
1334
0
                && apr_strtoi64(r->status_line, &end, 10) == r->status
1335
0
                && (end - 3) == r->status_line
1336
0
                && (len < 4 || apr_isspace(r->status_line[3]))
1337
0
                && (len < 5 || apr_isalnum(r->status_line[4]))) {
1338
                /* Since we passed the above check, we know that length three
1339
                 * is equivalent to only a 3 digit numeric http status.
1340
                 * RFC2616 mandates a trailing space, let's add it.
1341
                 * If we have an empty reason phrase, we also add "Unknown Reason".
1342
                 */
1343
0
                if (len == 3) {
1344
0
                    r->status_line = apr_pstrcat(r->pool, r->status_line, " Unknown Reason", NULL);
1345
0
                } else if (len == 4) {
1346
0
                    r->status_line = apr_pstrcat(r->pool, r->status_line, "Unknown Reason", NULL);
1347
0
                }
1348
0
                title = r->status_line;
1349
0
            }
1350
0
        }
1351
1352
        /* folks decided they didn't want the error code in the H1 text */
1353
0
        h1 = &title[4];
1354
1355
        /* can't count on a charset filter being in place here,
1356
         * so do ebcdic->ascii translation explicitly (if needed)
1357
         */
1358
1359
0
        ap_rvputs_proto_in_ascii(r,
1360
0
                  DOCTYPE_HTML_4_01
1361
0
                  "<html><head>\n<title>", title,
1362
0
                  "</title>\n</head><body>\n<h1>", h1, "</h1>\n",
1363
0
                  NULL);
1364
1365
0
        ap_rvputs_proto_in_ascii(r,
1366
0
                                 get_canned_error_string(status, r, location),
1367
0
                                 NULL);
1368
1369
0
        if (recursive_error) {
1370
0
            ap_rvputs_proto_in_ascii(r, "<p>Additionally, a ",
1371
0
                      status_lines[ap_index_of_response(recursive_error)],
1372
0
                      "\nerror was encountered while trying to use an "
1373
0
                      "ErrorDocument to handle the request.</p>\n", NULL);
1374
0
        }
1375
0
        ap_rvputs_proto_in_ascii(r, ap_psignature("<hr>\n", r), NULL);
1376
0
        ap_rvputs_proto_in_ascii(r, "</body></html>\n", NULL);
1377
0
    }
1378
0
    ap_finalize_request_protocol(r);
1379
0
}
1380
1381
/*
1382
 * Create a new method list with the specified number of preallocated
1383
 * extension slots.
1384
 */
1385
AP_DECLARE(ap_method_list_t *) ap_make_method_list(apr_pool_t *p, int nelts)
1386
0
{
1387
0
    ap_method_list_t *ml;
1388
1389
0
    ml = (ap_method_list_t *) apr_palloc(p, sizeof(ap_method_list_t));
1390
0
    ml->method_mask = 0;
1391
0
    ml->method_list = apr_array_make(p, nelts, sizeof(char *));
1392
0
    return ml;
1393
0
}
1394
1395
/*
1396
 * Make a copy of a method list (primarily for subrequests that may
1397
 * subsequently change it; don't want them changing the parent's, too!).
1398
 */
1399
AP_DECLARE(void) ap_copy_method_list(ap_method_list_t *dest,
1400
                                     ap_method_list_t *src)
1401
0
{
1402
0
    int i;
1403
0
    char **imethods;
1404
0
    char **omethods;
1405
1406
0
    dest->method_mask = src->method_mask;
1407
0
    imethods = (char **) src->method_list->elts;
1408
0
    for (i = 0; i < src->method_list->nelts; ++i) {
1409
0
        omethods = (char **) apr_array_push(dest->method_list);
1410
0
        *omethods = apr_pstrdup(dest->method_list->pool, imethods[i]);
1411
0
    }
1412
0
}
1413
1414
/*
1415
 * Return true if the specified HTTP method is in the provided
1416
 * method list.
1417
 */
1418
AP_DECLARE(int) ap_method_in_list(ap_method_list_t *l, const char *method)
1419
0
{
1420
0
    int methnum;
1421
1422
    /*
1423
     * If it's one of our known methods, use the shortcut and check the
1424
     * bitmask.
1425
     */
1426
0
    methnum = ap_method_number_of(method);
1427
0
    if (methnum != M_INVALID) {
1428
0
        return !!(l->method_mask & (AP_METHOD_BIT << methnum));
1429
0
    }
1430
    /*
1431
     * Otherwise, see if the method name is in the array of string names.
1432
     */
1433
0
    if ((l->method_list == NULL) || (l->method_list->nelts == 0)) {
1434
0
        return 0;
1435
0
    }
1436
1437
0
    return ap_array_str_contains(l->method_list, method);
1438
0
}
1439
1440
/*
1441
 * Add the specified method to a method list (if it isn't already there).
1442
 */
1443
AP_DECLARE(void) ap_method_list_add(ap_method_list_t *l, const char *method)
1444
0
{
1445
0
    int methnum;
1446
0
    const char **xmethod;
1447
1448
    /*
1449
     * If it's one of our known methods, use the shortcut and use the
1450
     * bitmask.
1451
     */
1452
0
    methnum = ap_method_number_of(method);
1453
0
    if (methnum != M_INVALID) {
1454
0
        l->method_mask |= (AP_METHOD_BIT << methnum);
1455
0
        return;
1456
0
    }
1457
    /*
1458
     * Otherwise, see if the method name is in the array of string names.
1459
     */
1460
0
    if (ap_array_str_contains(l->method_list, method)) {
1461
0
        return;
1462
0
    }
1463
1464
0
    xmethod = (const char **) apr_array_push(l->method_list);
1465
0
    *xmethod = method;
1466
0
}
1467
1468
/*
1469
 * Remove the specified method from a method list.
1470
 */
1471
AP_DECLARE(void) ap_method_list_remove(ap_method_list_t *l,
1472
                                       const char *method)
1473
0
{
1474
0
    int methnum;
1475
0
    char **methods;
1476
1477
    /*
1478
     * If it's a known methods, either builtin or registered
1479
     * by a module, use the bitmask.
1480
     */
1481
0
    methnum = ap_method_number_of(method);
1482
0
    if (methnum != M_INVALID) {
1483
0
        l->method_mask &= ~(AP_METHOD_BIT << methnum);
1484
0
        return;
1485
0
    }
1486
    /*
1487
     * Otherwise, see if the method name is in the array of string names.
1488
     */
1489
0
    if (l->method_list->nelts != 0) {
1490
0
        int i, j, k;
1491
0
        methods = (char **)l->method_list->elts;
1492
0
        for (i = 0; i < l->method_list->nelts; ) {
1493
0
            if (strcmp(method, methods[i]) == 0) {
1494
0
                for (j = i, k = i + 1; k < l->method_list->nelts; ++j, ++k) {
1495
0
                    methods[j] = methods[k];
1496
0
                }
1497
0
                --l->method_list->nelts;
1498
0
            }
1499
0
            else {
1500
0
                ++i;
1501
0
            }
1502
0
        }
1503
0
    }
1504
0
}
1505
1506
/*
1507
 * Reset a method list to be completely empty.
1508
 */
1509
AP_DECLARE(void) ap_clear_method_list(ap_method_list_t *l)
1510
0
{
1511
0
    l->method_mask = 0;
1512
0
    l->method_list->nelts = 0;
1513
0
}
1514
1515
AP_DECLARE(apr_status_t) ap_h1_append_header(apr_bucket_brigade *bb,
1516
                                             apr_pool_t *pool,
1517
                                             const char *name, const char *value)
1518
0
{
1519
#if APR_CHARSET_EBCDIC
1520
    char *headfield;
1521
    apr_size_t len;
1522
1523
    headfield = apr_pstrcat(pool, name, ": ", value, CRLF, NULL);
1524
    len = strlen(headfield);
1525
1526
    ap_xlate_proto_to_ascii(headfield, len);
1527
    return apr_brigade_write(bb, NULL, NULL, headfield, len);
1528
#else
1529
0
    struct iovec vec[4];
1530
0
    struct iovec *v = vec;
1531
0
    v->iov_base = (void *)name;
1532
0
    v->iov_len = strlen(name);
1533
0
    v++;
1534
0
    v->iov_base = ": ";
1535
0
    v->iov_len = sizeof(": ") - 1;
1536
0
    v++;
1537
0
    v->iov_base = (void *)value;
1538
0
    v->iov_len = strlen(value);
1539
0
    v++;
1540
0
    v->iov_base = CRLF;
1541
0
    v->iov_len = sizeof(CRLF) - 1;
1542
0
    return apr_brigade_writev(bb, NULL, NULL, vec, 4);
1543
0
#endif /* !APR_CHARSET_EBCDIC */
1544
0
}
1545
1546
AP_DECLARE(apr_status_t) ap_h1_append_headers(apr_bucket_brigade *bb,
1547
                                              request_rec *r,
1548
                                              apr_table_t *headers)
1549
0
{
1550
0
    const apr_array_header_t *elts;
1551
0
    const apr_table_entry_t *t_elt;
1552
0
    const apr_table_entry_t *t_end;
1553
0
    struct iovec *vec;
1554
0
    struct iovec *vec_next;
1555
1556
0
    elts = apr_table_elts(headers);
1557
0
    if (elts->nelts == 0) {
1558
0
        return APR_SUCCESS;
1559
0
    }
1560
0
    t_elt = (const apr_table_entry_t *)(elts->elts);
1561
0
    t_end = t_elt + elts->nelts;
1562
0
    vec = (struct iovec *)apr_palloc(r->pool, 4 * elts->nelts *
1563
0
                                     sizeof(struct iovec));
1564
0
    vec_next = vec;
1565
1566
    /* For each field, generate
1567
     *    name ": " value CRLF
1568
     */
1569
0
    do {
1570
0
        if (t_elt->key && t_elt->val) {
1571
0
            vec_next->iov_base = (void*)(t_elt->key);
1572
0
            vec_next->iov_len = strlen(t_elt->key);
1573
0
            vec_next++;
1574
0
            vec_next->iov_base = ": ";
1575
0
            vec_next->iov_len = sizeof(": ") - 1;
1576
0
            vec_next++;
1577
0
            vec_next->iov_base = (void*)(t_elt->val);
1578
0
            vec_next->iov_len = strlen(t_elt->val);
1579
0
            vec_next++;
1580
0
            vec_next->iov_base = CRLF;
1581
0
            vec_next->iov_len = sizeof(CRLF) - 1;
1582
0
            vec_next++;
1583
0
        }
1584
0
        t_elt++;
1585
0
    } while (t_elt < t_end);
1586
1587
0
    if (APLOGrtrace4(r)) {
1588
0
        t_elt = (const apr_table_entry_t *)(elts->elts);
1589
0
        do {
1590
0
            ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, "  %s: %s",
1591
0
                          t_elt->key, t_elt->val);
1592
0
            t_elt++;
1593
0
        } while (t_elt < t_end);
1594
0
    }
1595
1596
#if APR_CHARSET_EBCDIC
1597
    {
1598
        apr_size_t len;
1599
        char *tmp = apr_pstrcatv(r->pool, vec, vec_next - vec, &len);
1600
        ap_xlate_proto_to_ascii(tmp, len);
1601
        return apr_brigade_write(bb, NULL, NULL, tmp, len);
1602
    }
1603
#else
1604
0
    return apr_brigade_writev(bb, NULL, NULL, vec, vec_next - vec);
1605
0
#endif
1606
0
}
1607
1608
AP_DECLARE(apr_status_t) ap_h1_terminate_header(apr_bucket_brigade *bb)
1609
0
{
1610
0
    char crlf[] = CRLF;
1611
0
    apr_size_t buflen;
1612
1613
0
    buflen = strlen(crlf);
1614
0
    ap_xlate_proto_to_ascii(crlf, buflen);
1615
0
    return apr_brigade_write(bb, NULL, NULL, crlf, buflen);
1616
0
}
1617
1618
AP_DECLARE(void) ap_h1_add_end_chunk(apr_bucket_brigade *b,
1619
                                     apr_bucket *eos,
1620
                                     request_rec *r,
1621
                                     apr_table_t *trailers)
1622
0
{
1623
0
    if (!trailers || apr_is_empty_table(trailers)) {
1624
0
        apr_bucket *e;
1625
1626
0
        ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1627
0
                      "append empty end chunk");
1628
0
        e = apr_bucket_immortal_create(ZERO_ASCII CRLF_ASCII
1629
0
                                       CRLF_ASCII, 5, b->bucket_alloc);
1630
0
        if (eos) {
1631
0
            APR_BUCKET_INSERT_BEFORE(eos, e);
1632
0
        }
1633
0
        else {
1634
0
            APR_BRIGADE_INSERT_TAIL(b, e);
1635
0
        }
1636
0
    }
1637
0
    else {
1638
0
        apr_bucket_brigade *tmp;
1639
1640
0
        ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1641
0
                      "append end chunk with trailers");
1642
0
        tmp = eos? apr_brigade_split_ex(b, eos, NULL) : NULL;
1643
0
        apr_brigade_write(b, NULL, NULL, ZERO_ASCII CRLF_ASCII, 3);
1644
0
        ap_h1_append_headers(b, r, trailers);
1645
0
        ap_h1_terminate_header(b);
1646
0
        if (tmp) APR_BRIGADE_CONCAT(b, tmp);
1647
0
    }
1648
0
}
1649
1650
typedef enum {
1651
    rrl_none, rrl_badprotocol, rrl_badmethod, rrl_badwhitespace, rrl_excesswhitespace,
1652
    rrl_missinguri, rrl_baduri, rrl_trailingtext,
1653
} rrl_error;
1654
1655
/* get the length of a name for logging, but no more than 80 bytes */
1656
0
#define LOG_NAME_MAX_LEN 80
1657
static int log_name_len(const char *name)
1658
0
{
1659
0
    apr_size_t len = strlen(name);
1660
0
    return (len > LOG_NAME_MAX_LEN)? LOG_NAME_MAX_LEN : (int)len;
1661
0
}
1662
1663
static void rrl_log_error(request_rec *r, rrl_error error, const char *etoken)
1664
0
{
1665
0
    switch (error) {
1666
0
    case rrl_none:
1667
0
        break;
1668
0
    case rrl_badprotocol:
1669
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)
1670
0
                      "HTTP Request Line; Unrecognized protocol '%.*s' "
1671
0
                      "(perhaps whitespace was injected?)",
1672
0
                      log_name_len(etoken), etoken);
1673
0
        break;
1674
0
    case rrl_badmethod:
1675
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03445)
1676
0
                      "HTTP Request Line; Invalid method token: '%.*s'",
1677
0
                      log_name_len(etoken), etoken);
1678
0
        break;
1679
0
    case rrl_badwhitespace:
1680
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03447)
1681
0
                      "HTTP Request Line; Invalid whitespace");
1682
0
        break;
1683
0
    case rrl_excesswhitespace:
1684
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03448)
1685
0
                      "HTTP Request Line; Excess whitespace "
1686
0
                      "(disallowed by HttpProtocolOptions Strict)");
1687
0
        break;
1688
0
    case rrl_missinguri:
1689
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03446)
1690
0
                      "HTTP Request Line; Missing URI");
1691
0
        break;
1692
0
    case rrl_baduri:
1693
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03454)
1694
0
                      "HTTP Request Line; URI incorrectly encoded: '%.*s'",
1695
0
                      log_name_len(etoken), etoken);
1696
0
        break;
1697
0
    case rrl_trailingtext:
1698
0
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03449)
1699
0
                      "HTTP Request Line; Extraneous text found '%.*s' "
1700
0
                      "(perhaps whitespace was injected?)",
1701
0
                      log_name_len(etoken), etoken);
1702
0
        break;
1703
0
    }
1704
0
}
1705
1706
/* remember the first error we encountered during tokenization */
1707
#define RRL_ERROR(e, et, y, yt)     \
1708
0
    do { \
1709
0
        if (e == rrl_none) {\
1710
0
            e = y; et = yt;\
1711
0
        }\
1712
0
    } while (0)
1713
1714
static rrl_error tokenize_request_line(
1715
        char *line, int strict,
1716
        const char **pmethod, const char **puri, const char **pprotocol,
1717
        const char **perror_token)
1718
0
{
1719
0
    char *method, *protocol, *uri, *ll;
1720
0
    rrl_error e = rrl_none;
1721
0
    char *etoken = NULL;
1722
0
    apr_size_t len = 0;
1723
1724
0
    method = line;
1725
    /* If there is whitespace before a method, skip it and mark in error */
1726
0
    if (apr_isspace(*method)) {
1727
0
        RRL_ERROR(e, etoken, rrl_badwhitespace, method);
1728
0
        for ( ; apr_isspace(*method); ++method)
1729
0
            ;
1730
0
    }
1731
1732
    /* Scan the method up to the next whitespace, ensure it contains only
1733
     * valid http-token characters, otherwise mark in error
1734
     */
1735
0
    if (strict) {
1736
0
        ll = (char*) ap_scan_http_token(method);
1737
0
    }
1738
0
    else {
1739
0
        ll = (char*) ap_scan_vchar_obstext(method);
1740
0
    }
1741
1742
0
    if ((ll == method) || (*ll && !apr_isspace(*ll))) {
1743
0
        RRL_ERROR(e, etoken, rrl_badmethod, ll);
1744
0
        ll = strpbrk(ll, "\t\n\v\f\r ");
1745
0
    }
1746
1747
    /* Verify method terminated with a single SP, or mark as specific error */
1748
0
    if (!ll) {
1749
0
        RRL_ERROR(e, etoken, rrl_missinguri, NULL);
1750
0
        protocol = uri = "";
1751
0
        goto done;
1752
0
    }
1753
0
    else if (strict && ll[0] && apr_isspace(ll[1])) {
1754
0
        RRL_ERROR(e, etoken, rrl_excesswhitespace, ll);
1755
0
    }
1756
1757
    /* Advance uri pointer over leading whitespace, NUL terminate the method
1758
     * If non-SP whitespace is encountered, mark as specific error
1759
     */
1760
0
    for (uri = ll; apr_isspace(*uri); ++uri)
1761
0
        if (*uri != ' ')
1762
0
            RRL_ERROR(e, etoken, rrl_badwhitespace, uri);
1763
0
    *ll = '\0';
1764
1765
0
    if (!*uri)
1766
0
        RRL_ERROR(e, etoken, rrl_missinguri, NULL);
1767
1768
    /* Scan the URI up to the next whitespace, ensure it contains no raw
1769
     * control characters, otherwise mark in error
1770
     */
1771
0
    ll = (char*) ap_scan_vchar_obstext(uri);
1772
0
    if (ll == uri || (*ll && !apr_isspace(*ll))) {
1773
0
        RRL_ERROR(e, etoken, rrl_baduri, ll);
1774
0
        ll = strpbrk(ll, "\t\n\v\f\r ");
1775
0
    }
1776
1777
    /* Verify URI terminated with a single SP, or mark as specific error */
1778
0
    if (!ll) {
1779
0
        protocol = "";
1780
0
        goto done;
1781
0
    }
1782
0
    else if (strict && ll[0] && apr_isspace(ll[1])) {
1783
0
        RRL_ERROR(e, etoken, rrl_excesswhitespace, ll);
1784
0
    }
1785
1786
    /* Advance protocol pointer over leading whitespace, NUL terminate the uri
1787
     * If non-SP whitespace is encountered, mark as specific error
1788
     */
1789
0
    for (protocol = ll; apr_isspace(*protocol); ++protocol)
1790
0
        if (*protocol != ' ')
1791
0
            RRL_ERROR(e, etoken, rrl_badwhitespace, protocol);
1792
0
    *ll = '\0';
1793
1794
    /* Scan the protocol up to the next whitespace, validation comes later */
1795
0
    if (!(ll = (char*) ap_scan_vchar_obstext(protocol))) {
1796
0
        len = strlen(protocol);
1797
0
        goto done;
1798
0
    }
1799
0
    len = ll - protocol;
1800
1801
    /* Advance over trailing whitespace, if found mark in error,
1802
     * determine if trailing text is found, unconditionally mark in error,
1803
     * finally NUL terminate the protocol string
1804
     */
1805
0
    if (*ll && !apr_isspace(*ll)) {
1806
0
        RRL_ERROR(e, etoken, rrl_badprotocol, ll);
1807
0
    }
1808
0
    else if (strict && *ll) {
1809
0
        RRL_ERROR(e, etoken, rrl_excesswhitespace, ll);
1810
0
    }
1811
0
    else {
1812
0
        for ( ; apr_isspace(*ll); ++ll)
1813
0
            if (*ll != ' ') {
1814
0
                RRL_ERROR(e, etoken, rrl_badwhitespace, ll);
1815
0
                break;
1816
0
            }
1817
0
        if (*ll)
1818
0
            RRL_ERROR(e, etoken, rrl_trailingtext, ll);
1819
0
    }
1820
0
    *((char *)protocol + len) = '\0';
1821
1822
0
done:
1823
0
    *pmethod = method;
1824
0
    *puri = uri;
1825
0
    *pprotocol = protocol;
1826
0
    *perror_token = etoken;
1827
0
    return e;
1828
0
}
1829
1830
AP_DECLARE(int) ap_h1_tokenize_request_line(
1831
        request_rec *r, const char *line,
1832
        const char **pmethod, const char **puri, const char **pprotocol)
1833
0
{
1834
0
    core_server_config *conf = ap_get_core_module_config(r->server->module_config);
1835
0
    int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
1836
0
    rrl_error error;
1837
0
    const char *error_token;
1838
1839
0
    ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r,
1840
0
                  "ap_tokenize_request_line: '%s'", line);
1841
0
    error = tokenize_request_line(apr_pstrdup(r->pool, line), strict, pmethod,
1842
0
                                  puri, pprotocol, &error_token);
1843
0
    ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r,
1844
0
                  "ap_tokenize_request: error=%d, method=%s, uri=%s, protocol=%s",
1845
0
                  error, *pmethod, *puri, *pprotocol);
1846
0
    if (error != rrl_none) {
1847
0
        rrl_log_error(r, error, error_token);
1848
0
        return 0;
1849
0
    }
1850
0
    return 1;
1851
0
}