aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Server/HTTP/ReadHeaders.cpp
blob: b705750106461fa654236667e81e9256d7799d1c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <Server/HTTP/ReadHeaders.h>

#include <IO/ReadBuffer.h>
#include <IO/ReadHelpers.h>

#include <Poco/Net/NetException.h>

namespace DB
{

void readHeaders(
    Poco::Net::MessageHeader & headers, ReadBuffer & in, size_t max_fields_number, size_t max_name_length, size_t max_value_length)
{
    char ch = 0;  // silence uninitialized warning from gcc-*
    std::string name;
    std::string value;

    name.reserve(32);
    value.reserve(64);

    size_t fields = 0;

    while (true)
    {
        if (fields > max_fields_number)
            throw Poco::Net::MessageException("Too many header fields");

        name.clear();
        value.clear();

        /// Field name
        while (in.peek(ch) && ch != ':' && !Poco::Ascii::isSpace(ch) && name.size() <= max_name_length)
        {
            name += ch;
            in.ignore();
        }

        if (in.eof())
            throw Poco::Net::MessageException("Field is invalid");

        if (name.empty())
        {
            if (ch == '\r')
                /// Start of the empty-line delimiter
                break;
            if (ch == ':')
                throw Poco::Net::MessageException("Field name is empty");
        }
        else
        {
            if (name.size() > max_name_length)
                throw Poco::Net::MessageException("Field name is too long");
            if (ch != ':')
                throw Poco::Net::MessageException(fmt::format("Field name is invalid or no colon found: \"{}\"", name));
        }

        in.ignore();

        skipWhitespaceIfAny(in, true);

        if (in.eof())
            throw Poco::Net::MessageException("Field is invalid");

        /// Field value - folded values not supported.
        while (in.read(ch) && ch != '\r' && ch != '\n' && value.size() <= max_value_length)
            value += ch;

        if (in.eof())
            throw Poco::Net::MessageException("Field is invalid");

        if (ch == '\n')
            throw Poco::Net::MessageException("No CRLF found");

        if (value.size() > max_value_length)
            throw Poco::Net::MessageException("Field value is too long");

        skipToNextLineOrEOF(in);

        Poco::trimRightInPlace(value);
        headers.add(name, headers.decodeWord(value));
        ++fields;
    }
}

}