libmicrohttpd2

HTTP server C library (MHD 2.x, alpha)
Log | Files | Refs | README | LICENSE

stream_process_request.c (145571B)


      1 /* SPDX-License-Identifier: LGPL-2.1-or-later OR (GPL-2.0-or-later WITH eCos-exception-2.0) */
      2 /*
      3   This file is part of GNU libmicrohttpd.
      4   Copyright (C) 2014-2024 Evgeny Grin (Karlson2k)
      5   Copyright (C) 2007-2020 Daniel Pittman and Christian Grothoff
      6 
      7   GNU libmicrohttpd is free software; you can redistribute it and/or
      8   modify it under the terms of the GNU Lesser General Public
      9   License as published by the Free Software Foundation; either
     10   version 2.1 of the License, or (at your option) any later version.
     11 
     12   GNU libmicrohttpd is distributed in the hope that it will be useful,
     13   but WITHOUT ANY WARRANTY; without even the implied warranty of
     14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     15   Lesser General Public License for more details.
     16 
     17   Alternatively, you can redistribute GNU libmicrohttpd and/or
     18   modify it under the terms of the GNU General Public License as
     19   published by the Free Software Foundation; either version 2 of
     20   the License, or (at your option) any later version, together
     21   with the eCos exception, as follows:
     22 
     23     As a special exception, if other files instantiate templates or
     24     use macros or inline functions from this file, or you compile this
     25     file and link it with other works to produce a work based on this
     26     file, this file does not by itself cause the resulting work to be
     27     covered by the GNU General Public License. However the source code
     28     for this file must still be made available in accordance with
     29     section (3) of the GNU General Public License v2.
     30 
     31     This exception does not invalidate any other reasons why a work
     32     based on this file might be covered by the GNU General Public
     33     License.
     34 
     35   You should have received copies of the GNU Lesser General Public
     36   License and the GNU General Public License along with this library;
     37   if not, see <https://www.gnu.org/licenses/>.
     38 */
     39 
     40 /**
     41  * @file src/mhd2/stream_process_request.c
     42  * @brief  The implementation of internal functions for requests parsing
     43  *         and processing
     44  * @author Karlson2k (Evgeny Grin)
     45  *
     46  * Based on the MHD v0.x code by Daniel Pittman, Christian Grothoff and other
     47  * contributors.
     48  */
     49 
     50 #include "mhd_sys_options.h"
     51 #include "stream_process_request.h"
     52 
     53 #include "sys_bool_type.h"
     54 #include "sys_base_types.h"
     55 
     56 #include "mhd_assert.h"
     57 #include "mhd_unreachable.h"
     58 #include "mhd_assume.h"
     59 
     60 #include "sys_malloc.h"
     61 
     62 #ifdef MHD_USE_TRACE_SUSPEND_RESUME
     63 #  include <stdio.h>
     64 #endif /* MHD_USE_TRACE_SUSPEND_RESUME */
     65 
     66 #include "mhd_str_types.h"
     67 #include "mhd_str_macros.h"
     68 #include "mhd_str.h"
     69 
     70 #include <string.h>
     71 
     72 #include "mhd_daemon.h"
     73 #include "mhd_connection.h"
     74 
     75 #include "daemon_logger.h"
     76 #include "mhd_panic.h"
     77 
     78 #include "mempool_funcs.h"
     79 
     80 #include "response_destroy.h"
     81 #include "request_funcs.h"
     82 #include "request_get_value.h"
     83 #include "respond_with_error.h"
     84 #include "stream_funcs.h"
     85 #include "daemon_funcs.h"
     86 #include "http_method_parse.h"
     87 
     88 #ifdef MHD_SUPPORT_POST_PARSER
     89 #  include "post_parser_funcs.h"
     90 #endif /* MHD_SUPPORT_POST_PARSER */
     91 
     92 #include "mhd_public_api.h"
     93 
     94 
     95 /**
     96  * Response text used when the request (http header) is
     97  * malformed.
     98  */
     99 #define ERR_RSP_REQUEST_MALFORMED \
    100         "<html><head><title>Request malformed</title></head>" \
    101         "<body>HTTP request is syntactically incorrect.</body></html>"
    102 
    103 /**
    104  * Response text used when the request HTTP version is too old.
    105  */
    106 #define ERR_RSP_REQ_HTTP_VER_IS_TOO_OLD \
    107         "<html>" \
    108         "<head><title>Requested HTTP version is not supported</title></head>" \
    109         "<body>Requested HTTP version is too old and not " \
    110         "supported.</body></html>"
    111 /**
    112  * Response text used when the request HTTP version is not supported.
    113  */
    114 #define ERR_RSP_REQ_HTTP_VER_IS_NOT_SUPPORTED \
    115         "<html>" \
    116         "<head><title>Requested HTTP version is not supported</title></head>" \
    117         "<body>Requested HTTP version is not supported.</body></html>"
    118 
    119 /**
    120  * Response text used when the request HTTP header has bare CR character
    121  * without LF character (and CR is not allowed to be treated as whitespace).
    122  */
    123 #define ERR_RSP_BARE_CR_IN_HEADER \
    124         "<html>" \
    125         "<head><title>Request broken</title></head>" \
    126         "<body>Request HTTP header has bare CR character without " \
    127         "following LF character.</body>" \
    128         "</html>"
    129 
    130 /**
    131  * Response text used when the request HTTP footer has bare CR character
    132  * without LF character (and CR is not allowed to be treated as whitespace).
    133  */
    134 #define ERR_RSP_BARE_CR_IN_FOOTER \
    135         "<html>" \
    136         "<head><title>Request broken</title></head>" \
    137         "<body>Request HTTP footer has bare CR character without " \
    138         "following LF character.</body>" \
    139         "</html>"
    140 
    141 /**
    142  * Response text used when the request HTTP header has bare LF character
    143  * without CR character.
    144  */
    145 #define ERR_RSP_BARE_LF_IN_HEADER \
    146         "<html>" \
    147         "<head><title>Request broken</title></head>" \
    148         "<body>Request HTTP header has bare LF character without " \
    149         "preceding CR character.</body>" \
    150         "</html>"
    151 /**
    152  * Response text used when the request HTTP footer has bare LF character
    153  * without CR character.
    154  */
    155 #define ERR_RSP_BARE_LF_IN_FOOTER \
    156         "<html>" \
    157         "<head><title>Request broken</title></head>" \
    158         "<body>Request HTTP footer has bare LF character without " \
    159         "preceding CR character.</body>" \
    160         "</html>"
    161 
    162 /**
    163  * Response text used when the request line has more then two whitespaces.
    164  */
    165 #define ERR_RSP_RQ_LINE_TOO_MANY_WSP \
    166         "<html>" \
    167         "<head><title>Request broken</title></head>" \
    168         "<body>The request line has more then two whitespaces.</body>" \
    169         "</html>"
    170 
    171 /**
    172  * Response text used when the request line has invalid characters in URI.
    173  */
    174 #define ERR_RSP_RQ_TARGET_INVALID_CHAR \
    175         "<html>" \
    176         "<head><title>Request broken</title></head>" \
    177         "<body>HTTP request has invalid characters in " \
    178         "the request-target.</body>" \
    179         "</html>"
    180 
    181 /**
    182  * Response text used when line folding is used in request headers.
    183  */
    184 #define ERR_RSP_OBS_FOLD \
    185         "<html>" \
    186         "<head><title>Request broken</title></head>" \
    187         "<body>Obsolete line folding is used in HTTP request header.</body>" \
    188         "</html>"
    189 
    190 /**
    191  * Response text used when line folding is used in request footers.
    192  */
    193 #define ERR_RSP_OBS_FOLD_FOOTER \
    194         "<html>" \
    195         "<head><title>Request broken</title></head>" \
    196         "<body>Obsolete line folding is used in HTTP request footer.</body>" \
    197         "</html>"
    198 
    199 /**
    200  * Response text used when request header has no colon character.
    201  */
    202 #define ERR_RSP_HEADER_WITHOUT_COLON \
    203         "<html>" \
    204         "<head><title>Request broken</title></head>" \
    205         "<body>HTTP request header line has no colon character.</body>" \
    206         "</html>"
    207 
    208 /**
    209  * Response text used when request footer has no colon character.
    210  */
    211 #define ERR_RSP_FOOTER_WITHOUT_COLON \
    212         "<html>" \
    213         "<head><title>Request broken</title></head>" \
    214         "<body>HTTP request footer line has no colon character.</body>" \
    215         "</html>"
    216 /**
    217  * Response text used when the request has whitespace at the start
    218  * of the first header line.
    219  */
    220 #define ERR_RSP_WSP_BEFORE_HEADER \
    221         "<html>" \
    222         "<head><title>Request broken</title></head>" \
    223         "<body>HTTP request has whitespace between the request line and " \
    224         "the first header.</body>" \
    225         "</html>"
    226 
    227 /**
    228  * Response text used when the request has whitespace at the start
    229  * of the first footer line.
    230  */
    231 #define ERR_RSP_WSP_BEFORE_FOOTER \
    232         "<html>" \
    233         "<head><title>Request broken</title></head>" \
    234         "<body>First HTTP footer line has whitespace at the first " \
    235         "position.</body>" \
    236         "</html>"
    237 
    238 /**
    239  * Response text used when the whitespace found before colon (inside header
    240  * name or between header name and colon).
    241  */
    242 #define ERR_RSP_WSP_IN_HEADER_NAME \
    243         "<html>" \
    244         "<head><title>Request broken</title></head>" \
    245         "<body>HTTP request has whitespace before the first colon " \
    246         "in header line.</body>" \
    247         "</html>"
    248 
    249 /**
    250  * Response text used when the whitespace found before colon (inside header
    251  * name or between header name and colon).
    252  */
    253 #define ERR_RSP_WSP_IN_FOOTER_NAME \
    254         "<html>" \
    255         "<head><title>Request broken</title></head>" \
    256         "<body>HTTP request has whitespace before the first colon " \
    257         "in footer line.</body>" \
    258         "</html>"
    259 /**
    260  * Response text used when request header has invalid character.
    261  */
    262 #define ERR_RSP_INVALID_CHR_IN_HEADER \
    263         "<html>" \
    264         "<head><title>Request broken</title></head>" \
    265         "<body>HTTP request has invalid character in header.</body>" \
    266         "</html>"
    267 
    268 /**
    269  * Response text used when request header has invalid character.
    270  */
    271 #define ERR_RSP_INVALID_CHR_IN_FOOTER \
    272         "<html>" \
    273         "<head><title>Request broken</title></head>" \
    274         "<body>HTTP request has invalid character in footer.</body>" \
    275         "</html>"
    276 
    277 /**
    278  * Response text used when request header has zero-length header (filed) name.
    279  */
    280 #define ERR_RSP_EMPTY_HEADER_NAME \
    281         "<html>" \
    282         "<head><title>Request broken</title></head>" \
    283         "<body>HTTP request header has empty header name.</body>" \
    284         "</html>"
    285 
    286 /**
    287  * Response text used when request header has zero-length header (filed) name.
    288  */
    289 #define ERR_RSP_EMPTY_FOOTER_NAME \
    290         "<html>" \
    291         "<head><title>Request broken</title></head>" \
    292         "<body>HTTP request footer has empty footer name.</body>" \
    293         "</html>"
    294 
    295 /**
    296  * Response text used when the request header is too big to be processed.
    297  */
    298 #define ERR_RSP_REQUEST_HEADER_TOO_BIG \
    299    "<html>" \
    300    "<head><title>Request too big</title></head>" \
    301    "<body><p>The total size of the request headers, which includes the " \
    302    "request target and the request field lines, exceeds the memory " \
    303    "constraints of this web server.</p>" \
    304    "<p>The request could be re-tried with shorter field lines, a shorter " \
    305    "request target or a shorter request method token.</p></body>" \
    306    "</html>"
    307 
    308 /**
    309  * Response text used when the request header is too big to be processed.
    310  */
    311 #define ERR_RSP_REQUEST_FOOTER_TOO_BIG \
    312         "<html>" \
    313         "<head><title>Request too big</title></head>" \
    314         "<body><p>The total size of the request headers, which includes the " \
    315         "request target, the request field lines and the chunked trailer " \
    316         "section exceeds the memory constraints of this web server.</p>" \
    317         "<p>The request could be re-tried with a shorter chunked trailer " \
    318         "section, shorter field lines, a shorter request target or " \
    319         "a shorter request method token.</p></body>" \
    320         "</html>"
    321 
    322 /**
    323  * Response text used when the request (http header) is too big to
    324  * be processed.
    325  */
    326 #define ERR_RSP_MSG_REQUEST_TOO_BIG \
    327         "<html>" \
    328         "<head><title>Request too big</title></head>" \
    329         "<body>Request HTTP header is too big for the memory constraints " \
    330         "of this webserver.</body>" \
    331         "</html>"
    332 /**
    333  * Response text used when the request chunk size line with chunk extension
    334  * cannot fit the buffer.
    335  */
    336 #define ERR_RSP_REQUEST_CHUNK_LINE_EXT_TOO_BIG \
    337   "<html>" \
    338   "<head><title>Request too big</title></head>" \
    339   "<body><p>The total size of the request target, the request field lines " \
    340   "and the chunk size line exceeds the memory constraints of this web " \
    341   "server.</p>" \
    342   "<p>The request could be re-tried without chunk extensions, with a smaller " \
    343   "chunk size, shorter field lines, a shorter request target or a shorter " \
    344   "request method token.</p></body>" \
    345   "</html>"
    346 
    347 /**
    348  * Response text used when the request chunk size line without chunk extension
    349  * cannot fit the buffer.
    350  */
    351 #define ERR_RSP_REQUEST_CHUNK_LINE_TOO_BIG \
    352    "<html>" \
    353    "<head><title>Request too big</title></head>" \
    354    "<body><p>The total size of the request target, the request field lines " \
    355    "and the chunk size line exceeds the memory constraints of this web " \
    356    "server.</p>" \
    357    "<p>The request could be re-tried with a smaller " \
    358    "chunk size, shorter field lines, a shorter request target or a shorter " \
    359    "request method token.</p></body>" \
    360    "</html>"
    361 
    362 /**
    363  * Response text used when the request (http header) does not
    364  * contain a "Host:" header and still claims to be HTTP 1.1.
    365  */
    366 #define ERR_RSP_REQUEST_LACKS_HOST \
    367         "<html>" \
    368         "<head><title>&quot;Host:&quot; header required</title></head>" \
    369         "<body>HTTP/1.1 request without <b>&quot;Host:&quot;</b>.</body>" \
    370         "</html>"
    371 
    372 /**
    373  * Response text used when the request has more than one "Host:" header.
    374  */
    375 #define ERR_RSP_REQUEST_HAS_SEVERAL_HOSTS \
    376         "<html>" \
    377         "<head>" \
    378         "<title>Several &quot;Host:&quot; headers used</title></head>" \
    379         "<body>" \
    380         "Request with more than one <b>&quot;Host:&quot;</b> header.</body>" \
    381         "</html>"
    382 
    383 /**
    384  * Response text used when the request has more than one "Host:" header.
    385  */
    386 #define ERR_RSP_REQUEST_HAS_MALFORMED_HOST \
    387         "<html>" \
    388         "<head>" \
    389         "<title>Malformed &quot;Host:&quot; header</title></head>" \
    390         "<body>" \
    391         "Malformed <b>&quot;Host:&quot;</b> header in the request.</body>" \
    392         "</html>"
    393 
    394 /**
    395  * Response text used when the request has unsupported "Transfer-Encoding:".
    396  */
    397 #define ERR_RSP_UNSUPPORTED_TR_ENCODING \
    398         "<html>" \
    399         "<head><title>Unsupported Transfer-Encoding</title></head>" \
    400         "<body>The Transfer-Encoding used in request is not supported.</body>" \
    401         "</html>"
    402 
    403 /**
    404  * Response text used when the request has unsupported "Expect:" value.
    405  */
    406 #define ERR_RSP_UNSUPPORTED_EXPECT_HDR_VALUE \
    407         "<html>" \
    408         "<head><title>Unsupported 'Expect:'</title></head>" \
    409         "<body>The value of 'Expect:' header used in the request is " \
    410         "not supported.</body>" \
    411         "</html>"
    412 
    413 /**
    414  * Response text used when the request has unsupported both headers:
    415  * "Transfer-Encoding:" and "Content-Length:"
    416  */
    417 #define ERR_RSP_REQUEST_CNTNLENGTH_WITH_TR_ENCODING \
    418    "<html>" \
    419    "<head><title>Malformed request</title></head>" \
    420    "<body>Wrong combination of the request headers: both Transfer-Encoding " \
    421    "and Content-Length headers are used at the same time.</body>" \
    422    "</html>"
    423 
    424 /**
    425  * Response text used when the request HTTP content is too large.
    426  */
    427 #define ERR_RSP_REQUEST_CONTENTLENGTH_TOOLARGE \
    428         "<html><head><title>Request content too large</title></head>" \
    429         "<body>HTTP request has too large value for " \
    430         "<b>Content-Length</b> header.</body></html>"
    431 
    432 /**
    433  * Response text used when the request HTTP chunked encoding is
    434  * malformed.
    435  */
    436 #define ERR_RSP_REQUEST_CONTENTLENGTH_MALFORMED \
    437         "<html><head><title>Request malformed</title></head>" \
    438         "<body>HTTP request has wrong value for " \
    439         "<b>Content-Length</b> header.</body></html>"
    440 
    441 /**
    442  * Response text used when the request has more than one "Content-Length:"
    443  * header.
    444  */
    445 #define ERR_RSP_REQUEST_CONTENTLENGTH_SEVERAL \
    446         "<html><head><title>Request malformed</title></head>" \
    447         "<body>HTTP request has several " \
    448         "<b>Content-Length</b> headers.</body></html>"
    449 
    450 /**
    451  * Response text used when the request HTTP chunked encoding is
    452  * malformed.
    453  */
    454 #define ERR_RSP_REQUEST_CHUNKED_MALFORMED \
    455         "<html><head><title>Request malformed</title></head>" \
    456         "<body>HTTP chunked encoding is syntactically incorrect.</body></html>"
    457 
    458 /**
    459  * Response text used when the request HTTP chunk is too large.
    460  */
    461 #define ERR_RSP_REQUEST_CHUNK_TOO_LARGE \
    462         "<html><head><title>Request content too large</title></head>" \
    463         "<body>The chunk size used in HTTP chunked encoded " \
    464         "request is too large.</body></html>"
    465 
    466 
    467 /**
    468  * The reasonable length of the upload chunk "header" (the size specifier
    469  * with optional chunk extension).
    470  * MHD tries to keep the space in the read buffer large enough to read
    471  * the chunk "header" in one step.
    472  * The real "header" could be much larger, it will be handled correctly
    473  * anyway, however it may require several rounds of buffer grow.
    474  */
    475 #define MHD_CHUNK_HEADER_REASONABLE_LEN 24
    476 
    477 /**
    478  * The valid length of any HTTP version string
    479  */
    480 #define HTTP_VER_LEN (mhd_SSTR_LEN (MHD_HTTP_VERSION_1_1_STR))
    481 
    482 
    483 /**
    484  * Detect standard HTTP request method
    485  *
    486  * @param connection the connection to process
    487  */
    488 static MHD_FN_PAR_NONNULL_ALL_ void
    489 parse_http_std_method (struct MHD_Connection *restrict connection)
    490 {
    491   const char *const restrict m = connection->rq.method.cstr; /**< short alias */
    492   const size_t len =  connection->rq.method.len; /**< short alias */
    493   mhd_assert (NULL != m);
    494   mhd_assert (0 != len);
    495   mhd_assert (0 == m[len]);
    496 
    497   connection->rq.http_mthd = mhd_parse_http_method (len,
    498                                                     m);
    499 }
    500 
    501 
    502 /**
    503  * Internal version of #MHD_HTTP_ProtocolVersion extended with mhd_HTTP_VER_0X
    504  */
    505 enum MHD_FIXED_ENUM_MHD_SET_ mhd_HTTP_ProtVerParse
    506 {
    507   mhd_HTTP_VER_INVALID = MHD_HTTP_VERSION_INVALID
    508   ,
    509   mhd_HTTP_VER_0X = 9
    510   ,
    511   mhd_HTTP_VER_1_0 = MHD_HTTP_VERSION_1_0
    512   ,
    513   mhd_HTTP_VER_1_1 = MHD_HTTP_VERSION_1_1
    514   ,
    515   mhd_HTTP_VER_1_2P = MHD_HTTP_VERSION_1_2P
    516   ,
    517   mhd_HTTP_VER_2 = MHD_HTTP_VERSION_2
    518   ,
    519   mhd_HTTP_VER_3 = MHD_HTTP_VERSION_3
    520   ,
    521   mhd_HTTP_VER_FUTURE = MHD_HTTP_VERSION_FUTURE
    522 };
    523 
    524 
    525 /**
    526  * Parse HTTP version
    527  *
    528  * @param len the length of @a http_string in bytes
    529  * @param http_string the pointer to HTTP version string
    530  */
    531 static MHD_FN_PAR_IN_SIZE_ (2, 1) MHD_FN_PAR_NONNULL_ALL_
    532 enum mhd_HTTP_ProtVerParse
    533 parse_http_version (size_t len,
    534                     const char *restrict http_string)
    535 {
    536   const char *const h = http_string; /**< short alias */
    537   mhd_assert (NULL != http_string);
    538 
    539   /* String must start with 'HTTP/d.d', case-sensitive match.
    540    * See https://www.rfc-editor.org/rfc/rfc9112#name-http-version */
    541   if ((HTTP_VER_LEN == len)
    542       && (0 == memcmp ("HTTP/", h, 5u))
    543       && ('.' == h[6]))
    544   {
    545     const unsigned char mj = (unsigned char)(h[5] - '0');  /**< Major number */
    546     const unsigned char mn = (unsigned char)(h[7] - '0');  /**< Minor number */
    547 
    548     if (1u == mj)
    549     {
    550       /* HTTP/1.x */
    551       if (1u == mn)
    552         return mhd_HTTP_VER_1_1;
    553       if (0u == mn)
    554         return mhd_HTTP_VER_1_0;
    555       if (9u >= mn)
    556         return mhd_HTTP_VER_1_2P;
    557 
    558       return mhd_HTTP_VER_INVALID;
    559     }
    560 
    561     if ((0u == mj) && (9u >= mn))
    562       return mhd_HTTP_VER_0X; /* Too old major version */
    563 
    564     if ((2u == mj) && (0u == mn))
    565       return mhd_HTTP_VER_2;
    566   }
    567 
    568   return mhd_HTTP_VER_INVALID;
    569 }
    570 
    571 
    572 /**
    573  * Detect HTTP version, send error response if version is not supported
    574  *
    575  * @param connection the connection
    576  * @param http_string the pointer to HTTP version string
    577  * @param len the length of @a http_string in bytes
    578  * @return true if HTTP version is correct and supported,
    579  *         false if HTTP version is not correct or unsupported.
    580  */
    581 static MHD_FN_PAR_IN_SIZE_ (3, 2) MHD_FN_PAR_NONNULL_ALL_ bool
    582 process_http_version (struct MHD_Connection *restrict connection,
    583                       size_t len,
    584                       const char *restrict http_string)
    585 {
    586   enum mhd_HTTP_ProtVerParse h_ver;
    587 
    588   h_ver = parse_http_version (len,
    589                               http_string);
    590   if (mhd_HTTP_VER_0X == h_ver)
    591   {
    592     connection->rq.http_ver = MHD_HTTP_VERSION_INVALID;
    593     mhd_RESPOND_WITH_ERROR_STATIC (connection,
    594                                    MHD_HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
    595                                    ERR_RSP_REQ_HTTP_VER_IS_TOO_OLD);
    596     return false;
    597   }
    598 
    599   connection->rq.http_ver = (enum MHD_HTTP_ProtocolVersion)h_ver;
    600 
    601   switch (connection->rq.http_ver)
    602   {
    603   case MHD_HTTP_VERSION_INVALID:
    604     break;
    605   case MHD_HTTP_VERSION_1_1:
    606   case MHD_HTTP_VERSION_1_0:
    607     return true;
    608   case MHD_HTTP_VERSION_1_2P:
    609     if (MHD_PSL_VERY_STRICT > connection->daemon->req_cfg.strictness)
    610       return true;
    611     break;
    612   case MHD_HTTP_VERSION_2:
    613     mhd_RESPOND_WITH_ERROR_STATIC (connection,
    614                                    MHD_HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
    615                                    ERR_RSP_REQ_HTTP_VER_IS_NOT_SUPPORTED);
    616     return false;
    617   case MHD_HTTP_VERSION_3:
    618   case MHD_HTTP_VERSION_FUTURE:
    619   default:
    620     mhd_UNREACHABLE ();
    621     break;
    622   }
    623 
    624   mhd_RESPOND_WITH_ERROR_STATIC (connection,
    625                                  MHD_HTTP_STATUS_BAD_REQUEST,
    626                                  ERR_RSP_REQUEST_MALFORMED);
    627   return false;
    628 }
    629 
    630 
    631 #ifndef MHD_MAX_EMPTY_LINES_SKIP
    632 /**
    633  * The maximum number of ignored empty line before the request line
    634  * at default "strictness" level.
    635  */
    636 #  define MHD_MAX_EMPTY_LINES_SKIP 1024
    637 #endif /* ! MHD_MAX_EMPTY_LINES_SKIP */
    638 
    639 
    640 /**
    641  * Find and parse the request line.
    642  * @param c the connection to process
    643  * @return true if request line completely processed (or unrecoverable error
    644  *         found) and state is changed,
    645  *         false if not enough data yet in the receive buffer
    646  */
    647 static MHD_FN_PAR_NONNULL_ALL_ bool
    648 get_request_line_inner (struct MHD_Connection *restrict c)
    649 {
    650   size_t p; /**< The current processing position */
    651   const int discp_lvl = c->daemon->req_cfg.strictness;
    652   /* Allow to skip one or more empty lines before the request line.
    653      RFC 9112, section 2.2 */
    654   const bool skip_empty_lines = (1 >= discp_lvl);
    655   /* Allow to skip more then one empty line before the request line.
    656      RFC 9112, section 2.2 */
    657   const bool skip_several_empty_lines = (skip_empty_lines && (0 >= discp_lvl));
    658   /* Allow to skip unlimited number of empty lines before the request line.
    659      RFC 9112, section 2.2 */
    660   const bool skip_unlimited_empty_lines =
    661     (skip_empty_lines && (-3 >= discp_lvl));
    662   /* Treat bare LF as the end of the line.
    663      RFC 9112, section 2.2 */
    664   const bool bare_lf_as_crlf = mhd_ALLOW_BARE_LF_AS_CRLF (discp_lvl);
    665   /* Treat tab as whitespace delimiter.
    666      RFC 9112, section 3 */
    667   const bool tab_as_wsp = (0 >= discp_lvl);
    668   /* Treat VT (vertical tab) and FF (form feed) as whitespace delimiters.
    669      RFC 9112, section 3 */
    670   const bool other_wsp_as_wsp = (-1 >= discp_lvl);
    671   /* Treat continuous whitespace block as a single space.
    672      RFC 9112, section 3 */
    673   const bool wsp_blocks = (-1 >= discp_lvl);
    674   /* Parse whitespace in URI, special parsing of the request line.
    675      RFC 9112, section 3.2 */
    676   const bool wsp_in_uri = (0 >= discp_lvl);
    677   /* Keep whitespace in URI, give app URI with whitespace instead of
    678      automatic redirect to fixed URI.
    679      Violates RFC 9112, section 3.2 */
    680   const bool wsp_in_uri_keep = (-2 >= discp_lvl);
    681   /* Keep bare CR character as is.
    682      Violates RFC 9112, section 2.2 */
    683   const bool bare_cr_keep = (wsp_in_uri_keep && (-3 >= discp_lvl));
    684   /* Treat bare CR as space; replace it with space before processing.
    685      RFC 9112, section 2.2 */
    686   const bool bare_cr_as_sp = ((!bare_cr_keep) && (-1 >= discp_lvl));
    687 
    688   mhd_assert (mhd_HTTP_STAGE_INIT == c->stage \
    689               || mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
    690   mhd_assert (NULL == c->rq.method.cstr \
    691               || mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
    692   mhd_assert (mhd_HTTP_METHOD_NO_METHOD == c->rq.http_mthd \
    693               || mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
    694   mhd_assert (mhd_HTTP_METHOD_NO_METHOD == c->rq.http_mthd \
    695               || 0 != c->rq.hdrs.rq_line.proc_pos);
    696 
    697   if (0 == c->read_buffer_offset)
    698   {
    699     mhd_assert (mhd_HTTP_STAGE_INIT == c->stage);
    700     return false; /* No data to process */
    701   }
    702   p = c->rq.hdrs.rq_line.proc_pos;
    703   mhd_assert (p <= c->read_buffer_offset);
    704 
    705   /* Skip empty lines, if any (and if allowed) */
    706   /* See RFC 9112, section 2.2 */
    707   if ((0 == p)
    708       && (skip_empty_lines))
    709   {
    710     /* Skip empty lines before the request line.
    711        See RFC 9112, section 2.2 */
    712     bool is_empty_line;
    713     mhd_assert (mhd_HTTP_STAGE_INIT == c->stage);
    714     mhd_assert (0 == c->rq.method.len);
    715     mhd_assert (NULL == c->rq.method.cstr);
    716     mhd_assert (NULL == c->rq.url);
    717     mhd_assert (0 == c->rq.url_len);
    718     mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt);
    719     mhd_assert (0 == c->rq.req_target_len);
    720     mhd_assert (NULL == c->rq.version);
    721     do
    722     {
    723       is_empty_line = false;
    724       if ('\r' == c->read_buffer[0])
    725       {
    726         if (1 == c->read_buffer_offset)
    727           return false; /* Not enough data yet */
    728         if ('\n' == c->read_buffer[1])
    729         {
    730           is_empty_line = true;
    731           c->read_buffer += 2;
    732           c->read_buffer_size -= 2;
    733           c->read_buffer_offset -= 2;
    734           c->rq.hdrs.rq_line.skipped_empty_lines++;
    735         }
    736       }
    737       else if (('\n' == c->read_buffer[0])
    738                && (bare_lf_as_crlf))
    739       {
    740         is_empty_line = true;
    741         c->read_buffer += 1;
    742         c->read_buffer_size -= 1;
    743         c->read_buffer_offset -= 1;
    744         c->rq.hdrs.rq_line.skipped_empty_lines++;
    745       }
    746       if (is_empty_line)
    747       {
    748         if ((!skip_unlimited_empty_lines)
    749             && (((unsigned int)((skip_several_empty_lines) ?
    750                                 MHD_MAX_EMPTY_LINES_SKIP : 1)) <
    751                 c->rq.hdrs.rq_line.skipped_empty_lines))
    752         {
    753           mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
    754                             "Too many meaningless extra empty lines " \
    755                             "received before the request.");
    756           return true; /* Process connection closure */
    757         }
    758         if (0 == c->read_buffer_offset)
    759           return false;  /* No more data to process */
    760       }
    761     } while (is_empty_line);
    762   }
    763   /* All empty lines are skipped */
    764 
    765   c->stage = mhd_HTTP_STAGE_REQ_LINE_RECEIVING;
    766   /* Read and parse the request line */
    767   mhd_assert (1 <= c->read_buffer_offset);
    768 
    769   while (p < c->read_buffer_offset)
    770   {
    771     char *const restrict read_buffer = c->read_buffer;
    772     const char chr = read_buffer[p];
    773     bool end_of_line;
    774     /*
    775        The processing logic is different depending on the configured strictness:
    776 
    777        When whitespace BLOCKS are NOT ALLOWED, the end of the whitespace is
    778        processed BEFORE processing of the current character.
    779        When whitespace BLOCKS are ALLOWED, the end of the whitespace is
    780        processed AFTER processing of the current character.
    781 
    782        When space char in the URI is ALLOWED, the delimiter between the URI and
    783        the HTTP version string is processed only at the END of the line.
    784        When space in the URI is NOT ALLOWED, the delimiter between the URI and
    785        the HTTP version string is processed as soon as the FIRST whitespace is
    786        found after URI start.
    787      */
    788 
    789     end_of_line = false;
    790 
    791     mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) \
    792                 || (c->rq.hdrs.rq_line.last_ws_end > \
    793                     c->rq.hdrs.rq_line.last_ws_start));
    794     mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_start) \
    795                 || (0 != c->rq.hdrs.rq_line.last_ws_end));
    796 
    797     /* Check for the end of the line */
    798     if ('\r' == chr)
    799     {
    800       if (p + 1 == c->read_buffer_offset)
    801       {
    802         c->rq.hdrs.rq_line.proc_pos = p;
    803         return false; /* Not enough data yet */
    804       }
    805       else if ('\n' == read_buffer[p + 1])
    806         end_of_line = true;
    807       else
    808       {
    809         /* Bare CR alone */
    810         /* Must be rejected or replaced with space char.
    811            See RFC 9112, section 2.2 */
    812         if (bare_cr_as_sp)
    813         {
    814           read_buffer[p] = ' ';
    815           c->rq.num_cr_sp_replaced++;
    816           continue; /* Re-start processing of the current character */
    817         }
    818         else if (!bare_cr_keep)
    819         {
    820           /* A quick simple check whether this line looks like an HTTP request */
    821           if ((mhd_HTTP_METHOD_GET <= c->rq.http_mthd)
    822               && (mhd_HTTP_METHOD_DELETE >= c->rq.http_mthd))
    823           {
    824             mhd_RESPOND_WITH_ERROR_STATIC (c,
    825                                            MHD_HTTP_STATUS_BAD_REQUEST,
    826                                            ERR_RSP_BARE_CR_IN_HEADER);
    827           }
    828           else
    829             mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
    830                               "Bare CR characters are not allowed " \
    831                               "in the request line.");
    832 
    833           return true; /* Error in the request */
    834         }
    835       }
    836     }
    837     else if ('\n' == chr)
    838     {
    839       /* Bare LF may be recognised as a line delimiter.
    840          See RFC 9112, section 2.2 */
    841       if (bare_lf_as_crlf)
    842         end_of_line = true;
    843       else
    844       {
    845         /* While RFC does not enforce error for bare LF character,
    846            if this char is not treated as a line delimiter, it should be
    847            rejected to avoid any security weakness due to request smuggling. */
    848         /* A quick simple check whether this line looks like an HTTP request */
    849         if ((mhd_HTTP_METHOD_GET <= c->rq.http_mthd)
    850             && (mhd_HTTP_METHOD_DELETE >= c->rq.http_mthd))
    851         {
    852           mhd_RESPOND_WITH_ERROR_STATIC (c,
    853                                          MHD_HTTP_STATUS_BAD_REQUEST,
    854                                          ERR_RSP_BARE_LF_IN_HEADER);
    855         }
    856         else
    857           mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
    858                             "Bare LF characters are not allowed " \
    859                             "in the request line.");
    860         return true; /* Error in the request */
    861       }
    862     }
    863 
    864     if (end_of_line)
    865     {
    866       /* Handle the end of the request line */
    867 
    868       if (NULL != c->rq.method.cstr)
    869       {
    870         if (wsp_in_uri)
    871         {
    872           /* The end of the URI and the start of the HTTP version string
    873              should be determined now. */
    874           mhd_assert (NULL == c->rq.version);
    875           mhd_assert (0 == c->rq.req_target_len);
    876           if (0 != c->rq.hdrs.rq_line.last_ws_end)
    877           {
    878             /* Determine the end and the length of the URI */
    879             if (NULL != c->rq.hdrs.rq_line.rq_tgt)
    880             {
    881               read_buffer[c->rq.hdrs.rq_line.last_ws_start] = 0;  /* Zero terminate the URI */
    882               c->rq.req_target_len =
    883                 c->rq.hdrs.rq_line.last_ws_start
    884                 - (size_t)(c->rq.hdrs.rq_line.rq_tgt - read_buffer);
    885             }
    886             else if ((c->rq.hdrs.rq_line.last_ws_start + 1 <
    887                       c->rq.hdrs.rq_line.last_ws_end)
    888                      && (HTTP_VER_LEN == (p - c->rq.hdrs.rq_line.last_ws_end)))
    889             {
    890               /* Found only HTTP method and HTTP version and more than one
    891                  whitespace between them. Assume zero-length URI. */
    892               mhd_assert (wsp_blocks);
    893               c->rq.hdrs.rq_line.last_ws_start++;
    894               read_buffer[c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */
    895               c->rq.hdrs.rq_line.rq_tgt =
    896                 read_buffer + c->rq.hdrs.rq_line.last_ws_start;
    897               c->rq.req_target_len = 0;
    898               c->rq.hdrs.rq_line.num_ws_in_uri = 0;
    899               c->rq.hdrs.rq_line.rq_tgt_qmark = NULL;
    900             }
    901             /* Determine the start of the HTTP version string */
    902             if (NULL != c->rq.hdrs.rq_line.rq_tgt)
    903             {
    904               c->rq.version = read_buffer + c->rq.hdrs.rq_line.last_ws_end;
    905             }
    906           }
    907         }
    908         else
    909         {
    910           /* The end of the URI and the start of the HTTP version string
    911              should be already known. */
    912           if ((NULL == c->rq.version)
    913               && (NULL != c->rq.hdrs.rq_line.rq_tgt)
    914               && (HTTP_VER_LEN == p - (size_t)(c->rq.hdrs.rq_line.rq_tgt
    915                                                - read_buffer))
    916               && (0 != read_buffer[(size_t)
    917                                    (c->rq.hdrs.rq_line.rq_tgt
    918                                     - read_buffer) - 1]))
    919           {
    920             /* Found only HTTP method and HTTP version and more than one
    921                whitespace between them. Assume zero-length URI. */
    922             size_t uri_pos;
    923             mhd_assert (wsp_blocks);
    924             mhd_assert (0 == c->rq.req_target_len);
    925             uri_pos = (size_t)(c->rq.hdrs.rq_line.rq_tgt - read_buffer) - 1;
    926             mhd_assert (uri_pos < p);
    927             c->rq.version = c->rq.hdrs.rq_line.rq_tgt;
    928             read_buffer[uri_pos] = 0;  /* Zero terminate the URI */
    929             c->rq.hdrs.rq_line.rq_tgt = read_buffer + uri_pos;
    930             c->rq.req_target_len = 0;
    931             c->rq.hdrs.rq_line.num_ws_in_uri = 0;
    932             c->rq.hdrs.rq_line.rq_tgt_qmark = NULL;
    933           }
    934         }
    935 
    936         if (NULL != c->rq.version)
    937         {
    938           mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
    939           if (!process_http_version (c,
    940                                      p - (size_t)(c->rq.version
    941                                                   - read_buffer),
    942                                      c->rq.version))
    943           {
    944             mhd_assert (mhd_HTTP_STAGE_REQ_LINE_RECEIVING < c->stage);
    945             return true; /* Unsupported / broken HTTP version */
    946           }
    947           read_buffer[p] = 0; /* Zero terminate the HTTP version strings */
    948           if ('\r' == chr)
    949           {
    950             p++; /* Consume CR */
    951             mhd_assert (p < c->read_buffer_offset); /* The next character has been already checked */
    952           }
    953           p++; /* Consume LF */
    954           c->read_buffer += p;
    955           c->read_buffer_size -= p;
    956           c->read_buffer_offset -= p;
    957           mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \
    958                       c->rq.req_target_len);
    959           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) \
    960                       || (0 != c->rq.req_target_len));
    961           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) \
    962                       || ((size_t)(c->rq.hdrs.rq_line.rq_tgt_qmark \
    963                                    - c->rq.hdrs.rq_line.rq_tgt) < \
    964                           c->rq.req_target_len));
    965           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) \
    966                       || (c->rq.hdrs.rq_line.rq_tgt_qmark >= \
    967                           c->rq.hdrs.rq_line.rq_tgt));
    968           return true; /* The request line is successfully parsed */
    969         }
    970       }
    971       /* Error in the request line */
    972 
    973       /* A quick simple check whether this line looks like an HTTP request */
    974       if ((mhd_HTTP_METHOD_GET <= c->rq.http_mthd)
    975           && (mhd_HTTP_METHOD_DELETE >= c->rq.http_mthd))
    976       {
    977         mhd_RESPOND_WITH_ERROR_STATIC (c,
    978                                        MHD_HTTP_STATUS_BAD_REQUEST,
    979                                        ERR_RSP_REQUEST_MALFORMED);
    980       }
    981       else
    982         mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
    983                           "The request line is malformed.");
    984 
    985       return true;
    986     }
    987 
    988     /* Process possible end of the previously found whitespace delimiter */
    989     if ((!wsp_blocks)
    990         && (p == c->rq.hdrs.rq_line.last_ws_end)
    991         && (0 != c->rq.hdrs.rq_line.last_ws_end))
    992     {
    993       /* Previous character was a whitespace char and whitespace blocks
    994          are not allowed. */
    995       /* The current position is the next character after
    996          a whitespace delimiter */
    997       if (NULL == c->rq.hdrs.rq_line.rq_tgt)
    998       {
    999         /* The current position is the start of the URI */
   1000         mhd_assert (0 == c->rq.req_target_len);
   1001         mhd_assert (NULL == c->rq.version);
   1002         c->rq.hdrs.rq_line.rq_tgt = read_buffer + p;
   1003         /* Reset the whitespace marker */
   1004         c->rq.hdrs.rq_line.last_ws_start = 0;
   1005         c->rq.hdrs.rq_line.last_ws_end = 0;
   1006       }
   1007       else
   1008       {
   1009         /* It was a whitespace after the start of the URI */
   1010         if (!wsp_in_uri)
   1011         {
   1012           mhd_assert ((0 != c->rq.req_target_len) \
   1013                       || (c->rq.hdrs.rq_line.rq_tgt + 1 == read_buffer + p));
   1014           mhd_assert (NULL == c->rq.version); /* Too many whitespaces? This error is handled at whitespace start */
   1015           c->rq.version = read_buffer + p;
   1016           /* Reset the whitespace marker */
   1017           c->rq.hdrs.rq_line.last_ws_start = 0;
   1018           c->rq.hdrs.rq_line.last_ws_end = 0;
   1019         }
   1020       }
   1021     }
   1022 
   1023     /* Process the current character.
   1024        Is it not the end of the line.  */
   1025     if ((' ' == chr)
   1026         || (('\t' == chr) && (tab_as_wsp))
   1027         || ((other_wsp_as_wsp) && ((0xb == chr) || (0xc == chr))))
   1028     {
   1029       /* A whitespace character */
   1030       if ((0 == c->rq.hdrs.rq_line.last_ws_end)
   1031           || (p != c->rq.hdrs.rq_line.last_ws_end)
   1032           || (!wsp_blocks))
   1033       {
   1034         /* Found first whitespace char of the new whitespace block */
   1035         if (NULL == c->rq.method.cstr)
   1036         {
   1037           /* Found the end of the HTTP method string */
   1038           mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_start);
   1039           mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_end);
   1040           mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt);
   1041           mhd_assert (0 == c->rq.req_target_len);
   1042           mhd_assert (NULL == c->rq.version);
   1043           if (0 == p)
   1044           {
   1045             mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
   1046                               "The request line starts with a whitespace.");
   1047             return true; /* Error in the request */
   1048           }
   1049           read_buffer[p] = 0; /* Zero-terminate the request method string */
   1050           c->rq.method.cstr = read_buffer;
   1051           c->rq.method.len = p;
   1052           parse_http_std_method (c);
   1053         }
   1054         else
   1055         {
   1056           /* A whitespace after the start of the URI */
   1057           if (!wsp_in_uri)
   1058           {
   1059             /* Whitespace in URI is not allowed to be parsed */
   1060             if (NULL == c->rq.version)
   1061             {
   1062               mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   1063               /* This is a delimiter between URI and HTTP version string */
   1064               read_buffer[p] = 0; /* Zero-terminate request URI string */
   1065               mhd_assert (((size_t)(c->rq.hdrs.rq_line.rq_tgt   \
   1066                                     - read_buffer)) <= p);
   1067               c->rq.req_target_len =
   1068                 p - (size_t)(c->rq.hdrs.rq_line.rq_tgt - read_buffer);
   1069             }
   1070             else
   1071             {
   1072               /* This is a delimiter AFTER version string */
   1073 
   1074               /* A quick simple check whether this line looks like an HTTP request */
   1075               if ((mhd_HTTP_METHOD_GET <= c->rq.http_mthd)
   1076                   && (mhd_HTTP_METHOD_DELETE >= c->rq.http_mthd))
   1077               {
   1078                 mhd_RESPOND_WITH_ERROR_STATIC (c,
   1079                                                MHD_HTTP_STATUS_BAD_REQUEST,
   1080                                                ERR_RSP_RQ_LINE_TOO_MANY_WSP);
   1081               }
   1082               else
   1083                 mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
   1084                                   "The request line has more than "
   1085                                   "two whitespaces.");
   1086               return true; /* Error in the request */
   1087             }
   1088           }
   1089           else
   1090           {
   1091             /* Whitespace in URI is allowed to be parsed */
   1092             if (0 != c->rq.hdrs.rq_line.last_ws_end)
   1093             {
   1094               /* The whitespace after the start of the URI has been found already */
   1095               c->rq.hdrs.rq_line.num_ws_in_uri +=
   1096                 c->rq.hdrs.rq_line.last_ws_end
   1097                 - c->rq.hdrs.rq_line.last_ws_start;
   1098             }
   1099           }
   1100         }
   1101         c->rq.hdrs.rq_line.last_ws_start = p;
   1102         c->rq.hdrs.rq_line.last_ws_end = p + 1; /* Will be updated on the next char parsing */
   1103       }
   1104       else
   1105       {
   1106         /* Continuation of the whitespace block */
   1107         mhd_assert (0 != c->rq.hdrs.rq_line.last_ws_end);
   1108         mhd_assert (0 != p);
   1109         c->rq.hdrs.rq_line.last_ws_end = p + 1;
   1110       }
   1111     }
   1112     else
   1113     {
   1114       /* Non-whitespace char, not the end of the line */
   1115       mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) \
   1116                   || (c->rq.hdrs.rq_line.last_ws_end == p) \
   1117                   || wsp_in_uri);
   1118 
   1119       if ((p == c->rq.hdrs.rq_line.last_ws_end)
   1120           && (0 != c->rq.hdrs.rq_line.last_ws_end)
   1121           && (wsp_blocks))
   1122       {
   1123         /* The end of the whitespace block */
   1124         if (NULL == c->rq.hdrs.rq_line.rq_tgt)
   1125         {
   1126           /* This is the first character of the URI */
   1127           mhd_assert (0 == c->rq.req_target_len);
   1128           mhd_assert (NULL == c->rq.version);
   1129           c->rq.hdrs.rq_line.rq_tgt = read_buffer + p;
   1130           /* Reset the whitespace marker */
   1131           c->rq.hdrs.rq_line.last_ws_start = 0;
   1132           c->rq.hdrs.rq_line.last_ws_end = 0;
   1133         }
   1134         else
   1135         {
   1136           if (!wsp_in_uri)
   1137           {
   1138             /* This is the first character of the HTTP version */
   1139             mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   1140             mhd_assert ((0 != c->rq.req_target_len) \
   1141                         || (c->rq.hdrs.rq_line.rq_tgt + 1 == read_buffer + p));
   1142             mhd_assert (NULL == c->rq.version); /* Handled at whitespace start */
   1143             c->rq.version = read_buffer + p;
   1144             /* Reset the whitespace marker */
   1145             c->rq.hdrs.rq_line.last_ws_start = 0;
   1146             c->rq.hdrs.rq_line.last_ws_end = 0;
   1147           }
   1148         }
   1149       }
   1150 
   1151       /* Handle other special characters */
   1152       if ('?' == chr)
   1153       {
   1154         if ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark)
   1155             && (NULL != c->rq.hdrs.rq_line.rq_tgt))
   1156         {
   1157           c->rq.hdrs.rq_line.rq_tgt_qmark = read_buffer + p;
   1158         }
   1159       }
   1160       else if ((0xb == chr) || (0xc == chr))
   1161       {
   1162         /* VT or LF characters */
   1163         mhd_assert (!other_wsp_as_wsp);
   1164         if ((NULL != c->rq.hdrs.rq_line.rq_tgt)
   1165             && (NULL == c->rq.version)
   1166             && (wsp_in_uri))
   1167         {
   1168           c->rq.hdrs.rq_line.num_ws_in_uri++;
   1169         }
   1170         else
   1171         {
   1172           mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
   1173                             "Invalid character is in the request line.");
   1174           return true; /* Error in the request */
   1175         }
   1176       }
   1177       else if (0 == chr)
   1178       {
   1179         /* NUL character */
   1180         mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN,
   1181                           "The NUL character is in the request line.");
   1182         return true; /* Error in the request */
   1183       }
   1184     }
   1185 
   1186     p++;
   1187   }
   1188 
   1189   c->rq.hdrs.rq_line.proc_pos = p;
   1190   return false; /* Not enough data yet */
   1191 }
   1192 
   1193 
   1194 /**
   1195  * Callback for iterating over GET parameters
   1196  * @param cls the iterator metadata
   1197  * @param name the name of the parameter
   1198  * @param value the value of the parameter
   1199  * @return bool to continue iterations,
   1200  *         false to stop the iteration
   1201  */
   1202 static MHD_FN_PAR_NONNULL_ (2) MHD_FN_PAR_NONNULL_ (3) bool
   1203 request_add_get_arg (void *restrict cls,
   1204                      const struct MHD_String *restrict name,
   1205                      const struct MHD_StringNullable *restrict value)
   1206 {
   1207   struct MHD_Stream *s = (struct MHD_Stream *)cls;
   1208 
   1209   return mhd_stream_add_field_nullable (s, MHD_VK_URI_QUERY_PARAM, name, value);
   1210 }
   1211 
   1212 
   1213 MHD_INTERNAL
   1214 MHD_FN_PAR_NONNULL_ (2) MHD_FN_PAR_CSTR_ (2)
   1215 MHD_FN_PAR_INOUT_SIZE_ (2, 1) bool
   1216 // TODO: detect and report errors
   1217 mhd_parse_uri_args (size_t args_len,
   1218                     char *restrict args,
   1219                     mhd_GetArgumentInter cb,
   1220                     void *restrict cls)
   1221 {
   1222   size_t i;
   1223 
   1224   mhd_assert (args_len < (size_t)(args_len + 1));  /* Does not work when args_len == SIZE_MAX */
   1225 
   1226   for (i = 0; i < args_len; ++i) /* Looking for names of the parameters */
   1227   {
   1228     size_t name_start;
   1229     size_t name_len;
   1230     size_t value_start;
   1231     size_t value_len;
   1232     struct MHD_String name;
   1233     struct MHD_StringNullable value;
   1234 
   1235     /* Found start of the name */
   1236 
   1237     value_start = 0;
   1238     for (name_start = i; i < args_len; ++i) /* Processing parameter */
   1239     {
   1240       if ('+' == args[i])
   1241         args[i] = ' ';
   1242       else if ('=' == args[i])
   1243       {
   1244         /* Found start of the value */
   1245         for (value_start = ++i; i < args_len; ++i) /* Processing parameter value */
   1246         {
   1247           if ('+' == args[i])
   1248             args[i] = ' ';
   1249           else if ('&' == args[i]) /* delimiter for the next parameter */
   1250             break; /* Next parameter */
   1251         }
   1252         break; /* End of the current parameter */
   1253       }
   1254       else if ('&' == args[i])
   1255         break; /* End of the name of the parameter without a value */
   1256     }
   1257 
   1258     /* PCT-decode, zero-terminate and store the found parameter */
   1259 
   1260     if (0 != value_start) /* Value cannot start at zero position */
   1261     { /* Name with value */
   1262       mhd_assert (name_start + 1 <= value_start);
   1263       name_len = value_start - name_start - 1;
   1264 
   1265       value_len =
   1266         mhd_str_pct_decode_lenient_n (args + value_start, i - value_start,
   1267                                       args + value_start, i - value_start,
   1268                                       NULL); // TODO: add support for broken encoding detection
   1269       if (value_start + value_len < args_len)
   1270         args[value_start + value_len] = 0;
   1271       value.cstr = args + value_start;
   1272       value.len = value_len;
   1273     }
   1274     else
   1275     { /* Name without value */
   1276       name_len = i - name_start;
   1277 
   1278       value.cstr = NULL;
   1279       value.len = 0;
   1280     }
   1281     name_len = mhd_str_pct_decode_lenient_n (args + name_start, name_len,
   1282                                              args + name_start, name_len,
   1283                                              NULL); // TODO: add support for broken encoding detection
   1284     if (name_start + name_len < args_len)
   1285       args[name_start + name_len] = 0;
   1286     name.cstr = args + name_start;
   1287     name.len = name_len;
   1288     if (!cb (cls, &name, &value))
   1289       return false;
   1290   }
   1291   return true;
   1292 }
   1293 
   1294 
   1295 /**
   1296  * Process request-target string, form URI and URI parameters
   1297  * @param c the connection to process
   1298  * @return true if request-target successfully processed,
   1299  *         false if error encountered
   1300  */
   1301 static MHD_FN_PAR_NONNULL_ALL_ bool
   1302 process_request_target (struct MHD_Connection *c)
   1303 {
   1304   size_t params_len;
   1305 
   1306   mhd_assert (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
   1307   mhd_assert (NULL == c->rq.url);
   1308   mhd_assert (0 == c->rq.url_len);
   1309   mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   1310   mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) \
   1311               || (c->rq.hdrs.rq_line.rq_tgt <=
   1312                   c->rq.hdrs.rq_line.rq_tgt_qmark));
   1313   mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) \
   1314               || (c->rq.req_target_len > \
   1315                   (size_t)(c->rq.hdrs.rq_line.rq_tgt_qmark \
   1316                            - c->rq.hdrs.rq_line.rq_tgt)));
   1317 
   1318   /* Log callback before the request-target is modified/decoded */
   1319   if (NULL != c->daemon->req_cfg.uri_cb.cb)
   1320   {
   1321     struct MHD_EarlyUriCbData req_data;
   1322     req_data.request = &(c->rq);
   1323     req_data.full_uri.cstr = c->rq.hdrs.rq_line.rq_tgt;
   1324     req_data.full_uri.len = c->rq.req_target_len;
   1325     c->rq.app_aware = true;
   1326     c->daemon->req_cfg.uri_cb.cb (c->daemon->req_cfg.uri_cb.cls,
   1327                                   &req_data,
   1328                                   &(c->rq.app_context));
   1329   }
   1330 
   1331   if (NULL != c->rq.hdrs.rq_line.rq_tgt_qmark)
   1332   {
   1333     params_len =
   1334       c->rq.req_target_len
   1335       - (size_t)(c->rq.hdrs.rq_line.rq_tgt_qmark - c->rq.hdrs.rq_line.rq_tgt);
   1336 
   1337     mhd_assert (1 <= params_len);
   1338 
   1339     c->rq.hdrs.rq_line.rq_tgt_qmark[0] = 0; /* Replace '?' with zero termination */
   1340 
   1341     // TODO: support detection of decoding errors
   1342     if (!mhd_parse_uri_args (params_len - 1,
   1343                              c->rq.hdrs.rq_line.rq_tgt_qmark + 1,
   1344                              &request_add_get_arg,
   1345                              &(c->h1_stream)))
   1346     {
   1347       mhd_LOG_MSG (c->daemon, MHD_SC_CONNECTION_POOL_NO_MEM_GET_PARAM,
   1348                    "Not enough memory in the pool to store GET parameter");
   1349 
   1350       mhd_RESPOND_WITH_ERROR_STATIC (
   1351         c,
   1352         mhd_stream_get_no_space_err_status_code (c,
   1353                                                  MHD_PROC_RECV_URI,
   1354                                                  0,
   1355                                                  NULL),
   1356         ERR_RSP_MSG_REQUEST_TOO_BIG);
   1357       mhd_assert (mhd_HTTP_STAGE_REQ_LINE_RECEIVING != c->stage);
   1358       return false;
   1359 
   1360     }
   1361   }
   1362   else
   1363     params_len = 0;
   1364 
   1365   mhd_assert (strlen (c->rq.hdrs.rq_line.rq_tgt) == \
   1366               c->rq.req_target_len - params_len);
   1367 
   1368   /* Finally unescape URI itself */
   1369   // TODO: support detection of decoding errors
   1370   c->rq.url_len =
   1371     mhd_str_pct_decode_lenient_n (c->rq.hdrs.rq_line.rq_tgt,
   1372                                   c->rq.req_target_len - params_len,
   1373                                   c->rq.hdrs.rq_line.rq_tgt,
   1374                                   c->rq.req_target_len - params_len,
   1375                                   NULL);
   1376   c->rq.url = c->rq.hdrs.rq_line.rq_tgt;
   1377 
   1378   return true;
   1379 }
   1380 
   1381 
   1382 #ifndef MHD_MAX_FIXED_URI_LEN
   1383 /**
   1384  * The maximum size of the fixed URI for automatic redirection
   1385  */
   1386 #  define MHD_MAX_FIXED_URI_LEN (64 * 1024)
   1387 #endif /* ! MHD_MAX_FIXED_URI_LEN */
   1388 
   1389 /**
   1390  * Send the automatic redirection to fixed URI when received URI with
   1391  * whitespaces.
   1392  * If URI is too large, close connection with error.
   1393  *
   1394  * @param c the connection to process
   1395  */
   1396 static void
   1397 send_redirect_fixed_rq_target (struct MHD_Connection *restrict c)
   1398 {
   1399   static const char hdr_prefix[] = MHD_HTTP_HEADER_LOCATION ": ";
   1400   static const size_t hdr_prefix_len =
   1401     mhd_SSTR_LEN (MHD_HTTP_HEADER_LOCATION ": ");
   1402   char *hdr_line;
   1403   char *b;
   1404   size_t fixed_uri_len;
   1405   size_t i;
   1406   size_t o;
   1407 
   1408   mhd_assert (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
   1409   mhd_assert (0 != c->rq.hdrs.rq_line.num_ws_in_uri);
   1410   mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \
   1411               c->rq.req_target_len);
   1412   fixed_uri_len = c->rq.req_target_len
   1413                   + 2 * c->rq.hdrs.rq_line.num_ws_in_uri;
   1414   if ((fixed_uri_len + 200 > c->daemon->conns.cfg.mem_pool_size)
   1415       || (fixed_uri_len > MHD_MAX_FIXED_URI_LEN)
   1416       || (NULL ==
   1417           (hdr_line = (char *)malloc (fixed_uri_len + 1 + hdr_prefix_len))))
   1418   {
   1419     mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_CLIENT_HTTP_ERR_ABORT_CONN, \
   1420                       "The request has whitespace character is " \
   1421                       "in the URI and the URI is too large to " \
   1422                       "send automatic redirect to fixed URI.");
   1423     return;
   1424   }
   1425   memcpy (hdr_line, hdr_prefix, hdr_prefix_len);
   1426   b = hdr_line + hdr_prefix_len;
   1427   i = 0;
   1428   o = 0;
   1429 
   1430   do
   1431   {
   1432     const char chr = c->rq.hdrs.rq_line.rq_tgt[i++];
   1433 
   1434     mhd_assert ('\r' != chr); /* Replaced during request line parsing */
   1435     mhd_assert ('\n' != chr); /* Rejected during request line parsing */
   1436     mhd_assert (0 != chr); /* Rejected during request line parsing */
   1437     switch (chr)
   1438     {
   1439     case ' ':
   1440       b[o++] = '%';
   1441       b[o++] = '2';
   1442       b[o++] = '0';
   1443       break;
   1444     case '\t':
   1445       b[o++] = '%';
   1446       b[o++] = '0';
   1447       b[o++] = '9';
   1448       break;
   1449     case 0x0B:   /* VT (vertical tab) */
   1450       b[o++] = '%';
   1451       b[o++] = '0';
   1452       b[o++] = 'B';
   1453       break;
   1454     case 0x0C:   /* FF (form feed) */
   1455       b[o++] = '%';
   1456       b[o++] = '0';
   1457       b[o++] = 'C';
   1458       break;
   1459     default:
   1460       b[o++] = chr;
   1461       break;
   1462     }
   1463   } while (i < c->rq.req_target_len);
   1464   mhd_assert (fixed_uri_len == o);
   1465   b[o] = 0; /* Zero-terminate the result */
   1466 
   1467   mhd_RESPOND_WITH_ERROR_HEADER (c,
   1468                                  MHD_HTTP_STATUS_MOVED_PERMANENTLY,
   1469                                  ERR_RSP_RQ_TARGET_INVALID_CHAR,
   1470                                  o + hdr_prefix_len,
   1471                                  hdr_line);
   1472 
   1473   return;
   1474 }
   1475 
   1476 
   1477 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   1478 mhd_stream_get_request_line (struct MHD_Connection *restrict c)
   1479 {
   1480   const int discp_lvl = c->daemon->req_cfg.strictness;
   1481   /* Parse whitespace in URI, special parsing of the request line */
   1482   const bool wsp_in_uri = (0 >= discp_lvl);
   1483   /* Keep whitespace in URI, give app URI with whitespace instead of
   1484      automatic redirect to fixed URI */
   1485   const bool wsp_in_uri_keep = (-2 >= discp_lvl);
   1486 
   1487   if (!get_request_line_inner (c))
   1488   {
   1489     /* End of the request line has not been found yet */
   1490     mhd_assert ((!wsp_in_uri) || NULL == c->rq.version);
   1491     if ((NULL != c->rq.version)
   1492         && (HTTP_VER_LEN <
   1493             (c->rq.hdrs.rq_line.proc_pos
   1494              - (size_t)(c->rq.version - c->read_buffer))))
   1495     {
   1496       c->rq.http_ver = MHD_HTTP_VERSION_INVALID;
   1497       mhd_RESPOND_WITH_ERROR_STATIC (c,
   1498                                      MHD_HTTP_STATUS_BAD_REQUEST,
   1499                                      ERR_RSP_REQUEST_MALFORMED);
   1500       return true; /* Error in the request */
   1501     }
   1502     return false;
   1503   }
   1504   if (mhd_HTTP_STAGE_REQ_LINE_RECEIVING < c->stage)
   1505     return true; /* Error in the request */
   1506 
   1507   mhd_assert (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage);
   1508   mhd_assert (NULL == c->rq.url);
   1509   mhd_assert (0 == c->rq.url_len);
   1510   mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   1511   if (0 != c->rq.hdrs.rq_line.num_ws_in_uri)
   1512   {
   1513     if (!wsp_in_uri)
   1514     {
   1515       mhd_RESPOND_WITH_ERROR_STATIC (c,
   1516                                      MHD_HTTP_STATUS_BAD_REQUEST,
   1517                                      ERR_RSP_RQ_TARGET_INVALID_CHAR);
   1518       return true; /* Error in the request */
   1519     }
   1520     if (!wsp_in_uri_keep)
   1521     {
   1522       send_redirect_fixed_rq_target (c);
   1523       return true; /* Error in the request */
   1524     }
   1525   }
   1526   if (!process_request_target (c))
   1527     return true; /* Error in processing */
   1528 
   1529   c->stage = mhd_HTTP_STAGE_REQ_LINE_RECEIVED;
   1530   return true;
   1531 }
   1532 
   1533 
   1534 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ void
   1535 mhd_stream_switch_to_rq_headers_proc (struct MHD_Connection *restrict c)
   1536 {
   1537   c->rq.field_lines.start = c->read_buffer;
   1538   mhd_stream_reset_rq_hdr_proc_state (c);
   1539   c->stage = mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING;
   1540 }
   1541 
   1542 
   1543 /**
   1544  * Send error reply when receive buffer space exhausted while receiving or
   1545  * storing the request headers
   1546  * @param c the connection to handle
   1547  * @param add_header the optional pointer to the current header string being
   1548  *                   processed or the header failed to be added.
   1549  *                   Could be not zero-terminated and can contain binary zeros.
   1550  *                   Can be NULL.
   1551  * @param add_header_size the size of the @a add_header
   1552  */
   1553 mhd_static_inline
   1554 MHD_FN_PAR_NONNULL_ (1) MHD_FN_PAR_NONNULL_IF_NONZERO_ (2, 3) void
   1555 handle_req_headers_no_space (struct MHD_Connection *restrict c,
   1556                              const char *restrict add_header,
   1557                              size_t add_header_size)
   1558 {
   1559   unsigned int err_code;
   1560 
   1561   err_code = mhd_stream_get_no_space_err_status_code (c,
   1562                                                       MHD_PROC_RECV_HEADERS,
   1563                                                       add_header_size,
   1564                                                       add_header);
   1565   mhd_RESPOND_WITH_ERROR_STATIC (c,
   1566                                  err_code,
   1567                                  ERR_RSP_REQUEST_HEADER_TOO_BIG);
   1568 }
   1569 
   1570 
   1571 /**
   1572  * Send error reply when receive buffer space exhausted while receiving or
   1573  * storing the request footers (for chunked requests).
   1574  * @param c the connection to handle
   1575  * @param add_footer the optional pointer to the current footer string being
   1576  *                   processed or the footer failed to be added.
   1577  *                   Could be not zero-terminated and can contain binary zeros.
   1578  *                   Can be NULL.
   1579  * @param add_footer_size the size of the @a add_footer
   1580  */
   1581 mhd_static_inline
   1582 MHD_FN_PAR_NONNULL_ (1) MHD_FN_PAR_NONNULL_IF_NONZERO_ (2, 3) void
   1583 handle_req_footers_no_space (struct MHD_Connection *restrict c,
   1584                              const char *restrict add_footer,
   1585                              size_t add_footer_size)
   1586 {
   1587   (void)add_footer;
   1588   (void)add_footer_size;                     /* Unused */
   1589   mhd_assert (c->rq.have_chunked_upload);
   1590 
   1591   /* Footers should be optional */
   1592   mhd_RESPOND_WITH_ERROR_STATIC (
   1593     c,
   1594     MHD_HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE,
   1595     ERR_RSP_REQUEST_FOOTER_TOO_BIG);
   1596 }
   1597 
   1598 
   1599 /**
   1600  * Results of header line reading
   1601  */
   1602 enum MHD_FIXED_ENUM_ mhd_HdrLineReadRes
   1603 {
   1604   /**
   1605    * Not enough data yet
   1606    */
   1607   MHD_HDR_LINE_READING_NEED_MORE_DATA = 0,
   1608   /**
   1609    * New header line has been read
   1610    */
   1611   MHD_HDR_LINE_READING_GOT_HEADER,
   1612   /**
   1613    * Error in header data, error response has been queued
   1614    */
   1615   MHD_HDR_LINE_READING_DATA_ERROR,
   1616   /**
   1617    * Found the end of the request header (end of field lines)
   1618    */
   1619   MHD_HDR_LINE_READING_GOT_END_OF_HEADER
   1620 };
   1621 
   1622 
   1623 /**
   1624  * Find the end of the request header line and make basic header parsing.
   1625  * Handle errors and header folding.
   1626  * @param c the connection to process
   1627  * @param process_footers if true then footers are processed,
   1628  *                        if false then headers are processed
   1629  * @param[out] hdr_name the name of the parsed header (field)
   1630  * @param[out] hdr_value the value of the parsed header (field)
   1631  * @return mhd_HdrLineReadRes value
   1632  */
   1633 static enum mhd_HdrLineReadRes
   1634 get_req_header (struct MHD_Connection *restrict c,
   1635                 bool process_footers,
   1636                 struct MHD_String *restrict hdr_name,
   1637                 struct MHD_String *restrict hdr_value)
   1638 {
   1639   const int discp_lvl = c->daemon->req_cfg.strictness;
   1640   /* Treat bare LF as the end of the line.
   1641      RFC 9112, section 2.2-3
   1642      Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5).
   1643      Bare LF is processed as end of the line or rejected as broken request. */
   1644   const bool bare_lf_as_crlf = mhd_ALLOW_BARE_LF_AS_CRLF (discp_lvl);
   1645   /* Keep bare CR character as is.
   1646      Violates RFC 9112, section 2.2-4 */
   1647   const bool bare_cr_keep = (-3 >= discp_lvl);
   1648   /* Treat bare CR as space; replace it with space before processing.
   1649      RFC 9112, section 2.2-4 */
   1650   const bool bare_cr_as_sp = ((!bare_cr_keep) && (-1 >= discp_lvl));
   1651   /* Treat NUL as space; replace it with space before processing.
   1652      RFC 9110, section 5.5-5 */
   1653   const bool nul_as_sp = (-1 >= discp_lvl);
   1654   /* Allow folded header lines.
   1655      RFC 9112, section 5.2-4 */
   1656   const bool allow_folded = (0 >= discp_lvl);
   1657   /* Do not reject headers with the whitespace at the start of the first line.
   1658      When allowed, the first line with whitespace character at the first
   1659      position is ignored (as well as all possible line foldings of the first
   1660      line).
   1661      RFC 9112, section 2.2-8 */
   1662   const bool allow_wsp_at_start = allow_folded && (-1 >= discp_lvl);
   1663   /* Allow whitespace in header (field) name.
   1664      Violates RFC 9110, section 5.1-2 */
   1665   const bool allow_wsp_in_name = (-2 >= discp_lvl);
   1666   /* Allow zero-length header (field) name.
   1667      Violates RFC 9110, section 5.1-2 */
   1668   const bool allow_empty_name = (-2 >= discp_lvl);
   1669   /* Allow whitespace before colon.
   1670      Violates RFC 9112, section 5.1-2 */
   1671   const bool allow_wsp_before_colon = (-3 >= discp_lvl);
   1672   /* Do not abort the request when header line has no colon, just skip such
   1673      bad lines.
   1674      RFC 9112, section 5-1 */
   1675   const bool allow_line_without_colon = (-2 >= discp_lvl);
   1676 
   1677   size_t p; /**< The position of the currently processed character */
   1678 
   1679   (void)process_footers;  /* Unused parameter in non-debug and no messages */
   1680 
   1681   mhd_assert ((process_footers ? mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   1682                mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) == \
   1683               c->stage);
   1684 
   1685   p = c->rq.hdrs.hdr.proc_pos;
   1686 
   1687   mhd_assert (p <= c->read_buffer_offset);
   1688   while (p < c->read_buffer_offset)
   1689   {
   1690     char *const restrict read_buffer = c->read_buffer;
   1691     const char chr = read_buffer[p];
   1692     bool end_of_line;
   1693 
   1694     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) \
   1695                 || (c->rq.hdrs.hdr.name_len < p));
   1696     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || (0 != p));
   1697     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) \
   1698                 || (c->rq.hdrs.hdr.name_end_found));
   1699     mhd_assert ((0 == c->rq.hdrs.hdr.value_start) \
   1700                 || (c->rq.hdrs.hdr.name_len < c->rq.hdrs.hdr.value_start));
   1701     mhd_assert ((0 == c->rq.hdrs.hdr.value_start) \
   1702                 || (0 != c->rq.hdrs.hdr.name_len));
   1703     mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) \
   1704                 || (0 == c->rq.hdrs.hdr.name_len) \
   1705                 || (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.name_len));
   1706     mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) \
   1707                 || (0 == c->rq.hdrs.hdr.value_start) \
   1708                 || (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start));
   1709 
   1710     /* Check for the end of the line */
   1711     if ('\r' == chr)
   1712     {
   1713       if (0 != p)
   1714       {
   1715         /* Line is not empty, need to check for possible line folding */
   1716         if (p + 2 >= c->read_buffer_offset)
   1717           break; /* Not enough data yet to check for folded line */
   1718       }
   1719       else
   1720       {
   1721         /* Line is empty, no need to check for possible line folding */
   1722         if (p + 2 > c->read_buffer_offset)
   1723           break; /* Not enough data yet to check for the end of the line */
   1724       }
   1725       if ('\n' == read_buffer[p + 1])
   1726         end_of_line = true;
   1727       else
   1728       {
   1729         /* Bare CR alone */
   1730         /* Must be rejected or replaced with space char.
   1731            See RFC 9112, section 2.2-4 */
   1732         if (bare_cr_as_sp)
   1733         {
   1734           read_buffer[p] = ' ';
   1735           c->rq.num_cr_sp_replaced++;
   1736           continue; /* Re-start processing of the current character */
   1737         }
   1738         else if (!bare_cr_keep)
   1739         {
   1740           if (!process_footers)
   1741             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1742                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1743                                            ERR_RSP_BARE_CR_IN_HEADER);
   1744           else
   1745             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1746                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1747                                            ERR_RSP_BARE_CR_IN_FOOTER);
   1748           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1749         }
   1750         end_of_line = false;
   1751       }
   1752     }
   1753     else if ('\n' == chr)
   1754     {
   1755       /* Bare LF may be recognised as a line delimiter.
   1756          See RFC 9112, section 2.2-3 */
   1757       if (bare_lf_as_crlf)
   1758       {
   1759         if (0 != p)
   1760         {
   1761           /* Line is not empty, need to check for possible line folding */
   1762           if (p + 1 >= c->read_buffer_offset)
   1763             break; /* Not enough data yet to check for folded line */
   1764         }
   1765         end_of_line = true;
   1766       }
   1767       else
   1768       {
   1769         if (!process_footers)
   1770           mhd_RESPOND_WITH_ERROR_STATIC (c,
   1771                                          MHD_HTTP_STATUS_BAD_REQUEST,
   1772                                          ERR_RSP_BARE_LF_IN_HEADER);
   1773         else
   1774           mhd_RESPOND_WITH_ERROR_STATIC (c,
   1775                                          MHD_HTTP_STATUS_BAD_REQUEST,
   1776                                          ERR_RSP_BARE_LF_IN_FOOTER);
   1777         return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1778       }
   1779     }
   1780     else
   1781       end_of_line = false;
   1782 
   1783     if (end_of_line)
   1784     {
   1785       /* Handle the end of the line */
   1786       /**
   1787        *  The full length of the line, including CRLF (or bare LF).
   1788        */
   1789       const size_t line_len = p + (('\r' == chr) ? 2 : 1);
   1790       char next_line_char;
   1791       mhd_assert (line_len <= c->read_buffer_offset);
   1792 
   1793       if (0 == p)
   1794       {
   1795         /* Zero-length header line. This is the end of the request header
   1796            section.
   1797            RFC 9112, Section 2.1-1 */
   1798         mhd_assert (!c->rq.hdrs.hdr.starts_with_ws);
   1799         mhd_assert (!c->rq.hdrs.hdr.name_end_found);
   1800         mhd_assert (0 == c->rq.hdrs.hdr.name_len);
   1801         mhd_assert (0 == c->rq.hdrs.hdr.ws_start);
   1802         mhd_assert (0 == c->rq.hdrs.hdr.value_start);
   1803         /* Consume the line with CRLF (or bare LF) */
   1804         c->read_buffer += line_len;
   1805         c->read_buffer_offset -= line_len;
   1806         c->read_buffer_size -= line_len;
   1807         return MHD_HDR_LINE_READING_GOT_END_OF_HEADER;
   1808       }
   1809 
   1810       mhd_assert (line_len < c->read_buffer_offset);
   1811       mhd_assert (0 != line_len);
   1812       mhd_assert ('\n' == read_buffer[line_len - 1]);
   1813       next_line_char = read_buffer[line_len];
   1814       if ((' ' == next_line_char)
   1815           || ('\t' == next_line_char))
   1816       {
   1817         /* Folded line */
   1818         if (!allow_folded)
   1819         {
   1820           if (!process_footers)
   1821             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1822                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1823                                            ERR_RSP_OBS_FOLD);
   1824           else
   1825             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1826                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1827                                            ERR_RSP_OBS_FOLD_FOOTER);
   1828 
   1829           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1830         }
   1831         /* Replace CRLF (or bare LF) character(s) with space characters.
   1832            See RFC 9112, Section 5.2-4 */
   1833         read_buffer[p] = ' ';
   1834         if ('\r' == chr)
   1835           read_buffer[p + 1] = ' ';
   1836         continue; /* Re-start processing of the current character */
   1837       }
   1838       else
   1839       {
   1840         /* It is not a folded line, it's the real end of the non-empty line */
   1841         bool skip_line = false;
   1842         mhd_assert (0 != p);
   1843         if (c->rq.hdrs.hdr.starts_with_ws)
   1844         {
   1845           /* This is the first line and it starts with whitespace. This line
   1846              must be discarded completely.
   1847              See RFC 9112, Section 2.2-8 */
   1848           mhd_assert (allow_wsp_at_start);
   1849 
   1850           mhd_LOG_MSG (c->daemon, MHD_SC_REQ_FIRST_HEADER_LINE_SPACE_PREFIXED,
   1851                        "Whitespace-prefixed first header line " \
   1852                        "has been skipped.");
   1853           skip_line = true;
   1854         }
   1855         else if (!c->rq.hdrs.hdr.name_end_found)
   1856         {
   1857           if (!allow_line_without_colon)
   1858           {
   1859             if (!process_footers)
   1860               mhd_RESPOND_WITH_ERROR_STATIC (c,
   1861                                              MHD_HTTP_STATUS_BAD_REQUEST,
   1862                                              ERR_RSP_HEADER_WITHOUT_COLON);
   1863             else
   1864               mhd_RESPOND_WITH_ERROR_STATIC (c,
   1865                                              MHD_HTTP_STATUS_BAD_REQUEST,
   1866                                              ERR_RSP_FOOTER_WITHOUT_COLON);
   1867 
   1868             return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1869           }
   1870           /* Skip broken line completely */
   1871           c->rq.skipped_broken_lines++;
   1872           skip_line = true;
   1873         }
   1874         if (skip_line)
   1875         {
   1876           /* Skip the entire line */
   1877           c->read_buffer += line_len;
   1878           c->read_buffer_offset -= line_len;
   1879           c->read_buffer_size -= line_len;
   1880           p = 0;
   1881           /* Reset processing state */
   1882           memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr));
   1883           /* Start processing of the next line */
   1884           continue;
   1885         }
   1886         else
   1887         {
   1888           /* This line should be valid header line */
   1889           size_t value_len;
   1890           mhd_assert ((0 != c->rq.hdrs.hdr.name_len) || allow_empty_name);
   1891 
   1892           hdr_name->cstr = read_buffer + 0; /* The name always starts at the first character */
   1893           hdr_name->len = c->rq.hdrs.hdr.name_len;
   1894           mhd_assert (0 == hdr_name->cstr[hdr_name->len]);
   1895 
   1896           if (0 == c->rq.hdrs.hdr.value_start)
   1897           {
   1898             c->rq.hdrs.hdr.value_start = p;
   1899             read_buffer[p] = 0;
   1900             value_len = 0;
   1901           }
   1902           else if (0 != c->rq.hdrs.hdr.ws_start)
   1903           {
   1904             mhd_assert (p > c->rq.hdrs.hdr.ws_start);
   1905             mhd_assert (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start);
   1906             read_buffer[c->rq.hdrs.hdr.ws_start] = 0;
   1907             value_len = c->rq.hdrs.hdr.ws_start - c->rq.hdrs.hdr.value_start;
   1908           }
   1909           else
   1910           {
   1911             mhd_assert (p > c->rq.hdrs.hdr.ws_start);
   1912             read_buffer[p] = 0;
   1913             value_len = p - c->rq.hdrs.hdr.value_start;
   1914           }
   1915           hdr_value->cstr = read_buffer + c->rq.hdrs.hdr.value_start;
   1916           hdr_value->len = value_len;
   1917           mhd_assert (0 == hdr_value->cstr[hdr_value->len]);
   1918           /* Consume the entire line */
   1919           c->read_buffer += line_len;
   1920           c->read_buffer_offset -= line_len;
   1921           c->read_buffer_size -= line_len;
   1922           return MHD_HDR_LINE_READING_GOT_HEADER;
   1923         }
   1924       }
   1925     }
   1926     else if ((' ' == chr) || ('\t' == chr))
   1927     {
   1928       if (0 == p)
   1929       {
   1930         if (!allow_wsp_at_start)
   1931         {
   1932           if (!process_footers)
   1933             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1934                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1935                                            ERR_RSP_WSP_BEFORE_HEADER);
   1936           else
   1937             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1938                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1939                                            ERR_RSP_WSP_BEFORE_FOOTER);
   1940           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1941         }
   1942         c->rq.hdrs.hdr.starts_with_ws = true;
   1943       }
   1944       else if ((!c->rq.hdrs.hdr.name_end_found)
   1945                && (!c->rq.hdrs.hdr.starts_with_ws))
   1946       {
   1947         /* Whitespace in header name / between header name and colon */
   1948         if (allow_wsp_in_name || allow_wsp_before_colon)
   1949         {
   1950           if (0 == c->rq.hdrs.hdr.ws_start)
   1951             c->rq.hdrs.hdr.ws_start = p;
   1952         }
   1953         else
   1954         {
   1955           if (!process_footers)
   1956             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1957                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1958                                            ERR_RSP_WSP_IN_HEADER_NAME);
   1959           else
   1960             mhd_RESPOND_WITH_ERROR_STATIC (c,
   1961                                            MHD_HTTP_STATUS_BAD_REQUEST,
   1962                                            ERR_RSP_WSP_IN_FOOTER_NAME);
   1963 
   1964           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1965         }
   1966       }
   1967       else
   1968       {
   1969         /* Whitespace before/inside/after header (field) value */
   1970         if (0 == c->rq.hdrs.hdr.ws_start)
   1971           c->rq.hdrs.hdr.ws_start = p;
   1972       }
   1973     }
   1974     else if (0 == chr)
   1975     {
   1976       if (!nul_as_sp)
   1977       {
   1978         if (!process_footers)
   1979           mhd_RESPOND_WITH_ERROR_STATIC (c,
   1980                                          MHD_HTTP_STATUS_BAD_REQUEST,
   1981                                          ERR_RSP_INVALID_CHR_IN_HEADER);
   1982         else
   1983           mhd_RESPOND_WITH_ERROR_STATIC (c,
   1984                                          MHD_HTTP_STATUS_BAD_REQUEST,
   1985                                          ERR_RSP_INVALID_CHR_IN_FOOTER);
   1986 
   1987         return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   1988       }
   1989       read_buffer[p] = ' ';
   1990       continue; /* Re-start processing of the current character */
   1991     }
   1992     else
   1993     {
   1994       /* Not a whitespace, not the end of the header line */
   1995       mhd_assert ('\r' != chr);
   1996       mhd_assert ('\n' != chr);
   1997       mhd_assert ('\0' != chr);
   1998       if ((!c->rq.hdrs.hdr.name_end_found)
   1999           && (!c->rq.hdrs.hdr.starts_with_ws))
   2000       {
   2001         /* Processing the header (field) name */
   2002         if (':' == chr)
   2003         {
   2004           if (0 == c->rq.hdrs.hdr.ws_start)
   2005             c->rq.hdrs.hdr.name_len = p;
   2006           else
   2007           {
   2008             mhd_assert (allow_wsp_in_name || allow_wsp_before_colon);
   2009             if (!allow_wsp_before_colon)
   2010             {
   2011               if (!process_footers)
   2012                 mhd_RESPOND_WITH_ERROR_STATIC (c,
   2013                                                MHD_HTTP_STATUS_BAD_REQUEST,
   2014                                                ERR_RSP_WSP_IN_HEADER_NAME);
   2015               else
   2016                 mhd_RESPOND_WITH_ERROR_STATIC (c,
   2017                                                MHD_HTTP_STATUS_BAD_REQUEST,
   2018                                                ERR_RSP_WSP_IN_FOOTER_NAME);
   2019               return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   2020             }
   2021             c->rq.hdrs.hdr.name_len = c->rq.hdrs.hdr.ws_start;
   2022 #ifndef MHD_FAVOR_SMALL_CODE
   2023             c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   2024 #endif /* ! MHD_FAVOR_SMALL_CODE */
   2025           }
   2026           if ((0 == c->rq.hdrs.hdr.name_len) && !allow_empty_name)
   2027           {
   2028             if (!process_footers)
   2029               mhd_RESPOND_WITH_ERROR_STATIC (c,
   2030                                              MHD_HTTP_STATUS_BAD_REQUEST,
   2031                                              ERR_RSP_EMPTY_HEADER_NAME);
   2032             else
   2033               mhd_RESPOND_WITH_ERROR_STATIC (c,
   2034                                              MHD_HTTP_STATUS_BAD_REQUEST,
   2035                                              ERR_RSP_EMPTY_FOOTER_NAME);
   2036             return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   2037           }
   2038           c->rq.hdrs.hdr.name_end_found = true;
   2039           read_buffer[c->rq.hdrs.hdr.name_len] = 0; /* Zero-terminate the name */
   2040         }
   2041         else
   2042         {
   2043           if (0 != c->rq.hdrs.hdr.ws_start)
   2044           {
   2045             /* End of the whitespace in header (field) name */
   2046             mhd_assert (allow_wsp_in_name || allow_wsp_before_colon);
   2047             if (!allow_wsp_in_name)
   2048             {
   2049               if (!process_footers)
   2050                 mhd_RESPOND_WITH_ERROR_STATIC (c,
   2051                                                MHD_HTTP_STATUS_BAD_REQUEST,
   2052                                                ERR_RSP_WSP_IN_HEADER_NAME);
   2053               else
   2054                 mhd_RESPOND_WITH_ERROR_STATIC (c,
   2055                                                MHD_HTTP_STATUS_BAD_REQUEST,
   2056                                                ERR_RSP_WSP_IN_FOOTER_NAME);
   2057 
   2058               return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   2059             }
   2060 #ifndef MHD_FAVOR_SMALL_CODE
   2061             c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   2062 #endif /* ! MHD_FAVOR_SMALL_CODE */
   2063           }
   2064         }
   2065       }
   2066       else
   2067       {
   2068         /* Processing the header (field) value */
   2069         if (0 == c->rq.hdrs.hdr.value_start)
   2070           c->rq.hdrs.hdr.value_start = p;
   2071 #ifndef MHD_FAVOR_SMALL_CODE
   2072         c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   2073 #endif /* ! MHD_FAVOR_SMALL_CODE */
   2074       }
   2075 #ifdef MHD_FAVOR_SMALL_CODE
   2076       c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   2077 #endif /* MHD_FAVOR_SMALL_CODE */
   2078     }
   2079     p++;
   2080   }
   2081   c->rq.hdrs.hdr.proc_pos = p;
   2082   return MHD_HDR_LINE_READING_NEED_MORE_DATA; /* Not enough data yet */
   2083 }
   2084 
   2085 
   2086 /**
   2087  * Reset request header processing state.
   2088  *
   2089  * This function resets the processing state before processing the next header
   2090  * (or footer) line.
   2091  * @param c the connection to process
   2092  */
   2093 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ void
   2094 mhd_stream_reset_rq_hdr_proc_state (struct MHD_Connection *c)
   2095 {
   2096   memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr));
   2097 }
   2098 
   2099 
   2100 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   2101 mhd_stream_get_request_headers (struct MHD_Connection *restrict c,
   2102                                 bool process_footers)
   2103 {
   2104   do
   2105   {
   2106     struct MHD_String hdr_name;
   2107     struct MHD_String hdr_value;
   2108     enum mhd_HdrLineReadRes res;
   2109 
   2110     mhd_assert ((process_footers ? mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   2111                  mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) == \
   2112                 c->stage);
   2113 
   2114 #ifndef NDEBUG
   2115     hdr_name.cstr = NULL;
   2116     hdr_value.cstr = NULL;
   2117 #endif /* ! NDEBUG */
   2118     res = get_req_header (c, process_footers, &hdr_name, &hdr_value);
   2119     if (MHD_HDR_LINE_READING_GOT_HEADER == res)
   2120     {
   2121       mhd_assert ((process_footers ? mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   2122                    mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) == \
   2123                   c->stage);
   2124       mhd_assert (NULL != hdr_name.cstr);
   2125       mhd_assert (NULL != hdr_value.cstr);
   2126       /* Values must be zero-terminated and must not have binary zeros */
   2127       mhd_assert (strlen (hdr_name.cstr) == hdr_name.len);
   2128       mhd_assert (strlen (hdr_value.cstr) == hdr_value.len);
   2129       /* Values must not have whitespaces at the start or at the end */
   2130       mhd_assert ((hdr_name.len == 0) || (hdr_name.cstr[0] != ' '));
   2131       mhd_assert ((hdr_name.len == 0) || (hdr_name.cstr[0] != '\t'));
   2132       mhd_assert ((hdr_name.len == 0) \
   2133                   || (hdr_name.cstr[hdr_name.len - 1] != ' '));
   2134       mhd_assert ((hdr_name.len == 0) \
   2135                   || (hdr_name.cstr[hdr_name.len - 1] != '\t'));
   2136       mhd_assert ((hdr_value.len == 0) || (hdr_value.cstr[0] != ' '));
   2137       mhd_assert ((hdr_value.len == 0) || (hdr_value.cstr[0] != '\t'));
   2138       mhd_assert ((hdr_value.len == 0) \
   2139                   || (hdr_value.cstr[hdr_value.len - 1] != ' '));
   2140       mhd_assert ((hdr_value.len == 0) \
   2141                   || (hdr_value.cstr[hdr_value.len - 1] != '\t'));
   2142 
   2143       if (!mhd_stream_add_field (&(c->h1_stream),
   2144                                  process_footers ?
   2145                                  MHD_VK_TRAILER : MHD_VK_HEADER,
   2146                                  &hdr_name,
   2147                                  &hdr_value))
   2148       {
   2149         size_t add_element_size;
   2150 
   2151         mhd_assert (hdr_name.cstr < hdr_value.cstr);
   2152 
   2153         if (!process_footers)
   2154           mhd_LOG_MSG (c->daemon, MHD_SC_CONNECTION_POOL_NO_MEM_REQ, \
   2155                        "Failed to allocate memory in the connection memory " \
   2156                        "pool to store header.");
   2157         else
   2158           mhd_LOG_MSG (c->daemon, MHD_SC_CONNECTION_POOL_NO_MEM_REQ, \
   2159                        "Failed to allocate memory in the connection memory " \
   2160                        "pool to store footer.");
   2161 
   2162         add_element_size = hdr_value.len
   2163                            + (size_t)(hdr_value.cstr - hdr_name.cstr);
   2164 
   2165         if (!process_footers)
   2166           handle_req_headers_no_space (c, hdr_name.cstr, add_element_size);
   2167         else
   2168           handle_req_footers_no_space (c, hdr_name.cstr, add_element_size);
   2169 
   2170         mhd_assert (mhd_HTTP_STAGE_FULL_REQ_RECEIVED < c->stage);
   2171         return true;
   2172       }
   2173       /* Reset processing state */
   2174       mhd_stream_reset_rq_hdr_proc_state (c);
   2175       mhd_assert ((process_footers ? mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   2176                    mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) == \
   2177                   c->stage);
   2178       /* Read the next header (field) line */
   2179       continue;
   2180     }
   2181     else if (MHD_HDR_LINE_READING_NEED_MORE_DATA == res)
   2182     {
   2183       mhd_assert ((process_footers ? mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   2184                    mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) == \
   2185                   c->stage);
   2186       return false;
   2187     }
   2188     else if (MHD_HDR_LINE_READING_DATA_ERROR == res)
   2189     {
   2190       mhd_assert ((process_footers ? \
   2191                    mhd_HTTP_STAGE_FOOTERS_RECEIVING : \
   2192                    mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING) < c->stage);
   2193       mhd_assert (c->stop_with_error);
   2194       mhd_assert (c->discard_request);
   2195       return true;
   2196     }
   2197     mhd_assert (MHD_HDR_LINE_READING_GOT_END_OF_HEADER == res);
   2198     break;
   2199   } while (1);
   2200 
   2201   if (1 == c->rq.num_cr_sp_replaced)
   2202   {
   2203     if (!process_footers)
   2204       mhd_LOG_MSG (c->daemon, MHD_SC_REQ_HEADER_CR_REPLACED, \
   2205                    "One bare CR character has been replaced with space " \
   2206                    "in the request line or in the request headers.");
   2207     else
   2208       mhd_LOG_MSG (c->daemon, MHD_SC_REQ_FOOTER_CR_REPLACED, \
   2209                    "One bare CR character has been replaced with space " \
   2210                    "in the request footers.");
   2211   }
   2212   else if (0 != c->rq.num_cr_sp_replaced)
   2213   {
   2214     if (!process_footers)
   2215       mhd_LOG_PRINT (c->daemon, MHD_SC_REQ_HEADER_CR_REPLACED, \
   2216                      mhd_LOG_FMT ("%" PRIuFAST64 " bare CR characters have " \
   2217                                   "been replaced with spaces in the request " \
   2218                                   "line and/or in the request headers."), \
   2219                      (uint_fast64_t)c->rq.num_cr_sp_replaced);
   2220     else
   2221       mhd_LOG_PRINT (c->daemon, MHD_SC_REQ_HEADER_CR_REPLACED, \
   2222                      mhd_LOG_FMT ("%" PRIuFAST64 " bare CR characters have " \
   2223                                   "been replaced with spaces in the request " \
   2224                                   "footers."), \
   2225                      (uint_fast64_t)c->rq.num_cr_sp_replaced);
   2226 
   2227 
   2228   }
   2229   if (1 == c->rq.skipped_broken_lines)
   2230   {
   2231     if (!process_footers)
   2232       mhd_LOG_MSG (c->daemon, MHD_SC_REQ_HEADER_LINE_NO_COLON, \
   2233                    "One header line without colon has been skipped.");
   2234     else
   2235       mhd_LOG_MSG (c->daemon, MHD_SC_REQ_FOOTER_LINE_NO_COLON, \
   2236                    "One footer line without colon has been skipped.");
   2237   }
   2238   else if (0 != c->rq.skipped_broken_lines)
   2239   {
   2240     if (!process_footers)
   2241       mhd_LOG_PRINT (c->daemon, MHD_SC_REQ_HEADER_CR_REPLACED, \
   2242                      mhd_LOG_FMT ("%" PRIu64 " header lines without colons "
   2243                                   "have been skipped."),
   2244                      (uint_fast64_t)c->rq.skipped_broken_lines);
   2245     else
   2246       mhd_LOG_PRINT (c->daemon, MHD_SC_REQ_HEADER_CR_REPLACED, \
   2247                      mhd_LOG_FMT ("%" PRIu64 " footer lines without colons "
   2248                                   "have been skipped."),
   2249                      (uint_fast64_t)c->rq.skipped_broken_lines);
   2250   }
   2251 
   2252   mhd_assert (c->rq.method.cstr < c->read_buffer);
   2253   if (!process_footers)
   2254   {
   2255     c->rq.header_size = (size_t)(c->read_buffer - c->rq.method.cstr);
   2256     mhd_assert (NULL != c->rq.field_lines.start);
   2257     c->rq.field_lines.size =
   2258       (size_t)((c->read_buffer - c->rq.field_lines.start) - 1);
   2259     if ('\r' == *(c->read_buffer - 2))
   2260       c->rq.field_lines.size--;
   2261     c->stage = mhd_HTTP_STAGE_HEADERS_RECEIVED;
   2262 
   2263     if (mhd_BUF_INC_SIZE > c->read_buffer_size)
   2264     {
   2265       /* Try to re-use some of the last bytes of the request header */
   2266       /* Do this only if space in the read buffer is limited AND
   2267          amount of read ahead data is small. */
   2268       /**
   2269        *  The position of the terminating NUL after the last character of
   2270        *  the last header element.
   2271        */
   2272       const char *last_elmnt_end;
   2273       size_t shift_back_size;
   2274       struct mhd_RequestField *header;
   2275       header = mhd_DLINKEDL_GET_LAST (&(c->rq), fields);
   2276       if (NULL != header)
   2277         last_elmnt_end =
   2278           header->field.nv.value.cstr + header->field.nv.value.len;
   2279       else
   2280         last_elmnt_end = c->rq.version + HTTP_VER_LEN;
   2281       mhd_assert ((last_elmnt_end + 1) < c->read_buffer);
   2282       shift_back_size = (size_t)(c->read_buffer - (last_elmnt_end + 1));
   2283       if (0 != c->read_buffer_offset)
   2284         memmove (c->read_buffer - shift_back_size,
   2285                  c->read_buffer,
   2286                  c->read_buffer_offset);
   2287       c->read_buffer -= shift_back_size;
   2288       c->read_buffer_size += shift_back_size;
   2289     }
   2290   }
   2291   else
   2292     c->stage = mhd_HTTP_STAGE_FOOTERS_RECEIVED;
   2293 
   2294   return true;
   2295 }
   2296 
   2297 
   2298 #ifdef MHD_SUPPORT_COOKIES
   2299 
   2300 /**
   2301  * Cookie parsing result
   2302  */
   2303 enum mhd_ParseCookie
   2304 {
   2305   MHD_PARSE_COOKIE_OK_LAX = 2        /**< Cookies parsed, but workarounds used */
   2306   ,
   2307   MHD_PARSE_COOKIE_OK = 1            /**< Success or no cookies in headers */
   2308   ,
   2309   MHD_PARSE_COOKIE_NO_MEMORY = 0     /**< Not enough memory in the pool */
   2310   ,
   2311   MHD_PARSE_COOKIE_MALFORMED = -1    /**< Invalid cookie header */
   2312 };
   2313 
   2314 
   2315 /**
   2316  * Parse the cookies string (see RFC 6265).
   2317  *
   2318  * Try to parse the cookies string even if it is not strictly formed
   2319  * as specified by RFC 6265.
   2320  *
   2321  * @param str_len the size of the @a str, not including mandatory
   2322  *                zero-termination
   2323  * @param str the string to parse, without leading whitespaces
   2324  * @param strictness the protocol strictness
   2325  * @param s the stream to process
   2326  * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
   2327  */
   2328 static MHD_FN_PAR_NONNULL_ALL_
   2329 MHD_FN_PAR_CSTR_ (2)
   2330 MHD_FN_PAR_INOUT_SIZE_ (2, 1) enum mhd_ParseCookie
   2331 parse_cookies_string (const size_t str_len,
   2332                       char *restrict str,
   2333                       enum MHD_ProtocolStrictLevel strictness,
   2334                       struct MHD_Stream *restrict s)
   2335 {
   2336   size_t i;
   2337   bool non_strict;
   2338   /* Skip extra whitespaces and empty cookies */
   2339   const bool allow_wsp_empty = (MHD_PSL_DEFAULT >= strictness);
   2340   /* Allow whitespaces around '=' character */
   2341   const bool wsp_around_eq = (MHD_PSL_EXTRA_PERMISSIVE >= strictness);
   2342   /* Allow whitespaces in quoted cookie value */
   2343   const bool wsp_in_quoted = (MHD_PSL_VERY_PERMISSIVE >= strictness);
   2344   /* Allow tab as space after semicolon between cookies */
   2345   const bool tab_as_sp = (MHD_PSL_DEFAULT >= strictness);
   2346   /* Allow no space after semicolon between cookies */
   2347   const bool allow_no_space = (MHD_PSL_DEFAULT >= strictness);
   2348 
   2349   non_strict = false;
   2350   i = 0;
   2351   while (i < str_len)
   2352   {
   2353     size_t name_start;
   2354     size_t name_len;
   2355     size_t value_start;
   2356     size_t value_len;
   2357     bool val_quoted;
   2358     /* Skip any whitespaces and empty cookies */
   2359     while (' ' == str[i] || '\t' == str[i] || ';' == str[i])
   2360     {
   2361       if (!allow_wsp_empty)
   2362         return MHD_PARSE_COOKIE_MALFORMED;
   2363       non_strict = true;
   2364       i++;
   2365       if (i == str_len)
   2366         return non_strict ? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
   2367     }
   2368     /* 'i' must point to the first char of cookie-name */
   2369     name_start = i;
   2370     /* Find the end of the cookie-name */
   2371     do
   2372     {
   2373       const char l = str[i];
   2374       if (('=' == l) || (' ' == l) || ('\t' == l) || ('"' == l) || (',' == l)
   2375           || (';' == l) || (0 == l))
   2376         break;
   2377     } while (str_len > ++i);
   2378     name_len = i - name_start;
   2379     /* Skip any whitespaces */
   2380     while (str_len > i && (' ' == str[i] || '\t' == str[i]))
   2381     {
   2382       if (!wsp_around_eq)
   2383         return MHD_PARSE_COOKIE_MALFORMED;
   2384       non_strict = true;
   2385       i++;
   2386     }
   2387     if ((str_len == i) || ('=' != str[i]) || (0 == name_len))
   2388       return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie name */
   2389     /* 'i' must point to the '=' char */
   2390     mhd_assert ('=' == str[i]);
   2391     i++;
   2392     /* Skip any whitespaces */
   2393     while (str_len > i && (' ' == str[i] || '\t' == str[i]))
   2394     {
   2395       if (!wsp_around_eq)
   2396         return MHD_PARSE_COOKIE_MALFORMED;
   2397       non_strict = true;
   2398       i++;
   2399     }
   2400     /* 'i' must point to the first char of cookie-value */
   2401     if (str_len == i)
   2402     {
   2403       value_start = 0;
   2404       value_len = 0;
   2405 #  ifndef NDEBUG
   2406       val_quoted = false; /* This assignment used in assert */
   2407 #  endif
   2408     }
   2409     else
   2410     {
   2411       bool valid_cookie;
   2412       val_quoted = ('"' == str[i]);
   2413       if (val_quoted)
   2414         i++;
   2415       value_start = i;
   2416       /* Find the end of the cookie-value */
   2417       while (str_len > i)
   2418       {
   2419         const char l = str[i];
   2420         if ((';' == l) || ('"' == l) || (',' == l) || ('\\' == l) || (0 == l))
   2421           break;
   2422         if ((' ' == l) || ('\t' == l))
   2423         {
   2424           if (!val_quoted)
   2425             break;
   2426           if (!wsp_in_quoted)
   2427             return MHD_PARSE_COOKIE_MALFORMED;
   2428           non_strict = true;
   2429         }
   2430         i++;
   2431       }
   2432       value_len = i - value_start;
   2433       if (val_quoted)
   2434       {
   2435         if ((str_len == i) || ('"' != str[i]))
   2436           return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie value, no closing quote */
   2437         i++;
   2438       }
   2439       /* Skip any whitespaces */
   2440       if ((str_len > i) && ((' ' == str[i]) || ('\t' == str[i])))
   2441       {
   2442         do
   2443         {
   2444           i++;
   2445         } while (str_len > i && (' ' == str[i] || '\t' == str[i]));
   2446         /* Whitespace at the end? */
   2447         if (str_len > i)
   2448         {
   2449           if (!allow_wsp_empty)
   2450             return MHD_PARSE_COOKIE_MALFORMED;
   2451           non_strict = true;
   2452         }
   2453       }
   2454       if (str_len == i)
   2455         valid_cookie = true;
   2456       else if (';' == str[i])
   2457         valid_cookie = true;
   2458       else
   2459         valid_cookie = false;
   2460 
   2461       if (!valid_cookie)
   2462         return MHD_PARSE_COOKIE_MALFORMED; /* Garbage at the end of the cookie value */
   2463     }
   2464 
   2465     mhd_ASSUME (0u != name_len);
   2466     mhd_ASSUME (str_len > name_start + name_len);
   2467     str[name_start + name_len] = '\0';
   2468 
   2469     if (0 != value_len)
   2470     {
   2471       struct MHD_String name;
   2472       struct MHD_String value;
   2473       mhd_ASSUME (str_len >= value_start + value_len);
   2474       name.cstr = str + name_start;
   2475       name.len = name_len;
   2476       if (value_start + value_len < str_len) /* Do not write outside allowed area */
   2477         str[value_start + value_len] = '\0'; /* Zero-terminate the value */
   2478       value.cstr = str + value_start;
   2479       value.len = value_len;
   2480       if (!mhd_stream_add_field (s,
   2481                                  MHD_VK_COOKIE,
   2482                                  &name,
   2483                                  &value))
   2484         return MHD_PARSE_COOKIE_NO_MEMORY;
   2485     }
   2486     else
   2487     {
   2488       struct MHD_String name;
   2489       struct MHD_String value;
   2490       name.cstr = str + name_start;
   2491       name.len = name_len;
   2492       value.cstr = "";
   2493       value.len = 0;
   2494       if (!mhd_stream_add_field (s,
   2495                                  MHD_VK_COOKIE,
   2496                                  &name,
   2497                                  &value))
   2498         return MHD_PARSE_COOKIE_NO_MEMORY;
   2499     }
   2500     if (str_len > i)
   2501     {
   2502       mhd_assert (0 == str[i] || ';' == str[i]);
   2503       mhd_assert (!val_quoted || ';' == str[i]);
   2504       mhd_assert (';' != str[i] || val_quoted || non_strict || 0 == value_len);
   2505       i++;
   2506       if (str_len == i)
   2507       { /* No next cookie after semicolon */
   2508         if (!allow_wsp_empty)
   2509           return MHD_PARSE_COOKIE_MALFORMED;
   2510         non_strict = true;
   2511       }
   2512       else if (' ' != str[i])
   2513       {/* No space after semicolon */
   2514         if (('\t' == str[i]) && tab_as_sp)
   2515           i++;
   2516         else if (!allow_no_space)
   2517           return MHD_PARSE_COOKIE_MALFORMED;
   2518         non_strict = true;
   2519       }
   2520       else
   2521       {
   2522         i++;
   2523         if (str_len == i)
   2524         {
   2525           if (!allow_wsp_empty)
   2526             return MHD_PARSE_COOKIE_MALFORMED;
   2527           non_strict = true;
   2528         }
   2529       }
   2530     }
   2531   }
   2532   return non_strict ? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
   2533 }
   2534 
   2535 
   2536 /**
   2537  * Parse the cookie header (see RFC 6265).
   2538  *
   2539  * @param connection connection to parse header of
   2540  * @param cookie_val the value of the "Cookie:" header
   2541  * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
   2542  */
   2543 static enum mhd_ParseCookie
   2544 parse_cookie_header (struct MHD_Connection *restrict connection,
   2545                      struct MHD_StringNullable *restrict cookie_val)
   2546 {
   2547   char *cpy;
   2548   size_t i;
   2549   enum mhd_ParseCookie parse_res;
   2550   struct mhd_RequestField *const saved_tail =
   2551     connection->rq.fields.last;  // FIXME: a better way?
   2552   const bool allow_partially_correct_cookie =
   2553     (1 >= connection->daemon->req_cfg.strictness);
   2554 
   2555   if (NULL == cookie_val)
   2556     return MHD_PARSE_COOKIE_OK;
   2557   if (0 == cookie_val->len)
   2558     return MHD_PARSE_COOKIE_OK;
   2559 
   2560   cpy = (char *)mhd_stream_alloc_memory (connection,
   2561                                          cookie_val->len + 1);
   2562   if (NULL == cpy)
   2563     parse_res = MHD_PARSE_COOKIE_NO_MEMORY;
   2564   else
   2565   {
   2566     memcpy (cpy,
   2567             cookie_val->cstr,
   2568             cookie_val->len + 1);
   2569     mhd_assert (0 == cpy[cookie_val->len]);
   2570 
   2571     /* Must not have initial whitespaces */
   2572     mhd_assert (' ' != cpy[0]);
   2573     mhd_assert ('\t' != cpy[0]);
   2574 
   2575     i = 0;
   2576     parse_res = parse_cookies_string (cookie_val->len - i,
   2577                                       cpy + i,
   2578                                       connection->daemon->req_cfg.strictness,
   2579                                       &(connection->h1_stream));
   2580   }
   2581 
   2582   switch (parse_res)
   2583   {
   2584   case MHD_PARSE_COOKIE_OK:
   2585     break;
   2586   case MHD_PARSE_COOKIE_OK_LAX:
   2587     if (saved_tail != connection->rq.fields.last)
   2588       mhd_LOG_MSG (connection->daemon, MHD_SC_REQ_COOKIE_PARSED_NOT_COMPLIANT, \
   2589                    "The Cookie header has been parsed, but it is not "
   2590                    "fully compliant with specifications.");
   2591     break;
   2592   case MHD_PARSE_COOKIE_MALFORMED:
   2593     if (saved_tail != connection->rq.fields.last) // FIXME: a better way?
   2594     {
   2595       if (!allow_partially_correct_cookie)
   2596       {
   2597         /* Remove extracted values from partially broken cookie */
   2598         /* Memory remains allocated until the end of the request processing */
   2599         connection->rq.fields.last = saved_tail;  // FIXME: a better way?
   2600         saved_tail->fields.next = NULL;  // FIXME: a better way?
   2601         mhd_LOG_MSG ( \
   2602           connection->daemon, MHD_SC_REQ_COOKIE_IGNORED_NOT_COMPLIANT, \
   2603           "The Cookie header is ignored as it contains malformed data.");
   2604       }
   2605       else
   2606         mhd_LOG_MSG (connection->daemon, MHD_SC_REQ_COOKIE_PARSED_PARTIALLY, \
   2607                      "The Cookie header has been only partially parsed " \
   2608                      "as it contains malformed data.");
   2609     }
   2610     else
   2611       mhd_LOG_MSG (connection->daemon, MHD_SC_REQ_COOKIE_INVALID,
   2612                    "The Cookie header has malformed data.");
   2613     break;
   2614   case MHD_PARSE_COOKIE_NO_MEMORY:
   2615     mhd_LOG_MSG (connection->daemon, MHD_SC_CONNECTION_POOL_NO_MEM_COOKIE,
   2616                  "Not enough memory in the connection pool to "
   2617                  "parse client cookies!\n");
   2618     break;
   2619   default:
   2620     mhd_UNREACHABLE ();
   2621     break;
   2622   }
   2623 
   2624   return parse_res;
   2625 }
   2626 
   2627 
   2628 /**
   2629  * Send error reply when receive buffer space exhausted while receiving or
   2630  * storing the request headers
   2631  * @param c the connection to handle
   2632  */
   2633 mhd_static_inline void
   2634 handle_req_cookie_no_space (struct MHD_Connection *restrict c)
   2635 {
   2636   unsigned int err_code;
   2637 
   2638   err_code = mhd_stream_get_no_space_err_status_code (c,
   2639                                                       MHD_PROC_RECV_COOKIE,
   2640                                                       0,
   2641                                                       NULL);
   2642   mhd_RESPOND_WITH_ERROR_STATIC (c,
   2643                                  err_code,
   2644                                  ERR_RSP_REQUEST_HEADER_TOO_BIG);
   2645 }
   2646 
   2647 
   2648 #endif /* MHD_SUPPORT_COOKIES */
   2649 
   2650 
   2651 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ void
   2652 mhd_stream_parse_request_headers (struct MHD_Connection *restrict c)
   2653 {
   2654   bool has_host;
   2655   bool has_trenc;
   2656   bool has_cntnlen;
   2657   bool has_keepalive;
   2658   struct mhd_RequestField *f;
   2659 
   2660   /* The presence of the request body is indicated by "Content-Length:" or
   2661      "Transfer-Encoding:" request headers.
   2662      Unless one of these two headers is used, the request has no request body.
   2663      See RFC9112, Section 6, paragraph 4. */
   2664   c->rq.have_chunked_upload = false;
   2665   c->rq.cntn.cntn_size = 0;
   2666 
   2667   has_host = false;
   2668   has_trenc = false;
   2669   has_cntnlen = false;
   2670   has_keepalive = true;
   2671 
   2672   for (f = mhd_DLINKEDL_GET_FIRST (&(c->rq), fields);
   2673        NULL != f;
   2674        f = mhd_DLINKEDL_GET_NEXT (f, fields))
   2675   {
   2676     if (MHD_VK_HEADER != f->field.kind)
   2677       continue;
   2678 
   2679     /* "Host:" */
   2680     if (mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_HOST,
   2681                                      f->field.nv.name.cstr,
   2682                                      f->field.nv.name.len))
   2683     {
   2684       if ((has_host)
   2685           && (-3 < c->daemon->req_cfg.strictness))
   2686       {
   2687         mhd_LOG_MSG (c->daemon, MHD_SC_HOST_HEADER_SEVERAL, \
   2688                      "Received request with more than one 'Host' header.");
   2689         mhd_RESPOND_WITH_ERROR_STATIC (c,
   2690                                        MHD_HTTP_STATUS_BAD_REQUEST,
   2691                                        ERR_RSP_REQUEST_HAS_SEVERAL_HOSTS);
   2692         return;
   2693       }
   2694       if ((0u == f->field.nv.value.len)
   2695           && (-3 < c->daemon->req_cfg.strictness))
   2696       {
   2697         mhd_LOG_MSG (c->daemon, MHD_SC_HOST_HEADER_MALFORMED, \
   2698                      "Received request with empty 'Host' header.");
   2699         mhd_RESPOND_WITH_ERROR_STATIC (c,
   2700                                        MHD_HTTP_STATUS_BAD_REQUEST,
   2701                                        ERR_RSP_REQUEST_HAS_MALFORMED_HOST);
   2702         return;
   2703       }
   2704       has_host = true;
   2705       continue;
   2706     }
   2707 
   2708     /* "Content-Length:" */
   2709     if (mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_CONTENT_LENGTH,
   2710                                      f->field.nv.name.cstr,
   2711                                      f->field.nv.name.len))
   2712     {
   2713       size_t num_digits;
   2714       uint_fast64_t cntn_size;
   2715 
   2716       num_digits = mhd_str_to_uint64_n (f->field.nv.value.cstr,
   2717                                         f->field.nv.value.len,
   2718                                         &cntn_size);
   2719       if (((0 == num_digits)
   2720            && (0 != f->field.nv.value.len)
   2721            && ('9' >= f->field.nv.value.cstr[0])
   2722            && ('0' <= f->field.nv.value.cstr[0]))
   2723           || (MHD_SIZE_UNKNOWN == c->rq.cntn.cntn_size))
   2724       {
   2725         mhd_LOG_MSG (c->daemon, MHD_SC_CONTENT_LENGTH_TOO_LARGE, \
   2726                      "Too large value of 'Content-Length' header. " \
   2727                      "Closing connection.");
   2728         mhd_RESPOND_WITH_ERROR_STATIC (c, \
   2729                                        MHD_HTTP_STATUS_CONTENT_TOO_LARGE, \
   2730                                        ERR_RSP_REQUEST_CONTENTLENGTH_TOOLARGE);
   2731         return;
   2732       }
   2733       else if ((f->field.nv.value.len != num_digits)
   2734                || (0 == num_digits))
   2735       {
   2736         mhd_LOG_MSG (c->daemon, MHD_SC_CONTENT_LENGTH_MALFORMED, \
   2737                      "Failed to parse 'Content-Length' header. " \
   2738                      "Closing connection.");
   2739         mhd_RESPOND_WITH_ERROR_STATIC (c, \
   2740                                        MHD_HTTP_STATUS_BAD_REQUEST, \
   2741                                        ERR_RSP_REQUEST_CONTENTLENGTH_MALFORMED);
   2742         return;
   2743       }
   2744 
   2745       if (has_cntnlen)
   2746       {
   2747         bool send_err;
   2748         send_err = false;
   2749         if (c->rq.cntn.cntn_size == cntn_size)
   2750         {
   2751           if (0 < c->daemon->req_cfg.strictness)
   2752           {
   2753             mhd_LOG_MSG (c->daemon, MHD_SC_CONTENT_LENGTH_SEVERAL_SAME, \
   2754                          "Received request with more than one " \
   2755                          "'Content-Length' header with the same value.");
   2756             send_err = true;
   2757           }
   2758         }
   2759         else
   2760         {
   2761           mhd_LOG_MSG (c->daemon, MHD_SC_CONTENT_LENGTH_SEVERAL_DIFFERENT, \
   2762                        "Received request with more than one " \
   2763                        "'Content-Length' header with conflicting values.");
   2764           send_err = true;
   2765         }
   2766 
   2767         if (send_err)
   2768         {
   2769           mhd_RESPOND_WITH_ERROR_STATIC ( \
   2770             c, \
   2771             MHD_HTTP_STATUS_BAD_REQUEST, \
   2772             ERR_RSP_REQUEST_CONTENTLENGTH_SEVERAL);
   2773           return;
   2774         }
   2775       }
   2776       mhd_assert ((0 == c->rq.cntn.cntn_size) \
   2777                   || (c->rq.cntn.cntn_size == cntn_size));
   2778       c->rq.cntn.cntn_size = cntn_size;
   2779       has_cntnlen = true;
   2780       continue;
   2781     }
   2782 
   2783     /* "Connection:" */
   2784     if (mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_CONNECTION,
   2785                                      f->field.nv.name.cstr,
   2786                                      f->field.nv.name.len))
   2787     {
   2788       if (mhd_str_has_token_caseless (f->field.nv.value.cstr, // TODO: compare as size string
   2789                                       "close",
   2790                                       mhd_SSTR_LEN ("close")))
   2791       {
   2792         mhd_assert (mhd_CONN_MUST_UPGRADE != c->conn_reuse);
   2793         c->conn_reuse = mhd_CONN_MUST_CLOSE;
   2794       }
   2795       else if ((MHD_HTTP_VERSION_1_0 == c->rq.http_ver)
   2796                && (mhd_CONN_MUST_CLOSE != c->conn_reuse))
   2797       {
   2798         if (mhd_str_has_token_caseless (f->field.nv.value.cstr,  // TODO: compare as size string
   2799                                         "keep-alive",
   2800                                         mhd_SSTR_LEN ("keep-alive")))
   2801           has_keepalive = true;
   2802       }
   2803 
   2804       continue;
   2805     }
   2806 
   2807     /* "Transfer-Encoding:" */
   2808     if (mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_TRANSFER_ENCODING,
   2809                                      f->field.nv.name.cstr,
   2810                                      f->field.nv.name.len))
   2811     {
   2812       if (mhd_str_equal_caseless_n_st ("chunked",
   2813                                        f->field.nv.value.cstr,
   2814                                        f->field.nv.value.len))
   2815       {
   2816         c->rq.have_chunked_upload = true;
   2817         c->rq.cntn.cntn_size = MHD_SIZE_UNKNOWN;
   2818       }
   2819       else
   2820       {
   2821         mhd_LOG_MSG (c->daemon, MHD_SC_TRANSFER_ENCODING_UNSUPPORTED, \
   2822                      "The 'Transfer-Encoding' used in request is " \
   2823                      "unsupported or invalid.");
   2824         mhd_RESPOND_WITH_ERROR_STATIC (c,
   2825                                        MHD_HTTP_STATUS_BAD_REQUEST,
   2826                                        ERR_RSP_UNSUPPORTED_TR_ENCODING);
   2827         return;
   2828       }
   2829       has_trenc = true;
   2830       continue;
   2831     }
   2832 
   2833 #ifdef MHD_SUPPORT_COOKIES
   2834     /* "Cookie:" */
   2835     if ((!c->daemon->req_cfg.disable_cookies)
   2836         && mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_COOKIE,
   2837                                         f->field.nv.name.cstr,
   2838                                         f->field.nv.name.len))
   2839     {
   2840       if (MHD_PARSE_COOKIE_NO_MEMORY ==
   2841           parse_cookie_header (c,
   2842                                &(f->field.nv.value)))
   2843       {
   2844         handle_req_cookie_no_space (c);
   2845         return;
   2846       }
   2847       continue;
   2848     }
   2849 #endif /* MHD_SUPPORT_COOKIES */
   2850 
   2851     /* "Expect: 100-continue" */
   2852     if (mhd_str_equal_caseless_n_st (MHD_HTTP_HEADER_EXPECT,
   2853                                      f->field.nv.name.cstr,
   2854                                      f->field.nv.name.len))
   2855     {
   2856       if (mhd_str_equal_caseless_n_st ("100-continue",
   2857                                        f->field.nv.value.cstr,
   2858                                        f->field.nv.value.len))
   2859         c->rq.have_expect_100 = true;
   2860       else
   2861       {
   2862         if (0 < c->daemon->req_cfg.strictness)
   2863         {
   2864           mhd_LOG_MSG (c->daemon, MHD_SC_EXPECT_HEADER_VALUE_UNSUPPORTED, \
   2865                        "The 'Expect' header value used in request is " \
   2866                        "unsupported or invalid.");
   2867           mhd_RESPOND_WITH_ERROR_STATIC (c,
   2868                                          MHD_HTTP_STATUS_EXPECTATION_FAILED,
   2869                                          ERR_RSP_UNSUPPORTED_EXPECT_HDR_VALUE);
   2870           return;
   2871         }
   2872       }
   2873       continue;
   2874     }
   2875   }
   2876 
   2877   c->rq.cntn.cntn_present = (has_trenc || has_cntnlen);
   2878   if (has_trenc && has_cntnlen)
   2879   {
   2880     if (0 < c->daemon->req_cfg.strictness)
   2881     {
   2882       mhd_RESPOND_WITH_ERROR_STATIC ( \
   2883         c, \
   2884         MHD_HTTP_STATUS_BAD_REQUEST, \
   2885         ERR_RSP_REQUEST_CNTNLENGTH_WITH_TR_ENCODING);
   2886       return;
   2887     }
   2888     /* Must close connection after reply to prevent potential attack */
   2889     c->conn_reuse = mhd_CONN_MUST_CLOSE;
   2890     c->rq.cntn.cntn_size = MHD_SIZE_UNKNOWN;
   2891     mhd_assert (c->rq.have_chunked_upload);
   2892     mhd_LOG_MSG (c->daemon, MHD_SC_CONTENT_LENGTH_AND_TR_ENC, \
   2893                  "The 'Content-Length' request header is ignored " \
   2894                  "as chunked 'Transfer-Encoding' is used " \
   2895                  "for this request.");
   2896   }
   2897 
   2898   if (MHD_HTTP_VERSION_IS_LIKE_11 (c->rq.http_ver))
   2899   {
   2900     if ((!has_host)
   2901         && (-3 < c->daemon->req_cfg.strictness))
   2902     {
   2903       mhd_LOG_MSG (c->daemon, MHD_SC_HOST_HEADER_MISSING, \
   2904                    "Received HTTP/1.1 request without 'Host' header.");
   2905       mhd_RESPOND_WITH_ERROR_STATIC (c,
   2906                                      MHD_HTTP_STATUS_BAD_REQUEST,
   2907                                      ERR_RSP_REQUEST_LACKS_HOST);
   2908       return;
   2909     }
   2910   }
   2911   else
   2912   {
   2913     if (!has_keepalive)
   2914       c->conn_reuse = mhd_CONN_MUST_CLOSE; /* Do not re-use HTTP/1.0 connection by default */
   2915     if (has_trenc)
   2916       c->conn_reuse = mhd_CONN_MUST_CLOSE; /* Framing could be incorrect */
   2917   }
   2918 
   2919   c->stage = mhd_HTTP_STAGE_HEADERS_PROCESSED;
   2920   return;
   2921 }
   2922 
   2923 
   2924 /**
   2925  * Is "100 Continue" needed to be sent for current request?
   2926  *
   2927  * @param c the connection to check
   2928  * @return false 100 CONTINUE is not needed,
   2929  *         true otherwise
   2930  */
   2931 static MHD_FN_PAR_NONNULL_ALL_ bool
   2932 need_100_continue (struct MHD_Connection *restrict c)
   2933 {
   2934   mhd_assert (MHD_HTTP_VERSION_IS_1X (c->rq.http_ver));
   2935   mhd_assert (mhd_HTTP_STAGE_HEADERS_PROCESSED <= c->stage);
   2936   mhd_assert (mhd_HTTP_STAGE_BODY_RECEIVING > c->stage);
   2937 
   2938   if (!c->rq.have_expect_100)
   2939     return false; /* "100 Continue" has not been requested by the client */
   2940 
   2941   if (0 != c->read_buffer_offset)
   2942     return false; /* Part of the content has been received already */
   2943 
   2944   if (0 == c->rq.cntn.cntn_size)
   2945     return false; /* There is no content or zero-sized content for this request */
   2946 
   2947   if (MHD_HTTP_VERSION_1_0 == c->rq.http_ver)
   2948     return false; /* '100 Continue' is not allowed for HTTP/1.0 */
   2949 
   2950   return true;
   2951 }
   2952 
   2953 
   2954 /**
   2955  * Check whether special buffer is required to handle the upload content and
   2956  * try to allocate if necessary.
   2957  * Respond with error to the client if buffer cannot be allocated
   2958  * @param c the connection to
   2959  * @return true if succeed,
   2960  *         false if error response is set
   2961  */
   2962 static MHD_FN_PAR_NONNULL_ALL_ bool
   2963 check_and_alloc_buf_for_upload_processing (struct MHD_Connection *restrict c)
   2964 {
   2965   mhd_assert ((mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act) \
   2966               || (mhd_ACTION_POST_PARSE == c->rq.app_act.head_act.act));
   2967 
   2968   if (c->rq.have_chunked_upload)
   2969     return true; /* The size is unknown, buffers will be dynamically allocated
   2970                     and re-allocated */
   2971   mhd_assert (c->read_buffer_size > c->read_buffer_offset);
   2972 #if 0 // TODO: support processing full response in the connection buffer
   2973   if ((c->read_buffer_size - c->read_buffer_offset) >=
   2974       c->rq.cntn.cntn_size)
   2975     return true; /* No additional buffer needed */
   2976 #endif
   2977 
   2978   if ((mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act)
   2979       && (NULL == c->rq.app_act.head_act.data.upload.full.cb))
   2980     return true; /* data will be processed only incrementally */
   2981 
   2982   if (mhd_ACTION_UPLOAD != c->rq.app_act.head_act.act)
   2983   {
   2984     // TODO: add check for intermental-only POST processing */
   2985     mhd_assert (0 && "Not implemented yet");
   2986     return false;
   2987   }
   2988 
   2989   if ((c->rq.cntn.cntn_size >
   2990        c->rq.app_act.head_act.data.upload.large_buffer_size)
   2991       || !mhd_daemon_get_lbuf (c->daemon,
   2992                                (size_t)c->rq.cntn.cntn_size,
   2993                                &(c->rq.cntn.lbuf)))
   2994   {
   2995     if (NULL != c->rq.app_act.head_act.data.upload.inc.cb)
   2996     {
   2997       c->rq.app_act.head_act.data.upload.full.cb = NULL;
   2998       return true; /* Data can be processed incrementally */
   2999     }
   3000 
   3001     mhd_RESPOND_WITH_ERROR_STATIC (c,
   3002                                    MHD_HTTP_STATUS_CONTENT_TOO_LARGE,
   3003                                    ERR_RSP_REQUEST_CONTENTLENGTH_TOOLARGE);
   3004     return false;
   3005   }
   3006 
   3007   return true;
   3008 }
   3009 
   3010 
   3011 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   3012 mhd_stream_call_app_request_cb (struct MHD_Connection *restrict c)
   3013 {
   3014   struct MHD_Daemon *restrict d = c->daemon;
   3015   struct MHD_String path;
   3016   const struct MHD_Action *a;
   3017 
   3018   mhd_assert (mhd_HTTP_METHOD_NO_METHOD != c->rq.http_mthd);
   3019   mhd_assert (NULL == c->rp.response);
   3020 
   3021   if (mhd_ACTION_NO_ACTION != c->rq.app_act.head_act.act)
   3022     MHD_PANIC ("MHD_Action has been set already");
   3023 
   3024   path.cstr = c->rq.url;
   3025   path.len = c->rq.url_len;
   3026 
   3027   c->rq.app_aware = true;
   3028   a = d->req_cfg.cb (d->req_cfg.cb_cls,
   3029                      &(c->rq),
   3030                      &path,
   3031                      (enum MHD_HTTP_Method)c->rq.http_mthd,
   3032                      c->rq.cntn.cntn_size);
   3033 
   3034   if ((NULL != a)
   3035       && (((&(c->rq.app_act.head_act) != a))
   3036           || !mhd_ACTION_IS_VALID (c->rq.app_act.head_act.act)))
   3037   {
   3038     mhd_LOG_MSG (d, MHD_SC_ACTION_INVALID, \
   3039                  "Provided action is not a correct action generated " \
   3040                  "for the current request.");
   3041     /* Perform cleanup of the created but now unused action */
   3042     switch (c->rq.app_act.head_act.act)
   3043     {
   3044     case mhd_ACTION_RESPONSE:
   3045       mhd_assert (NULL != c->rq.app_act.head_act.data.response);
   3046       mhd_response_dec_use_count (c->rq.app_act.head_act.data.response);
   3047       break;
   3048     case mhd_ACTION_UPLOAD:
   3049     case mhd_ACTION_SUSPEND:
   3050       /* No cleanup needed */
   3051       break;
   3052 #ifdef MHD_SUPPORT_POST_PARSER
   3053     case mhd_ACTION_POST_PARSE:
   3054       /* No cleanup needed */
   3055       break;
   3056 #endif /* MHD_SUPPORT_POST_PARSER */
   3057 #ifdef MHD_SUPPORT_UPGRADE
   3058     case mhd_ACTION_UPGRADE:
   3059       /* No cleanup needed */
   3060       break;
   3061 #endif /* MHD_SUPPORT_UPGRADE */
   3062     case mhd_ACTION_ABORT:
   3063       mhd_UNREACHABLE ();
   3064       break;
   3065     case mhd_ACTION_NO_ACTION:
   3066     default:
   3067       break;
   3068     }
   3069     a = NULL;
   3070   }
   3071   if (NULL == a)
   3072     c->rq.app_act.head_act.act = mhd_ACTION_ABORT;
   3073 
   3074   switch (c->rq.app_act.head_act.act)
   3075   {
   3076   case mhd_ACTION_RESPONSE:
   3077     c->rp.response = c->rq.app_act.head_act.data.response;
   3078     c->stage = mhd_HTTP_STAGE_REQ_RECV_FINISHED;
   3079     return true;
   3080   case mhd_ACTION_UPLOAD:
   3081     if (0 != c->rq.cntn.cntn_size)
   3082     {
   3083       if (!check_and_alloc_buf_for_upload_processing (c))
   3084         return true;
   3085       if (need_100_continue (c))
   3086       {
   3087         c->stage = mhd_HTTP_STAGE_CONTINUE_SENDING;
   3088         return true;
   3089       }
   3090       c->stage = mhd_HTTP_STAGE_BODY_RECEIVING;
   3091       return (0 != c->read_buffer_offset);
   3092     }
   3093     c->stage = mhd_HTTP_STAGE_FULL_REQ_RECEIVED;
   3094     return true;
   3095 #ifdef MHD_SUPPORT_POST_PARSER
   3096   case mhd_ACTION_POST_PARSE:
   3097     if (0 == c->rq.cntn.cntn_size)
   3098     {
   3099       c->rq.u_proc.post.parse_result = MHD_POST_PARSE_RES_REQUEST_EMPTY;
   3100       c->stage = mhd_HTTP_STAGE_FULL_REQ_RECEIVED;
   3101       return true;
   3102     }
   3103     if (!mhd_stream_prepare_for_post_parse (c))
   3104     {
   3105       mhd_assert (mhd_HTTP_STAGE_FOOTERS_RECEIVED < c->stage);
   3106       return true;
   3107     }
   3108     if (need_100_continue (c))
   3109     {
   3110       c->stage = mhd_HTTP_STAGE_CONTINUE_SENDING;
   3111       return true;
   3112     }
   3113     c->stage = mhd_HTTP_STAGE_BODY_RECEIVING;
   3114     return true;
   3115 #endif /* MHD_SUPPORT_POST_PARSER */
   3116   case mhd_ACTION_SUSPEND:
   3117     c->suspended = true;
   3118 #ifdef MHD_USE_TRACE_SUSPEND_RESUME
   3119     fprintf (stderr,
   3120              "%%%%%% Suspending connection, FD: %2llu\n",
   3121              (unsigned long long)c->sk.fd);
   3122 #endif /* MHD_USE_TRACE_SUSPEND_RESUME */
   3123     c->rq.app_act.head_act.act = mhd_ACTION_NO_ACTION;
   3124     return false;
   3125 #ifdef MHD_SUPPORT_UPGRADE
   3126   case mhd_ACTION_UPGRADE:
   3127     mhd_assert (0 == c->rq.cntn.cntn_size);
   3128     c->stage = mhd_HTTP_STAGE_UPGRADE_HEADERS_SENDING;
   3129     return false;
   3130 #endif /* MHD_SUPPORT_UPGRADE */
   3131   case mhd_ACTION_ABORT:
   3132     mhd_conn_start_closing_app_abort (c);
   3133     return true;
   3134   case mhd_ACTION_NO_ACTION:
   3135   default:
   3136     mhd_assert (0 && "Impossible value");
   3137     break;
   3138   }
   3139   mhd_UNREACHABLE ();
   3140   return false;
   3141 }
   3142 
   3143 
   3144 /**
   3145  * React on provided action for upload
   3146  * @param c the stream to use
   3147  * @param act the action provided by application
   3148  * @param final set to 'true' if this is final upload callback
   3149  * @return true if connection state has been changed,
   3150  *         false otherwise
   3151  */
   3152 MHD_INTERNAL
   3153 MHD_FN_PAR_NONNULL_ (1) bool
   3154 mhd_stream_process_upload_action (struct MHD_Connection *restrict c,
   3155                                   const struct MHD_UploadAction *act,
   3156                                   bool final)
   3157 {
   3158   if (NULL != act)
   3159   {
   3160     if ((&(c->rq.app_act.upl_act) != act)
   3161         || !mhd_UPLOAD_ACTION_IS_VALID (c->rq.app_act.upl_act.act)
   3162         || (final
   3163             && (mhd_UPLOAD_ACTION_CONTINUE == c->rq.app_act.upl_act.act)))
   3164     {
   3165       /* Perform cleanup of the created but now unused action */
   3166       switch (c->rq.app_act.upl_act.act)
   3167       {
   3168       case mhd_UPLOAD_ACTION_RESPONSE:
   3169         mhd_assert (NULL != c->rq.app_act.upl_act.data.response);
   3170         mhd_response_dec_use_count (c->rq.app_act.upl_act.data.response);
   3171         break;
   3172       case mhd_UPLOAD_ACTION_CONTINUE:
   3173       case mhd_UPLOAD_ACTION_SUSPEND:
   3174         /* No cleanup needed */
   3175         break;
   3176 #ifdef MHD_SUPPORT_UPGRADE
   3177       case mhd_UPLOAD_ACTION_UPGRADE:
   3178         /* No cleanup needed */
   3179         break;
   3180 #endif /* MHD_SUPPORT_UPGRADE */
   3181       case mhd_UPLOAD_ACTION_ABORT:
   3182         mhd_UNREACHABLE ();
   3183         break;
   3184       case mhd_UPLOAD_ACTION_NO_ACTION:
   3185       default:
   3186         break;
   3187       }
   3188       mhd_LOG_MSG (c->daemon, MHD_SC_UPLOAD_ACTION_INVALID, \
   3189                    "Provided action is not a correct action generated " \
   3190                    "for the current request.");
   3191       act = NULL;
   3192     }
   3193   }
   3194   if (NULL == act)
   3195     c->rq.app_act.upl_act.act = mhd_UPLOAD_ACTION_ABORT;
   3196 
   3197   switch (c->rq.app_act.upl_act.act)
   3198   {
   3199   case mhd_UPLOAD_ACTION_RESPONSE:
   3200     c->rp.response = c->rq.app_act.upl_act.data.response;
   3201     c->stage = mhd_HTTP_STAGE_REQ_RECV_FINISHED;
   3202     return true;
   3203   case mhd_UPLOAD_ACTION_CONTINUE:
   3204     memset (&(c->rq.app_act.upl_act), 0, sizeof(c->rq.app_act.upl_act));
   3205     return false;
   3206   case mhd_UPLOAD_ACTION_SUSPEND:
   3207     c->suspended = true;
   3208 #ifdef MHD_USE_TRACE_SUSPEND_RESUME
   3209     fprintf (stderr,
   3210              "%%%%%% Suspending connection, FD: %2llu\n",
   3211              (unsigned long long)c->sk.fd);
   3212 #endif /* MHD_USE_TRACE_SUSPEND_RESUME */
   3213     memset (&(c->rq.app_act.upl_act), 0, sizeof(c->rq.app_act.upl_act));
   3214     return false;
   3215 #ifdef MHD_SUPPORT_UPGRADE
   3216   case mhd_UPLOAD_ACTION_UPGRADE:
   3217     mhd_assert (c->rq.cntn.recv_size == c->rq.cntn.cntn_size);
   3218     mhd_assert (!c->rq.have_chunked_upload \
   3219                 || mhd_HTTP_STAGE_FULL_REQ_RECEIVED == c->stage);
   3220     c->stage = mhd_HTTP_STAGE_UPGRADE_HEADERS_SENDING;
   3221     return false;
   3222 #endif /* MHD_SUPPORT_UPGRADE */
   3223   case mhd_UPLOAD_ACTION_ABORT:
   3224     mhd_conn_start_closing_app_abort (c);
   3225     return true;
   3226   case mhd_UPLOAD_ACTION_NO_ACTION:
   3227   default:
   3228     mhd_assert (0 && "Impossible value");
   3229     break;
   3230   }
   3231   mhd_UNREACHABLE ();
   3232   return false;
   3233 }
   3234 
   3235 
   3236 static MHD_FN_PAR_NONNULL_ALL_ bool
   3237 process_request_chunked_body (struct MHD_Connection *restrict c)
   3238 {
   3239   struct MHD_Daemon *restrict d = c->daemon;
   3240   size_t available;
   3241   bool has_more_data;
   3242   char *restrict buffer_head;
   3243   const int discp_lvl = d->req_cfg.strictness;
   3244   /* Treat bare LF as the end of the line.
   3245      RFC 9112, section 2.2-3
   3246      Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5).
   3247      Bare LF is processed as end of the line or rejected as broken request. */
   3248   const bool bare_lf_as_crlf = mhd_ALLOW_BARE_LF_AS_CRLF (discp_lvl);
   3249   /* Allow "Bad WhiteSpace" in chunk extension.
   3250      RFC 9112, Section 7.1.1, Paragraph 2 */
   3251   const bool allow_bws = (MHD_PSL_VERY_STRICT > discp_lvl);
   3252   bool state_updated;
   3253 
   3254   mhd_assert (NULL == c->rp.response);
   3255   mhd_assert (c->rq.have_chunked_upload);
   3256   mhd_assert (MHD_SIZE_UNKNOWN == c->rq.cntn.cntn_size);
   3257 
   3258   buffer_head = c->read_buffer;
   3259   available = c->read_buffer_offset;
   3260   state_updated = false;
   3261   do
   3262   {
   3263     size_t cntn_data_ready;
   3264     bool need_inc_proc;
   3265 
   3266     has_more_data = false;
   3267 
   3268     if ((c->rq.current_chunk_offset ==
   3269          c->rq.current_chunk_size)
   3270         && (0 != c->rq.current_chunk_size))
   3271     {
   3272       size_t i;
   3273       mhd_assert (0 != available);
   3274       /* skip new line at the *end* of a chunk */
   3275       i = 0;
   3276       if ((2 <= available)
   3277           && ('\r' == buffer_head[0])
   3278           && ('\n' == buffer_head[1]))
   3279         i += 2;                        /* skip CRLF */
   3280       else if (bare_lf_as_crlf && ('\n' == buffer_head[0]))
   3281         i++;                           /* skip bare LF */
   3282       else if (2 > available)
   3283         break;                         /* need more upload data */
   3284       if (0 == i)
   3285       {
   3286         /* malformed encoding */
   3287         mhd_RESPOND_WITH_ERROR_STATIC (c,
   3288                                        MHD_HTTP_STATUS_BAD_REQUEST,
   3289                                        ERR_RSP_REQUEST_CHUNKED_MALFORMED);
   3290         return true;
   3291       }
   3292       available -= i;
   3293       buffer_head += i;
   3294       c->rq.current_chunk_offset = 0;
   3295       c->rq.current_chunk_size = 0;
   3296       if (0 == available)
   3297         break;
   3298     }
   3299     if (0 != c->rq.current_chunk_size)
   3300     {
   3301       uint_fast64_t cur_chunk_left;
   3302       mhd_assert (c->rq.current_chunk_offset < \
   3303                   c->rq.current_chunk_size);
   3304       /* we are in the middle of a chunk, give
   3305          as much as possible to the client (without
   3306          crossing chunk boundaries) */
   3307       cur_chunk_left
   3308         = c->rq.current_chunk_size
   3309           - c->rq.current_chunk_offset;
   3310       if (cur_chunk_left > available)
   3311         cntn_data_ready = available;
   3312       else
   3313       {         /* cur_chunk_left <= (size_t)available */
   3314         cntn_data_ready = (size_t)cur_chunk_left;
   3315         if (available > cntn_data_ready)
   3316           has_more_data = true;
   3317       }
   3318     }
   3319     else
   3320     { /* Need the parse the chunk size line */
   3321       /** The number of found digits in the chunk size number */
   3322       size_t num_dig;
   3323       uint_fast64_t chunk_size;
   3324       bool broken;
   3325       bool overflow;
   3326 
   3327       mhd_assert (0 != available);
   3328 
   3329       overflow = false;
   3330       chunk_size = 0; /* Mute possible compiler warning.
   3331                          The real value will be set later. */
   3332 
   3333       num_dig = mhd_strx_to_uint64_n (buffer_head,
   3334                                       available,
   3335                                       &chunk_size);
   3336       mhd_assert (num_dig <= available);
   3337       if (num_dig == available)
   3338         continue; /* Need line delimiter */
   3339 
   3340       broken = (0 == num_dig);
   3341       if (broken)
   3342         /* Check whether result is invalid due to uint64_t overflow */
   3343         overflow = ((('0' <= buffer_head[0]) && ('9' >= buffer_head[0]))
   3344                     || (('A' <= buffer_head[0]) && ('F' >= buffer_head[0]))
   3345                     || (('a' <= buffer_head[0]) && ('f' >= buffer_head[0])));
   3346       else
   3347       {
   3348         /**
   3349          * The length of the string with the number of the chunk size,
   3350          * including chunk extension
   3351          */
   3352         size_t chunk_size_line_len;
   3353 
   3354         chunk_size_line_len = 0;
   3355         if ((';' == buffer_head[num_dig])
   3356             || (allow_bws
   3357                 && ((' ' == buffer_head[num_dig])
   3358                     || ('\t' == buffer_head[num_dig]))))
   3359         { /* Chunk extension */
   3360           size_t i;
   3361 
   3362           /* Skip bad whitespaces (if any) */
   3363           for (i = num_dig; i < available; ++i)
   3364           {
   3365             if ((' ' != buffer_head[i]) && ('\t' != buffer_head[i]))
   3366               break;
   3367           }
   3368           if (i == available)
   3369             break; /* need more data */
   3370           if (';' == buffer_head[i])
   3371           {
   3372             for (++i; i < available; ++i)
   3373             {
   3374               if ('\n' == buffer_head[i])
   3375                 break;
   3376             }
   3377             if (i == available)
   3378               break; /* need more data */
   3379             mhd_assert (i > num_dig);
   3380             mhd_assert (1 <= i);
   3381             /* Found LF position at 'i' (buffer_head[i] = '\n'), chunk ends at i+1 */
   3382             if (bare_lf_as_crlf)
   3383               chunk_size_line_len = i + 1; /* Don't care about CR before LF */
   3384             else if ('\r' == buffer_head[i - 1])
   3385               chunk_size_line_len = i + 1; /* Have CR LF, all good */
   3386             /* else: invalid termination, leave chunk_size_line_len at 0 */
   3387           }
   3388           else
   3389           { /* No ';' after "bad whitespace" */
   3390             mhd_assert (allow_bws);
   3391             mhd_assert (0 == chunk_size_line_len);
   3392           }
   3393         }
   3394         else
   3395         {
   3396           mhd_assert (available >= num_dig);
   3397           if ((2 <= (available - num_dig))
   3398               && ('\r' == buffer_head[num_dig])
   3399               && ('\n' == buffer_head[num_dig + 1]))
   3400             chunk_size_line_len = num_dig + 2;
   3401           else if (bare_lf_as_crlf
   3402                    && ('\n' == buffer_head[num_dig]))
   3403             chunk_size_line_len = num_dig + 1;
   3404           else if (2 > (available - num_dig))
   3405             break; /* need more data */
   3406         }
   3407 
   3408         if (0 != chunk_size_line_len)
   3409         { /* Valid termination of the chunk size line */
   3410           mhd_assert (chunk_size_line_len <= available);
   3411           /* Start reading payload data of the chunk */
   3412           c->rq.current_chunk_offset = 0;
   3413           c->rq.current_chunk_size = chunk_size;
   3414 
   3415           available -= chunk_size_line_len;
   3416           buffer_head += chunk_size_line_len;
   3417 
   3418           if (0 == chunk_size)
   3419           { /* The final (termination) chunk */
   3420             c->rq.cntn.cntn_size = c->rq.cntn.recv_size;
   3421             c->stage = mhd_HTTP_STAGE_BODY_RECEIVED;
   3422             state_updated = true;
   3423             break;
   3424           }
   3425           if (available > 0)
   3426             has_more_data = true;
   3427           continue;
   3428         }
   3429         /* Invalid chunk size line */
   3430       }
   3431 
   3432       if (!overflow)
   3433         mhd_RESPOND_WITH_ERROR_STATIC (c,
   3434                                        MHD_HTTP_STATUS_BAD_REQUEST,
   3435                                        ERR_RSP_REQUEST_CHUNKED_MALFORMED);
   3436       else
   3437         mhd_RESPOND_WITH_ERROR_STATIC (c,
   3438                                        MHD_HTTP_STATUS_CONTENT_TOO_LARGE,
   3439                                        ERR_RSP_REQUEST_CHUNK_TOO_LARGE);
   3440       return true;
   3441     }
   3442     mhd_assert (c->rq.app_aware);
   3443 
   3444 #ifdef MHD_SUPPORT_POST_PARSER
   3445     if (mhd_ACTION_POST_PARSE == c->rq.app_act.head_act.act)
   3446     {
   3447       size_t size_provided;
   3448 
   3449       c->rq.cntn.recv_size += cntn_data_ready;
   3450       size_provided = cntn_data_ready;
   3451 
   3452       state_updated = mhd_stream_post_parse (c,
   3453                                              &size_provided,
   3454                                              buffer_head);
   3455       // TODO: support one chunk in-place processing?
   3456       mhd_assert ((0 == size_provided) \
   3457                   || (MHD_POST_PARSE_RES_OK != c->rq.u_proc.post.parse_result) \
   3458                   || (mhd_HTTP_STAGE_BODY_RECEIVING != c->stage));
   3459       if (mhd_HTTP_STAGE_BODY_RECEIVING != c->stage)
   3460         c->discard_request = true;
   3461 
   3462       /* Only the data actually taken by the parser is "processed".
   3463          Currently the parser takes all the provided data, unless it failed to
   3464          get enough large buffer memory.
   3465          TODO: in-place processing will require reworking the "recv_size"
   3466          accounting above and the buffer advancing below as well. */
   3467       mhd_assert (size_provided <= cntn_data_ready);
   3468       c->rq.cntn.proc_size += cntn_data_ready - size_provided;
   3469     }
   3470     else
   3471 #endif /* MHD_SUPPORT_POST_PARSER */
   3472     if (1)
   3473     {
   3474       mhd_assert (mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act);
   3475       if (NULL != c->rq.app_act.head_act.data.upload.full.cb)
   3476       {
   3477         need_inc_proc = false;
   3478 
   3479         mhd_assert (0 == c->rq.cntn.proc_size);
   3480         if ((uint_fast64_t)c->rq.cntn.lbuf.size <
   3481             c->rq.cntn.recv_size + cntn_data_ready)
   3482         {
   3483           size_t grow_size;
   3484 
   3485           grow_size = (size_t)(c->rq.cntn.recv_size + cntn_data_ready
   3486                                - c->rq.cntn.lbuf.size);
   3487           if (((size_t)(c->rq.cntn.recv_size + cntn_data_ready) <
   3488                cntn_data_ready)
   3489               || (!mhd_daemon_grow_lbuf (d,
   3490                                          grow_size,
   3491                                          &(c->rq.cntn.lbuf))))
   3492           {
   3493             /* Failed to grow the buffer, no space to put the new data */
   3494             const struct MHD_UploadAction *act;
   3495             if (NULL == c->rq.app_act.head_act.data.upload.inc.cb)
   3496             {
   3497               mhd_RESPOND_WITH_ERROR_STATIC (
   3498                 c,
   3499                 MHD_HTTP_STATUS_CONTENT_TOO_LARGE,
   3500                 ERR_RSP_MSG_REQUEST_TOO_BIG);
   3501               return true;
   3502             }
   3503             c->rq.app_act.head_act.data.upload.full.cb = NULL; /* Cannot process "full" content */
   3504             /* Process previously buffered data */
   3505             mhd_assert (c->rq.cntn.recv_size <= c->rq.cntn.lbuf.size);
   3506             act = c->rq.app_act.head_act.data.upload.inc.cb (
   3507               c->rq.app_act.head_act.data.upload.inc.cls,
   3508               &(c->rq),
   3509               (size_t)c->rq.cntn.recv_size,
   3510               c->rq.cntn.lbuf.data);
   3511             c->rq.cntn.proc_size = c->rq.cntn.recv_size;
   3512             mhd_daemon_free_lbuf (d, &(c->rq.cntn.lbuf));
   3513             if (mhd_stream_process_upload_action (c, act, false))
   3514               return true;
   3515             need_inc_proc = true;
   3516           }
   3517         }
   3518         if (!need_inc_proc)
   3519         {
   3520           memcpy (c->rq.cntn.lbuf.data + c->rq.cntn.recv_size,
   3521                   buffer_head, cntn_data_ready);
   3522           c->rq.cntn.recv_size += cntn_data_ready;
   3523         }
   3524       }
   3525       else
   3526         need_inc_proc = true;
   3527 
   3528       if (need_inc_proc)
   3529       {
   3530         const struct MHD_UploadAction *act;
   3531         mhd_assert (NULL != c->rq.app_act.head_act.data.upload.inc.cb);
   3532 
   3533         c->rq.cntn.recv_size += cntn_data_ready;
   3534         act = c->rq.app_act.head_act.data.upload.inc.cb (
   3535           c->rq.app_act.head_act.data.upload.inc.cls,
   3536           &(c->rq),
   3537           cntn_data_ready,
   3538           buffer_head);
   3539         c->rq.cntn.proc_size += cntn_data_ready;
   3540         state_updated = mhd_stream_process_upload_action (c, act, false);
   3541       }
   3542     }
   3543     /* dh left "processed" bytes in buffer for next time... */
   3544     mhd_ASSUME (available >= cntn_data_ready);
   3545     buffer_head += cntn_data_ready;
   3546     available -= cntn_data_ready;
   3547     mhd_assert (MHD_SIZE_UNKNOWN == c->rq.cntn.cntn_size);
   3548     mhd_ASSUME (c->rq.current_chunk_offset + cntn_data_ready >=
   3549                 c->rq.current_chunk_offset);
   3550     c->rq.current_chunk_offset += cntn_data_ready;
   3551   } while (has_more_data && !state_updated);
   3552   /* TODO: optionally? zero out reused memory region */
   3553   if ((available > 0)
   3554       && (buffer_head != c->read_buffer))
   3555     memmove (c->read_buffer,
   3556              buffer_head,
   3557              available);
   3558   else
   3559     mhd_assert ((0 == available) \
   3560                 || (c->read_buffer_offset == available));
   3561   c->read_buffer_offset = available;
   3562 
   3563   return state_updated;
   3564 }
   3565 
   3566 
   3567 static MHD_FN_PAR_NONNULL_ALL_ bool
   3568 process_request_nonchunked_body (struct MHD_Connection *restrict c)
   3569 {
   3570   size_t cntn_data_ready;
   3571   bool read_buf_reuse;
   3572   bool state_updated;
   3573 
   3574   mhd_assert (NULL == c->rp.response);
   3575   mhd_assert (!c->rq.have_chunked_upload);
   3576   mhd_assert (MHD_SIZE_UNKNOWN != c->rq.cntn.cntn_size);
   3577   mhd_assert (c->rq.cntn.recv_size < c->rq.cntn.cntn_size);
   3578   mhd_assert (c->rq.app_aware);
   3579 
   3580   if ((c->rq.cntn.cntn_size - c->rq.cntn.recv_size) < c->read_buffer_offset)
   3581     cntn_data_ready = (size_t)(c->rq.cntn.cntn_size - c->rq.cntn.recv_size);
   3582   else
   3583     cntn_data_ready = c->read_buffer_offset;
   3584 
   3585   read_buf_reuse = false;
   3586   state_updated = false;
   3587   mhd_assert (!read_buf_reuse);  /* Mute analyser warning */
   3588 
   3589 #ifdef MHD_SUPPORT_POST_PARSER
   3590   if (mhd_ACTION_POST_PARSE == c->rq.app_act.head_act.act)
   3591   {
   3592     size_t size_provided;
   3593     // TODO: rework to correctly support partial processing
   3594     // TODO: rework to support receiving directly into "large buffer"
   3595     c->rq.cntn.recv_size += cntn_data_ready;
   3596     size_provided = cntn_data_ready;
   3597 
   3598     state_updated = mhd_stream_post_parse (c,
   3599                                            &size_provided,
   3600                                            c->read_buffer);
   3601     mhd_assert ((0 == size_provided) \
   3602                 || (MHD_POST_PARSE_RES_OK != c->rq.u_proc.post.parse_result) \
   3603                 || (mhd_HTTP_STAGE_BODY_RECEIVING != c->stage));
   3604     if (mhd_HTTP_STAGE_BODY_RECEIVING != c->stage)
   3605       c->discard_request = true;
   3606 
   3607     read_buf_reuse = true;
   3608     /* Only the data actually taken by the parser is "processed".
   3609        Currently the parser takes all the provided data, unless it failed to
   3610        get enough large buffer memory.
   3611        TODO: in-place processing will require reworking the "recv_size"
   3612        accounting above and the read buffer reuse as well. */
   3613     mhd_assert (size_provided <= cntn_data_ready);
   3614     c->rq.cntn.proc_size += cntn_data_ready - size_provided;
   3615     if (c->rq.cntn.recv_size == c->rq.cntn.cntn_size)
   3616     {
   3617       c->stage = mhd_HTTP_STAGE_FULL_REQ_RECEIVED;
   3618       state_updated = true;
   3619     }
   3620   }
   3621   else
   3622 #endif /* MHD_SUPPORT_POST_PARSER */
   3623   if (1)
   3624   {
   3625     mhd_assert (mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act);
   3626     if (NULL != c->rq.app_act.head_act.data.upload.full.cb)
   3627     {
   3628       // TODO: implement processing in pool memory if buffer is large enough
   3629       mhd_assert ((c->rq.cntn.recv_size + cntn_data_ready) <=
   3630                   (uint_fast64_t)c->rq.cntn.lbuf.size);
   3631       memcpy (c->rq.cntn.lbuf.data + c->rq.cntn.recv_size,
   3632               c->read_buffer, cntn_data_ready);
   3633       c->rq.cntn.recv_size += cntn_data_ready;
   3634       read_buf_reuse = true;
   3635       if (c->rq.cntn.recv_size == c->rq.cntn.cntn_size)
   3636       {
   3637         c->stage = mhd_HTTP_STAGE_FULL_REQ_RECEIVED;
   3638         state_updated = true;
   3639       }
   3640     }
   3641     else
   3642     {
   3643       const struct MHD_UploadAction *act;
   3644       mhd_assert (NULL != c->rq.app_act.head_act.data.upload.inc.cb);
   3645 
   3646       c->rq.cntn.recv_size += cntn_data_ready;
   3647       act = c->rq.app_act.head_act.data.upload.inc.cb (
   3648         c->rq.app_act.head_act.data.upload.inc.cls,
   3649         &(c->rq),
   3650         cntn_data_ready,
   3651         c->read_buffer);
   3652       c->rq.cntn.proc_size += cntn_data_ready;
   3653       read_buf_reuse = true;
   3654       state_updated = mhd_stream_process_upload_action (c, act, false);
   3655     }
   3656   }
   3657 
   3658   if (read_buf_reuse)
   3659   {
   3660     size_t data_left_size;
   3661     mhd_assert (c->read_buffer_offset >= cntn_data_ready);
   3662     data_left_size = c->read_buffer_offset - cntn_data_ready;
   3663     if (0 != data_left_size)
   3664       memmove (c->read_buffer,
   3665                c->read_buffer + cntn_data_ready,
   3666                data_left_size);
   3667     c->read_buffer_offset = data_left_size;
   3668   }
   3669 
   3670   return state_updated;
   3671 }
   3672 
   3673 
   3674 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   3675 mhd_stream_process_request_body (struct MHD_Connection *restrict c)
   3676 {
   3677   if (c->rq.have_chunked_upload)
   3678     return process_request_chunked_body (c);
   3679 
   3680   return process_request_nonchunked_body (c);
   3681 }
   3682 
   3683 
   3684 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   3685 mhd_stream_call_app_final_upload_cb (struct MHD_Connection *restrict c)
   3686 {
   3687   const struct MHD_UploadAction *act;
   3688   bool state_changed;
   3689   mhd_assert (mhd_ACTION_POST_PARSE == c->rq.app_act.head_act.act \
   3690               || mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act);
   3691 
   3692 #ifdef MHD_SUPPORT_POST_PARSER
   3693   if (mhd_ACTION_POST_PARSE == c->rq.app_act.head_act.act)
   3694     return mhd_stream_process_post_finish (c);
   3695 #endif /* MHD_SUPPORT_POST_PARSER */
   3696 
   3697   mhd_assert (mhd_ACTION_UPLOAD == c->rq.app_act.head_act.act);
   3698 
   3699   if (NULL != c->rq.app_act.head_act.data.upload.full.cb)
   3700   {
   3701     mhd_assert (c->rq.cntn.recv_size == c->rq.cntn.cntn_size);
   3702     mhd_assert (0 == c->rq.cntn.proc_size);
   3703     mhd_assert (NULL != c->rq.cntn.lbuf.data);
   3704     mhd_assert (c->rq.cntn.recv_size <= c->rq.cntn.lbuf.size);
   3705     // TODO: implement processing in pool memory if it is large enough
   3706     act = c->rq.app_act.head_act.data.upload.full.cb (
   3707       c->rq.app_act.head_act.data.upload.full.cls,
   3708       &(c->rq),
   3709       (size_t)c->rq.cntn.recv_size,
   3710       c->rq.cntn.lbuf.data);
   3711     c->rq.cntn.proc_size = c->rq.cntn.recv_size;
   3712   }
   3713   else
   3714   {
   3715     mhd_assert (NULL != c->rq.app_act.head_act.data.upload.inc.cb);
   3716     mhd_assert (c->rq.cntn.cntn_size == c->rq.cntn.proc_size);
   3717     act = c->rq.app_act.head_act.data.upload.inc.cb (
   3718       c->rq.app_act.head_act.data.upload.inc.cls,
   3719       &(c->rq),
   3720       0,
   3721       NULL);
   3722   }
   3723 
   3724   state_changed = mhd_stream_process_upload_action (c, act, true);
   3725   if (!c->suspended)
   3726     mhd_daemon_free_lbuf (c->daemon, &(c->rq.cntn.lbuf));
   3727 
   3728   return state_changed;
   3729 }
   3730 
   3731 
   3732 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ bool
   3733 mhd_stream_process_req_recv_finished (struct MHD_Connection *restrict c)
   3734 {
   3735   if (NULL != c->rq.cntn.lbuf.data)
   3736     mhd_daemon_free_lbuf (c->daemon, &(c->rq.cntn.lbuf));
   3737   c->rq.cntn.lbuf.data = NULL;
   3738   if (c->rq.cntn.cntn_size != c->rq.cntn.proc_size)
   3739     c->discard_request = true;
   3740   mhd_assert (NULL != c->rp.response);
   3741   c->stage = mhd_HTTP_STAGE_START_REPLY;
   3742   return true;
   3743 }
   3744 
   3745 
   3746 /**
   3747  * Send error reply when receive buffer space exhausted while receiving
   3748  * the chunk size line.
   3749  * @param c the connection to handle
   3750  * @param chunk_size_line the optional pointer to the partially received
   3751  *                        the current chunk size line.
   3752  *                        Could be not zero-terminated and can contain binary
   3753  *                        zeros.
   3754  *                        Can be NULL.
   3755  * @param chunk_size_line_size the size of the @a chunk_size_line
   3756  */
   3757 static MHD_FN_PAR_NONNULL_ (1) MHD_FN_PAR_NONNULL_IF_NONZERO_ (2, 3) void
   3758 handle_req_chunk_size_line_no_space (struct MHD_Connection *c,
   3759                                      const char *chunk_size_line,
   3760                                      size_t chunk_size_line_size)
   3761 {
   3762   unsigned int err_code;
   3763 
   3764   if (NULL != chunk_size_line)
   3765   {
   3766     const char *semicol;
   3767     /* Check for chunk extension */
   3768     semicol = (const char *)
   3769               memchr (chunk_size_line,
   3770                       ';',
   3771                       chunk_size_line_size);
   3772     if (NULL != semicol)
   3773     { /* Chunk extension present. It could be removed without any loss of the
   3774          details of the request. */
   3775       mhd_RESPOND_WITH_ERROR_STATIC (c,
   3776                                      MHD_HTTP_STATUS_CONTENT_TOO_LARGE,
   3777                                      ERR_RSP_REQUEST_CHUNK_LINE_EXT_TOO_BIG);
   3778       return;
   3779     }
   3780   }
   3781   err_code = mhd_stream_get_no_space_err_status_code (c,
   3782                                                       MHD_PROC_RECV_BODY_CHUNKED,
   3783                                                       chunk_size_line_size,
   3784                                                       chunk_size_line);
   3785   mhd_RESPOND_WITH_ERROR_STATIC (c,
   3786                                  err_code,
   3787                                  ERR_RSP_REQUEST_CHUNK_LINE_TOO_BIG);
   3788 }
   3789 
   3790 
   3791 /**
   3792  * Handle situation with read buffer exhaustion.
   3793  * Must be called when no more space left in the read buffer, no more
   3794  * space left in the memory pool to grow the read buffer, but more data
   3795  * need to be received from the client.
   3796  * Could be called when the result of received data processing cannot be
   3797  * stored in the memory pool (like some header).
   3798  * @param c the connection to process
   3799  * @param stage the receive stage where the exhaustion happens.
   3800  * @return 'true' if connection should NOT be closed,
   3801  *         'false' if connection is closing
   3802  */
   3803 static MHD_FN_PAR_NONNULL_ALL_ bool
   3804 handle_recv_no_space (struct MHD_Connection *c,
   3805                       enum MHD_ProcRecvDataStage stage)
   3806 {
   3807   mhd_assert (MHD_PROC_RECV_INIT <= stage);
   3808   mhd_assert (MHD_PROC_RECV_FOOTERS >= stage);
   3809   mhd_assert (mhd_HTTP_STAGE_FULL_REQ_RECEIVED > c->stage);
   3810   mhd_assert ((MHD_PROC_RECV_INIT != stage) \
   3811               || (mhd_HTTP_STAGE_INIT == c->stage));
   3812   mhd_assert ((MHD_PROC_RECV_METHOD != stage) \
   3813               || (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage));
   3814   mhd_assert ((MHD_PROC_RECV_URI != stage) \
   3815               || (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage));
   3816   mhd_assert ((MHD_PROC_RECV_HTTPVER != stage) \
   3817               || (mhd_HTTP_STAGE_REQ_LINE_RECEIVING == c->stage));
   3818   mhd_assert ((MHD_PROC_RECV_HEADERS != stage) \
   3819               || (mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING == c->stage));
   3820   mhd_assert (MHD_PROC_RECV_COOKIE != stage); /* handle_req_cookie_no_space() must be called directly */
   3821   mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) \
   3822               || (mhd_HTTP_STAGE_BODY_RECEIVING == c->stage));
   3823   mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) \
   3824               || (mhd_HTTP_STAGE_BODY_RECEIVING == c->stage));
   3825   mhd_assert ((MHD_PROC_RECV_FOOTERS != stage) \
   3826               || (mhd_HTTP_STAGE_FOOTERS_RECEIVING == c->stage));
   3827   mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) \
   3828               || (!c->rq.have_chunked_upload));
   3829   mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) \
   3830               || (c->rq.have_chunked_upload));
   3831   switch (stage)
   3832   {
   3833   case MHD_PROC_RECV_INIT:
   3834   case MHD_PROC_RECV_METHOD:
   3835     /* Some data has been received, but it is not clear yet whether
   3836      * the received data is an valid HTTP request */
   3837     mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_NO_POOL_MEM_FOR_REQUEST, \
   3838                       "No space left in the read buffer when " \
   3839                       "receiving the initial part of " \
   3840                       "the request line.");
   3841     return false;
   3842   case MHD_PROC_RECV_URI:
   3843   case MHD_PROC_RECV_HTTPVER:
   3844     /* Some data has been received, but the request line is incomplete */
   3845     mhd_assert (mhd_HTTP_METHOD_NO_METHOD != c->rq.http_mthd);
   3846     mhd_assert (MHD_HTTP_VERSION_INVALID == c->rq.http_ver);
   3847     /* A quick simple check whether the incomplete line looks
   3848      * like an HTTP request */
   3849     if ((mhd_HTTP_METHOD_GET <= c->rq.http_mthd)
   3850         && (mhd_HTTP_METHOD_DELETE >= c->rq.http_mthd))
   3851     {
   3852       mhd_RESPOND_WITH_ERROR_STATIC (c,
   3853                                      MHD_HTTP_STATUS_URI_TOO_LONG,
   3854                                      ERR_RSP_MSG_REQUEST_TOO_BIG);
   3855       return true;
   3856     }
   3857     mhd_STREAM_ABORT (c, mhd_CONN_CLOSE_NO_POOL_MEM_FOR_REQUEST, \
   3858                       "No space left in the read buffer when " \
   3859                       "receiving the URI in " \
   3860                       "the request line. " \
   3861                       "The request uses non-standard HTTP request " \
   3862                       "method token.");
   3863     return false;
   3864   case MHD_PROC_RECV_HEADERS:
   3865     handle_req_headers_no_space (c, c->read_buffer, c->read_buffer_offset);
   3866     return true;
   3867   case MHD_PROC_RECV_BODY_NORMAL:
   3868     /* A header probably has been added to a suspended connection and
   3869        it took precisely all the space in the buffer.
   3870        Very low probability. */
   3871     mhd_assert (!c->rq.have_chunked_upload);
   3872     handle_req_headers_no_space (c, NULL, 0); // FIXME: check
   3873     return true;
   3874   case MHD_PROC_RECV_BODY_CHUNKED:
   3875     mhd_assert (c->rq.have_chunked_upload);
   3876     if (c->rq.current_chunk_offset != c->rq.current_chunk_size)
   3877     { /* Receiving content of the chunk */
   3878       /* A header probably has been added to a suspended connection and
   3879          it took precisely all the space in the buffer.
   3880          Very low probability. */
   3881       handle_req_headers_no_space (c, NULL, 0);  // FIXME: check
   3882     }
   3883     else
   3884     {
   3885       if (0 != c->rq.current_chunk_size)
   3886       { /* Waiting for chunk-closing CRLF */
   3887         /* Not really possible as some payload should be
   3888            processed and the space used by payload should be available. */
   3889         handle_req_headers_no_space (c, NULL, 0);  // FIXME: check
   3890       }
   3891       else
   3892       { /* Reading the line with the chunk size */
   3893         handle_req_chunk_size_line_no_space (c,
   3894                                              c->read_buffer,
   3895                                              c->read_buffer_offset);
   3896       }
   3897     }
   3898     return true;
   3899   case MHD_PROC_RECV_FOOTERS:
   3900     handle_req_footers_no_space (c, c->read_buffer, c->read_buffer_offset);
   3901     return true;
   3902   /* The next cases should not be possible */
   3903   case MHD_PROC_RECV_COOKIE:
   3904   default:
   3905     break;
   3906   }
   3907   mhd_UNREACHABLE ();
   3908   return false;
   3909 }
   3910 
   3911 
   3912 /**
   3913  * Try growing the read buffer.  We initially claim half the available
   3914  * buffer space for the read buffer (the other half being left for
   3915  * management data structures; the write buffer can in the end take
   3916  * virtually everything as the read buffer can be reduced to the
   3917  * minimum necessary at that point.
   3918  *
   3919  * @param connection the connection
   3920  * @param required set to 'true' if grow is required, i.e. connection
   3921  *                 will fail if no additional space is granted
   3922  * @return 'true' on success, 'false' on failure
   3923  */
   3924 static MHD_FN_PAR_NONNULL_ALL_ bool
   3925 try_grow_read_buffer (struct MHD_Connection *restrict connection,
   3926                       bool required)
   3927 {
   3928   size_t new_size;
   3929   size_t avail_size;
   3930   const size_t def_grow_size = 1536; // TODO: remove hardcoded increment
   3931   char *rb;
   3932 
   3933   avail_size = mhd_pool_get_free (connection->pool);
   3934   if (0 == avail_size)
   3935     return false;               /* No more space available */
   3936   if (0 == connection->read_buffer_size)
   3937     new_size = avail_size / 2;  /* Use half of available buffer for reading */
   3938   else
   3939   {
   3940     size_t grow_size;
   3941 
   3942     grow_size = avail_size / 8;
   3943     if (def_grow_size > grow_size)
   3944     {                  /* Shortage of space */
   3945       const size_t left_free =
   3946         connection->read_buffer_size - connection->read_buffer_offset;
   3947       mhd_assert (connection->read_buffer_size >= \
   3948                   connection->read_buffer_offset);
   3949       if ((def_grow_size <= grow_size + left_free)
   3950           && (left_free < def_grow_size))
   3951         grow_size = def_grow_size - left_free;  /* Use precise 'def_grow_size' for new free space */
   3952       else if (!required)
   3953         return false;                           /* Grow is not mandatory, leave some space in pool */
   3954       else
   3955       {
   3956         /* Shortage of space, but grow is mandatory */
   3957         const size_t small_inc =
   3958           ((mhd_BUF_INC_SIZE > def_grow_size) ?
   3959            def_grow_size : mhd_BUF_INC_SIZE) / 8;
   3960         if (small_inc < avail_size)
   3961           grow_size = small_inc;
   3962         else
   3963           grow_size = avail_size;
   3964       }
   3965     }
   3966     new_size = connection->read_buffer_size + grow_size;
   3967   }
   3968   /* Make sure that read buffer will not be moved */
   3969   if ((NULL != connection->read_buffer)
   3970       && !mhd_pool_is_resizable_inplace (connection->pool,
   3971                                          connection->read_buffer,
   3972                                          connection->read_buffer_size))
   3973   {
   3974     mhd_assert (0);
   3975     return false;
   3976   }
   3977   /* we can actually grow the buffer, do it! */
   3978   rb = (char *)mhd_pool_reallocate (connection->pool,
   3979                                     connection->read_buffer,
   3980                                     connection->read_buffer_size,
   3981                                     new_size);
   3982   if (NULL == rb)
   3983   {
   3984     /* This should NOT be possible: we just computed 'new_size' so that
   3985        it should fit. If it happens, somehow our read buffer is not in
   3986        the right position in the pool, say because someone called
   3987        mhd_pool_allocate() without 'from_end' set to 'true'? Anyway,
   3988        should be investigated! (Ideally provide all data from
   3989        *pool and connection->read_buffer and new_size for debugging). */
   3990     mhd_assert (0);
   3991     return false;
   3992   }
   3993   mhd_assert (connection->read_buffer == rb);
   3994   connection->read_buffer = rb;
   3995   mhd_assert (NULL != connection->read_buffer);
   3996   connection->read_buffer_size = new_size;
   3997   return true;
   3998 }
   3999 
   4000 
   4001 MHD_INTERNAL MHD_FN_PAR_NONNULL_ALL_ enum mhd_ConnectionBufferGrowResult
   4002 mhd_stream_check_and_grow_read_buffer_space (struct MHD_Connection *restrict c)
   4003 {
   4004   enum MHD_ProcRecvDataStage stage;
   4005   bool res;
   4006   /**
   4007    * The increase of read buffer size is desirable.
   4008    */
   4009   bool rbuff_grow_desired;
   4010   /**
   4011    * The increase of read buffer size is a hard requirement.
   4012    */
   4013   bool rbuff_grow_required;
   4014 
   4015   mhd_assert (0 != (MHD_EVENT_LOOP_INFO_RECV & c->event_loop_info));
   4016   mhd_assert (!c->discard_request);
   4017 
   4018   rbuff_grow_required = (c->read_buffer_offset == c->read_buffer_size);
   4019   if (rbuff_grow_required)
   4020     rbuff_grow_desired = true;
   4021   else
   4022   {
   4023     rbuff_grow_desired = (c->read_buffer_offset + 1536 > // TODO: remove handcoded buffer grow size
   4024                           c->read_buffer_size);
   4025 
   4026     if ((rbuff_grow_desired)
   4027         && (mhd_HTTP_STAGE_BODY_RECEIVING == c->stage))
   4028     {
   4029       if (!c->rq.have_chunked_upload)
   4030       {
   4031         mhd_assert (MHD_SIZE_UNKNOWN != c->rq.cntn.cntn_size);
   4032         /* Do not grow read buffer more than necessary to process the current
   4033            request. */
   4034         rbuff_grow_desired =
   4035           (c->rq.cntn.cntn_size - c->rq.cntn.recv_size > c->read_buffer_size); // FIXME
   4036       }
   4037       else
   4038       {
   4039         mhd_assert (MHD_SIZE_UNKNOWN == c->rq.cntn.cntn_size);
   4040         if (0 == c->rq.current_chunk_size)
   4041           rbuff_grow_desired =  /* Reading value of the next chunk size */
   4042                                (MHD_CHUNK_HEADER_REASONABLE_LEN >
   4043                                 c->read_buffer_size);
   4044         else
   4045         {
   4046           const uint_fast64_t cur_chunk_left =
   4047             c->rq.current_chunk_size - c->rq.current_chunk_offset;
   4048           /* Do not grow read buffer more than necessary to process the current
   4049              chunk with terminating CRLF. */
   4050           mhd_assert (c->rq.current_chunk_offset <= c->rq.current_chunk_size);
   4051           rbuff_grow_desired =
   4052             ((cur_chunk_left + 2) > (uint_fast64_t)(c->read_buffer_size));
   4053         }
   4054       }
   4055     }
   4056   }
   4057 
   4058   if (!rbuff_grow_desired)
   4059     return mhd_CONN_BUFF_GROW_OK; /* No need to increase the buffer */
   4060 
   4061   if (try_grow_read_buffer (c, rbuff_grow_required))
   4062     return mhd_CONN_BUFF_GROW_OK; /* Buffer increase succeed */
   4063 
   4064   if (!rbuff_grow_required)
   4065     return mhd_CONN_BUFF_GROW_OK; /* Can continue without buffer increase */
   4066 
   4067   /* Failed to increase the read buffer size, but need to read the data
   4068      from the network.
   4069      No more space left in the buffer, no more space to increase the buffer. */
   4070 
   4071   switch (c->stage)
   4072   {
   4073   case mhd_HTTP_STAGE_INIT:
   4074     stage = MHD_PROC_RECV_INIT;
   4075     break;
   4076   case mhd_HTTP_STAGE_REQ_LINE_RECEIVING:
   4077     if (mhd_HTTP_METHOD_NO_METHOD == c->rq.http_mthd)
   4078       stage = MHD_PROC_RECV_METHOD;
   4079     else if (0 == c->rq.req_target_len)
   4080       stage = MHD_PROC_RECV_URI;
   4081     else
   4082       stage = MHD_PROC_RECV_HTTPVER;
   4083     break;
   4084   case mhd_HTTP_STAGE_REQ_HEADERS_RECEIVING:
   4085     stage = MHD_PROC_RECV_HEADERS;
   4086     break;
   4087   case mhd_HTTP_STAGE_BODY_RECEIVING:
   4088     stage = c->rq.have_chunked_upload ?
   4089             MHD_PROC_RECV_BODY_CHUNKED : MHD_PROC_RECV_BODY_NORMAL;
   4090     break;
   4091   case mhd_HTTP_STAGE_FOOTERS_RECEIVING:
   4092     stage = MHD_PROC_RECV_FOOTERS;
   4093     break;
   4094   case mhd_HTTP_STAGE_REQ_LINE_RECEIVED:
   4095   case mhd_HTTP_STAGE_HEADERS_RECEIVED:
   4096   case mhd_HTTP_STAGE_HEADERS_PROCESSED:
   4097   case mhd_HTTP_STAGE_CONTINUE_SENDING:
   4098   case mhd_HTTP_STAGE_BODY_RECEIVED:
   4099   case mhd_HTTP_STAGE_FOOTERS_RECEIVED:
   4100   case mhd_HTTP_STAGE_FULL_REQ_RECEIVED:
   4101   case mhd_HTTP_STAGE_REQ_RECV_FINISHED:
   4102   case mhd_HTTP_STAGE_START_REPLY:
   4103   case mhd_HTTP_STAGE_HEADERS_SENDING:
   4104   case mhd_HTTP_STAGE_HEADERS_SENT:
   4105   case mhd_HTTP_STAGE_UNCHUNKED_BODY_UNREADY:
   4106   case mhd_HTTP_STAGE_UNCHUNKED_BODY_READY:
   4107   case mhd_HTTP_STAGE_CHUNKED_BODY_UNREADY:
   4108   case mhd_HTTP_STAGE_CHUNKED_BODY_READY:
   4109   case mhd_HTTP_STAGE_CHUNKED_BODY_SENT:
   4110   case mhd_HTTP_STAGE_FOOTERS_SENDING:
   4111   case mhd_HTTP_STAGE_FULL_REPLY_SENT:
   4112   case mhd_HTTP_STAGE_PRE_CLOSING:
   4113   case mhd_HTTP_STAGE_CLOSED:
   4114 #ifdef MHD_SUPPORT_UPGRADE
   4115   case mhd_HTTP_STAGE_UPGRADE_HEADERS_SENDING:
   4116   case mhd_HTTP_STAGE_UPGRADING:
   4117   case mhd_HTTP_STAGE_UPGRADED:
   4118   case mhd_HTTP_STAGE_UPGRADED_CLEANING:
   4119 #endif /* MHD_SUPPORT_UPGRADE */
   4120   default:
   4121     mhd_UNREACHABLE ();
   4122     stage = MHD_PROC_RECV_BODY_NORMAL;
   4123     break;
   4124   }
   4125 
   4126   res = handle_recv_no_space (c, stage);
   4127 
   4128   mhd_assert (!res || !c->dbg.closing_started);
   4129   mhd_assert (res || c->dbg.closing_started);
   4130 
   4131   return
   4132     res ? mhd_CONN_BUFF_GROW_ERR_REPLY : mhd_CONN_BUFF_GROW_ERR_CONN_CLOSE;
   4133 }