libmicrohttpd

HTTP/1.x server C library (MHD 1.x, stable)
Log | Files | Refs | Submodules | README | LICENSE

connection.c (296802B)


      1 /*
      2      This file is part of libmicrohttpd
      3      Copyright (C) 2007-2020 Daniel Pittman and Christian Grothoff
      4      Copyright (C) 2015-2026 Evgeny Grin (Karlson2k)
      5 
      6      This library is free software; you can redistribute it and/or
      7      modify it under the terms of the GNU Lesser General Public
      8      License as published by the Free Software Foundation; either
      9      version 2.1 of the License, or (at your option) any later version.
     10 
     11      This library is distributed in the hope that it will be useful,
     12      but WITHOUT ANY WARRANTY; without even the implied warranty of
     13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14      Lesser General Public License for more details.
     15 
     16      You should have received a copy of the GNU Lesser General Public
     17      License along with this library; if not, write to the Free Software
     18      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
     19 
     20 */
     21 /**
     22  * @file connection.c
     23  * @brief  Methods for managing connections
     24  * @author Daniel Pittman
     25  * @author Christian Grothoff
     26  * @author Karlson2k (Evgeny Grin)
     27  */
     28 #include "internal.h"
     29 #include "mhd_limits.h"
     30 #include "connection.h"
     31 #include "memorypool.h"
     32 #include "response.h"
     33 #include "mhd_mono_clock.h"
     34 #include "mhd_str.h"
     35 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
     36 #include "mhd_locks.h"
     37 #endif
     38 #include "mhd_sockets.h"
     39 #include "mhd_compat.h"
     40 #include "mhd_itc.h"
     41 #ifdef MHD_LINUX_SOLARIS_SENDFILE
     42 #include <sys/sendfile.h>
     43 #endif /* MHD_LINUX_SOLARIS_SENDFILE */
     44 #if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE)
     45 #include <sys/types.h>
     46 #include <sys/socket.h>
     47 #include <sys/uio.h>
     48 #endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */
     49 #ifdef HTTPS_SUPPORT
     50 #include "connection_https.h"
     51 #endif /* HTTPS_SUPPORT */
     52 #ifdef HAVE_SYS_PARAM_H
     53 /* For FreeBSD version identification */
     54 #include <sys/param.h>
     55 #endif /* HAVE_SYS_PARAM_H */
     56 #include "mhd_send.h"
     57 #include "mhd_assert.h"
     58 #include "mhd_check.h"
     59 
     60 /**
     61  * Get whether bare LF in HTTP header and other protocol elements
     62  * should be treated as the line termination depending on the configured
     63  * strictness level.
     64  * RFC 9112, section 2.2
     65  */
     66 #define MHD_ALLOW_BARE_LF_AS_CRLF_(discp_lvl) (0 >= discp_lvl)
     67 
     68 /**
     69  * The reasonable length of the upload chunk "header" (the size specifier
     70  * with optional chunk extension).
     71  * MHD tries to keep the space in the read buffer large enough to read
     72  * the chunk "header" in one step.
     73  * The real "header" could be much larger, it will be handled correctly
     74  * anyway, however it may require several rounds of buffer grow.
     75  */
     76 #define MHD_CHUNK_HEADER_REASONABLE_LEN 24
     77 
     78 /**
     79  * Message to transmit when http 1.1 request is received
     80  */
     81 #define HTTP_100_CONTINUE "HTTP/1.1 100 Continue\r\n\r\n"
     82 
     83 /**
     84  * Response text used when the request (http header) is too big to
     85  * be processed.
     86  */
     87 #ifdef HAVE_MESSAGES
     88 #define ERR_MSG_REQUEST_TOO_BIG \
     89         "<html>" \
     90         "<head><title>Request too big</title></head>" \
     91         "<body>Request HTTP header is too big for the memory constraints " \
     92         "of this webserver.</body>" \
     93         "</html>"
     94 #else
     95 #define ERR_MSG_REQUEST_TOO_BIG ""
     96 #endif
     97 
     98 /**
     99  * Response text used when the request header is too big to be processed.
    100  */
    101 #ifdef HAVE_MESSAGES
    102 #define ERR_MSG_REQUEST_HEADER_TOO_BIG \
    103         "<html>" \
    104         "<head><title>Request too big</title></head>" \
    105         "<body><p>The total size of the request headers, which includes the " \
    106         "request target and the request field lines, exceeds the memory " \
    107         "constraints of this web server.</p>" \
    108         "<p>The request could be re-tried with shorter field lines, a shorter " \
    109         "request target or a shorter request method token.</p></body>" \
    110         "</html>"
    111 #else
    112 #define ERR_MSG_REQUEST_HEADER_TOO_BIG ""
    113 #endif
    114 
    115 /**
    116  * Response text used when the request cookie header is too big to be processed.
    117  */
    118 #ifdef HAVE_MESSAGES
    119 #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG \
    120         "<html>" \
    121         "<head><title>Request too big</title></head>" \
    122         "<body><p>The total size of the request headers, which includes the " \
    123         "request target and the request field lines, exceeds the memory " \
    124         "constraints of this web server.</p> " \
    125         "<p>The request could be re-tried with smaller " \
    126         "<b>&quot;Cookie:&quot;</b> field value, shorter other field lines, " \
    127         "a shorter request target or a shorter request method token.</p></body> " \
    128         "</html>"
    129 #else
    130 #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG ""
    131 #endif
    132 
    133 /**
    134  * Response text used when the request chunk size line with chunk extension
    135  * cannot fit the buffer.
    136  */
    137 #ifdef HAVE_MESSAGES
    138 #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG \
    139         "<html>" \
    140         "<head><title>Request too big</title></head>" \
    141         "<body><p>The total size of the request target, the request field lines " \
    142         "and the chunk size line exceeds the memory constraints of this web " \
    143         "server.</p>" \
    144         "<p>The request could be re-tried without chunk extensions, with a smaller " \
    145         "chunk size, shorter field lines, a shorter request target or a shorter " \
    146         "request method token.</p></body>" \
    147         "</html>"
    148 #else
    149 #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG ""
    150 #endif
    151 
    152 /**
    153  * Response text used when the request chunk size line without chunk extension
    154  * cannot fit the buffer.
    155  */
    156 #ifdef HAVE_MESSAGES
    157 #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG \
    158         "<html>" \
    159         "<head><title>Request too big</title></head>" \
    160         "<body><p>The total size of the request target, the request field lines " \
    161         "and the chunk size line exceeds the memory constraints of this web " \
    162         "server.</p>" \
    163         "<p>The request could be re-tried with a smaller " \
    164         "chunk size, shorter field lines, a shorter request target or a shorter " \
    165         "request method token.</p></body>" \
    166         "</html>"
    167 #else
    168 #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG ""
    169 #endif
    170 
    171 /**
    172  * Response text used when the request header is too big to be processed.
    173  */
    174 #ifdef HAVE_MESSAGES
    175 #define ERR_MSG_REQUEST_FOOTER_TOO_BIG \
    176         "<html>" \
    177         "<head><title>Request too big</title></head>" \
    178         "<body><p>The total size of the request headers, which includes the " \
    179         "request target, the request field lines and the chunked trailer " \
    180         "section exceeds the memory constraints of this web server.</p>" \
    181         "<p>The request could be re-tried with a shorter chunked trailer " \
    182         "section, shorter field lines, a shorter request target or " \
    183         "a shorter request method token.</p></body>" \
    184         "</html>"
    185 #else
    186 #define ERR_MSG_REQUEST_FOOTER_TOO_BIG ""
    187 #endif
    188 
    189 /**
    190  * Response text used when the request line has more then two whitespaces.
    191  */
    192 #ifdef HAVE_MESSAGES
    193 #define RQ_LINE_TOO_MANY_WSP \
    194         "<html>" \
    195         "<head><title>Request broken</title></head>" \
    196         "<body>The request line has more then two whitespaces.</body>" \
    197         "</html>"
    198 #else
    199 #define RQ_LINE_TOO_MANY_WSP ""
    200 #endif
    201 
    202 /**
    203  * Response text used when the request HTTP header has bare CR character
    204  * without LF character (and CR is not allowed to be treated as whitespace).
    205  */
    206 #ifdef HAVE_MESSAGES
    207 #define BARE_CR_IN_HEADER \
    208         "<html>" \
    209         "<head><title>Request broken</title></head>" \
    210         "<body>Request HTTP header has bare CR character without " \
    211         "following LF character.</body>" \
    212         "</html>"
    213 #else
    214 #define BARE_CR_IN_HEADER ""
    215 #endif
    216 
    217 /**
    218  * Response text used when the request HTTP footer has bare CR character
    219  * without LF character (and CR is not allowed to be treated as whitespace).
    220  */
    221 #ifdef HAVE_MESSAGES
    222 #define BARE_CR_IN_FOOTER \
    223         "<html>" \
    224         "<head><title>Request broken</title></head>" \
    225         "<body>Request HTTP footer has bare CR character without " \
    226         "following LF character.</body>" \
    227         "</html>"
    228 #else
    229 #define BARE_CR_IN_FOOTER ""
    230 #endif
    231 
    232 /**
    233  * Response text used when the request HTTP header has bare LF character
    234  * without CR character.
    235  */
    236 #ifdef HAVE_MESSAGES
    237 #define BARE_LF_IN_HEADER \
    238         "<html>" \
    239         "<head><title>Request broken</title></head>" \
    240         "<body>Request HTTP header has bare LF character without " \
    241         "preceding CR character.</body>" \
    242         "</html>"
    243 #else
    244 #define BARE_LF_IN_HEADER ""
    245 #endif
    246 
    247 /**
    248  * Response text used when the request HTTP footer has bare LF character
    249  * without CR character.
    250  */
    251 #ifdef HAVE_MESSAGES
    252 #define BARE_LF_IN_FOOTER \
    253         "<html>" \
    254         "<head><title>Request broken</title></head>" \
    255         "<body>Request HTTP footer has bare LF character without " \
    256         "preceding CR character.</body>" \
    257         "</html>"
    258 #else
    259 #define BARE_LF_IN_FOOTER ""
    260 #endif
    261 
    262 /**
    263  * Response text used when the request line has invalid characters in URI.
    264  */
    265 #ifdef HAVE_MESSAGES
    266 #define RQ_TARGET_INVALID_CHAR \
    267         "<html>" \
    268         "<head><title>Request broken</title></head>" \
    269         "<body>HTTP request has invalid characters in " \
    270         "the request-target.</body>" \
    271         "</html>"
    272 #else
    273 #define RQ_TARGET_INVALID_CHAR ""
    274 #endif
    275 
    276 /**
    277  * Response text used when line folding is used in request headers.
    278  */
    279 #ifdef HAVE_MESSAGES
    280 #define ERR_RSP_OBS_FOLD \
    281         "<html>" \
    282         "<head><title>Request broken</title></head>" \
    283         "<body>Obsolete line folding is used in HTTP request header.</body>" \
    284         "</html>"
    285 #else
    286 #define ERR_RSP_OBS_FOLD ""
    287 #endif
    288 
    289 /**
    290  * Response text used when line folding is used in request footers.
    291  */
    292 #ifdef HAVE_MESSAGES
    293 #define ERR_RSP_OBS_FOLD_FOOTER \
    294         "<html>" \
    295         "<head><title>Request broken</title></head>" \
    296         "<body>Obsolete line folding is used in HTTP request footer.</body>" \
    297         "</html>"
    298 #else
    299 #define ERR_RSP_OBS_FOLD_FOOTER ""
    300 #endif
    301 
    302 /**
    303  * Response text used when the request has whitespace at the start
    304  * of the first header line.
    305  */
    306 #ifdef HAVE_MESSAGES
    307 #define ERR_RSP_WSP_BEFORE_HEADER \
    308         "<html>" \
    309         "<head><title>Request broken</title></head>" \
    310         "<body>HTTP request has whitespace between the request line and " \
    311         "the first header.</body>" \
    312         "</html>"
    313 #else
    314 #define ERR_RSP_WSP_BEFORE_HEADER ""
    315 #endif
    316 
    317 /**
    318  * Response text used when the request has whitespace at the start
    319  * of the first footer line.
    320  */
    321 #ifdef HAVE_MESSAGES
    322 #define ERR_RSP_WSP_BEFORE_FOOTER \
    323         "<html>" \
    324         "<head><title>Request broken</title></head>" \
    325         "<body>First HTTP footer line has whitespace at the first " \
    326         "position.</body>" \
    327         "</html>"
    328 #else
    329 #define ERR_RSP_WSP_BEFORE_FOOTER ""
    330 #endif
    331 
    332 /**
    333  * Response text used when the whitespace found before colon (inside header
    334  * name or between header name and colon).
    335  */
    336 #ifdef HAVE_MESSAGES
    337 #define ERR_RSP_WSP_IN_HEADER_NAME \
    338         "<html>" \
    339         "<head><title>Request broken</title></head>" \
    340         "<body>HTTP request has whitespace before the first colon " \
    341         "in header line.</body>" \
    342         "</html>"
    343 #else
    344 #define ERR_RSP_WSP_IN_HEADER_NAME ""
    345 #endif
    346 
    347 /**
    348  * Response text used when the whitespace found before colon (inside header
    349  * name or between header name and colon).
    350  */
    351 #ifdef HAVE_MESSAGES
    352 #define ERR_RSP_WSP_IN_FOOTER_NAME \
    353         "<html>" \
    354         "<head><title>Request broken</title></head>" \
    355         "<body>HTTP request has whitespace before the first colon " \
    356         "in footer line.</body>" \
    357         "</html>"
    358 #else
    359 #define ERR_RSP_WSP_IN_FOOTER_NAME ""
    360 #endif
    361 
    362 
    363 /**
    364  * Response text used when the whitespace found before colon (inside header
    365  * name or between header name and colon).
    366  */
    367 #ifdef HAVE_MESSAGES
    368 #define ERR_RSP_INVALID_CHAR_IN_FIELD_NAME \
    369         "<html>" \
    370         "<head><title>Request broken</title></head>" \
    371         "<body>HTTP request has invalid character in field name.</body>" \
    372         "</html>"
    373 #else
    374 #define ERR_RSP_INVALID_CHAR_IN_FIELD_NAME ""
    375 #endif
    376 
    377 /**
    378  * Response text used when request header has invalid character.
    379  */
    380 #ifdef HAVE_MESSAGES
    381 #define ERR_RSP_INVALID_CHR_IN_HEADER \
    382         "<html>" \
    383         "<head><title>Request broken</title></head>" \
    384         "<body>HTTP request has invalid character in header.</body>" \
    385         "</html>"
    386 #else
    387 #define ERR_RSP_INVALID_CHR_IN_HEADER ""
    388 #endif
    389 
    390 /**
    391  * Response text used when request header has invalid character.
    392  */
    393 #ifdef HAVE_MESSAGES
    394 #define ERR_RSP_INVALID_CHR_IN_FOOTER \
    395         "<html>" \
    396         "<head><title>Request broken</title></head>" \
    397         "<body>HTTP request has invalid character in footer.</body>" \
    398         "</html>"
    399 #else
    400 #define ERR_RSP_INVALID_CHR_IN_FOOTER ""
    401 #endif
    402 
    403 /**
    404  * Response text used when request header has no colon character.
    405  */
    406 #ifdef HAVE_MESSAGES
    407 #define ERR_RSP_HEADER_WITHOUT_COLON \
    408         "<html>" \
    409         "<head><title>Request broken</title></head>" \
    410         "<body>HTTP request header line has no colon character.</body>" \
    411         "</html>"
    412 #else
    413 #define ERR_RSP_HEADER_WITHOUT_COLON ""
    414 #endif
    415 
    416 /**
    417  * Response text used when request footer has no colon character.
    418  */
    419 #ifdef HAVE_MESSAGES
    420 #define ERR_RSP_FOOTER_WITHOUT_COLON \
    421         "<html>" \
    422         "<head><title>Request broken</title></head>" \
    423         "<body>HTTP request footer line has no colon character.</body>" \
    424         "</html>"
    425 #else
    426 #define ERR_RSP_FOOTER_WITHOUT_COLON ""
    427 #endif
    428 
    429 /**
    430  * Response text used when request header has zero-length header (filed) name.
    431  */
    432 #ifdef HAVE_MESSAGES
    433 #define ERR_RSP_EMPTY_HEADER_NAME \
    434         "<html>" \
    435         "<head><title>Request broken</title></head>" \
    436         "<body>HTTP request header has empty header name.</body>" \
    437         "</html>"
    438 #else
    439 #define ERR_RSP_EMPTY_HEADER_NAME ""
    440 #endif
    441 
    442 /**
    443  * Response text used when request header has zero-length header (filed) name.
    444  */
    445 #ifdef HAVE_MESSAGES
    446 #define ERR_RSP_EMPTY_FOOTER_NAME \
    447         "<html>" \
    448         "<head><title>Request broken</title></head>" \
    449         "<body>HTTP request footer has empty footer name.</body>" \
    450         "</html>"
    451 #else
    452 #define ERR_RSP_EMPTY_FOOTER_NAME ""
    453 #endif
    454 
    455 /**
    456  * Response text used when the request (http header) does not
    457  * contain a "Host:" header and still claims to be HTTP 1.1.
    458  *
    459  * Intentionally empty here to keep our memory footprint
    460  * minimal.
    461  */
    462 #ifdef HAVE_MESSAGES
    463 #define REQUEST_LACKS_HOST \
    464         "<html>" \
    465         "<head><title>&quot;Host:&quot; header required</title></head>" \
    466         "<body>HTTP/1.1 request without <b>&quot;Host:&quot;</b>.</body>" \
    467         "</html>"
    468 
    469 #else
    470 #define REQUEST_LACKS_HOST ""
    471 #endif
    472 
    473 /**
    474  * Response text used when the request has multiple "Host:" headers
    475  */
    476 #define REQUEST_MULTIPLE_HOST_HDR \
    477         "<html>" \
    478         "<head><title>Multiple &quot;Host:&quot; headers</title></head>" \
    479         "<body>Request contains several <b>&quot;Host:&quot;</b> headers." \
    480         "</body></html>"
    481 
    482 /**
    483  * Response text used when the request (http header) has
    484  * multiple "Content-length" headers.
    485  */
    486 #ifdef HAVE_MESSAGES
    487 #define REQUEST_AMBIGUOUS_CONTENT_LENGTH \
    488         "<html>" \
    489         "<head><title>&quot;Content-Length:&quot; header must be unique</title></head>" \
    490         "<body>HTTP/1.1 request with multiple <b>&quot;Content-Length:&quot;</b> headers.</body>" \
    491         "</html>"
    492 
    493 #else
    494 #define REQUEST_AMBIGUOUS_CONTENT_LENGTH ""
    495 #endif
    496 
    497 /**
    498  * Response text used when the request has unsupported "Transfer-Encoding:".
    499  */
    500 #ifdef HAVE_MESSAGES
    501 #define REQUEST_UNSUPPORTED_TR_ENCODING \
    502         "<html>" \
    503         "<head><title>Unsupported Transfer-Encoding</title></head>" \
    504         "<body>The Transfer-Encoding used in request is not supported.</body>" \
    505         "</html>"
    506 #else
    507 #define REQUEST_UNSUPPORTED_TR_ENCODING ""
    508 #endif
    509 
    510 /**
    511  * Response text used when the request has unsupported both headers:
    512  * "Transfer-Encoding:" and "Content-Length:"
    513  */
    514 #ifdef HAVE_MESSAGES
    515 #define REQUEST_LENGTH_WITH_TR_ENCODING \
    516         "<html>" \
    517         "<head><title>Malformed request</title></head>" \
    518         "<body>Wrong combination of the request headers: both Transfer-Encoding " \
    519         "and Content-Length headers are used at the same time.</body>" \
    520         "</html>"
    521 #else
    522 #define REQUEST_LENGTH_WITH_TR_ENCODING ""
    523 #endif
    524 
    525 /**
    526  * Response text used when the HTTP/1.0 request has "Transfer-Encoding:" header
    527  */
    528 #define REQUEST_HTTP1_0_TR_ENCODING \
    529         "<html><head><title>Malformed request</title></head>" \
    530         "<body><b>&quot;Transfer-Encoding:&quot;</b> must not be used " \
    531         "with HTTP/1.0.</body></html>"
    532 
    533 /**
    534  * Response text used when the request (http header) is
    535  * malformed.
    536  *
    537  * Intentionally empty here to keep our memory footprint
    538  * minimal.
    539  */
    540 #ifdef HAVE_MESSAGES
    541 #define REQUEST_MALFORMED \
    542         "<html><head><title>Request malformed</title></head>" \
    543         "<body>HTTP request is syntactically incorrect.</body></html>"
    544 #else
    545 #define REQUEST_MALFORMED ""
    546 #endif
    547 
    548 /**
    549  * Response text used when the request target path has %00 sequence.
    550  */
    551 #define REQUEST_HAS_NUL_CHAR_IN_PATH \
    552         "<html><head><title>Bad Request Path</title></head>" \
    553         "<body>The request path contains invalid characters.</body></html>"
    554 
    555 /**
    556  * Response text used when the request HTTP chunked encoding is
    557  * malformed.
    558  */
    559 #ifdef HAVE_MESSAGES
    560 #define REQUEST_CHUNKED_MALFORMED \
    561         "<html><head><title>Request malformed</title></head>" \
    562         "<body>HTTP chunked encoding is syntactically incorrect.</body></html>"
    563 #else
    564 #define REQUEST_CHUNKED_MALFORMED ""
    565 #endif
    566 
    567 /**
    568  * Response text used when the request HTTP chunk is too large.
    569  */
    570 #ifdef HAVE_MESSAGES
    571 #define REQUEST_CHUNK_TOO_LARGE \
    572         "<html><head><title>Request content too large</title></head>" \
    573         "<body>The chunk size used in HTTP chunked encoded " \
    574         "request is too large.</body></html>"
    575 #else
    576 #define REQUEST_CHUNK_TOO_LARGE ""
    577 #endif
    578 
    579 /**
    580  * Response text used when the request HTTP content is too large.
    581  */
    582 #ifdef HAVE_MESSAGES
    583 #define REQUEST_CONTENTLENGTH_TOOLARGE \
    584         "<html><head><title>Request content too large</title></head>" \
    585         "<body>HTTP request has too large value for " \
    586         "<b>Content-Length</b> header.</body></html>"
    587 #else
    588 #define REQUEST_CONTENTLENGTH_TOOLARGE ""
    589 #endif
    590 
    591 /**
    592  * Response text used when the request HTTP chunked encoding is
    593  * malformed.
    594  */
    595 #ifdef HAVE_MESSAGES
    596 #define REQUEST_CONTENTLENGTH_MALFORMED \
    597         "<html><head><title>Request malformed</title></head>" \
    598         "<body>HTTP request has wrong value for " \
    599         "<b>Content-Length</b> header.</body></html>"
    600 #else
    601 #define REQUEST_CONTENTLENGTH_MALFORMED ""
    602 #endif
    603 
    604 /**
    605  * Response text used when there is an internal server error.
    606  *
    607  * Intentionally empty here to keep our memory footprint
    608  * minimal.
    609  */
    610 #ifdef HAVE_MESSAGES
    611 #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP \
    612         "<html><head><title>Internal server error</title></head>" \
    613         "<body>Please ask the developer of this Web server to carefully " \
    614         "read the GNU libmicrohttpd documentation about connection " \
    615         "management and blocking.</body></html>"
    616 #else
    617 #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP ""
    618 #endif
    619 
    620 /**
    621  * Response text used when the request HTTP version is too old.
    622  */
    623 #ifdef HAVE_MESSAGES
    624 #define REQ_HTTP_VER_IS_TOO_OLD \
    625         "<html><head><title>Requested HTTP version is not supported</title></head>" \
    626         "<body>Requested HTTP version is too old and not " \
    627         "supported.</body></html>"
    628 #else
    629 #define REQ_HTTP_VER_IS_TOO_OLD ""
    630 #endif
    631 
    632 /**
    633  * Response text used when the request HTTP version is not supported.
    634  */
    635 #ifdef HAVE_MESSAGES
    636 #define REQ_HTTP_VER_IS_NOT_SUPPORTED \
    637         "<html><head><title>Requested HTTP version is not supported</title></head>" \
    638         "<body>Requested HTTP version is not supported.</body></html>"
    639 #else
    640 #define REQ_HTTP_VER_IS_NOT_SUPPORTED ""
    641 #endif
    642 
    643 
    644 /**
    645  * sendfile() chuck size
    646  */
    647 #define MHD_SENFILE_CHUNK_         (0x20000)
    648 
    649 /**
    650  * sendfile() chuck size for thread-per-connection
    651  */
    652 #define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000)
    653 
    654 #ifdef HAVE_MESSAGES
    655 /**
    656  * Return text description for MHD_ERR_*_ codes
    657  * @param mhd_err_code the error code
    658  * @return pointer to static string with error description
    659  */
    660 static const char *
    661 str_conn_error_ (ssize_t mhd_err_code)
    662 {
    663   switch (mhd_err_code)
    664   {
    665   case MHD_ERR_AGAIN_:
    666     return _ ("The operation would block, retry later");
    667   case MHD_ERR_CONNRESET_:
    668     return _ ("The connection was forcibly closed by remote peer");
    669   case MHD_ERR_NOTCONN_:
    670     return _ ("The socket is not connected");
    671   case MHD_ERR_NOMEM_:
    672     return _ ("Not enough system resources to serve the request");
    673   case MHD_ERR_BADF_:
    674     return _ ("Bad FD value");
    675   case MHD_ERR_INVAL_:
    676     return _ ("Argument value is invalid");
    677   case MHD_ERR_OPNOTSUPP_:
    678     return _ ("Argument value is not supported");
    679   case MHD_ERR_PIPE_:
    680     return _ ("The socket is no longer available for sending");
    681   case MHD_ERR_TLS_:
    682     return _ ("TLS encryption or decryption error");
    683   default:
    684     break;   /* Mute compiler warning */
    685   }
    686   if (0 <= mhd_err_code)
    687     return _ ("Not an error code");
    688 
    689   mhd_assert (0); /* Should never be reachable */
    690   return _ ("Wrong error code value");
    691 }
    692 
    693 
    694 #endif /* HAVE_MESSAGES */
    695 
    696 /**
    697  * Allocate memory from connection's memory pool.
    698  * If memory pool doesn't have enough free memory but read or write buffer
    699  * have some unused memory, the size of the buffer will be reduced as needed.
    700  * @param connection the connection to use
    701  * @param size the size of allocated memory area
    702  * @return pointer to allocated memory region in the pool or
    703  *         NULL if no memory is available
    704  */
    705 void *
    706 MHD_connection_alloc_memory_ (struct MHD_Connection *connection,
    707                               size_t size)
    708 {
    709   struct MHD_Connection *const c = connection; /* a short alias */
    710   struct MemoryPool *const pool = c->pool;     /* a short alias */
    711   size_t need_to_be_freed = 0; /**< The required amount of additional free memory */
    712   void *res;
    713 
    714   res = MHD_pool_try_alloc (pool,
    715                             size,
    716                             &need_to_be_freed);
    717   if (NULL != res)
    718     return res;
    719 
    720   if (MHD_pool_is_resizable_inplace (pool,
    721                                      c->write_buffer,
    722                                      c->write_buffer_size))
    723   {
    724     if (c->write_buffer_size - c->write_buffer_append_offset >=
    725         need_to_be_freed)
    726     {
    727       char *buf;
    728       const size_t new_buf_size = c->write_buffer_size - need_to_be_freed;
    729       buf = MHD_pool_reallocate (pool,
    730                                  c->write_buffer,
    731                                  c->write_buffer_size,
    732                                  new_buf_size);
    733       mhd_assert (c->write_buffer == buf);
    734       mhd_assert (c->write_buffer_append_offset <= new_buf_size);
    735       mhd_assert (c->write_buffer_send_offset <= new_buf_size);
    736       c->write_buffer_size = new_buf_size;
    737       c->write_buffer = buf;
    738     }
    739     else
    740       return NULL;
    741   }
    742   else if (MHD_pool_is_resizable_inplace (pool,
    743                                           c->read_buffer,
    744                                           c->read_buffer_size))
    745   {
    746     if (c->read_buffer_size - c->read_buffer_offset >= need_to_be_freed)
    747     {
    748       char *buf;
    749       const size_t new_buf_size = c->read_buffer_size - need_to_be_freed;
    750       buf = MHD_pool_reallocate (pool,
    751                                  c->read_buffer,
    752                                  c->read_buffer_size,
    753                                  new_buf_size);
    754       mhd_assert (c->read_buffer == buf);
    755       mhd_assert (c->read_buffer_offset <= new_buf_size);
    756       c->read_buffer_size = new_buf_size;
    757       c->read_buffer = buf;
    758     }
    759     else
    760       return NULL;
    761   }
    762   else
    763     return NULL;
    764   res = MHD_pool_allocate (pool, size, true);
    765   mhd_assert (NULL != res); /* It has been checked that pool has enough space */
    766   return res;
    767 }
    768 
    769 
    770 /**
    771  * Callback for receiving data from the socket.
    772  *
    773  * @param connection the MHD connection structure
    774  * @param other where to write received data to
    775  * @param i maximum size of other (in bytes)
    776  * @return positive value for number of bytes actually received or
    777  *         negative value for error number MHD_ERR_xxx_
    778  */
    779 static ssize_t
    780 recv_param_adapter (struct MHD_Connection *connection,
    781                     void *other,
    782                     size_t i)
    783 {
    784   ssize_t ret;
    785 
    786   if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
    787        (MHD_CONNECTION_CLOSED == connection->state) )
    788   {
    789     return MHD_ERR_NOTCONN_;
    790   }
    791   if (i > MHD_SCKT_SEND_MAX_SIZE_)
    792     i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */
    793 
    794   ret = MHD_recv_ (connection->socket_fd,
    795                    other,
    796                    i);
    797   if (0 > ret)
    798   {
    799     const int err = MHD_socket_get_error_ ();
    800     if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
    801     {
    802 #ifdef EPOLL_SUPPORT
    803       /* Got EAGAIN --- no longer read-ready */
    804       connection->epoll_state &=
    805         ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
    806 #endif /* EPOLL_SUPPORT */
    807       return MHD_ERR_AGAIN_;
    808     }
    809     if (MHD_SCKT_ERR_IS_EINTR_ (err))
    810       return MHD_ERR_AGAIN_;
    811     if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
    812       return MHD_ERR_CONNRESET_;
    813     if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_))
    814       return MHD_ERR_OPNOTSUPP_;
    815     if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_))
    816       return MHD_ERR_NOTCONN_;
    817     if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_))
    818       return MHD_ERR_INVAL_;
    819     if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))
    820       return MHD_ERR_NOMEM_;
    821     if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_))
    822       return MHD_ERR_BADF_;
    823     /* Treat any other error as a hard error. */
    824     return MHD_ERR_NOTCONN_;
    825   }
    826 #ifdef EPOLL_SUPPORT
    827   else if (i > (size_t) ret)
    828     connection->epoll_state &=
    829       ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
    830 #endif /* EPOLL_SUPPORT */
    831   return ret;
    832 }
    833 
    834 
    835 _MHD_EXTERN enum MHD_Result
    836 MHD_get_connection_URI_path_n (struct MHD_Connection *connection,
    837                                const char **uri,
    838                                size_t *uri_size)
    839 {
    840   if (NULL != uri)
    841     *uri = NULL;
    842   if (NULL != uri_size)
    843     *uri_size = 0u;
    844 
    845   if (connection->state < MHD_CONNECTION_REQ_LINE_RECEIVED)
    846     return MHD_NO;
    847   if (connection->state >= MHD_CONNECTION_START_REPLY)
    848     return MHD_NO;
    849   if (NULL == connection->rq.url)
    850     return MHD_NO;
    851 
    852   if (NULL != uri)
    853     *uri = connection->rq.url;
    854   if (NULL != uri_size)
    855     *uri_size = connection->rq.url_len;
    856 
    857   return MHD_YES;
    858 }
    859 
    860 
    861 /**
    862  * Get all of the headers from the request.
    863  *
    864  * @param connection connection to get values from
    865  * @param kind types of values to iterate over, can be a bitmask
    866  * @param iterator callback to call on each header;
    867  *        maybe NULL (then just count headers)
    868  * @param iterator_cls extra argument to @a iterator
    869  * @return number of entries iterated over
    870  *         -1 if connection is NULL.
    871  * @ingroup request
    872  */
    873 _MHD_EXTERN int
    874 MHD_get_connection_values (struct MHD_Connection *connection,
    875                            enum MHD_ValueKind kind,
    876                            MHD_KeyValueIterator iterator,
    877                            void *iterator_cls)
    878 {
    879   int ret;
    880   struct MHD_HTTP_Req_Header *pos;
    881 
    882   if (NULL == connection)
    883     return -1;
    884   ret = 0;
    885   for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
    886     if (0 != (pos->kind & kind))
    887     {
    888       ret++;
    889       if ( (NULL != iterator) &&
    890            (MHD_NO == iterator (iterator_cls,
    891                                 pos->kind,
    892                                 pos->header,
    893                                 pos->value)) )
    894         return ret;
    895     }
    896   return ret;
    897 }
    898 
    899 
    900 /**
    901  * Get all of the headers from the request.
    902  *
    903  * @param connection connection to get values from
    904  * @param kind types of values to iterate over, can be a bitmask
    905  * @param iterator callback to call on each header;
    906  *        maybe NULL (then just count headers)
    907  * @param iterator_cls extra argument to @a iterator
    908  * @return number of entries iterated over,
    909  *         -1 if connection is NULL.
    910  * @ingroup request
    911  */
    912 _MHD_EXTERN int
    913 MHD_get_connection_values_n (struct MHD_Connection *connection,
    914                              enum MHD_ValueKind kind,
    915                              MHD_KeyValueIteratorN iterator,
    916                              void *iterator_cls)
    917 {
    918   int ret;
    919   struct MHD_HTTP_Req_Header *pos;
    920 
    921   if (NULL == connection)
    922     return -1;
    923   ret = 0;
    924 
    925   if (NULL == iterator)
    926     for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
    927     {
    928       if (0 != (kind & pos->kind))
    929         ret++;
    930     }
    931   else
    932     for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
    933       if (0 != (kind & pos->kind))
    934       {
    935         ret++;
    936         if (MHD_NO == iterator (iterator_cls,
    937                                 pos->kind,
    938                                 pos->header,
    939                                 pos->header_size,
    940                                 pos->value,
    941                                 pos->value_size))
    942           return ret;
    943       }
    944   return ret;
    945 }
    946 
    947 
    948 /**
    949  * This function can be used to add an arbitrary entry to connection.
    950  * Internal version of #MHD_set_connection_value_n() without checking
    951  * of arguments values.
    952  *
    953  * @param connection the connection for which a
    954  *                   value should be set
    955  * @param kind kind of the value
    956  * @param key key for the value, must be zero-terminated
    957  * @param key_size number of bytes in @a key (excluding 0-terminator)
    958  * @param value the value itself, must be zero-terminated
    959  * @param value_size number of bytes in @a value (excluding 0-terminator)
    960  * @return #MHD_NO if the operation could not be
    961  *         performed due to insufficient memory;
    962  *         #MHD_YES on success
    963  * @ingroup request
    964  */
    965 static enum MHD_Result
    966 MHD_set_connection_value_n_nocheck_ (struct MHD_Connection *connection,
    967                                      enum MHD_ValueKind kind,
    968                                      const char *key,
    969                                      size_t key_size,
    970                                      const char *value,
    971                                      size_t value_size)
    972 {
    973   struct MHD_HTTP_Req_Header *pos;
    974 
    975   pos = MHD_connection_alloc_memory_ (connection,
    976                                       sizeof (struct MHD_HTTP_Req_Header));
    977   if (NULL == pos)
    978     return MHD_NO;
    979   pos->header = key;
    980   pos->header_size = key_size;
    981   pos->value = value;
    982   pos->value_size = value_size;
    983   pos->kind = kind;
    984   pos->next = NULL;
    985   pos->prev = NULL;
    986   /* append 'pos' to the linked list of headers */
    987   if (NULL == connection->rq.headers_received_tail)
    988   {
    989     mhd_assert (NULL == connection->rq.headers_received);
    990     connection->rq.headers_received = pos;
    991     connection->rq.headers_received_tail = pos;
    992   }
    993   else
    994   {
    995     mhd_assert (NULL != connection->rq.headers_received);
    996     mhd_assert (NULL == connection->rq.headers_received_tail->next);
    997     mhd_assert (pos != connection->rq.headers_received_tail);
    998     mhd_assert (pos != connection->rq.headers_received);
    999     connection->rq.headers_received_tail->next = pos;
   1000     connection->rq.headers_received_tail = pos;
   1001   }
   1002   return MHD_YES;
   1003 }
   1004 
   1005 
   1006 /**
   1007  * This function can be used to add an arbitrary entry to connection.
   1008  * This function could add entry with binary zero, which is allowed
   1009  * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is
   1010  * recommended to use #MHD_set_connection_value.
   1011  *
   1012  * This function MUST only be called from within the
   1013  * #MHD_AccessHandlerCallback (otherwise, access maybe improperly
   1014  * synchronized).  Furthermore, the client must guarantee that the key
   1015  * and value arguments are 0-terminated strings that are NOT freed
   1016  * until the connection is closed.  (The easiest way to do this is by
   1017  * passing only arguments to permanently allocated strings.).
   1018  *
   1019  * @param connection the connection for which a
   1020  *  value should be set
   1021  * @param kind kind of the value
   1022  * @param key key for the value, must be zero-terminated
   1023  * @param key_size number of bytes in @a key (excluding 0-terminator)
   1024  * @param value the value itself, must be zero-terminated
   1025  * @param value_size number of bytes in @a value (excluding 0-terminator)
   1026  * @return #MHD_NO if the operation could not be
   1027  *         performed due to insufficient memory;
   1028  *         #MHD_YES on success
   1029  * @ingroup request
   1030  */
   1031 _MHD_EXTERN enum MHD_Result
   1032 MHD_set_connection_value_n (struct MHD_Connection *connection,
   1033                             enum MHD_ValueKind kind,
   1034                             const char *key,
   1035                             size_t key_size,
   1036                             const char *value,
   1037                             size_t value_size)
   1038 {
   1039   if ( (MHD_GET_ARGUMENT_KIND != kind) &&
   1040        ( ((key ? strlen (key) : 0) != key_size) ||
   1041          ((value ? strlen (value) : 0) != value_size) ) )
   1042     return MHD_NO; /* binary zero is allowed only in GET arguments */
   1043 
   1044   return MHD_set_connection_value_n_nocheck_ (connection,
   1045                                               kind,
   1046                                               key,
   1047                                               key_size,
   1048                                               value,
   1049                                               value_size);
   1050 }
   1051 
   1052 
   1053 /**
   1054  * This function can be used to add an entry to the HTTP headers of a
   1055  * connection (so that the #MHD_get_connection_values function will
   1056  * return them -- and the `struct MHD_PostProcessor` will also see
   1057  * them).  This maybe required in certain situations (see Mantis
   1058  * #1399) where (broken) HTTP implementations fail to supply values
   1059  * needed by the post processor (or other parts of the application).
   1060  *
   1061  * This function MUST only be called from within the
   1062  * #MHD_AccessHandlerCallback (otherwise, access maybe improperly
   1063  * synchronized).  Furthermore, the client must guarantee that the key
   1064  * and value arguments are 0-terminated strings that are NOT freed
   1065  * until the connection is closed.  (The easiest way to do this is by
   1066  * passing only arguments to permanently allocated strings.).
   1067  *
   1068  * @param connection the connection for which a
   1069  *  value should be set
   1070  * @param kind kind of the value
   1071  * @param key key for the value
   1072  * @param value the value itself
   1073  * @return #MHD_NO if the operation could not be
   1074  *         performed due to insufficient memory;
   1075  *         #MHD_YES on success
   1076  * @ingroup request
   1077  */
   1078 _MHD_EXTERN enum MHD_Result
   1079 MHD_set_connection_value (struct MHD_Connection *connection,
   1080                           enum MHD_ValueKind kind,
   1081                           const char *key,
   1082                           const char *value)
   1083 {
   1084   return MHD_set_connection_value_n_nocheck_ (connection,
   1085                                               kind,
   1086                                               key,
   1087                                               NULL != key
   1088                                               ? strlen (key)
   1089                                               : 0,
   1090                                               value,
   1091                                               NULL != value
   1092                                               ? strlen (value)
   1093                                               : 0);
   1094 }
   1095 
   1096 
   1097 /**
   1098  * Get a particular header value.  If multiple
   1099  * values match the kind, return any one of them.
   1100  *
   1101  * @param connection connection to get values from
   1102  * @param kind what kind of value are we looking for
   1103  * @param key the header to look for, NULL to lookup 'trailing' value without a key
   1104  * @return NULL if no such item was found
   1105  * @ingroup request
   1106  */
   1107 _MHD_EXTERN const char *
   1108 MHD_lookup_connection_value (struct MHD_Connection *connection,
   1109                              enum MHD_ValueKind kind,
   1110                              const char *key)
   1111 {
   1112   const char *value;
   1113 
   1114   value = NULL;
   1115   (void) MHD_lookup_connection_value_n (connection,
   1116                                         kind,
   1117                                         key,
   1118                                         (NULL == key) ? 0 : strlen (key),
   1119                                         &value,
   1120                                         NULL);
   1121   return value;
   1122 }
   1123 
   1124 
   1125 /**
   1126  * Get a particular header value.  If multiple
   1127  * values match the kind, return any one of them.
   1128  * @note Since MHD_VERSION 0x00096304
   1129  *
   1130  * @param connection connection to get values from
   1131  * @param kind what kind of value are we looking for
   1132  * @param key the header to look for, NULL to lookup 'trailing' value without a key
   1133  * @param key_size the length of @a key in bytes
   1134  * @param[out] value_ptr the pointer to variable, which will be set to found value,
   1135  *                       will not be updated if key not found,
   1136  *                       could be NULL to just check for presence of @a key
   1137  * @param[out] value_size_ptr the pointer variable, which will set to found value,
   1138  *                            will not be updated if key not found,
   1139  *                            could be NULL
   1140  * @return #MHD_YES if key is found,
   1141  *         #MHD_NO otherwise.
   1142  * @ingroup request
   1143  */
   1144 _MHD_EXTERN enum MHD_Result
   1145 MHD_lookup_connection_value_n (struct MHD_Connection *connection,
   1146                                enum MHD_ValueKind kind,
   1147                                const char *key,
   1148                                size_t key_size,
   1149                                const char **value_ptr,
   1150                                size_t *value_size_ptr)
   1151 {
   1152   struct MHD_HTTP_Req_Header *pos;
   1153 
   1154   if (NULL == connection)
   1155     return MHD_NO;
   1156 
   1157   if (NULL == key)
   1158   {
   1159     for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
   1160     {
   1161       if ( (0 != (kind & pos->kind)) &&
   1162            (NULL == pos->header) )
   1163         break;
   1164     }
   1165   }
   1166   else
   1167   {
   1168     for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
   1169     {
   1170       if ( (0 != (kind & pos->kind)) &&
   1171            (key_size == pos->header_size) &&
   1172            ( (key == pos->header) ||
   1173              (MHD_str_equal_caseless_bin_n_ (key,
   1174                                              pos->header,
   1175                                              key_size) ) ) )
   1176         break;
   1177     }
   1178   }
   1179 
   1180   if (NULL == pos)
   1181     return MHD_NO;
   1182 
   1183   if (NULL != value_ptr)
   1184     *value_ptr = pos->value;
   1185 
   1186   if (NULL != value_size_ptr)
   1187     *value_size_ptr = pos->value_size;
   1188 
   1189   return MHD_YES;
   1190 }
   1191 
   1192 
   1193 /**
   1194  * Check whether request header contains particular token.
   1195  *
   1196  * Token could be surrounded by spaces and tabs and delimited by comma.
   1197  * Case-insensitive match used for header names and tokens.
   1198  * @param connection the connection to get values from
   1199  * @param header     the header name
   1200  * @param header_len the length of header, not including optional
   1201  *                   terminating null-character
   1202  * @param token      the token to find
   1203  * @param token_len  the length of token, not including optional
   1204  *                   terminating null-character.
   1205  * @return true if token is found in specified header,
   1206  *         false otherwise
   1207  */
   1208 static bool
   1209 MHD_lookup_header_token_ci (const struct MHD_Connection *connection,
   1210                             const char *header,
   1211                             size_t header_len,
   1212                             const char *token,
   1213                             size_t token_len)
   1214 {
   1215   struct MHD_HTTP_Req_Header *pos;
   1216 
   1217   if ((NULL == connection) || (NULL == header) || (0 == header[0]) ||
   1218       (NULL == token) || (0 == token[0]))
   1219     return false;
   1220 
   1221   for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
   1222   {
   1223     if ((0 != (pos->kind & MHD_HEADER_KIND)) &&
   1224         (header_len == pos->header_size) &&
   1225         ( (header == pos->header) ||
   1226           (MHD_str_equal_caseless_bin_n_ (header,
   1227                                           pos->header,
   1228                                           header_len)) ) &&
   1229         (MHD_str_has_token_caseless_ (pos->value, token, token_len)))
   1230       return true;
   1231   }
   1232   return false;
   1233 }
   1234 
   1235 
   1236 /**
   1237  * Check whether request header contains particular static @a tkn.
   1238  *
   1239  * Token could be surrounded by spaces and tabs and delimited by comma.
   1240  * Case-insensitive match used for header names and tokens.
   1241  * @param c   the connection to get values from
   1242  * @param h   the static string of header name
   1243  * @param tkn the static string of token to find
   1244  * @return true if token is found in specified header,
   1245  *         false otherwise
   1246  */
   1247 #define MHD_lookup_header_s_token_ci(c,h,tkn) \
   1248         MHD_lookup_header_token_ci ((c),(h),MHD_STATICSTR_LEN_ (h), \
   1249                                     (tkn),MHD_STATICSTR_LEN_ (tkn))
   1250 
   1251 
   1252 /**
   1253  * Do we (still) need to send a 100 continue
   1254  * message for this connection?
   1255  *
   1256  * @param connection connection to test
   1257  * @return false if we don't need 100 CONTINUE, true if we do
   1258  */
   1259 static bool
   1260 need_100_continue (struct MHD_Connection *connection)
   1261 {
   1262   const char *expect;
   1263 
   1264   if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver))
   1265     return false;
   1266 
   1267   if (0 == connection->rq.remaining_upload_size)
   1268     return false;
   1269 
   1270   if (MHD_NO ==
   1271       MHD_lookup_connection_value_n (connection,
   1272                                      MHD_HEADER_KIND,
   1273                                      MHD_HTTP_HEADER_EXPECT,
   1274                                      MHD_STATICSTR_LEN_ ( \
   1275                                        MHD_HTTP_HEADER_EXPECT),
   1276                                      &expect,
   1277                                      NULL))
   1278     return false;
   1279 
   1280   if (MHD_str_equal_caseless_ (expect,
   1281                                "100-continue"))
   1282     return true;
   1283 
   1284   return false;
   1285 }
   1286 
   1287 
   1288 /**
   1289  * Mark connection as "closed".
   1290  * @remark To be called from any thread.
   1291  *
   1292  * @param connection connection to close
   1293  */
   1294 void
   1295 MHD_connection_mark_closed_ (struct MHD_Connection *connection)
   1296 {
   1297   const struct MHD_Daemon *daemon = connection->daemon;
   1298 
   1299   if (0 == (daemon->options & MHD_USE_TURBO))
   1300   {
   1301 #ifdef HTTPS_SUPPORT
   1302     /* For TLS connection use shutdown of TLS layer
   1303      * and do not shutdown TCP socket. This give more
   1304      * chances to send TLS closure data to remote side.
   1305      * Closure of TLS layer will be interpreted by
   1306      * remote side as end of transmission. */
   1307     if (0 != (daemon->options & MHD_USE_TLS))
   1308     {
   1309       if (! MHD_tls_connection_shutdown (connection))
   1310         shutdown (connection->socket_fd,
   1311                   SHUT_WR);
   1312     }
   1313     else   /* Combined with next 'shutdown()'. */
   1314 #endif /* HTTPS_SUPPORT */
   1315     shutdown (connection->socket_fd,
   1316               SHUT_WR);
   1317   }
   1318   connection->state = MHD_CONNECTION_CLOSED;
   1319   connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
   1320 }
   1321 
   1322 
   1323 /**
   1324  * Close the given connection and give the
   1325  * specified termination code to the user.
   1326  * @remark To be called only from thread that
   1327  * process connection's recv(), send() and response.
   1328  *
   1329  * @param connection connection to close
   1330  * @param termination_code termination reason to give
   1331  */
   1332 void
   1333 MHD_connection_close_ (struct MHD_Connection *connection,
   1334                        enum MHD_RequestTerminationCode termination_code)
   1335 {
   1336   struct MHD_Daemon *daemon = connection->daemon;
   1337   struct MHD_Response *resp = connection->rp.response;
   1338 
   1339   mhd_assert (! connection->suspended);
   1340 #ifdef MHD_USE_THREADS
   1341   mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
   1342                MHD_thread_handle_ID_is_current_thread_ (connection->tid) );
   1343 #endif /* MHD_USE_THREADS */
   1344   if ( (NULL != daemon->notify_completed) &&
   1345        (connection->rq.client_aware) )
   1346     daemon->notify_completed (daemon->notify_completed_cls,
   1347                               connection,
   1348                               &connection->rq.client_context,
   1349                               termination_code);
   1350   connection->rq.client_aware = false;
   1351   if (NULL != resp)
   1352   {
   1353     connection->rp.response = NULL;
   1354     MHD_destroy_response (resp);
   1355   }
   1356   if (NULL != connection->pool)
   1357   {
   1358     MHD_pool_destroy (connection->pool);
   1359     connection->pool = NULL;
   1360   }
   1361 
   1362   MHD_connection_mark_closed_ (connection);
   1363 }
   1364 
   1365 
   1366 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
   1367 /**
   1368  * Stop TLS forwarding on upgraded connection and
   1369  * reflect remote disconnect state to socketpair.
   1370  * @remark In thread-per-connection mode this function
   1371  * can be called from any thread, in other modes this
   1372  * function must be called only from thread that process
   1373  * daemon's select()/poll()/etc.
   1374  *
   1375  * @param connection the upgraded connection
   1376  */
   1377 void
   1378 MHD_connection_finish_forward_ (struct MHD_Connection *connection)
   1379 {
   1380   struct MHD_Daemon *daemon = connection->daemon;
   1381   struct MHD_UpgradeResponseHandle *urh = connection->urh;
   1382 
   1383 #ifdef MHD_USE_THREADS
   1384   mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
   1385                MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \
   1386                MHD_thread_handle_ID_is_current_thread_ (daemon->tid) );
   1387 #endif /* MHD_USE_THREADS */
   1388 
   1389   if (0 == (daemon->options & MHD_USE_TLS))
   1390     return; /* Nothing to do with non-TLS connection. */
   1391 
   1392   if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
   1393     DLL_remove (daemon->urh_head,
   1394                 daemon->urh_tail,
   1395                 urh);
   1396 #ifdef EPOLL_SUPPORT
   1397   if (MHD_D_IS_USING_EPOLL_ (daemon) &&
   1398       (0 != epoll_ctl (daemon->epoll_upgrade_fd,
   1399                        EPOLL_CTL_DEL,
   1400                        connection->socket_fd,
   1401                        NULL)) )
   1402   {
   1403     MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
   1404   }
   1405   if (urh->in_eready_list)
   1406   {
   1407     EDLL_remove (daemon->eready_urh_head,
   1408                  daemon->eready_urh_tail,
   1409                  urh);
   1410     urh->in_eready_list = false;
   1411   }
   1412 #endif /* EPOLL_SUPPORT */
   1413   if (MHD_INVALID_SOCKET != urh->mhd.socket)
   1414   {
   1415 #ifdef EPOLL_SUPPORT
   1416     if (MHD_D_IS_USING_EPOLL_ (daemon) &&
   1417         (0 != epoll_ctl (daemon->epoll_upgrade_fd,
   1418                          EPOLL_CTL_DEL,
   1419                          urh->mhd.socket,
   1420                          NULL)) )
   1421     {
   1422       MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
   1423     }
   1424 #endif /* EPOLL_SUPPORT */
   1425     /* Reflect remote disconnect to application by breaking
   1426      * socketpair connection. */
   1427     shutdown (urh->mhd.socket, SHUT_RDWR);
   1428   }
   1429   /* Socketpair sockets will remain open as they will be
   1430    * used with MHD_UPGRADE_ACTION_CLOSE. They will be
   1431    * closed by cleanup_upgraded_connection() during
   1432    * connection's final cleanup.
   1433    */
   1434 }
   1435 
   1436 
   1437 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT*/
   1438 
   1439 
   1440 /**
   1441  * A serious error occurred, close the
   1442  * connection (and notify the application).
   1443  *
   1444  * @param connection connection to close with error
   1445  * @param emsg error message (can be NULL)
   1446  */
   1447 static void
   1448 connection_close_error (struct MHD_Connection *connection,
   1449                         const char *emsg)
   1450 {
   1451   connection->stop_with_error = true;
   1452   connection->discard_request = true;
   1453 #ifdef HAVE_MESSAGES
   1454   if (NULL != emsg)
   1455     MHD_DLOG (connection->daemon,
   1456               "%s\n",
   1457               emsg);
   1458 #else  /* ! HAVE_MESSAGES */
   1459   (void) emsg; /* Mute compiler warning. */
   1460 #endif /* ! HAVE_MESSAGES */
   1461   MHD_connection_close_ (connection,
   1462                          MHD_REQUEST_TERMINATED_WITH_ERROR);
   1463 }
   1464 
   1465 
   1466 /**
   1467  * Macro to only include error message in call to
   1468  * #connection_close_error() if we have HAVE_MESSAGES.
   1469  */
   1470 #ifdef HAVE_MESSAGES
   1471 #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, emsg)
   1472 #else
   1473 #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, NULL)
   1474 #endif
   1475 
   1476 
   1477 /**
   1478  * Prepare the response buffer of this connection for
   1479  * sending.  Assumes that the response mutex is
   1480  * already held.  If the transmission is complete,
   1481  * this function may close the socket (and return
   1482  * #MHD_NO).
   1483  *
   1484  * @param connection the connection
   1485  * @return #MHD_NO if readying the response failed (the
   1486  *  lock on the response will have been released already
   1487  *  in this case).
   1488  */
   1489 static enum MHD_Result
   1490 try_ready_normal_body (struct MHD_Connection *connection)
   1491 {
   1492   ssize_t ret;
   1493   struct MHD_Response *response;
   1494 
   1495   response = connection->rp.response;
   1496   mhd_assert (connection->rp.props.send_reply_body);
   1497 
   1498   if ( (0 == response->total_size) ||
   1499                      /* TODO: replace the next check with assert */
   1500        (connection->rp.rsp_write_position == response->total_size) )
   1501     return MHD_YES;  /* 0-byte response is always ready */
   1502   if (NULL != response->data_iov)
   1503   {
   1504     size_t copy_size;
   1505 
   1506     if (NULL != connection->rp.resp_iov.iov)
   1507       return MHD_YES;
   1508     copy_size = response->data_iovcnt * sizeof(MHD_iovec_);
   1509     connection->rp.resp_iov.iov = MHD_connection_alloc_memory_ (connection,
   1510                                                                 copy_size);
   1511     if (NULL == connection->rp.resp_iov.iov)
   1512     {
   1513       MHD_mutex_unlock_chk_ (&response->mutex);
   1514       /* not enough memory */
   1515       CONNECTION_CLOSE_ERROR (connection,
   1516                               _ ("Closing connection (out of memory)."));
   1517       return MHD_NO;
   1518     }
   1519     memcpy (connection->rp.resp_iov.iov,
   1520             response->data_iov,
   1521             copy_size);
   1522     connection->rp.resp_iov.cnt = response->data_iovcnt;
   1523     connection->rp.resp_iov.sent = 0;
   1524     return MHD_YES;
   1525   }
   1526   if (NULL == response->crc)
   1527     return MHD_YES;
   1528   if ( (response->data_start <=
   1529         connection->rp.rsp_write_position) &&
   1530        (response->data_size + response->data_start >
   1531         connection->rp.rsp_write_position) )
   1532     return MHD_YES; /* response already ready */
   1533 #if defined(_MHD_HAVE_SENDFILE)
   1534   if (MHD_resp_sender_sendfile == connection->rp.resp_sender)
   1535   {
   1536     /* will use sendfile, no need to bother response crc */
   1537     return MHD_YES;
   1538   }
   1539 #endif /* _MHD_HAVE_SENDFILE */
   1540 
   1541   ret = response->crc (response->crc_cls,
   1542                        connection->rp.rsp_write_position,
   1543                        (char *) response->data,
   1544                        (size_t) MHD_MIN ((uint64_t) response->data_buffer_size,
   1545                                          response->total_size
   1546                                          - connection->rp.rsp_write_position));
   1547   if (0 > ret)
   1548   {
   1549     /* either error or http 1.0 transfer, close socket! */
   1550     /* TODO: do not update total size, check whether response
   1551      * was really with unknown size */
   1552     response->total_size = connection->rp.rsp_write_position;
   1553 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   1554     MHD_mutex_unlock_chk_ (&response->mutex);
   1555 #endif
   1556     if (MHD_CONTENT_READER_END_OF_STREAM == ret)
   1557       MHD_connection_close_ (connection,
   1558                              MHD_REQUEST_TERMINATED_COMPLETED_OK);
   1559     else
   1560       CONNECTION_CLOSE_ERROR (connection,
   1561                               _ ("Closing connection (application reported " \
   1562                                  "error generating data)."));
   1563     return MHD_NO;
   1564   }
   1565   response->data_start = connection->rp.rsp_write_position;
   1566   response->data_size = (size_t) ret;
   1567   if (0 == ret)
   1568   {
   1569     connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
   1570 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   1571     MHD_mutex_unlock_chk_ (&response->mutex);
   1572 #endif
   1573     return MHD_NO;
   1574   }
   1575   return MHD_YES;
   1576 }
   1577 
   1578 
   1579 /**
   1580  * Prepare the response buffer of this connection for sending.
   1581  * Assumes that the response mutex is already held.  If the
   1582  * transmission is complete, this function may close the socket (and
   1583  * return #MHD_NO).
   1584  *
   1585  * @param connection the connection
   1586  * @param[out] p_finished the pointer to variable that will be set to "true"
   1587  *                        when application returned indication of the end
   1588  *                        of the stream
   1589  * @return #MHD_NO if readying the response failed
   1590  */
   1591 static enum MHD_Result
   1592 try_ready_chunked_body (struct MHD_Connection *connection,
   1593                         bool *p_finished)
   1594 {
   1595   ssize_t ret;
   1596   struct MHD_Response *response;
   1597   static const size_t max_chunk = 0xFFFFFF;
   1598   char chunk_hdr[7];            /* 6: max strlen of "FFFFFF" */
   1599   /* "FFFFFF" + "\r\n" */
   1600   static const size_t max_chunk_hdr_len = sizeof(chunk_hdr) + 2;
   1601   /* "FFFFFF" + "\r\n" + "\r\n" (chunk termination) */
   1602   static const size_t max_chunk_overhead = sizeof(chunk_hdr) + 2 + 2;
   1603   size_t chunk_hdr_len;
   1604   uint64_t left_to_send;
   1605   size_t size_to_fill;
   1606 
   1607   response = connection->rp.response;
   1608   mhd_assert (NULL != response->crc || NULL != response->data);
   1609 
   1610   mhd_assert (0 == connection->write_buffer_append_offset);
   1611 
   1612   /* The buffer must be reasonably large enough */
   1613   if (128 > connection->write_buffer_size)
   1614   {
   1615     size_t size;
   1616 
   1617     size = connection->write_buffer_size + MHD_pool_get_free (connection->pool);
   1618     if (128 > size)
   1619     {
   1620 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   1621       MHD_mutex_unlock_chk_ (&response->mutex);
   1622 #endif
   1623       /* not enough memory */
   1624       CONNECTION_CLOSE_ERROR (connection,
   1625                               _ ("Closing connection (out of memory)."));
   1626       return MHD_NO;
   1627     }
   1628     /* Limit the buffer size to the largest usable size for chunks */
   1629     if ( (max_chunk + max_chunk_overhead) < size)
   1630       size = max_chunk + max_chunk_overhead;
   1631     mhd_assert ((NULL == connection->write_buffer) || \
   1632                 MHD_pool_is_resizable_inplace (connection->pool, \
   1633                                                connection->write_buffer, \
   1634                                                connection->write_buffer_size));
   1635     connection->write_buffer =
   1636       MHD_pool_reallocate (connection->pool,
   1637                            connection->write_buffer,
   1638                            connection->write_buffer_size,
   1639                            size);
   1640     mhd_assert (NULL != connection->write_buffer);
   1641     connection->write_buffer_size = size;
   1642   }
   1643   mhd_assert (max_chunk_overhead < connection->write_buffer_size);
   1644 
   1645   if (MHD_SIZE_UNKNOWN == response->total_size)
   1646     left_to_send = MHD_SIZE_UNKNOWN;
   1647   else
   1648     left_to_send = response->total_size
   1649                    - connection->rp.rsp_write_position;
   1650 
   1651   size_to_fill = connection->write_buffer_size - max_chunk_overhead;
   1652   /* Limit size for the callback to the max usable size */
   1653   if (max_chunk < size_to_fill)
   1654     size_to_fill = max_chunk;
   1655   if (left_to_send < size_to_fill)
   1656     size_to_fill = (size_t) left_to_send;
   1657 
   1658   if (0 == left_to_send)
   1659     /* nothing to send, don't bother calling crc */
   1660     ret = MHD_CONTENT_READER_END_OF_STREAM;
   1661   else if ( (response->data_start <=
   1662              connection->rp.rsp_write_position) &&
   1663             (response->data_start + response->data_size >
   1664              connection->rp.rsp_write_position) )
   1665   {
   1666     /* difference between rsp_write_position and data_start is less
   1667        than data_size which is size_t type, no need to check for overflow */
   1668     const size_t data_write_offset
   1669       = (size_t) (connection->rp.rsp_write_position
   1670                   - response->data_start);
   1671     /* buffer already ready, use what is there for the chunk */
   1672     mhd_assert (SSIZE_MAX >= (response->data_size - data_write_offset));
   1673     mhd_assert (response->data_size >= data_write_offset);
   1674     ret = (ssize_t) (response->data_size - data_write_offset);
   1675     if ( ((size_t) ret) > size_to_fill)
   1676       ret = (ssize_t) size_to_fill;
   1677     memcpy (&connection->write_buffer[max_chunk_hdr_len],
   1678             &response->data[data_write_offset],
   1679             (size_t) ret);
   1680   }
   1681   else
   1682   {
   1683     if (NULL == response->crc)
   1684     { /* There is no way to reach this code */
   1685 #if defined(MHD_USE_THREADS)
   1686       MHD_mutex_unlock_chk_ (&response->mutex);
   1687 #endif
   1688       CONNECTION_CLOSE_ERROR (connection,
   1689                               _ ("No callback for the chunked data."));
   1690       return MHD_NO;
   1691     }
   1692     ret = response->crc (response->crc_cls,
   1693                          connection->rp.rsp_write_position,
   1694                          &connection->write_buffer[max_chunk_hdr_len],
   1695                          size_to_fill);
   1696   }
   1697   if (MHD_CONTENT_READER_END_WITH_ERROR == ret)
   1698   {
   1699     /* error, close socket! */
   1700     /* TODO: remove update of the response size */
   1701     response->total_size = connection->rp.rsp_write_position;
   1702 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   1703     MHD_mutex_unlock_chk_ (&response->mutex);
   1704 #endif
   1705     CONNECTION_CLOSE_ERROR (connection,
   1706                             _ ("Closing connection (application error " \
   1707                                "generating response)."));
   1708     return MHD_NO;
   1709   }
   1710   if (MHD_CONTENT_READER_END_OF_STREAM == ret)
   1711   {
   1712     *p_finished = true;
   1713     /* TODO: remove update of the response size */
   1714     response->total_size = connection->rp.rsp_write_position;
   1715     return MHD_YES;
   1716   }
   1717   if (0 == ret)
   1718   {
   1719     connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
   1720 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   1721     MHD_mutex_unlock_chk_ (&response->mutex);
   1722 #endif
   1723     return MHD_NO;
   1724   }
   1725   if (size_to_fill < (size_t) ret)
   1726   {
   1727 #if defined(MHD_USE_THREADS)
   1728     MHD_mutex_unlock_chk_ (&response->mutex);
   1729 #endif
   1730     CONNECTION_CLOSE_ERROR (connection,
   1731                             _ ("Closing connection (application returned " \
   1732                                "more data than requested)."));
   1733     return MHD_NO;
   1734   }
   1735   chunk_hdr_len = MHD_uint32_to_strx ((uint32_t) ret,
   1736                                       chunk_hdr,
   1737                                       sizeof(chunk_hdr));
   1738   mhd_assert (chunk_hdr_len != 0);
   1739   mhd_assert (chunk_hdr_len <= sizeof(chunk_hdr));
   1740   /* This underflow would turn 'write_buffer_send_offset' into a huge value and
   1741      make the following memcpy() write outside the write buffer.  */
   1742   if (MHD_CHECK_FAILED_ ((chunk_hdr_len + 2) <= max_chunk_hdr_len))
   1743   {
   1744     MHD_CHECK_LOG_ (connection->daemon,
   1745                     "(chunk_hdr_len + 2) <= max_chunk_hdr_len");
   1746 #if defined(MHD_USE_THREADS)
   1747     MHD_mutex_unlock_chk_ (&response->mutex);
   1748 #endif /* MHD_USE_THREADS */
   1749     connection_close_error (connection,
   1750                             NULL);
   1751     return MHD_NO;
   1752   }
   1753   *p_finished = false;
   1754   connection->write_buffer_send_offset =
   1755     (max_chunk_hdr_len - (chunk_hdr_len + 2));
   1756   memcpy (connection->write_buffer + connection->write_buffer_send_offset,
   1757           chunk_hdr,
   1758           chunk_hdr_len);
   1759   connection->write_buffer[max_chunk_hdr_len - 2] = '\r';
   1760   connection->write_buffer[max_chunk_hdr_len - 1] = '\n';
   1761   connection->write_buffer[max_chunk_hdr_len + (size_t) ret] = '\r';
   1762   connection->write_buffer[max_chunk_hdr_len + (size_t) ret + 1] = '\n';
   1763   connection->rp.rsp_write_position += (size_t) ret;
   1764   connection->write_buffer_append_offset = max_chunk_hdr_len + (size_t) ret + 2;
   1765   return MHD_YES;
   1766 }
   1767 
   1768 
   1769 /**
   1770  * Are we allowed to keep the given connection alive?
   1771  * We can use the TCP stream for a second request if the connection
   1772  * is HTTP 1.1 and the "Connection" header either does not exist or
   1773  * is not set to "close", or if the connection is HTTP 1.0 and the
   1774  * "Connection" header is explicitly set to "keep-alive".
   1775  * If no HTTP version is specified (or if it is not 1.0 or 1.1), we
   1776  * definitively close the connection.  If the "Connection" header is
   1777  * not exactly "close" or "keep-alive", we proceed to use the default
   1778  * for the respective HTTP version.
   1779  * If response has HTTP/1.0 flag or has "Connection: close" header
   1780  * then connection must be closed.
   1781  * If full request has not been read then connection must be closed
   1782  * as well.
   1783  *
   1784  * @param connection the connection to check for keepalive
   1785  * @return MHD_CONN_USE_KEEPALIVE if (based on the request and the response),
   1786  *         a keepalive is legal,
   1787  *         MHD_CONN_MUST_CLOSE if connection must be closed after sending
   1788  *         complete reply,
   1789  *         MHD_CONN_MUST_UPGRADE if connection must be upgraded.
   1790  */
   1791 static enum MHD_ConnKeepAlive
   1792 keepalive_possible (struct MHD_Connection *connection)
   1793 {
   1794   struct MHD_Connection *const c = connection; /**< a short alias */
   1795   struct MHD_Response *const r = c->rp.response;  /**< a short alias */
   1796 
   1797   mhd_assert (NULL != r);
   1798   if (MHD_CONN_MUST_CLOSE == c->keepalive)
   1799     return MHD_CONN_MUST_CLOSE;
   1800 
   1801 #ifdef UPGRADE_SUPPORT
   1802   /* TODO: Move below the next check when MHD stops closing connections
   1803    * when response is queued in first callback */
   1804   if (NULL != r->upgrade_handler)
   1805   {
   1806     /* No "close" token is enforced by 'add_response_header_connection()' */
   1807     mhd_assert (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE));
   1808     /* Valid HTTP version is enforced by 'MHD_queue_response()' */
   1809     mhd_assert (MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver));
   1810     mhd_assert (! c->stop_with_error);
   1811     return MHD_CONN_MUST_UPGRADE;
   1812   }
   1813 #endif /* UPGRADE_SUPPORT */
   1814 
   1815   mhd_assert ( (! c->stop_with_error) || (c->discard_request));
   1816   if ((c->read_closed) || (c->discard_request))
   1817     return MHD_CONN_MUST_CLOSE;
   1818 
   1819   if (0 != (r->flags & MHD_RF_HTTP_1_0_COMPATIBLE_STRICT))
   1820     return MHD_CONN_MUST_CLOSE;
   1821   if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE))
   1822     return MHD_CONN_MUST_CLOSE;
   1823 
   1824   if (! MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver))
   1825     return MHD_CONN_MUST_CLOSE;
   1826 
   1827   if (MHD_lookup_header_s_token_ci (c,
   1828                                     MHD_HTTP_HEADER_CONNECTION,
   1829                                     "close"))
   1830     return MHD_CONN_MUST_CLOSE;
   1831 
   1832   if ((MHD_HTTP_VER_1_0 == connection->rq.http_ver) ||
   1833       (0 != (connection->rp.response->flags & MHD_RF_HTTP_1_0_SERVER)))
   1834   {
   1835     if (MHD_lookup_header_s_token_ci (connection,
   1836                                       MHD_HTTP_HEADER_CONNECTION,
   1837                                       "Keep-Alive"))
   1838       return MHD_CONN_USE_KEEPALIVE;
   1839 
   1840     return MHD_CONN_MUST_CLOSE;
   1841   }
   1842 
   1843   if (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver))
   1844     return MHD_CONN_USE_KEEPALIVE;
   1845 
   1846   return MHD_CONN_MUST_CLOSE;
   1847 }
   1848 
   1849 
   1850 /**
   1851  * Produce time stamp.
   1852  *
   1853  * Result is NOT null-terminated.
   1854  * Result is always 29 bytes long.
   1855  *
   1856  * @param[out] date where to write the time stamp, with
   1857  *             at least 29 bytes available space.
   1858  */
   1859 static bool
   1860 get_date_str (char *date)
   1861 {
   1862   static const char *const days[] = {
   1863     "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
   1864   };
   1865   static const char *const mons[] = {
   1866     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   1867     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
   1868   };
   1869   static const size_t buf_len = 29;
   1870   struct tm now;
   1871   time_t t;
   1872   const char *src;
   1873 #if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \
   1874   ! defined(HAVE_GMTIME_R)
   1875   struct tm *pNow;
   1876 #endif
   1877 
   1878   if ((time_t) -1 == time (&t))
   1879     return false;
   1880 #if defined(HAVE_C11_GMTIME_S)
   1881   if (NULL == gmtime_s (&t,
   1882                         &now))
   1883     return false;
   1884 #elif defined(HAVE_W32_GMTIME_S)
   1885   if (0 != gmtime_s (&now,
   1886                      &t))
   1887     return false;
   1888 #elif defined(HAVE_GMTIME_R)
   1889   if (NULL == gmtime_r (&t,
   1890                         &now))
   1891     return false;
   1892 #else
   1893   pNow = gmtime (&t);
   1894   if (NULL == pNow)
   1895     return false;
   1896   now = *pNow;
   1897 #endif
   1898 
   1899   /* Day of the week */
   1900   src = days[now.tm_wday % 7];
   1901   date[0] = src[0];
   1902   date[1] = src[1];
   1903   date[2] = src[2];
   1904   date[3] = ',';
   1905   date[4] = ' ';
   1906   /* Day of the month */
   1907   if (2 != MHD_uint8_to_str_pad ((uint8_t) now.tm_mday, 2,
   1908                                  date + 5, buf_len - 5))
   1909     return false;
   1910   date[7] = ' ';
   1911   /* Month */
   1912   src = mons[now.tm_mon % 12];
   1913   date[8] = src[0];
   1914   date[9] = src[1];
   1915   date[10] = src[2];
   1916   date[11] = ' ';
   1917   /* Year */
   1918   if (4 != MHD_uint16_to_str ((uint16_t) (1900 + now.tm_year), date + 12,
   1919                               buf_len - 12))
   1920     return false;
   1921   date[16] = ' ';
   1922   /* Time */
   1923   MHD_uint8_to_str_pad ((uint8_t) now.tm_hour, 2, date + 17, buf_len - 17);
   1924   date[19] = ':';
   1925   MHD_uint8_to_str_pad ((uint8_t) now.tm_min, 2, date + 20, buf_len - 20);
   1926   date[22] = ':';
   1927   MHD_uint8_to_str_pad ((uint8_t) now.tm_sec, 2, date + 23, buf_len - 23);
   1928   date[25] = ' ';
   1929   date[26] = 'G';
   1930   date[27] = 'M';
   1931   date[28] = 'T';
   1932 
   1933   return true;
   1934 }
   1935 
   1936 
   1937 /**
   1938  * Produce HTTP DATE header.
   1939  * Result is always 37 bytes long (plus one terminating null).
   1940  *
   1941  * @param[out] header where to write the header, with
   1942  *             at least 38 bytes available space.
   1943  */
   1944 static bool
   1945 get_date_header (char *header)
   1946 {
   1947   if (! get_date_str (header + 6))
   1948   {
   1949     header[0] = 0;
   1950     return false;
   1951   }
   1952   header[0] = 'D';
   1953   header[1] = 'a';
   1954   header[2] = 't';
   1955   header[3] = 'e';
   1956   header[4] = ':';
   1957   header[5] = ' ';
   1958   header[35] = '\r';
   1959   header[36] = '\n';
   1960   header[37] = 0;
   1961   return true;
   1962 }
   1963 
   1964 
   1965 /**
   1966  * Try growing the read buffer.  We initially claim half the available
   1967  * buffer space for the read buffer (the other half being left for
   1968  * management data structures; the write buffer can in the end take
   1969  * virtually everything as the read buffer can be reduced to the
   1970  * minimum necessary at that point.
   1971  *
   1972  * @param connection the connection
   1973  * @param required set to 'true' if grow is required, i.e. connection
   1974  *                 will fail if no additional space is granted
   1975  * @return 'true' on success, 'false' on failure
   1976  */
   1977 static bool
   1978 try_grow_read_buffer (struct MHD_Connection *connection,
   1979                       bool required)
   1980 {
   1981   size_t new_size;
   1982   size_t avail_size;
   1983   const size_t def_grow_size = connection->daemon->pool_increment;
   1984   void *rb;
   1985 
   1986   avail_size = MHD_pool_get_free (connection->pool);
   1987   if (0 == avail_size)
   1988     return false;               /* No more space available */
   1989   if (0 == connection->read_buffer_size)
   1990     new_size = avail_size / 2;  /* Use half of available buffer for reading */
   1991   else
   1992   {
   1993     size_t grow_size;
   1994 
   1995     grow_size = avail_size / 8;
   1996     if (def_grow_size > grow_size)
   1997     {                  /* Shortage of space */
   1998       const size_t left_free =
   1999         connection->read_buffer_size - connection->read_buffer_offset;
   2000       mhd_assert (connection->read_buffer_size >= \
   2001                   connection->read_buffer_offset);
   2002       if ((def_grow_size <= grow_size + left_free)
   2003           && (left_free < def_grow_size))
   2004         grow_size = def_grow_size - left_free;  /* Use precise 'def_grow_size' for new free space */
   2005       else if (! required)
   2006         return false;                           /* Grow is not mandatory, leave some space in pool */
   2007       else
   2008       {
   2009         /* Shortage of space, but grow is mandatory */
   2010         const size_t small_inc =
   2011           ((MHD_BUF_INC_SIZE > def_grow_size) ?
   2012            def_grow_size : MHD_BUF_INC_SIZE) / 8;
   2013         if (small_inc < avail_size)
   2014           grow_size = small_inc;
   2015         else
   2016           grow_size = avail_size;
   2017       }
   2018     }
   2019     new_size = connection->read_buffer_size + grow_size;
   2020   }
   2021   /* Make sure that read buffer will not be moved */
   2022   if ((NULL != connection->read_buffer) &&
   2023       ! MHD_pool_is_resizable_inplace (connection->pool,
   2024                                        connection->read_buffer,
   2025                                        connection->read_buffer_size))
   2026   {
   2027     mhd_assert (0);
   2028     return false;
   2029   }
   2030   /* we can actually grow the buffer, do it! */
   2031   rb = MHD_pool_reallocate (connection->pool,
   2032                             connection->read_buffer,
   2033                             connection->read_buffer_size,
   2034                             new_size);
   2035   if (NULL == rb)
   2036   {
   2037     /* This should NOT be possible: we just computed 'new_size' so that
   2038        it should fit. If it happens, somehow our read buffer is not in
   2039        the right position in the pool, say because someone called
   2040        MHD_pool_allocate() without 'from_end' set to 'true'? Anyway,
   2041        should be investigated! (Ideally provide all data from
   2042        *pool and connection->read_buffer and new_size for debugging). */
   2043     mhd_assert (0);
   2044     return false;
   2045   }
   2046   mhd_assert (connection->read_buffer == rb);
   2047   connection->read_buffer = rb;
   2048   mhd_assert (NULL != connection->read_buffer);
   2049   connection->read_buffer_size = new_size;
   2050   return true;
   2051 }
   2052 
   2053 
   2054 /**
   2055  * Shrink connection read buffer to the zero size of free space in the buffer
   2056  * @param connection the connection whose read buffer is being manipulated
   2057  */
   2058 static void
   2059 connection_shrink_read_buffer (struct MHD_Connection *connection)
   2060 {
   2061   struct MHD_Connection *const c = connection; /**< a short alias */
   2062   void *new_buf;
   2063 
   2064   if ((NULL == c->read_buffer) || (0 == c->read_buffer_size))
   2065   {
   2066     mhd_assert (0 == c->read_buffer_size);
   2067     mhd_assert (0 == c->read_buffer_offset);
   2068     return;
   2069   }
   2070 
   2071   mhd_assert (c->read_buffer_offset <= c->read_buffer_size);
   2072   if (0 == c->read_buffer_offset)
   2073   {
   2074     MHD_pool_deallocate (c->pool, c->read_buffer, c->read_buffer_size);
   2075     c->read_buffer = NULL;
   2076     c->read_buffer_size = 0;
   2077   }
   2078   else
   2079   {
   2080     mhd_assert (MHD_pool_is_resizable_inplace (c->pool, c->read_buffer, \
   2081                                                c->read_buffer_size));
   2082     new_buf = MHD_pool_reallocate (c->pool, c->read_buffer, c->read_buffer_size,
   2083                                    c->read_buffer_offset);
   2084     mhd_assert (c->read_buffer == new_buf);
   2085     c->read_buffer = new_buf;
   2086     c->read_buffer_size = c->read_buffer_offset;
   2087   }
   2088 }
   2089 
   2090 
   2091 /**
   2092  * Allocate the maximum available amount of memory from MemoryPool
   2093  * for write buffer.
   2094  * @param connection the connection whose write buffer is being manipulated
   2095  * @return the size of the free space in the write buffer
   2096  */
   2097 static size_t
   2098 connection_maximize_write_buffer (struct MHD_Connection *connection)
   2099 {
   2100   struct MHD_Connection *const c = connection; /**< a short alias */
   2101   struct MemoryPool *const pool = connection->pool;
   2102   void *new_buf;
   2103   size_t new_size;
   2104   size_t free_size;
   2105 
   2106   mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size));
   2107   mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset);
   2108   mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset);
   2109 
   2110   free_size = MHD_pool_get_free (pool);
   2111   if (0 != free_size)
   2112   {
   2113     new_size = c->write_buffer_size + free_size;
   2114     /* This function must not move the buffer position.
   2115      * MHD_pool_reallocate () may return the new position only if buffer was
   2116      * allocated 'from_end' or is not the last allocation,
   2117      * which should not happen. */
   2118     mhd_assert ((NULL == c->write_buffer) || \
   2119                 MHD_pool_is_resizable_inplace (pool, c->write_buffer, \
   2120                                                c->write_buffer_size));
   2121     new_buf = MHD_pool_reallocate (pool,
   2122                                    c->write_buffer,
   2123                                    c->write_buffer_size,
   2124                                    new_size);
   2125     mhd_assert ((c->write_buffer == new_buf) || (NULL == c->write_buffer));
   2126     c->write_buffer = new_buf;
   2127     c->write_buffer_size = new_size;
   2128     if (c->write_buffer_send_offset == c->write_buffer_append_offset)
   2129     {
   2130       /* All data have been sent, reset offsets to zero. */
   2131       c->write_buffer_send_offset = 0;
   2132       c->write_buffer_append_offset = 0;
   2133     }
   2134   }
   2135 
   2136   return c->write_buffer_size - c->write_buffer_append_offset;
   2137 }
   2138 
   2139 
   2140 #if 0 /* disable unused function */
   2141 /**
   2142  * Shrink connection write buffer to the size of unsent data.
   2143  *
   2144  * @note: The number of calls of this function should be limited to avoid extra
   2145  * zeroing of the memory.
   2146  * @param connection the connection whose write buffer is being manipulated
   2147  * @param connection the connection to manipulate write buffer
   2148  */
   2149 static void
   2150 connection_shrink_write_buffer (struct MHD_Connection *connection)
   2151 {
   2152   struct MHD_Connection *const c = connection; /**< a short alias */
   2153   struct MemoryPool *const pool = connection->pool;
   2154   void *new_buf;
   2155 
   2156   mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size));
   2157   mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset);
   2158   mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset);
   2159 
   2160   if ( (NULL == c->write_buffer) || (0 == c->write_buffer_size))
   2161   {
   2162     mhd_assert (0 == c->write_buffer_append_offset);
   2163     mhd_assert (0 == c->write_buffer_send_offset);
   2164     c->write_buffer = NULL;
   2165     return;
   2166   }
   2167   if (c->write_buffer_append_offset == c->write_buffer_size)
   2168     return;
   2169 
   2170   new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size,
   2171                                  c->write_buffer_append_offset);
   2172   mhd_assert ((c->write_buffer == new_buf) || \
   2173               (0 == c->write_buffer_append_offset));
   2174   c->write_buffer_size = c->write_buffer_append_offset;
   2175   if (0 == c->write_buffer_size)
   2176     c->write_buffer = NULL;
   2177   else
   2178     c->write_buffer = new_buf;
   2179 }
   2180 
   2181 
   2182 #endif /* unused function */
   2183 
   2184 
   2185 /**
   2186  * Switch connection from recv mode to send mode.
   2187  *
   2188  * Current request header or body will not be read anymore,
   2189  * response must be assigned to connection.
   2190  * @param connection the connection to prepare for sending.
   2191  */
   2192 static void
   2193 connection_switch_from_recv_to_send (struct MHD_Connection *connection)
   2194 {
   2195   /* Read buffer is not needed for this request, shrink it.*/
   2196   connection_shrink_read_buffer (connection);
   2197 }
   2198 
   2199 
   2200 /**
   2201  * This enum type describes requirements for reply body and reply bode-specific
   2202  * headers (namely Content-Length, Transfer-Encoding).
   2203  */
   2204 enum replyBodyUse
   2205 {
   2206   /**
   2207    * No reply body allowed.
   2208    * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are
   2209    * not allowed as well.
   2210    */
   2211   RP_BODY_NONE = 0,
   2212 
   2213   /**
   2214    * Do not send reply body.
   2215    * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are
   2216    * allowed, but optional.
   2217    */
   2218   RP_BODY_HEADERS_ONLY = 1,
   2219 
   2220   /**
   2221    * Send reply body and
   2222    * reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked'.
   2223    * Reply body headers are required.
   2224    */
   2225   RP_BODY_SEND = 2
   2226 };
   2227 
   2228 
   2229 /**
   2230  * Check whether reply body must be used.
   2231  *
   2232  * If reply body is needed, it could be zero-sized.
   2233  *
   2234  * @param connection the connection to check
   2235  * @param rcode the response code
   2236  * @return enum value indicating whether response body can be used and
   2237  *         whether response body length headers are allowed or required.
   2238  * @sa is_reply_body_header_needed()
   2239  */
   2240 static enum replyBodyUse
   2241 is_reply_body_needed (struct MHD_Connection *connection,
   2242                       unsigned int rcode)
   2243 {
   2244   struct MHD_Connection *const c = connection; /**< a short alias */
   2245 
   2246   mhd_assert (100 <= rcode);
   2247   mhd_assert (999 >= rcode);
   2248 
   2249   if (199 >= rcode)
   2250     return RP_BODY_NONE;
   2251 
   2252   if (MHD_HTTP_NO_CONTENT == rcode)
   2253     return RP_BODY_NONE;
   2254 
   2255 #if 0
   2256   /* This check is not needed as upgrade handler is used only with code 101 */
   2257 #ifdef UPGRADE_SUPPORT
   2258   if (NULL != rp.response->upgrade_handler)
   2259     return RP_BODY_NONE;
   2260 #endif /* UPGRADE_SUPPORT */
   2261 #endif
   2262 
   2263 #if 0
   2264   /* CONNECT is not supported by MHD */
   2265   /* Successful responses for connect requests are filtered by
   2266    * MHD_queue_response() */
   2267   if ( (MHD_HTTP_MTHD_CONNECT == c->rq.http_mthd) &&
   2268        (2 == rcode / 100) )
   2269     return false; /* Actually pass-through CONNECT is not supported by MHD */
   2270 #endif
   2271 
   2272   /* Reply body headers could be used.
   2273    * Check whether reply body itself must be used. */
   2274 
   2275   if (MHD_HTTP_MTHD_HEAD == c->rq.http_mthd)
   2276     return RP_BODY_HEADERS_ONLY;
   2277 
   2278   if (MHD_HTTP_NOT_MODIFIED == rcode)
   2279     return RP_BODY_HEADERS_ONLY;
   2280 
   2281   /* Reply body must be sent. The body may have zero length, but body size
   2282    * must be indicated by headers ('Content-Length:' or
   2283    * 'Transfer-Encoding: chunked'). */
   2284   return RP_BODY_SEND;
   2285 }
   2286 
   2287 
   2288 /**
   2289  * Setup connection reply properties.
   2290  *
   2291  * Reply properties include presence of reply body, transfer-encoding
   2292  * type and other.
   2293  *
   2294  * @param connection to connection to process
   2295  */
   2296 static void
   2297 setup_reply_properties (struct MHD_Connection *connection)
   2298 {
   2299   struct MHD_Connection *const c = connection; /**< a short alias */
   2300   struct MHD_Response *const r = c->rp.response;  /**< a short alias */
   2301   enum replyBodyUse use_rp_body;
   2302   bool use_chunked;
   2303 
   2304   mhd_assert (NULL != r);
   2305 
   2306   /* ** Adjust reply properties ** */
   2307 
   2308   c->keepalive = keepalive_possible (c);
   2309   use_rp_body = is_reply_body_needed (c, c->rp.responseCode);
   2310   c->rp.props.send_reply_body = (use_rp_body > RP_BODY_HEADERS_ONLY);
   2311   c->rp.props.use_reply_body_headers = (use_rp_body >= RP_BODY_HEADERS_ONLY);
   2312 
   2313 #ifdef UPGRADE_SUPPORT
   2314   mhd_assert ( (NULL == r->upgrade_handler) ||
   2315                (RP_BODY_NONE == use_rp_body) );
   2316 #endif /* UPGRADE_SUPPORT */
   2317 
   2318   if (c->rp.props.use_reply_body_headers)
   2319   {
   2320     if ((MHD_SIZE_UNKNOWN == r->total_size) ||
   2321         (0 != (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)))
   2322     { /* Use chunked reply encoding if possible */
   2323 
   2324       /* Check whether chunked encoding is supported by the client */
   2325       if (! MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver))
   2326         use_chunked = false;
   2327       /* Check whether chunked encoding is allowed for the reply */
   2328       else if (0 != (r->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
   2329                                  | MHD_RF_HTTP_1_0_SERVER)))
   2330         use_chunked = false;
   2331       else
   2332         /* If chunked encoding is supported and allowed, and response size
   2333          * is unknown, use chunked even for non-Keep-Alive connections.
   2334          * See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3
   2335          * Also use chunked if it is enforced by application and supported by
   2336          * the client. */
   2337         use_chunked = true;
   2338     }
   2339     else
   2340       use_chunked = false;
   2341 
   2342     if ( (MHD_SIZE_UNKNOWN == r->total_size) &&
   2343          (! use_chunked) )
   2344     {
   2345       /* End of the stream is indicated by closure */
   2346       c->keepalive = MHD_CONN_MUST_CLOSE;
   2347     }
   2348   }
   2349   else
   2350     use_chunked = false; /* chunked encoding cannot be used without body */
   2351 
   2352   c->rp.props.chunked = use_chunked;
   2353 #ifdef _DEBUG
   2354   c->rp.props.set = true;
   2355 #endif /* _DEBUG */
   2356 }
   2357 
   2358 
   2359 /**
   2360  * Check whether queued response is suitable for @a connection.
   2361  * @param connection to connection to check
   2362  */
   2363 static void
   2364 check_connection_reply (struct MHD_Connection *connection)
   2365 {
   2366   struct MHD_Connection *const c = connection; /**< a short alias */
   2367   struct MHD_Response *const r = c->rp.response;  /**< a short alias */
   2368 
   2369   mhd_assert (c->rp.props.set);
   2370 #ifdef HAVE_MESSAGES
   2371   if ( (! c->rp.props.use_reply_body_headers) &&
   2372        (0 != r->total_size) )
   2373   {
   2374     MHD_DLOG (c->daemon,
   2375               _ ("This reply with response code %u cannot use reply body. "
   2376                  "Non-empty response body is ignored and not used.\n"),
   2377               (unsigned) (c->rp.responseCode));
   2378   }
   2379   if ( (! c->rp.props.use_reply_body_headers) &&
   2380        (0 != (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) )
   2381   {
   2382     MHD_DLOG (c->daemon,
   2383               _ ("This reply with response code %u cannot use reply body. "
   2384                  "Application defined \"Content-Length\" header violates"
   2385                  "HTTP specification.\n"),
   2386               (unsigned) (c->rp.responseCode));
   2387   }
   2388 #else
   2389   (void) c; /* Mute compiler warning */
   2390   (void) r; /* Mute compiler warning */
   2391 #endif
   2392 }
   2393 
   2394 
   2395 /**
   2396  * Append data to the buffer if enough space is available,
   2397  * update position.
   2398  * @param[out] buf the buffer to append data to
   2399  * @param[in,out] ppos the pointer to position in the @a buffer
   2400  * @param buf_size the size of the @a buffer
   2401  * @param append the data to append
   2402  * @param append_size the size of the @a append
   2403  * @return true if data has been added and position has been updated,
   2404  *         false if not enough space is available
   2405  */
   2406 static bool
   2407 buffer_append (char *buf,
   2408                size_t *ppos,
   2409                size_t buf_size,
   2410                const char *append,
   2411                size_t append_size)
   2412 {
   2413   mhd_assert (NULL != buf); /* Mute static analyzer */
   2414   if (buf_size < *ppos + append_size)
   2415     return false;
   2416   memcpy (buf + *ppos, append, append_size);
   2417   *ppos += append_size;
   2418   return true;
   2419 }
   2420 
   2421 
   2422 /**
   2423  * Append static string to the buffer if enough space is available,
   2424  * update position.
   2425  * @param[out] buf the buffer to append data to
   2426  * @param[in,out] ppos the pointer to position in the @a buffer
   2427  * @param buf_size the size of the @a buffer
   2428  * @param str the static string to append
   2429  * @return true if data has been added and position has been updated,
   2430  *         false if not enough space is available
   2431  */
   2432 #define buffer_append_s(buf,ppos,buf_size,str) \
   2433         buffer_append (buf,ppos,buf_size,str, MHD_STATICSTR_LEN_ (str))
   2434 
   2435 
   2436 /**
   2437  * Add user-defined headers from response object to
   2438  * the text buffer.
   2439  *
   2440  * @param buf the buffer to add headers to
   2441  * @param ppos the pointer to the position in the @a buf
   2442  * @param buf_size the size of the @a buf
   2443  * @param response the response
   2444  * @param filter_transf_enc skip "Transfer-Encoding" header if any
   2445  * @param filter_content_len skip "Content-Length" header if any
   2446  * @param add_close add "close" token to the
   2447  *                  "Connection:" header (if any), ignored if no "Connection:"
   2448  *                  header was added by user or if "close" token is already
   2449  *                  present in "Connection:" header
   2450  * @param add_keep_alive add "Keep-Alive" token to the
   2451  *                       "Connection:" header (if any)
   2452  * @return true if succeed,
   2453  *         false if buffer is too small
   2454  */
   2455 static bool
   2456 add_user_headers (char *buf,
   2457                   size_t *ppos,
   2458                   size_t buf_size,
   2459                   struct MHD_Response *response,
   2460                   bool filter_transf_enc,
   2461                   bool filter_content_len,
   2462                   bool add_close,
   2463                   bool add_keep_alive)
   2464 {
   2465   struct MHD_Response *const r = response; /**< a short alias */
   2466   struct MHD_HTTP_Res_Header *hdr; /**< Iterates through User-specified headers */
   2467   size_t el_size; /**< the size of current element to be added to the @a buf */
   2468 
   2469   mhd_assert (! add_close || ! add_keep_alive);
   2470 
   2471   if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))
   2472     filter_transf_enc = false;   /* No such header */
   2473   if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH))
   2474     filter_content_len = false;  /* No such header */
   2475   if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
   2476   {
   2477     add_close = false;          /* No such header */
   2478     add_keep_alive = false;     /* No such header */
   2479   }
   2480   else if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE))
   2481     add_close = false;          /* "close" token was already set */
   2482 
   2483   for (hdr = r->first_header; NULL != hdr; hdr = hdr->next)
   2484   {
   2485     size_t initial_pos = *ppos;
   2486     if (MHD_HEADER_KIND != hdr->kind)
   2487       continue;
   2488     if (filter_transf_enc)
   2489     { /* Need to filter-out "Transfer-Encoding" */
   2490       if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) ==
   2491            hdr->header_size) &&
   2492           (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_TRANSFER_ENCODING,
   2493                                           hdr->header, hdr->header_size)) )
   2494       {
   2495         filter_transf_enc = false; /* There is the only one such header */
   2496         continue; /* Skip "Transfer-Encoding" header */
   2497       }
   2498     }
   2499     if (filter_content_len)
   2500     { /* Need to filter-out "Content-Length" */
   2501       if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) ==
   2502            hdr->header_size) &&
   2503           (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH,
   2504                                           hdr->header, hdr->header_size)) )
   2505       {
   2506         /* Reset filter flag if only one header is allowed */
   2507         filter_transf_enc =
   2508           (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH));
   2509         continue; /* Skip "Content-Length" header */
   2510       }
   2511     }
   2512 
   2513     /* Add user header */
   2514     /* Check available space using subtractions to avoid integer overflow.
   2515        '4' is two colons/space plus the final CRLF. */
   2516     if ( (buf_size - *ppos < 4) ||
   2517          (buf_size - *ppos - 4 < hdr->header_size) ||
   2518          (buf_size - *ppos - 4 - hdr->header_size < hdr->value_size) )
   2519       return false;
   2520     el_size = hdr->header_size + 2 + hdr->value_size + 2;
   2521     memcpy (buf + *ppos, hdr->header, hdr->header_size);
   2522     (*ppos) += hdr->header_size;
   2523     buf[(*ppos)++] = ':';
   2524     buf[(*ppos)++] = ' ';
   2525     if (add_close || add_keep_alive)
   2526     {
   2527       /* "Connection:" header must be always the first one */
   2528       mhd_assert (MHD_str_equal_caseless_n_ (hdr->header, \
   2529                                              MHD_HTTP_HEADER_CONNECTION, \
   2530                                              hdr->header_size));
   2531 
   2532       if (add_close)
   2533       {
   2534         el_size += MHD_STATICSTR_LEN_ ("close, ");
   2535         if (buf_size < initial_pos + el_size)
   2536           return false;
   2537         memcpy (buf + *ppos, "close, ",
   2538                 MHD_STATICSTR_LEN_ ("close, "));
   2539         *ppos += MHD_STATICSTR_LEN_ ("close, ");
   2540       }
   2541       else
   2542       {
   2543         el_size += MHD_STATICSTR_LEN_ ("Keep-Alive, ");
   2544         if (buf_size < initial_pos + el_size)
   2545           return false;
   2546         memcpy (buf + *ppos, "Keep-Alive, ",
   2547                 MHD_STATICSTR_LEN_ ("Keep-Alive, "));
   2548         *ppos += MHD_STATICSTR_LEN_ ("Keep-Alive, ");
   2549       }
   2550       add_close = false;
   2551       add_keep_alive = false;
   2552     }
   2553     if (0 != hdr->value_size)
   2554       memcpy (buf + *ppos, hdr->value, hdr->value_size);
   2555     *ppos += hdr->value_size;
   2556     buf[(*ppos)++] = '\r';
   2557     buf[(*ppos)++] = '\n';
   2558     mhd_assert (initial_pos + el_size == (*ppos));
   2559   }
   2560   return true;
   2561 }
   2562 
   2563 
   2564 /**
   2565  * Allocate the connection's write buffer and fill it with all of the
   2566  * headers from the response.
   2567  * Required headers are added here.
   2568  *
   2569  * @param connection the connection
   2570  * @return #MHD_YES on success, #MHD_NO on failure (out of memory)
   2571  */
   2572 static enum MHD_Result
   2573 build_header_response (struct MHD_Connection *connection)
   2574 {
   2575   struct MHD_Connection *const c = connection; /**< a short alias */
   2576   struct MHD_Response *const r = c->rp.response; /**< a short alias */
   2577   char *buf;                                     /**< the output buffer */
   2578   size_t pos;                                    /**< append offset in the @a buf */
   2579   size_t buf_size;                               /**< the size of the @a buf */
   2580   size_t el_size;                                /**< the size of current element to be added to the @a buf */
   2581   unsigned rcode;                                /**< the response code */
   2582   bool use_conn_close;                           /**< Use "Connection: close" header */
   2583   bool use_conn_k_alive;                         /**< Use "Connection: Keep-Alive" header */
   2584 
   2585   mhd_assert (NULL != r);
   2586 
   2587   /* ** Adjust response properties ** */
   2588   setup_reply_properties (c);
   2589 
   2590   mhd_assert (c->rp.props.set);
   2591   mhd_assert ((MHD_CONN_MUST_CLOSE == c->keepalive) || \
   2592               (MHD_CONN_USE_KEEPALIVE == c->keepalive) || \
   2593               (MHD_CONN_MUST_UPGRADE == c->keepalive));
   2594 #ifdef UPGRADE_SUPPORT
   2595   mhd_assert ((NULL == r->upgrade_handler) || \
   2596               (MHD_CONN_MUST_UPGRADE == c->keepalive));
   2597 #else  /* ! UPGRADE_SUPPORT */
   2598   mhd_assert (MHD_CONN_MUST_UPGRADE != c->keepalive);
   2599 #endif /* ! UPGRADE_SUPPORT */
   2600   mhd_assert ((! c->rp.props.chunked) || c->rp.props.use_reply_body_headers);
   2601   mhd_assert ((! c->rp.props.send_reply_body) || \
   2602               c->rp.props.use_reply_body_headers);
   2603 #ifdef UPGRADE_SUPPORT
   2604   mhd_assert (NULL == r->upgrade_handler || \
   2605               ! c->rp.props.use_reply_body_headers);
   2606 #endif /* UPGRADE_SUPPORT */
   2607 
   2608   check_connection_reply (c);
   2609 
   2610   rcode = (unsigned) c->rp.responseCode;
   2611   if (MHD_CONN_MUST_CLOSE == c->keepalive)
   2612   {
   2613     /* The closure of connection must be always indicated by header
   2614      * to avoid hung connections */
   2615     use_conn_close = true;
   2616     use_conn_k_alive = false;
   2617   }
   2618   else if (MHD_CONN_USE_KEEPALIVE == c->keepalive)
   2619   {
   2620     use_conn_close = false;
   2621     /* Add "Connection: keep-alive" if request is HTTP/1.0 or
   2622      * if reply is HTTP/1.0
   2623      * For HTTP/1.1 add header only if explicitly requested by app
   2624      * (by response flag), as "Keep-Alive" is default for HTTP/1.1. */
   2625     if ((0 != (r->flags & MHD_RF_SEND_KEEP_ALIVE_HEADER)) ||
   2626         (MHD_HTTP_VER_1_0 == c->rq.http_ver) ||
   2627         (0 != (r->flags & MHD_RF_HTTP_1_0_SERVER)))
   2628       use_conn_k_alive = true;
   2629     else
   2630       use_conn_k_alive = false;
   2631   }
   2632   else
   2633   {
   2634     use_conn_close = false;
   2635     use_conn_k_alive = false;
   2636   }
   2637 
   2638   /* ** Actually build the response header ** */
   2639 
   2640   /* Get all space available */
   2641   connection_maximize_write_buffer (c);
   2642   buf = c->write_buffer;
   2643   pos = c->write_buffer_append_offset;
   2644   buf_size = c->write_buffer_size;
   2645   if (0 == buf_size)
   2646     return MHD_NO;
   2647   mhd_assert (NULL != buf);
   2648 
   2649   /* * The status line * */
   2650 
   2651   /* The HTTP version */
   2652   if (! c->rp.responseIcy)
   2653   { /* HTTP reply */
   2654     if (0 == (r->flags & MHD_RF_HTTP_1_0_SERVER))
   2655     { /* HTTP/1.1 reply */
   2656       /* Use HTTP/1.1 responses for HTTP/1.0 clients.
   2657        * See https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */
   2658       if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_1))
   2659         return MHD_NO;
   2660     }
   2661     else
   2662     { /* HTTP/1.0 reply */
   2663       if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_0))
   2664         return MHD_NO;
   2665     }
   2666   }
   2667   else
   2668   { /* ICY reply */
   2669     if (! buffer_append_s (buf, &pos, buf_size, "ICY"))
   2670       return MHD_NO;
   2671   }
   2672 
   2673   /* The response code */
   2674   if (buf_size < pos + 5) /* space + code + space */
   2675     return MHD_NO;
   2676   buf[pos++] = ' ';
   2677   pos += MHD_uint16_to_str ((uint16_t) rcode, buf + pos,
   2678                             buf_size - pos);
   2679   buf[pos++] = ' ';
   2680 
   2681   /* The reason phrase */
   2682   el_size = MHD_get_reason_phrase_len_for (rcode);
   2683   if (0 == el_size)
   2684   {
   2685     if (! buffer_append_s (buf, &pos, buf_size, "Non-Standard Status"))
   2686       return MHD_NO;
   2687   }
   2688   else if (! buffer_append (buf, &pos, buf_size,
   2689                             MHD_get_reason_phrase_for (rcode),
   2690                             el_size))
   2691     return MHD_NO;
   2692 
   2693   /* The linefeed */
   2694   if (buf_size < pos + 2)
   2695     return MHD_NO;
   2696   buf[pos++] = '\r';
   2697   buf[pos++] = '\n';
   2698 
   2699   /* * The headers * */
   2700 
   2701   /* Main automatic headers */
   2702 
   2703   /* The "Date:" header */
   2704   if ( (0 == (r->flags_auto & MHD_RAF_HAS_DATE_HDR)) &&
   2705        (0 == (c->daemon->options & MHD_USE_SUPPRESS_DATE_NO_CLOCK)) )
   2706   {
   2707     /* Additional byte for unused zero-termination */
   2708     if (buf_size < pos + 38)
   2709       return MHD_NO;
   2710     if (get_date_header (buf + pos))
   2711       pos += 37;
   2712   }
   2713   /* The "Connection:" header */
   2714   mhd_assert (! use_conn_close || ! use_conn_k_alive);
   2715   mhd_assert (! use_conn_k_alive || ! use_conn_close);
   2716   if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
   2717   {
   2718     if (use_conn_close)
   2719     {
   2720       if (! buffer_append_s (buf, &pos, buf_size,
   2721                              MHD_HTTP_HEADER_CONNECTION ": close\r\n"))
   2722         return MHD_NO;
   2723     }
   2724     else if (use_conn_k_alive)
   2725     {
   2726       if (! buffer_append_s (buf, &pos, buf_size,
   2727                              MHD_HTTP_HEADER_CONNECTION ": Keep-Alive\r\n"))
   2728         return MHD_NO;
   2729     }
   2730   }
   2731 
   2732   /* User-defined headers */
   2733 
   2734   if (! add_user_headers (buf, &pos, buf_size, r,
   2735                           ! c->rp.props.chunked,
   2736                           (! c->rp.props.use_reply_body_headers) &&
   2737                           (0 ==
   2738                            (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)),
   2739                           use_conn_close,
   2740                           use_conn_k_alive))
   2741     return MHD_NO;
   2742 
   2743   /* Other automatic headers */
   2744 
   2745   if ( (c->rp.props.use_reply_body_headers) &&
   2746        (0 == (r->flags & MHD_RF_HEAD_ONLY_RESPONSE)) )
   2747   {
   2748     /* Body-specific headers */
   2749 
   2750     if (c->rp.props.chunked)
   2751     { /* Chunked encoding is used */
   2752       if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))
   2753       { /* No chunked encoding header set by user */
   2754         if (! buffer_append_s (buf, &pos, buf_size,
   2755                                MHD_HTTP_HEADER_TRANSFER_ENCODING ": " \
   2756                                "chunked\r\n"))
   2757           return MHD_NO;
   2758       }
   2759     }
   2760     else /* Chunked encoding is not used */
   2761     {
   2762       if (MHD_SIZE_UNKNOWN != r->total_size)
   2763       { /* The size is known */
   2764         if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH))
   2765         { /* The response does not have "Content-Length" header */
   2766           if (! buffer_append_s (buf, &pos, buf_size,
   2767                                  MHD_HTTP_HEADER_CONTENT_LENGTH ": "))
   2768             return MHD_NO;
   2769           el_size = MHD_uint64_to_str (r->total_size, buf + pos,
   2770                                        buf_size - pos);
   2771           if (0 == el_size)
   2772             return MHD_NO;
   2773           pos += el_size;
   2774 
   2775           if (buf_size < pos + 2)
   2776             return MHD_NO;
   2777           buf[pos++] = '\r';
   2778           buf[pos++] = '\n';
   2779         }
   2780       }
   2781     }
   2782   }
   2783 
   2784   /* * Header termination * */
   2785   if (buf_size < pos + 2)
   2786     return MHD_NO;
   2787   buf[pos++] = '\r';
   2788   buf[pos++] = '\n';
   2789 
   2790   c->write_buffer_append_offset = pos;
   2791   return MHD_YES;
   2792 }
   2793 
   2794 
   2795 /**
   2796  * Allocate the connection's write buffer (if necessary) and fill it
   2797  * with response footers.
   2798  * Works only for chunked responses as other responses do not need
   2799  * and do not support any kind of footers.
   2800  *
   2801  * @param connection the connection
   2802  * @return #MHD_YES on success, #MHD_NO on failure (out of memory)
   2803  */
   2804 static enum MHD_Result
   2805 build_connection_chunked_response_footer (struct MHD_Connection *connection)
   2806 {
   2807   char *buf;           /**< the buffer to write footers to */
   2808   size_t buf_size;     /**< the size of the @a buf */
   2809   size_t used_size;    /**< the used size of the @a buf */
   2810   struct MHD_Connection *const c = connection; /**< a short alias */
   2811   struct MHD_HTTP_Res_Header *pos;
   2812 
   2813   mhd_assert (connection->rp.props.chunked);
   2814   /* TODO: allow combining of the final footer with the last chunk,
   2815    * modify the next assert. */
   2816   mhd_assert (MHD_CONNECTION_CHUNKED_BODY_SENT == connection->state);
   2817   mhd_assert (NULL != c->rp.response);
   2818 
   2819   buf_size = connection_maximize_write_buffer (c);
   2820   /* '5' is the minimal size of chunked footer ("0\r\n\r\n") */
   2821   if (buf_size < 5)
   2822     return MHD_NO;
   2823   mhd_assert (NULL != c->write_buffer);
   2824   buf = c->write_buffer + c->write_buffer_append_offset;
   2825   mhd_assert (NULL != buf);
   2826   used_size = 0;
   2827   buf[used_size++] = '0';
   2828   buf[used_size++] = '\r';
   2829   buf[used_size++] = '\n';
   2830 
   2831   for (pos = c->rp.response->first_header; NULL != pos; pos = pos->next)
   2832   {
   2833     if (MHD_FOOTER_KIND == pos->kind)
   2834     {
   2835 #ifdef _DEBUG
   2836       size_t new_used_size; /* resulting size with this header */
   2837 #endif /* _DEBUG */
   2838       /* '4' is colon, space, linefeeds */
   2839       /* Check available space using subtractions to avoid integer overflow. */
   2840       if ( (buf_size - used_size < 4) ||
   2841            (buf_size - used_size - 4 < pos->header_size) ||
   2842            (buf_size - used_size - 4 - pos->header_size < pos->value_size) )
   2843         return MHD_NO;
   2844 #ifdef _DEBUG
   2845       new_used_size = used_size + pos->header_size + pos->value_size + 4;
   2846 #endif /* _DEBUG */
   2847       memcpy (buf + used_size, pos->header, pos->header_size);
   2848       used_size += pos->header_size;
   2849       buf[used_size++] = ':';
   2850       buf[used_size++] = ' ';
   2851       memcpy (buf + used_size, pos->value, pos->value_size);
   2852       used_size += pos->value_size;
   2853       buf[used_size++] = '\r';
   2854       buf[used_size++] = '\n';
   2855 #ifdef _DEBUG
   2856       mhd_assert (used_size == new_used_size);
   2857 #endif /* _DEBUG */
   2858     }
   2859   }
   2860   if (used_size + 2 > buf_size)
   2861     return MHD_NO;
   2862   buf[used_size++] = '\r';
   2863   buf[used_size++] = '\n';
   2864 
   2865   c->write_buffer_append_offset += used_size;
   2866   mhd_assert (c->write_buffer_append_offset <= c->write_buffer_size);
   2867 
   2868   return MHD_YES;
   2869 }
   2870 
   2871 
   2872 /**
   2873  * We encountered an error processing the request.
   2874  * Handle it properly by stopping to read data
   2875  * and sending the indicated response code and message.
   2876  *
   2877  * @param connection the connection
   2878  * @param status_code the response code to send (400, 413 or 414)
   2879  * @param message the error message to send
   2880  * @param message_len the length of the @a message
   2881  * @param header_name the name of the header, malloc()ed by the caller,
   2882  *                    free() by this function, optional, can be NULL
   2883  * @param header_name_len the length of the @a header_name
   2884  * @param header_value the value of the header, malloc()ed by the caller,
   2885  *                     free() by this function, optional, can be NULL
   2886  * @param header_value_len the length of the @a header_value
   2887  */
   2888 static void
   2889 transmit_error_response_len (struct MHD_Connection *connection,
   2890                              unsigned int status_code,
   2891                              const char *message,
   2892                              size_t message_len,
   2893                              char *header_name,
   2894                              size_t header_name_len,
   2895                              char *header_value,
   2896                              size_t header_value_len)
   2897 {
   2898   struct MHD_Response *response;
   2899   enum MHD_Result iret;
   2900 
   2901   mhd_assert (! connection->stop_with_error); /* Do not send error twice */
   2902   if (connection->stop_with_error)
   2903   { /* Should not happen */
   2904     if (MHD_CONNECTION_CLOSED > connection->state)
   2905       connection->state = MHD_CONNECTION_CLOSED;
   2906     free (header_name);
   2907     free (header_value);
   2908     return;
   2909   }
   2910   connection->stop_with_error = true;
   2911   connection->discard_request = true;
   2912 #ifdef HAVE_MESSAGES
   2913   MHD_DLOG (connection->daemon,
   2914             _ ("Error processing request (HTTP response code is %u ('%s')). " \
   2915                "Closing connection.\n"),
   2916             status_code,
   2917             message);
   2918 #endif
   2919   if (MHD_CONNECTION_START_REPLY < connection->state)
   2920   {
   2921 #ifdef HAVE_MESSAGES
   2922     MHD_DLOG (connection->daemon,
   2923               _ ("Too late to send an error response, " \
   2924                  "response is being sent already.\n"),
   2925               status_code,
   2926               message);
   2927 #endif
   2928     CONNECTION_CLOSE_ERROR (connection,
   2929                             _ ("Too late for error response."));
   2930     free (header_name);
   2931     free (header_value);
   2932     return;
   2933   }
   2934   /* TODO: remove when special error queue function is implemented */
   2935   connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
   2936   if (0 != connection->read_buffer_size)
   2937   {
   2938     /* Read buffer is not needed anymore, discard it
   2939      * to free some space for error response. */
   2940     MHD_pool_deallocate (connection->pool,
   2941                          connection->read_buffer,
   2942                          connection->read_buffer_size);
   2943     connection->read_buffer = NULL;
   2944     connection->read_buffer_size = 0;
   2945     connection->read_buffer_offset = 0;
   2946   }
   2947   if (NULL != connection->rp.response)
   2948   {
   2949     MHD_destroy_response (connection->rp.response);
   2950     connection->rp.response = NULL;
   2951   }
   2952   response = MHD_create_response_from_buffer_static (message_len,
   2953                                                      message);
   2954   if (NULL == response)
   2955   {
   2956 #ifdef HAVE_MESSAGES
   2957     MHD_DLOG (connection->daemon,
   2958               _ ("Failed to create error response.\n"),
   2959               status_code,
   2960               message);
   2961 #endif
   2962     /* can't even send a reply, at least close the connection */
   2963     connection->state = MHD_CONNECTION_CLOSED;
   2964     free (header_name);
   2965     free (header_value);
   2966     return;
   2967   }
   2968   mhd_assert ((0 == header_name_len) || (NULL != header_name));
   2969   mhd_assert ((NULL == header_name) || (0 != header_name_len));
   2970   mhd_assert ((0 == header_value_len) || (NULL != header_value));
   2971   mhd_assert ((NULL == header_value) || (0 != header_value_len));
   2972   mhd_assert ((NULL == header_name) || (NULL != header_value));
   2973   mhd_assert ((NULL != header_value) || (NULL == header_name));
   2974   if (NULL != header_name)
   2975   {
   2976     iret = MHD_add_response_entry_no_alloc_ (response,
   2977                                              MHD_HEADER_KIND,
   2978                                              header_name, header_name_len,
   2979                                              header_value, header_value_len);
   2980     if (MHD_NO == iret)
   2981     {
   2982       free (header_name);
   2983       free (header_value);
   2984     }
   2985   }
   2986   else
   2987     iret = MHD_YES;
   2988 
   2989   if (MHD_NO != iret)
   2990   {
   2991     bool before = connection->in_access_handler;
   2992 
   2993     /* Fake the flag for the internal call */
   2994     connection->in_access_handler = true;
   2995     iret = MHD_queue_response (connection,
   2996                                status_code,
   2997                                response);
   2998     connection->in_access_handler = before;
   2999   }
   3000   MHD_destroy_response (response);
   3001   if (MHD_NO == iret)
   3002   {
   3003     /* can't even send a reply, at least close the connection */
   3004     CONNECTION_CLOSE_ERROR (connection,
   3005                             _ ("Closing connection " \
   3006                                "(failed to queue error response)."));
   3007     return;
   3008   }
   3009   mhd_assert (NULL != connection->rp.response);
   3010   /* Do not reuse this connection. */
   3011   connection->keepalive = MHD_CONN_MUST_CLOSE;
   3012   if (MHD_NO == build_header_response (connection))
   3013   {
   3014     /* No memory. Release everything. */
   3015     connection->rq.version = NULL;
   3016     connection->rq.method = NULL;
   3017     connection->rq.url = NULL;
   3018     connection->rq.url_len = 0;
   3019     connection->rq.url_for_callback = NULL;
   3020     connection->rq.headers_received = NULL;
   3021     connection->rq.headers_received_tail = NULL;
   3022     connection->write_buffer = NULL;
   3023     connection->write_buffer_size = 0;
   3024     connection->write_buffer_send_offset = 0;
   3025     connection->write_buffer_append_offset = 0;
   3026     connection->read_buffer
   3027       = MHD_pool_reset (connection->pool,
   3028                         NULL,
   3029                         0,
   3030                         0);
   3031     connection->read_buffer_size = 0;
   3032 
   3033     /* Retry with empty buffer */
   3034     if (MHD_NO == build_header_response (connection))
   3035     {
   3036       CONNECTION_CLOSE_ERROR (connection,
   3037                               _ ("Closing connection " \
   3038                                  "(failed to create error response header)."));
   3039       return;
   3040     }
   3041   }
   3042   connection->state = MHD_CONNECTION_HEADERS_SENDING;
   3043 }
   3044 
   3045 
   3046 /**
   3047  * Transmit static string as error response
   3048  */
   3049 #ifdef HAVE_MESSAGES
   3050 #  define transmit_error_response_static(c, code, msg) \
   3051         transmit_error_response_len (c, code, \
   3052                                      msg, MHD_STATICSTR_LEN_ (msg), \
   3053                                      NULL, 0, NULL, 0)
   3054 #else  /* ! HAVE_MESSAGES */
   3055 #  define transmit_error_response_static(c, code, msg) \
   3056         transmit_error_response_len (c, code, \
   3057                                      "", 0, \
   3058                                      NULL, 0, NULL, 0)
   3059 #endif /* ! HAVE_MESSAGES */
   3060 
   3061 /**
   3062  * Transmit static string as error response and add specified header
   3063  */
   3064 #ifdef HAVE_MESSAGES
   3065 #  define transmit_error_response_header(c, code, m, hd_n, hd_n_l, hd_v, hd_v_l) \
   3066         transmit_error_response_len (c, code, \
   3067                                      m, MHD_STATICSTR_LEN_ (m), \
   3068                                      hd_n, hd_n_l, \
   3069                                      hd_v, hd_v_l)
   3070 #else  /* ! HAVE_MESSAGES */
   3071 #  define transmit_error_response_header(c, code, m, hd_n, hd_n_l, hd_v, hd_v_l) \
   3072         transmit_error_response_len (c, code, \
   3073                                      "", 0, \
   3074                                      hd_n, hd_n_l, \
   3075                                      hd_v, hd_v_l)
   3076 #endif /* ! HAVE_MESSAGES */
   3077 
   3078 
   3079 /**
   3080  * Check whether the read buffer has any upload body data ready to
   3081  * be processed.
   3082  * Must be called only when connection is in MHD_CONNECTION_BODY_RECEIVING
   3083  * state.
   3084  *
   3085  * @param c the connection to check
   3086  * @return 'true' if upload body data is already in the read buffer,
   3087  *         'false' if no upload data is received and not processed.
   3088  */
   3089 static bool
   3090 has_unprocessed_upload_body_data_in_buffer (struct MHD_Connection *c)
   3091 {
   3092   mhd_assert (MHD_CONNECTION_BODY_RECEIVING == c->state);
   3093   if (! c->rq.have_chunked_upload)
   3094     return 0 != c->read_buffer_offset;
   3095 
   3096   /* Chunked upload */
   3097   mhd_assert (0 != c->rq.remaining_upload_size); /* Must not be possible in MHD_CONNECTION_BODY_RECEIVING state */
   3098   if (c->rq.current_chunk_offset == c->rq.current_chunk_size)
   3099   {
   3100     /* 0 == c->rq.current_chunk_size: Waiting the chunk size (chunk header).
   3101        0 != c->rq.current_chunk_size: Waiting for chunk-closing CRLF. */
   3102     return false;
   3103   }
   3104   return 0 != c->read_buffer_offset; /* Chunk payload data in the read buffer */
   3105 }
   3106 
   3107 
   3108 /**
   3109  * The stage of input data processing.
   3110  * Used for out-of-memory (in the pool) handling.
   3111  */
   3112 enum MHD_ProcRecvDataStage
   3113 {
   3114   MHD_PROC_RECV_INIT,        /**< No data HTTP request data have been processed yet */
   3115   MHD_PROC_RECV_METHOD,      /**< Processing/receiving the request HTTP method */
   3116   MHD_PROC_RECV_URI,         /**< Processing/receiving the request URI */
   3117   MHD_PROC_RECV_HTTPVER,     /**< Processing/receiving the request HTTP version string */
   3118   MHD_PROC_RECV_HEADERS,     /**< Processing/receiving the request HTTP headers */
   3119   MHD_PROC_RECV_COOKIE,      /**< Processing the received request cookie header */
   3120   MHD_PROC_RECV_BODY_NORMAL, /**< Processing/receiving the request non-chunked body */
   3121   MHD_PROC_RECV_BODY_CHUNKED,/**< Processing/receiving the request chunked body */
   3122   MHD_PROC_RECV_FOOTERS      /**< Processing/receiving the request footers */
   3123 };
   3124 
   3125 
   3126 #ifndef MHD_MAX_REASONABLE_HEADERS_SIZE_
   3127 /**
   3128  * A reasonable headers size (excluding request line) that should be sufficient
   3129  * for most requests.
   3130  * If incoming data buffer free space is not enough to process the complete
   3131  * header (the request line and all headers) and the headers size is larger than
   3132  * this size then the status code 431 "Request Header Fields Too Large" is
   3133  * returned to the client.
   3134  * The larger headers are processed by MHD if enough space is available.
   3135  */
   3136 #  define MHD_MAX_REASONABLE_HEADERS_SIZE_ (6 * 1024)
   3137 #endif /* ! MHD_MAX_REASONABLE_HEADERS_SIZE_ */
   3138 
   3139 #ifndef MHD_MAX_REASONABLE_REQ_TARGET_SIZE_
   3140 /**
   3141  * A reasonable request target (the request URI) size that should be sufficient
   3142  * for most requests.
   3143  * If incoming data buffer free space is not enough to process the complete
   3144  * header (the request line and all headers) and the request target size is
   3145  * larger than this size then the status code 414 "URI Too Long" is
   3146  * returned to the client.
   3147  * The larger request targets are processed by MHD if enough space is available.
   3148  * The value chosen according to RFC 9112 Section 3, paragraph 5
   3149  */
   3150 #  define MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ 8000
   3151 #endif /* ! MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ */
   3152 
   3153 #ifndef MHD_MIN_REASONABLE_HEADERS_SIZE_
   3154 /**
   3155  * A reasonable headers size (excluding request line) that should be sufficient
   3156  * for basic simple requests.
   3157  * When no space left in the receiving buffer try to avoid replying with
   3158  * the status code 431 "Request Header Fields Too Large" if headers size
   3159  * is smaller then this value.
   3160  */
   3161 #  define MHD_MIN_REASONABLE_HEADERS_SIZE_ 26
   3162 #endif /* ! MHD_MIN_REASONABLE_HEADERS_SIZE_ */
   3163 
   3164 #ifndef MHD_MIN_REASONABLE_REQ_TARGET_SIZE_
   3165 /**
   3166  * A reasonable request target (the request URI) size that should be sufficient
   3167  * for basic simple requests.
   3168  * When no space left in the receiving buffer try to avoid replying with
   3169  * the status code 414 "URI Too Long" if the request target size is smaller then
   3170  * this value.
   3171  */
   3172 #  define MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ 40
   3173 #endif /* ! MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ */
   3174 
   3175 #ifndef MHD_MIN_REASONABLE_REQ_METHOD_SIZE_
   3176 /**
   3177  * A reasonable request method string size that should be sufficient
   3178  * for basic simple requests.
   3179  * When no space left in the receiving buffer try to avoid replying with
   3180  * the status code 501 "Not Implemented" if the request method size is
   3181  * smaller then this value.
   3182  */
   3183 #  define MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ 16
   3184 #endif /* ! MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ */
   3185 
   3186 #ifndef MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_
   3187 /**
   3188  * A reasonable minimal chunk line length.
   3189  * When no space left in the receiving buffer reply with 413 "Content Too Large"
   3190  * if the chunk line length is larger than this value.
   3191  */
   3192 #  define MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ 4
   3193 #endif /* ! MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ */
   3194 
   3195 
   3196 /**
   3197  * Select the HTTP error status code for "out of receive buffer space" error.
   3198  * @param c the connection to process
   3199  * @param stage the current stage of request receiving
   3200  * @param add_element the optional pointer to the element failed to be processed
   3201  *                    or added, the meaning of the element depends on
   3202  *                    the @a stage. Could be not zero-terminated and can
   3203  *                    contain binary zeros. Can be NULL.
   3204  * @param add_element_size the size of the @a add_element
   3205  * @return the HTTP error code to use in the error reply
   3206  */
   3207 static unsigned int
   3208 get_no_space_err_status_code (struct MHD_Connection *c,
   3209                               enum MHD_ProcRecvDataStage stage,
   3210                               const char *add_element,
   3211                               size_t add_element_size)
   3212 {
   3213   size_t method_size;
   3214   size_t uri_size;
   3215   size_t opt_headers_size;
   3216   size_t host_field_line_size;
   3217 
   3218   mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED < c->state);
   3219   mhd_assert (MHD_PROC_RECV_HEADERS <= stage);
   3220   mhd_assert ((0 == add_element_size) || (NULL != add_element));
   3221 
   3222   if (MHD_CONNECTION_HEADERS_RECEIVED > c->state)
   3223   {
   3224     mhd_assert (NULL != c->rq.field_lines.start);
   3225     opt_headers_size =
   3226       (size_t) ((c->read_buffer + c->read_buffer_offset)
   3227                 - c->rq.field_lines.start);
   3228   }
   3229   else
   3230     opt_headers_size = c->rq.field_lines.size;
   3231 
   3232   /* The read buffer is fully used by the request line, the field lines
   3233      (headers) and internal information.
   3234      The return status code works as a suggestion for the client to reduce
   3235      one of the request elements. */
   3236 
   3237   if ((MHD_PROC_RECV_BODY_CHUNKED == stage) &&
   3238       (MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ < add_element_size))
   3239   {
   3240     /* Request could be re-tried easily with smaller chunk sizes */
   3241     return MHD_HTTP_CONTENT_TOO_LARGE;
   3242   }
   3243 
   3244   host_field_line_size = 0;
   3245   /* The "Host:" field line is mandatory.
   3246      The total size of the field lines (headers) cannot be smaller than
   3247      the size of the "Host:" field line. */
   3248   if ((MHD_PROC_RECV_HEADERS == stage)
   3249       && (0 != add_element_size))
   3250   {
   3251     static const size_t header_host_key_len =
   3252       MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST);
   3253     const bool is_host_header =
   3254       (header_host_key_len + 1 <= add_element_size)
   3255       && ( (0 == add_element[header_host_key_len])
   3256            || (':' == add_element[header_host_key_len]) )
   3257       && MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_HOST,
   3258                                         add_element,
   3259                                         header_host_key_len);
   3260     if (is_host_header)
   3261     {
   3262       const bool is_parsed = ! (
   3263         (MHD_CONNECTION_HEADERS_RECEIVED > c->state) &&
   3264         (add_element_size == c->read_buffer_offset) &&
   3265         (c->read_buffer == add_element) );
   3266       size_t actual_element_size;
   3267 
   3268       mhd_assert (! is_parsed || (0 == add_element[header_host_key_len]));
   3269       /* The actual size should be larger due to CRLF or LF chars,
   3270          however the exact termination sequence is not known here and
   3271          as perfect precision is not required, to simplify the code
   3272          assume the minimal length. */
   3273       if (is_parsed)
   3274         actual_element_size = add_element_size + 1;  /* "1" for LF */
   3275       else
   3276         actual_element_size = add_element_size;
   3277 
   3278       host_field_line_size = actual_element_size;
   3279       mhd_assert (opt_headers_size >= actual_element_size);
   3280       opt_headers_size -= actual_element_size;
   3281     }
   3282   }
   3283   if (0 == host_field_line_size)
   3284   {
   3285     static const size_t host_field_name_len =
   3286       MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST);
   3287     size_t host_field_name_value_len;
   3288     if (MHD_NO != MHD_lookup_connection_value_n (c,
   3289                                                  MHD_HEADER_KIND,
   3290                                                  MHD_HTTP_HEADER_HOST,
   3291                                                  host_field_name_len,
   3292                                                  NULL,
   3293                                                  &host_field_name_value_len))
   3294     {
   3295       /* Calculate the minimal size of the field line: no space between
   3296          colon and the field value, line terminated by LR */
   3297       host_field_line_size =
   3298         host_field_name_len + host_field_name_value_len + 2; /* "2" for ':' and LF */
   3299 
   3300       /* The "Host:" field could be added by application */
   3301       if (opt_headers_size >= host_field_line_size)
   3302       {
   3303         opt_headers_size -= host_field_line_size;
   3304         /* Take into account typical space after colon and CR at the end of the line */
   3305         if (opt_headers_size >= 2)
   3306           opt_headers_size -= 2;
   3307       }
   3308       else
   3309         host_field_line_size = 0; /* No "Host:" field line set by the client */
   3310     }
   3311   }
   3312 
   3313   uri_size = c->rq.req_target_len;
   3314   if (MHD_HTTP_MTHD_OTHER != c->rq.http_mthd)
   3315     method_size = 0; /* Do not recommend shorter request method */
   3316   else
   3317   {
   3318     mhd_assert (NULL != c->rq.method);
   3319     method_size = strlen (c->rq.method);
   3320   }
   3321 
   3322   if ((size_t) MHD_MAX_REASONABLE_HEADERS_SIZE_ < opt_headers_size)
   3323   {
   3324     /* Typically the easiest way to reduce request header size is
   3325        a removal of some optional headers. */
   3326     if (opt_headers_size > (uri_size / 8))
   3327     {
   3328       if ((opt_headers_size / 2) > method_size)
   3329         return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
   3330       else
   3331         return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */
   3332     }
   3333     else
   3334     { /* Request target is MUCH larger than headers */
   3335       if ((uri_size / 16) > method_size)
   3336         return MHD_HTTP_URI_TOO_LONG;
   3337       else
   3338         return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */
   3339     }
   3340   }
   3341   if ((size_t) MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ < uri_size)
   3342   {
   3343     /* If request target size if larger than maximum reasonable size
   3344        recommend client to reduce the request target size (length). */
   3345     if ((uri_size / 16) > method_size)
   3346       return MHD_HTTP_URI_TOO_LONG;     /* Request target is MUCH larger than headers */
   3347     else
   3348       return MHD_HTTP_NOT_IMPLEMENTED;  /* The length of the HTTP request method is unreasonably large */
   3349   }
   3350 
   3351   /* The read buffer is too small to handle reasonably large requests */
   3352 
   3353   if ((size_t) MHD_MIN_REASONABLE_HEADERS_SIZE_ < opt_headers_size)
   3354   {
   3355     /* Recommend application to retry with minimal headers */
   3356     if ((opt_headers_size * 4) > uri_size)
   3357     {
   3358       if (opt_headers_size > method_size)
   3359         return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
   3360       else
   3361         return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */
   3362     }
   3363     else
   3364     { /* Request target is significantly larger than headers */
   3365       if (uri_size > method_size * 4)
   3366         return MHD_HTTP_URI_TOO_LONG;
   3367       else
   3368         return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */
   3369     }
   3370   }
   3371   if ((size_t) MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ < uri_size)
   3372   {
   3373     /* Recommend application to retry with a shorter request target */
   3374     if (uri_size > method_size * 4)
   3375       return MHD_HTTP_URI_TOO_LONG;
   3376     else
   3377       return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */
   3378   }
   3379 
   3380   if ((size_t) MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ < method_size)
   3381   {
   3382     /* The request target (URI) and headers are (reasonably) very small.
   3383        Some non-standard long request method is used. */
   3384     /* The last resort response as it means "the method is not supported
   3385        by the server for any URI". */
   3386     return MHD_HTTP_NOT_IMPLEMENTED;
   3387   }
   3388 
   3389   /* The almost impossible situation: all elements are small, but cannot
   3390      fit the buffer. The application set the buffer size to
   3391      critically low value? */
   3392 
   3393   if ((1 < opt_headers_size) || (1 < uri_size))
   3394   {
   3395     if (opt_headers_size >= uri_size)
   3396       return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
   3397     else
   3398       return MHD_HTTP_URI_TOO_LONG;
   3399   }
   3400 
   3401   /* Nothing to reduce in the request.
   3402      Reply with some status. */
   3403   if (0 != host_field_line_size)
   3404     return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
   3405 
   3406   return MHD_HTTP_URI_TOO_LONG;
   3407 }
   3408 
   3409 
   3410 /**
   3411  * Send error reply when receive buffer space exhausted while receiving or
   3412  * storing the request headers
   3413  * @param c the connection to handle
   3414  * @param add_header the optional pointer to the current header string being
   3415  *                   processed or the header failed to be added.
   3416  *                   Could be not zero-terminated and can contain binary zeros.
   3417  *                   Can be NULL.
   3418  * @param add_header_size the size of the @a add_header
   3419  */
   3420 static void
   3421 handle_req_headers_no_space (struct MHD_Connection *c,
   3422                              const char *add_header,
   3423                              size_t add_header_size)
   3424 {
   3425   unsigned int err_code;
   3426 
   3427   err_code = get_no_space_err_status_code (c,
   3428                                            MHD_PROC_RECV_HEADERS,
   3429                                            add_header,
   3430                                            add_header_size);
   3431   transmit_error_response_static (c,
   3432                                   err_code,
   3433                                   ERR_MSG_REQUEST_HEADER_TOO_BIG);
   3434 }
   3435 
   3436 
   3437 #ifdef COOKIE_SUPPORT
   3438 /**
   3439  * Send error reply when the pool has no space to store 'cookie' header
   3440  * parsing results.
   3441  * @param c the connection to handle
   3442  */
   3443 static void
   3444 handle_req_cookie_no_space (struct MHD_Connection *c)
   3445 {
   3446   unsigned int err_code;
   3447 
   3448   err_code = get_no_space_err_status_code (c,
   3449                                            MHD_PROC_RECV_COOKIE,
   3450                                            NULL,
   3451                                            0);
   3452   transmit_error_response_static (c,
   3453                                   err_code,
   3454                                   ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG);
   3455 }
   3456 
   3457 
   3458 #endif /* COOKIE_SUPPORT */
   3459 
   3460 
   3461 /**
   3462  * Send error reply when receive buffer space exhausted while receiving
   3463  * the chunk size line.
   3464  * @param c the connection to handle
   3465  * @param add_header the optional pointer to the partially received
   3466  *                   the current chunk size line.
   3467  *                   Could be not zero-terminated and can contain binary zeros.
   3468  *                   Can be NULL.
   3469  * @param add_header_size the size of the @a add_header
   3470  */
   3471 static void
   3472 handle_req_chunk_size_line_no_space (struct MHD_Connection *c,
   3473                                      const char *chunk_size_line,
   3474                                      size_t chunk_size_line_size)
   3475 {
   3476   unsigned int err_code;
   3477 
   3478   if (NULL != chunk_size_line)
   3479   {
   3480     const char *semicol;
   3481     /* Check for chunk extension */
   3482     semicol = memchr (chunk_size_line, ';', chunk_size_line_size);
   3483     if (NULL != semicol)
   3484     { /* Chunk extension present. It could be removed without any loss of the
   3485          details of the request. */
   3486       transmit_error_response_static (c,
   3487                                       MHD_HTTP_CONTENT_TOO_LARGE,
   3488                                       ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG);
   3489       return; /* The error response has been queued already */
   3490     }
   3491   }
   3492   err_code = get_no_space_err_status_code (c,
   3493                                            MHD_PROC_RECV_BODY_CHUNKED,
   3494                                            chunk_size_line,
   3495                                            chunk_size_line_size);
   3496   transmit_error_response_static (c,
   3497                                   err_code,
   3498                                   ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG);
   3499 }
   3500 
   3501 
   3502 /**
   3503  * Send error reply when receive buffer space exhausted while receiving or
   3504  * storing the request footers (for chunked requests).
   3505  * @param c the connection to handle
   3506  * @param add_footer the optional pointer to the current footer string being
   3507  *                   processed or the footer failed to be added.
   3508  *                   Could be not zero-terminated and can contain binary zeros.
   3509  *                   Can be NULL.
   3510  * @param add_footer_size the size of the @a add_footer
   3511  */
   3512 static void
   3513 handle_req_footers_no_space (struct MHD_Connection *c,
   3514                              const char *add_footer,
   3515                              size_t add_footer_size)
   3516 {
   3517   (void) add_footer; (void) add_footer_size; /* Unused */
   3518   mhd_assert (c->rq.have_chunked_upload);
   3519 
   3520   /* Footers should be optional */
   3521   transmit_error_response_static (c,
   3522                                   MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
   3523                                   ERR_MSG_REQUEST_FOOTER_TOO_BIG);
   3524 }
   3525 
   3526 
   3527 /**
   3528  * Handle situation with read buffer exhaustion.
   3529  * Must be called when no more space left in the read buffer, no more
   3530  * space left in the memory pool to grow the read buffer, but more data
   3531  * need to be received from the client.
   3532  * Could be called when the result of received data processing cannot be
   3533  * stored in the memory pool (like some header).
   3534  * @param c the connection to process
   3535  * @param stage the receive stage where the exhaustion happens.
   3536  */
   3537 static void
   3538 handle_recv_no_space (struct MHD_Connection *c,
   3539                       enum MHD_ProcRecvDataStage stage)
   3540 {
   3541   mhd_assert (MHD_PROC_RECV_INIT <= stage);
   3542   mhd_assert (MHD_PROC_RECV_FOOTERS >= stage);
   3543   mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED > c->state);
   3544   mhd_assert ((MHD_PROC_RECV_INIT != stage) || \
   3545               (MHD_CONNECTION_INIT == c->state));
   3546   mhd_assert ((MHD_PROC_RECV_METHOD != stage) || \
   3547               (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state));
   3548   mhd_assert ((MHD_PROC_RECV_URI != stage) || \
   3549               (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state));
   3550   mhd_assert ((MHD_PROC_RECV_HTTPVER != stage) || \
   3551               (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state));
   3552   mhd_assert ((MHD_PROC_RECV_HEADERS != stage) || \
   3553               (MHD_CONNECTION_REQ_HEADERS_RECEIVING == c->state));
   3554   mhd_assert (MHD_PROC_RECV_COOKIE != stage); /* handle_req_cookie_no_space() must be called directly */
   3555   mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \
   3556               (MHD_CONNECTION_BODY_RECEIVING == c->state));
   3557   mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \
   3558               (MHD_CONNECTION_BODY_RECEIVING == c->state));
   3559   mhd_assert ((MHD_PROC_RECV_FOOTERS != stage) || \
   3560               (MHD_CONNECTION_FOOTERS_RECEIVING == c->state));
   3561   mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \
   3562               (! c->rq.have_chunked_upload));
   3563   mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \
   3564               (c->rq.have_chunked_upload));
   3565   switch (stage)
   3566   {
   3567   case MHD_PROC_RECV_INIT:
   3568   case MHD_PROC_RECV_METHOD:
   3569     /* Some data has been received, but it is not clear yet whether
   3570      * the received data is an valid HTTP request */
   3571     connection_close_error (c,
   3572                             _ ("No space left in the read buffer when " \
   3573                                "receiving the initial part of " \
   3574                                "the request line."));
   3575     return;
   3576   case MHD_PROC_RECV_URI:
   3577   case MHD_PROC_RECV_HTTPVER:
   3578     /* Some data has been received, but the request line is incomplete */
   3579     mhd_assert (MHD_HTTP_MTHD_NO_METHOD != c->rq.http_mthd);
   3580     mhd_assert (MHD_HTTP_VER_UNKNOWN == c->rq.http_ver);
   3581     /* A quick simple check whether the incomplete line looks
   3582      * like an HTTP request */
   3583     if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) &&
   3584         (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd))
   3585     {
   3586       transmit_error_response_static (c,
   3587                                       MHD_HTTP_URI_TOO_LONG,
   3588                                       ERR_MSG_REQUEST_TOO_BIG);
   3589       return;
   3590     }
   3591     connection_close_error (c,
   3592                             _ ("No space left in the read buffer when " \
   3593                                "receiving the URI in " \
   3594                                "the request line. " \
   3595                                "The request uses non-standard HTTP request " \
   3596                                "method token."));
   3597     return;
   3598   case MHD_PROC_RECV_HEADERS:
   3599     handle_req_headers_no_space (c, c->read_buffer, c->read_buffer_offset);
   3600     return;
   3601   case MHD_PROC_RECV_BODY_NORMAL:
   3602   case MHD_PROC_RECV_BODY_CHUNKED:
   3603     /* The 'some_payload_processed' flag reflects the *last* application
   3604        callback only.  After that callback more data may have been received
   3605        from the network, in particular a chunk-size line with a chunk
   3606        extension that does not fit into the read buffer.  Therefore the flag
   3607        alone does not imply that free space is available; it does so only as
   3608        long as unprocessed payload is still sitting in the buffer. */
   3609     mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \
   3610                 (! c->rq.some_payload_processed) || \
   3611                 (! has_unprocessed_upload_body_data_in_buffer (c)));
   3612     if (has_unprocessed_upload_body_data_in_buffer (c))
   3613     {
   3614       /* The connection must not be in MHD_EVENT_LOOP_INFO_READ state
   3615          when external polling is used and some data left unprocessed. */
   3616       mhd_assert (MHD_D_IS_USING_THREADS_ (c->daemon));
   3617       /* failed to grow the read buffer, and the
   3618          client which is supposed to handle the
   3619          received data in a *blocking* fashion
   3620          (in this mode) did not handle the data as
   3621          it was supposed to!
   3622          => we would either have to do busy-waiting
   3623          (on the client, which would likely fail),
   3624          or if we do nothing, we would just timeout
   3625          on the connection (if a timeout is even
   3626          set!).
   3627          Solution: we kill the connection with an error */
   3628       transmit_error_response_static (c,
   3629                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
   3630                                       ERROR_MSG_DATA_NOT_HANDLED_BY_APP);
   3631     }
   3632     else
   3633     {
   3634       if (MHD_PROC_RECV_BODY_NORMAL == stage)
   3635       {
   3636         /* A header probably has been added to a suspended connection and
   3637            it took precisely all the space in the buffer.
   3638            Very low probability. */
   3639         mhd_assert (! c->rq.have_chunked_upload);
   3640         handle_req_headers_no_space (c, NULL, 0);
   3641       }
   3642       else
   3643       {
   3644         mhd_assert (c->rq.have_chunked_upload);
   3645         if (c->rq.current_chunk_offset != c->rq.current_chunk_size)
   3646         { /* Receiving content of the chunk */
   3647           /* A header probably has been added to a suspended connection and
   3648              it took precisely all the space in the buffer.
   3649              Very low probability. */
   3650           handle_req_headers_no_space (c, NULL, 0);
   3651         }
   3652         else
   3653         {
   3654           if (0 != c->rq.current_chunk_size)
   3655           { /* Waiting for chunk-closing CRLF */
   3656             /* Not really possible as some payload should be
   3657                processed and the space used by payload should be available. */
   3658             handle_req_headers_no_space (c, NULL, 0);
   3659           }
   3660           else
   3661           { /* Reading the line with the chunk size */
   3662             handle_req_chunk_size_line_no_space (c,
   3663                                                  c->read_buffer,
   3664                                                  c->read_buffer_offset);
   3665           }
   3666         }
   3667       }
   3668     }
   3669     return;
   3670   case MHD_PROC_RECV_FOOTERS:
   3671     handle_req_footers_no_space (c, c->read_buffer, c->read_buffer_offset);
   3672     return;
   3673   /* The next cases should not be possible */
   3674   case MHD_PROC_RECV_COOKIE:
   3675   default:
   3676     break;
   3677   }
   3678   mhd_assert (0);
   3679 }
   3680 
   3681 
   3682 /**
   3683  * Check whether enough space is available in the read buffer for the next
   3684  * operation.
   3685  * Handles grow of the buffer if required and error conditions (when buffer
   3686  * grow is required but not possible).
   3687  * Must be called only when processing the event loop states and when
   3688  * reading is required for the next phase.
   3689  * @param c the connection to check
   3690  * @return true if connection handled successfully and enough buffer
   3691  *         is available,
   3692  *         false if not enough buffer is available and the loop's states
   3693  *         must be processed again as connection is in the error state.
   3694  */
   3695 static bool
   3696 check_and_grow_read_buffer_space (struct MHD_Connection *c)
   3697 {
   3698   /**
   3699    * The increase of read buffer size is desirable.
   3700    */
   3701   bool rbuff_grow_desired;
   3702   /**
   3703    * The increase of read buffer size is a hard requirement.
   3704    */
   3705   bool rbuff_grow_required;
   3706 
   3707   mhd_assert (0 != (MHD_EVENT_LOOP_INFO_READ & c->event_loop_info));
   3708   mhd_assert (! c->discard_request);
   3709 
   3710   rbuff_grow_required = (c->read_buffer_offset == c->read_buffer_size);
   3711   if (rbuff_grow_required)
   3712     rbuff_grow_desired = true;
   3713   else
   3714   {
   3715     rbuff_grow_desired = (c->read_buffer_offset + c->daemon->pool_increment >
   3716                           c->read_buffer_size);
   3717 
   3718     if ((rbuff_grow_desired) &&
   3719         (MHD_CONNECTION_BODY_RECEIVING == c->state))
   3720     {
   3721       if (! c->rq.have_chunked_upload)
   3722       {
   3723         mhd_assert (MHD_SIZE_UNKNOWN != c->rq.remaining_upload_size);
   3724         /* Do not grow read buffer more than necessary to process the current
   3725            request. */
   3726         rbuff_grow_desired =
   3727           (c->rq.remaining_upload_size > c->read_buffer_size);
   3728       }
   3729       else
   3730       {
   3731         mhd_assert (MHD_SIZE_UNKNOWN == c->rq.remaining_upload_size);
   3732         if (0 == c->rq.current_chunk_size)
   3733           rbuff_grow_desired =  /* Reading value of the next chunk size */
   3734                                (MHD_CHUNK_HEADER_REASONABLE_LEN >
   3735                                 c->read_buffer_size);
   3736         else
   3737         {
   3738           const uint64_t cur_chunk_left =
   3739             c->rq.current_chunk_size - c->rq.current_chunk_offset;
   3740           /* Do not grow read buffer more than necessary to process the current
   3741              chunk with terminating CRLF. */
   3742           mhd_assert (c->rq.current_chunk_offset <= c->rq.current_chunk_size);
   3743           rbuff_grow_desired =
   3744             ((cur_chunk_left + 2) > (uint64_t) (c->read_buffer_size));
   3745         }
   3746       }
   3747     }
   3748   }
   3749 
   3750   if (! rbuff_grow_desired)
   3751     return true; /* No need to increase the buffer */
   3752 
   3753   if (try_grow_read_buffer (c, rbuff_grow_required))
   3754     return true; /* Buffer increase succeed */
   3755 
   3756   if (! rbuff_grow_required)
   3757     return true; /* Can continue without buffer increase */
   3758 
   3759   /* Failed to increase the read buffer size, but need to read the data
   3760      from the network.
   3761      No more space left in the buffer, no more space to increase the buffer. */
   3762 
   3763   /* 'PROCESS_READ' event state flag must be set only if the last application
   3764      callback has processed some data. If any data is processed then some
   3765      space in the read buffer must be available. */
   3766   mhd_assert (0 == (MHD_EVENT_LOOP_INFO_PROCESS & c->event_loop_info));
   3767 
   3768   if ((! MHD_D_IS_USING_THREADS_ (c->daemon))
   3769       && (MHD_CONNECTION_BODY_RECEIVING == c->state)
   3770       && has_unprocessed_upload_body_data_in_buffer (c))
   3771   {
   3772     /* The application is handling processing cycles.
   3773        The data could be processed later. */
   3774     c->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
   3775     return true;
   3776   }
   3777   else
   3778   {
   3779     enum MHD_ProcRecvDataStage stage;
   3780 
   3781     switch (c->state)
   3782     {
   3783     case MHD_CONNECTION_INIT:
   3784       stage = MHD_PROC_RECV_INIT;
   3785       break;
   3786     case MHD_CONNECTION_REQ_LINE_RECEIVING:
   3787       if (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd)
   3788         stage = MHD_PROC_RECV_METHOD;
   3789       else if (0 == c->rq.req_target_len)
   3790         stage = MHD_PROC_RECV_URI;
   3791       else
   3792         stage = MHD_PROC_RECV_HTTPVER;
   3793       break;
   3794     case MHD_CONNECTION_REQ_HEADERS_RECEIVING:
   3795       stage = MHD_PROC_RECV_HEADERS;
   3796       break;
   3797     case MHD_CONNECTION_BODY_RECEIVING:
   3798       stage = c->rq.have_chunked_upload ?
   3799               MHD_PROC_RECV_BODY_CHUNKED : MHD_PROC_RECV_BODY_NORMAL;
   3800       break;
   3801     case MHD_CONNECTION_FOOTERS_RECEIVING:
   3802       stage = MHD_PROC_RECV_FOOTERS;
   3803       break;
   3804     case MHD_CONNECTION_REQ_LINE_RECEIVED:
   3805     case MHD_CONNECTION_HEADERS_RECEIVED:
   3806     case MHD_CONNECTION_HEADERS_PROCESSED:
   3807     case MHD_CONNECTION_CONTINUE_SENDING:
   3808     case MHD_CONNECTION_BODY_RECEIVED:
   3809     case MHD_CONNECTION_FOOTERS_RECEIVED:
   3810     case MHD_CONNECTION_FULL_REQ_RECEIVED:
   3811     case MHD_CONNECTION_START_REPLY:
   3812     case MHD_CONNECTION_HEADERS_SENDING:
   3813     case MHD_CONNECTION_HEADERS_SENT:
   3814     case MHD_CONNECTION_NORMAL_BODY_UNREADY:
   3815     case MHD_CONNECTION_NORMAL_BODY_READY:
   3816     case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
   3817     case MHD_CONNECTION_CHUNKED_BODY_READY:
   3818     case MHD_CONNECTION_CHUNKED_BODY_SENT:
   3819     case MHD_CONNECTION_FOOTERS_SENDING:
   3820     case MHD_CONNECTION_FULL_REPLY_SENT:
   3821     case MHD_CONNECTION_CLOSED:
   3822 #ifdef UPGRADE_SUPPORT
   3823     case MHD_CONNECTION_UPGRADE:
   3824 #endif
   3825     default:
   3826       stage = MHD_PROC_RECV_BODY_NORMAL;
   3827       mhd_assert (0);
   3828     }
   3829 
   3830     handle_recv_no_space (c, stage);
   3831   }
   3832   return false;
   3833 }
   3834 
   3835 
   3836 /**
   3837  * Update the 'event_loop_info' field of this connection based on the state
   3838  * that the connection is now in.  May also close the connection or
   3839  * perform other updates to the connection if needed to prepare for
   3840  * the next round of the event loop.
   3841  *
   3842  * @param connection connection to get poll set for
   3843  */
   3844 static void
   3845 MHD_connection_update_event_loop_info (struct MHD_Connection *connection)
   3846 {
   3847   /* Do not update states of suspended connection */
   3848   if (connection->suspended)
   3849     return; /* States will be updated after resume. */
   3850 #ifdef HTTPS_SUPPORT
   3851   if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
   3852   {   /* HTTPS connection. */
   3853     switch (connection->tls_state)
   3854     {
   3855     case MHD_TLS_CONN_INIT:
   3856       connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3857       return;
   3858     case MHD_TLS_CONN_HANDSHAKING:
   3859     case MHD_TLS_CONN_WR_CLOSING:
   3860       if (0 == gnutls_record_get_direction (connection->tls_session))
   3861         connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3862       else
   3863         connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3864       return;
   3865     case MHD_TLS_CONN_CONNECTED:
   3866       break; /* Do normal processing */
   3867     case MHD_TLS_CONN_WR_CLOSED:
   3868     case MHD_TLS_CONN_TLS_FAILED:
   3869       connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
   3870       return;
   3871     case MHD_TLS_CONN_TLS_CLOSING:  /* Not implemented yet */
   3872     case MHD_TLS_CONN_TLS_CLOSED:   /* Not implemented yet */
   3873     case MHD_TLS_CONN_INVALID_STATE:
   3874     case MHD_TLS_CONN_NO_TLS: /* Not possible */
   3875     default:
   3876       MHD_PANIC (_ ("Invalid TLS state value.\n"));
   3877     }
   3878   }
   3879 #endif /* HTTPS_SUPPORT */
   3880   while (1)
   3881   {
   3882 #if DEBUG_STATES
   3883     MHD_DLOG (connection->daemon,
   3884               _ ("In function %s handling connection at state: %s\n"),
   3885               MHD_FUNC_,
   3886               MHD_state_to_string (connection->state));
   3887 #endif
   3888     switch (connection->state)
   3889     {
   3890     case MHD_CONNECTION_INIT:
   3891     case MHD_CONNECTION_REQ_LINE_RECEIVING:
   3892       connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3893       break;
   3894     case MHD_CONNECTION_REQ_LINE_RECEIVED:
   3895       mhd_assert (0);
   3896       break;
   3897     case MHD_CONNECTION_REQ_HEADERS_RECEIVING:
   3898       connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3899       break;
   3900     case MHD_CONNECTION_HEADERS_RECEIVED:
   3901     case MHD_CONNECTION_HEADERS_PROCESSED:
   3902       mhd_assert (0);
   3903       break;
   3904     case MHD_CONNECTION_CONTINUE_SENDING:
   3905       connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3906       break;
   3907     case MHD_CONNECTION_BODY_RECEIVING:
   3908       if ((connection->rq.some_payload_processed) &&
   3909           has_unprocessed_upload_body_data_in_buffer (connection))
   3910       {
   3911         /* Some data was processed, the buffer must have some free space */
   3912         mhd_assert (connection->read_buffer_offset < \
   3913                     connection->read_buffer_size);
   3914         if (! connection->rq.have_chunked_upload)
   3915         {
   3916           /* Not a chunked upload. Do not read more than necessary to
   3917              process the current request. */
   3918           if (connection->rq.remaining_upload_size >=
   3919               connection->read_buffer_offset)
   3920             connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
   3921           else
   3922             connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ;
   3923         }
   3924         else
   3925         {
   3926           /* Chunked upload. The size of the current request is unknown.
   3927              Continue reading as the space in the read buffer is available. */
   3928           connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ;
   3929         }
   3930       }
   3931       else
   3932         connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3933       break;
   3934     case MHD_CONNECTION_BODY_RECEIVED:
   3935       mhd_assert (0);
   3936       break;
   3937     case MHD_CONNECTION_FOOTERS_RECEIVING:
   3938       connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   3939       break;
   3940     case MHD_CONNECTION_FOOTERS_RECEIVED:
   3941       mhd_assert (0);
   3942       break;
   3943     case MHD_CONNECTION_FULL_REQ_RECEIVED:
   3944       connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
   3945       break;
   3946     case MHD_CONNECTION_START_REPLY:
   3947       mhd_assert (0);
   3948       break;
   3949     case MHD_CONNECTION_HEADERS_SENDING:
   3950       /* headers in buffer, keep writing */
   3951       connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3952       break;
   3953     case MHD_CONNECTION_HEADERS_SENT:
   3954       mhd_assert (0);
   3955       break;
   3956     case MHD_CONNECTION_NORMAL_BODY_UNREADY:
   3957       connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
   3958       break;
   3959     case MHD_CONNECTION_NORMAL_BODY_READY:
   3960       connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3961       break;
   3962     case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
   3963       connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
   3964       break;
   3965     case MHD_CONNECTION_CHUNKED_BODY_READY:
   3966       connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3967       break;
   3968     case MHD_CONNECTION_CHUNKED_BODY_SENT:
   3969       mhd_assert (0);
   3970       break;
   3971     case MHD_CONNECTION_FOOTERS_SENDING:
   3972       connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
   3973       break;
   3974     case MHD_CONNECTION_FULL_REPLY_SENT:
   3975       mhd_assert (0);
   3976       break;
   3977     case MHD_CONNECTION_CLOSED:
   3978       connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
   3979       return;           /* do nothing, not even reading */
   3980 #ifdef UPGRADE_SUPPORT
   3981     case MHD_CONNECTION_UPGRADE:
   3982       mhd_assert (0);
   3983       break;
   3984 #endif /* UPGRADE_SUPPORT */
   3985     default:
   3986       mhd_assert (0);
   3987     }
   3988 
   3989     if (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info))
   3990     {
   3991       /* Check whether the space is available to receive data */
   3992       if (! check_and_grow_read_buffer_space (connection))
   3993       {
   3994         mhd_assert (connection->discard_request);
   3995         continue;
   3996       }
   3997     }
   3998     break; /* Everything was processed. */
   3999   }
   4000 }
   4001 
   4002 
   4003 /**
   4004  * Add an entry to the HTTP headers of a connection.  If this fails,
   4005  * transmit an error response (request too big).
   4006  *
   4007  * @param cls the context (connection)
   4008  * @param kind kind of the value
   4009  * @param key key for the value
   4010  * @param key_size number of bytes in @a key
   4011  * @param value the value itself
   4012  * @param value_size number of bytes in @a value
   4013  * @return #MHD_NO on failure (out of memory), #MHD_YES for success
   4014  */
   4015 static enum MHD_Result
   4016 connection_add_header (void *cls,
   4017                        const char *key,
   4018                        size_t key_size,
   4019                        const char *value,
   4020                        size_t value_size,
   4021                        enum MHD_ValueKind kind)
   4022 {
   4023   struct MHD_Connection *connection = (struct MHD_Connection *) cls;
   4024   if (MHD_NO ==
   4025       MHD_set_connection_value_n (connection,
   4026                                   kind,
   4027                                   key,
   4028                                   key_size,
   4029                                   value,
   4030                                   value_size))
   4031   {
   4032 #ifdef HAVE_MESSAGES
   4033     MHD_DLOG (connection->daemon,
   4034               _ ("Not enough memory in pool to allocate header record!\n"));
   4035 #endif
   4036     transmit_error_response_static (connection,
   4037                                     MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
   4038                                     ERR_MSG_REQUEST_TOO_BIG);
   4039     return MHD_NO;
   4040   }
   4041   return MHD_YES;
   4042 }
   4043 
   4044 
   4045 #ifdef COOKIE_SUPPORT
   4046 
   4047 /**
   4048  * Cookie parsing result
   4049  */
   4050 enum _MHD_ParseCookie
   4051 {
   4052   MHD_PARSE_COOKIE_OK = MHD_YES,      /**< Success or no cookies in headers */
   4053   MHD_PARSE_COOKIE_OK_LAX = 2,        /**< Cookies parsed, but workarounds used */
   4054   MHD_PARSE_COOKIE_MALFORMED = -1,    /**< Invalid cookie header */
   4055   MHD_PARSE_COOKIE_NO_MEMORY = MHD_NO /**< Not enough memory in the pool */
   4056 };
   4057 
   4058 
   4059 /**
   4060  * Parse the cookies string (see RFC 6265).
   4061  *
   4062  * Try to parse the cookies string even if it is not strictly formed
   4063  * as specified by RFC 6265.
   4064  *
   4065  * @param str the string to parse, without leading whitespaces
   4066  * @param str_len the size of the @a str, not including mandatory
   4067  *                zero-termination
   4068  * @param connection the connection to add parsed cookies
   4069  * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
   4070  */
   4071 static enum _MHD_ParseCookie
   4072 parse_cookies_string (char *str,
   4073                       const size_t str_len,
   4074                       struct MHD_Connection *connection)
   4075 {
   4076   size_t i;
   4077   bool non_strict;
   4078   /* Skip extra whitespaces and empty cookies */
   4079   const bool allow_wsp_empty = (0 >= connection->daemon->client_discipline);
   4080   /* Allow whitespaces around '=' character */
   4081   const bool wsp_around_eq = (-3 >= connection->daemon->client_discipline);
   4082   /* Allow whitespaces in quoted cookie value */
   4083   const bool wsp_in_quoted = (-2 >= connection->daemon->client_discipline);
   4084   /* Allow tab as space after semicolon between cookies */
   4085   const bool tab_as_sp = (0 >= connection->daemon->client_discipline);
   4086   /* Allow no space after semicolon between cookies */
   4087   const bool allow_no_space = (0 >= connection->daemon->client_discipline);
   4088 
   4089   non_strict = false;
   4090   i = 0;
   4091   while (i < str_len)
   4092   {
   4093     size_t name_start;
   4094     size_t name_len;
   4095     size_t value_start;
   4096     size_t value_len;
   4097     bool val_quoted;
   4098     /* Skip any whitespaces and empty cookies */
   4099     while (' ' == str[i] || '\t' == str[i] || ';' == str[i])
   4100     {
   4101       if (! allow_wsp_empty)
   4102         return MHD_PARSE_COOKIE_MALFORMED;
   4103       non_strict = true;
   4104       i++;
   4105       if (i == str_len)
   4106         return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
   4107     }
   4108     /* 'i' must point to the first char of cookie-name */
   4109     name_start = i;
   4110     /* Find the end of the cookie-name */
   4111     do
   4112     {
   4113       const char l = str[i];
   4114       if (('=' == l) || (' ' == l) || ('\t' == l) || ('"' == l) || (',' == l) ||
   4115           (';' == l) || (0 == l))
   4116         break;
   4117     } while (str_len > ++i);
   4118     name_len = i - name_start;
   4119     /* Skip any whitespaces */
   4120     while (str_len > i && (' ' == str[i] || '\t' == str[i]))
   4121     {
   4122       if (! wsp_around_eq)
   4123         return MHD_PARSE_COOKIE_MALFORMED;
   4124       non_strict = true;
   4125       i++;
   4126     }
   4127     if ((str_len == i) || ('=' != str[i]) || (0 == name_len))
   4128       return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie name */
   4129     /* 'i' must point to the '=' char */
   4130     mhd_assert ('=' == str[i]);
   4131     i++;
   4132     /* Skip any whitespaces */
   4133     while (str_len > i && (' ' == str[i] || '\t' == str[i]))
   4134     {
   4135       if (! wsp_around_eq)
   4136         return MHD_PARSE_COOKIE_MALFORMED;
   4137       non_strict = true;
   4138       i++;
   4139     }
   4140     /* 'i' must point to the first char of cookie-value */
   4141     if (str_len == i)
   4142     {
   4143       value_start = 0;
   4144       value_len = 0;
   4145 #ifdef _DEBUG
   4146       val_quoted = false; /* This assignment used in assert */
   4147 #endif
   4148     }
   4149     else
   4150     {
   4151       bool valid_cookie;
   4152       val_quoted = ('"' == str[i]);
   4153       if (val_quoted)
   4154         i++;
   4155       value_start = i;
   4156       /* Find the end of the cookie-value */
   4157       while (str_len > i)
   4158       {
   4159         const char l = str[i];
   4160         if ((';' == l) || ('"' == l) || (',' == l) || (';' == l) ||
   4161             ('\\' == l) || (0 == l))
   4162           break;
   4163         if ((' ' == l) || ('\t' == l))
   4164         {
   4165           if (! val_quoted)
   4166             break;
   4167           if (! wsp_in_quoted)
   4168             return MHD_PARSE_COOKIE_MALFORMED;
   4169           non_strict = true;
   4170         }
   4171         i++;
   4172       }
   4173       value_len = i - value_start;
   4174       if (val_quoted)
   4175       {
   4176         if ((str_len == i) || ('"' != str[i]))
   4177           return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie value, no closing quote */
   4178         i++;
   4179       }
   4180       /* Skip any whitespaces */
   4181       if ((str_len > i) && ((' ' == str[i]) || ('\t' == str[i])))
   4182       {
   4183         do
   4184         {
   4185           i++;
   4186         } while (str_len > i && (' ' == str[i] || '\t' == str[i]));
   4187         /* Whitespace at the end? */
   4188         if (str_len > i)
   4189         {
   4190           if (! allow_wsp_empty)
   4191             return MHD_PARSE_COOKIE_MALFORMED;
   4192           non_strict = true;
   4193         }
   4194       }
   4195       if (str_len == i)
   4196         valid_cookie = true;
   4197       else if (';' == str[i])
   4198         valid_cookie = true;
   4199       else
   4200         valid_cookie = false;
   4201 
   4202       if (! valid_cookie)
   4203         return MHD_PARSE_COOKIE_MALFORMED; /* Garbage at the end of the cookie value */
   4204     }
   4205     mhd_assert (0 != name_len);
   4206     str[name_start + name_len] = 0; /* Zero-terminate the name */
   4207     if (0 != value_len)
   4208     {
   4209       mhd_assert (value_start + value_len <= str_len);
   4210       str[value_start + value_len] = 0; /* Zero-terminate the value */
   4211       if (MHD_NO ==
   4212           MHD_set_connection_value_n_nocheck_ (connection,
   4213                                                MHD_COOKIE_KIND,
   4214                                                str + name_start,
   4215                                                name_len,
   4216                                                str + value_start,
   4217                                                value_len))
   4218         return MHD_PARSE_COOKIE_NO_MEMORY;
   4219     }
   4220     else
   4221     {
   4222       if (MHD_NO ==
   4223           MHD_set_connection_value_n_nocheck_ (connection,
   4224                                                MHD_COOKIE_KIND,
   4225                                                str + name_start,
   4226                                                name_len,
   4227                                                "",
   4228                                                0))
   4229         return MHD_PARSE_COOKIE_NO_MEMORY;
   4230     }
   4231     if (str_len > i)
   4232     {
   4233       mhd_assert (0 == str[i] || ';' == str[i]);
   4234       mhd_assert (! val_quoted || ';' == str[i]);
   4235       mhd_assert (';' != str[i] || val_quoted || non_strict || 0 == value_len);
   4236       i++;
   4237       if (str_len == i)
   4238       { /* No next cookie after semicolon */
   4239         if (! allow_wsp_empty)
   4240           return MHD_PARSE_COOKIE_MALFORMED;
   4241         non_strict = true;
   4242       }
   4243       else if (' ' != str[i])
   4244       {/* No space after semicolon */
   4245         if (('\t' == str[i]) && tab_as_sp)
   4246           i++;
   4247         else if (! allow_no_space)
   4248           return MHD_PARSE_COOKIE_MALFORMED;
   4249         non_strict = true;
   4250       }
   4251       else
   4252       {
   4253         i++;
   4254         if (str_len == i)
   4255         {
   4256           if (! allow_wsp_empty)
   4257             return MHD_PARSE_COOKIE_MALFORMED;
   4258           non_strict = true;
   4259         }
   4260       }
   4261     }
   4262   }
   4263   return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
   4264 }
   4265 
   4266 
   4267 /**
   4268  * Parse the cookie header (see RFC 6265).
   4269  *
   4270  * @param connection connection to parse header of
   4271  * @param hdr the value of the "Cookie:" header
   4272  * @param hdr_len the length of the @a hdr string
   4273  * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
   4274  */
   4275 static enum _MHD_ParseCookie
   4276 parse_cookie_header (struct MHD_Connection *connection,
   4277                      const char *hdr,
   4278                      size_t hdr_len)
   4279 {
   4280   char *cpy;
   4281   size_t i;
   4282   enum _MHD_ParseCookie parse_res;
   4283   struct MHD_HTTP_Req_Header *const saved_tail =
   4284     connection->rq.headers_received_tail;
   4285   const bool allow_partially_correct_cookie =
   4286     (1 >= connection->daemon->client_discipline);
   4287 
   4288   if (0 == hdr_len)
   4289     return MHD_PARSE_COOKIE_OK;
   4290 
   4291   cpy = MHD_connection_alloc_memory_ (connection,
   4292                                       hdr_len + 1);
   4293   if (NULL == cpy)
   4294     parse_res = MHD_PARSE_COOKIE_NO_MEMORY;
   4295   else
   4296   {
   4297     memcpy (cpy,
   4298             hdr,
   4299             hdr_len);
   4300     cpy[hdr_len] = '\0';
   4301 
   4302     i = 0;
   4303     /* Skip all initial whitespaces */
   4304     while (i < hdr_len && (' ' == cpy[i] || '\t' == cpy[i]))
   4305       i++;
   4306 
   4307     parse_res = parse_cookies_string (cpy + i, hdr_len - i, connection);
   4308   }
   4309 
   4310   switch (parse_res)
   4311   {
   4312   case MHD_PARSE_COOKIE_OK:
   4313     break;
   4314   case MHD_PARSE_COOKIE_OK_LAX:
   4315 #ifdef HAVE_MESSAGES
   4316     if (saved_tail != connection->rq.headers_received_tail)
   4317       MHD_DLOG (connection->daemon,
   4318                 _ ("The Cookie header has been parsed, but it is not fully "
   4319                    "compliant with the standard.\n"));
   4320 #endif /* HAVE_MESSAGES */
   4321     break;
   4322   case MHD_PARSE_COOKIE_MALFORMED:
   4323     if (saved_tail != connection->rq.headers_received_tail)
   4324     {
   4325       if (! allow_partially_correct_cookie)
   4326       {
   4327         /* Remove extracted values from partially broken cookie */
   4328         /* Memory remains allocated until the end of the request processing */
   4329         connection->rq.headers_received_tail = saved_tail;
   4330         saved_tail->next = NULL;
   4331 #ifdef HAVE_MESSAGES
   4332         MHD_DLOG (connection->daemon,
   4333                   _ ("The Cookie header has been ignored as it contains "
   4334                      "malformed data.\n"));
   4335 #endif /* HAVE_MESSAGES */
   4336       }
   4337 #ifdef HAVE_MESSAGES
   4338       else
   4339         MHD_DLOG (connection->daemon,
   4340                   _ ("The Cookie header has been only partially parsed as it "
   4341                      "contains malformed data.\n"));
   4342 #endif /* HAVE_MESSAGES */
   4343     }
   4344 #ifdef HAVE_MESSAGES
   4345     else
   4346       MHD_DLOG (connection->daemon,
   4347                 _ ("The Cookie header has malformed data.\n"));
   4348 #endif /* HAVE_MESSAGES */
   4349     break;
   4350   case MHD_PARSE_COOKIE_NO_MEMORY:
   4351 #ifdef HAVE_MESSAGES
   4352     MHD_DLOG (connection->daemon,
   4353               _ ("Not enough memory in the connection pool to "
   4354                  "parse client cookies!\n"));
   4355 #endif /* HAVE_MESSAGES */
   4356     break;
   4357   default:
   4358     mhd_assert (0);
   4359     break;
   4360   }
   4361 #ifndef HAVE_MESSAGES
   4362   (void) saved_tail; /* Mute compiler warning */
   4363 #endif /* ! HAVE_MESSAGES */
   4364 
   4365   return parse_res;
   4366 }
   4367 
   4368 
   4369 #endif /* COOKIE_SUPPORT */
   4370 
   4371 
   4372 /**
   4373  * The valid length of any HTTP version string
   4374  */
   4375 #define HTTP_VER_LEN (MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1))
   4376 
   4377 /**
   4378  * Detect HTTP version, send error response if version is not supported
   4379  *
   4380  * @param connection the connection
   4381  * @param http_string the pointer to HTTP version string
   4382  * @param len the length of @a http_string in bytes
   4383  * @return true if HTTP version is correct and supported,
   4384  *         false if HTTP version is not correct or unsupported.
   4385  */
   4386 static bool
   4387 parse_http_version (struct MHD_Connection *connection,
   4388                     const char *http_string,
   4389                     size_t len)
   4390 {
   4391   const char *const h = http_string; /**< short alias */
   4392   mhd_assert (NULL != http_string);
   4393 
   4394   /* String must start with 'HTTP/d.d', case-sensitive match.
   4395    * See https://www.rfc-editor.org/rfc/rfc9112#name-http-version */
   4396   if ((HTTP_VER_LEN != len) ||
   4397       ('H' != h[0]) || ('T' != h[1]) || ('T' != h[2]) || ('P' != h[3]) ||
   4398       ('/' != h[4])
   4399       || ('.' != h[6]) ||
   4400       (('0' > h[5]) || ('9' < h[5])) ||
   4401       (('0' > h[7]) || ('9' < h[7])))
   4402   {
   4403     connection->rq.http_ver = MHD_HTTP_VER_INVALID;
   4404     transmit_error_response_static (connection,
   4405                                     MHD_HTTP_BAD_REQUEST,
   4406                                     REQUEST_MALFORMED);
   4407     return false;
   4408   }
   4409   if (1 == h[5] - '0')
   4410   {
   4411     /* HTTP/1.x */
   4412     if (1 == h[7] - '0')
   4413       connection->rq.http_ver = MHD_HTTP_VER_1_1;
   4414     else if (0 == h[7] - '0')
   4415       connection->rq.http_ver = MHD_HTTP_VER_1_0;
   4416     else
   4417       connection->rq.http_ver = MHD_HTTP_VER_1_2__1_9;
   4418 
   4419     return true;
   4420   }
   4421 
   4422   if (0 == h[5] - '0')
   4423   {
   4424     /* Too old major version */
   4425     connection->rq.http_ver = MHD_HTTP_VER_TOO_OLD;
   4426     transmit_error_response_static (connection,
   4427                                     MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED,
   4428                                     REQ_HTTP_VER_IS_TOO_OLD);
   4429     return false;
   4430   }
   4431 
   4432   connection->rq.http_ver = MHD_HTTP_VER_FUTURE;
   4433   transmit_error_response_static (connection,
   4434                                   MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED,
   4435                                   REQ_HTTP_VER_IS_NOT_SUPPORTED);
   4436   return false;
   4437 }
   4438 
   4439 
   4440 /**
   4441  * Detect standard HTTP request method
   4442  *
   4443  * @param connection the connection
   4444  * @param method the pointer to HTTP request method string
   4445  * @param len the length of @a method in bytes
   4446  */
   4447 static void
   4448 parse_http_std_method (struct MHD_Connection *connection,
   4449                        const char *method,
   4450                        size_t len)
   4451 {
   4452   const char *const m = method; /**< short alias */
   4453   mhd_assert (NULL != m);
   4454   mhd_assert (0 != len);
   4455 
   4456   if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET) == len) &&
   4457       (0 == memcmp (m, MHD_HTTP_METHOD_GET, len)))
   4458     connection->rq.http_mthd = MHD_HTTP_MTHD_GET;
   4459   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_HEAD) == len) &&
   4460            (0 == memcmp (m, MHD_HTTP_METHOD_HEAD, len)))
   4461     connection->rq.http_mthd = MHD_HTTP_MTHD_HEAD;
   4462   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_POST) == len) &&
   4463            (0 == memcmp (m, MHD_HTTP_METHOD_POST, len)))
   4464     connection->rq.http_mthd = MHD_HTTP_MTHD_POST;
   4465   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_PUT) == len) &&
   4466            (0 == memcmp (m, MHD_HTTP_METHOD_PUT, len)))
   4467     connection->rq.http_mthd = MHD_HTTP_MTHD_PUT;
   4468   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_DELETE) == len) &&
   4469            (0 == memcmp (m, MHD_HTTP_METHOD_DELETE, len)))
   4470     connection->rq.http_mthd = MHD_HTTP_MTHD_DELETE;
   4471   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_CONNECT) == len) &&
   4472            (0 == memcmp (m, MHD_HTTP_METHOD_CONNECT, len)))
   4473     connection->rq.http_mthd = MHD_HTTP_MTHD_CONNECT;
   4474   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_OPTIONS) == len) &&
   4475            (0 == memcmp (m, MHD_HTTP_METHOD_OPTIONS, len)))
   4476     connection->rq.http_mthd = MHD_HTTP_MTHD_OPTIONS;
   4477   else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_TRACE) == len) &&
   4478            (0 == memcmp (m, MHD_HTTP_METHOD_TRACE, len)))
   4479     connection->rq.http_mthd = MHD_HTTP_MTHD_TRACE;
   4480   else
   4481     connection->rq.http_mthd = MHD_HTTP_MTHD_OTHER;
   4482 }
   4483 
   4484 
   4485 /**
   4486  * Call the handler of the application for this
   4487  * connection.  Handles chunking of the upload
   4488  * as well as normal uploads.
   4489  *
   4490  * @param connection connection we're processing
   4491  */
   4492 static void
   4493 call_connection_handler (struct MHD_Connection *connection)
   4494 {
   4495   struct MHD_Daemon *daemon = connection->daemon;
   4496   size_t processed;
   4497 
   4498   if (NULL != connection->rp.response)
   4499     return;                     /* already queued a response */
   4500   processed = 0;
   4501   connection->rq.client_aware = true;
   4502   connection->in_access_handler = true;
   4503   if (MHD_NO ==
   4504       daemon->default_handler (daemon->default_handler_cls,
   4505                                connection,
   4506                                connection->rq.url_for_callback,
   4507                                connection->rq.method,
   4508                                connection->rq.version,
   4509                                NULL,
   4510                                &processed,
   4511                                &connection->rq.client_context))
   4512   {
   4513     connection->in_access_handler = false;
   4514     /* serious internal error, close connection */
   4515     CONNECTION_CLOSE_ERROR (connection,
   4516                             _ ("Application reported internal error, " \
   4517                                "closing connection."));
   4518     return;
   4519   }
   4520   connection->in_access_handler = false;
   4521 }
   4522 
   4523 
   4524 /**
   4525  * Call the handler of the application for this
   4526  * connection.  Handles chunking of the upload
   4527  * as well as normal uploads.
   4528  *
   4529  * @param connection connection we're processing
   4530  */
   4531 static void
   4532 process_request_body (struct MHD_Connection *connection)
   4533 {
   4534   struct MHD_Daemon *daemon = connection->daemon;
   4535   size_t available;
   4536   bool instant_retry;
   4537   char *buffer_head;
   4538   const int discp_lvl = daemon->client_discipline;
   4539   /* RFC does not allow LF as the line termination in chunk headers.
   4540      See RFC 9112, section 7.1 and section 2.2-3 */
   4541   const bool bare_lf_as_crlf = (-2 > discp_lvl);
   4542   /* Allow "Bad WhiteSpace" in chunk extension.
   4543      RFC 9112, Section 7.1.1, Paragraph 2 */
   4544   const bool allow_bws = (2 > discp_lvl);
   4545 
   4546   mhd_assert (NULL == connection->rp.response);
   4547 
   4548   buffer_head = connection->read_buffer;
   4549   available = connection->read_buffer_offset;
   4550   do
   4551   {
   4552     size_t to_be_processed;
   4553     size_t left_unprocessed;
   4554     size_t processed_size;
   4555 
   4556     instant_retry = false;
   4557     if (connection->rq.have_chunked_upload)
   4558     {
   4559       mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size);
   4560       if ( (connection->rq.current_chunk_offset ==
   4561             connection->rq.current_chunk_size) &&
   4562            (0 != connection->rq.current_chunk_size) )
   4563       {
   4564         /* Skip CRLF chunk termination */
   4565         size_t i;
   4566         mhd_assert (0 != available);
   4567         /* skip new line at the *end* of a chunk */
   4568         i = 0;
   4569         if ( (2 <= available) &&
   4570              ('\r' == buffer_head[0]) &&
   4571              ('\n' == buffer_head[1]) )
   4572           i += 2;                        /* skip CRLF */
   4573         else if (bare_lf_as_crlf && ('\n' == buffer_head[0]))
   4574           i++;                           /* skip bare LF */
   4575         else if (2 > available)
   4576           break;                         /* need more upload data */
   4577         if (0 == i)
   4578         {
   4579           /* malformed encoding */
   4580           transmit_error_response_static (connection,
   4581                                           MHD_HTTP_BAD_REQUEST,
   4582                                           REQUEST_CHUNKED_MALFORMED);
   4583           return;
   4584         }
   4585         available -= i;
   4586         buffer_head += i;
   4587         connection->rq.current_chunk_offset = 0;
   4588         connection->rq.current_chunk_size = 0;
   4589         if (0 == available)
   4590           break;
   4591       }
   4592       if (0 != connection->rq.current_chunk_size)
   4593       {
   4594         /* Process chunk "content" */
   4595         uint64_t cur_chunk_left;
   4596         mhd_assert (connection->rq.current_chunk_offset < \
   4597                     connection->rq.current_chunk_size);
   4598         cur_chunk_left
   4599           = connection->rq.current_chunk_size
   4600             - connection->rq.current_chunk_offset;
   4601         if (cur_chunk_left > available)
   4602           to_be_processed = available;
   4603         else
   4604         {         /* cur_chunk_left <= (size_t)available */
   4605           to_be_processed = (size_t) cur_chunk_left;
   4606           if (available > to_be_processed)
   4607             instant_retry = true;
   4608         }
   4609       }
   4610       else
   4611       { /* Need the parse the chunk size line */
   4612         /** The number of found digits in the chunk size number */
   4613         size_t num_dig;
   4614         uint64_t chunk_size;
   4615         bool broken;
   4616         bool overflow;
   4617 
   4618         mhd_assert (0 != available);
   4619 
   4620         overflow = false;
   4621         chunk_size = 0; /* Mute possible compiler warning.
   4622                            The real value will be set later. */
   4623 
   4624         num_dig = MHD_strx_to_uint64_n_ (buffer_head,
   4625                                          available,
   4626                                          &chunk_size);
   4627         mhd_assert (num_dig <= available);
   4628         if (num_dig == available)
   4629           continue; /* Need line delimiter */
   4630 
   4631         broken = (0 == num_dig);
   4632         if (broken)
   4633         {
   4634           uint64_t dummy;
   4635           /* Check whether result is invalid due to uint64_t overflow */
   4636           overflow = (0 != MHD_strx_to_uint64_n_ (buffer_head,
   4637                                                   1,
   4638                                                   &dummy));
   4639         }
   4640         else
   4641         {
   4642           /**
   4643            * The length of the string with the number of the chunk size,
   4644            * including chunk extension
   4645            */
   4646           size_t chunk_size_line_len;
   4647 
   4648           chunk_size_line_len = 0;
   4649           if ((';' == buffer_head[num_dig]) ||
   4650               (allow_bws &&
   4651                ((' ' == buffer_head[num_dig]) ||
   4652                 ('\t' == buffer_head[num_dig]))))
   4653           { /* Chunk extension or "bad whitespace" after chunk length */
   4654             size_t i;
   4655 
   4656             /* Skip bad whitespaces (if any) */
   4657             for (i = num_dig; i < available; ++i)
   4658             {
   4659               if ((' ' != buffer_head[i]) && ('\t' != buffer_head[i]))
   4660                 break;
   4661             }
   4662             if (i == available)
   4663               break; /* need more data */
   4664             if (';' == buffer_head[i])
   4665             {
   4666               /* Chunk extension */
   4667               for (++i; i < available; ++i)
   4668               {
   4669                 if (('\r' == buffer_head[i]) ||
   4670                     ('\n' == buffer_head[i]))
   4671                   break;
   4672               }
   4673               if (i == available)
   4674                 break; /* need more data */
   4675               mhd_assert (i > num_dig);
   4676               mhd_assert (1 <= i);
   4677               if ('\r' == buffer_head[i])
   4678               {
   4679                 if (i + 1 == available)
   4680                   break; /* need more data */
   4681                 if ('\n' == buffer_head[i + 1])
   4682                   chunk_size_line_len = i + 2; /* Valid chunk header */
   4683               }
   4684               else
   4685               {
   4686                 mhd_assert ('\n' == buffer_head[i]);
   4687                 if (bare_lf_as_crlf)
   4688                   chunk_size_line_len = i + 1; /* Valid chunk header */
   4689               }
   4690               /* The chunk header is broken
   4691                  if chunk_size_line_len is zero here. */
   4692             }
   4693             else
   4694             { /* No ';' after "bad whitespace" */
   4695               mhd_assert (allow_bws);
   4696               mhd_assert (0 == chunk_size_line_len);
   4697             }
   4698           }
   4699           else
   4700           {
   4701             /* No chunk extension */
   4702             mhd_assert (available >= num_dig);
   4703             if ((2 <= (available - num_dig)) &&
   4704                 ('\r' == buffer_head[num_dig]) &&
   4705                 ('\n' == buffer_head[num_dig + 1]))
   4706               chunk_size_line_len = num_dig + 2;
   4707             else if (bare_lf_as_crlf &&
   4708                      ('\n' == buffer_head[num_dig]))
   4709               chunk_size_line_len = num_dig + 1;
   4710             else if (2 > (available - num_dig))
   4711               break; /* need more data */
   4712           }
   4713 
   4714           if (0 != chunk_size_line_len)
   4715           { /* Valid termination of the chunk size line */
   4716             mhd_assert (chunk_size_line_len <= available);
   4717             /* Start reading payload data of the chunk */
   4718             connection->rq.current_chunk_offset = 0;
   4719             connection->rq.current_chunk_size = chunk_size;
   4720 
   4721             available -= chunk_size_line_len;
   4722             buffer_head += chunk_size_line_len;
   4723 
   4724             if (0 == chunk_size)
   4725             { /* The final (termination) chunk */
   4726               connection->rq.remaining_upload_size = 0;
   4727               break;
   4728             }
   4729             if (available > 0)
   4730               instant_retry = true;
   4731             continue;
   4732           }
   4733           /* Invalid chunk size line */
   4734         }
   4735 
   4736         if (! overflow)
   4737           transmit_error_response_static (connection,
   4738                                           MHD_HTTP_BAD_REQUEST,
   4739                                           REQUEST_CHUNKED_MALFORMED);
   4740         else
   4741           transmit_error_response_static (connection,
   4742                                           MHD_HTTP_CONTENT_TOO_LARGE,
   4743                                           REQUEST_CHUNK_TOO_LARGE);
   4744         return;
   4745       }
   4746     }
   4747     else
   4748     {
   4749       /* no chunked encoding, give all to the client */
   4750       mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size);
   4751       mhd_assert (0 != connection->rq.remaining_upload_size);
   4752       if (connection->rq.remaining_upload_size < available)
   4753         to_be_processed = (size_t) connection->rq.remaining_upload_size;
   4754       else
   4755         to_be_processed = available;
   4756     }
   4757     left_unprocessed = to_be_processed;
   4758     connection->rq.client_aware = true;
   4759     connection->in_access_handler = true;
   4760     if (MHD_NO ==
   4761         daemon->default_handler (daemon->default_handler_cls,
   4762                                  connection,
   4763                                  connection->rq.url_for_callback,
   4764                                  connection->rq.method,
   4765                                  connection->rq.version,
   4766                                  buffer_head,
   4767                                  &left_unprocessed,
   4768                                  &connection->rq.client_context))
   4769     {
   4770       connection->in_access_handler = false;
   4771       /* serious internal error, close connection */
   4772       CONNECTION_CLOSE_ERROR (connection,
   4773                               _ ("Application reported internal error, " \
   4774                                  "closing connection."));
   4775       return;
   4776     }
   4777     connection->in_access_handler = false;
   4778 
   4779     if (left_unprocessed > to_be_processed)
   4780       MHD_PANIC (_ ("libmicrohttpd API violation.\n"));
   4781 
   4782     connection->rq.some_payload_processed =
   4783       (left_unprocessed != to_be_processed);
   4784 
   4785     if (0 != left_unprocessed)
   4786     {
   4787       instant_retry = false; /* client did not process everything */
   4788 #ifdef HAVE_MESSAGES
   4789       if ((! connection->rq.some_payload_processed) &&
   4790           (! connection->suspended))
   4791       {
   4792         /* client did not process any upload data, complain if
   4793            the setup was incorrect, which may prevent us from
   4794            handling the rest of the request */
   4795         if (MHD_D_IS_USING_THREADS_ (daemon))
   4796           MHD_DLOG (daemon,
   4797                     _ ("WARNING: Access Handler Callback has not processed " \
   4798                        "any upload data and connection is not suspended. " \
   4799                        "This may result in hung connection.\n"));
   4800       }
   4801 #endif /* HAVE_MESSAGES */
   4802     }
   4803     processed_size = to_be_processed - left_unprocessed;
   4804     /* dh left "processed" bytes in buffer for next time... */
   4805     buffer_head += processed_size;
   4806     available -= processed_size;
   4807     if (! connection->rq.have_chunked_upload)
   4808     {
   4809       mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size);
   4810       connection->rq.remaining_upload_size -= processed_size;
   4811     }
   4812     else
   4813     {
   4814       mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size);
   4815       connection->rq.current_chunk_offset += processed_size;
   4816     }
   4817   } while (instant_retry);
   4818   /* TODO: zero out reused memory region */
   4819   if ( (available > 0) &&
   4820        (buffer_head != connection->read_buffer) )
   4821     memmove (connection->read_buffer,
   4822              buffer_head,
   4823              available);
   4824   else
   4825     mhd_assert ((0 == available) || \
   4826                 (connection->read_buffer_offset == available));
   4827   connection->read_buffer_offset = available;
   4828 }
   4829 
   4830 
   4831 /**
   4832  * Check if we are done sending the write-buffer.
   4833  * If so, transition into "next_state".
   4834  *
   4835  * @param connection connection to check write status for
   4836  * @param next_state the next state to transition to
   4837  * @return #MHD_NO if we are not done, #MHD_YES if we are
   4838  */
   4839 static enum MHD_Result
   4840 check_write_done (struct MHD_Connection *connection,
   4841                   enum MHD_CONNECTION_STATE next_state)
   4842 {
   4843   if ( (connection->write_buffer_append_offset !=
   4844         connection->write_buffer_send_offset)
   4845        /* || data_in_tls_buffers == true  */
   4846        )
   4847     return MHD_NO;
   4848   connection->write_buffer_append_offset = 0;
   4849   connection->write_buffer_send_offset = 0;
   4850   connection->state = next_state;
   4851   return MHD_YES;
   4852 }
   4853 
   4854 
   4855 /**
   4856  * Parse the various headers; figure out the size
   4857  * of the upload and make sure the headers follow
   4858  * the protocol.
   4859  *
   4860  * @param c the connection to process
   4861  */
   4862 static void
   4863 parse_connection_headers (struct MHD_Connection *c)
   4864 {
   4865   struct MHD_HTTP_Req_Header *pos;
   4866   bool have_hdr_host;
   4867   bool have_cntn_len;
   4868 
   4869   have_hdr_host = false;
   4870   have_cntn_len = false;
   4871 
   4872   /* The presence of the request body is indicated by "Content-Length:" or
   4873      "Transfer-Encoding:" request headers.
   4874      See RFC 9112 section 6.1, 6.2, 6.3; RFC 9110 Section 8.6. */
   4875 
   4876   mhd_assert (0 == c->rq.remaining_upload_size);
   4877   mhd_assert (! c->rq.have_chunked_upload);
   4878 
   4879   for (pos = c->rq.headers_received; NULL != pos; pos = pos->next)
   4880   {
   4881     if (MHD_HEADER_KIND != pos->kind)
   4882       continue;
   4883 
   4884     if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_HOST,
   4885                                          pos->header,
   4886                                          pos->header_size))
   4887     {
   4888       if (have_hdr_host)
   4889       {
   4890         if (-3 < c->daemon->client_discipline)
   4891         {
   4892           transmit_error_response_static (c,
   4893                                           MHD_HTTP_BAD_REQUEST,
   4894                                           REQUEST_MULTIPLE_HOST_HDR);
   4895           return;
   4896         }
   4897       }
   4898       have_hdr_host = true;
   4899     }
   4900 #ifdef COOKIE_SUPPORT
   4901     else if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_COOKIE,
   4902                                               pos->header,
   4903                                               pos->header_size))
   4904     {
   4905       if (MHD_PARSE_COOKIE_NO_MEMORY == parse_cookie_header (c,
   4906                                                              pos->value,
   4907                                                              pos->value_size))
   4908       {
   4909         handle_req_cookie_no_space (c);
   4910         return;
   4911       }
   4912     }
   4913 #endif /* COOKIE_SUPPORT */
   4914     else if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH,
   4915                                               pos->header,
   4916                                               pos->header_size))
   4917     {
   4918       const char *clen;
   4919       size_t val_len;
   4920       size_t num_digits;
   4921       uint64_t decoded_val;
   4922 
   4923       val_len = pos->value_size;
   4924       clen = pos->value;
   4925 
   4926       mhd_assert ('\0' == clen[val_len]);
   4927 
   4928       if ((have_cntn_len)
   4929           && (0 < c->daemon->client_discipline))
   4930       {
   4931         transmit_error_response_static (c,
   4932                                         MHD_HTTP_BAD_REQUEST,
   4933                                         REQUEST_AMBIGUOUS_CONTENT_LENGTH);
   4934         return;
   4935       }
   4936 
   4937       num_digits = MHD_str_to_uint64_n_ (clen,
   4938                                          val_len,
   4939                                          &decoded_val);
   4940 
   4941       if ((0 == num_digits) ||
   4942           (val_len != num_digits) ||
   4943           (MHD_SIZE_UNKNOWN == decoded_val))
   4944       { /* Bad or too large value */
   4945 
   4946         if (have_cntn_len)
   4947         {
   4948           transmit_error_response_static (c,
   4949                                           MHD_HTTP_BAD_REQUEST,
   4950                                           REQUEST_AMBIGUOUS_CONTENT_LENGTH);
   4951           return;
   4952         }
   4953 
   4954         if ((val_len != num_digits)
   4955             || ('0' > clen[0]) || ('9' < clen[0]))
   4956         {
   4957 #ifdef HAVE_MESSAGES
   4958           MHD_DLOG (c->daemon,
   4959                     _ ("Malformed 'Content-Length' header. " \
   4960                        "Closing connection.\n"));
   4961 #endif
   4962           transmit_error_response_static (c,
   4963                                           MHD_HTTP_BAD_REQUEST,
   4964                                           REQUEST_CONTENTLENGTH_MALFORMED);
   4965           return;
   4966         }
   4967 
   4968 #ifdef HAVE_MESSAGES
   4969         MHD_DLOG (c->daemon,
   4970                   _ ("Too large value of 'Content-Length' header. " \
   4971                      "Closing connection.\n"));
   4972 #endif
   4973         transmit_error_response_static (c,
   4974                                         MHD_HTTP_CONTENT_TOO_LARGE,
   4975                                         REQUEST_CONTENTLENGTH_TOOLARGE);
   4976         return;
   4977       }
   4978 
   4979       if ((have_cntn_len) &&
   4980           (c->rq.remaining_upload_size != decoded_val))
   4981       {
   4982         if (-3 < c->daemon->client_discipline)
   4983         {
   4984           transmit_error_response_static (c,
   4985                                           MHD_HTTP_BAD_REQUEST,
   4986                                           REQUEST_AMBIGUOUS_CONTENT_LENGTH);
   4987           return;
   4988         }
   4989         /* The HTTP framing is broken.
   4990            Use smallest (safest) length value and force-close
   4991            after processing of this request. */
   4992         if (c->rq.remaining_upload_size > decoded_val)
   4993           c->rq.remaining_upload_size = decoded_val;
   4994         c->keepalive = MHD_CONN_MUST_CLOSE;
   4995       }
   4996       else
   4997         c->rq.remaining_upload_size = decoded_val;
   4998 
   4999       have_cntn_len = true;
   5000     }
   5001     else if (MHD_str_equal_caseless_s_bin_n_ (
   5002                MHD_HTTP_HEADER_TRANSFER_ENCODING,
   5003                pos->header,
   5004                pos->header_size))
   5005     {
   5006 
   5007       if (MHD_HTTP_VER_1_1 > c->rq.http_ver)
   5008       {
   5009         /* RFC 9112, 6.1, last paragraph */
   5010         if (0 < c->daemon->client_discipline)
   5011         {
   5012           transmit_error_response_static (c,
   5013                                           MHD_HTTP_BAD_REQUEST,
   5014                                           REQUEST_HTTP1_0_TR_ENCODING);
   5015           return;
   5016         }
   5017         /* HTTP framing potentially broken */
   5018         c->keepalive = MHD_CONN_MUST_CLOSE;
   5019       }
   5020 
   5021       if (c->rq.have_chunked_upload
   5022           || ! MHD_str_equal_caseless_s_bin_n_ ("chunked",
   5023                                                 pos->value,
   5024                                                 pos->value_size))
   5025       {
   5026         transmit_error_response_static (c,
   5027                                         c->rq.have_chunked_upload ?
   5028                                         MHD_HTTP_BAD_REQUEST :
   5029                                         MHD_HTTP_NOT_IMPLEMENTED,
   5030                                         REQUEST_UNSUPPORTED_TR_ENCODING);
   5031         return;
   5032       }
   5033       c->rq.have_chunked_upload = true;
   5034       c->rq.remaining_upload_size = MHD_SIZE_UNKNOWN;
   5035     }
   5036   }
   5037 
   5038   if (c->rq.have_chunked_upload && have_cntn_len)
   5039   {
   5040     if (0 < c->daemon->client_discipline)
   5041     {
   5042       transmit_error_response_static (c,
   5043                                       MHD_HTTP_BAD_REQUEST,
   5044                                       REQUEST_LENGTH_WITH_TR_ENCODING);
   5045       return;
   5046     }
   5047     else
   5048     {
   5049 #ifdef HAVE_MESSAGES
   5050       MHD_DLOG (c->daemon,
   5051                 _ ("The 'Content-Length' request header is ignored "
   5052                    "as chunked Transfer-Encoding is set in the "
   5053                    "same request.\n"));
   5054 #endif /* HAVE_MESSAGES */
   5055       c->rq.remaining_upload_size = MHD_SIZE_UNKNOWN;
   5056       /* Must close connection after reply to prevent potential attack */
   5057       c->keepalive = MHD_CONN_MUST_CLOSE;
   5058     }
   5059   }
   5060 
   5061   mhd_assert (! c->rq.have_chunked_upload ||
   5062               (MHD_SIZE_UNKNOWN == c->rq.remaining_upload_size));
   5063   mhd_assert ((0 == c->rq.remaining_upload_size) ||
   5064               have_cntn_len || c->rq.have_chunked_upload);
   5065 
   5066   if (! have_hdr_host
   5067       && (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver))
   5068       && (-3 < c->daemon->client_discipline))
   5069   {
   5070 #ifdef HAVE_MESSAGES
   5071     MHD_DLOG (c->daemon,
   5072               _ ("Received HTTP/1.1 request without `Host' header.\n"));
   5073 #endif
   5074     transmit_error_response_static (c,
   5075                                     MHD_HTTP_BAD_REQUEST,
   5076                                     REQUEST_LACKS_HOST);
   5077     return;
   5078   }
   5079 }
   5080 
   5081 
   5082 /**
   5083  * Reset request header processing state.
   5084  *
   5085  * This function resets the processing state before processing the next header
   5086  * (or footer) line.
   5087  * @param c the connection to process
   5088  */
   5089 _MHD_static_inline void
   5090 reset_rq_header_processing_state (struct MHD_Connection *c)
   5091 {
   5092   memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr));
   5093 }
   5094 
   5095 
   5096 /**
   5097  * Switch to request headers (field lines) processing state.
   5098  * @param c the connection to process
   5099  */
   5100 _MHD_static_inline void
   5101 switch_to_rq_headers_processing (struct MHD_Connection *c)
   5102 {
   5103   c->rq.field_lines.start = c->read_buffer;
   5104   memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr));
   5105   c->state = MHD_CONNECTION_REQ_HEADERS_RECEIVING;
   5106 }
   5107 
   5108 
   5109 #ifndef MHD_MAX_EMPTY_LINES_SKIP
   5110 /**
   5111  * The maximum number of ignored empty line before the request line
   5112  * at default "strictness" level.
   5113  */
   5114 #define MHD_MAX_EMPTY_LINES_SKIP 1024
   5115 #endif /* ! MHD_MAX_EMPTY_LINES_SKIP */
   5116 
   5117 /**
   5118  * Find and parse the request line.
   5119  * @param c the connection to process
   5120  * @return true if request line completely processed (or unrecoverable error
   5121  *         found) and state is changed,
   5122  *         false if not enough data yet in the receive buffer
   5123  */
   5124 static bool
   5125 get_request_line_inner (struct MHD_Connection *c)
   5126 {
   5127   size_t p; /**< The current processing position */
   5128   const int discp_lvl = c->daemon->client_discipline;
   5129   /* Allow to skip one or more empty lines before the request line.
   5130      RFC 9112, section 2.2 */
   5131   const bool skip_empty_lines = (1 >= discp_lvl);
   5132   /* Allow to skip more then one empty line before the request line.
   5133      RFC 9112, section 2.2 */
   5134   const bool skip_several_empty_lines = (skip_empty_lines && (0 >= discp_lvl));
   5135   /* Allow to skip number of unlimited empty lines before the request line.
   5136      RFC 9112, section 2.2 */
   5137   const bool skip_unlimited_empty_lines =
   5138     (skip_empty_lines && (-3 >= discp_lvl));
   5139   /* Treat bare LF as the end of the line.
   5140      RFC 9112, section 2.2 */
   5141   const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl);
   5142   /* Treat tab as whitespace delimiter.
   5143      RFC 9112, section 3 */
   5144   const bool tab_as_wsp = (0 >= discp_lvl);
   5145   /* Treat VT (vertical tab) and FF (form feed) as whitespace delimiters.
   5146      RFC 9112, section 3 */
   5147   const bool other_wsp_as_wsp = (-1 >= discp_lvl);
   5148   /* Treat continuous whitespace block as a single space.
   5149      RFC 9112, section 3 */
   5150   const bool wsp_blocks = (-1 >= discp_lvl);
   5151   /* Parse whitespace in URI, special parsing of the request line.
   5152      RFC 9112, section 3.2 */
   5153   const bool wsp_in_uri = (0 >= discp_lvl);
   5154   /* Keep whitespace in URI, give app URI with whitespace instead of
   5155      automatic redirect to fixed URI.
   5156      Violates RFC 9112, section 3.2 */
   5157   const bool wsp_in_uri_keep = (-2 >= discp_lvl);
   5158   /* Keep bare CR character as is.
   5159      Violates RFC 9112, section 2.2 */
   5160   const bool bare_cr_keep = (wsp_in_uri_keep && (-3 >= discp_lvl));
   5161   /* Treat bare CR as space; replace it with space before processing.
   5162      RFC 9112, section 2.2 */
   5163   const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl));
   5164 
   5165   mhd_assert (MHD_CONNECTION_INIT == c->state || \
   5166               MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5167   mhd_assert (NULL == c->rq.method || \
   5168               MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5169   mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \
   5170               MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5171   mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \
   5172               0 != c->rq.hdrs.rq_line.proc_pos);
   5173 
   5174   if (0 == c->read_buffer_offset)
   5175   {
   5176     mhd_assert (MHD_CONNECTION_INIT == c->state);
   5177     return false; /* No data to process */
   5178   }
   5179   p = c->rq.hdrs.rq_line.proc_pos;
   5180   mhd_assert (p <= c->read_buffer_offset);
   5181 
   5182   /* Skip empty lines, if any (and if allowed) */
   5183   /* See RFC 9112, section 2.2 */
   5184   if ((0 == p)
   5185       && (skip_empty_lines))
   5186   {
   5187     /* Skip empty lines before the request line.
   5188        See RFC 9112, section 2.2 */
   5189     bool is_empty_line;
   5190     mhd_assert (MHD_CONNECTION_INIT == c->state);
   5191     mhd_assert (NULL == c->rq.method);
   5192     mhd_assert (NULL == c->rq.url);
   5193     mhd_assert (0 == c->rq.url_len);
   5194     mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt);
   5195     mhd_assert (0 == c->rq.req_target_len);
   5196     mhd_assert (NULL == c->rq.version);
   5197     do
   5198     {
   5199       is_empty_line = false;
   5200       if ('\r' == c->read_buffer[0])
   5201       {
   5202         if (1 == c->read_buffer_offset)
   5203           return false; /* Not enough data yet */
   5204         if ('\n' == c->read_buffer[1])
   5205         {
   5206           is_empty_line = true;
   5207           c->read_buffer += 2;
   5208           c->read_buffer_size -= 2;
   5209           c->read_buffer_offset -= 2;
   5210           c->rq.hdrs.rq_line.skipped_empty_lines++;
   5211         }
   5212       }
   5213       else if (('\n' == c->read_buffer[0]) &&
   5214                (bare_lf_as_crlf))
   5215       {
   5216         is_empty_line = true;
   5217         c->read_buffer += 1;
   5218         c->read_buffer_size -= 1;
   5219         c->read_buffer_offset -= 1;
   5220         c->rq.hdrs.rq_line.skipped_empty_lines++;
   5221       }
   5222       if (is_empty_line)
   5223       {
   5224         if ((! skip_unlimited_empty_lines) &&
   5225             (((unsigned int) ((skip_several_empty_lines) ?
   5226                               MHD_MAX_EMPTY_LINES_SKIP : 1)) <
   5227              c->rq.hdrs.rq_line.skipped_empty_lines))
   5228         {
   5229           connection_close_error (c,
   5230                                   _ ("Too many meaningless extra empty lines " \
   5231                                      "received before the request"));
   5232           return true; /* Process connection closure */
   5233         }
   5234         if (0 == c->read_buffer_offset)
   5235           return false;  /* No more data to process */
   5236       }
   5237     } while (is_empty_line);
   5238   }
   5239   /* All empty lines are skipped */
   5240 
   5241   c->state = MHD_CONNECTION_REQ_LINE_RECEIVING;
   5242   /* Read and parse the request line */
   5243   mhd_assert (1 <= c->read_buffer_offset);
   5244 
   5245   while (p < c->read_buffer_offset)
   5246   {
   5247     const char chr = c->read_buffer[p];
   5248     bool end_of_line;
   5249     /*
   5250        The processing logic is different depending on the configured strictness:
   5251 
   5252        When whitespace BLOCKS are NOT ALLOWED, the end of the whitespace is
   5253        processed BEFORE processing of the current character.
   5254        When whitespace BLOCKS are ALLOWED, the end of the whitespace is
   5255        processed AFTER processing of the current character.
   5256 
   5257        When space char in the URI is ALLOWED, the delimiter between the URI and
   5258        the HTTP version string is processed only at the END of the line.
   5259        When space in the URI is NOT ALLOWED, the delimiter between the URI and
   5260        the HTTP version string is processed as soon as the FIRST whitespace is
   5261        found after URI start.
   5262      */
   5263 
   5264     end_of_line = false;
   5265 
   5266     mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \
   5267                 (c->rq.hdrs.rq_line.last_ws_end > \
   5268                  c->rq.hdrs.rq_line.last_ws_start));
   5269     mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_start) || \
   5270                 (0 != c->rq.hdrs.rq_line.last_ws_end));
   5271 
   5272     /* Check for the end of the line */
   5273     if ('\r' == chr)
   5274     {
   5275       if (p + 1 == c->read_buffer_offset)
   5276       {
   5277         c->rq.hdrs.rq_line.proc_pos = p;
   5278         return false; /* Not enough data yet */
   5279       }
   5280       else if ('\n' == c->read_buffer[p + 1])
   5281         end_of_line = true;
   5282       else
   5283       {
   5284         /* Bare CR alone */
   5285         /* Must be rejected or replaced with space char.
   5286            See RFC 9112, section 2.2 */
   5287         if (bare_cr_as_sp)
   5288         {
   5289           c->read_buffer[p] = ' ';
   5290           c->rq.num_cr_sp_replaced++;
   5291           continue; /* Re-start processing of the current character */
   5292         }
   5293         else if (! bare_cr_keep)
   5294         {
   5295           /* A quick simple check whether this line looks like an HTTP request */
   5296           if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) &&
   5297               (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd))
   5298           {
   5299             transmit_error_response_static (c,
   5300                                             MHD_HTTP_BAD_REQUEST,
   5301                                             BARE_CR_IN_HEADER);
   5302           }
   5303           else
   5304             connection_close_error (c,
   5305                                     _ ("Bare CR characters are not allowed " \
   5306                                        "in the request line.\n"));
   5307           return true; /* Error in the request */
   5308         }
   5309       }
   5310     }
   5311     else if ('\n' == chr)
   5312     {
   5313       /* Bare LF may be recognised as a line delimiter.
   5314          See RFC 9112, section 2.2 */
   5315       if (bare_lf_as_crlf)
   5316         end_of_line = true;
   5317       else
   5318       {
   5319         /* While RFC does not enforce error for bare LF character,
   5320            if this char is not treated as a line delimiter, it should be
   5321            rejected to avoid any security weakness due to request smuggling. */
   5322         /* A quick simple check whether this line looks like an HTTP request */
   5323         if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) &&
   5324             (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd))
   5325         {
   5326           transmit_error_response_static (c,
   5327                                           MHD_HTTP_BAD_REQUEST,
   5328                                           BARE_LF_IN_HEADER);
   5329         }
   5330         else
   5331           connection_close_error (c,
   5332                                   _ ("Bare LF characters are not allowed " \
   5333                                      "in the request line.\n"));
   5334         return true; /* Error in the request */
   5335       }
   5336     }
   5337 
   5338     if (end_of_line)
   5339     {
   5340       /* Handle the end of the request line */
   5341 
   5342       if (NULL != c->rq.method)
   5343       {
   5344         if (wsp_in_uri)
   5345         {
   5346           /* The end of the URI and the start of the HTTP version string
   5347              should be determined now. */
   5348           mhd_assert (NULL == c->rq.version);
   5349           mhd_assert (0 == c->rq.req_target_len);
   5350           if (0 != c->rq.hdrs.rq_line.last_ws_end)
   5351           {
   5352             /* Determine the end and the length of the URI */
   5353             if (NULL != c->rq.hdrs.rq_line.rq_tgt)
   5354             {
   5355               c->read_buffer [c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */
   5356               c->rq.req_target_len =
   5357                 c->rq.hdrs.rq_line.last_ws_start
   5358                 - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer);
   5359             }
   5360             else if ((c->rq.hdrs.rq_line.last_ws_start + 1 <
   5361                       c->rq.hdrs.rq_line.last_ws_end) &&
   5362                      (HTTP_VER_LEN == (p - c->rq.hdrs.rq_line.last_ws_end)))
   5363             {
   5364               /* Found only HTTP method and HTTP version and more than one
   5365                  whitespace between them. Assume zero-length URI. */
   5366               mhd_assert (wsp_blocks);
   5367               c->rq.hdrs.rq_line.last_ws_start++;
   5368               c->read_buffer[c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */
   5369               c->rq.hdrs.rq_line.rq_tgt =
   5370                 c->read_buffer + c->rq.hdrs.rq_line.last_ws_start;
   5371               c->rq.req_target_len = 0;
   5372               c->rq.hdrs.rq_line.num_ws_in_uri = 0;
   5373               c->rq.hdrs.rq_line.rq_tgt_qmark = NULL;
   5374             }
   5375             /* Determine the start of the HTTP version string */
   5376             if (NULL != c->rq.hdrs.rq_line.rq_tgt)
   5377             {
   5378               c->rq.version = c->read_buffer + c->rq.hdrs.rq_line.last_ws_end;
   5379             }
   5380           }
   5381         }
   5382         else
   5383         {
   5384           /* The end of the URI and the start of the HTTP version string
   5385              should be already known. */
   5386           if ((NULL == c->rq.version)
   5387               && (NULL != c->rq.hdrs.rq_line.rq_tgt)
   5388               && (HTTP_VER_LEN == p - (size_t) (c->rq.hdrs.rq_line.rq_tgt
   5389                                                 - c->read_buffer))
   5390               && (0 != c->read_buffer[(size_t)
   5391                                       (c->rq.hdrs.rq_line.rq_tgt
   5392                                        - c->read_buffer) - 1]))
   5393           {
   5394             /* Found only HTTP method and HTTP version and more than one
   5395                whitespace between them. Assume zero-length URI. */
   5396             size_t uri_pos;
   5397             mhd_assert (wsp_blocks);
   5398             mhd_assert (0 == c->rq.req_target_len);
   5399             uri_pos = (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer) - 1;
   5400             mhd_assert (uri_pos < p);
   5401             c->rq.version = c->rq.hdrs.rq_line.rq_tgt;
   5402             c->read_buffer[uri_pos] = 0;  /* Zero terminate the URI */
   5403             c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + uri_pos;
   5404             c->rq.req_target_len = 0;
   5405             c->rq.hdrs.rq_line.num_ws_in_uri = 0;
   5406             c->rq.hdrs.rq_line.rq_tgt_qmark = NULL;
   5407           }
   5408         }
   5409 
   5410         if (NULL != c->rq.version)
   5411         {
   5412           mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   5413           if (! parse_http_version (c, c->rq.version,
   5414                                     p
   5415                                     - (size_t) (c->rq.version
   5416                                                 - c->read_buffer)))
   5417           {
   5418             mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state);
   5419             return true; /* Unsupported / broken HTTP version */
   5420           }
   5421           c->read_buffer[p] = 0; /* Zero terminate the HTTP version strings */
   5422           if ('\r' == chr)
   5423           {
   5424             p++; /* Consume CR */
   5425             mhd_assert (p < c->read_buffer_offset); /* The next character has been already checked */
   5426           }
   5427           p++; /* Consume LF */
   5428           c->read_buffer += p;
   5429           c->read_buffer_size -= p;
   5430           c->read_buffer_offset -= p;
   5431           mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \
   5432                       c->rq.req_target_len);
   5433           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \
   5434                       (0 != c->rq.req_target_len));
   5435           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \
   5436                       ((size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \
   5437                                  - c->rq.hdrs.rq_line.rq_tgt) < \
   5438                        c->rq.req_target_len));
   5439           mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \
   5440                       (c->rq.hdrs.rq_line.rq_tgt_qmark >= \
   5441                        c->rq.hdrs.rq_line.rq_tgt));
   5442           return true; /* The request line is successfully parsed */
   5443         }
   5444       }
   5445       /* Error in the request line */
   5446 
   5447       /* A quick simple check whether this line looks like an HTTP request */
   5448       if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) &&
   5449           (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd))
   5450       {
   5451         transmit_error_response_static (c,
   5452                                         MHD_HTTP_BAD_REQUEST,
   5453                                         REQUEST_MALFORMED);
   5454       }
   5455       else
   5456         connection_close_error (c,
   5457                                 _ ("The request line is malformed.\n"));
   5458 
   5459       return true;
   5460     }
   5461 
   5462     /* Process possible end of the previously found whitespace delimiter */
   5463     if ((! wsp_blocks) &&
   5464         (p == c->rq.hdrs.rq_line.last_ws_end) &&
   5465         (0 != c->rq.hdrs.rq_line.last_ws_end))
   5466     {
   5467       /* Previous character was a whitespace char and whitespace blocks
   5468          are not allowed. */
   5469       /* The current position is the next character after
   5470          a whitespace delimiter */
   5471       if (NULL == c->rq.hdrs.rq_line.rq_tgt)
   5472       {
   5473         /* The current position is the start of the URI */
   5474         mhd_assert (0 == c->rq.req_target_len);
   5475         mhd_assert (NULL == c->rq.version);
   5476         c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p;
   5477         /* Reset the whitespace marker */
   5478         c->rq.hdrs.rq_line.last_ws_start = 0;
   5479         c->rq.hdrs.rq_line.last_ws_end = 0;
   5480       }
   5481       else
   5482       {
   5483         /* It was a whitespace after the start of the URI */
   5484         if (! wsp_in_uri)
   5485         {
   5486           mhd_assert ((0 != c->rq.req_target_len) || \
   5487                       (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p));
   5488           mhd_assert (NULL == c->rq.version); /* Too many whitespaces? This error is handled at whitespace start */
   5489           c->rq.version = c->read_buffer + p;
   5490           /* Reset the whitespace marker */
   5491           c->rq.hdrs.rq_line.last_ws_start = 0;
   5492           c->rq.hdrs.rq_line.last_ws_end = 0;
   5493         }
   5494       }
   5495     }
   5496 
   5497     /* Process the current character.
   5498        Is it not the end of the line.  */
   5499     if ((' ' == chr)
   5500         || (('\t' == chr) && (tab_as_wsp))
   5501         || ((other_wsp_as_wsp) && ((0xb == chr) || (0xc == chr))))
   5502     {
   5503       /* A whitespace character */
   5504       if ((0 == c->rq.hdrs.rq_line.last_ws_end) ||
   5505           (p != c->rq.hdrs.rq_line.last_ws_end) ||
   5506           (! wsp_blocks))
   5507       {
   5508         /* Found first whitespace char of the new whitespace block */
   5509         if (NULL == c->rq.method)
   5510         {
   5511           /* Found the end of the HTTP method string */
   5512           mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_start);
   5513           mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_end);
   5514           mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt);
   5515           mhd_assert (0 == c->rq.req_target_len);
   5516           mhd_assert (NULL == c->rq.version);
   5517           if (0 == p)
   5518           {
   5519             connection_close_error (c,
   5520                                     _ ("The request line starts with "
   5521                                        "a whitespace.\n"));
   5522             return true; /* Error in the request */
   5523           }
   5524           c->read_buffer[p] = 0; /* Zero-terminate the request method string */
   5525           c->rq.method = c->read_buffer;
   5526           parse_http_std_method (c, c->rq.method, p);
   5527         }
   5528         else
   5529         {
   5530           /* A whitespace after the start of the URI */
   5531           if (! wsp_in_uri)
   5532           {
   5533             /* Whitespace in URI is not allowed to be parsed */
   5534             if (NULL == c->rq.version)
   5535             {
   5536               mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   5537               /* This is a delimiter between URI and HTTP version string */
   5538               c->read_buffer[p] = 0; /* Zero-terminate request URI string */
   5539               mhd_assert (((size_t) (c->rq.hdrs.rq_line.rq_tgt   \
   5540                                      - c->read_buffer)) <= p);
   5541               c->rq.req_target_len =
   5542                 p - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer);
   5543             }
   5544             else
   5545             {
   5546               /* This is a delimiter AFTER version string */
   5547 
   5548               /* A quick simple check whether this line looks like an HTTP request */
   5549               if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) &&
   5550                   (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd))
   5551               {
   5552                 transmit_error_response_static (c,
   5553                                                 MHD_HTTP_BAD_REQUEST,
   5554                                                 RQ_LINE_TOO_MANY_WSP);
   5555               }
   5556               else
   5557                 connection_close_error (c,
   5558                                         _ ("The request line has more than "
   5559                                            "two whitespaces.\n"));
   5560               return true; /* Error in the request */
   5561             }
   5562           }
   5563           else
   5564           {
   5565             /* Whitespace in URI is allowed to be parsed */
   5566             if (0 != c->rq.hdrs.rq_line.last_ws_end)
   5567             {
   5568               /* The whitespace after the start of the URI has been found already */
   5569               c->rq.hdrs.rq_line.num_ws_in_uri +=
   5570                 c->rq.hdrs.rq_line.last_ws_end
   5571                 - c->rq.hdrs.rq_line.last_ws_start;
   5572             }
   5573           }
   5574         }
   5575         c->rq.hdrs.rq_line.last_ws_start = p;
   5576         c->rq.hdrs.rq_line.last_ws_end = p + 1; /* Will be updated on the next char parsing */
   5577       }
   5578       else
   5579       {
   5580         /* Continuation of the whitespace block */
   5581         mhd_assert (0 != c->rq.hdrs.rq_line.last_ws_end);
   5582         mhd_assert (0 != p);
   5583         c->rq.hdrs.rq_line.last_ws_end = p + 1;
   5584       }
   5585     }
   5586     else
   5587     {
   5588       /* Non-whitespace char, not the end of the line */
   5589       mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \
   5590                   (c->rq.hdrs.rq_line.last_ws_end == p) || \
   5591                   wsp_in_uri);
   5592 
   5593       if ((p == c->rq.hdrs.rq_line.last_ws_end) &&
   5594           (0 != c->rq.hdrs.rq_line.last_ws_end) &&
   5595           (wsp_blocks))
   5596       {
   5597         /* The end of the whitespace block */
   5598         if (NULL == c->rq.hdrs.rq_line.rq_tgt)
   5599         {
   5600           /* This is the first character of the URI */
   5601           mhd_assert (0 == c->rq.req_target_len);
   5602           mhd_assert (NULL == c->rq.version);
   5603           c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p;
   5604           /* Reset the whitespace marker */
   5605           c->rq.hdrs.rq_line.last_ws_start = 0;
   5606           c->rq.hdrs.rq_line.last_ws_end = 0;
   5607         }
   5608         else
   5609         {
   5610           if (! wsp_in_uri)
   5611           {
   5612             /* This is the first character of the HTTP version */
   5613             mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   5614             mhd_assert ((0 != c->rq.req_target_len) || \
   5615                         (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p));
   5616             mhd_assert (NULL == c->rq.version); /* Handled at whitespace start */
   5617             c->rq.version = c->read_buffer + p;
   5618             /* Reset the whitespace marker */
   5619             c->rq.hdrs.rq_line.last_ws_start = 0;
   5620             c->rq.hdrs.rq_line.last_ws_end = 0;
   5621           }
   5622         }
   5623       }
   5624 
   5625       /* Handle other special characters */
   5626       if ('?' == chr)
   5627       {
   5628         if ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) &&
   5629             (NULL != c->rq.hdrs.rq_line.rq_tgt))
   5630         {
   5631           c->rq.hdrs.rq_line.rq_tgt_qmark = c->read_buffer + p;
   5632         }
   5633       }
   5634       else if ((0xb == chr) || (0xc == chr))
   5635       {
   5636         /* VT or LF characters */
   5637         mhd_assert (! other_wsp_as_wsp);
   5638         if ((NULL != c->rq.hdrs.rq_line.rq_tgt) &&
   5639             (NULL == c->rq.version) &&
   5640             (wsp_in_uri))
   5641         {
   5642           c->rq.hdrs.rq_line.num_ws_in_uri++;
   5643         }
   5644         else
   5645         {
   5646           connection_close_error (c,
   5647                                   _ ("Invalid character is in the "
   5648                                      "request line.\n"));
   5649           return true; /* Error in the request */
   5650         }
   5651       }
   5652       else if (0 == chr)
   5653       {
   5654         /* NUL character */
   5655         connection_close_error (c,
   5656                                 _ ("The NUL character is in the "
   5657                                    "request line.\n"));
   5658         return true; /* Error in the request */
   5659       }
   5660     }
   5661 
   5662     p++;
   5663   }
   5664 
   5665   c->rq.hdrs.rq_line.proc_pos = p;
   5666   return false; /* Not enough data yet */
   5667 }
   5668 
   5669 
   5670 #ifndef MHD_MAX_FIXED_URI_LEN
   5671 /**
   5672  * The maximum size of the fixed URI for automatic redirection
   5673  */
   5674 #define MHD_MAX_FIXED_URI_LEN (64 * 1024)
   5675 #endif /* ! MHD_MAX_FIXED_URI_LEN */
   5676 
   5677 /**
   5678  * Send the automatic redirection to fixed URI when received URI with
   5679  * whitespaces.
   5680  * If URI is too large, close connection with error.
   5681  *
   5682  * @param c the connection to process
   5683  */
   5684 static void
   5685 send_redirect_fixed_rq_target (struct MHD_Connection *c)
   5686 {
   5687   char *b;
   5688   size_t fixed_uri_len;
   5689   size_t i;
   5690   size_t o;
   5691   char *hdr_name;
   5692   size_t hdr_name_len;
   5693 
   5694   mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5695   mhd_assert (0 != c->rq.hdrs.rq_line.num_ws_in_uri);
   5696   mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \
   5697               c->rq.req_target_len);
   5698   fixed_uri_len = c->rq.req_target_len
   5699                   + 2 * c->rq.hdrs.rq_line.num_ws_in_uri;
   5700   if ( (fixed_uri_len + 200 > c->daemon->pool_size) ||
   5701        (fixed_uri_len > MHD_MAX_FIXED_URI_LEN) ||
   5702        (NULL == (b = malloc (fixed_uri_len + 1))) )
   5703   {
   5704     connection_close_error (c,
   5705                             _ ("The request has whitespace character is " \
   5706                                "in the URI and the URI is too large to " \
   5707                                "send automatic redirect to fixed URI.\n"));
   5708     return;
   5709   }
   5710   i = 0;
   5711   o = 0;
   5712 
   5713   do
   5714   {
   5715     const char chr = c->rq.hdrs.rq_line.rq_tgt[i++];
   5716     /* The number of bytes that this iteration appends to the buffer. */
   5717     const size_t add_size =
   5718       ((' ' == chr) || ('\t' == chr) || (0x0B == chr) || (0x0C == chr)) ? 3 : 1;
   5719 
   5720     mhd_assert ('\r' != chr); /* Replaced during request line parsing */
   5721     mhd_assert ('\n' != chr); /* Rejected during request line parsing */
   5722     mhd_assert (0 != chr); /* Rejected during request line parsing */
   5723     /* Check the remaining space before write. */
   5724     if (MHD_CHECK_FAILED_ (add_size <= fixed_uri_len - o))
   5725     {
   5726       MHD_CHECK_LOG_ (c->daemon,
   5727                       "add_size <= fixed_uri_len - o");
   5728       free (b);
   5729       connection_close_error (c,
   5730                               NULL);
   5731       return;
   5732     }
   5733     switch (chr)
   5734     {
   5735     case ' ':
   5736       b[o++] = '%';
   5737       b[o++] = '2';
   5738       b[o++] = '0';
   5739       break;
   5740     case '\t':
   5741       b[o++] = '%';
   5742       b[o++] = '0';
   5743       b[o++] = '9';
   5744       break;
   5745     case 0x0B:   /* VT (vertical tab) */
   5746       b[o++] = '%';
   5747       b[o++] = '0';
   5748       b[o++] = 'B';
   5749       break;
   5750     case 0x0C:   /* FF (form feed) */
   5751       b[o++] = '%';
   5752       b[o++] = '0';
   5753       b[o++] = 'C';
   5754       break;
   5755     default:
   5756       b[o++] = chr;
   5757       break;
   5758     }
   5759   } while (i < c->rq.req_target_len);
   5760   mhd_assert (fixed_uri_len == o);
   5761   b[o] = 0; /* Zero-terminate the result */
   5762 
   5763   hdr_name_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_LOCATION);
   5764   hdr_name = malloc (hdr_name_len + 1);
   5765   if (NULL != hdr_name)
   5766   {
   5767     memcpy (hdr_name,
   5768             MHD_HTTP_HEADER_LOCATION,
   5769             hdr_name_len + 1);
   5770     /* hdr_name and b are free()d within this call */
   5771     transmit_error_response_header (c,
   5772                                     MHD_HTTP_MOVED_PERMANENTLY,
   5773                                     RQ_TARGET_INVALID_CHAR,
   5774                                     hdr_name,
   5775                                     hdr_name_len,
   5776                                     b,
   5777                                     o);
   5778     return;
   5779   }
   5780   free (b);
   5781   connection_close_error (c,
   5782                           _ ("The request has whitespace character is in the " \
   5783                              "URI.\n"));
   5784   return;
   5785 }
   5786 
   5787 
   5788 /**
   5789  * Process request-target string, form URI and URI parameters
   5790  * @param c the connection to process
   5791  * @return true if request-target successfully processed,
   5792  *         false if error encountered
   5793  */
   5794 static bool
   5795 process_request_target (struct MHD_Connection *c)
   5796 {
   5797 #ifdef _DEBUG
   5798   size_t params_len;
   5799 #endif /* _DEBUG */
   5800   mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5801   mhd_assert (NULL == c->rq.url);
   5802   mhd_assert (0 == c->rq.url_len);
   5803   mhd_assert (NULL == c->rq.url_for_callback);
   5804   mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   5805   mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \
   5806               (c->rq.hdrs.rq_line.rq_tgt <= c->rq.hdrs.rq_line.rq_tgt_qmark));
   5807   mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \
   5808               (c->rq.req_target_len > \
   5809                (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \
   5810                          - c->rq.hdrs.rq_line.rq_tgt)));
   5811 
   5812   /* Log callback before the request-target is modified/decoded */
   5813   if (NULL != c->daemon->uri_log_callback)
   5814   {
   5815     c->rq.client_aware = true;
   5816     c->rq.client_context =
   5817       c->daemon->uri_log_callback (c->daemon->uri_log_callback_cls,
   5818                                    c->rq.hdrs.rq_line.rq_tgt,
   5819                                    c);
   5820   }
   5821 
   5822   if (NULL != c->rq.hdrs.rq_line.rq_tgt_qmark)
   5823   {
   5824 #ifdef _DEBUG
   5825     params_len =
   5826       c->rq.req_target_len
   5827       - (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark - c->rq.hdrs.rq_line.rq_tgt);
   5828 #endif /* _DEBUG */
   5829     c->rq.hdrs.rq_line.rq_tgt_qmark[0] = 0; /* Replace '?' with zero termination */
   5830     if (MHD_NO == MHD_parse_arguments_ (c,
   5831                                         MHD_GET_ARGUMENT_KIND,
   5832                                         c->rq.hdrs.rq_line.rq_tgt_qmark + 1,
   5833                                         &connection_add_header,
   5834                                         c))
   5835     {
   5836       mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING != c->state);
   5837       return false;
   5838     }
   5839   }
   5840 #ifdef _DEBUG
   5841   else
   5842     params_len = 0;
   5843 #endif /* _DEBUG */
   5844 
   5845   mhd_assert (NULL == c->rq.url_for_callback);
   5846   mhd_assert (strlen (c->rq.hdrs.rq_line.rq_tgt) == \
   5847               c->rq.req_target_len - params_len);
   5848 
   5849   /* Finally unescape URI itself */
   5850   c->rq.url_len =
   5851     c->daemon->unescape_callback (c->daemon->unescape_callback_cls,
   5852                                   c,
   5853                                   c->rq.hdrs.rq_line.rq_tgt);
   5854   c->rq.url = c->rq.hdrs.rq_line.rq_tgt;
   5855 
   5856   if (2 == c->daemon->allow_bzero_in_url)
   5857     c->rq.url_for_callback = c->rq.url;
   5858   else if (strlen (c->rq.url) == c->rq.url_len)
   5859     c->rq.url_for_callback = c->rq.url;
   5860   else if (0 == c->daemon->allow_bzero_in_url)
   5861   {
   5862     transmit_error_response_static (c,
   5863                                     MHD_HTTP_BAD_REQUEST,
   5864                                     REQUEST_HAS_NUL_CHAR_IN_PATH);
   5865     return false;
   5866   }
   5867 
   5868   return true;
   5869 }
   5870 
   5871 
   5872 /**
   5873  * Find and parse the request line.
   5874  * Advance to the next state when done, handle errors.
   5875  * @param c the connection to process
   5876  * @return true if request line completely processed and state is changed,
   5877  *         false if not enough data yet in the receive buffer
   5878  */
   5879 static bool
   5880 get_request_line (struct MHD_Connection *c)
   5881 {
   5882   const int discp_lvl = c->daemon->client_discipline;
   5883   /* Parse whitespace in URI, special parsing of the request line */
   5884   const bool wsp_in_uri = (0 >= discp_lvl);
   5885   /* Keep whitespace in URI, give app URI with whitespace instead of
   5886      automatic redirect to fixed URI */
   5887   const bool wsp_in_uri_keep = (-2 >= discp_lvl);
   5888 
   5889   if (! get_request_line_inner (c))
   5890   {
   5891     /* End of the request line has not been found yet */
   5892     mhd_assert ((! wsp_in_uri) || NULL == c->rq.version);
   5893     if ((NULL != c->rq.version) &&
   5894         (HTTP_VER_LEN <
   5895          (c->rq.hdrs.rq_line.proc_pos
   5896           - (size_t) (c->rq.version - c->read_buffer))))
   5897     {
   5898       c->rq.http_ver = MHD_HTTP_VER_INVALID;
   5899       transmit_error_response_static (c,
   5900                                       MHD_HTTP_BAD_REQUEST,
   5901                                       REQUEST_MALFORMED);
   5902       return true; /* Error in the request */
   5903     }
   5904     return false;
   5905   }
   5906   if (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state)
   5907     return true; /* Error in the request */
   5908 
   5909   mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state);
   5910   mhd_assert (NULL == c->rq.url);
   5911   mhd_assert (0 == c->rq.url_len);
   5912   mhd_assert (NULL == c->rq.url_for_callback);
   5913   mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt);
   5914   if (0 != c->rq.hdrs.rq_line.num_ws_in_uri)
   5915   {
   5916     if (! wsp_in_uri)
   5917     {
   5918       transmit_error_response_static (c,
   5919                                       MHD_HTTP_BAD_REQUEST,
   5920                                       RQ_TARGET_INVALID_CHAR);
   5921       return true; /* Error in the request */
   5922     }
   5923     if (! wsp_in_uri_keep)
   5924     {
   5925       send_redirect_fixed_rq_target (c);
   5926       return true; /* Error in the request */
   5927     }
   5928   }
   5929   if (! process_request_target (c))
   5930     return true; /* Error in processing */
   5931 
   5932   c->state = MHD_CONNECTION_REQ_LINE_RECEIVED;
   5933   return true;
   5934 }
   5935 
   5936 
   5937 /**
   5938  * Results of header line reading
   5939  */
   5940 enum MHD_HdrLineReadRes_
   5941 {
   5942   /**
   5943    * Not enough data yet
   5944    */
   5945   MHD_HDR_LINE_READING_NEED_MORE_DATA = 0,
   5946   /**
   5947    * New header line has been read
   5948    */
   5949   MHD_HDR_LINE_READING_GOT_HEADER,
   5950   /**
   5951    * Error in header data, error response has been queued
   5952    */
   5953   MHD_HDR_LINE_READING_DATA_ERROR,
   5954   /**
   5955    * Found the end of the request header (end of field lines)
   5956    */
   5957   MHD_HDR_LINE_READING_GOT_END_OF_HEADER
   5958 } _MHD_FIXED_ENUM;
   5959 
   5960 
   5961 /**
   5962  * Check if a character is legal inside of a field
   5963  * name according to RFC 9110.
   5964  *
   5965  * @param chr character to test
   5966  * @return true if character is allowed
   5967  */
   5968 _MHD_static_inline bool
   5969 char_legal_in_field_name (char chr)
   5970 {
   5971   switch (chr)
   5972   {
   5973   case '!':
   5974   case '#':
   5975   case '$':
   5976   case '%':
   5977   case '&':
   5978   case '\'':
   5979   case '*':
   5980   case '+':
   5981   case '-':
   5982   case '.':
   5983   case '^':
   5984   case '_':
   5985   case '`':
   5986   case '|':
   5987   case '~':
   5988   case 'a':
   5989   case 'b':
   5990   case 'c':
   5991   case 'd':
   5992   case 'e':
   5993   case 'f':
   5994   case 'g':
   5995   case 'h':
   5996   case 'i':
   5997   case 'j':
   5998   case 'k':
   5999   case 'l':
   6000   case 'm':
   6001   case 'n':
   6002   case 'o':
   6003   case 'p':
   6004   case 'q':
   6005   case 'r':
   6006   case 's':
   6007   case 't':
   6008   case 'u':
   6009   case 'v':
   6010   case 'w':
   6011   case 'x':
   6012   case 'y':
   6013   case 'z':
   6014   case 'A':
   6015   case 'B':
   6016   case 'C':
   6017   case 'D':
   6018   case 'E':
   6019   case 'F':
   6020   case 'G':
   6021   case 'H':
   6022   case 'I':
   6023   case 'J':
   6024   case 'K':
   6025   case 'L':
   6026   case 'M':
   6027   case 'N':
   6028   case 'O':
   6029   case 'P':
   6030   case 'Q':
   6031   case 'R':
   6032   case 'S':
   6033   case 'T':
   6034   case 'U':
   6035   case 'V':
   6036   case 'W':
   6037   case 'X':
   6038   case 'Y':
   6039   case 'Z':
   6040   case '0':
   6041   case '1':
   6042   case '2':
   6043   case '3':
   6044   case '4':
   6045   case '5':
   6046   case '6':
   6047   case '7':
   6048   case '8':
   6049   case '9':
   6050     return true;
   6051   default:
   6052     return false;
   6053   }
   6054 }
   6055 
   6056 
   6057 /**
   6058  * Find the end of the request header line and make basic header parsing.
   6059  * Handle errors and header folding.
   6060  * @param c the connection to process
   6061  * @param process_footers if true then footers are processed,
   6062  *                        if false then headers are processed
   6063  * @param[out] hdr_name the name of the parsed header (field)
   6064  * @param[out] hdr_name the value of the parsed header (field)
   6065  * @return true if request header line completely processed,
   6066  *         false if not enough data yet in the receive buffer
   6067  */
   6068 static enum MHD_HdrLineReadRes_
   6069 get_req_header (struct MHD_Connection *c,
   6070                 bool process_footers,
   6071                 struct _MHD_str_w_len *hdr_name,
   6072                 struct _MHD_str_w_len *hdr_value)
   6073 {
   6074   const int discp_lvl = c->daemon->client_discipline;
   6075   /* Treat bare LF as the end of the line.
   6076      RFC 9112, section 2.2-3
   6077      Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5).
   6078      Bare LF is processed as end of the line or rejected as broken request. */
   6079   const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl);
   6080   /* Keep bare CR character as is.
   6081      Violates RFC 9112, section 2.2-4 */
   6082   const bool bare_cr_keep = (-3 >= discp_lvl);
   6083   /* Treat bare CR as space; replace it with space before processing.
   6084      RFC 9112, section 2.2-4 */
   6085   const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl));
   6086   /* Treat NUL as space; replace it with space before processing.
   6087      RFC 9110, section 5.5-5 */
   6088   const bool nul_as_sp = (-1 >= discp_lvl);
   6089   /* Allow folded header lines.
   6090      RFC 9112, section 5.2-4 */
   6091   const bool allow_folded = (0 >= discp_lvl);
   6092   /* Do not reject headers with the whitespace at the start of the first line.
   6093      When allowed, the first line with whitespace character at the first
   6094      position is ignored (as well as all possible line foldings of the first
   6095      line).
   6096      RFC 9112, section 2.2-8 */
   6097   const bool allow_wsp_at_start = allow_folded && (-1 >= discp_lvl);
   6098   /* Allow whitespace in header (field) name.
   6099      Violates RFC 9110, section 5.1-2 */
   6100   const bool allow_wsp_in_name = (-2 >= discp_lvl);
   6101   /* Allow zero-length header (field) name.
   6102      Violates RFC 9110, section 5.1-2 */
   6103   const bool allow_empty_name = (-2 >= discp_lvl);
   6104   /* Allow non-tchar characters in header (field) name.
   6105      Violates RFC 9110, section 5.1 */
   6106   const bool allow_extended_charset = (-2 >= discp_lvl);
   6107   /* Allow whitespace before colon.
   6108      Violates RFC 9112, section 5.1-2 */
   6109   const bool allow_wsp_before_colon = (-3 >= discp_lvl);
   6110   /* Do not abort the request when header line has no colon, just skip such
   6111      bad lines.
   6112      RFC 9112, section 5-1 */
   6113   const bool allow_line_without_colon = (-2 >= discp_lvl);
   6114 
   6115   size_t p; /**< The position of the currently processed character */
   6116 
   6117 #if ! defined (HAVE_MESSAGES) && ! defined(_DEBUG)
   6118   (void) process_footers; /* Unused parameter */
   6119 #endif /* !HAVE_MESSAGES && !_DEBUG */
   6120 
   6121   mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \
   6122                MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \
   6123               c->state);
   6124 
   6125   p = c->rq.hdrs.hdr.proc_pos;
   6126 
   6127   mhd_assert (p <= c->read_buffer_offset);
   6128   while (p < c->read_buffer_offset)
   6129   {
   6130     const char chr = c->read_buffer[p];
   6131     bool end_of_line;
   6132 
   6133     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \
   6134                 (c->rq.hdrs.hdr.name_len < p));
   6135     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || (0 != p));
   6136     mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \
   6137                 (c->rq.hdrs.hdr.name_end_found));
   6138     mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \
   6139                 (c->rq.hdrs.hdr.name_len < c->rq.hdrs.hdr.value_start));
   6140     /* A zero-length header (field) name is possible in two deliberately
   6141        non-conformant modes: a first line starting with whitespace (which is
   6142        discarded as a whole when its end is reached) and an empty field name
   6143        allowed by 'allow_empty_name'. */
   6144     mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \
   6145                 (0 != c->rq.hdrs.hdr.name_len) || \
   6146                 (c->rq.hdrs.hdr.starts_with_ws) || \
   6147                 (allow_empty_name && c->rq.hdrs.hdr.name_end_found));
   6148     mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \
   6149                 (0 == c->rq.hdrs.hdr.name_len) || \
   6150                 (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.name_len));
   6151     mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \
   6152                 (0 == c->rq.hdrs.hdr.value_start) || \
   6153                 (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start));
   6154 
   6155     /* Check for the end of the line */
   6156     if ('\r' == chr)
   6157     {
   6158       if (0 != p)
   6159       {
   6160         /* Line is not empty, need to check for possible line folding */
   6161         if (p + 2 >= c->read_buffer_offset)
   6162           break; /* Not enough data yet to check for folded line */
   6163       }
   6164       else
   6165       {
   6166         /* Line is empty, no need to check for possible line folding */
   6167         if (p + 2 > c->read_buffer_offset)
   6168           break; /* Not enough data yet to check for the end of the line */
   6169       }
   6170       if ('\n' == c->read_buffer[p + 1])
   6171         end_of_line = true;
   6172       else
   6173       {
   6174         /* Bare CR alone */
   6175         /* Must be rejected or replaced with space char.
   6176            See RFC 9112, section 2.2-4 */
   6177         if (bare_cr_as_sp)
   6178         {
   6179           c->read_buffer[p] = ' ';
   6180           c->rq.num_cr_sp_replaced++;
   6181           continue; /* Re-start processing of the current character */
   6182         }
   6183         else if (! bare_cr_keep)
   6184         {
   6185           if (! process_footers)
   6186             transmit_error_response_static (c,
   6187                                             MHD_HTTP_BAD_REQUEST,
   6188                                             BARE_CR_IN_HEADER);
   6189           else
   6190             transmit_error_response_static (c,
   6191                                             MHD_HTTP_BAD_REQUEST,
   6192                                             BARE_CR_IN_FOOTER);
   6193           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6194         }
   6195         end_of_line = false;
   6196       }
   6197     }
   6198     else if ('\n' == chr)
   6199     {
   6200       /* Bare LF may be recognised as a line delimiter.
   6201          See RFC 9112, section 2.2-3 */
   6202       if (bare_lf_as_crlf)
   6203       {
   6204         if (0 != p)
   6205         {
   6206           /* Line is not empty, need to check for possible line folding */
   6207           if (p + 1 >= c->read_buffer_offset)
   6208             break; /* Not enough data yet to check for folded line */
   6209         }
   6210         end_of_line = true;
   6211       }
   6212       else
   6213       {
   6214         if (! process_footers)
   6215           transmit_error_response_static (c,
   6216                                           MHD_HTTP_BAD_REQUEST,
   6217                                           BARE_LF_IN_HEADER);
   6218         else
   6219           transmit_error_response_static (c,
   6220                                           MHD_HTTP_BAD_REQUEST,
   6221                                           BARE_LF_IN_FOOTER);
   6222         return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6223       }
   6224     }
   6225     else
   6226       end_of_line = false;
   6227 
   6228     if (end_of_line)
   6229     {
   6230       /* Handle the end of the line */
   6231       /**
   6232        *  The full length of the line, including CRLF (or bare LF).
   6233        */
   6234       const size_t line_len = p + (('\r' == chr) ? 2 : 1);
   6235       char next_line_char;
   6236       mhd_assert (line_len <= c->read_buffer_offset);
   6237 
   6238       if (0 == p)
   6239       {
   6240         /* Zero-length header line. This is the end of the request header
   6241            section.
   6242            RFC 9112, Section 2.1-1 */
   6243         mhd_assert (! c->rq.hdrs.hdr.starts_with_ws);
   6244         mhd_assert (! c->rq.hdrs.hdr.name_end_found);
   6245         mhd_assert (0 == c->rq.hdrs.hdr.name_len);
   6246         mhd_assert (0 == c->rq.hdrs.hdr.ws_start);
   6247         mhd_assert (0 == c->rq.hdrs.hdr.value_start);
   6248         /* Consume the line with CRLF (or bare LF) */
   6249         c->read_buffer += line_len;
   6250         c->read_buffer_offset -= line_len;
   6251         c->read_buffer_size -= line_len;
   6252         return MHD_HDR_LINE_READING_GOT_END_OF_HEADER;
   6253       }
   6254 
   6255       mhd_assert (line_len < c->read_buffer_offset);
   6256       mhd_assert (0 != line_len);
   6257       mhd_assert ('\n' == c->read_buffer[line_len - 1]);
   6258       next_line_char = c->read_buffer[line_len];
   6259       if ((' ' == next_line_char) ||
   6260           ('\t' == next_line_char))
   6261       {
   6262         /* Folded line */
   6263         if (! allow_folded)
   6264         {
   6265           if (! process_footers)
   6266             transmit_error_response_static (c,
   6267                                             MHD_HTTP_BAD_REQUEST,
   6268                                             ERR_RSP_OBS_FOLD);
   6269           else
   6270             transmit_error_response_static (c,
   6271                                             MHD_HTTP_BAD_REQUEST,
   6272                                             ERR_RSP_OBS_FOLD_FOOTER);
   6273 
   6274           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6275         }
   6276         /* Replace CRLF (or bare LF) character(s) with space characters.
   6277            See RFC 9112, Section 5.2-4 */
   6278         c->read_buffer[p] = ' ';
   6279         if ('\r' == chr)
   6280           c->read_buffer[p + 1] = ' ';
   6281         continue; /* Re-start processing of the current character */
   6282       }
   6283       else
   6284       {
   6285         /* It is not a folded line, it's the real end of the non-empty line */
   6286         bool skip_line = false;
   6287         mhd_assert (0 != p);
   6288         if (c->rq.hdrs.hdr.starts_with_ws)
   6289         {
   6290           /* This is the first line and it starts with whitespace. This line
   6291              must be discarded completely.
   6292              See RFC 9112, Section 2.2-8 */
   6293           mhd_assert (allow_wsp_at_start);
   6294 #ifdef HAVE_MESSAGES
   6295           MHD_DLOG (c->daemon,
   6296                     _ ("Whitespace-prefixed first header line " \
   6297                        "has been skipped.\n"));
   6298 #endif /* HAVE_MESSAGES */
   6299           skip_line = true;
   6300         }
   6301         else if (! c->rq.hdrs.hdr.name_end_found)
   6302         {
   6303           if (! allow_line_without_colon)
   6304           {
   6305             if (! process_footers)
   6306               transmit_error_response_static (c,
   6307                                               MHD_HTTP_BAD_REQUEST,
   6308                                               ERR_RSP_HEADER_WITHOUT_COLON);
   6309             else
   6310               transmit_error_response_static (c,
   6311                                               MHD_HTTP_BAD_REQUEST,
   6312                                               ERR_RSP_FOOTER_WITHOUT_COLON);
   6313 
   6314             return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6315           }
   6316           /* Skip broken line completely */
   6317           c->rq.skipped_broken_lines++;
   6318           skip_line = true;
   6319         }
   6320         if (skip_line)
   6321         {
   6322           /* Skip the entire line */
   6323           c->read_buffer += line_len;
   6324           c->read_buffer_offset -= line_len;
   6325           c->read_buffer_size -= line_len;
   6326           p = 0;
   6327           /* Reset processing state */
   6328           memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr));
   6329           /* Start processing of the next line */
   6330           continue;
   6331         }
   6332         else
   6333         {
   6334           /* This line should be valid header line */
   6335           size_t value_len;
   6336           mhd_assert ((0 != c->rq.hdrs.hdr.name_len) || allow_empty_name);
   6337 
   6338           hdr_name->str = c->read_buffer + 0; /* The name always starts at the first character */
   6339           hdr_name->len = c->rq.hdrs.hdr.name_len;
   6340           mhd_assert (0 == hdr_name->str[hdr_name->len]);
   6341 
   6342           if (0 == c->rq.hdrs.hdr.value_start)
   6343           {
   6344             c->rq.hdrs.hdr.value_start = p;
   6345             c->read_buffer[p] = 0;
   6346             value_len = 0;
   6347           }
   6348           else if (0 != c->rq.hdrs.hdr.ws_start)
   6349           {
   6350             mhd_assert (p > c->rq.hdrs.hdr.ws_start);
   6351             mhd_assert (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start);
   6352             c->read_buffer[c->rq.hdrs.hdr.ws_start] = 0;
   6353             value_len = c->rq.hdrs.hdr.ws_start - c->rq.hdrs.hdr.value_start;
   6354           }
   6355           else
   6356           {
   6357             mhd_assert (p > c->rq.hdrs.hdr.ws_start);
   6358             c->read_buffer[p] = 0;
   6359             value_len = p - c->rq.hdrs.hdr.value_start;
   6360           }
   6361           hdr_value->str = c->read_buffer + c->rq.hdrs.hdr.value_start;
   6362           hdr_value->len = value_len;
   6363           mhd_assert (0 == hdr_value->str[hdr_value->len]);
   6364           /* Consume the entire line */
   6365           c->read_buffer += line_len;
   6366           c->read_buffer_offset -= line_len;
   6367           c->read_buffer_size -= line_len;
   6368           return MHD_HDR_LINE_READING_GOT_HEADER;
   6369         }
   6370       }
   6371     }
   6372     else if ((' ' == chr) || ('\t' == chr))
   6373     {
   6374       if (0 == p)
   6375       {
   6376         if (! allow_wsp_at_start)
   6377         {
   6378           if (! process_footers)
   6379             transmit_error_response_static (c,
   6380                                             MHD_HTTP_BAD_REQUEST,
   6381                                             ERR_RSP_WSP_BEFORE_HEADER);
   6382           else
   6383             transmit_error_response_static (c,
   6384                                             MHD_HTTP_BAD_REQUEST,
   6385                                             ERR_RSP_WSP_BEFORE_FOOTER);
   6386           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6387         }
   6388         c->rq.hdrs.hdr.starts_with_ws = true;
   6389       }
   6390       else if ((! c->rq.hdrs.hdr.name_end_found) &&
   6391                (! c->rq.hdrs.hdr.starts_with_ws))
   6392       {
   6393         /* Whitespace in header name / between header name and colon */
   6394         if (allow_wsp_in_name || allow_wsp_before_colon)
   6395         {
   6396           if (0 == c->rq.hdrs.hdr.ws_start)
   6397             c->rq.hdrs.hdr.ws_start = p;
   6398         }
   6399         else
   6400         {
   6401           if (! process_footers)
   6402             transmit_error_response_static (c,
   6403                                             MHD_HTTP_BAD_REQUEST,
   6404                                             ERR_RSP_WSP_IN_HEADER_NAME);
   6405           else
   6406             transmit_error_response_static (c,
   6407                                             MHD_HTTP_BAD_REQUEST,
   6408                                             ERR_RSP_WSP_IN_FOOTER_NAME);
   6409 
   6410           return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6411         }
   6412       }
   6413       else
   6414       {
   6415         /* Whitespace before/inside/after header (field) value */
   6416         if (0 == c->rq.hdrs.hdr.ws_start)
   6417           c->rq.hdrs.hdr.ws_start = p;
   6418       }
   6419     }
   6420     else if (0 == chr)
   6421     {
   6422       if (! nul_as_sp)
   6423       {
   6424         if (! process_footers)
   6425           transmit_error_response_static (c,
   6426                                           MHD_HTTP_BAD_REQUEST,
   6427                                           ERR_RSP_INVALID_CHR_IN_HEADER);
   6428         else
   6429           transmit_error_response_static (c,
   6430                                           MHD_HTTP_BAD_REQUEST,
   6431                                           ERR_RSP_INVALID_CHR_IN_FOOTER);
   6432 
   6433         return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6434       }
   6435       c->read_buffer[p] = ' ';
   6436       continue; /* Re-start processing of the current character */
   6437     }
   6438     else
   6439     {
   6440       /* Not a whitespace, not the end of the header line */
   6441       /* A bare CR reaches this point when it is kept as an ordinary
   6442          character ('bare_cr_keep', MHD_OPTION_CLIENT_DISCIPLINE_LVL -3);
   6443          in every other mode it is either replaced with a space or
   6444          rejected before. */
   6445       mhd_assert (('\r' != chr) || bare_cr_keep);
   6446       mhd_assert ('\n' != chr);
   6447       mhd_assert ('\0' != chr);
   6448       if ( (! c->rq.hdrs.hdr.name_end_found) &&
   6449            (! c->rq.hdrs.hdr.starts_with_ws) )
   6450       {
   6451         /* Processing the header (field) string before the header value */
   6452 
   6453         if (':' != chr)
   6454         {
   6455           /* Processing the header (field) name */
   6456           if (0 != c->rq.hdrs.hdr.ws_start)
   6457           {
   6458             /* End of the whitespace in header (field) name */
   6459             mhd_assert (allow_wsp_in_name || allow_wsp_before_colon);
   6460             if (! allow_wsp_in_name)
   6461             {
   6462               if (! process_footers)
   6463                 transmit_error_response_static (c,
   6464                                                 MHD_HTTP_BAD_REQUEST,
   6465                                                 ERR_RSP_WSP_IN_HEADER_NAME);
   6466               else
   6467                 transmit_error_response_static (c,
   6468                                                 MHD_HTTP_BAD_REQUEST,
   6469                                                 ERR_RSP_WSP_IN_FOOTER_NAME);
   6470 
   6471               return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6472             }
   6473 #ifndef MHD_FAVOR_SMALL_CODE
   6474             c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   6475 #endif /* ! MHD_FAVOR_SMALL_CODE */
   6476           }
   6477           if ( (! allow_extended_charset) &&
   6478                (! char_legal_in_field_name (chr)) )
   6479           {
   6480             transmit_error_response_static (c,
   6481                                             MHD_HTTP_BAD_REQUEST,
   6482                                             ERR_RSP_INVALID_CHAR_IN_FIELD_NAME);
   6483             return MHD_HDR_LINE_READING_DATA_ERROR;
   6484           }
   6485 #ifndef MHD_FAVOR_SMALL_CODE
   6486           /* A tight loop for processing header (field) names */
   6487           while (c->read_buffer_offset > ++p)
   6488           {
   6489             if (! char_legal_in_field_name (c->read_buffer[p]))
   6490               break; /* Re-process the current character in the standard loop */
   6491           }
   6492           continue;
   6493 #endif /* ! MHD_FAVOR_SMALL_CODE */
   6494         }
   6495         else
   6496         {
   6497           if (0 == c->rq.hdrs.hdr.ws_start)
   6498             c->rq.hdrs.hdr.name_len = p;
   6499           else
   6500           {
   6501             mhd_assert (allow_wsp_in_name || allow_wsp_before_colon);
   6502             if (! allow_wsp_before_colon)
   6503             {
   6504               if (! process_footers)
   6505                 transmit_error_response_static (c,
   6506                                                 MHD_HTTP_BAD_REQUEST,
   6507                                                 ERR_RSP_WSP_IN_HEADER_NAME);
   6508               else
   6509                 transmit_error_response_static (c,
   6510                                                 MHD_HTTP_BAD_REQUEST,
   6511                                                 ERR_RSP_WSP_IN_FOOTER_NAME);
   6512               return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6513             }
   6514             c->rq.hdrs.hdr.name_len = c->rq.hdrs.hdr.ws_start;
   6515 #ifndef MHD_FAVOR_SMALL_CODE
   6516             c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   6517 #endif /* ! MHD_FAVOR_SMALL_CODE */
   6518           }
   6519           if ((0 == c->rq.hdrs.hdr.name_len) && ! allow_empty_name)
   6520           {
   6521             if (! process_footers)
   6522               transmit_error_response_static (c,
   6523                                               MHD_HTTP_BAD_REQUEST,
   6524                                               ERR_RSP_EMPTY_HEADER_NAME);
   6525             else
   6526               transmit_error_response_static (c,
   6527                                               MHD_HTTP_BAD_REQUEST,
   6528                                               ERR_RSP_EMPTY_FOOTER_NAME);
   6529             return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */
   6530           }
   6531           c->rq.hdrs.hdr.name_end_found = true;
   6532           c->read_buffer[c->rq.hdrs.hdr.name_len] = 0; /* Zero-terminate the name */
   6533         }
   6534       }
   6535       else
   6536       {
   6537         /* Processing the header (field) value */
   6538         if (0 == c->rq.hdrs.hdr.value_start)
   6539           c->rq.hdrs.hdr.value_start = p;
   6540 #ifndef MHD_FAVOR_SMALL_CODE
   6541         /* A tight loop for processing long header (field) values */
   6542         while (1)
   6543         {
   6544           /* 'p' points to a non-whitespace character */
   6545           mhd_assert (' ' != c->read_buffer[p]);
   6546           mhd_assert ('\t' != c->read_buffer[p]);
   6547           c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   6548           while (c->read_buffer_offset > ++p)
   6549           {
   6550             /* Rough check for a non-whitespace and non-control character.
   6551                Quick processing only for the most common characters; other
   6552                characters are processed in the standard loop. */
   6553             if (((unsigned char) ' ') >= ((unsigned char) c->read_buffer[p]))
   6554               break;
   6555           }
   6556           if (c->read_buffer_offset <= p)
   6557             break;
   6558           if ((' ' != c->read_buffer[p]) && ('\t' != c->read_buffer[p]))
   6559             break; /* Not a whitespace character; re-process the current character in the standard loop */
   6560           /* Quick whitespace skipping loop */
   6561           c->rq.hdrs.hdr.ws_start = p;
   6562           while (c->read_buffer_offset > ++p)
   6563           {
   6564             if ((' ' != c->read_buffer[p]) && ('\t' != c->read_buffer[p]))
   6565               break; /* End of the whitespace sequence */
   6566           }
   6567           if (c->read_buffer_offset <= p)
   6568             break;
   6569           /* Rough check for a non-whitespace and non-control character.
   6570              Quick processing only for the most common characters; other
   6571              characters are processed in the standard loop. */
   6572           if (((unsigned char) ' ') >= ((unsigned char) c->read_buffer[p]))
   6573             break; /* Re-process the current character in the standard loop */
   6574           /* Continue in the tight loop for processing long header (field) values */
   6575         }
   6576         continue;
   6577 #endif /* ! MHD_FAVOR_SMALL_CODE */
   6578       }
   6579 #ifdef MHD_FAVOR_SMALL_CODE
   6580       c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */
   6581 #endif /* MHD_FAVOR_SMALL_CODE */
   6582     }
   6583     p++;
   6584   }
   6585   c->rq.hdrs.hdr.proc_pos = p;
   6586   return MHD_HDR_LINE_READING_NEED_MORE_DATA; /* Not enough data yet */
   6587 }
   6588 
   6589 
   6590 /**
   6591  * Find the end of the request headers and make basic header parsing.
   6592  * Advance to the next state when done, handle errors.
   6593  * @param c the connection to process
   6594  * @param process_footers if true then footers are processed,
   6595  *                        if false then headers are processed
   6596  * @return true if request headers reading finished (either successfully
   6597  *         or with error),
   6598  *         false if not enough data yet in the receive buffer
   6599  */
   6600 static bool
   6601 get_req_headers (struct MHD_Connection *c, bool process_footers)
   6602 {
   6603   do
   6604   {
   6605     struct _MHD_str_w_len hdr_name;
   6606     struct _MHD_str_w_len hdr_value;
   6607     enum MHD_HdrLineReadRes_ res;
   6608 
   6609     mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \
   6610                  MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \
   6611                 c->state);
   6612 
   6613     #ifdef _DEBUG
   6614     hdr_name.str = NULL;
   6615     hdr_value.str = NULL;
   6616 #endif /* _DEBUG */
   6617     res = get_req_header (c, process_footers, &hdr_name, &hdr_value);
   6618     if (MHD_HDR_LINE_READING_GOT_HEADER == res)
   6619     {
   6620       mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \
   6621                    MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \
   6622                   c->state);
   6623       mhd_assert (NULL != hdr_name.str);
   6624       mhd_assert (NULL != hdr_value.str);
   6625       /* Values must be zero-terminated and must not have binary zeros */
   6626       mhd_assert (strlen (hdr_name.str) == hdr_name.len);
   6627       mhd_assert (strlen (hdr_value.str) == hdr_value.len);
   6628       /* Values must not have whitespaces at the start or at the end */
   6629       mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != ' '));
   6630       mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != '\t'));
   6631       mhd_assert ((hdr_name.len == 0) || \
   6632                   (hdr_name.str[hdr_name.len - 1] != ' '));
   6633       mhd_assert ((hdr_name.len == 0) || \
   6634                   (hdr_name.str[hdr_name.len - 1] != '\t'));
   6635       mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != ' '));
   6636       mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != '\t'));
   6637       mhd_assert ((hdr_value.len == 0) || \
   6638                   (hdr_value.str[hdr_value.len - 1] != ' '));
   6639       mhd_assert ((hdr_value.len == 0) || \
   6640                   (hdr_value.str[hdr_value.len - 1] != '\t'));
   6641 
   6642       if (MHD_NO ==
   6643           MHD_set_connection_value_n_nocheck_ (c,
   6644                                                (! process_footers) ?
   6645                                                MHD_HEADER_KIND :
   6646                                                MHD_FOOTER_KIND,
   6647                                                hdr_name.str, hdr_name.len,
   6648                                                hdr_value.str, hdr_value.len))
   6649       {
   6650         size_t add_element_size;
   6651 
   6652         mhd_assert (hdr_name.str < hdr_value.str);
   6653 
   6654 #ifdef HAVE_MESSAGES
   6655         MHD_DLOG (c->daemon,
   6656                   _ ("Failed to allocate memory in the connection memory " \
   6657                      "pool to store %s.\n"),
   6658                   (! process_footers) ? _ ("header") : _ ("footer"));
   6659 #endif /* HAVE_MESSAGES */
   6660 
   6661         add_element_size = hdr_value.len
   6662                            + (size_t) (hdr_value.str - hdr_name.str);
   6663 
   6664         if (! process_footers)
   6665           handle_req_headers_no_space (c, hdr_name.str, add_element_size);
   6666         else
   6667           handle_req_footers_no_space (c, hdr_name.str, add_element_size);
   6668 
   6669         mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED < c->state);
   6670         return true;
   6671       }
   6672       /* Reset processing state */
   6673       reset_rq_header_processing_state (c);
   6674       mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \
   6675                    MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \
   6676                   c->state);
   6677       /* Read the next header (field) line */
   6678       continue;
   6679     }
   6680     else if (MHD_HDR_LINE_READING_NEED_MORE_DATA == res)
   6681     {
   6682       mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \
   6683                    MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \
   6684                   c->state);
   6685       return false;
   6686     }
   6687     else if (MHD_HDR_LINE_READING_DATA_ERROR == res)
   6688     {
   6689       mhd_assert ((process_footers ? \
   6690                    MHD_CONNECTION_FOOTERS_RECEIVING : \
   6691                    MHD_CONNECTION_REQ_HEADERS_RECEIVING) < c->state);
   6692       mhd_assert (c->stop_with_error);
   6693       mhd_assert (c->discard_request);
   6694       return true;
   6695     }
   6696     mhd_assert (MHD_HDR_LINE_READING_GOT_END_OF_HEADER == res);
   6697     break;
   6698   } while (1);
   6699 
   6700 #ifdef HAVE_MESSAGES
   6701   if (1 == c->rq.num_cr_sp_replaced)
   6702   {
   6703     MHD_DLOG (c->daemon,
   6704               _ ("One bare CR character has been replaced with space " \
   6705                  "in %s.\n"),
   6706               (! process_footers) ?
   6707               _ ("the request line or in the request headers") :
   6708               _ ("the request footers"));
   6709   }
   6710   else if (0 != c->rq.num_cr_sp_replaced)
   6711   {
   6712     MHD_DLOG (c->daemon,
   6713               _ ("%" PRIu64 " bare CR characters have been replaced with " \
   6714                  "spaces in the request line and/or in the request %s.\n"),
   6715               (uint64_t) c->rq.num_cr_sp_replaced,
   6716               (! process_footers) ? _ ("headers") : _ ("footers"));
   6717   }
   6718   if (1 == c->rq.skipped_broken_lines)
   6719   {
   6720     MHD_DLOG (c->daemon,
   6721               _ ("One %s line without colon has been skipped.\n"),
   6722               (! process_footers) ? _ ("header") : _ ("footer"));
   6723   }
   6724   else if (0 != c->rq.skipped_broken_lines)
   6725   {
   6726     MHD_DLOG (c->daemon,
   6727               _ ("%" PRIu64 " %s lines without colons has been skipped.\n"),
   6728               (uint64_t) c->rq.skipped_broken_lines,
   6729               (! process_footers) ? _ ("header") : _ ("footer"));
   6730   }
   6731 #endif /* HAVE_MESSAGES */
   6732 
   6733   mhd_assert (c->rq.method < c->read_buffer);
   6734   if (! process_footers)
   6735   {
   6736     c->rq.header_size = (size_t) (c->read_buffer - c->rq.method);
   6737     mhd_assert (NULL != c->rq.field_lines.start);
   6738     c->rq.field_lines.size =
   6739       (size_t) ((c->read_buffer - c->rq.field_lines.start) - 1);
   6740     if ('\r' == *(c->read_buffer - 2))
   6741       c->rq.field_lines.size--;
   6742     c->state = MHD_CONNECTION_HEADERS_RECEIVED;
   6743 
   6744     if (MHD_BUF_INC_SIZE > c->read_buffer_size)
   6745     {
   6746       /* Try to re-use some of the last bytes of the request header */
   6747       /* Do this only if space in the read buffer is limited AND
   6748          amount of read ahead data is small. */
   6749       /**
   6750        *  The position of the terminating NUL after the last character of
   6751        *  the last header element.
   6752        */
   6753       const char *last_elmnt_end;
   6754       size_t shift_back_size;
   6755 
   6756       if (NULL != c->rq.headers_received_tail)
   6757       {
   6758         if (NULL == c->rq.headers_received_tail->value)
   6759         {
   6760           /* Tailing query argument without '=', we only have the header */
   6761           last_elmnt_end =
   6762             c->rq.headers_received_tail->header
   6763             + c->rq.headers_received_tail->header_size;
   6764         }
   6765         else
   6766         {
   6767           last_elmnt_end =
   6768             c->rq.headers_received_tail->value
   6769             + c->rq.headers_received_tail->value_size;
   6770         }
   6771       }
   6772       else
   6773       {
   6774         last_elmnt_end = c->rq.version + HTTP_VER_LEN;
   6775       }
   6776       /* The request line strings (method, url, version) remain visible to
   6777          the application for the whole request, and the last received header
   6778          is not necessarily above them: when it is not, reclaiming down to
   6779          the header end puts the read buffer on top of the version string,
   6780          and the next recv() overwrites the terminator the application is
   6781          about to read through.  Never reclaim below the end of the request
   6782          line. */
   6783       if ((NULL != c->rq.version) &&
   6784           (last_elmnt_end < c->rq.version + HTTP_VER_LEN))
   6785         last_elmnt_end = c->rq.version + HTTP_VER_LEN;
   6786       /* Check that @a last_elmnt_end points into the request that has
   6787          just been parsed, which lives entirely
   6788          between the start of the request line and the current read buffer
   6789          position.  */
   6790       MHD_CHECK_CONN_CLOSE_RET_ (c,
   6791                                  (NULL != last_elmnt_end) &&
   6792                                  (c->rq.method <= last_elmnt_end) &&
   6793                                  (last_elmnt_end < c->read_buffer - 1),
   6794                                  true);
   6795       shift_back_size = (size_t) (c->read_buffer - (last_elmnt_end + 1));
   6796       if (0 != c->read_buffer_offset)
   6797         memmove (c->read_buffer - shift_back_size,
   6798                  c->read_buffer,
   6799                  c->read_buffer_offset);
   6800       c->read_buffer -= shift_back_size;
   6801       c->read_buffer_size += shift_back_size;
   6802     }
   6803   }
   6804   else
   6805     c->state = MHD_CONNECTION_FOOTERS_RECEIVED;
   6806 
   6807   return true;
   6808 }
   6809 
   6810 
   6811 /**
   6812  * Update the 'last_activity' field of the connection to the current time
   6813  * and move the connection to the head of the 'normal_timeout' list if
   6814  * the timeout for the connection uses the default value.
   6815  *
   6816  * @param connection the connection that saw some activity
   6817  */
   6818 void
   6819 MHD_update_last_activity_ (struct MHD_Connection *connection)
   6820 {
   6821   struct MHD_Daemon *daemon = connection->daemon;
   6822 #if defined(MHD_USE_THREADS)
   6823   mhd_assert (NULL == daemon->worker_pool);
   6824 #endif /* MHD_USE_THREADS */
   6825 
   6826   if (0 == connection->connection_timeout_ms)
   6827     return;  /* Skip update of activity for connections
   6828                without timeout timer. */
   6829   if (connection->suspended)
   6830     return;  /* no activity on suspended connections */
   6831 
   6832   connection->last_activity = MHD_monotonic_msec_counter ();
   6833   if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
   6834     return; /* each connection has personal timeout */
   6835 
   6836   if (connection->connection_timeout_ms != daemon->connection_timeout_ms)
   6837     return; /* custom timeout, no need to move it in "normal" DLL */
   6838 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   6839   MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
   6840 #endif
   6841   /* move connection to head of timeout list (by remove + add operation) */
   6842   XDLL_remove (daemon->normal_timeout_head,
   6843                daemon->normal_timeout_tail,
   6844                connection);
   6845   XDLL_insert (daemon->normal_timeout_head,
   6846                daemon->normal_timeout_tail,
   6847                connection);
   6848 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   6849   MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
   6850 #endif
   6851 }
   6852 
   6853 
   6854 /**
   6855  * This function handles a particular connection when it has been
   6856  * determined that there is data to be read off a socket. All
   6857  * implementations (multithreaded, external polling, internal polling)
   6858  * call this function to handle reads.
   6859  *
   6860  * @param connection connection to handle
   6861  * @param socket_error set to true if socket error was detected
   6862  */
   6863 void
   6864 MHD_connection_handle_read (struct MHD_Connection *connection,
   6865                             bool socket_error)
   6866 {
   6867   ssize_t bytes_read;
   6868 
   6869   if ( (MHD_CONNECTION_CLOSED == connection->state) ||
   6870        (connection->suspended) )
   6871     return;
   6872 #ifdef HTTPS_SUPPORT
   6873   if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
   6874   {   /* HTTPS connection. */
   6875     if (MHD_TLS_CONN_CONNECTED > connection->tls_state)
   6876     {
   6877       if (! MHD_run_tls_handshake_ (connection))
   6878         return;
   6879     }
   6880   }
   6881 #endif /* HTTPS_SUPPORT */
   6882 
   6883   mhd_assert (NULL != connection->read_buffer);
   6884   if (connection->read_buffer_size == connection->read_buffer_offset)
   6885     return; /* No space for receiving data. */
   6886 
   6887   bytes_read = connection->recv_cls (connection,
   6888                                      &connection->read_buffer
   6889                                      [connection->read_buffer_offset],
   6890                                      connection->read_buffer_size
   6891                                      - connection->read_buffer_offset);
   6892   if ((bytes_read < 0) || socket_error)
   6893   {
   6894     if ((MHD_ERR_AGAIN_ == bytes_read) && ! socket_error)
   6895       return;     /* No new data to process. */
   6896     if ((bytes_read > 0) && connection->sk_nonblck)
   6897     { /* Try to detect the socket error */
   6898       int dummy;
   6899       bytes_read = connection->recv_cls (connection, &dummy, sizeof (dummy));
   6900     }
   6901     if (MHD_ERR_CONNRESET_ == bytes_read)
   6902     {
   6903       if ( (MHD_CONNECTION_INIT < connection->state) &&
   6904            (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) )
   6905       {
   6906 #ifdef HAVE_MESSAGES
   6907         MHD_DLOG (connection->daemon,
   6908                   _ ("Socket has been disconnected when reading request.\n"));
   6909 #endif
   6910         connection->discard_request = true;
   6911       }
   6912       MHD_connection_close_ (connection,
   6913                              MHD_REQUEST_TERMINATED_READ_ERROR);
   6914       return;
   6915     }
   6916 
   6917 #ifdef HAVE_MESSAGES
   6918     if (MHD_CONNECTION_INIT != connection->state)
   6919       MHD_DLOG (connection->daemon,
   6920                 _ ("Connection socket is closed when reading " \
   6921                    "request due to the error: %s\n"),
   6922                 (bytes_read < 0) ? str_conn_error_ (bytes_read) :
   6923                 "detected connection closure");
   6924 #endif
   6925     CONNECTION_CLOSE_ERROR (connection,
   6926                             NULL);
   6927     return;
   6928   }
   6929 
   6930   if (0 == bytes_read)
   6931   {   /* Remote side closed connection. */
   6932     connection->read_closed = true;
   6933     if ( (MHD_CONNECTION_INIT < connection->state) &&
   6934          (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) )
   6935     {
   6936 #ifdef HAVE_MESSAGES
   6937       MHD_DLOG (connection->daemon,
   6938                 _ ("Connection was closed by remote side with incomplete "
   6939                    "request.\n"));
   6940 #endif
   6941       connection->discard_request = true;
   6942       MHD_connection_close_ (connection,
   6943                              MHD_REQUEST_TERMINATED_CLIENT_ABORT);
   6944     }
   6945     else if (MHD_CONNECTION_INIT == connection->state)
   6946       /* This termination code cannot be reported to the application
   6947        * because application has not been informed yet about this request */
   6948       MHD_connection_close_ (connection,
   6949                              MHD_REQUEST_TERMINATED_COMPLETED_OK);
   6950     else
   6951       MHD_connection_close_ (connection,
   6952                              MHD_REQUEST_TERMINATED_WITH_ERROR);
   6953     return;
   6954   }
   6955   connection->read_buffer_offset += (size_t) bytes_read;
   6956   MHD_update_last_activity_ (connection);
   6957 #if DEBUG_STATES
   6958   MHD_DLOG (connection->daemon,
   6959             _ ("In function %s handling connection at state: %s\n"),
   6960             MHD_FUNC_,
   6961             MHD_state_to_string (connection->state));
   6962 #endif
   6963   /* TODO: check whether the next 'switch()' really needed */
   6964   switch (connection->state)
   6965   {
   6966   case MHD_CONNECTION_INIT:
   6967   case MHD_CONNECTION_REQ_LINE_RECEIVING:
   6968   case MHD_CONNECTION_REQ_HEADERS_RECEIVING:
   6969   case MHD_CONNECTION_BODY_RECEIVING:
   6970   case MHD_CONNECTION_FOOTERS_RECEIVING:
   6971   case MHD_CONNECTION_FULL_REQ_RECEIVED:
   6972     /* nothing to do but default action */
   6973     if (connection->read_closed)
   6974     {
   6975       /* TODO: check whether this really needed */
   6976       MHD_connection_close_ (connection,
   6977                              MHD_REQUEST_TERMINATED_READ_ERROR);
   6978     }
   6979     return;
   6980   case MHD_CONNECTION_CLOSED:
   6981     return;
   6982 #ifdef UPGRADE_SUPPORT
   6983   case MHD_CONNECTION_UPGRADE:
   6984     mhd_assert (0);
   6985     return;
   6986 #endif /* UPGRADE_SUPPORT */
   6987   case MHD_CONNECTION_START_REPLY:
   6988     /* shrink read buffer to how much is actually used */
   6989     /* TODO: remove shrink as it handled in special function */
   6990     if ((0 != connection->read_buffer_size) &&
   6991         (connection->read_buffer_size != connection->read_buffer_offset))
   6992     {
   6993       mhd_assert (NULL != connection->read_buffer);
   6994       connection->read_buffer =
   6995         MHD_pool_reallocate (connection->pool,
   6996                              connection->read_buffer,
   6997                              connection->read_buffer_size,
   6998                              connection->read_buffer_offset);
   6999       connection->read_buffer_size = connection->read_buffer_offset;
   7000     }
   7001     break;
   7002   case MHD_CONNECTION_REQ_LINE_RECEIVED:
   7003   case MHD_CONNECTION_HEADERS_RECEIVED:
   7004   case MHD_CONNECTION_HEADERS_PROCESSED:
   7005   case MHD_CONNECTION_BODY_RECEIVED:
   7006   case MHD_CONNECTION_FOOTERS_RECEIVED:
   7007     /* Milestone state, no data should be read */
   7008     mhd_assert (0); /* Should not be possible */
   7009     break;
   7010   case MHD_CONNECTION_CONTINUE_SENDING:
   7011   case MHD_CONNECTION_HEADERS_SENDING:
   7012   case MHD_CONNECTION_HEADERS_SENT:
   7013   case MHD_CONNECTION_NORMAL_BODY_UNREADY:
   7014   case MHD_CONNECTION_NORMAL_BODY_READY:
   7015   case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
   7016   case MHD_CONNECTION_CHUNKED_BODY_READY:
   7017   case MHD_CONNECTION_CHUNKED_BODY_SENT:
   7018   case MHD_CONNECTION_FOOTERS_SENDING:
   7019   case MHD_CONNECTION_FULL_REPLY_SENT:
   7020   default:
   7021     mhd_assert (0); /* Should not be possible */
   7022     break;
   7023   }
   7024   return;
   7025 }
   7026 
   7027 
   7028 /**
   7029  * This function was created to handle writes to sockets when it has
   7030  * been determined that the socket can be written to. All
   7031  * implementations (multithreaded, external select, internal select)
   7032  * call this function
   7033  *
   7034  * @param connection connection to handle
   7035  */
   7036 void
   7037 MHD_connection_handle_write (struct MHD_Connection *connection)
   7038 {
   7039   struct MHD_Response *response;
   7040   ssize_t ret;
   7041   if (connection->suspended)
   7042     return;
   7043 
   7044 #ifdef HTTPS_SUPPORT
   7045   if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
   7046   {   /* HTTPS connection. */
   7047     if (MHD_TLS_CONN_CONNECTED > connection->tls_state)
   7048     {
   7049       if (! MHD_run_tls_handshake_ (connection))
   7050         return;
   7051     }
   7052   }
   7053 #endif /* HTTPS_SUPPORT */
   7054 
   7055 #if DEBUG_STATES
   7056   MHD_DLOG (connection->daemon,
   7057             _ ("In function %s handling connection at state: %s\n"),
   7058             MHD_FUNC_,
   7059             MHD_state_to_string (connection->state));
   7060 #endif
   7061   switch (connection->state)
   7062   {
   7063   case MHD_CONNECTION_INIT:
   7064   case MHD_CONNECTION_REQ_LINE_RECEIVING:
   7065   case MHD_CONNECTION_REQ_LINE_RECEIVED:
   7066   case MHD_CONNECTION_REQ_HEADERS_RECEIVING:
   7067   case MHD_CONNECTION_HEADERS_RECEIVED:
   7068   case MHD_CONNECTION_HEADERS_PROCESSED:
   7069     mhd_assert (0);
   7070     return;
   7071   case MHD_CONNECTION_CONTINUE_SENDING:
   7072     ret = MHD_send_data_ (connection,
   7073                           &HTTP_100_CONTINUE
   7074                           [connection->continue_message_write_offset],
   7075                           MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)
   7076                           - connection->continue_message_write_offset,
   7077                           true);
   7078     if (ret < 0)
   7079     {
   7080       if (MHD_ERR_AGAIN_ == ret)
   7081         return;
   7082 #ifdef HAVE_MESSAGES
   7083       MHD_DLOG (connection->daemon,
   7084                 _ ("Failed to send data in request for %s.\n"),
   7085                 connection->rq.url);
   7086 #endif
   7087       CONNECTION_CLOSE_ERROR (connection,
   7088                               NULL);
   7089       return;
   7090     }
   7091 #if _MHD_DEBUG_SEND_DATA
   7092     fprintf (stderr,
   7093              _ ("Sent 100 continue response: `%.*s'\n"),
   7094              (int) ret,
   7095              &HTTP_100_CONTINUE[connection->continue_message_write_offset]);
   7096 #endif
   7097     connection->continue_message_write_offset += (size_t) ret;
   7098     MHD_update_last_activity_ (connection);
   7099     return;
   7100   case MHD_CONNECTION_BODY_RECEIVING:
   7101   case MHD_CONNECTION_BODY_RECEIVED:
   7102   case MHD_CONNECTION_FOOTERS_RECEIVING:
   7103   case MHD_CONNECTION_FOOTERS_RECEIVED:
   7104   case MHD_CONNECTION_FULL_REQ_RECEIVED:
   7105     mhd_assert (0);
   7106     return;
   7107   case MHD_CONNECTION_START_REPLY:
   7108     mhd_assert (0);
   7109     return;
   7110   case MHD_CONNECTION_HEADERS_SENDING:
   7111     {
   7112       struct MHD_Response *const resp = connection->rp.response;
   7113       const size_t wb_ready = connection->write_buffer_append_offset
   7114                               - connection->write_buffer_send_offset;
   7115       mhd_assert (connection->write_buffer_append_offset >= \
   7116                   connection->write_buffer_send_offset);
   7117       mhd_assert (NULL != resp);
   7118       mhd_assert ( (0 == resp->data_size) || \
   7119                    (0 == resp->data_start) || \
   7120                    (NULL != resp->crc) );
   7121       mhd_assert ( (0 == connection->rp.rsp_write_position) || \
   7122                    (resp->total_size ==
   7123                     connection->rp.rsp_write_position) );
   7124       mhd_assert ((MHD_CONN_MUST_UPGRADE != connection->keepalive) || \
   7125                   (! connection->rp.props.send_reply_body));
   7126 
   7127       if ( (connection->rp.props.send_reply_body) &&
   7128            (NULL == resp->crc) &&
   7129            (NULL == resp->data_iov) &&
   7130            /* TODO: remove the next check as 'send_reply_body' is used */
   7131            (0 == connection->rp.rsp_write_position) &&
   7132            (! connection->rp.props.chunked) )
   7133       {
   7134         mhd_assert (resp->total_size >= resp->data_size);
   7135         mhd_assert (0 == resp->data_start);
   7136         /* Send response headers alongside the response body, if the body
   7137          * data is available. */
   7138         ret = MHD_send_hdr_and_body_ (connection,
   7139                                       &connection->write_buffer
   7140                                       [connection->write_buffer_send_offset],
   7141                                       wb_ready,
   7142                                       false,
   7143                                       resp->data,
   7144                                       resp->data_size,
   7145                                       (resp->total_size == resp->data_size));
   7146       }
   7147       else
   7148       {
   7149         /* This is response for HEAD request or reply body is not allowed
   7150          * for any other reason or reply body is dynamically generated. */
   7151         /* Do not send the body data even if it's available. */
   7152         ret = MHD_send_hdr_and_body_ (connection,
   7153                                       &connection->write_buffer
   7154                                       [connection->write_buffer_send_offset],
   7155                                       wb_ready,
   7156                                       false,
   7157                                       NULL,
   7158                                       0,
   7159                                       ((0 == resp->total_size) ||
   7160                                        (! connection->rp.props.send_reply_body)
   7161                                       ));
   7162       }
   7163 
   7164       if (ret < 0)
   7165       {
   7166         if (MHD_ERR_AGAIN_ == ret)
   7167           return;
   7168 #ifdef HAVE_MESSAGES
   7169         MHD_DLOG (connection->daemon,
   7170                   _ ("Failed to send the response headers for the " \
   7171                      "request for `%s'. Error: %s\n"),
   7172                   connection->rq.url,
   7173                   str_conn_error_ (ret));
   7174 #endif
   7175         CONNECTION_CLOSE_ERROR (connection,
   7176                                 NULL);
   7177         return;
   7178       }
   7179       /* 'ret' is not negative, it's safe to cast it to 'size_t'. */
   7180       if (((size_t) ret) > wb_ready)
   7181       {
   7182         /* The complete header and some response data have been sent,
   7183          * update both offsets. */
   7184         mhd_assert (0 == connection->rp.rsp_write_position);
   7185         mhd_assert (! connection->rp.props.chunked);
   7186         mhd_assert (connection->rp.props.send_reply_body);
   7187         connection->write_buffer_send_offset += wb_ready;
   7188         connection->rp.rsp_write_position = ((size_t) ret) - wb_ready;
   7189       }
   7190       else
   7191         connection->write_buffer_send_offset += (size_t) ret;
   7192       MHD_update_last_activity_ (connection);
   7193       if (MHD_CONNECTION_HEADERS_SENDING != connection->state)
   7194         return;
   7195       check_write_done (connection,
   7196                         MHD_CONNECTION_HEADERS_SENT);
   7197       return;
   7198     }
   7199   case MHD_CONNECTION_HEADERS_SENT:
   7200     return;
   7201   case MHD_CONNECTION_NORMAL_BODY_READY:
   7202     response = connection->rp.response;
   7203     if (connection->rp.rsp_write_position <
   7204         connection->rp.response->total_size)
   7205     {
   7206       uint64_t data_write_offset;
   7207 
   7208 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7209       if (NULL != response->crc)
   7210         MHD_mutex_lock_chk_ (&response->mutex);
   7211 #endif
   7212       if (MHD_NO == try_ready_normal_body (connection))
   7213       {
   7214         /* mutex was already unlocked by try_ready_normal_body */
   7215         return;
   7216       }
   7217 #if defined(_MHD_HAVE_SENDFILE)
   7218       if (MHD_resp_sender_sendfile == connection->rp.resp_sender)
   7219       {
   7220         mhd_assert (NULL == response->data_iov);
   7221         ret = MHD_send_sendfile_ (connection);
   7222       }
   7223       else /* combined with the next 'if' */
   7224 #endif /* _MHD_HAVE_SENDFILE */
   7225       if (NULL != response->data_iov)
   7226       {
   7227         ret = MHD_send_iovec_ (connection,
   7228                                &connection->rp.resp_iov,
   7229                                true);
   7230       }
   7231       else
   7232       {
   7233         data_write_offset = connection->rp.rsp_write_position
   7234                             - response->data_start;
   7235         if (data_write_offset > (uint64_t) SIZE_MAX)
   7236           MHD_PANIC (_ ("Data offset exceeds limit.\n"));
   7237         ret = MHD_send_data_ (connection,
   7238                               &response->data
   7239                               [(size_t) data_write_offset],
   7240                               response->data_size
   7241                               - (size_t) data_write_offset,
   7242                               true);
   7243 #if _MHD_DEBUG_SEND_DATA
   7244         if (ret > 0)
   7245           fprintf (stderr,
   7246                    _ ("Sent %d-byte DATA response: `%.*s'\n"),
   7247                    (int) ret,
   7248                    (int) ret,
   7249                    &rp.response->data[connection->rp.rsp_write_position
   7250                                       - rp.response->data_start]);
   7251 #endif
   7252       }
   7253 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7254       if (NULL != response->crc)
   7255         MHD_mutex_unlock_chk_ (&response->mutex);
   7256 #endif
   7257       if (ret < 0)
   7258       {
   7259         if (MHD_ERR_AGAIN_ == ret)
   7260           return;
   7261 #ifdef HAVE_MESSAGES
   7262         MHD_DLOG (connection->daemon,
   7263                   _ ("Failed to send the response body for the " \
   7264                      "request for `%s'. Error: %s\n"),
   7265                   connection->rq.url,
   7266                   str_conn_error_ (ret));
   7267 #endif
   7268         CONNECTION_CLOSE_ERROR (connection,
   7269                                 NULL);
   7270         return;
   7271       }
   7272       connection->rp.rsp_write_position += (size_t) ret;
   7273       MHD_update_last_activity_ (connection);
   7274     }
   7275     if (connection->rp.rsp_write_position ==
   7276         connection->rp.response->total_size)
   7277       connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
   7278     return;
   7279   case MHD_CONNECTION_NORMAL_BODY_UNREADY:
   7280     mhd_assert (0);
   7281     return;
   7282   case MHD_CONNECTION_CHUNKED_BODY_READY:
   7283     ret = MHD_send_data_ (connection,
   7284                           &connection->write_buffer
   7285                           [connection->write_buffer_send_offset],
   7286                           connection->write_buffer_append_offset
   7287                           - connection->write_buffer_send_offset,
   7288                           true);
   7289     if (ret < 0)
   7290     {
   7291       if (MHD_ERR_AGAIN_ == ret)
   7292         return;
   7293 #ifdef HAVE_MESSAGES
   7294       MHD_DLOG (connection->daemon,
   7295                 _ ("Failed to send the chunked response body for the " \
   7296                    "request for `%s'. Error: %s\n"),
   7297                 connection->rq.url,
   7298                 str_conn_error_ (ret));
   7299 #endif
   7300       CONNECTION_CLOSE_ERROR (connection,
   7301                               NULL);
   7302       return;
   7303     }
   7304     connection->write_buffer_send_offset += (size_t) ret;
   7305     MHD_update_last_activity_ (connection);
   7306     if (MHD_CONNECTION_CHUNKED_BODY_READY != connection->state)
   7307       return;
   7308     check_write_done (connection,
   7309                       (connection->rp.response->total_size ==
   7310                        connection->rp.rsp_write_position) ?
   7311                       MHD_CONNECTION_CHUNKED_BODY_SENT :
   7312                       MHD_CONNECTION_CHUNKED_BODY_UNREADY);
   7313     return;
   7314   case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
   7315   case MHD_CONNECTION_CHUNKED_BODY_SENT:
   7316     mhd_assert (0);
   7317     return;
   7318   case MHD_CONNECTION_FOOTERS_SENDING:
   7319     ret = MHD_send_data_ (connection,
   7320                           &connection->write_buffer
   7321                           [connection->write_buffer_send_offset],
   7322                           connection->write_buffer_append_offset
   7323                           - connection->write_buffer_send_offset,
   7324                           true);
   7325     if (ret < 0)
   7326     {
   7327       if (MHD_ERR_AGAIN_ == ret)
   7328         return;
   7329 #ifdef HAVE_MESSAGES
   7330       MHD_DLOG (connection->daemon,
   7331                 _ ("Failed to send the footers for the " \
   7332                    "request for `%s'. Error: %s\n"),
   7333                 connection->rq.url,
   7334                 str_conn_error_ (ret));
   7335 #endif
   7336       CONNECTION_CLOSE_ERROR (connection,
   7337                               NULL);
   7338       return;
   7339     }
   7340     connection->write_buffer_send_offset += (size_t) ret;
   7341     MHD_update_last_activity_ (connection);
   7342     if (MHD_CONNECTION_FOOTERS_SENDING != connection->state)
   7343       return;
   7344     check_write_done (connection,
   7345                       MHD_CONNECTION_FULL_REPLY_SENT);
   7346     return;
   7347   case MHD_CONNECTION_FULL_REPLY_SENT:
   7348     mhd_assert (0);
   7349     return;
   7350   case MHD_CONNECTION_CLOSED:
   7351     return;
   7352 #ifdef UPGRADE_SUPPORT
   7353   case MHD_CONNECTION_UPGRADE:
   7354     mhd_assert (0);
   7355     return;
   7356 #endif /* UPGRADE_SUPPORT */
   7357   default:
   7358     mhd_assert (0);
   7359     CONNECTION_CLOSE_ERROR (connection,
   7360                             _ ("Internal error.\n"));
   7361     break;
   7362   }
   7363   return;
   7364 }
   7365 
   7366 
   7367 /**
   7368  * Check whether connection has timed out.
   7369  * @param c the connection to check
   7370  * @return true if connection has timeout and needs to be closed,
   7371  *         false otherwise.
   7372  */
   7373 static bool
   7374 connection_check_timedout (struct MHD_Connection *c)
   7375 {
   7376   const uint64_t timeout = c->connection_timeout_ms;
   7377   uint64_t now;
   7378   uint64_t since_actv;
   7379 
   7380   if (c->suspended)
   7381     return false;
   7382   if (0 == timeout)
   7383     return false;
   7384   now = MHD_monotonic_msec_counter ();
   7385   since_actv = now - c->last_activity;
   7386   /* Keep the next lines in sync with #connection_get_wait() to avoid
   7387    * undesired side-effects like busy-waiting. */
   7388   if (timeout < since_actv)
   7389   {
   7390     if (UINT64_MAX / 2 < since_actv)
   7391     {
   7392       const uint64_t jump_back = c->last_activity - now;
   7393       /* Very unlikely that it is more than quarter-million years pause.
   7394        * More likely that system clock jumps back. */
   7395       if (5000 >= jump_back)
   7396       {
   7397 #ifdef HAVE_MESSAGES
   7398         MHD_DLOG (c->daemon,
   7399                   _ ("Detected system clock %u milliseconds jump back.\n"),
   7400                   (unsigned int) jump_back);
   7401 #endif
   7402         return false;
   7403       }
   7404 #ifdef HAVE_MESSAGES
   7405       MHD_DLOG (c->daemon,
   7406                 _ ("Detected too large system clock %" PRIu64 " milliseconds "
   7407                    "jump back.\n"),
   7408                 jump_back);
   7409 #endif
   7410     }
   7411     return true;
   7412   }
   7413   return false;
   7414 }
   7415 
   7416 
   7417 /**
   7418  * Clean up the state of the given connection and move it into the
   7419  * clean up queue for final disposal.
   7420  * @remark To be called only from thread that process connection's
   7421  * recv(), send() and response.
   7422  *
   7423  * @param connection handle for the connection to clean up
   7424  */
   7425 static void
   7426 cleanup_connection (struct MHD_Connection *connection)
   7427 {
   7428   struct MHD_Daemon *daemon = connection->daemon;
   7429 #ifdef MHD_USE_THREADS
   7430   mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
   7431                MHD_thread_handle_ID_is_current_thread_ (connection->tid) );
   7432   mhd_assert (NULL == daemon->worker_pool);
   7433 #endif /* MHD_USE_THREADS */
   7434 
   7435   if (connection->in_cleanup)
   7436     return; /* Prevent double cleanup. */
   7437   connection->in_cleanup = true;
   7438   if (NULL != connection->rp.response)
   7439   {
   7440     MHD_destroy_response (connection->rp.response);
   7441     connection->rp.response = NULL;
   7442   }
   7443 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7444   MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
   7445 #endif
   7446   if (connection->suspended)
   7447   {
   7448     DLL_remove (daemon->suspended_connections_head,
   7449                 daemon->suspended_connections_tail,
   7450                 connection);
   7451     connection->suspended = false;
   7452   }
   7453   else
   7454   {
   7455     if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
   7456     {
   7457       if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
   7458         XDLL_remove (daemon->normal_timeout_head,
   7459                      daemon->normal_timeout_tail,
   7460                      connection);
   7461       else
   7462         XDLL_remove (daemon->manual_timeout_head,
   7463                      daemon->manual_timeout_tail,
   7464                      connection);
   7465     }
   7466     DLL_remove (daemon->connections_head,
   7467                 daemon->connections_tail,
   7468                 connection);
   7469   }
   7470   DLL_insert (daemon->cleanup_head,
   7471               daemon->cleanup_tail,
   7472               connection);
   7473   connection->resuming = false;
   7474   connection->in_idle = false;
   7475 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7476   MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
   7477 #endif
   7478   if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
   7479   {
   7480     /* if we were at the connection limit before and are in
   7481        thread-per-connection mode, signal the main thread
   7482        to resume accepting connections */
   7483     if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
   7484          (! MHD_itc_activate_ (daemon->itc, "c")) )
   7485     {
   7486 #ifdef HAVE_MESSAGES
   7487       MHD_DLOG (daemon,
   7488                 _ ("Failed to signal end of connection via inter-thread " \
   7489                    "communication channel.\n"));
   7490 #endif
   7491     }
   7492   }
   7493 }
   7494 
   7495 
   7496 /**
   7497  * Set initial internal states for the connection to start reading and
   7498  * processing incoming data.
   7499  * @param c the connection to process
   7500  */
   7501 void
   7502 MHD_connection_set_initial_state_ (struct MHD_Connection *c)
   7503 {
   7504   size_t read_buf_size;
   7505 
   7506 #ifdef HTTPS_SUPPORT
   7507   mhd_assert ( (0 == (c->daemon->options & MHD_USE_TLS)) || \
   7508                (MHD_TLS_CONN_INIT == c->tls_state) );
   7509   mhd_assert ( (0 != (c->daemon->options & MHD_USE_TLS)) || \
   7510                (MHD_TLS_CONN_NO_TLS == c->tls_state) );
   7511 #endif /* HTTPS_SUPPORT */
   7512   mhd_assert (MHD_CONNECTION_INIT == c->state);
   7513 
   7514   c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN;
   7515   c->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
   7516 
   7517   memset (&c->rq, 0, sizeof(c->rq));
   7518   memset (&c->rp, 0, sizeof(c->rp));
   7519 
   7520   c->write_buffer = NULL;
   7521   c->write_buffer_size = 0;
   7522   c->write_buffer_send_offset = 0;
   7523   c->write_buffer_append_offset = 0;
   7524 
   7525   c->continue_message_write_offset = 0;
   7526 
   7527   c->read_buffer_offset = 0;
   7528   read_buf_size = c->daemon->pool_size / 2;
   7529   c->read_buffer
   7530     = MHD_pool_allocate (c->pool,
   7531                          read_buf_size,
   7532                          false);
   7533   c->read_buffer_size = read_buf_size;
   7534 }
   7535 
   7536 
   7537 /**
   7538  * Reset connection after request-reply cycle.
   7539  * @param connection the connection to process
   7540  * @param reuse the flag to choose whether to close connection or
   7541  *              prepare connection for the next request processing
   7542  */
   7543 static void
   7544 connection_reset (struct MHD_Connection *connection,
   7545                   bool reuse)
   7546 {
   7547   struct MHD_Connection *const c = connection; /**< a short alias */
   7548   struct MHD_Daemon *const d = connection->daemon;
   7549 
   7550   if (! reuse)
   7551   {
   7552     /* Next function will destroy response, notify client,
   7553      * destroy memory pool, and set connection state to "CLOSED" */
   7554     MHD_connection_close_ (c,
   7555                            c->stop_with_error ?
   7556                            MHD_REQUEST_TERMINATED_WITH_ERROR :
   7557                            MHD_REQUEST_TERMINATED_COMPLETED_OK);
   7558     c->read_buffer = NULL;
   7559     c->read_buffer_size = 0;
   7560     c->read_buffer_offset = 0;
   7561     c->write_buffer = NULL;
   7562     c->write_buffer_size = 0;
   7563     c->write_buffer_send_offset = 0;
   7564     c->write_buffer_append_offset = 0;
   7565   }
   7566   else
   7567   {
   7568     /* Reset connection to process the next request */
   7569     size_t new_read_buf_size;
   7570     mhd_assert (! c->stop_with_error);
   7571     mhd_assert (! c->discard_request);
   7572 
   7573     if ( (NULL != d->notify_completed) &&
   7574          (c->rq.client_aware) )
   7575       d->notify_completed (d->notify_completed_cls,
   7576                            c,
   7577                            &c->rq.client_context,
   7578                            MHD_REQUEST_TERMINATED_COMPLETED_OK);
   7579     c->rq.client_aware = false;
   7580 
   7581     if (NULL != c->rp.response)
   7582       MHD_destroy_response (c->rp.response);
   7583     c->rp.response = NULL;
   7584 
   7585     c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN;
   7586     c->state = MHD_CONNECTION_INIT;
   7587     c->event_loop_info =
   7588       (0 == c->read_buffer_offset) ?
   7589       MHD_EVENT_LOOP_INFO_READ : MHD_EVENT_LOOP_INFO_PROCESS;
   7590 
   7591     memset (&c->rq, 0, sizeof(c->rq));
   7592 
   7593     /* iov (if any) will be deallocated by MHD_pool_reset */
   7594     memset (&c->rp, 0, sizeof(c->rp));
   7595 
   7596     c->write_buffer = NULL;
   7597     c->write_buffer_size = 0;
   7598     c->write_buffer_send_offset = 0;
   7599     c->write_buffer_append_offset = 0;
   7600     c->continue_message_write_offset = 0;
   7601 
   7602     /* Reset the read buffer to the starting size,
   7603        preserving the bytes we have already read. */
   7604     new_read_buf_size = c->daemon->pool_size / 2;
   7605     if (c->read_buffer_offset > new_read_buf_size)
   7606       new_read_buf_size = c->read_buffer_offset;
   7607 
   7608     c->read_buffer
   7609       = MHD_pool_reset (c->pool,
   7610                         c->read_buffer,
   7611                         c->read_buffer_offset,
   7612                         new_read_buf_size);
   7613     c->read_buffer_size = new_read_buf_size;
   7614   }
   7615   c->rq.client_context = NULL;
   7616 }
   7617 
   7618 
   7619 /**
   7620  * This function was created to handle per-connection processing that
   7621  * has to happen even if the socket cannot be read or written to.
   7622  * All implementations (multithreaded, external select, internal select)
   7623  * call this function.
   7624  * @remark To be called only from thread that process connection's
   7625  * recv(), send() and response.
   7626  *
   7627  * @param connection connection to handle
   7628  * @return #MHD_YES if we should continue to process the
   7629  *         connection (not dead yet), #MHD_NO if it died
   7630  */
   7631 enum MHD_Result
   7632 MHD_connection_handle_idle (struct MHD_Connection *connection)
   7633 {
   7634   struct MHD_Daemon *daemon = connection->daemon;
   7635   enum MHD_Result ret;
   7636 #ifdef MHD_USE_THREADS
   7637   mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
   7638                MHD_thread_handle_ID_is_current_thread_ (connection->tid) );
   7639 #endif /* MHD_USE_THREADS */
   7640   /* 'daemon' is not used if epoll is not available and asserts are disabled */
   7641   (void) daemon; /* Mute compiler warning */
   7642 
   7643   connection->in_idle = true;
   7644   while (! connection->suspended)
   7645   {
   7646 #ifdef HTTPS_SUPPORT
   7647     if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
   7648     {     /* HTTPS connection. */
   7649       if ((MHD_TLS_CONN_INIT <= connection->tls_state) &&
   7650           (MHD_TLS_CONN_CONNECTED > connection->tls_state))
   7651         break;
   7652     }
   7653 #endif /* HTTPS_SUPPORT */
   7654 #if DEBUG_STATES
   7655     MHD_DLOG (daemon,
   7656               _ ("In function %s handling connection at state: %s\n"),
   7657               MHD_FUNC_,
   7658               MHD_state_to_string (connection->state));
   7659 #endif
   7660     switch (connection->state)
   7661     {
   7662     case MHD_CONNECTION_INIT:
   7663     case MHD_CONNECTION_REQ_LINE_RECEIVING:
   7664       if (get_request_line (connection))
   7665       {
   7666         mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < connection->state);
   7667         mhd_assert ((MHD_IS_HTTP_VER_SUPPORTED (connection->rq.http_ver)) \
   7668                     || (connection->discard_request));
   7669         continue;
   7670       }
   7671       mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING >= connection->state);
   7672       break;
   7673     case MHD_CONNECTION_REQ_LINE_RECEIVED:
   7674       switch_to_rq_headers_processing (connection);
   7675       mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED != connection->state);
   7676       continue;
   7677     case MHD_CONNECTION_REQ_HEADERS_RECEIVING:
   7678       if (get_req_headers (connection, false))
   7679       {
   7680         mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING < connection->state);
   7681         mhd_assert ((MHD_CONNECTION_HEADERS_RECEIVED == connection->state) || \
   7682                     (connection->discard_request));
   7683         continue;
   7684       }
   7685       mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING == connection->state);
   7686       break;
   7687     case MHD_CONNECTION_HEADERS_RECEIVED:
   7688       parse_connection_headers (connection);
   7689       if (MHD_CONNECTION_HEADERS_RECEIVED != connection->state)
   7690         continue;
   7691       connection->state = MHD_CONNECTION_HEADERS_PROCESSED;
   7692       if (connection->suspended)
   7693         break;
   7694       continue;
   7695     case MHD_CONNECTION_HEADERS_PROCESSED:
   7696       call_connection_handler (connection);     /* first call */
   7697       if (MHD_CONNECTION_HEADERS_PROCESSED != connection->state)
   7698         continue;
   7699       if (connection->suspended)
   7700         continue;
   7701 
   7702       if ( (NULL == connection->rp.response) &&
   7703            (need_100_continue (connection)) &&
   7704            /* If the client is already sending the payload (body)
   7705               there is no need to send "100 Continue" */
   7706            (0 == connection->read_buffer_offset) )
   7707       {
   7708         connection->state = MHD_CONNECTION_CONTINUE_SENDING;
   7709         break;
   7710       }
   7711       if ( (NULL != connection->rp.response) &&
   7712            (0 != connection->rq.remaining_upload_size) )
   7713       {
   7714         /* we refused (no upload allowed!) */
   7715         connection->rq.remaining_upload_size = 0;
   7716         /* force close, in case client still tries to upload... */
   7717         connection->discard_request = true;
   7718       }
   7719       connection->state = (0 == connection->rq.remaining_upload_size)
   7720                           ? MHD_CONNECTION_FULL_REQ_RECEIVED
   7721                           : MHD_CONNECTION_BODY_RECEIVING;
   7722       if (connection->suspended)
   7723         break;
   7724       continue;
   7725     case MHD_CONNECTION_CONTINUE_SENDING:
   7726       if (connection->continue_message_write_offset ==
   7727           MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE))
   7728       {
   7729         connection->state = MHD_CONNECTION_BODY_RECEIVING;
   7730         continue;
   7731       }
   7732       break;
   7733     case MHD_CONNECTION_BODY_RECEIVING:
   7734       mhd_assert (0 != connection->rq.remaining_upload_size);
   7735       mhd_assert (! connection->discard_request);
   7736       mhd_assert (NULL == connection->rp.response);
   7737       if (0 != connection->read_buffer_offset)
   7738       {
   7739         process_request_body (connection);           /* loop call */
   7740         if (MHD_CONNECTION_BODY_RECEIVING != connection->state)
   7741           continue;
   7742       }
   7743       /* Modify here when queueing of the response during data processing
   7744          will be supported */
   7745       mhd_assert (! connection->discard_request);
   7746       mhd_assert (NULL == connection->rp.response);
   7747       if (0 == connection->rq.remaining_upload_size)
   7748       {
   7749         connection->state = MHD_CONNECTION_BODY_RECEIVED;
   7750         continue;
   7751       }
   7752       break;
   7753     case MHD_CONNECTION_BODY_RECEIVED:
   7754       mhd_assert (! connection->discard_request);
   7755       mhd_assert (NULL == connection->rp.response);
   7756       if (0 == connection->rq.remaining_upload_size)
   7757       {
   7758         if (connection->rq.have_chunked_upload)
   7759         {
   7760           /* Reset counter variables reused for footers */
   7761           connection->rq.num_cr_sp_replaced = 0;
   7762           connection->rq.skipped_broken_lines = 0;
   7763           reset_rq_header_processing_state (connection);
   7764           connection->state = MHD_CONNECTION_FOOTERS_RECEIVING;
   7765         }
   7766         else
   7767           connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
   7768         continue;
   7769       }
   7770       break;
   7771     case MHD_CONNECTION_FOOTERS_RECEIVING:
   7772       if (get_req_headers (connection, true))
   7773       {
   7774         mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING < connection->state);
   7775         mhd_assert ((MHD_CONNECTION_FOOTERS_RECEIVED == connection->state) || \
   7776                     (connection->discard_request));
   7777         continue;
   7778       }
   7779       mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING == connection->state);
   7780       break;
   7781     case MHD_CONNECTION_FOOTERS_RECEIVED:
   7782       /* The header, the body, and the footers of the request has been received,
   7783        * switch to the final processing of the request. */
   7784       connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
   7785       continue;
   7786     case MHD_CONNECTION_FULL_REQ_RECEIVED:
   7787       call_connection_handler (connection);     /* "final" call */
   7788       if (connection->state != MHD_CONNECTION_FULL_REQ_RECEIVED)
   7789         continue;
   7790       if (NULL == connection->rp.response)
   7791         break;                  /* try again next time */
   7792       /* Response is ready, start reply */
   7793       connection->state = MHD_CONNECTION_START_REPLY;
   7794       continue;
   7795     case MHD_CONNECTION_START_REPLY:
   7796       mhd_assert (NULL != connection->rp.response);
   7797       connection_switch_from_recv_to_send (connection);
   7798       if (MHD_NO == build_header_response (connection))
   7799       {
   7800         /* oops - close! */
   7801         CONNECTION_CLOSE_ERROR (connection,
   7802                                 _ ("Closing connection (failed to create "
   7803                                    "response header).\n"));
   7804         continue;
   7805       }
   7806       connection->state = MHD_CONNECTION_HEADERS_SENDING;
   7807       break;
   7808 
   7809     case MHD_CONNECTION_HEADERS_SENDING:
   7810       /* no default action */
   7811       break;
   7812     case MHD_CONNECTION_HEADERS_SENT:
   7813 #ifdef UPGRADE_SUPPORT
   7814       if (NULL != connection->rp.response->upgrade_handler)
   7815       {
   7816         connection->state = MHD_CONNECTION_UPGRADE;
   7817         /* This connection is "upgraded".  Pass socket to application. */
   7818         if (MHD_NO ==
   7819             MHD_response_execute_upgrade_ (connection->rp.response,
   7820                                            connection))
   7821         {
   7822           /* upgrade failed, fail hard */
   7823           CONNECTION_CLOSE_ERROR (connection,
   7824                                   NULL);
   7825           continue;
   7826         }
   7827         /* Response is not required anymore for this connection. */
   7828         if (1)
   7829         {
   7830           struct MHD_Response *const resp = connection->rp.response;
   7831 
   7832           connection->rp.response = NULL;
   7833           MHD_destroy_response (resp);
   7834         }
   7835         continue;
   7836       }
   7837 #endif /* UPGRADE_SUPPORT */
   7838 
   7839       if (connection->rp.props.send_reply_body)
   7840       {
   7841         if (connection->rp.props.chunked)
   7842           connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
   7843         else
   7844           connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
   7845       }
   7846       else
   7847         connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
   7848       continue;
   7849     case MHD_CONNECTION_NORMAL_BODY_READY:
   7850       mhd_assert (connection->rp.props.send_reply_body);
   7851       mhd_assert (! connection->rp.props.chunked);
   7852       /* nothing to do here */
   7853       break;
   7854     case MHD_CONNECTION_NORMAL_BODY_UNREADY:
   7855       mhd_assert (connection->rp.props.send_reply_body);
   7856       mhd_assert (! connection->rp.props.chunked);
   7857 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7858       if (NULL != connection->rp.response->crc)
   7859         MHD_mutex_lock_chk_ (&connection->rp.response->mutex);
   7860 #endif
   7861       if (0 == connection->rp.response->total_size)
   7862       {
   7863 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7864         if (NULL != connection->rp.response->crc)
   7865           MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
   7866 #endif
   7867         if (connection->rp.props.chunked)
   7868           connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT;
   7869         else
   7870           connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
   7871         continue;
   7872       }
   7873       if (MHD_NO != try_ready_normal_body (connection))
   7874       {
   7875 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7876         if (NULL != connection->rp.response->crc)
   7877           MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
   7878 #endif
   7879         connection->state = MHD_CONNECTION_NORMAL_BODY_READY;
   7880         /* Buffering for flushable socket was already enabled*/
   7881 
   7882         break;
   7883       }
   7884       /* mutex was already unlocked by "try_ready_normal_body */
   7885       /* not ready, no socket action */
   7886       break;
   7887     case MHD_CONNECTION_CHUNKED_BODY_READY:
   7888       mhd_assert (connection->rp.props.send_reply_body);
   7889       mhd_assert (connection->rp.props.chunked);
   7890       /* nothing to do here */
   7891       break;
   7892     case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
   7893       mhd_assert (connection->rp.props.send_reply_body);
   7894       mhd_assert (connection->rp.props.chunked);
   7895 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7896       if (NULL != connection->rp.response->crc)
   7897         MHD_mutex_lock_chk_ (&connection->rp.response->mutex);
   7898 #endif
   7899       if ( (0 == connection->rp.response->total_size) ||
   7900            (connection->rp.rsp_write_position ==
   7901             connection->rp.response->total_size) )
   7902       {
   7903 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7904         if (NULL != connection->rp.response->crc)
   7905           MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
   7906 #endif
   7907         connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT;
   7908         continue;
   7909       }
   7910       if (1)
   7911       { /* pseudo-branch for local variables scope */
   7912         bool finished;
   7913         if (MHD_NO != try_ready_chunked_body (connection, &finished))
   7914         {
   7915 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   7916           if (NULL != connection->rp.response->crc)
   7917             MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
   7918 #endif
   7919           connection->state = finished ? MHD_CONNECTION_CHUNKED_BODY_SENT :
   7920                               MHD_CONNECTION_CHUNKED_BODY_READY;
   7921           continue;
   7922         }
   7923         /* mutex was already unlocked by try_ready_chunked_body */
   7924       }
   7925       break;
   7926     case MHD_CONNECTION_CHUNKED_BODY_SENT:
   7927       mhd_assert (connection->rp.props.send_reply_body);
   7928       mhd_assert (connection->rp.props.chunked);
   7929       mhd_assert (connection->write_buffer_send_offset <= \
   7930                   connection->write_buffer_append_offset);
   7931 
   7932       if (MHD_NO == build_connection_chunked_response_footer (connection))
   7933       {
   7934         /* oops - close! */
   7935         CONNECTION_CLOSE_ERROR (connection,
   7936                                 _ ("Closing connection (failed to create " \
   7937                                    "response footer)."));
   7938         continue;
   7939       }
   7940       mhd_assert (connection->write_buffer_send_offset < \
   7941                   connection->write_buffer_append_offset);
   7942       connection->state = MHD_CONNECTION_FOOTERS_SENDING;
   7943       continue;
   7944     case MHD_CONNECTION_FOOTERS_SENDING:
   7945       mhd_assert (connection->rp.props.send_reply_body);
   7946       mhd_assert (connection->rp.props.chunked);
   7947       /* no default action */
   7948       break;
   7949     case MHD_CONNECTION_FULL_REPLY_SENT:
   7950       if (MHD_HTTP_PROCESSING == connection->rp.responseCode)
   7951       {
   7952         /* After this type of response, we allow sending another! */
   7953         connection->state = MHD_CONNECTION_HEADERS_PROCESSED;
   7954         MHD_destroy_response (connection->rp.response);
   7955         connection->rp.response = NULL;
   7956         /* FIXME: maybe partially reset memory pool? */
   7957         continue;
   7958       }
   7959       /* Reset connection after complete reply */
   7960       connection_reset (connection,
   7961                         MHD_CONN_USE_KEEPALIVE == connection->keepalive &&
   7962                         ! connection->read_closed &&
   7963                         ! connection->discard_request);
   7964       continue;
   7965     case MHD_CONNECTION_CLOSED:
   7966       cleanup_connection (connection);
   7967       connection->in_idle = false;
   7968       return MHD_NO;
   7969 #ifdef UPGRADE_SUPPORT
   7970     case MHD_CONNECTION_UPGRADE:
   7971       connection->in_idle = false;
   7972       return MHD_YES;     /* keep open */
   7973 #endif /* UPGRADE_SUPPORT */
   7974     default:
   7975       mhd_assert (0);
   7976       break;
   7977     }
   7978     break;
   7979   }
   7980   if (connection_check_timedout (connection))
   7981   {
   7982     MHD_connection_close_ (connection,
   7983                            MHD_REQUEST_TERMINATED_TIMEOUT_REACHED);
   7984     connection->in_idle = false;
   7985     return MHD_YES;
   7986   }
   7987   MHD_connection_update_event_loop_info (connection);
   7988   ret = MHD_YES;
   7989 #ifdef EPOLL_SUPPORT
   7990   if ( (! connection->suspended) &&
   7991        MHD_D_IS_USING_EPOLL_ (daemon) )
   7992   {
   7993     ret = MHD_connection_epoll_update_ (connection);
   7994   }
   7995 #endif /* EPOLL_SUPPORT */
   7996   connection->in_idle = false;
   7997   return ret;
   7998 }
   7999 
   8000 
   8001 #ifdef EPOLL_SUPPORT
   8002 /**
   8003  * Perform epoll() processing, possibly moving the connection back into
   8004  * the epoll() set if needed.
   8005  *
   8006  * @param connection connection to process
   8007  * @return #MHD_YES if we should continue to process the
   8008  *         connection (not dead yet), #MHD_NO if it died
   8009  */
   8010 enum MHD_Result
   8011 MHD_connection_epoll_update_ (struct MHD_Connection *connection)
   8012 {
   8013   struct MHD_Daemon *const daemon = connection->daemon;
   8014 
   8015   mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon));
   8016 
   8017   if ((0 != (MHD_EVENT_LOOP_INFO_PROCESS & connection->event_loop_info)) &&
   8018       (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)))
   8019   {
   8020     /* Make sure that connection waiting for processing will be processed */
   8021     EDLL_insert (daemon->eready_head,
   8022                  daemon->eready_tail,
   8023                  connection);
   8024     connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
   8025   }
   8026 
   8027   if ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) &&
   8028        (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) &&
   8029        ( ( (MHD_EVENT_LOOP_INFO_WRITE == connection->event_loop_info) &&
   8030            (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY))) ||
   8031          ( (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) &&
   8032            (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ) )
   8033   {
   8034     /* add to epoll set */
   8035     struct epoll_event event;
   8036 
   8037     event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
   8038     event.data.ptr = connection;
   8039     if (0 != epoll_ctl (daemon->epoll_fd,
   8040                         EPOLL_CTL_ADD,
   8041                         connection->socket_fd,
   8042                         &event))
   8043     {
   8044 #ifdef HAVE_MESSAGES
   8045       if (0 != (daemon->options & MHD_USE_ERROR_LOG))
   8046         MHD_DLOG (daemon,
   8047                   _ ("Call to epoll_ctl failed: %s\n"),
   8048                   MHD_socket_last_strerr_ ());
   8049 #endif
   8050       connection->state = MHD_CONNECTION_CLOSED;
   8051       cleanup_connection (connection);
   8052       return MHD_NO;
   8053     }
   8054     connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
   8055   }
   8056   return MHD_YES;
   8057 }
   8058 
   8059 
   8060 #endif
   8061 
   8062 
   8063 /**
   8064  * Set callbacks for this connection to those for HTTP.
   8065  *
   8066  * @param connection connection to initialize
   8067  */
   8068 void
   8069 MHD_set_http_callbacks_ (struct MHD_Connection *connection)
   8070 {
   8071   connection->recv_cls = &recv_param_adapter;
   8072 }
   8073 
   8074 
   8075 /**
   8076  * Obtain information about the given connection.
   8077  * The returned pointer is invalidated with the next call of this function or
   8078  * when the connection is closed.
   8079  *
   8080  * @param connection what connection to get information about
   8081  * @param info_type what information is desired?
   8082  * @param ... depends on @a info_type
   8083  * @return NULL if this information is not available
   8084  *         (or if the @a info_type is unknown)
   8085  * @ingroup specialized
   8086  */
   8087 _MHD_EXTERN const union MHD_ConnectionInfo *
   8088 MHD_get_connection_info (struct MHD_Connection *connection,
   8089                          enum MHD_ConnectionInfoType info_type,
   8090                          ...)
   8091 {
   8092   switch (info_type)
   8093   {
   8094 #ifdef HTTPS_SUPPORT
   8095   case MHD_CONNECTION_INFO_CIPHER_ALGO:
   8096     if (NULL == connection->tls_session)
   8097       return NULL;
   8098     if (1)
   8099     { /* Workaround to mute compiler warning */
   8100       gnutls_cipher_algorithm_t res;
   8101       res = gnutls_cipher_get (connection->tls_session);
   8102       connection->connection_info_dummy.cipher_algorithm = (int) res;
   8103     }
   8104     return &connection->connection_info_dummy;
   8105   case MHD_CONNECTION_INFO_PROTOCOL:
   8106     if (NULL == connection->tls_session)
   8107       return NULL;
   8108     if (1)
   8109     { /* Workaround to mute compiler warning */
   8110       gnutls_protocol_t res;
   8111       res = gnutls_protocol_get_version (connection->tls_session);
   8112       connection->connection_info_dummy.protocol = (int) res;
   8113     }
   8114     return &connection->connection_info_dummy;
   8115   case MHD_CONNECTION_INFO_GNUTLS_SESSION:
   8116     if (NULL == connection->tls_session)
   8117       return NULL;
   8118     connection->connection_info_dummy.tls_session = connection->tls_session;
   8119     return &connection->connection_info_dummy;
   8120 #else  /* ! HTTPS_SUPPORT */
   8121   case MHD_CONNECTION_INFO_CIPHER_ALGO:
   8122   case MHD_CONNECTION_INFO_PROTOCOL:
   8123   case MHD_CONNECTION_INFO_GNUTLS_SESSION:
   8124 #endif /* ! HTTPS_SUPPORT */
   8125   case MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT:
   8126     return NULL; /* Not implemented */
   8127   case MHD_CONNECTION_INFO_CLIENT_ADDRESS:
   8128     if (0 < connection->addr_len)
   8129     {
   8130       mhd_assert (sizeof (connection->addr) == \
   8131                   sizeof (connection->connection_info_dummy.client_addr));
   8132       memcpy (&connection->connection_info_dummy.client_addr,
   8133               &connection->addr,
   8134               sizeof(connection->addr));
   8135       return &connection->connection_info_dummy;
   8136     }
   8137     return NULL;
   8138   case MHD_CONNECTION_INFO_DAEMON:
   8139     connection->connection_info_dummy.daemon =
   8140       MHD_get_master (connection->daemon);
   8141     return &connection->connection_info_dummy;
   8142   case MHD_CONNECTION_INFO_CONNECTION_FD:
   8143     connection->connection_info_dummy.connect_fd = connection->socket_fd;
   8144     return &connection->connection_info_dummy;
   8145   case MHD_CONNECTION_INFO_SOCKET_CONTEXT:
   8146     connection->connection_info_dummy.socket_context =
   8147       connection->socket_context;
   8148     return &connection->connection_info_dummy;
   8149   case MHD_CONNECTION_INFO_CONNECTION_SUSPENDED:
   8150     connection->connection_info_dummy.suspended =
   8151       connection->suspended ? MHD_YES : MHD_NO;
   8152     return &connection->connection_info_dummy;
   8153   case MHD_CONNECTION_INFO_CONNECTION_TIMEOUT:
   8154 #if SIZEOF_UNSIGNED_INT <= (SIZEOF_UINT64_T - 2)
   8155     if (UINT_MAX < connection->connection_timeout_ms / 1000)
   8156       connection->connection_info_dummy.connection_timeout = UINT_MAX;
   8157     else
   8158 #endif /* SIZEOF_UNSIGNED_INT <=(SIZEOF_UINT64_T - 2) */
   8159     connection->connection_info_dummy.connection_timeout =
   8160       (unsigned int) (connection->connection_timeout_ms / 1000);
   8161     return &connection->connection_info_dummy;
   8162   case MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE:
   8163     if ( (MHD_CONNECTION_HEADERS_RECEIVED > connection->state) ||
   8164          (MHD_CONNECTION_CLOSED == connection->state) )
   8165       return NULL;   /* invalid, too early! */
   8166     connection->connection_info_dummy.header_size = connection->rq.header_size;
   8167     return &connection->connection_info_dummy;
   8168   case MHD_CONNECTION_INFO_HTTP_STATUS:
   8169     if (NULL == connection->rp.response)
   8170       return NULL;
   8171     connection->connection_info_dummy.http_status = connection->rp.responseCode;
   8172     return &connection->connection_info_dummy;
   8173   default:
   8174     return NULL;
   8175   }
   8176 }
   8177 
   8178 
   8179 /**
   8180  * Set a custom option for the given connection, overriding defaults.
   8181  *
   8182  * @param connection connection to modify
   8183  * @param option option to set
   8184  * @param ... arguments to the option, depending on the option type
   8185  * @return #MHD_YES on success, #MHD_NO if setting the option failed
   8186  * @ingroup specialized
   8187  */
   8188 _MHD_EXTERN enum MHD_Result
   8189 MHD_set_connection_option (struct MHD_Connection *connection,
   8190                            enum MHD_CONNECTION_OPTION option,
   8191                            ...)
   8192 {
   8193   va_list ap;
   8194   struct MHD_Daemon *daemon;
   8195   unsigned int ui_val;
   8196 
   8197   daemon = connection->daemon;
   8198   switch (option)
   8199   {
   8200   case MHD_CONNECTION_OPTION_TIMEOUT:
   8201     if (0 == connection->connection_timeout_ms)
   8202       connection->last_activity = MHD_monotonic_msec_counter ();
   8203     va_start (ap, option);
   8204     ui_val = va_arg (ap, unsigned int);
   8205     va_end (ap);
   8206 #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT
   8207     if ((UINT64_MAX / 4000 - 1) < ui_val)
   8208     {
   8209 #ifdef HAVE_MESSAGES
   8210       MHD_DLOG (connection->daemon,
   8211                 _ ("The specified connection timeout (%u) is too " \
   8212                    "large. Maximum allowed value (%" PRIu64 ") will be used " \
   8213                    "instead.\n"),
   8214                 ui_val,
   8215                 (UINT64_MAX / 4000 - 1));
   8216 #endif
   8217       ui_val = UINT64_MAX / 4000 - 1;
   8218     }
   8219 #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */
   8220     if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
   8221     {
   8222 #if defined(MHD_USE_THREADS)
   8223       MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
   8224 #endif
   8225       if (! connection->suspended)
   8226       {
   8227         if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
   8228           XDLL_remove (daemon->normal_timeout_head,
   8229                        daemon->normal_timeout_tail,
   8230                        connection);
   8231         else
   8232           XDLL_remove (daemon->manual_timeout_head,
   8233                        daemon->manual_timeout_tail,
   8234                        connection);
   8235         connection->connection_timeout_ms = ((uint64_t) ui_val) * 1000;
   8236         if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
   8237           XDLL_insert (daemon->normal_timeout_head,
   8238                        daemon->normal_timeout_tail,
   8239                        connection);
   8240         else
   8241           XDLL_insert (daemon->manual_timeout_head,
   8242                        daemon->manual_timeout_tail,
   8243                        connection);
   8244       }
   8245 #if defined(MHD_USE_THREADS)
   8246       MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
   8247 #endif
   8248     }
   8249     return MHD_YES;
   8250   default:
   8251     return MHD_NO;
   8252   }
   8253 }
   8254 
   8255 
   8256 /**
   8257  * Queue a response to be transmitted to the client (as soon as
   8258  * possible but after #MHD_AccessHandlerCallback returns).
   8259  *
   8260  * For any active connection this function must be called
   8261  * only by #MHD_AccessHandlerCallback callback.
   8262  *
   8263  * For suspended connection this function can be called at any moment (this
   8264  * behaviour is deprecated and will be removed!). Response  will be sent
   8265  * as soon as connection is resumed.
   8266  *
   8267  * For single thread environment, when MHD is used in "external polling" mode
   8268  * (without MHD_USE_SELECT_INTERNALLY) this function can be called any
   8269  * time (this behaviour is deprecated and will be removed!).
   8270  *
   8271  * If HTTP specifications require use no body in reply, like @a status_code with
   8272  * value 1xx, the response body is automatically not sent even if it is present
   8273  * in the response. No "Content-Length" or "Transfer-Encoding" headers are
   8274  * generated and added.
   8275  *
   8276  * When the response is used to respond HEAD request or used with @a status_code
   8277  * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length"
   8278  * header is added automatically based the size of the body in the response.
   8279  * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced
   8280  * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead
   8281  * of "Content-Length" header. For example, if response with zero-size body is
   8282  * used for HEAD request, then "Content-Length: 0" is added automatically to
   8283  * reply headers.
   8284  * @sa #MHD_RF_HEAD_ONLY_RESPONSE
   8285  *
   8286  * In situations, where reply body is required, like answer for the GET request
   8287  * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body
   8288  * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1)
   8289  * are added automatically.
   8290  * In practice, the same response object can be used to respond to both HEAD and
   8291  * GET requests.
   8292  *
   8293  * @param connection the connection identifying the client
   8294  * @param status_code HTTP status code (i.e. #MHD_HTTP_OK)
   8295  * @param response response to transmit, the NULL is tolerated
   8296  * @return #MHD_NO on error (reply already sent, response is NULL),
   8297  *         #MHD_YES on success or if message has been queued
   8298  * @ingroup response
   8299  * @sa #MHD_AccessHandlerCallback
   8300  */
   8301 _MHD_EXTERN enum MHD_Result
   8302 MHD_queue_response (struct MHD_Connection *connection,
   8303                     unsigned int status_code,
   8304                     struct MHD_Response *response)
   8305 {
   8306   struct MHD_Daemon *daemon;
   8307   bool reply_icy;
   8308 
   8309   if ((NULL == connection) || (NULL == response))
   8310     return MHD_NO;
   8311 
   8312   daemon = connection->daemon;
   8313   if ((! connection->in_access_handler) && (! connection->suspended) &&
   8314       MHD_D_IS_USING_THREADS_ (daemon))
   8315     return MHD_NO;
   8316 
   8317   reply_icy = (0 != (status_code & MHD_ICY_FLAG));
   8318   status_code &= ~MHD_ICY_FLAG;
   8319 
   8320 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   8321   if ( (! connection->suspended) &&
   8322        MHD_D_IS_USING_THREADS_ (daemon) &&
   8323        (! MHD_thread_handle_ID_is_current_thread_ (connection->tid)) )
   8324   {
   8325 #ifdef HAVE_MESSAGES
   8326     MHD_DLOG (daemon,
   8327               _ ("Attempted to queue response on wrong thread!\n"));
   8328 #endif
   8329     return MHD_NO;
   8330   }
   8331 #endif
   8332 
   8333   if (NULL != connection->rp.response)
   8334     return MHD_NO; /* The response was already set */
   8335 
   8336   if ( (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) &&
   8337        (MHD_CONNECTION_FULL_REQ_RECEIVED != connection->state) )
   8338     return MHD_NO; /* Wrong connection state */
   8339 
   8340   if (daemon->shutdown)
   8341     return MHD_NO;
   8342 
   8343 #ifdef UPGRADE_SUPPORT
   8344   if (NULL != response->upgrade_handler)
   8345   {
   8346     if (0 == (daemon->options & MHD_ALLOW_UPGRADE))
   8347     {
   8348 #ifdef HAVE_MESSAGES
   8349       MHD_DLOG (daemon,
   8350                 _ ("Attempted 'upgrade' connection on daemon without" \
   8351                    " MHD_ALLOW_UPGRADE option!\n"));
   8352 #endif
   8353       return MHD_NO;
   8354     }
   8355     if (MHD_HTTP_SWITCHING_PROTOCOLS != status_code)
   8356     {
   8357 #ifdef HAVE_MESSAGES
   8358       MHD_DLOG (daemon,
   8359                 _ ("Application used invalid status code for" \
   8360                    " 'upgrade' response!\n"));
   8361 #endif
   8362       return MHD_NO;
   8363     }
   8364     if (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
   8365     {
   8366 #ifdef HAVE_MESSAGES
   8367       MHD_DLOG (daemon,
   8368                 _ ("Application used invalid response" \
   8369                    " without \"Connection\" header!\n"));
   8370 #endif
   8371       return MHD_NO;
   8372     }
   8373     /* MHD_add_response_header() keeps the "Connection" header first, so
   8374        response->first_header could be read directly here; look it up by
   8375        name instead, so that this does not silently break if that ever
   8376        stops being true. */
   8377     mhd_assert (NULL != response->first_header);
   8378     mhd_assert (MHD_str_equal_caseless_ (response->first_header->header,
   8379                                          MHD_HTTP_HEADER_CONNECTION));
   8380     if (! MHD_check_response_header_s_token_ci (response,
   8381                                                 MHD_HTTP_HEADER_CONNECTION,
   8382                                                 "upgrade"))
   8383     {
   8384 #ifdef HAVE_MESSAGES
   8385       MHD_DLOG (daemon,
   8386                 _ ("Application used invalid response" \
   8387                    " without \"upgrade\" token in" \
   8388                    " \"Connection\" header!\n"));
   8389 #endif
   8390       return MHD_NO;
   8391     }
   8392     if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver))
   8393     {
   8394 #ifdef HAVE_MESSAGES
   8395       MHD_DLOG (daemon,
   8396                 _ ("Connection \"Upgrade\" can be used only " \
   8397                    "with HTTP/1.1 connections!\n"));
   8398 #endif
   8399       return MHD_NO;
   8400     }
   8401     if (MHD_CONN_MUST_CLOSE == connection->keepalive)
   8402     {
   8403       /* MHD has already decided, while parsing the request, that this
   8404        * connection cannot be reused; 'keepalive_possible()' therefore
   8405        * returns MHD_CONN_MUST_CLOSE rather than MHD_CONN_MUST_UPGRADE
   8406        * for it, and 'build_header_response()' asserts that an upgrade
   8407        * reply is only ever built for MHD_CONN_MUST_UPGRADE.  Refuse the
   8408        * response here instead of aborting there.
   8409        *
   8410        * The application cannot test for this itself: the request that
   8411        * triggers it looks perfectly well-formed to the access handler.
   8412        * A request carrying both "Content-Length" and
   8413        * "Transfer-Encoding: chunked" is the shortest way in and needs
   8414        * no non-default daemon options at all. */
   8415 #ifdef HAVE_MESSAGES
   8416       MHD_DLOG (daemon,
   8417                 _ ("Connection cannot be upgraded: it has already been " \
   8418                    "marked as \"must close\" while the request was " \
   8419                    "being parsed.\n"));
   8420 #endif
   8421       return MHD_NO;
   8422     }
   8423   }
   8424 #endif /* UPGRADE_SUPPORT */
   8425   if (MHD_HTTP_SWITCHING_PROTOCOLS == status_code)
   8426   {
   8427 #ifdef UPGRADE_SUPPORT
   8428     if (NULL == response->upgrade_handler)
   8429     {
   8430 #ifdef HAVE_MESSAGES
   8431       MHD_DLOG (daemon,
   8432                 _ ("Application used status code 101 \"Switching Protocols\" " \
   8433                    "with non-'upgrade' response!\n"));
   8434 #endif /* HAVE_MESSAGES */
   8435       return MHD_NO;
   8436     }
   8437 #else  /* ! UPGRADE_SUPPORT */
   8438 #ifdef HAVE_MESSAGES
   8439     MHD_DLOG (daemon,
   8440               _ ("Application used status code 101 \"Switching Protocols\", " \
   8441                  "but this MHD was built without \"Upgrade\" support!\n"));
   8442 #endif /* HAVE_MESSAGES */
   8443     return MHD_NO;
   8444 #endif /* ! UPGRADE_SUPPORT */
   8445   }
   8446   if ( (100 > status_code) ||
   8447        (999 < status_code) )
   8448   {
   8449 #ifdef HAVE_MESSAGES
   8450     MHD_DLOG (daemon,
   8451               _ ("Refused wrong status code (%u). " \
   8452                  "HTTP requires three digits status code!\n"),
   8453               status_code);
   8454 #endif
   8455     return MHD_NO;
   8456   }
   8457   if (200 > status_code)
   8458   {
   8459     if (MHD_HTTP_VER_1_0 == connection->rq.http_ver)
   8460     {
   8461 #ifdef HAVE_MESSAGES
   8462       MHD_DLOG (daemon,
   8463                 _ ("Wrong status code (%u) refused. " \
   8464                    "HTTP/1.0 clients do not support 1xx status codes!\n"),
   8465                 (status_code));
   8466 #endif
   8467       return MHD_NO;
   8468     }
   8469     if (0 != (response->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
   8470                                  | MHD_RF_HTTP_1_0_SERVER)))
   8471     {
   8472 #ifdef HAVE_MESSAGES
   8473       MHD_DLOG (daemon,
   8474                 _ ("Wrong status code (%u) refused. " \
   8475                    "HTTP/1.0 reply mode does not support 1xx status codes!\n"),
   8476                 (status_code));
   8477 #endif
   8478       return MHD_NO;
   8479     }
   8480   }
   8481   if ( (MHD_HTTP_MTHD_CONNECT == connection->rq.http_mthd) &&
   8482        (2 == status_code / 100) )
   8483   {
   8484 #ifdef HAVE_MESSAGES
   8485     MHD_DLOG (daemon,
   8486               _ ("Successful (%u) response code cannot be used to answer " \
   8487                  "\"CONNECT\" request!\n"),
   8488               (status_code));
   8489 #endif
   8490     return MHD_NO;
   8491   }
   8492 
   8493   if ( (0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) &&
   8494        (RP_BODY_HEADERS_ONLY < is_reply_body_needed (connection, status_code)) )
   8495   {
   8496 #ifdef HAVE_MESSAGES
   8497     MHD_DLOG (daemon,
   8498               _ ("HEAD-only response cannot be used when the request requires "
   8499                  "reply body to be sent!\n"));
   8500 #endif
   8501     return MHD_NO;
   8502   }
   8503 
   8504 #ifdef HAVE_MESSAGES
   8505   if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) &&
   8506        (0 != (MHD_RAF_HAS_CONTENT_LENGTH & response->flags_auto)) )
   8507   {
   8508     MHD_DLOG (daemon,
   8509               _ ("The response has application-defined \"Content-Length\" " \
   8510                  "header. The reply to the request will be not " \
   8511                  "HTTP-compliant and may result in hung connection or " \
   8512                  "other problems!\n"));
   8513   }
   8514 #endif
   8515 
   8516   MHD_increment_response_rc (response);
   8517   connection->rp.response = response;
   8518   connection->rp.responseCode = status_code;
   8519   connection->rp.responseIcy = reply_icy;
   8520 #if defined(_MHD_HAVE_SENDFILE)
   8521   if ( (response->fd == -1) ||
   8522        (response->is_pipe) ||
   8523        (0 != (connection->daemon->options & MHD_USE_TLS))
   8524 #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \
   8525        defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE)
   8526        || (! daemon->sigpipe_blocked && ! connection->sk_spipe_suppress)
   8527 #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED &&
   8528           MHD_SEND_SPIPE_SUPPRESS_POSSIBLE */
   8529        )
   8530     connection->rp.resp_sender = MHD_resp_sender_std;
   8531   else
   8532     connection->rp.resp_sender = MHD_resp_sender_sendfile;
   8533 #endif /* _MHD_HAVE_SENDFILE */
   8534   /* FIXME: if 'is_pipe' is set, TLS is off, and we have *splice*, we could use splice()
   8535      to avoid two user-space copies... */
   8536 
   8537   if ( (MHD_HTTP_MTHD_HEAD == connection->rq.http_mthd) ||
   8538        (MHD_HTTP_OK > status_code) ||
   8539        (MHD_HTTP_NO_CONTENT == status_code) ||
   8540        (MHD_HTTP_NOT_MODIFIED == status_code) )
   8541   {
   8542     /* if this is a "HEAD" request, or a status code for
   8543        which a body is not allowed, pretend that we
   8544        have already sent the full message body. */
   8545     /* TODO: remove the next assignment, use 'rp_props.send_reply_body' in
   8546      * checks */
   8547     connection->rp.rsp_write_position = response->total_size;
   8548   }
   8549   if (MHD_CONNECTION_HEADERS_PROCESSED == connection->state)
   8550   {
   8551     /* response was queued "early", refuse to read body / footers or
   8552        further requests! */
   8553     connection->discard_request = true;
   8554     connection->state = MHD_CONNECTION_START_REPLY;
   8555     connection->rq.remaining_upload_size = 0;
   8556   }
   8557   if (! connection->in_idle)
   8558     (void) MHD_connection_handle_idle (connection);
   8559   MHD_update_last_activity_ (connection);
   8560   return MHD_YES;
   8561 }
   8562 
   8563 
   8564 /* end of connection.c */