-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathHTTPServerRequest.cpp
More file actions
212 lines (170 loc) · 7.75 KB
/
Copy pathHTTPServerRequest.cpp
File metadata and controls
212 lines (170 loc) · 7.75 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#include <memory>
#include <Server/HTTP/HTTPServerRequest.h>
#include <IO/EmptyReadBuffer.h>
#include <IO/HTTPChunkedReadBuffer.h>
#include <IO/LimitReadBuffer.h>
#include <IO/ReadBufferFromPocoSocket.h>
#include <IO/ReadHelpers.h>
#include <IO/ReadBuffer.h>
#include <Server/HTTP/DeadlineReadBuffer.h>
#include <Server/HTTP/HTTPServerResponse.h>
#include <Server/HTTP/ReadHeaders.h>
#include <Poco/Net/HTTPHeaderStream.h>
#include <Poco/Net/HTTPStream.h>
#include <Poco/Net/NetException.h>
#include <Common/logger_useful.h>
#if USE_SSL
#include <Poco/Net/SecureStreamSocketImpl.h>
#include <Poco/Net/SSLException.h>
#include <Common/Crypto/X509Certificate.h>
#endif
static constexpr UInt64 HTTP_MAX_CHUNK_SIZE = 100ULL << 30;
namespace DB
{
HTTPServerRequest::HTTPServerRequest(HTTPContextPtr context, HTTPServerResponse & response, Poco::Net::HTTPServerSession & session, const ProfileEvents::Event & read_event)
: max_uri_size(context->getMaxUriSize())
, max_fields_number(context->getMaxFields())
, max_field_name_size(context->getMaxFieldNameSize())
, max_field_value_size(context->getMaxFieldValueSize())
, max_request_header_size(context->getMaxRequestHeaderSize())
{
response.attachRequest(this);
/// Now that we know socket is still connected, obtain addresses
client_address = session.clientAddress();
server_address = session.serverAddress();
secure = session.socket().secure();
auto receive_timeout = context->getReceiveTimeout();
auto send_timeout = context->getSendTimeout();
auto headers_read_timeout = context->getHeadersReadTimeout();
/// Use the smaller of headers_read_timeout and receive_timeout during header parsing
/// to enforce a total deadline on the entire handshake phase.
auto effective_timeout = (headers_read_timeout > Poco::Timespan(0) &&
(receive_timeout <= Poco::Timespan(0) || headers_read_timeout < receive_timeout))
? headers_read_timeout : receive_timeout;
session.socket().setReceiveTimeout(effective_timeout);
session.socket().setSendTimeout(send_timeout);
auto socket_in = std::make_unique<ReadBufferFromPocoSocket>(session.socket(), read_event);
socket = session.socket().impl();
/// Wrap the socket buffer with a deadline check if configured.
/// The deadline is enforced in DeadlineReadBuffer::nextImpl on every buffer refill,
/// which protects all parsing (request line, URI, headers) automatically.
if (headers_read_timeout > Poco::Timespan(0))
{
auto deadline = std::chrono::steady_clock::now()
+ std::chrono::microseconds(headers_read_timeout.totalMicroseconds());
DeadlineReadBuffer deadline_in(*socket_in, deadline);
readRequest(deadline_in); /// Try parse according to RFC7230
}
else
{
readRequest(*socket_in); /// Try parse according to RFC7230
}
/// Restore the original receive timeout for body reads.
session.socket().setReceiveTimeout(receive_timeout);
/// Build the body stream from the underlying socket buffer (not the deadline wrapper).
auto in = std::move(socket_in);
/// If a client crashes, most systems will gracefully terminate the connection with FIN just like it's done on close().
/// So we will get 0 from recv(...) and will not be able to understand that something went wrong (well, we probably
/// will get RST later on attempt to write to the socket that closed on the other side, but it will happen when the query is finished).
/// If we are extremely unlucky and data format is TSV, for example, then we may stop parsing exactly between rows
/// and decide that it's EOF (but it is not). It may break deduplication, because clients cannot control it
/// and retry with exactly the same (incomplete) set of rows.
/// That's why we have to check body size if it's provided.
if (getChunkedTransferEncoding())
{
stream = std::make_shared<HTTPChunkedReadBuffer>(std::move(in), HTTP_MAX_CHUNK_SIZE);
stream_is_bounded = true;
}
else if (hasContentLength())
{
size_t content_length = getContentLength();
stream = std::make_shared<LimitReadBuffer>(std::move(in), LimitReadBuffer::Settings{.read_no_less = content_length, .read_no_more = content_length, .expect_eof = true});
stream_is_bounded = true;
}
else if (getMethod() != HTTPRequest::HTTP_GET && getMethod() != HTTPRequest::HTTP_HEAD && getMethod() != HTTPRequest::HTTP_DELETE)
{
stream = std::move(in);
if (!startsWith(getContentType(), "multipart/form-data"))
LOG_WARNING(LogFrequencyLimiter(getLogger("HTTPServerRequest"), 10), "Got an HTTP request with no content length "
"and no chunked/multipart encoding, it may be impossible to distinguish graceful EOF from abnormal connection loss");
}
else
{
/// We have to distinguish empty buffer and nullptr.
stream = std::make_shared<EmptyReadBuffer>();
stream_is_bounded = true;
}
}
bool HTTPServerRequest::checkPeerConnected() const
{
return socket->connectionOpen();
}
#if USE_SSL
bool HTTPServerRequest::havePeerCertificate() const
{
if (!secure)
return false;
const Poco::Net::SecureStreamSocketImpl * secure_socket = dynamic_cast<const Poco::Net::SecureStreamSocketImpl *>(socket);
if (!secure_socket)
return false;
return secure_socket->havePeerCertificate();
}
X509Certificate HTTPServerRequest::peerCertificate() const
{
if (!secure)
throw Poco::Net::SSLException("No certificate available");
const Poco::Net::SecureStreamSocketImpl * secure_socket = dynamic_cast<const Poco::Net::SecureStreamSocketImpl *>(socket);
if (!secure_socket)
throw Poco::Net::SSLException("No certificate available");
return X509Certificate(secure_socket->peerCertificate());
}
#endif
void HTTPServerRequest::readRequest(ReadBuffer & in)
{
char ch = 0;
std::string method;
std::string uri;
std::string version;
method.reserve(16);
uri.reserve(64);
version.reserve(16);
if (in.eof())
throw Poco::Net::NoMessageException();
skipWhitespaceIfAny(in);
if (in.eof())
throw Poco::Net::MessageException("No HTTP request header");
while (in.read(ch) && !Poco::Ascii::isSpace(ch) && method.size() <= MAX_METHOD_LENGTH)
method += ch;
if (method.size() > MAX_METHOD_LENGTH)
throw Poco::Net::MessageException("HTTP request method invalid or too long");
skipWhitespaceIfAny(in);
while (in.read(ch) && !Poco::Ascii::isSpace(ch) && uri.size() <= max_uri_size)
uri += ch;
if (uri.size() > max_uri_size)
throw Poco::Net::MessageException("HTTP request URI invalid or too long");
skipWhitespaceIfAny(in);
while (in.read(ch) && !Poco::Ascii::isSpace(ch) && version.size() <= MAX_VERSION_LENGTH)
version += ch;
if (version.size() > MAX_VERSION_LENGTH)
throw Poco::Net::MessageException(fmt::format("Invalid HTTP version string: {}", version));
// since HTTP always use Windows-style EOL '\r\n' we always can safely skip to '\n'
skipToNextLineOrEOF(in);
readHeaders(*this, in, max_fields_number, max_field_name_size, max_field_value_size, max_request_header_size);
skipToNextLineOrEOF(in);
setMethod(method);
setURI(uri);
setVersion(version);
}
std::string HTTPServerRequest::toStringForLogging() const
{
return fmt::format(
"Method: {}, Address: {}, User-Agent: {}{}, Content Type: {}, Transfer Encoding: {}, X-Forwarded-For: {}",
getMethod(),
clientAddress().toString(),
get("User-Agent", "(none)"),
(hasContentLength() ? fmt::format(", Length: {}", getContentLength()) : ""),
getContentType(),
getTransferEncoding(),
get("X-Forwarded-For", "(none)"));
}
}