]>
Commit | Line | Data |
---|---|---|
dd11e0b7 | 1 | /* |
5b74111a | 2 | * Copyright (C) 1996-2018 The Squid Software Foundation and contributors |
dd11e0b7 | 3 | * |
bbc27441 AJ |
4 | * Squid software is distributed under GPLv2+ license and includes |
5 | * contributions from numerous individuals and organizations. | |
6 | * Please see the COPYING and CONTRIBUTORS files for details. | |
dd11e0b7 | 7 | */ |
f88bb09c | 8 | |
bbc27441 AJ |
9 | /* DEBUG: section 33 Client-side Routines */ |
10 | ||
63be0a78 | 11 | /** |
12 | \defgroup ClientSide Client-Side Logics | |
13 | * | |
d85b8894 | 14 | \section cserrors Errors and client side |
edce4d98 | 15 | * |
63be0a78 | 16 | \par Problem the first: |
17 | * the store entry is no longer authoritative on the | |
edce4d98 | 18 | * reply status. EBITTEST (E_ABORT) is no longer a valid test outside |
19 | * of client_side_reply.c. | |
20 | * Problem the second: resources are wasted if we delay in cleaning up. | |
21 | * Problem the third we can't depend on a connection close to clean up. | |
9e008dda | 22 | * |
63be0a78 | 23 | \par Nice thing the first: |
9e008dda | 24 | * Any step in the stream can callback with data |
edce4d98 | 25 | * representing an error. |
26 | * Nice thing the second: once you stop requesting reads from upstream, | |
27 | * upstream can be stopped too. | |
28 | * | |
63be0a78 | 29 | \par Solution #1: |
30 | * Error has a callback mechanism to hand over a membuf | |
9e008dda | 31 | * with the error content. The failing node pushes that back as the |
edce4d98 | 32 | * reply. Can this be generalised to reduce duplicate efforts? |
33 | * A: Possibly. For now, only one location uses this. | |
34 | * How to deal with pre-stream errors? | |
35 | * Tell client_side_reply that we *want* an error page before any | |
36 | * stream calls occur. Then we simply read as normal. | |
63be0a78 | 37 | * |
38 | * | |
d85b8894 | 39 | \section pconn_logic Persistent connection logic: |
63be0a78 | 40 | * |
41 | \par | |
42 | * requests (httpClientRequest structs) get added to the connection | |
43 | * list, with the current one being chr | |
9e008dda | 44 | * |
63be0a78 | 45 | \par |
46 | * The request is *immediately* kicked off, and data flows through | |
47 | * to clientSocketRecipient. | |
9e008dda | 48 | * |
63be0a78 | 49 | \par |
50 | * If the data that arrives at clientSocketRecipient is not for the current | |
51 | * request, clientSocketRecipient simply returns, without requesting more | |
52 | * data, or sending it. | |
53 | * | |
54 | \par | |
4a4fbcef | 55 | * ConnStateData::kick() will then detect the presence of data in |
9e008dda | 56 | * the next ClientHttpRequest, and will send it, restablishing the |
63be0a78 | 57 | * data flow. |
edce4d98 | 58 | */ |
59 | ||
582c2af2 | 60 | #include "squid.h" |
04f55905 | 61 | #include "acl/FilledChecklist.h" |
65d448bc | 62 | #include "anyp/PortCfg.h" |
00406b24 | 63 | #include "base/Subscription.h" |
d841c88d | 64 | #include "base/TextException.h" |
a011edee | 65 | #include "CachePeer.h" |
95e6d864 | 66 | #include "client_db.h" |
602d9612 | 67 | #include "client_side.h" |
04f55905 AJ |
68 | #include "client_side_reply.h" |
69 | #include "client_side_request.h" | |
70 | #include "ClientRequestContext.h" | |
c8be6d7b | 71 | #include "clientStream.h" |
c4b7a5a9 | 72 | #include "comm.h" |
cfd66529 | 73 | #include "comm/Connection.h" |
d841c88d | 74 | #include "comm/Loops.h" |
7e66d5e2 | 75 | #include "comm/Read.h" |
cbff89ba | 76 | #include "comm/TcpAcceptor.h" |
582c2af2 FC |
77 | #include "comm/Write.h" |
78 | #include "CommCalls.h" | |
8eb0a7ee | 79 | #include "errorpage.h" |
c4ad1349 | 80 | #include "fd.h" |
04f55905 | 81 | #include "fde.h" |
95e6d864 | 82 | #include "fqdncache.h" |
eb13c21e | 83 | #include "FwdState.h" |
67679543 | 84 | #include "globals.h" |
24438ec5 AJ |
85 | #include "helper.h" |
86 | #include "helper/Reply.h" | |
5c0c642e | 87 | #include "http.h" |
c99510dd | 88 | #include "http/one/RequestParser.h" |
db1720f8 | 89 | #include "http/one/TeChunkedParser.h" |
d3dddfb5 | 90 | #include "http/Stream.h" |
25b6a907 | 91 | #include "HttpHdrContRange.h" |
a5bac1d2 | 92 | #include "HttpHeaderTools.h" |
528b2c61 | 93 | #include "HttpReply.h" |
94 | #include "HttpRequest.h" | |
4daaf3cb AJ |
95 | #include "ident/Config.h" |
96 | #include "ident/Ident.h" | |
308e60be | 97 | #include "internal.h" |
cbff89ba | 98 | #include "ipc/FdNotes.h" |
fe090a86 | 99 | #include "ipc/StartListening.h" |
1c7ae5ff | 100 | #include "log/access_log.h" |
0eb49b6d | 101 | #include "MemBuf.h" |
04f55905 | 102 | #include "MemObject.h" |
b6149797 | 103 | #include "mime_header.h" |
b1cef121 | 104 | #include "parser/Tokenizer.h" |
582c2af2 | 105 | #include "profiler/Profiler.h" |
2bcab852 | 106 | #include "security/NegotiationHistory.h" |
92ae4c86 | 107 | #include "servers/forward.h" |
4d5904f7 | 108 | #include "SquidConfig.h" |
582c2af2 | 109 | #include "SquidTime.h" |
e1656dc4 | 110 | #include "StatCounters.h" |
00a7574e | 111 | #include "StatHist.h" |
582c2af2 FC |
112 | #include "Store.h" |
113 | #include "TimeOrTag.h" | |
4e540555 | 114 | #include "tools.h" |
582c2af2 FC |
115 | |
116 | #if USE_AUTH | |
117 | #include "auth/UserRequest.h" | |
118 | #endif | |
119 | #if USE_DELAY_POOLS | |
120 | #include "ClientInfo.h" | |
b27668ec | 121 | #include "MessageDelayPools.h" |
582c2af2 | 122 | #endif |
cb4f4424 | 123 | #if USE_OPENSSL |
d620ae0e | 124 | #include "ssl/bio.h" |
95d2589c | 125 | #include "ssl/context_storage.h" |
602d9612 | 126 | #include "ssl/gadgets.h" |
95d2589c | 127 | #include "ssl/helper.h" |
602d9612 | 128 | #include "ssl/ProxyCerts.h" |
fd4624d7 | 129 | #include "ssl/ServerBump.h" |
4db984be | 130 | #include "ssl/support.h" |
95d2589c | 131 | #endif |
95d2589c | 132 | |
ed6e9fb9 AJ |
133 | // for tvSubUsec() which should be in SquidTime.h |
134 | #include "util.h" | |
135 | ||
074d6a40 AJ |
136 | #include <climits> |
137 | #include <cmath> | |
95d2589c | 138 | #include <limits> |
95d2589c | 139 | |
5492ad1d | 140 | #if LINGERING_CLOSE |
141 | #define comm_close comm_lingering_close | |
142 | #endif | |
143 | ||
cbff89ba | 144 | /// dials clientListenerConnectionOpened call |
fe090a86 AR |
145 | class ListeningStartedDialer: public CallDialer, public Ipc::StartListeningCb |
146 | { | |
147 | public: | |
fa720bfb AJ |
148 | typedef void (*Handler)(AnyP::PortCfgPointer &portCfg, const Ipc::FdNoteId note, const Subscription::Pointer &sub); |
149 | ListeningStartedDialer(Handler aHandler, AnyP::PortCfgPointer &aPortCfg, const Ipc::FdNoteId note, const Subscription::Pointer &aSub): | |
f53969cc | 150 | handler(aHandler), portCfg(aPortCfg), portTypeNote(note), sub(aSub) {} |
fe090a86 | 151 | |
5667a628 AR |
152 | virtual void print(std::ostream &os) const { |
153 | startPrint(os) << | |
f53969cc | 154 | ", " << FdNote(portTypeNote) << " port=" << (void*)&portCfg << ')'; |
5667a628 | 155 | } |
fe090a86 AR |
156 | |
157 | virtual bool canDial(AsyncCall &) const { return true; } | |
8bbb16e3 | 158 | virtual void dial(AsyncCall &) { (handler)(portCfg, portTypeNote, sub); } |
fe090a86 AR |
159 | |
160 | public: | |
161 | Handler handler; | |
162 | ||
163 | private: | |
fa720bfb | 164 | AnyP::PortCfgPointer portCfg; ///< from HttpPortList |
cbff89ba | 165 | Ipc::FdNoteId portTypeNote; ///< Type of IPC socket being opened |
cbff89ba | 166 | Subscription::Pointer sub; ///< The handler to be subscribed for this connetion listener |
fe090a86 AR |
167 | }; |
168 | ||
fa720bfb | 169 | static void clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub); |
fe090a86 | 170 | |
e0d28505 | 171 | static IOACB httpAccept; |
8d77a37c | 172 | static CTCB clientLifetimeTimeout; |
3898f57f | 173 | #if USE_IDENT |
05832ae1 | 174 | static IDCB clientIdentDone; |
3898f57f | 175 | #endif |
190154cf | 176 | static int clientIsContentLengthValid(HttpRequest * r); |
47f6e231 | 177 | static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength); |
50c09fc4 | 178 | |
91369933 AJ |
179 | static void clientUpdateStatHistCounters(const LogTags &logType, int svc_time); |
180 | static void clientUpdateStatCounters(const LogTags &logType); | |
c8be6d7b | 181 | static void clientUpdateHierCounters(HierarchyLogEntry *); |
528b2c61 | 182 | static bool clientPingHasFinished(ping_data const *aPing); |
41ebd397 | 183 | void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry::Pointer &); |
d3dddfb5 | 184 | static void ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest, ConnStateData * conn); |
c8be6d7b | 185 | |
84cc2635 | 186 | char *skipLeadingSpace(char *aString); |
62e76326 | 187 | |
edce4d98 | 188 | #if USE_IDENT |
4d55827a | 189 | static void |
edce4d98 | 190 | clientIdentDone(const char *ident, void *data) |
4d55827a | 191 | { |
cc59d02a | 192 | ConnStateData *conn = (ConnStateData *)data; |
73c36fd9 | 193 | xstrncpy(conn->clientConnection->rfc931, ident ? ident : dash_str, USER_IDENT_SZ); |
e81957b7 | 194 | } |
447e176b | 195 | #endif |
7a2f978b | 196 | |
c8be6d7b | 197 | void |
91369933 | 198 | clientUpdateStatCounters(const LogTags &logType) |
a7c05555 | 199 | { |
e4f1fdae | 200 | ++statCounter.client_http.requests; |
62e76326 | 201 | |
91369933 | 202 | if (logType.isTcpHit()) |
e4f1fdae | 203 | ++statCounter.client_http.hits; |
62e76326 | 204 | |
91369933 | 205 | if (logType.oldType == LOG_TCP_HIT) |
e4f1fdae | 206 | ++statCounter.client_http.disk_hits; |
91369933 | 207 | else if (logType.oldType == LOG_TCP_MEM_HIT) |
e4f1fdae | 208 | ++statCounter.client_http.mem_hits; |
c8be6d7b | 209 | } |
210 | ||
211 | void | |
91369933 | 212 | clientUpdateStatHistCounters(const LogTags &logType, int svc_time) |
c8be6d7b | 213 | { |
e8baef82 | 214 | statCounter.client_http.allSvcTime.count(svc_time); |
63be0a78 | 215 | /** |
ee1679df | 216 | * The idea here is not to be complete, but to get service times |
217 | * for only well-defined types. For example, we don't include | |
1d7ab0f4 | 218 | * LOG_TCP_REFRESH_FAIL because its not really a cache hit |
ee1679df | 219 | * (we *tried* to validate it, but failed). |
220 | */ | |
62e76326 | 221 | |
91369933 | 222 | switch (logType.oldType) { |
62e76326 | 223 | |
1d7ab0f4 | 224 | case LOG_TCP_REFRESH_UNMODIFIED: |
e8baef82 | 225 | statCounter.client_http.nearHitSvcTime.count(svc_time); |
62e76326 | 226 | break; |
227 | ||
787ea68c | 228 | case LOG_TCP_INM_HIT: |
ee1679df | 229 | case LOG_TCP_IMS_HIT: |
e8baef82 | 230 | statCounter.client_http.nearMissSvcTime.count(svc_time); |
62e76326 | 231 | break; |
232 | ||
ee1679df | 233 | case LOG_TCP_HIT: |
62e76326 | 234 | |
ee1679df | 235 | case LOG_TCP_MEM_HIT: |
62e76326 | 236 | |
b540e168 | 237 | case LOG_TCP_OFFLINE_HIT: |
e8baef82 | 238 | statCounter.client_http.hitSvcTime.count(svc_time); |
62e76326 | 239 | break; |
240 | ||
ee1679df | 241 | case LOG_TCP_MISS: |
62e76326 | 242 | |
ee1679df | 243 | case LOG_TCP_CLIENT_REFRESH_MISS: |
e8baef82 | 244 | statCounter.client_http.missSvcTime.count(svc_time); |
62e76326 | 245 | break; |
246 | ||
ee1679df | 247 | default: |
62e76326 | 248 | /* make compiler warnings go away */ |
249 | break; | |
ee1679df | 250 | } |
c8be6d7b | 251 | } |
252 | ||
528b2c61 | 253 | bool |
c8be6d7b | 254 | clientPingHasFinished(ping_data const *aPing) |
255 | { | |
256 | if (0 != aPing->stop.tv_sec && 0 != aPing->start.tv_sec) | |
62e76326 | 257 | return true; |
258 | ||
528b2c61 | 259 | return false; |
c8be6d7b | 260 | } |
261 | ||
262 | void | |
263 | clientUpdateHierCounters(HierarchyLogEntry * someEntry) | |
264 | { | |
265 | ping_data *i; | |
62e76326 | 266 | |
c8547a11 | 267 | switch (someEntry->code) { |
268 | #if USE_CACHE_DIGESTS | |
62e76326 | 269 | |
c8547a11 | 270 | case CD_PARENT_HIT: |
62e76326 | 271 | |
a196e1e4 | 272 | case CD_SIBLING_HIT: |
95dc7ff4 | 273 | ++ statCounter.cd.times_used; |
62e76326 | 274 | break; |
c8547a11 | 275 | #endif |
62e76326 | 276 | |
c8547a11 | 277 | case SIBLING_HIT: |
62e76326 | 278 | |
c8547a11 | 279 | case PARENT_HIT: |
62e76326 | 280 | |
c8547a11 | 281 | case FIRST_PARENT_MISS: |
62e76326 | 282 | |
c8547a11 | 283 | case CLOSEST_PARENT_MISS: |
95dc7ff4 | 284 | ++ statCounter.icp.times_used; |
62e76326 | 285 | i = &someEntry->ping; |
286 | ||
287 | if (clientPingHasFinished(i)) | |
e8baef82 | 288 | statCounter.icp.querySvcTime.count(tvSubUsec(i->start, i->stop)); |
62e76326 | 289 | |
290 | if (i->timeout) | |
95dc7ff4 | 291 | ++ statCounter.icp.query_timeouts; |
62e76326 | 292 | |
293 | break; | |
294 | ||
c8547a11 | 295 | case CLOSEST_PARENT: |
62e76326 | 296 | |
c8547a11 | 297 | case CLOSEST_DIRECT: |
95dc7ff4 | 298 | ++ statCounter.netdb.times_used; |
62e76326 | 299 | |
300 | break; | |
301 | ||
69c95dd3 | 302 | default: |
62e76326 | 303 | break; |
17b6e784 | 304 | } |
a7c05555 | 305 | } |
306 | ||
528b2c61 | 307 | void |
308 | ClientHttpRequest::updateCounters() | |
c8be6d7b | 309 | { |
528b2c61 | 310 | clientUpdateStatCounters(logType); |
62e76326 | 311 | |
528b2c61 | 312 | if (request->errType != ERR_NONE) |
95dc7ff4 | 313 | ++ statCounter.client_http.errors; |
62e76326 | 314 | |
528b2c61 | 315 | clientUpdateStatHistCounters(logType, |
af0ded40 | 316 | tvSubMsec(al->cache.start_time, current_time)); |
62e76326 | 317 | |
528b2c61 | 318 | clientUpdateHierCounters(&request->hier); |
c8be6d7b | 319 | } |
320 | ||
edce4d98 | 321 | void |
41ebd397 | 322 | prepareLogWithRequestDetails(HttpRequest * request, AccessLogEntry::Pointer &aLogEntry) |
7a2f978b | 323 | { |
c8be6d7b | 324 | assert(request); |
41ebd397 | 325 | assert(aLogEntry != NULL); |
7684c4b1 | 326 | |
327 | if (Config.onoff.log_mime_hdrs) { | |
7684c4b1 | 328 | MemBuf mb; |
2fe7eff9 | 329 | mb.init(); |
10201568 | 330 | request->header.packInto(&mb); |
105d1937 A |
331 | //This is the request after adaptation or redirection |
332 | aLogEntry->headers.adapted_request = xstrdup(mb.buf); | |
333 | ||
334 | // the virgin request is saved to aLogEntry->request | |
335 | if (aLogEntry->request) { | |
105d1937 | 336 | mb.reset(); |
10201568 | 337 | aLogEntry->request->header.packInto(&mb); |
105d1937 A |
338 | aLogEntry->headers.request = xstrdup(mb.buf); |
339 | } | |
3ff65596 | 340 | |
5038f9d8 AR |
341 | #if USE_ADAPTATION |
342 | const Adaptation::History::Pointer ah = request->adaptLogHistory(); | |
343 | if (ah != NULL) { | |
5038f9d8 | 344 | mb.reset(); |
10201568 | 345 | ah->lastMeta.packInto(&mb); |
99690f32 | 346 | aLogEntry->adapt.last_meta = xstrdup(mb.buf); |
5038f9d8 | 347 | } |
3ff65596 AR |
348 | #endif |
349 | ||
2fe7eff9 | 350 | mb.clean(); |
7684c4b1 | 351 | } |
352 | ||
3ff65596 | 353 | #if ICAP_CLIENT |
5038f9d8 | 354 | const Adaptation::Icap::History::Pointer ih = request->icapHistory(); |
3ff65596 | 355 | if (ih != NULL) |
01bd87d8 | 356 | ih->processingTime(aLogEntry->icap.processingTime); |
3ff65596 AR |
357 | #endif |
358 | ||
c8be6d7b | 359 | aLogEntry->http.method = request->method; |
360 | aLogEntry->http.version = request->http_ver; | |
c8be6d7b | 361 | aLogEntry->hier = request->hier; |
5b4117d8 | 362 | aLogEntry->cache.extuser = request->extacl_user.termedBuf(); |
abb929f0 | 363 | |
a119c6ad AR |
364 | // Adapted request, if any, inherits and then collects all the stats, but |
365 | // the virgin request gets logged instead; copy the stats to log them. | |
366 | // TODO: avoid losses by keeping these stats in a shared history object? | |
64b66b76 | 367 | if (aLogEntry->request) { |
a119c6ad | 368 | aLogEntry->request->dnsWait = request->dnsWait; |
64b66b76 CT |
369 | aLogEntry->request->errType = request->errType; |
370 | aLogEntry->request->errDetail = request->errDetail; | |
371 | } | |
c8be6d7b | 372 | } |
373 | ||
374 | void | |
528b2c61 | 375 | ClientHttpRequest::logRequest() |
376 | { | |
91369933 AJ |
377 | if (!out.size && logType.oldType == LOG_TAG_NONE) |
378 | debugs(33, 5, "logging half-baked transaction: " << log_uri); | |
6fd1086a | 379 | |
41ebd397 CT |
380 | al->icp.opcode = ICP_INVALID; |
381 | al->url = log_uri; | |
382 | debugs(33, 9, "clientLogRequest: al.url='" << al->url << "'"); | |
62e76326 | 383 | |
41ebd397 | 384 | if (al->reply) { |
9b769c67 | 385 | al->http.code = al->reply->sline.status(); |
41ebd397 | 386 | al->http.content_type = al->reply->content_type.termedBuf(); |
6fd1086a | 387 | } else if (loggingEntry() && loggingEntry()->mem_obj) { |
9b769c67 | 388 | al->http.code = loggingEntry()->mem_obj->getReply()->sline.status(); |
41ebd397 | 389 | al->http.content_type = loggingEntry()->mem_obj->getReply()->content_type.termedBuf(); |
6fd1086a | 390 | } |
5f8252d2 | 391 | |
41ebd397 | 392 | debugs(33, 9, "clientLogRequest: http.code='" << al->http.code << "'"); |
90a8964c | 393 | |
3a646078 | 394 | if (loggingEntry() && loggingEntry()->mem_obj && loggingEntry()->objectLen() >= 0) |
d6df21d2 | 395 | al->cache.objectSize = loggingEntry()->contentLen(); // payload duplicate ?? with or without TE ? |
90a8964c | 396 | |
cc0ca3b9 | 397 | al->http.clientRequestSz.header = req_sz; |
bd59d61c EB |
398 | // the virgin request is saved to al->request |
399 | if (al->request && al->request->body_pipe) | |
400 | al->http.clientRequestSz.payloadData = al->request->body_pipe->producedSize(); | |
cc0ca3b9 | 401 | al->http.clientReplySz.header = out.headers_sz; |
d6df21d2 | 402 | // XXX: calculate without payload encoding or headers !! |
cc0ca3b9 | 403 | al->http.clientReplySz.payloadData = out.size - out.headers_sz; // pretend its all un-encoded data for now. |
90a8964c | 404 | |
41ebd397 | 405 | al->cache.highOffset = out.offset; |
90a8964c | 406 | |
41ebd397 | 407 | al->cache.code = logType; |
62e76326 | 408 | |
01bd87d8 | 409 | tvSub(al->cache.trTime, al->cache.start_time, current_time); |
62e76326 | 410 | |
6fd1086a | 411 | if (request) |
41ebd397 | 412 | prepareLogWithRequestDetails(request, al); |
62e76326 | 413 | |
cb4f4424 | 414 | #if USE_OPENSSL && 0 |
62e76326 | 415 | |
6fd1086a AR |
416 | /* This is broken. Fails if the connection has been closed. Needs |
417 | * to snarf the ssl details some place earlier.. | |
418 | */ | |
419 | if (getConn() != NULL) | |
41ebd397 | 420 | al->cache.ssluser = sslGetUserEmail(fd_table[getConn()->fd].ssl); |
62e76326 | 421 | |
a7ad6e4e | 422 | #endif |
62e76326 | 423 | |
f8a2338f AJ |
424 | /* Add notes (if we have a request to annotate) */ |
425 | if (request) { | |
75d47340 CT |
426 | SBuf matched; |
427 | for (auto h: Config.notes) { | |
428 | if (h->match(request, al->reply, NULL, matched)) { | |
429 | request->notes()->add(h->key(), matched); | |
430 | debugs(33, 3, h->key() << " " << matched); | |
f8a2338f | 431 | } |
d7f4a0b7 | 432 | } |
75d47340 CT |
433 | // The al->notes and request->notes must point to the same object. |
434 | al->syncNotes(request); | |
d7f4a0b7 CT |
435 | } |
436 | ||
8ebad780 | 437 | ACLFilledChecklist checklist(NULL, request, NULL); |
b248c2a3 | 438 | if (al->reply) { |
8ebad780 CT |
439 | checklist.reply = al->reply; |
440 | HTTPMSGLOCK(checklist.reply); | |
b248c2a3 | 441 | } |
62e76326 | 442 | |
8ebad780 | 443 | if (request) { |
542e1a7a | 444 | HTTPMSGUNLOCK(al->adapted_request); |
8ebad780 CT |
445 | al->adapted_request = request; |
446 | HTTPMSGLOCK(al->adapted_request); | |
447 | } | |
cb365059 EB |
448 | // no need checklist.syncAle(): already synced |
449 | checklist.al = al; | |
8ebad780 CT |
450 | accessLogLog(al, &checklist); |
451 | ||
452 | bool updatePerformanceCounters = true; | |
453 | if (Config.accessList.stats_collection) { | |
454 | ACLFilledChecklist statsCheck(Config.accessList.stats_collection, request, NULL); | |
cb365059 | 455 | statsCheck.al = al; |
8ebad780 CT |
456 | if (al->reply) { |
457 | statsCheck.reply = al->reply; | |
458 | HTTPMSGLOCK(statsCheck.reply); | |
b248c2a3 | 459 | } |
06bf5384 | 460 | updatePerformanceCounters = statsCheck.fastCheck().allowed(); |
8ebad780 CT |
461 | } |
462 | ||
463 | if (updatePerformanceCounters) { | |
2ae98e09 TH |
464 | if (request) |
465 | updateCounters(); | |
7684c4b1 | 466 | |
1b76e6c1 AJ |
467 | if (getConn() != NULL && getConn()->clientConnection != NULL) |
468 | clientdbUpdate(getConn()->clientConnection->remote, logType, AnyP::PROTO_HTTP, out.size); | |
7a2f978b | 469 | } |
c8be6d7b | 470 | } |
471 | ||
472 | void | |
528b2c61 | 473 | ClientHttpRequest::freeResources() |
c8be6d7b | 474 | { |
528b2c61 | 475 | safe_free(uri); |
528b2c61 | 476 | safe_free(redirect.location); |
30abd221 | 477 | range_iter.boundary.clean(); |
bec110e4 | 478 | clearRequest(); |
62e76326 | 479 | |
528b2c61 | 480 | if (client_stream.tail) |
62e76326 | 481 | clientStreamAbort((clientStreamNode *)client_stream.tail->data, this); |
c8be6d7b | 482 | } |
483 | ||
484 | void | |
485 | httpRequestFree(void *data) | |
486 | { | |
59a1efb2 | 487 | ClientHttpRequest *http = (ClientHttpRequest *)data; |
c8be6d7b | 488 | assert(http != NULL); |
528b2c61 | 489 | delete http; |
7a2f978b | 490 | } |
491 | ||
492 | /* This is a handler normally called by comm_close() */ | |
ced8def3 | 493 | void ConnStateData::connStateClosed(const CommCloseCbParams &) |
7a2f978b | 494 | { |
6e1d409c | 495 | deleteThis("ConnStateData::connStateClosed"); |
a46d2c0e | 496 | } |
62e76326 | 497 | |
cc1e110a AJ |
498 | #if USE_AUTH |
499 | void | |
500 | ConnStateData::setAuth(const Auth::UserRequest::Pointer &aur, const char *by) | |
501 | { | |
502 | if (auth_ == NULL) { | |
503 | if (aur != NULL) { | |
504 | debugs(33, 2, "Adding connection-auth to " << clientConnection << " from " << by); | |
505 | auth_ = aur; | |
506 | } | |
507 | return; | |
508 | } | |
509 | ||
510 | // clobered with self-pointer | |
511 | // NP: something nasty is going on in Squid, but harmless. | |
512 | if (aur == auth_) { | |
513 | debugs(33, 2, "WARNING: Ignoring duplicate connection-auth for " << clientConnection << " from " << by); | |
514 | return; | |
515 | } | |
516 | ||
517 | /* | |
518 | * Connection-auth relies on a single set of credentials being preserved | |
519 | * for all requests on a connection once they have been setup. | |
520 | * There are several things which need to happen to preserve security | |
521 | * when connection-auth credentials change unexpectedly or are unset. | |
522 | * | |
523 | * 1) auth helper released from any active state | |
524 | * | |
525 | * They can only be reserved by a handshake process which this | |
526 | * connection can now never complete. | |
527 | * This prevents helpers hanging when their connections close. | |
528 | * | |
529 | * 2) pinning is expected to be removed and server conn closed | |
530 | * | |
531 | * The upstream link is authenticated with the same credentials. | |
532 | * Expecting the same level of consistency we should have received. | |
533 | * This prevents upstream being faced with multiple or missing | |
534 | * credentials after authentication. | |
535 | * NP: un-pin is left to the cleanup in ConnStateData::swanSong() | |
536 | * we just trigger that cleanup here via comm_reset_close() or | |
537 | * ConnStateData::stopReceiving() | |
538 | * | |
539 | * 3) the connection needs to close. | |
540 | * | |
541 | * This prevents attackers injecting requests into a connection, | |
542 | * or gateways wrongly multiplexing users into a single connection. | |
543 | * | |
544 | * When credentials are missing closure needs to follow an auth | |
545 | * challenge for best recovery by the client. | |
546 | * | |
547 | * When credentials change there is nothing we can do but abort as | |
548 | * fast as possible. Sending TCP RST instead of an HTTP response | |
549 | * is the best-case action. | |
550 | */ | |
551 | ||
552 | // clobbered with nul-pointer | |
553 | if (aur == NULL) { | |
554 | debugs(33, 2, "WARNING: Graceful closure on " << clientConnection << " due to connection-auth erase from " << by); | |
555 | auth_->releaseAuthServer(); | |
556 | auth_ = NULL; | |
557 | // XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here. | |
558 | // NP: the current situation seems to fix challenge loops in Safari without visible issues in others. | |
559 | // we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered. | |
560 | stopReceiving("connection-auth removed"); | |
561 | return; | |
562 | } | |
563 | ||
564 | // clobbered with alternative credentials | |
565 | if (aur != auth_) { | |
566 | debugs(33, 2, "ERROR: Closing " << clientConnection << " due to change of connection-auth from " << by); | |
567 | auth_->releaseAuthServer(); | |
568 | auth_ = NULL; | |
569 | // this is a fatal type of problem. | |
570 | // Close the connection immediately with TCP RST to abort all traffic flow | |
571 | comm_reset_close(clientConnection); | |
572 | return; | |
573 | } | |
574 | ||
575 | /* NOT REACHABLE */ | |
576 | } | |
577 | #endif | |
578 | ||
6e1d409c | 579 | // cleans up before destructor is called |
a2ac85d9 | 580 | void |
6e1d409c | 581 | ConnStateData::swanSong() |
a46d2c0e | 582 | { |
73c36fd9 | 583 | debugs(33, 2, HERE << clientConnection); |
da6dbcd1 EB |
584 | checkLogging(); |
585 | ||
f35961af | 586 | flags.readMore = false; |
f53969cc | 587 | clientdbEstablished(clientConnection->remote, -1); /* decrement */ |
43e45ea7 | 588 | pipeline.terminateAll(0); |
6e1d409c | 589 | |
801cfc26 | 590 | // XXX: Closing pinned conn is too harsh: The Client may want to continue! |
89b1d7a2 | 591 | unpinConnection(true); |
e3a4aecc | 592 | |
fcc444e3 | 593 | Server::swanSong(); // closes the client connection |
d67acb4e | 594 | |
cc1e110a AJ |
595 | #if USE_AUTH |
596 | // NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST | |
597 | setAuth(NULL, "ConnStateData::SwanSong cleanup"); | |
598 | #endif | |
599 | ||
6e1d409c | 600 | flags.swanSang = true; |
a2ac85d9 | 601 | } |
602 | ||
603 | bool | |
604 | ConnStateData::isOpen() const | |
605 | { | |
10b06767 | 606 | return cbdataReferenceValid(this) && // XXX: checking "this" in a method |
73c36fd9 AJ |
607 | Comm::IsConnOpen(clientConnection) && |
608 | !fd_table[clientConnection->fd].closing(); | |
a2ac85d9 | 609 | } |
610 | ||
611 | ConnStateData::~ConnStateData() | |
612 | { | |
73c36fd9 | 613 | debugs(33, 3, HERE << clientConnection); |
a2ac85d9 | 614 | |
615 | if (isOpen()) | |
e0236918 | 616 | debugs(33, DBG_IMPORTANT, "BUG: ConnStateData did not close " << clientConnection); |
6e1d409c AR |
617 | |
618 | if (!flags.swanSang) | |
e0236918 | 619 | debugs(33, DBG_IMPORTANT, "BUG: ConnStateData was not destroyed properly; " << clientConnection); |
62e76326 | 620 | |
279152e7 AJ |
621 | if (bodyPipe != NULL) |
622 | stopProducingFor(bodyPipe, false); | |
87f237a9 | 623 | |
fcc444e3 AJ |
624 | delete bodyParser; // TODO: pool |
625 | ||
cb4f4424 | 626 | #if USE_OPENSSL |
fd4624d7 | 627 | delete sslServerBump; |
8a7fe008 | 628 | #endif |
7a2f978b | 629 | } |
630 | ||
63be0a78 | 631 | /** |
450fe1cb | 632 | * clientSetKeepaliveFlag() sets request->flags.proxyKeepalive. |
c68e9c6b | 633 | * This is the client-side persistent connection flag. We need |
634 | * to set this relatively early in the request processing | |
635 | * to handle hacks for broken servers and clients. | |
636 | */ | |
92ae4c86 | 637 | void |
59a1efb2 | 638 | clientSetKeepaliveFlag(ClientHttpRequest * http) |
c68e9c6b | 639 | { |
190154cf | 640 | HttpRequest *request = http->request; |
f6329bc3 | 641 | |
7f06a3d8 AJ |
642 | debugs(33, 3, "http_ver = " << request->http_ver); |
643 | debugs(33, 3, "method = " << request->method); | |
62e76326 | 644 | |
4a1acc56 | 645 | // TODO: move to HttpRequest::hdrCacheInit, just like HttpReply. |
e857372a | 646 | request->flags.proxyKeepalive = request->persistent(); |
c68e9c6b | 647 | } |
648 | ||
3e42b356 | 649 | /// checks body length of non-chunked requests |
31be8b80 | 650 | static int |
190154cf | 651 | clientIsContentLengthValid(HttpRequest * r) |
31be8b80 | 652 | { |
3e42b356 AR |
653 | // No Content-Length means this request just has no body, but conflicting |
654 | // Content-Lengths mean a message framing error (RFC 7230 Section 3.3.3 #4). | |
655 | if (r->header.conflictingContentLength()) | |
656 | return 0; | |
657 | ||
914b89a2 | 658 | switch (r->method.id()) { |
62e76326 | 659 | |
c2a7cefd | 660 | case Http::METHOD_GET: |
62e76326 | 661 | |
c2a7cefd | 662 | case Http::METHOD_HEAD: |
62e76326 | 663 | /* We do not want to see a request entity on GET/HEAD requests */ |
664 | return (r->content_length <= 0 || Config.onoff.request_entities); | |
665 | ||
ffc128c4 | 666 | default: |
62e76326 | 667 | /* For other types of requests we don't care */ |
668 | return 1; | |
ffc128c4 | 669 | } |
62e76326 | 670 | |
ffc128c4 | 671 | /* NOT REACHED */ |
31be8b80 | 672 | } |
673 | ||
c8be6d7b | 674 | int |
47f6e231 | 675 | clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength) |
efd900cb | 676 | { |
c8be6d7b | 677 | if (Config.maxRequestBodySize && |
62e76326 | 678 | bodyLength > Config.maxRequestBodySize) |
f53969cc | 679 | return 1; /* too large */ |
62e76326 | 680 | |
efd900cb | 681 | return 0; |
682 | } | |
683 | ||
528b2c61 | 684 | bool |
685 | ClientHttpRequest::multipartRangeRequest() const | |
686 | { | |
687 | return request->multipartRangeRequest(); | |
688 | } | |
689 | ||
4ad60609 | 690 | void |
d6fdeb41 | 691 | clientPackTermBound(String boundary, MemBuf *mb) |
528b2c61 | 692 | { |
4391cd15 | 693 | mb->appendf("\r\n--" SQUIDSTRINGPH "--\r\n", SQUIDSTRINGPRINT(boundary)); |
d6fdeb41 | 694 | debugs(33, 6, "buf offset: " << mb->size); |
528b2c61 | 695 | } |
696 | ||
d6fdeb41 | 697 | void |
a0c227a9 | 698 | clientPackRangeHdr(const HttpReplyPointer &rep, const HttpHdrRangeSpec * spec, String boundary, MemBuf * mb) |
528b2c61 | 699 | { |
75faaa7a | 700 | HttpHeader hdr(hoReply); |
528b2c61 | 701 | assert(rep); |
702 | assert(spec); | |
703 | ||
704 | /* put boundary */ | |
d6fdeb41 | 705 | debugs(33, 5, "appending boundary: " << boundary); |
528b2c61 | 706 | /* rfc2046 requires to _prepend_ boundary with <crlf>! */ |
4391cd15 | 707 | mb->appendf("\r\n--" SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(boundary)); |
528b2c61 | 708 | |
709 | /* stuff the header with required entries and pack it */ | |
62e76326 | 710 | |
789217a2 FC |
711 | if (rep->header.has(Http::HdrType::CONTENT_TYPE)) |
712 | hdr.putStr(Http::HdrType::CONTENT_TYPE, rep->header.getStr(Http::HdrType::CONTENT_TYPE)); | |
62e76326 | 713 | |
528b2c61 | 714 | httpHeaderAddContRange(&hdr, *spec, rep->content_length); |
62e76326 | 715 | |
10201568 | 716 | hdr.packInto(mb); |
519e0948 | 717 | hdr.clean(); |
528b2c61 | 718 | |
719 | /* append <crlf> (we packed a header, not a reply) */ | |
10201568 | 720 | mb->append("\r\n", 2); |
528b2c61 | 721 | } |
722 | ||
63be0a78 | 723 | /** returns expected content length for multi-range replies |
528b2c61 | 724 | * note: assumes that httpHdrRangeCanonize has already been called |
725 | * warning: assumes that HTTP headers for individual ranges at the | |
726 | * time of the actuall assembly will be exactly the same as | |
727 | * the headers when clientMRangeCLen() is called */ | |
728 | int | |
729 | ClientHttpRequest::mRangeCLen() | |
c8be6d7b | 730 | { |
47f6e231 | 731 | int64_t clen = 0; |
c8be6d7b | 732 | MemBuf mb; |
528b2c61 | 733 | |
86a2f789 | 734 | assert(memObject()); |
528b2c61 | 735 | |
2fe7eff9 | 736 | mb.init(); |
528b2c61 | 737 | HttpHdrRange::iterator pos = request->range->begin(); |
62e76326 | 738 | |
528b2c61 | 739 | while (pos != request->range->end()) { |
62e76326 | 740 | /* account for headers for this range */ |
2fe7eff9 | 741 | mb.reset(); |
86a2f789 | 742 | clientPackRangeHdr(memObject()->getReply(), |
62e76326 | 743 | *pos, range_iter.boundary, &mb); |
744 | clen += mb.size; | |
528b2c61 | 745 | |
62e76326 | 746 | /* account for range content */ |
747 | clen += (*pos)->length; | |
528b2c61 | 748 | |
4a7a3d56 | 749 | debugs(33, 6, "clientMRangeCLen: (clen += " << mb.size << " + " << (*pos)->length << ") == " << clen); |
62e76326 | 750 | ++pos; |
528b2c61 | 751 | } |
62e76326 | 752 | |
528b2c61 | 753 | /* account for the terminating boundary */ |
2fe7eff9 | 754 | mb.reset(); |
62e76326 | 755 | |
528b2c61 | 756 | clientPackTermBound(range_iter.boundary, &mb); |
62e76326 | 757 | |
528b2c61 | 758 | clen += mb.size; |
759 | ||
2fe7eff9 | 760 | mb.clean(); |
62e76326 | 761 | |
528b2c61 | 762 | return clen; |
763 | } | |
764 | ||
63be0a78 | 765 | /** |
766 | * generates a "unique" boundary string for multipart responses | |
528b2c61 | 767 | * the caller is responsible for cleaning the string */ |
30abd221 | 768 | String |
528b2c61 | 769 | ClientHttpRequest::rangeBoundaryStr() const |
770 | { | |
528b2c61 | 771 | const char *key; |
7dbca7a4 AJ |
772 | String b(APP_FULLNAME); |
773 | b.append(":",1); | |
86a2f789 | 774 | key = storeEntry()->getMD5Text(); |
528b2c61 | 775 | b.append(key, strlen(key)); |
776 | return b; | |
777 | } | |
778 | ||
63be0a78 | 779 | /** |
7dc5f514 | 780 | * Write a chunk of data to a client socket. If the reply is present, |
781 | * send the reply headers down the wire too, and clean them up when | |
782 | * finished. | |
9e008dda | 783 | * Pre-condition: |
edce4d98 | 784 | * The request is one backed by a connection, not an internal request. |
785 | * data context is not NULL | |
786 | * There are no more entries in the stream chain. | |
2246b732 | 787 | */ |
92ae4c86 | 788 | void |
59a1efb2 | 789 | clientSocketRecipient(clientStreamNode * node, ClientHttpRequest * http, |
2324cda2 | 790 | HttpReply * rep, StoreIOBuffer receivedData) |
edce4d98 | 791 | { |
61beade2 | 792 | // do not try to deliver if client already ABORTED |
51571330 AJ |
793 | if (!http->getConn() || !cbdataReferenceValid(http->getConn()) || !Comm::IsConnOpen(http->getConn()->clientConnection)) |
794 | return; | |
795 | ||
edce4d98 | 796 | /* Test preconditions */ |
797 | assert(node != NULL); | |
559da936 | 798 | PROF_start(clientSocketRecipient); |
62e76326 | 799 | /* TODO: handle this rather than asserting |
9e008dda AJ |
800 | * - it should only ever happen if we cause an abort and |
801 | * the callback chain loops back to here, so we can simply return. | |
802 | * However, that itself shouldn't happen, so it stays as an assert for now. | |
edce4d98 | 803 | */ |
804 | assert(cbdataReferenceValid(node)); | |
edce4d98 | 805 | assert(node->node.next == NULL); |
d3dddfb5 | 806 | Http::StreamPointer context = dynamic_cast<Http::Stream *>(node->data.getRaw()); |
94a396a3 | 807 | assert(context != NULL); |
5c336a3b | 808 | |
528b2c61 | 809 | /* TODO: check offset is what we asked for */ |
62e76326 | 810 | |
efd5e784 AJ |
811 | // TODO: enforces HTTP/1 MUST on pipeline order, but is irrelevant to HTTP/2 |
812 | if (context != http->getConn()->pipeline.front()) | |
2324cda2 | 813 | context->deferRecipientForLater(node, rep, receivedData); |
24e1fd72 CT |
814 | else if (http->getConn()->cbControlMsgSent) // 1xx to the user is pending |
815 | context->deferRecipientForLater(node, rep, receivedData); | |
92ae4c86 AR |
816 | else |
817 | http->getConn()->handleReply(rep, receivedData); | |
fc68f6b1 | 818 | |
559da936 | 819 | PROF_stop(clientSocketRecipient); |
edce4d98 | 820 | } |
821 | ||
63be0a78 | 822 | /** |
823 | * Called when a downstream node is no longer interested in | |
edce4d98 | 824 | * our data. As we are a terminal node, this means on aborts |
825 | * only | |
826 | */ | |
827 | void | |
59a1efb2 | 828 | clientSocketDetach(clientStreamNode * node, ClientHttpRequest * http) |
edce4d98 | 829 | { |
edce4d98 | 830 | /* Test preconditions */ |
831 | assert(node != NULL); | |
62e76326 | 832 | /* TODO: handle this rather than asserting |
9e008dda AJ |
833 | * - it should only ever happen if we cause an abort and |
834 | * the callback chain loops back to here, so we can simply return. | |
edce4d98 | 835 | * However, that itself shouldn't happen, so it stays as an assert for now. |
836 | */ | |
837 | assert(cbdataReferenceValid(node)); | |
838 | /* Set null by ContextFree */ | |
edce4d98 | 839 | assert(node->node.next == NULL); |
0655fa4d | 840 | /* this is the assert discussed above */ |
d3dddfb5 | 841 | assert(NULL == dynamic_cast<Http::Stream *>(node->data.getRaw())); |
edce4d98 | 842 | /* We are only called when the client socket shutsdown. |
843 | * Tell the prev pipeline member we're finished | |
844 | */ | |
845 | clientStreamDetach(node, http); | |
7a2f978b | 846 | } |
847 | ||
c8be6d7b | 848 | void |
a46d2c0e | 849 | ConnStateData::readNextRequest() |
c8be6d7b | 850 | { |
73c36fd9 | 851 | debugs(33, 5, HERE << clientConnection << " reading next req"); |
bf8fe701 | 852 | |
97b32442 | 853 | fd_note(clientConnection->fd, "Idle client: Waiting for next request"); |
63be0a78 | 854 | /** |
5ddf7edc | 855 | * Set the timeout BEFORE calling readSomeData(). |
c8be6d7b | 856 | */ |
1cf238db | 857 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 858 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, |
4cb2536f | 859 | TimeoutDialer, this, ConnStateData::requestTimeout); |
c5c06f02 | 860 | commSetConnTimeout(clientConnection, clientConnection->timeLeft(idleTimeout()), timeoutCall); |
1cf238db | 861 | |
a46d2c0e | 862 | readSomeData(); |
63be0a78 | 863 | /** Please don't do anything with the FD past here! */ |
c8be6d7b | 864 | } |
865 | ||
09d3938c | 866 | static void |
d3dddfb5 | 867 | ClientSocketContextPushDeferredIfNeeded(Http::StreamPointer deferredRequest, ConnStateData * conn) |
c8be6d7b | 868 | { |
73c36fd9 | 869 | debugs(33, 2, HERE << conn->clientConnection << " Sending next"); |
bf8fe701 | 870 | |
63be0a78 | 871 | /** If the client stream is waiting on a socket write to occur, then */ |
62e76326 | 872 | |
c8be6d7b | 873 | if (deferredRequest->flags.deferred) { |
63be0a78 | 874 | /** NO data is allowed to have been sent. */ |
62e76326 | 875 | assert(deferredRequest->http->out.size == 0); |
63be0a78 | 876 | /** defer now. */ |
62e76326 | 877 | clientSocketRecipient(deferredRequest->deferredparams.node, |
878 | deferredRequest->http, | |
879 | deferredRequest->deferredparams.rep, | |
880 | deferredRequest->deferredparams.queuedBuffer); | |
c8be6d7b | 881 | } |
62e76326 | 882 | |
63be0a78 | 883 | /** otherwise, the request is still active in a callbacksomewhere, |
c8be6d7b | 884 | * and we are done |
f4f278b5 | 885 | */ |
f4f278b5 | 886 | } |
887 | ||
0655fa4d | 888 | void |
f4a53cf7 | 889 | ConnStateData::kick() |
1a92a1e2 | 890 | { |
4a4fbcef AJ |
891 | if (!Comm::IsConnOpen(clientConnection)) { |
892 | debugs(33, 2, clientConnection << " Connection was closed"); | |
893 | return; | |
894 | } | |
0655fa4d | 895 | |
f4a53cf7 AJ |
896 | if (pinning.pinned && !Comm::IsConnOpen(pinning.serverConnection)) { |
897 | debugs(33, 2, clientConnection << " Connection was pinned but server side gone. Terminating client connection"); | |
898 | clientConnection->close(); | |
d67acb4e AJ |
899 | return; |
900 | } | |
901 | ||
cf6eb29e CT |
902 | /** \par |
903 | * We are done with the response, and we are either still receiving request | |
904 | * body (early response!) or have already stopped receiving anything. | |
905 | * | |
906 | * If we are still receiving, then clientParseRequest() below will fail. | |
907 | * (XXX: but then we will call readNextRequest() which may succeed and | |
908 | * execute a smuggled request as we are not done with the current request). | |
909 | * | |
910 | * If we stopped because we got everything, then try the next request. | |
911 | * | |
912 | * If we stopped receiving because of an error, then close now to avoid | |
913 | * getting stuck and to prevent accidental request smuggling. | |
914 | */ | |
915 | ||
f4a53cf7 AJ |
916 | if (const char *reason = stoppedReceiving()) { |
917 | debugs(33, 3, "closing for earlier request error: " << reason); | |
918 | clientConnection->close(); | |
cf6eb29e CT |
919 | return; |
920 | } | |
921 | ||
63be0a78 | 922 | /** \par |
f900210a | 923 | * Attempt to parse a request from the request buffer. |
924 | * If we've been fed a pipelined request it may already | |
925 | * be in our read buffer. | |
926 | * | |
63be0a78 | 927 | \par |
f900210a | 928 | * This needs to fall through - if we're unlucky and parse the _last_ request |
929 | * from our read buffer we may never re-register for another client read. | |
930 | */ | |
931 | ||
f4a53cf7 AJ |
932 | if (clientParseRequests()) { |
933 | debugs(33, 3, clientConnection << ": parsed next request from buffer"); | |
f900210a | 934 | } |
935 | ||
63be0a78 | 936 | /** \par |
f900210a | 937 | * Either we need to kick-start another read or, if we have |
938 | * a half-closed connection, kill it after the last request. | |
939 | * This saves waiting for half-closed connections to finished being | |
940 | * half-closed _AND_ then, sometimes, spending "Timeout" time in | |
941 | * the keepalive "Waiting for next request" state. | |
942 | */ | |
f4a53cf7 | 943 | if (commIsHalfClosed(clientConnection->fd) && pipeline.empty()) { |
e500cc89 | 944 | debugs(33, 3, "half-closed client with no pending requests, closing"); |
f4a53cf7 | 945 | clientConnection->close(); |
f900210a | 946 | return; |
947 | } | |
948 | ||
63be0a78 | 949 | /** \par |
f900210a | 950 | * At this point we either have a parsed request (which we've |
951 | * kicked off the processing for) or not. If we have a deferred | |
952 | * request (parsed but deferred for pipeling processing reasons) | |
953 | * then look at processing it. If not, simply kickstart | |
954 | * another read. | |
955 | */ | |
d3dddfb5 | 956 | Http::StreamPointer deferredRequest = pipeline.front(); |
efd5e784 | 957 | if (deferredRequest != nullptr) { |
f4a53cf7 AJ |
958 | debugs(33, 3, clientConnection << ": calling PushDeferredIfNeeded"); |
959 | ClientSocketContextPushDeferredIfNeeded(deferredRequest, this); | |
960 | } else if (flags.readMore) { | |
961 | debugs(33, 3, clientConnection << ": calling readNextRequest()"); | |
962 | readNextRequest(); | |
f35961af AR |
963 | } else { |
964 | // XXX: Can this happen? CONNECT tunnels have deferredRequest set. | |
f4a53cf7 | 965 | debugs(33, DBG_IMPORTANT, MYNAME << "abandoning " << clientConnection); |
f900210a | 966 | } |
1a92a1e2 | 967 | } |
968 | ||
cf6eb29e CT |
969 | void |
970 | ConnStateData::stopSending(const char *error) | |
971 | { | |
972 | debugs(33, 4, HERE << "sending error (" << clientConnection << "): " << error << | |
973 | "; old receiving error: " << | |
974 | (stoppedReceiving() ? stoppedReceiving_ : "none")); | |
fc68f6b1 | 975 | |
cf6eb29e CT |
976 | if (const char *oldError = stoppedSending()) { |
977 | debugs(33, 3, HERE << "already stopped sending: " << oldError); | |
978 | return; // nothing has changed as far as this connection is concerned | |
979 | } | |
980 | stoppedSending_ = error; | |
fc68f6b1 | 981 | |
cf6eb29e CT |
982 | if (!stoppedReceiving()) { |
983 | if (const int64_t expecting = mayNeedToReadMoreBody()) { | |
984 | debugs(33, 5, HERE << "must still read " << expecting << | |
fcc444e3 | 985 | " request body bytes with " << inBuf.length() << " unused"); |
cf6eb29e | 986 | return; // wait for the request receiver to finish reading |
3b299123 | 987 | } |
55e44db9 | 988 | } |
989 | ||
cf6eb29e | 990 | clientConnection->close(); |
55e44db9 | 991 | } |
992 | ||
0655fa4d | 993 | void |
21cd3227 AJ |
994 | ConnStateData::afterClientWrite(size_t size) |
995 | { | |
996 | if (pipeline.empty()) | |
997 | return; | |
998 | ||
d6fdeb41 AJ |
999 | auto ctx = pipeline.front(); |
1000 | if (size) { | |
1001 | statCounter.client_http.kbytes_out += size; | |
1002 | if (ctx->http->logType.isTcpHit()) | |
1003 | statCounter.client_http.hit_kbytes_out += size; | |
7a2f978b | 1004 | } |
d6fdeb41 | 1005 | ctx->writeComplete(size); |
7a2f978b | 1006 | } |
1007 | ||
d3dddfb5 | 1008 | Http::Stream * |
eacfca83 | 1009 | ConnStateData::abortRequestParsing(const char *const uri) |
038eb4ed | 1010 | { |
eacfca83 | 1011 | ClientHttpRequest *http = new ClientHttpRequest(this); |
fcc444e3 | 1012 | http->req_sz = inBuf.length(); |
bec110e4 | 1013 | http->setErrorUri(uri); |
d3dddfb5 | 1014 | auto *context = new Http::Stream(clientConnection, http); |
942b1c39 AJ |
1015 | StoreIOBuffer tempBuffer; |
1016 | tempBuffer.data = context->reqbuf; | |
1017 | tempBuffer.length = HTTP_REQBUF_SZ; | |
edce4d98 | 1018 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, |
0655fa4d | 1019 | clientReplyStatus, new clientReplyContext(http), clientSocketRecipient, |
942b1c39 | 1020 | clientSocketDetach, context, tempBuffer); |
edce4d98 | 1021 | return context; |
038eb4ed | 1022 | } |
1023 | ||
d442618d AJ |
1024 | void |
1025 | ConnStateData::startShutdown() | |
1026 | { | |
1027 | // RegisteredRunner API callback - Squid has been shut down | |
1028 | ||
1029 | // if connection is idle terminate it now, | |
1030 | // otherwise wait for grace period to end | |
e500cc89 | 1031 | if (pipeline.empty()) |
d442618d AJ |
1032 | endingShutdown(); |
1033 | } | |
1034 | ||
1035 | void | |
1036 | ConnStateData::endingShutdown() | |
1037 | { | |
1038 | // RegisteredRunner API callback - Squid shutdown grace period is over | |
1039 | ||
1040 | // force the client connection to close immediately | |
1041 | // swanSong() in the close handler will cleanup. | |
1042 | if (Comm::IsConnOpen(clientConnection)) | |
1043 | clientConnection->close(); | |
d442618d AJ |
1044 | } |
1045 | ||
c8be6d7b | 1046 | char * |
1047 | skipLeadingSpace(char *aString) | |
1048 | { | |
1049 | char *result = aString; | |
62e76326 | 1050 | |
c8be6d7b | 1051 | while (xisspace(*aString)) |
62e76326 | 1052 | ++aString; |
1053 | ||
c8be6d7b | 1054 | return result; |
1055 | } | |
1056 | ||
63be0a78 | 1057 | /** |
d4a04ed5 | 1058 | * 'end' defaults to NULL for backwards compatibility |
1059 | * remove default value if we ever get rid of NULL-terminated | |
1060 | * request buffers. | |
1061 | */ | |
1062 | const char * | |
1063 | findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end) | |
c8be6d7b | 1064 | { |
d4a04ed5 | 1065 | if (NULL == end) { |
1066 | end = uriAndHTTPVersion + strcspn(uriAndHTTPVersion, "\r\n"); | |
1067 | assert(end); | |
1068 | } | |
62e76326 | 1069 | |
5e263176 | 1070 | for (; end > uriAndHTTPVersion; --end) { |
d4a04ed5 | 1071 | if (*end == '\n' || *end == '\r') |
62e76326 | 1072 | continue; |
1073 | ||
d4a04ed5 | 1074 | if (xisspace(*end)) { |
1075 | if (strncasecmp(end + 1, "HTTP/", 5) == 0) | |
1076 | return end + 1; | |
62e76326 | 1077 | else |
1078 | break; | |
1079 | } | |
c8be6d7b | 1080 | } |
62e76326 | 1081 | |
3f38a55e | 1082 | return NULL; |
c8be6d7b | 1083 | } |
1084 | ||
82b04b16 CT |
1085 | static char * |
1086 | prepareAcceleratedURL(ConnStateData * conn, const Http1::RequestParserPointer &hp) | |
62e76326 | 1087 | { |
3f38a55e | 1088 | int vhost = conn->port->vhost; |
1089 | int vport = conn->port->vport; | |
9ff1b8ca | 1090 | static char ipbuf[MAX_IPSTRLEN]; |
c8be6d7b | 1091 | |
3f38a55e | 1092 | /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */ |
c8be6d7b | 1093 | |
5f3cc9a2 | 1094 | static const SBuf cache_object("cache_object://"); |
9bafa70d | 1095 | if (hp->requestUri().startsWith(cache_object)) |
82b04b16 | 1096 | return nullptr; /* already in good shape */ |
34399323 | 1097 | |
b1cef121 | 1098 | // XXX: re-use proper URL parser for this |
9bafa70d | 1099 | SBuf url = hp->requestUri(); // use full provided URI if we abort |
b1cef121 AJ |
1100 | do { // use a loop so we can break out of it |
1101 | ::Parser::Tokenizer tok(url); | |
f9688132 | 1102 | if (tok.skip('/')) // origin-form URL already. |
b1cef121 AJ |
1103 | break; |
1104 | ||
62e76326 | 1105 | if (conn->port->vhost) |
82b04b16 | 1106 | return nullptr; /* already in good shape */ |
62e76326 | 1107 | |
b1cef121 | 1108 | // skip the URI scheme |
9bafa70d | 1109 | static const CharacterSet uriScheme = CharacterSet("URI-scheme","+-.") + CharacterSet::ALPHA + CharacterSet::DIGIT; |
b1cef121 | 1110 | static const SBuf uriSchemeEnd("://"); |
9bafa70d | 1111 | if (!tok.skipAll(uriScheme) || !tok.skip(uriSchemeEnd)) |
b1cef121 | 1112 | break; |
62e76326 | 1113 | |
b1cef121 AJ |
1114 | // skip the authority segment |
1115 | // RFC 3986 complex nested ABNF for "authority" boils down to this: | |
1116 | static const CharacterSet authority = CharacterSet("authority","-._~%:@[]!$&'()*+,;=") + | |
f53969cc | 1117 | CharacterSet::HEXDIG + CharacterSet::ALPHA + CharacterSet::DIGIT; |
9bafa70d | 1118 | if (!tok.skipAll(authority)) |
b1cef121 | 1119 | break; |
62e76326 | 1120 | |
63ccea28 | 1121 | static const SBuf slashUri("/"); |
83e3a594 | 1122 | const SBuf t = tok.remaining(); |
b1cef121 | 1123 | if (t.isEmpty()) |
63ccea28 | 1124 | url = slashUri; |
b1cef121 AJ |
1125 | else if (t[0]=='/') // looks like path |
1126 | url = t; | |
1127 | else if (t[0]=='?' || t[0]=='#') { // looks like query or fragment. fix '/' | |
63ccea28 | 1128 | url = slashUri; |
b1cef121 AJ |
1129 | url.append(t); |
1130 | } // else do nothing. invalid path | |
62e76326 | 1131 | |
b1cef121 | 1132 | } while(false); |
62e76326 | 1133 | |
b1cef121 AJ |
1134 | #if SHOULD_REJECT_UNKNOWN_URLS |
1135 | // reject URI which are not well-formed even after the processing above | |
f9688132 | 1136 | if (url.isEmpty() || url[0] != '/') { |
f1d5359e | 1137 | hp->parseStatusCode = Http::scBadRequest; |
943cdf6d | 1138 | return conn->abortRequestParsing("error:invalid-request"); |
3f38a55e | 1139 | } |
b1cef121 | 1140 | #endif |
3f38a55e | 1141 | |
5463e4b9 | 1142 | if (vport < 0) |
82b04b16 | 1143 | vport = conn->clientConnection->local.port(); |
5463e4b9 | 1144 | |
9ff1b8ca | 1145 | char *host = NULL; |
82b04b16 | 1146 | if (vhost && (host = hp->getHeaderField("Host"))) { |
5463e4b9 AJ |
1147 | debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host << " + vport=" << vport); |
1148 | char thost[256]; | |
1149 | if (vport > 0) { | |
1150 | thost[0] = '\0'; | |
1151 | char *t = NULL; | |
82b04b16 | 1152 | if (host[strlen(host) - 1] != ']' && (t = strrchr(host,':')) != NULL) { |
5463e4b9 AJ |
1153 | strncpy(thost, host, (t-host)); |
1154 | snprintf(thost+(t-host), sizeof(thost)-(t-host), ":%d", vport); | |
1155 | host = thost; | |
1156 | } else if (!t) { | |
1157 | snprintf(thost, sizeof(thost), "%s:%d",host, vport); | |
1158 | host = thost; | |
1159 | } | |
1160 | } // else nothing to alter port-wise. | |
d31d59d8 | 1161 | const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image(); |
82b04b16 CT |
1162 | const int url_sz = scheme.length() + strlen(host) + url.length() + 32; |
1163 | char *uri = (char *)xcalloc(url_sz, 1); | |
1164 | snprintf(uri, url_sz, SQUIDSBUFPH "://%s" SQUIDSBUFPH, SQUIDSBUFPRINT(scheme), host, SQUIDSBUFPRINT(url)); | |
1165 | debugs(33, 5, "ACCEL VHOST REWRITE: " << uri); | |
1166 | return uri; | |
5463e4b9 AJ |
1167 | } else if (conn->port->defaultsite /* && !vhost */) { |
1168 | debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn->port->defaultsite << " + vport=" << vport); | |
5463e4b9 AJ |
1169 | char vportStr[32]; |
1170 | vportStr[0] = '\0'; | |
1171 | if (vport > 0) { | |
1172 | snprintf(vportStr, sizeof(vportStr),":%d",vport); | |
1173 | } | |
d31d59d8 | 1174 | const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image(); |
82b04b16 CT |
1175 | const int url_sz = scheme.length() + strlen(conn->port->defaultsite) + sizeof(vportStr) + url.length() + 32; |
1176 | char *uri = (char *)xcalloc(url_sz, 1); | |
1177 | snprintf(uri, url_sz, SQUIDSBUFPH "://%s%s" SQUIDSBUFPH, | |
d31d59d8 | 1178 | SQUIDSBUFPRINT(scheme), conn->port->defaultsite, vportStr, SQUIDSBUFPRINT(url)); |
82b04b16 CT |
1179 | debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: " << uri); |
1180 | return uri; | |
5463e4b9 | 1181 | } else if (vport > 0 /* && (!vhost || no Host:) */) { |
3cc0f4e7 | 1182 | debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport); |
5463e4b9 | 1183 | /* Put the local socket IP address as the hostname, with whatever vport we found */ |
82b04b16 | 1184 | conn->clientConnection->local.toHostStr(ipbuf,MAX_IPSTRLEN); |
d31d59d8 | 1185 | const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image(); |
82b04b16 CT |
1186 | const int url_sz = scheme.length() + sizeof(ipbuf) + url.length() + 32; |
1187 | char *uri = (char *)xcalloc(url_sz, 1); | |
1188 | snprintf(uri, url_sz, SQUIDSBUFPH "://%s:%d" SQUIDSBUFPH, | |
d31d59d8 | 1189 | SQUIDSBUFPRINT(scheme), ipbuf, vport, SQUIDSBUFPRINT(url)); |
82b04b16 CT |
1190 | debugs(33, 5, "ACCEL VPORT REWRITE: " << uri); |
1191 | return uri; | |
3f38a55e | 1192 | } |
82b04b16 CT |
1193 | |
1194 | return nullptr; | |
3f38a55e | 1195 | } |
1196 | ||
82b04b16 CT |
1197 | static char * |
1198 | buildUrlFromHost(ConnStateData * conn, const Http1::RequestParserPointer &hp) | |
62e76326 | 1199 | { |
82b04b16 | 1200 | char *uri = nullptr; |
3f38a55e | 1201 | /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */ |
9bafa70d | 1202 | if (const char *host = hp->getHeaderField("Host")) { |
d31d59d8 | 1203 | const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image(); |
82b04b16 CT |
1204 | const int url_sz = scheme.length() + strlen(host) + hp->requestUri().length() + 32; |
1205 | uri = (char *)xcalloc(url_sz, 1); | |
1206 | snprintf(uri, url_sz, SQUIDSBUFPH "://%s" SQUIDSBUFPH, | |
1207 | SQUIDSBUFPRINT(scheme), | |
1208 | host, | |
1209 | SQUIDSBUFPRINT(hp->requestUri())); | |
1210 | } | |
1211 | return uri; | |
1212 | } | |
1213 | ||
1214 | char * | |
1215 | ConnStateData::prepareTlsSwitchingURL(const Http1::RequestParserPointer &hp) | |
1216 | { | |
1217 | Must(switchedToHttps()); | |
1218 | ||
1219 | if (!hp->requestUri().isEmpty() && hp->requestUri()[0] != '/') | |
1220 | return nullptr; /* already in good shape */ | |
1221 | ||
1222 | char *uri = buildUrlFromHost(this, hp); | |
1223 | #if USE_OPENSSL | |
1224 | if (!uri) { | |
1225 | Must(tlsConnectPort); | |
1226 | Must(sslConnectHostOrIp.size()); | |
1227 | SBuf useHost; | |
1228 | if (!tlsClientSni().isEmpty()) | |
1229 | useHost = tlsClientSni(); | |
1230 | else | |
1231 | useHost.assign(sslConnectHostOrIp.rawBuf(), sslConnectHostOrIp.size()); | |
1232 | ||
1233 | const SBuf &scheme = AnyP::UriScheme(transferProtocol.protocol).image(); | |
1234 | const int url_sz = scheme.length() + useHost.length() + hp->requestUri().length() + 32; | |
1235 | uri = (char *)xcalloc(url_sz, 1); | |
1236 | snprintf(uri, url_sz, SQUIDSBUFPH "://" SQUIDSBUFPH ":%d" SQUIDSBUFPH, | |
1237 | SQUIDSBUFPRINT(scheme), | |
1238 | SQUIDSBUFPRINT(useHost), | |
1239 | tlsConnectPort, | |
1240 | SQUIDSBUFPRINT(hp->requestUri())); | |
1241 | } | |
1242 | #endif | |
1243 | if (uri) | |
1244 | debugs(33, 5, "TLS switching host rewrite: " << uri); | |
1245 | return uri; | |
1246 | } | |
1247 | ||
1248 | static char * | |
1249 | prepareTransparentURL(ConnStateData * conn, const Http1::RequestParserPointer &hp) | |
1250 | { | |
1251 | // TODO Must() on URI !empty when the parser supports throw. For now avoid assert(). | |
1252 | if (!hp->requestUri().isEmpty() && hp->requestUri()[0] != '/') | |
1253 | return nullptr; /* already in good shape */ | |
1254 | ||
1255 | char *uri = buildUrlFromHost(conn, hp); | |
1256 | if (!uri){ | |
62e76326 | 1257 | /* Put the local socket IP address as the hostname. */ |
f9688132 | 1258 | static char ipbuf[MAX_IPSTRLEN]; |
82b04b16 CT |
1259 | conn->clientConnection->local.toHostStr(ipbuf,MAX_IPSTRLEN); |
1260 | const SBuf &scheme = AnyP::UriScheme(conn->transferProtocol.protocol).image(); | |
1261 | const int url_sz = sizeof(ipbuf) + hp->requestUri().length() + 32; | |
1262 | uri = (char *)xcalloc(url_sz, 1); | |
1263 | snprintf(uri, url_sz, SQUIDSBUFPH "://%s:%d" SQUIDSBUFPH, | |
d31d59d8 | 1264 | SQUIDSBUFPRINT(scheme), |
82b04b16 | 1265 | ipbuf, conn->clientConnection->local.port(), SQUIDSBUFPRINT(hp->requestUri())); |
c8be6d7b | 1266 | } |
82b04b16 CT |
1267 | |
1268 | if (uri) | |
1269 | debugs(33, 5, "TRANSPARENT REWRITE: " << uri); | |
1270 | return uri; | |
c8be6d7b | 1271 | } |
1272 | ||
7830d88a | 1273 | /** Parse an HTTP request |
9e008dda | 1274 | * |
7830d88a FC |
1275 | * \note Sets result->flags.parsed_ok to 0 if failed to parse the request, |
1276 | * to 1 if the request was correctly parsed. | |
1277 | * \param[in] csd a ConnStateData. The caller must make sure it is not null | |
1b51ee7b | 1278 | * \param[in] hp an Http1::RequestParser |
7830d88a FC |
1279 | * \param[out] mehtod_p will be set as a side-effect of the parsing. |
1280 | * Pointed-to value will be set to Http::METHOD_NONE in case of | |
1281 | * parsing failure | |
1282 | * \param[out] http_ver will be set as a side-effect of the parsing | |
1283 | * \return NULL on incomplete requests, | |
d3dddfb5 | 1284 | * a Http::Stream on success or failure. |
7a2f978b | 1285 | */ |
d3dddfb5 | 1286 | Http::Stream * |
9bafa70d | 1287 | parseHttpRequest(ConnStateData *csd, const Http1::RequestParserPointer &hp) |
7a2f978b | 1288 | { |
87abd755 AJ |
1289 | /* Attempt to parse the first line; this will define where the method, url, version and header begin */ |
1290 | { | |
fcc444e3 | 1291 | const bool parsedOk = hp->parse(csd->inBuf); |
fc68f6b1 | 1292 | |
36a9c964 | 1293 | // sync the buffers after parsing. |
fcc444e3 | 1294 | csd->inBuf = hp->remaining(); |
7a4fa6a0 | 1295 | |
9bafa70d | 1296 | if (hp->needsMoreData()) { |
87abd755 AJ |
1297 | debugs(33, 5, "Incomplete request, waiting for end of request line"); |
1298 | return NULL; | |
1299 | } | |
fc68f6b1 | 1300 | |
6b2b6cfe CT |
1301 | if (csd->mayTunnelUnsupportedProto()) { |
1302 | csd->preservedClientData = hp->parsed(); | |
1303 | csd->preservedClientData.append(csd->inBuf); | |
1304 | } | |
1305 | ||
016a316b | 1306 | if (!parsedOk) { |
fc10bc7d AR |
1307 | const bool tooBig = |
1308 | hp->parseStatusCode == Http::scRequestHeaderFieldsTooLarge || | |
1309 | hp->parseStatusCode == Http::scUriTooLong; | |
1310 | auto result = csd->abortRequestParsing( | |
1311 | tooBig ? "error:request-too-large" : "error:invalid-request"); | |
1312 | // assume that remaining leftovers belong to this bad request | |
e6a4c1b2 AJ |
1313 | if (!csd->inBuf.isEmpty()) |
1314 | csd->consumeInput(csd->inBuf.length()); | |
fc10bc7d | 1315 | return result; |
016a316b | 1316 | } |
84cc2635 | 1317 | } |
fc68f6b1 | 1318 | |
6d0613b2 AJ |
1319 | /* We know the whole request is in parser now */ |
1320 | debugs(11, 2, "HTTP Client " << csd->clientConnection); | |
1321 | debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << | |
9bafa70d AJ |
1322 | hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol() << "\n" << |
1323 | hp->mimeHeader() << | |
6d0613b2 | 1324 | "\n----------"); |
fc68f6b1 | 1325 | |
adf29627 | 1326 | /* deny CONNECT via accelerated ports */ |
9bafa70d | 1327 | if (hp->method() == Http::METHOD_CONNECT && csd->port != NULL && csd->port->flags.accelSurrogate) { |
4599cded | 1328 | debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->transferProtocol << " Accelerator port " << csd->port->s.port()); |
9bafa70d | 1329 | debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol()); |
f1d5359e | 1330 | hp->parseStatusCode = Http::scMethodNotAllowed; |
eacfca83 | 1331 | return csd->abortRequestParsing("error:method-not-allowed"); |
adf29627 AJ |
1332 | } |
1333 | ||
c27e1e37 | 1334 | /* RFC 7540 section 11.6 registers the method PRI as HTTP/2 specific |
5de5c2d0 AJ |
1335 | * Deny "PRI" method if used in HTTP/1.x or 0.9 versions. |
1336 | * If seen it signals a broken client or proxy has corrupted the traffic. | |
1337 | */ | |
1338 | if (hp->method() == Http::METHOD_PRI && hp->messageProtocol() < Http::ProtocolVersion(2,0)) { | |
1339 | debugs(33, DBG_IMPORTANT, "WARNING: PRI method received on " << csd->transferProtocol << " port " << csd->port->s.port()); | |
1340 | debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol()); | |
093c6381 | 1341 | hp->parseStatusCode = Http::scMethodNotAllowed; |
5de5c2d0 AJ |
1342 | return csd->abortRequestParsing("error:method-not-allowed"); |
1343 | } | |
1344 | ||
9bafa70d AJ |
1345 | if (hp->method() == Http::METHOD_NONE) { |
1346 | debugs(33, DBG_IMPORTANT, "WARNING: Unsupported method: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol()); | |
f1d5359e | 1347 | hp->parseStatusCode = Http::scMethodNotAllowed; |
eacfca83 | 1348 | return csd->abortRequestParsing("error:unsupported-request-method"); |
3f38a55e | 1349 | } |
7a2f978b | 1350 | |
6d0613b2 AJ |
1351 | // Process headers after request line |
1352 | debugs(33, 3, "complete request received. " << | |
9bafa70d AJ |
1353 | "prefix_sz = " << hp->messageHeaderSize() << |
1354 | ", request-line-size=" << hp->firstLineSize() << | |
1355 | ", mime-header-size=" << hp->headerBlockSize() << | |
1356 | ", mime header block:\n" << hp->mimeHeader() << "\n----------"); | |
62e76326 | 1357 | |
7a2f978b | 1358 | /* Ok, all headers are received */ |
9ff1b8ca AJ |
1359 | ClientHttpRequest *http = new ClientHttpRequest(csd); |
1360 | ||
9bafa70d | 1361 | http->req_sz = hp->messageHeaderSize(); |
d3dddfb5 | 1362 | Http::Stream *result = new Http::Stream(csd->clientConnection, http); |
62e76326 | 1363 | |
942b1c39 AJ |
1364 | StoreIOBuffer tempBuffer; |
1365 | tempBuffer.data = result->reqbuf; | |
1366 | tempBuffer.length = HTTP_REQBUF_SZ; | |
1367 | ||
0655fa4d | 1368 | ClientStreamData newServer = new clientReplyContext(http); |
0655fa4d | 1369 | ClientStreamData newClient = result; |
edce4d98 | 1370 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, |
0655fa4d | 1371 | clientReplyStatus, newServer, clientSocketRecipient, |
942b1c39 | 1372 | clientSocketDetach, newClient, tempBuffer); |
62e76326 | 1373 | |
3ff65596 | 1374 | /* set url */ |
450e09f9 | 1375 | debugs(33,5, "Prepare absolute URL from " << |
2ee34428 | 1376 | (csd->transparent()?"intercept":(csd->port->flags.accelSurrogate ? "accel":""))); |
3f38a55e | 1377 | /* Rewrite the URL in transparent or accelerator mode */ |
89272111 AJ |
1378 | /* NP: there are several cases to traverse here: |
1379 | * - standard mode (forward proxy) | |
1380 | * - transparent mode (TPROXY) | |
1381 | * - transparent mode with failures | |
1382 | * - intercept mode (NAT) | |
1383 | * - intercept mode with failures | |
1384 | * - accelerator mode (reverse proxy) | |
51b5dcf5 | 1385 | * - internal relative-URL |
89272111 | 1386 | * - mixed combos of the above with internal URL |
151ba0d4 AJ |
1387 | * - remote interception with PROXY protocol |
1388 | * - remote reverse-proxy with PROXY protocol | |
89272111 | 1389 | */ |
82b04b16 CT |
1390 | if (csd->switchedToHttps()) { |
1391 | http->uri = csd->prepareTlsSwitchingURL(hp); | |
1392 | } else if (csd->transparent() || csd->switchedToHttps()) { | |
89272111 | 1393 | /* intercept or transparent mode, properly working with no failures */ |
82b04b16 | 1394 | http->uri = prepareTransparentURL(csd, hp); |
89272111 | 1395 | |
51b5dcf5 | 1396 | } else if (internalCheck(hp->requestUri())) { // NP: only matches relative-URI |
89272111 | 1397 | /* internal URL mode */ |
2f2749d7 | 1398 | /* prepend our name & port */ |
51b5dcf5 | 1399 | http->uri = xstrdup(internalLocalUri(NULL, hp->requestUri())); |
59c59acf AJ |
1400 | // We just re-wrote the URL. Must replace the Host: header. |
1401 | // But have not parsed there yet!! flag for local-only handling. | |
be4d35dc | 1402 | http->flags.internal = true; |
59c59acf | 1403 | |
82b04b16 | 1404 | } else if (csd->port->flags.accelSurrogate) { |
59c59acf | 1405 | /* accelerator mode */ |
82b04b16 CT |
1406 | http->uri = prepareAcceleratedURL(csd, hp); |
1407 | http->flags.accel = true; | |
3f38a55e | 1408 | } |
1409 | ||
1410 | if (!http->uri) { | |
62e76326 | 1411 | /* No special rewrites have been applied above, use the |
1412 | * requested url. may be rewritten later, so make extra room */ | |
9bafa70d | 1413 | int url_sz = hp->requestUri().length() + Config.appendDomainLen + 5; |
62e76326 | 1414 | http->uri = (char *)xcalloc(url_sz, 1); |
3f0e38d6 | 1415 | SBufToCstring(http->uri, hp->requestUri()); |
3f38a55e | 1416 | } |
62e76326 | 1417 | |
c4b7a5a9 | 1418 | result->flags.parsed_ok = 1; |
c8be6d7b | 1419 | return result; |
7a2f978b | 1420 | } |
1421 | ||
fcc444e3 | 1422 | bool |
1cf238db | 1423 | ConnStateData::connFinishedWithConn(int size) |
c8be6d7b | 1424 | { |
1425 | if (size == 0) { | |
e500cc89 | 1426 | if (pipeline.empty() && inBuf.isEmpty()) { |
62e76326 | 1427 | /* no current or pending requests */ |
73c36fd9 | 1428 | debugs(33, 4, HERE << clientConnection << " closed"); |
fcc444e3 | 1429 | return true; |
62e76326 | 1430 | } else if (!Config.onoff.half_closed_clients) { |
1431 | /* admin doesn't want to support half-closed client sockets */ | |
73c36fd9 | 1432 | debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)"); |
08a175bb | 1433 | pipeline.terminateAll(0); |
fcc444e3 | 1434 | return true; |
62e76326 | 1435 | } |
c8be6d7b | 1436 | } |
62e76326 | 1437 | |
fcc444e3 | 1438 | return false; |
c8be6d7b | 1439 | } |
1440 | ||
92ae4c86 AR |
1441 | void |
1442 | ConnStateData::consumeInput(const size_t byteCount) | |
1443 | { | |
fcc444e3 AJ |
1444 | assert(byteCount > 0 && byteCount <= inBuf.length()); |
1445 | inBuf.consume(byteCount); | |
1446 | debugs(33, 5, "inBuf has " << inBuf.length() << " unused bytes"); | |
92ae4c86 AR |
1447 | } |
1448 | ||
1cf238db | 1449 | void |
f35961af | 1450 | ConnStateData::clientAfterReadingRequests() |
c4b7a5a9 | 1451 | { |
39cb8c41 | 1452 | // Were we expecting to read more request body from half-closed connection? |
73c36fd9 AJ |
1453 | if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) { |
1454 | debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection); | |
1455 | clientConnection->close(); | |
39cb8c41 | 1456 | return; |
c4b7a5a9 | 1457 | } |
1458 | ||
f35961af AR |
1459 | if (flags.readMore) |
1460 | readSomeData(); | |
c4b7a5a9 | 1461 | } |
1462 | ||
84c77748 AR |
1463 | void |
1464 | ConnStateData::quitAfterError(HttpRequest *request) | |
1465 | { | |
1466 | // From HTTP p.o.v., we do not have to close after every error detected | |
1467 | // at the client-side, but many such errors do require closure and the | |
1468 | // client-side code is bad at handling errors so we play it safe. | |
1469 | if (request) | |
e857372a | 1470 | request->flags.proxyKeepalive = false; |
84c77748 AR |
1471 | flags.readMore = false; |
1472 | debugs(33,4, HERE << "Will close after error: " << clientConnection); | |
1473 | } | |
1474 | ||
cb4f4424 | 1475 | #if USE_OPENSSL |
d3dddfb5 | 1476 | bool ConnStateData::serveDelayedError(Http::Stream *context) |
8eb0a7ee CT |
1477 | { |
1478 | ClientHttpRequest *http = context->http; | |
fd4624d7 CT |
1479 | |
1480 | if (!sslServerBump) | |
8eb0a7ee CT |
1481 | return false; |
1482 | ||
fd4624d7 | 1483 | assert(sslServerBump->entry); |
7a957a93 | 1484 | // Did we create an error entry while processing CONNECT? |
fd4624d7 | 1485 | if (!sslServerBump->entry->isEmpty()) { |
84c77748 AR |
1486 | quitAfterError(http->request); |
1487 | ||
7a957a93 AR |
1488 | // Get the saved error entry and send it to the client by replacing the |
1489 | // ClientHttpRequest store entry with it. | |
8eb0a7ee CT |
1490 | clientStreamNode *node = context->getClientReplyContext(); |
1491 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
7a957a93 AR |
1492 | assert(repContext); |
1493 | debugs(33, 5, "Responding with delated error for " << http->uri); | |
f0baf149 | 1494 | repContext->setReplyToStoreEntry(sslServerBump->entry, "delayed SslBump error"); |
7a957a93 | 1495 | |
7a957a93 | 1496 | // Get error details from the fake certificate-peeking request. |
129fe2a1 | 1497 | http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail); |
8eb0a7ee | 1498 | context->pullData(); |
8eb0a7ee CT |
1499 | return true; |
1500 | } | |
1501 | ||
7a957a93 AR |
1502 | // In bump-server-first mode, we have not necessarily seen the intended |
1503 | // server name at certificate-peeking time. Check for domain mismatch now, | |
1504 | // when we can extract the intended name from the bumped HTTP request. | |
92e3827b | 1505 | if (const Security::CertPointer &srvCert = sslServerBump->serverCert) { |
8eb0a7ee | 1506 | HttpRequest *request = http->request; |
92e3827b | 1507 | if (!Ssl::checkX509ServerValidity(srvCert.get(), request->url.host())) { |
7a957a93 | 1508 | debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << |
5c51bffb | 1509 | "does not match domainname " << request->url.host()); |
8eb0a7ee | 1510 | |
d4a56c34 | 1511 | bool allowDomainMismatch = false; |
638402dd AJ |
1512 | if (Config.ssl_client.cert_error) { |
1513 | ACLFilledChecklist check(Config.ssl_client.cert_error, request, dash_str); | |
cb365059 | 1514 | check.al = http->al; |
92e3827b | 1515 | check.sslErrors = new Security::CertErrors(Security::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH, srvCert)); |
cb365059 | 1516 | check.syncAle(request, http->log_uri); |
06bf5384 | 1517 | allowDomainMismatch = check.fastCheck().allowed(); |
638402dd AJ |
1518 | delete check.sslErrors; |
1519 | check.sslErrors = NULL; | |
1520 | } | |
8eb0a7ee | 1521 | |
7d82c5b8 | 1522 | if (!allowDomainMismatch) { |
84c77748 AR |
1523 | quitAfterError(request); |
1524 | ||
8eb0a7ee CT |
1525 | clientStreamNode *node = context->getClientReplyContext(); |
1526 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
1527 | assert (repContext); | |
1528 | ||
d8165775 | 1529 | request->hier = sslServerBump->request->hier; |
7a957a93 | 1530 | |
8eb0a7ee | 1531 | // Create an error object and fill it |
955394ce | 1532 | ErrorState *err = new ErrorState(ERR_SECURE_CONNECT_FAIL, Http::scServiceUnavailable, request); |
8eb0a7ee | 1533 | err->src_addr = clientConnection->remote; |
7a957a93 AR |
1534 | Ssl::ErrorDetail *errDetail = new Ssl::ErrorDetail( |
1535 | SQUID_X509_V_ERR_DOMAIN_MISMATCH, | |
92e3827b | 1536 | srvCert.get(), nullptr); |
8eb0a7ee CT |
1537 | err->detail = errDetail; |
1538 | repContext->setReplyToError(request->method, err); | |
1539 | assert(context->http->out.offset == 0); | |
1540 | context->pullData(); | |
8eb0a7ee CT |
1541 | return true; |
1542 | } | |
1543 | } | |
1544 | } | |
1545 | ||
1546 | return false; | |
1547 | } | |
cb4f4424 | 1548 | #endif // USE_OPENSSL |
8eb0a7ee | 1549 | |
3248e962 CT |
1550 | /** |
1551 | * Check on_unsupported_protocol checklist and return true if tunnel mode selected | |
1552 | * or false otherwise | |
1553 | */ | |
1554 | bool | |
6b2b6cfe | 1555 | clientTunnelOnError(ConnStateData *conn, Http::StreamPointer &context, HttpRequest::Pointer &request, const HttpRequestMethod& method, err_type requestError) |
3248e962 | 1556 | { |
6b2b6cfe CT |
1557 | if (conn->mayTunnelUnsupportedProto()) { |
1558 | ACLFilledChecklist checklist(Config.accessList.on_unsupported_protocol, request.getRaw(), nullptr); | |
cb365059 | 1559 | checklist.al = (context && context->http) ? context->http->al : nullptr; |
3248e962 CT |
1560 | checklist.requestErrorType = requestError; |
1561 | checklist.src_addr = conn->clientConnection->remote; | |
1562 | checklist.my_addr = conn->clientConnection->local; | |
1563 | checklist.conn(conn); | |
cb365059 EB |
1564 | ClientHttpRequest *http = context ? context->http : nullptr; |
1565 | const char *log_uri = http ? http->log_uri : nullptr; | |
1566 | checklist.syncAle(request.getRaw(), log_uri); | |
3248e962 | 1567 | allow_t answer = checklist.fastCheck(); |
06bf5384 | 1568 | if (answer.allowed() && answer.kind == 1) { |
3248e962 | 1569 | debugs(33, 3, "Request will be tunneled to server"); |
6400749d AJ |
1570 | if (context) { |
1571 | assert(conn->pipeline.front() == context); // XXX: still assumes HTTP/1 semantics | |
6b2b6cfe | 1572 | context->finished(); // Will remove from conn->pipeline queue |
6400749d | 1573 | } |
3248e962 | 1574 | Comm::SetSelect(conn->clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0); |
6b2b6cfe | 1575 | return conn->initiateTunneledRequest(request, Http::METHOD_NONE, "unknown-protocol", conn->preservedClientData); |
3248e962 CT |
1576 | } else { |
1577 | debugs(33, 3, "Continue with returning the error: " << requestError); | |
1578 | } | |
1579 | } | |
1580 | ||
3248e962 CT |
1581 | return false; |
1582 | } | |
1583 | ||
ec69bdb2 | 1584 | void |
28fd6d0b AJ |
1585 | clientProcessRequestFinished(ConnStateData *conn, const HttpRequest::Pointer &request) |
1586 | { | |
1587 | /* | |
1588 | * DPW 2007-05-18 | |
1589 | * Moved the TCP_RESET feature from clientReplyContext::sendMoreData | |
1590 | * to here because calling comm_reset_close() causes http to | |
48a37aee | 1591 | * be freed before accessing. |
28fd6d0b AJ |
1592 | */ |
1593 | if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) { | |
1594 | debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection); | |
1595 | conn->flags.readMore = false; | |
1596 | comm_reset_close(conn->clientConnection); | |
1597 | } | |
1598 | } | |
1599 | ||
9bafa70d | 1600 | void |
d3dddfb5 | 1601 | clientProcessRequest(ConnStateData *conn, const Http1::RequestParserPointer &hp, Http::Stream *context) |
c4b7a5a9 | 1602 | { |
59a1efb2 | 1603 | ClientHttpRequest *http = context->http; |
39cb8c41 | 1604 | bool chunked = false; |
e18b8316 | 1605 | bool mustReplyToOptions = false; |
3ff65596 | 1606 | bool unsupportedTe = false; |
39cb8c41 | 1607 | bool expectBody = false; |
5f8252d2 | 1608 | |
ec69bdb2 CT |
1609 | // We already have the request parsed and checked, so we |
1610 | // only need to go through the final body/conn setup to doCallouts(). | |
1611 | assert(http->request); | |
1612 | HttpRequest::Pointer request = http->request; | |
1613 | ||
92ae4c86 | 1614 | // temporary hack to avoid splitting this huge function with sensitive code |
f9688132 | 1615 | const bool isFtp = !hp; |
9bafa70d | 1616 | |
92ae4c86 AR |
1617 | // Some blobs below are still HTTP-specific, but we would have to rewrite |
1618 | // this entire function to remove them from the FTP code path. Connection | |
1619 | // setup and body_pipe preparation blobs are needed for FTP. | |
1620 | ||
cd4a5c60 | 1621 | request->manager(conn, http->al); |
40d34a62 | 1622 | |
c4b7a5a9 | 1623 | request->flags.accelerated = http->flags.accel; |
450fe1cb | 1624 | request->flags.sslBumped=conn->switchedToHttps(); |
7fb65ee4 | 1625 | // TODO: decouple http->flags.accel from request->flags.sslBumped |
450fe1cb | 1626 | request->flags.noDirect = (request->flags.accelerated && !request->flags.sslBumped) ? |
e4a14600 | 1627 | !conn->port->allow_direct : 0; |
63df1d28 AJ |
1628 | request->sources |= isFtp ? Http::Message::srcFtp : |
1629 | ((request->flags.sslBumped || conn->port->transport.protocol == AnyP::PROTO_HTTPS) ? Http::Message::srcHttps : Http::Message::srcHttp); | |
21512911 CT |
1630 | #if USE_AUTH |
1631 | if (request->flags.sslBumped) { | |
cc1e110a AJ |
1632 | if (conn->getAuth() != NULL) |
1633 | request->auth_user_request = conn->getAuth(); | |
21512911 CT |
1634 | } |
1635 | #endif | |
2ad20b4f | 1636 | |
51b5dcf5 | 1637 | if (internalCheck(request->url.path())) { |
5c51bffb AJ |
1638 | if (internalHostnameIs(request->url.host()) && request->url.port() == getMyPort()) { |
1639 | debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true)); | |
be4d35dc | 1640 | http->flags.internal = true; |
51b5dcf5 | 1641 | } else if (Config.onoff.global_internal_static && internalStaticCheck(request->url.path())) { |
5c51bffb | 1642 | debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (global_internal_static on)"); |
d31d59d8 | 1643 | request->url.setScheme(AnyP::PROTO_HTTP, "http"); |
851feda6 | 1644 | request->url.host(internalHostname()); |
5c51bffb | 1645 | request->url.port(getMyPort()); |
be4d35dc | 1646 | http->flags.internal = true; |
bec110e4 | 1647 | http->setLogUriToRequestUri(); |
4e3f4dc7 | 1648 | } else |
5c51bffb | 1649 | debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->url.authority(true) << " (not this proxy)"); |
f024c970 | 1650 | } |
e72a0ec0 | 1651 | |
c4b7a5a9 | 1652 | request->flags.internal = http->flags.internal; |
9bafa70d AJ |
1653 | |
1654 | if (!isFtp) { | |
63df1d28 | 1655 | // XXX: for non-HTTP messages instantiate a different Http::Message child type |
9bafa70d AJ |
1656 | // for now Squid only supports HTTP requests |
1657 | const AnyP::ProtocolVersion &http_ver = hp->messageProtocol(); | |
1658 | assert(request->http_ver.protocol == http_ver.protocol); | |
1659 | request->http_ver.major = http_ver.major; | |
1660 | request->http_ver.minor = http_ver.minor; | |
1661 | } | |
62e76326 | 1662 | |
39cb8c41 AR |
1663 | if (request->header.chunked()) { |
1664 | chunked = true; | |
789217a2 FC |
1665 | } else if (request->header.has(Http::HdrType::TRANSFER_ENCODING)) { |
1666 | const String te = request->header.getList(Http::HdrType::TRANSFER_ENCODING); | |
39cb8c41 AR |
1667 | // HTTP/1.1 requires chunking to be the last encoding if there is one |
1668 | unsupportedTe = te.size() && te != "identity"; | |
1669 | } // else implied identity coding | |
de48b288 | 1670 | |
f9688132 | 1671 | mustReplyToOptions = (request->method == Http::METHOD_OPTIONS) && |
789217a2 | 1672 | (request->header.getInt64(Http::HdrType::MAX_FORWARDS) == 0); |
b248c2a3 | 1673 | if (!urlCheckRequest(request.getRaw()) || mustReplyToOptions || unsupportedTe) { |
62e76326 | 1674 | clientStreamNode *node = context->getClientReplyContext(); |
b248c2a3 | 1675 | conn->quitAfterError(request.getRaw()); |
0655fa4d | 1676 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
1677 | assert (repContext); | |
955394ce | 1678 | repContext->setReplyToError(ERR_UNSUP_REQ, Http::scNotImplemented, request->method, NULL, |
b248c2a3 | 1679 | conn->clientConnection->remote, request.getRaw(), NULL, NULL); |
62e76326 | 1680 | assert(context->http->out.offset == 0); |
1681 | context->pullData(); | |
28fd6d0b AJ |
1682 | clientProcessRequestFinished(conn, request); |
1683 | return; | |
c4b7a5a9 | 1684 | } |
1685 | ||
b248c2a3 | 1686 | if (!chunked && !clientIsContentLengthValid(request.getRaw())) { |
62e76326 | 1687 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 1688 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
1689 | assert (repContext); | |
b248c2a3 | 1690 | conn->quitAfterError(request.getRaw()); |
0655fa4d | 1691 | repContext->setReplyToError(ERR_INVALID_REQ, |
955394ce | 1692 | Http::scLengthRequired, request->method, NULL, |
b248c2a3 | 1693 | conn->clientConnection->remote, request.getRaw(), NULL, NULL); |
62e76326 | 1694 | assert(context->http->out.offset == 0); |
1695 | context->pullData(); | |
28fd6d0b AJ |
1696 | clientProcessRequestFinished(conn, request); |
1697 | return; | |
c4b7a5a9 | 1698 | } |
1699 | ||
92ae4c86 | 1700 | clientSetKeepaliveFlag(http); |
f35961af | 1701 | // Let tunneling code be fully responsible for CONNECT requests |
c2a7cefd | 1702 | if (http->request->method == Http::METHOD_CONNECT) { |
b66e0e86 | 1703 | context->mayUseConnection(true); |
f35961af AR |
1704 | conn->flags.readMore = false; |
1705 | } | |
fc68f6b1 | 1706 | |
cb4f4424 | 1707 | #if USE_OPENSSL |
28fd6d0b | 1708 | if (conn->switchedToHttps() && conn->serveDelayedError(context)) { |
28fd6d0b AJ |
1709 | clientProcessRequestFinished(conn, request); |
1710 | return; | |
1711 | } | |
061bbdec CT |
1712 | #endif |
1713 | ||
b66e0e86 | 1714 | /* Do we expect a request-body? */ |
39cb8c41 AR |
1715 | expectBody = chunked || request->content_length > 0; |
1716 | if (!context->mayUseConnection() && expectBody) { | |
1717 | request->body_pipe = conn->expectRequestBody( | |
de48b288 | 1718 | chunked ? -1 : request->content_length); |
5f8252d2 | 1719 | |
62e76326 | 1720 | /* Is it too large? */ |
39cb8c41 | 1721 | if (!chunked && // if chunked, we will check as we accumulate |
de48b288 | 1722 | clientIsRequestBodyTooLargeForPolicy(request->content_length)) { |
62e76326 | 1723 | clientStreamNode *node = context->getClientReplyContext(); |
0655fa4d | 1724 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); |
1725 | assert (repContext); | |
b248c2a3 | 1726 | conn->quitAfterError(request.getRaw()); |
0655fa4d | 1727 | repContext->setReplyToError(ERR_TOO_BIG, |
f11c8e2f | 1728 | Http::scPayloadTooLarge, Http::METHOD_NONE, NULL, |
73c36fd9 | 1729 | conn->clientConnection->remote, http->request, NULL, NULL); |
62e76326 | 1730 | assert(context->http->out.offset == 0); |
1731 | context->pullData(); | |
28fd6d0b AJ |
1732 | clientProcessRequestFinished(conn, request); |
1733 | return; | |
62e76326 | 1734 | } |
1735 | ||
92ae4c86 | 1736 | if (!isFtp) { |
a5d444a5 DK |
1737 | // We may stop producing, comm_close, and/or call setReplyToError() |
1738 | // below, so quit on errors to avoid http->doCallouts() | |
28fd6d0b AJ |
1739 | if (!conn->handleRequestBodyData()) { |
1740 | clientProcessRequestFinished(conn, request); | |
1741 | return; | |
1742 | } | |
39cb8c41 | 1743 | |
a5d444a5 | 1744 | if (!request->body_pipe->productionEnded()) { |
e7ce227f | 1745 | debugs(33, 5, "need more request body"); |
a5d444a5 DK |
1746 | context->mayUseConnection(true); |
1747 | assert(conn->flags.readMore); | |
1748 | } | |
f35961af | 1749 | } |
c4b7a5a9 | 1750 | } |
1751 | ||
de31d06f | 1752 | http->calloutContext = new ClientRequestContext(http); |
1753 | ||
1754 | http->doCallouts(); | |
9e008dda | 1755 | |
28fd6d0b | 1756 | clientProcessRequestFinished(conn, request); |
c4b7a5a9 | 1757 | } |
1758 | ||
92ae4c86 AR |
1759 | int |
1760 | ConnStateData::pipelinePrefetchMax() const | |
1761 | { | |
efbea402 CT |
1762 | // TODO: Support pipelined requests through pinned connections. |
1763 | if (pinning.pinned) | |
1764 | return 0; | |
92ae4c86 AR |
1765 | return Config.pipeline_max_prefetch; |
1766 | } | |
1767 | ||
079a8480 AJ |
1768 | /** |
1769 | * Limit the number of concurrent requests. | |
1770 | * \return true when there are available position(s) in the pipeline queue for another request. | |
1771 | * \return false when the pipeline queue is full or disabled. | |
1772 | */ | |
1773 | bool | |
1774 | ConnStateData::concurrentRequestQueueFilled() const | |
c4b7a5a9 | 1775 | { |
e500cc89 | 1776 | const int existingRequestCount = pipeline.count(); |
079a8480 AJ |
1777 | |
1778 | // default to the configured pipeline size. | |
1779 | // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue | |
0de57497 | 1780 | #if USE_OPENSSL |
43b43c46 | 1781 | const int internalRequest = (transparent() && sslBumpMode == Ssl::bumpSplice) ? 1 : 0; |
0de57497 | 1782 | #else |
06211564 | 1783 | const int internalRequest = 0; |
0de57497 | 1784 | #endif |
43b43c46 | 1785 | const int concurrentRequestLimit = pipelinePrefetchMax() + 1 + internalRequest; |
62e76326 | 1786 | |
079a8480 AJ |
1787 | // when queue filled already we cant add more. |
1788 | if (existingRequestCount >= concurrentRequestLimit) { | |
1789 | debugs(33, 3, clientConnection << " max concurrent requests reached (" << concurrentRequestLimit << ")"); | |
1790 | debugs(33, 5, clientConnection << " deferring new request until one is done"); | |
1791 | return true; | |
c4b7a5a9 | 1792 | } |
62e76326 | 1793 | |
079a8480 | 1794 | return false; |
c4b7a5a9 | 1795 | } |
1796 | ||
00d0ce87 | 1797 | /** |
d3d92daa | 1798 | * Perform proxy_protocol_access ACL tests on the client which |
3bd97e7e AJ |
1799 | * connected to PROXY protocol port to see if we trust the |
1800 | * sender enough to accept their PROXY header claim. | |
00d0ce87 | 1801 | */ |
6658cc16 | 1802 | bool |
00d0ce87 AJ |
1803 | ConnStateData::proxyProtocolValidateClient() |
1804 | { | |
d3d92daa AJ |
1805 | if (!Config.accessList.proxyProtocol) |
1806 | return proxyProtocolError("PROXY client not permitted by default ACL"); | |
1807 | ||
1808 | ACLFilledChecklist ch(Config.accessList.proxyProtocol, NULL, clientConnection->rfc931); | |
00d0ce87 AJ |
1809 | ch.src_addr = clientConnection->remote; |
1810 | ch.my_addr = clientConnection->local; | |
6658cc16 | 1811 | ch.conn(this); |
00d0ce87 | 1812 | |
06bf5384 | 1813 | if (!ch.fastCheck().allowed()) |
3bd97e7e AJ |
1814 | return proxyProtocolError("PROXY client not permitted by ACLs"); |
1815 | ||
6658cc16 | 1816 | return true; |
00d0ce87 AJ |
1817 | } |
1818 | ||
1819 | /** | |
1820 | * Perform cleanup on PROXY protocol errors. | |
1821 | * If header parsing hits a fatal error terminate the connection, | |
1822 | * otherwise wait for more data. | |
1823 | */ | |
1824 | bool | |
3bd97e7e | 1825 | ConnStateData::proxyProtocolError(const char *msg) |
00d0ce87 | 1826 | { |
3c082dbe | 1827 | if (msg) { |
70a16fea AJ |
1828 | // This is important to know, but maybe not so much that flooding the log is okay. |
1829 | #if QUIET_PROXY_PROTOCOL | |
1830 | // display the first of every 32 occurances at level 1, the others at level 2. | |
1831 | static uint8_t hide = 0; | |
1832 | debugs(33, (hide++ % 32 == 0 ? DBG_IMPORTANT : 2), msg << " from " << clientConnection); | |
1833 | #else | |
1834 | debugs(33, DBG_IMPORTANT, msg << " from " << clientConnection); | |
1835 | #endif | |
3bd97e7e | 1836 | mustStop(msg); |
3c082dbe | 1837 | } |
00d0ce87 AJ |
1838 | return false; |
1839 | } | |
1840 | ||
3bd97e7e | 1841 | /// magic octet prefix for PROXY protocol version 1 |
70a16fea | 1842 | static const SBuf Proxy1p0magic("PROXY ", 6); |
3bd97e7e AJ |
1843 | |
1844 | /// magic octet prefix for PROXY protocol version 2 | |
70a16fea | 1845 | static const SBuf Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12); |
3bd97e7e | 1846 | |
00d0ce87 | 1847 | /** |
3bd97e7e AJ |
1848 | * Test the connection read buffer for PROXY protocol header. |
1849 | * Version 1 and 2 header currently supported. | |
00d0ce87 AJ |
1850 | */ |
1851 | bool | |
3d74cb1f | 1852 | ConnStateData::parseProxyProtocolHeader() |
00d0ce87 | 1853 | { |
00d0ce87 | 1854 | // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt |
cbae7ab9 | 1855 | |
70a16fea | 1856 | // detect and parse PROXY/2.0 protocol header |
fcc444e3 | 1857 | if (inBuf.startsWith(Proxy2p0magic)) |
70a16fea | 1858 | return parseProxy2p0(); |
00d0ce87 | 1859 | |
70a16fea | 1860 | // detect and parse PROXY/1.0 protocol header |
fcc444e3 | 1861 | if (inBuf.startsWith(Proxy1p0magic)) |
bd1be2ae | 1862 | return parseProxy1p0(); |
00d0ce87 | 1863 | |
70a16fea | 1864 | // detect and terminate other protocols |
fcc444e3 | 1865 | if (inBuf.length() >= Proxy2p0magic.length()) { |
70a16fea AJ |
1866 | // PROXY/1.0 magic is shorter, so we know that |
1867 | // the input does not start with any PROXY magic | |
3bd97e7e AJ |
1868 | return proxyProtocolError("PROXY protocol error: invalid header"); |
1869 | } | |
00d0ce87 | 1870 | |
3d74cb1f AJ |
1871 | // TODO: detect short non-magic prefixes earlier to avoid |
1872 | // waiting for more data which may never come | |
1873 | ||
3bd97e7e AJ |
1874 | // not enough bytes to parse yet. |
1875 | return false; | |
1876 | } | |
00d0ce87 | 1877 | |
3bd97e7e AJ |
1878 | /// parse the PROXY/1.0 protocol header from the connection read buffer |
1879 | bool | |
70a16fea | 1880 | ConnStateData::parseProxy1p0() |
3bd97e7e | 1881 | { |
fcc444e3 | 1882 | ::Parser::Tokenizer tok(inBuf); |
70a16fea | 1883 | tok.skip(Proxy1p0magic); |
3bd97e7e | 1884 | |
154ea566 AJ |
1885 | // skip to first LF (assumes it is part of CRLF) |
1886 | static const CharacterSet lineContent = CharacterSet::LF.complement("non-LF"); | |
1887 | SBuf line; | |
1888 | if (tok.prefix(line, lineContent, 107-Proxy1p0magic.length())) { | |
1889 | if (tok.skip('\n')) { | |
1890 | // found valid header | |
fcc444e3 | 1891 | inBuf = tok.remaining(); |
154ea566 AJ |
1892 | needProxyProtocolHeader_ = false; |
1893 | // reset the tokenizer to work on found line only. | |
1894 | tok.reset(line); | |
1895 | } else | |
1896 | return false; // no LF yet | |
1897 | ||
1898 | } else // protocol error only if there are more than 107 bytes prefix header | |
fcc444e3 | 1899 | return proxyProtocolError(inBuf.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL); |
154ea566 | 1900 | |
1689cdbc AJ |
1901 | static const SBuf unknown("UNKNOWN"), tcpName("TCP"); |
1902 | if (tok.skip(tcpName)) { | |
3bd97e7e | 1903 | |
1689cdbc AJ |
1904 | // skip TCP/IP version number |
1905 | static const CharacterSet tcpVersions("TCP-version","46"); | |
bd1be2ae | 1906 | if (!tok.skipOne(tcpVersions)) |
154ea566 | 1907 | return proxyProtocolError("PROXY/1.0 error: missing TCP version"); |
00d0ce87 | 1908 | |
3bd97e7e AJ |
1909 | // skip SP after protocol version |
1910 | if (!tok.skip(' ')) | |
154ea566 | 1911 | return proxyProtocolError("PROXY/1.0 error: missing SP"); |
00d0ce87 | 1912 | |
3bd97e7e AJ |
1913 | SBuf ipa, ipb; |
1914 | int64_t porta, portb; | |
1689cdbc AJ |
1915 | static const CharacterSet ipChars = CharacterSet("IP Address",".:") + CharacterSet::HEXDIG; |
1916 | ||
1917 | // parse: src-IP SP dst-IP SP src-port SP dst-port CR | |
1918 | // leave the LF until later. | |
1919 | const bool correct = tok.prefix(ipa, ipChars) && tok.skip(' ') && | |
1920 | tok.prefix(ipb, ipChars) && tok.skip(' ') && | |
1921 | tok.int64(porta) && tok.skip(' ') && | |
1922 | tok.int64(portb) && | |
1923 | tok.skip('\r'); | |
1924 | if (!correct) | |
154ea566 | 1925 | return proxyProtocolError("PROXY/1.0 error: invalid syntax"); |
00d0ce87 | 1926 | |
3bd97e7e AJ |
1927 | // parse IP and port strings |
1928 | Ip::Address originalClient, originalDest; | |
00d0ce87 | 1929 | |
3bd97e7e AJ |
1930 | if (!originalClient.GetHostByName(ipa.c_str())) |
1931 | return proxyProtocolError("PROXY/1.0 error: invalid src-IP address"); | |
00d0ce87 | 1932 | |
3bd97e7e AJ |
1933 | if (!originalDest.GetHostByName(ipb.c_str())) |
1934 | return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address"); | |
00d0ce87 | 1935 | |
3bd97e7e AJ |
1936 | if (porta > 0 && porta <= 0xFFFF) // max uint16_t |
1937 | originalClient.port(static_cast<uint16_t>(porta)); | |
1938 | else | |
1939 | return proxyProtocolError("PROXY/1.0 error: invalid src port"); | |
cbae7ab9 | 1940 | |
3bd97e7e AJ |
1941 | if (portb > 0 && portb <= 0xFFFF) // max uint16_t |
1942 | originalDest.port(static_cast<uint16_t>(portb)); | |
1943 | else | |
1944 | return proxyProtocolError("PROXY/1.0 error: invalid dst port"); | |
cbae7ab9 | 1945 | |
3bd97e7e AJ |
1946 | // we have original client and destination details now |
1947 | // replace the client connection values | |
1948 | debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection); | |
1949 | clientConnection->local = originalDest; | |
1950 | clientConnection->remote = originalClient; | |
65984b09 YW |
1951 | if ((clientConnection->flags & COMM_TRANSPARENT)) |
1952 | clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP. | |
3bd97e7e | 1953 | debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection); |
3bd97e7e | 1954 | return true; |
1689cdbc AJ |
1955 | |
1956 | } else if (tok.skip(unknown)) { | |
154ea566 AJ |
1957 | // found valid but unusable header |
1958 | return true; | |
1689cdbc AJ |
1959 | |
1960 | } else | |
154ea566 | 1961 | return proxyProtocolError("PROXY/1.0 error: invalid protocol family"); |
cbae7ab9 | 1962 | |
3bd97e7e AJ |
1963 | return false; |
1964 | } | |
cbae7ab9 | 1965 | |
3bd97e7e AJ |
1966 | /// parse the PROXY/2.0 protocol header from the connection read buffer |
1967 | bool | |
70a16fea | 1968 | ConnStateData::parseProxy2p0() |
3bd97e7e | 1969 | { |
1689cdbc | 1970 | static const SBuf::size_type prefixLen = Proxy2p0magic.length(); |
fcc444e3 | 1971 | if (inBuf.length() < prefixLen + 4) |
1689cdbc AJ |
1972 | return false; // need more bytes |
1973 | ||
fcc444e3 | 1974 | if ((inBuf[prefixLen] & 0xF0) != 0x20) // version == 2 is mandatory |
3bd97e7e | 1975 | return proxyProtocolError("PROXY/2.0 error: invalid version"); |
cbae7ab9 | 1976 | |
fcc444e3 | 1977 | const char command = (inBuf[prefixLen] & 0x0F); |
3bd97e7e AJ |
1978 | if ((command & 0xFE) != 0x00) // values other than 0x0-0x1 are invalid |
1979 | return proxyProtocolError("PROXY/2.0 error: invalid command"); | |
cbae7ab9 | 1980 | |
fcc444e3 | 1981 | const char family = (inBuf[prefixLen+1] & 0xF0) >>4; |
3bd97e7e AJ |
1982 | if (family > 0x3) // values other than 0x0-0x3 are invalid |
1983 | return proxyProtocolError("PROXY/2.0 error: invalid family"); | |
cbae7ab9 | 1984 | |
fcc444e3 | 1985 | const char proto = (inBuf[prefixLen+1] & 0x0F); |
3bd97e7e AJ |
1986 | if (proto > 0x2) // values other than 0x0-0x2 are invalid |
1987 | return proxyProtocolError("PROXY/2.0 error: invalid protocol type"); | |
cbae7ab9 | 1988 | |
fcc444e3 | 1989 | const char *clen = inBuf.rawContent() + prefixLen + 2; |
17954dbd AJ |
1990 | uint16_t len; |
1991 | memcpy(&len, clen, sizeof(len)); | |
1992 | len = ntohs(len); | |
cbae7ab9 | 1993 | |
fcc444e3 | 1994 | if (inBuf.length() < prefixLen + 4 + len) |
3bd97e7e | 1995 | return false; // need more bytes |
cbae7ab9 | 1996 | |
fcc444e3 AJ |
1997 | inBuf.consume(prefixLen + 4); // 4 being the extra bytes |
1998 | const SBuf extra = inBuf.consume(len); | |
3bd97e7e | 1999 | needProxyProtocolHeader_ = false; // found successfully |
cbae7ab9 | 2000 | |
3bd97e7e AJ |
2001 | // LOCAL connections do nothing with the extras |
2002 | if (command == 0x00/* LOCAL*/) | |
cbae7ab9 AJ |
2003 | return true; |
2004 | ||
1689cdbc | 2005 | union pax { |
3bd97e7e AJ |
2006 | struct { /* for TCP/UDP over IPv4, len = 12 */ |
2007 | struct in_addr src_addr; | |
2008 | struct in_addr dst_addr; | |
2009 | uint16_t src_port; | |
2010 | uint16_t dst_port; | |
2011 | } ipv4_addr; | |
2012 | struct { /* for TCP/UDP over IPv6, len = 36 */ | |
bd1be2ae A |
2013 | struct in6_addr src_addr; |
2014 | struct in6_addr dst_addr; | |
2015 | uint16_t src_port; | |
2016 | uint16_t dst_port; | |
3bd97e7e AJ |
2017 | } ipv6_addr; |
2018 | #if NOT_SUPPORTED | |
2019 | struct { /* for AF_UNIX sockets, len = 216 */ | |
bd1be2ae A |
2020 | uint8_t src_addr[108]; |
2021 | uint8_t dst_addr[108]; | |
3bd97e7e AJ |
2022 | } unix_addr; |
2023 | #endif | |
1689cdbc | 2024 | }; |
3bd97e7e | 2025 | |
17954dbd AJ |
2026 | pax ipu; |
2027 | memcpy(&ipu, extra.rawContent(), sizeof(pax)); | |
3bd97e7e AJ |
2028 | |
2029 | // replace the client connection values | |
2030 | debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection); | |
bd1be2ae | 2031 | switch (family) { |
3bd97e7e | 2032 | case 0x1: // IPv4 |
17954dbd AJ |
2033 | clientConnection->local = ipu.ipv4_addr.dst_addr; |
2034 | clientConnection->local.port(ntohs(ipu.ipv4_addr.dst_port)); | |
2035 | clientConnection->remote = ipu.ipv4_addr.src_addr; | |
2036 | clientConnection->remote.port(ntohs(ipu.ipv4_addr.src_port)); | |
65984b09 YW |
2037 | if ((clientConnection->flags & COMM_TRANSPARENT)) |
2038 | clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP. | |
3bd97e7e AJ |
2039 | break; |
2040 | case 0x2: // IPv6 | |
17954dbd AJ |
2041 | clientConnection->local = ipu.ipv6_addr.dst_addr; |
2042 | clientConnection->local.port(ntohs(ipu.ipv6_addr.dst_port)); | |
2043 | clientConnection->remote = ipu.ipv6_addr.src_addr; | |
2044 | clientConnection->remote.port(ntohs(ipu.ipv6_addr.src_port)); | |
65984b09 YW |
2045 | if ((clientConnection->flags & COMM_TRANSPARENT)) |
2046 | clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP. | |
3bd97e7e AJ |
2047 | break; |
2048 | default: // do nothing | |
2049 | break; | |
00d0ce87 | 2050 | } |
3bd97e7e | 2051 | debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection); |
3bd97e7e | 2052 | return true; |
00d0ce87 AJ |
2053 | } |
2054 | ||
3248e962 CT |
2055 | void |
2056 | ConnStateData::receivedFirstByte() | |
2057 | { | |
2058 | if (receivedFirstByte_) | |
2059 | return; | |
2060 | ||
2061 | receivedFirstByte_ = true; | |
2062 | // Set timeout to Config.Timeout.request | |
2063 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; | |
2064 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, | |
2065 | TimeoutDialer, this, ConnStateData::requestTimeout); | |
2066 | commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall); | |
2067 | } | |
2068 | ||
63be0a78 | 2069 | /** |
f900210a | 2070 | * Attempt to parse one or more requests from the input buffer. |
eacfca83 AR |
2071 | * Returns true after completing parsing of at least one request [header]. That |
2072 | * includes cases where parsing ended with an error (e.g., a huge request). | |
f900210a | 2073 | */ |
4959e21e | 2074 | bool |
f35961af | 2075 | ConnStateData::clientParseRequests() |
f900210a | 2076 | { |
f900210a | 2077 | bool parsed_req = false; |
2078 | ||
1b76e6c1 | 2079 | debugs(33, 5, HERE << clientConnection << ": attempting to parse"); |
f900210a | 2080 | |
39cb8c41 | 2081 | // Loop while we have read bytes that are not needed for producing the body |
f35961af | 2082 | // On errors, bodyPipe may become nil, but readMore will be cleared |
fcc444e3 | 2083 | while (!inBuf.isEmpty() && !bodyPipe && flags.readMore) { |
f900210a | 2084 | |
801cfc26 CT |
2085 | // Prohibit concurrent requests when using a pinned to-server connection |
2086 | // because our Client classes do not support request pipelining. | |
2087 | if (pinning.pinned && !pinning.readHandler) { | |
2088 | debugs(33, 3, clientConnection << " waits for busy " << pinning.serverConnection); | |
2089 | break; | |
2090 | } | |
2091 | ||
079a8480 AJ |
2092 | /* Limit the number of concurrent requests */ |
2093 | if (concurrentRequestQueueFilled()) | |
f900210a | 2094 | break; |
f900210a | 2095 | |
00d0ce87 | 2096 | // try to parse the PROXY protocol header magic bytes |
42cbf844 AJ |
2097 | if (needProxyProtocolHeader_) { |
2098 | if (!parseProxyProtocolHeader()) | |
2099 | break; | |
2100 | ||
2101 | // we have been waiting for PROXY to provide client-IP | |
2102 | // for some lookups, ie rDNS and IDENT. | |
2103 | whenClientIpKnown(); | |
2104 | } | |
00d0ce87 | 2105 | |
6b2b6cfe | 2106 | if (Http::StreamPointer context = parseOneRequest()) { |
eacfca83 | 2107 | debugs(33, 5, clientConnection << ": done parsing a request"); |
f900210a | 2108 | |
8d77a37c | 2109 | AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout", |
dc49061a | 2110 | CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http)); |
1b76e6c1 | 2111 | commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall); |
f900210a | 2112 | |
eacfca83 AR |
2113 | context->registerWithConn(); |
2114 | ||
9bafa70d | 2115 | processParsedRequest(context); |
f900210a | 2116 | |
4959e21e | 2117 | parsed_req = true; // XXX: do we really need to parse everything right NOW ? |
f900210a | 2118 | |
2119 | if (context->mayUseConnection()) { | |
f35961af | 2120 | debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection"); |
f900210a | 2121 | break; |
2122 | } | |
eacfca83 AR |
2123 | } else { |
2124 | debugs(33, 5, clientConnection << ": not enough request data: " << | |
fcc444e3 AJ |
2125 | inBuf.length() << " < " << Config.maxRequestHeaderSize); |
2126 | Must(inBuf.length() < Config.maxRequestHeaderSize); | |
eacfca83 | 2127 | break; |
f900210a | 2128 | } |
39cb8c41 | 2129 | } |
fc68f6b1 | 2130 | |
a5baffba | 2131 | /* XXX where to 'finish' the parsing pass? */ |
f900210a | 2132 | return parsed_req; |
2133 | } | |
2134 | ||
1cf238db | 2135 | void |
fcc444e3 | 2136 | ConnStateData::afterClientRead() |
c4b7a5a9 | 2137 | { |
3cae14a6 | 2138 | #if USE_OPENSSL |
d20cf186 AR |
2139 | if (parsingTlsHandshake) { |
2140 | parseTlsHandshake(); | |
3cae14a6 CT |
2141 | return; |
2142 | } | |
2143 | #endif | |
d20cf186 | 2144 | |
94439e4e | 2145 | /* Process next request */ |
e500cc89 | 2146 | if (pipeline.empty()) |
fcc444e3 | 2147 | fd_note(clientConnection->fd, "Reading next request"); |
c8be6d7b | 2148 | |
f35961af | 2149 | if (!clientParseRequests()) { |
9e008dda AJ |
2150 | if (!isOpen()) |
2151 | return; | |
f900210a | 2152 | /* |
2153 | * If the client here is half closed and we failed | |
2154 | * to parse a request, close the connection. | |
2155 | * The above check with connFinishedWithConn() only | |
2156 | * succeeds _if_ the buffer is empty which it won't | |
2157 | * be if we have an incomplete request. | |
f4a53cf7 | 2158 | * XXX: This duplicates ConnStateData::kick |
f900210a | 2159 | */ |
e500cc89 | 2160 | if (pipeline.empty() && commIsHalfClosed(clientConnection->fd)) { |
fcc444e3 | 2161 | debugs(33, 5, clientConnection << ": half-closed connection, no completed request parsed, connection closing."); |
73c36fd9 | 2162 | clientConnection->close(); |
ee6f0213 | 2163 | return; |
62e76326 | 2164 | } |
f900210a | 2165 | } |
ee6f0213 | 2166 | |
1cf238db | 2167 | if (!isOpen()) |
2e216b1d | 2168 | return; |
2169 | ||
f35961af | 2170 | clientAfterReadingRequests(); |
94439e4e | 2171 | } |
2172 | ||
63be0a78 | 2173 | /** |
2174 | * called when new request data has been read from the socket | |
39cb8c41 AR |
2175 | * |
2176 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
2177 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 2178 | */ |
39cb8c41 | 2179 | bool |
7e66d5e2 | 2180 | ConnStateData::handleReadData() |
94439e4e | 2181 | { |
5f8252d2 | 2182 | // if we are reading a body, stuff data into the body pipe |
2183 | if (bodyPipe != NULL) | |
39cb8c41 AR |
2184 | return handleRequestBodyData(); |
2185 | return true; | |
94439e4e | 2186 | } |
2187 | ||
63be0a78 | 2188 | /** |
fcc444e3 | 2189 | * called when new request body data has been buffered in inBuf |
63be0a78 | 2190 | * may close the connection if we were closing and piped everything out |
39cb8c41 AR |
2191 | * |
2192 | * \retval false called comm_close or setReplyToError (the caller should bail) | |
2193 | * \retval true we did not call comm_close or setReplyToError | |
63be0a78 | 2194 | */ |
39cb8c41 | 2195 | bool |
5f8252d2 | 2196 | ConnStateData::handleRequestBodyData() |
94439e4e | 2197 | { |
5f8252d2 | 2198 | assert(bodyPipe != NULL); |
2199 | ||
fcc444e3 | 2200 | if (bodyParser) { // chunked encoding |
be29ee33 | 2201 | if (const err_type error = handleChunkedRequestBody()) { |
39cb8c41 AR |
2202 | abortChunkedRequestBody(error); |
2203 | return false; | |
3ff65596 | 2204 | } |
39cb8c41 | 2205 | } else { // identity encoding |
73c36fd9 | 2206 | debugs(33,5, HERE << "handling plain request body for " << clientConnection); |
fcc444e3 | 2207 | const size_t putSize = bodyPipe->putMoreData(inBuf.c_str(), inBuf.length()); |
be29ee33 AJ |
2208 | if (putSize > 0) |
2209 | consumeInput(putSize); | |
2210 | ||
3ff65596 AR |
2211 | if (!bodyPipe->mayNeedMoreData()) { |
2212 | // BodyPipe will clear us automagically when we produced everything | |
2213 | bodyPipe = NULL; | |
2214 | } | |
2215 | } | |
2216 | ||
3ff65596 | 2217 | if (!bodyPipe) { |
73c36fd9 | 2218 | debugs(33,5, HERE << "produced entire request body for " << clientConnection); |
62e76326 | 2219 | |
cf6eb29e | 2220 | if (const char *reason = stoppedSending()) { |
5f8252d2 | 2221 | /* we've finished reading like good clients, |
2222 | * now do the close that initiateClose initiated. | |
5f8252d2 | 2223 | */ |
cf6eb29e | 2224 | debugs(33, 3, HERE << "closing for earlier sending error: " << reason); |
73c36fd9 | 2225 | clientConnection->close(); |
39cb8c41 AR |
2226 | return false; |
2227 | } | |
2228 | } | |
2229 | ||
2230 | return true; | |
2231 | } | |
2232 | ||
2233 | /// parses available chunked encoded body bytes, checks size, returns errors | |
2234 | err_type | |
be29ee33 | 2235 | ConnStateData::handleChunkedRequestBody() |
39cb8c41 | 2236 | { |
fcc444e3 | 2237 | debugs(33, 7, "chunked from " << clientConnection << ": " << inBuf.length()); |
39cb8c41 AR |
2238 | |
2239 | try { // the parser will throw on errors | |
2240 | ||
fcc444e3 | 2241 | if (inBuf.isEmpty()) // nothing to do |
39cb8c41 AR |
2242 | return ERR_NONE; |
2243 | ||
39cb8c41 | 2244 | BodyPipeCheckout bpc(*bodyPipe); |
fcc444e3 AJ |
2245 | bodyParser->setPayloadBuffer(&bpc.buf); |
2246 | const bool parsed = bodyParser->parse(inBuf); | |
2247 | inBuf = bodyParser->remaining(); // sync buffers | |
39cb8c41 | 2248 | bpc.checkIn(); |
39cb8c41 AR |
2249 | |
2250 | // dechunk then check: the size limit applies to _dechunked_ content | |
2251 | if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize())) | |
2252 | return ERR_TOO_BIG; | |
2253 | ||
2254 | if (parsed) { | |
2255 | finishDechunkingRequest(true); | |
2256 | Must(!bodyPipe); | |
2257 | return ERR_NONE; // nil bodyPipe implies body end for the caller | |
5f8252d2 | 2258 | } |
39cb8c41 AR |
2259 | |
2260 | // if chunk parser needs data, then the body pipe must need it too | |
fcc444e3 | 2261 | Must(!bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData()); |
39cb8c41 AR |
2262 | |
2263 | // if parser needs more space and we can consume nothing, we will stall | |
fcc444e3 | 2264 | Must(!bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent()); |
39cb8c41 AR |
2265 | } catch (...) { // TODO: be more specific |
2266 | debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status()); | |
2267 | return ERR_INVALID_REQ; | |
94439e4e | 2268 | } |
39cb8c41 AR |
2269 | |
2270 | debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status()); | |
2271 | return ERR_NONE; | |
2272 | } | |
2273 | ||
2274 | /// quit on errors related to chunked request body handling | |
2275 | void | |
2276 | ConnStateData::abortChunkedRequestBody(const err_type error) | |
2277 | { | |
2278 | finishDechunkingRequest(false); | |
2279 | ||
2280 | // XXX: The code below works if we fail during initial request parsing, | |
d5430dc8 | 2281 | // but if we fail when the server connection is used already, the server may send |
39cb8c41 AR |
2282 | // us its response too, causing various assertions. How to prevent that? |
2283 | #if WE_KNOW_HOW_TO_SEND_ERRORS | |
d3dddfb5 | 2284 | Http::StreamPointer context = pipeline.front(); |
39cb8c41 AR |
2285 | if (context != NULL && !context->http->out.offset) { // output nothing yet |
2286 | clientStreamNode *node = context->getClientReplyContext(); | |
2287 | clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw()); | |
2288 | assert(repContext); | |
955394ce | 2289 | const Http::StatusCode scode = (error == ERR_TOO_BIG) ? |
f11c8e2f | 2290 | Http::scPayloadTooLarge : HTTP_BAD_REQUEST; |
39cb8c41 AR |
2291 | repContext->setReplyToError(error, scode, |
2292 | repContext->http->request->method, | |
2293 | repContext->http->uri, | |
a3c6762c | 2294 | CachePeer, |
39cb8c41 | 2295 | repContext->http->request, |
fcc444e3 | 2296 | inBuf, NULL); |
39cb8c41 AR |
2297 | context->pullData(); |
2298 | } else { | |
2299 | // close or otherwise we may get stuck as nobody will notice the error? | |
73c36fd9 | 2300 | comm_reset_close(clientConnection); |
39cb8c41 AR |
2301 | } |
2302 | #else | |
2303 | debugs(33, 3, HERE << "aborting chunked request without error " << error); | |
73c36fd9 | 2304 | comm_reset_close(clientConnection); |
39cb8c41 | 2305 | #endif |
f35961af | 2306 | flags.readMore = false; |
5f8252d2 | 2307 | } |
55e44db9 | 2308 | |
5f8252d2 | 2309 | void |
1cf238db | 2310 | ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer ) |
5f8252d2 | 2311 | { |
cf6eb29e CT |
2312 | // request reader may get stuck waiting for space if nobody consumes body |
2313 | if (bodyPipe != NULL) | |
2314 | bodyPipe->enableAutoConsumption(); | |
2315 | ||
92ae4c86 | 2316 | // kids extend |
94439e4e | 2317 | } |
2318 | ||
63be0a78 | 2319 | /** general lifetime handler for HTTP requests */ |
1cf238db | 2320 | void |
2321 | ConnStateData::requestTimeout(const CommTimeoutCbParams &io) | |
7a2f978b | 2322 | { |
d5b97346 AJ |
2323 | if (!Comm::IsConnOpen(io.conn)) |
2324 | return; | |
2325 | ||
6b2b6cfe CT |
2326 | if (mayTunnelUnsupportedProto() && !receivedFirstByte_) { |
2327 | Http::StreamPointer context = pipeline.front(); | |
2328 | Must(context && context->http); | |
2329 | HttpRequest::Pointer request = context->http->request; | |
2330 | if (clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_REQUEST_START_TIMEOUT)) | |
2331 | return; | |
3248e962 | 2332 | } |
af57a2e3 | 2333 | /* |
62e76326 | 2334 | * Just close the connection to not confuse browsers |
6177a89f HN |
2335 | * using persistent connections. Some browsers open |
2336 | * a connection and then do not use it until much | |
62e76326 | 2337 | * later (presumeably because the request triggering |
2338 | * the open has already been completed on another | |
2339 | * connection) | |
2340 | */ | |
1cf238db | 2341 | debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired."); |
8d77a37c | 2342 | io.conn->close(); |
7a2f978b | 2343 | } |
2344 | ||
b5c39993 | 2345 | static void |
8d77a37c | 2346 | clientLifetimeTimeout(const CommTimeoutCbParams &io) |
b5c39993 | 2347 | { |
8d77a37c | 2348 | ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data); |
cb61ec47 AJ |
2349 | debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout"); |
2350 | debugs(33, DBG_IMPORTANT, "\t" << http->uri); | |
a981b360 | 2351 | http->logType.err.timedout = true; |
8d77a37c AJ |
2352 | if (Comm::IsConnOpen(io.conn)) |
2353 | io.conn->close(); | |
b5c39993 | 2354 | } |
2355 | ||
94bfd31f | 2356 | ConnStateData::ConnStateData(const MasterXaction::Pointer &xact) : |
f53969cc | 2357 | AsyncJob("ConnStateData"), // kids overwrite |
fcc444e3 AJ |
2358 | Server(xact), |
2359 | bodyParser(nullptr), | |
cb4f4424 | 2360 | #if USE_OPENSSL |
f53969cc | 2361 | sslBumpMode(Ssl::bumpEnd), |
4579a6d0 | 2362 | #endif |
f53969cc | 2363 | needProxyProtocolHeader_(false), |
4579a6d0 | 2364 | #if USE_OPENSSL |
f53969cc | 2365 | switchedToHttps_(false), |
d20cf186 | 2366 | parsingTlsHandshake(false), |
82b04b16 | 2367 | tlsConnectPort(0), |
f53969cc SM |
2368 | sslServerBump(NULL), |
2369 | signAlgorithm(Ssl::algSignTrusted), | |
94bfd31f | 2370 | #endif |
f53969cc | 2371 | stoppedSending_(NULL), |
fcc444e3 | 2372 | stoppedReceiving_(NULL) |
c8be6d7b | 2373 | { |
4579a6d0 AJ |
2374 | flags.readMore = true; // kids may overwrite |
2375 | flags.swanSang = false; | |
2376 | ||
94bfd31f AJ |
2377 | pinning.host = NULL; |
2378 | pinning.port = -1; | |
2379 | pinning.pinned = false; | |
2380 | pinning.auth = false; | |
2381 | pinning.zeroReply = false; | |
2382 | pinning.peer = NULL; | |
2383 | ||
2384 | // store the details required for creating more MasterXaction objects as new requests come in | |
94bfd31f AJ |
2385 | log_addr = xact->tcpClient->remote; |
2386 | log_addr.applyMask(Config.Addrs.client_netmask); | |
d442618d AJ |
2387 | |
2388 | // register to receive notice of Squid signal events | |
2389 | // which may affect long persisting client connections | |
b856803f | 2390 | registerRunner(); |
92ae4c86 AR |
2391 | } |
2392 | ||
2393 | void | |
2394 | ConnStateData::start() | |
2395 | { | |
2396 | BodyProducer::start(); | |
2397 | HttpControlMsgSink::start(); | |
2398 | ||
5529ca8a | 2399 | if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF && |
94bfd31f | 2400 | (transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) { |
5529ca8a | 2401 | #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT) |
2402 | int i = IP_PMTUDISC_DONT; | |
b69e9ffa AJ |
2403 | if (setsockopt(clientConnection->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof(i)) < 0) { |
2404 | int xerrno = errno; | |
2405 | debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection << " : " << xstrerr(xerrno)); | |
2406 | } | |
5529ca8a | 2407 | #else |
9bb67276 | 2408 | static bool reported = false; |
5529ca8a | 2409 | |
2410 | if (!reported) { | |
9bb67276 AJ |
2411 | debugs(33, DBG_IMPORTANT, "NOTICE: Path MTU discovery disabling is not supported on your platform."); |
2412 | reported = true; | |
5529ca8a | 2413 | } |
89aec9b6 AJ |
2414 | #endif |
2415 | } | |
5529ca8a | 2416 | |
89aec9b6 | 2417 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
94bfd31f AJ |
2418 | AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, ConnStateData::connStateClosed); |
2419 | comm_add_close_handler(clientConnection->fd, call); | |
5529ca8a | 2420 | |
42cbf844 AJ |
2421 | needProxyProtocolHeader_ = port->flags.proxySurrogate; |
2422 | if (needProxyProtocolHeader_) { | |
2423 | if (!proxyProtocolValidateClient()) // will close the connection on failure | |
2424 | return; | |
2425 | } else | |
2426 | whenClientIpKnown(); | |
2427 | ||
2428 | } | |
2429 | ||
2430 | void | |
2431 | ConnStateData::whenClientIpKnown() | |
2432 | { | |
89aec9b6 | 2433 | if (Config.onoff.log_fqdn) |
94bfd31f | 2434 | fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS); |
89aec9b6 AJ |
2435 | |
2436 | #if USE_IDENT | |
2437 | if (Ident::TheConfig.identLookup) { | |
2438 | ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL); | |
92ae4c86 AR |
2439 | identChecklist.src_addr = clientConnection->remote; |
2440 | identChecklist.my_addr = clientConnection->local; | |
06bf5384 | 2441 | if (identChecklist.fastCheck().allowed()) |
92ae4c86 | 2442 | Ident::Start(clientConnection, clientIdentDone, this); |
89aec9b6 | 2443 | } |
5529ca8a | 2444 | #endif |
2445 | ||
94bfd31f | 2446 | clientdbEstablished(clientConnection->remote, 1); |
5529ca8a | 2447 | |
9a0a18de | 2448 | #if USE_DELAY_POOLS |
92ae4c86 | 2449 | fd_table[clientConnection->fd].clientInfo = NULL; |
b4cd430a | 2450 | |
e37f1cd4 EB |
2451 | if (!Config.onoff.client_db) |
2452 | return; // client delay pools require client_db | |
b4cd430a | 2453 | |
e37f1cd4 EB |
2454 | const auto &pools = ClientDelayPools::Instance()->pools; |
2455 | if (pools.size()) { | |
2efeb0b7 | 2456 | ACLFilledChecklist ch(NULL, NULL, NULL); |
b4cd430a | 2457 | |
2efeb0b7 AJ |
2458 | // TODO: we check early to limit error response bandwith but we |
2459 | // should recheck when we can honor delay_pool_uses_indirect | |
2460 | // TODO: we should also pass the port details for myportname here. | |
92ae4c86 AR |
2461 | ch.src_addr = clientConnection->remote; |
2462 | ch.my_addr = clientConnection->local; | |
b4cd430a | 2463 | |
95dc7ff4 | 2464 | for (unsigned int pool = 0; pool < pools.size(); ++pool) { |
b4cd430a | 2465 | |
2efeb0b7 | 2466 | /* pools require explicit 'allow' to assign a client into them */ |
b27668ec EB |
2467 | if (pools[pool]->access) { |
2468 | ch.changeAcl(pools[pool]->access); | |
2efeb0b7 | 2469 | allow_t answer = ch.fastCheck(); |
06bf5384 | 2470 | if (answer.allowed()) { |
2efeb0b7 AJ |
2471 | |
2472 | /* request client information from db after we did all checks | |
2473 | this will save hash lookup if client failed checks */ | |
92ae4c86 | 2474 | ClientInfo * cli = clientdbGetInfo(clientConnection->remote); |
2efeb0b7 AJ |
2475 | assert(cli); |
2476 | ||
2477 | /* put client info in FDE */ | |
92ae4c86 | 2478 | fd_table[clientConnection->fd].clientInfo = cli; |
2efeb0b7 AJ |
2479 | |
2480 | /* setup write limiter for this request */ | |
2481 | const double burst = floor(0.5 + | |
b27668ec EB |
2482 | (pools[pool]->highwatermark * Config.ClientDelay.initial)/100.0); |
2483 | cli->setWriteLimiter(pools[pool]->rate, burst, pools[pool]->highwatermark); | |
2efeb0b7 AJ |
2484 | break; |
2485 | } else { | |
2486 | debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer); | |
2487 | } | |
b4cd430a CT |
2488 | } |
2489 | } | |
2490 | } | |
2491 | #endif | |
92ae4c86 AR |
2492 | |
2493 | // kids must extend to actually start doing something (e.g., reading) | |
7a2f978b | 2494 | } |
2495 | ||
e7ce227f | 2496 | /** Handle a new connection on an HTTP socket. */ |
92ae4c86 AR |
2497 | void |
2498 | httpAccept(const CommAcceptCbParams ¶ms) | |
6afea0a4 AR |
2499 | { |
2500 | MasterXaction::Pointer xact = params.xaction; | |
2501 | AnyP::PortCfgPointer s = xact->squidPort; | |
2502 | ||
2503 | // NP: it is possible the port was reconfigured when the call or accept() was queued. | |
2504 | ||
2505 | if (params.flag != Comm::OK) { | |
2506 | // Its possible the call was still queued when the client disconnected | |
e7ce227f | 2507 | debugs(33, 2, s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
6afea0a4 AR |
2508 | return; |
2509 | } | |
2510 | ||
e7ce227f | 2511 | debugs(33, 4, params.conn << ": accepted"); |
92ae4c86 | 2512 | fd_note(params.conn->fd, "client http connect"); |
6afea0a4 | 2513 | |
e7ce227f | 2514 | if (s->tcp_keepalive.enabled) |
6afea0a4 | 2515 | commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); |
6afea0a4 | 2516 | |
e7ce227f | 2517 | ++incoming_sockets_accepted; |
6afea0a4 AR |
2518 | |
2519 | // Socket is ready, setup the connection manager to start using it | |
5e77f674 AJ |
2520 | auto *srv = Http::NewServer(xact); |
2521 | AsyncJob::Start(srv); // usually async-calls readSomeData() | |
7a2f978b | 2522 | } |
2523 | ||
86f77270 | 2524 | /// Create TLS connection structure and update fd_table |
157c5ace | 2525 | static bool |
0476ec45 | 2526 | httpsCreate(const Comm::ConnectionPointer &conn, const Security::ContextPointer &ctx) |
ae7ff0b8 | 2527 | { |
86f77270 | 2528 | if (Security::CreateServerSession(ctx, conn, "client https start")) { |
ca2526bd | 2529 | debugs(33, 5, "will negotiate TLS on " << conn); |
157c5ace | 2530 | return true; |
ae7ff0b8 | 2531 | } |
2532 | ||
51e09c08 | 2533 | debugs(33, DBG_IMPORTANT, "ERROR: could not create TLS server context for " << conn); |
b3a8ae1b | 2534 | conn->close(); |
157c5ace | 2535 | return false; |
ae7ff0b8 | 2536 | } |
2537 | ||
3248e962 | 2538 | /** |
44352c16 | 2539 | * |
1700fab7 AJ |
2540 | * \retval 1 on success |
2541 | * \retval 0 when needs more data | |
2542 | * \retval -1 on error | |
3248e962 | 2543 | */ |
1700fab7 | 2544 | static int |
51e09c08 | 2545 | tlsAttemptHandshake(ConnStateData *conn, PF *callback) |
1f7c9178 | 2546 | { |
1700fab7 | 2547 | // TODO: maybe throw instead of returning -1 |
51e09c08 | 2548 | // see https://github.com/squid-cache/squid/pull/81#discussion_r153053278 |
d620ae0e | 2549 | int fd = conn->clientConnection->fd; |
51e09c08 | 2550 | auto session = fd_table[fd].ssl.get(); |
1f7c9178 | 2551 | |
e9447f01 | 2552 | errno = 0; |
62e76326 | 2553 | |
51e09c08 AJ |
2554 | #if USE_OPENSSL |
2555 | const auto ret = SSL_accept(session); | |
2556 | if (ret > 0) | |
1700fab7 | 2557 | return 1; |
62e76326 | 2558 | |
51e09c08 AJ |
2559 | const int xerrno = errno; |
2560 | const auto ssl_error = SSL_get_error(session, ret); | |
62e76326 | 2561 | |
51e09c08 | 2562 | switch (ssl_error) { |
62e76326 | 2563 | |
51e09c08 AJ |
2564 | case SSL_ERROR_WANT_READ: |
2565 | Comm::SetSelect(fd, COMM_SELECT_READ, callback, (callback ? conn : nullptr), 0); | |
1700fab7 | 2566 | return 0; |
6de9e64b | 2567 | |
51e09c08 AJ |
2568 | case SSL_ERROR_WANT_WRITE: |
2569 | Comm::SetSelect(fd, COMM_SELECT_WRITE, callback, (callback ? conn : nullptr), 0); | |
1700fab7 | 2570 | return 0; |
6de9e64b | 2571 | |
51e09c08 AJ |
2572 | case SSL_ERROR_SYSCALL: |
2573 | if (ret == 0) { | |
2574 | debugs(83, 2, "Error negotiating SSL connection on FD " << fd << ": Aborted by client: " << ssl_error); | |
2575 | } else { | |
2576 | debugs(83, (xerrno == ECONNRESET) ? 1 : 2, "Error negotiating SSL connection on FD " << fd << ": " << | |
2577 | (xerrno == 0 ? Security::ErrorString(ssl_error) : xstrerr(xerrno))); | |
62e76326 | 2578 | } |
51e09c08 AJ |
2579 | break; |
2580 | ||
2581 | case SSL_ERROR_ZERO_RETURN: | |
2582 | debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " << fd << ": Closed by client"); | |
2583 | break; | |
2584 | ||
2585 | default: | |
2586 | debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " << | |
2587 | fd << ": " << Security::ErrorString(ssl_error) << | |
2588 | " (" << ssl_error << "/" << ret << ")"); | |
2589 | } | |
62e76326 | 2590 | |
51e09c08 AJ |
2591 | #elif USE_GNUTLS |
2592 | ||
2593 | const auto x = gnutls_handshake(session); | |
2594 | if (x == GNUTLS_E_SUCCESS) | |
1700fab7 | 2595 | return 1; |
51e09c08 AJ |
2596 | |
2597 | if (gnutls_error_is_fatal(x)) { | |
2598 | debugs(83, 2, "Error negotiating TLS on " << conn->clientConnection << ": Aborted by client: " << Security::ErrorString(x)); | |
2599 | ||
2600 | } else if (x == GNUTLS_E_INTERRUPTED || x == GNUTLS_E_AGAIN) { | |
2601 | const auto ioAction = (gnutls_record_get_direction(session)==0 ? COMM_SELECT_READ : COMM_SELECT_WRITE); | |
2602 | Comm::SetSelect(fd, ioAction, callback, (callback ? conn : nullptr), 0); | |
1700fab7 | 2603 | return 0; |
1f7c9178 | 2604 | } |
51e09c08 AJ |
2605 | |
2606 | #else | |
2607 | // Performing TLS handshake should never be reachable without a TLS/SSL library. | |
2608 | (void)session; // avoid compiler and static analysis complaints | |
2609 | fatal("FATAL: HTTPS not supported by this Squid."); | |
2610 | #endif | |
2611 | ||
1700fab7 | 2612 | return -1; |
d620ae0e CT |
2613 | } |
2614 | ||
2615 | /** negotiate an SSL connection */ | |
2616 | static void | |
2617 | clientNegotiateSSL(int fd, void *data) | |
2618 | { | |
2619 | ConnStateData *conn = (ConnStateData *)data; | |
51e09c08 | 2620 | |
1700fab7 AJ |
2621 | const int ret = tlsAttemptHandshake(conn, clientNegotiateSSL); |
2622 | if (ret <= 0) { | |
2623 | if (ret < 0) // An error | |
2624 | conn->clientConnection->close(); | |
d620ae0e | 2625 | return; |
1700fab7 | 2626 | } |
62e76326 | 2627 | |
ad23e748 | 2628 | Security::SessionPointer session(fd_table[fd].ssl); |
51e09c08 AJ |
2629 | |
2630 | #if USE_OPENSSL | |
ad23e748 AJ |
2631 | if (Security::SessionIsResumed(session)) { |
2632 | debugs(83, 2, "Session " << SSL_get_session(session.get()) << | |
2633 | " reused on FD " << fd << " (" << fd_table[fd].ipaddr << | |
2634 | ":" << (int)fd_table[fd].remote_port << ")"); | |
6de9e64b | 2635 | } else { |
014adac1 | 2636 | if (Debug::Enabled(83, 4)) { |
6de9e64b | 2637 | /* Write out the SSL session details.. actually the call below, but |
2638 | * OpenSSL headers do strange typecasts confusing GCC.. */ | |
2639 | /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */ | |
afdd443f | 2640 | #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L |
ad23e748 AJ |
2641 | PEM_ASN1_write(reinterpret_cast<i2d_of_void *>(i2d_SSL_SESSION), |
2642 | PEM_STRING_SSL_SESSION, debug_log, | |
bba00f17 | 2643 | reinterpret_cast<char *>(SSL_get_session(session.get())), |
ad23e748 | 2644 | nullptr, nullptr, 0, nullptr, nullptr); |
2930f303 | 2645 | |
0fd2205b | 2646 | #elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1) |
2930f303 | 2647 | |
0fd2205b | 2648 | /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here. |
2649 | * This is caused by an unpredicatble gcc behaviour on a cast of the first argument | |
2650 | * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it, | |
2651 | * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1. | |
2652 | * Because there are two possible usable cast, if you get an error here, try the other | |
2653 | * commented line. */ | |
2654 | ||
ad23e748 AJ |
2655 | PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, |
2656 | debug_log, | |
bba00f17 | 2657 | reinterpret_cast<char *>(SSL_get_session(session.get())), |
ad23e748 AJ |
2658 | nullptr, nullptr, 0, nullptr, nullptr); |
2659 | /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, | |
2660 | debug_log, | |
bba00f17 | 2661 | reinterpret_cast<char *>(SSL_get_session(session.get())), |
ad23e748 AJ |
2662 | nullptr, nullptr, 0, nullptr, nullptr); |
2663 | */ | |
0e33d58c | 2664 | #else |
ad23e748 | 2665 | debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source."); |
0fd2205b | 2666 | |
0e33d58c | 2667 | #endif |
6de9e64b | 2668 | /* Note: This does not automatically fflush the log file.. */ |
2669 | } | |
2670 | ||
ad23e748 AJ |
2671 | debugs(83, 2, "New session " << SSL_get_session(session.get()) << |
2672 | " on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << | |
2673 | fd_table[fd].remote_port << ")"); | |
6de9e64b | 2674 | } |
51e09c08 AJ |
2675 | #else |
2676 | debugs(83, 2, "TLS session reuse not yet implemented."); | |
2677 | #endif | |
6de9e64b | 2678 | |
2bcab852 | 2679 | // Connection established. Retrieve TLS connection parameters for logging. |
ad23e748 | 2680 | conn->clientConnection->tlsNegotiations()->retrieveNegotiatedInfo(session); |
1f7c9178 | 2681 | |
51e09c08 | 2682 | #if USE_OPENSSL |
ad23e748 | 2683 | X509 *client_cert = SSL_get_peer_certificate(session.get()); |
62e76326 | 2684 | |
ad23e748 AJ |
2685 | if (client_cert) { |
2686 | debugs(83, 3, "FD " << fd << " client certificate: subject: " << | |
bf8fe701 | 2687 | X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0)); |
2688 | ||
ad23e748 | 2689 | debugs(83, 3, "FD " << fd << " client certificate: issuer: " << |
bf8fe701 | 2690 | X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0)); |
1f7c9178 | 2691 | |
62e76326 | 2692 | X509_free(client_cert); |
1f7c9178 | 2693 | } else { |
51e09c08 | 2694 | debugs(83, 5, "FD " << fd << " has no client certificate."); |
1f7c9178 | 2695 | } |
51e09c08 AJ |
2696 | #else |
2697 | debugs(83, 2, "Client certificate requesting not yet implemented."); | |
2698 | #endif | |
1f7c9178 | 2699 | |
a46d2c0e | 2700 | conn->readSomeData(); |
1f7c9178 | 2701 | } |
2702 | ||
379e8c1c | 2703 | /** |
0476ec45 AJ |
2704 | * If Security::ContextPointer is given, starts reading the TLS handshake. |
2705 | * Otherwise, calls switchToHttps to generate a dynamic Security::ContextPointer. | |
379e8c1c AR |
2706 | */ |
2707 | static void | |
0476ec45 | 2708 | httpsEstablish(ConnStateData *connState, const Security::ContextPointer &ctx) |
379e8c1c | 2709 | { |
379e8c1c AR |
2710 | assert(connState); |
2711 | const Comm::ConnectionPointer &details = connState->clientConnection; | |
2712 | ||
0476ec45 | 2713 | if (!ctx || !httpsCreate(details, ctx)) |
379e8c1c AR |
2714 | return; |
2715 | ||
7a957a93 AR |
2716 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; |
2717 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer, | |
87f237a9 | 2718 | connState, ConnStateData::requestTimeout); |
379e8c1c AR |
2719 | commSetConnTimeout(details, Config.Timeout.request, timeoutCall); |
2720 | ||
36048c42 | 2721 | Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0); |
379e8c1c AR |
2722 | } |
2723 | ||
51e09c08 | 2724 | #if USE_OPENSSL |
379e8c1c | 2725 | /** |
87f237a9 | 2726 | * A callback function to use with the ACLFilledChecklist callback. |
379e8c1c AR |
2727 | */ |
2728 | static void | |
2729 | httpsSslBumpAccessCheckDone(allow_t answer, void *data) | |
2730 | { | |
2731 | ConnStateData *connState = (ConnStateData *) data; | |
2732 | ||
7a957a93 | 2733 | // if the connection is closed or closing, just return. |
379e8c1c AR |
2734 | if (!connState->isOpen()) |
2735 | return; | |
2736 | ||
06bf5384 | 2737 | if (answer.allowed()) { |
bf352fb2 | 2738 | debugs(33, 2, "sslBump action " << Ssl::bumpMode(answer.kind) << "needed for " << connState->clientConnection); |
08097970 | 2739 | connState->sslBumpMode = static_cast<Ssl::BumpMode>(answer.kind); |
379e8c1c | 2740 | } else { |
bf352fb2 CT |
2741 | debugs(33, 3, "sslBump not needed for " << connState->clientConnection); |
2742 | connState->sslBumpMode = Ssl::bumpSplice; | |
2743 | } | |
2744 | ||
2745 | if (connState->sslBumpMode == Ssl::bumpTerminate) { | |
2746 | connState->clientConnection->close(); | |
2747 | return; | |
9e104535 | 2748 | } |
bf352fb2 | 2749 | |
efda53c5 CT |
2750 | if (!connState->fakeAConnectRequest("ssl-bump", connState->inBuf)) |
2751 | connState->clientConnection->close(); | |
a30b692c | 2752 | } |
51e09c08 | 2753 | #endif |
379e8c1c | 2754 | |
63be0a78 | 2755 | /** handle a new HTTPS connection */ |
1f7c9178 | 2756 | static void |
449f0115 | 2757 | httpsAccept(const CommAcceptCbParams ¶ms) |
1f7c9178 | 2758 | { |
94bfd31f AJ |
2759 | MasterXaction::Pointer xact = params.xaction; |
2760 | const AnyP::PortCfgPointer s = xact->squidPort; | |
2761 | ||
c0ff709f | 2762 | // NP: it is possible the port was reconfigured when the call or accept() was queued. |
c4b7a5a9 | 2763 | |
c8407295 | 2764 | if (params.flag != Comm::OK) { |
cbff89ba | 2765 | // Its possible the call was still queued when the client disconnected |
449f0115 | 2766 | debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno)); |
62e76326 | 2767 | return; |
c4b7a5a9 | 2768 | } |
62e76326 | 2769 | |
449f0115 AJ |
2770 | debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation."); |
2771 | fd_note(params.conn->fd, "client https connect"); | |
62e76326 | 2772 | |
859741ed AJ |
2773 | if (s->tcp_keepalive.enabled) { |
2774 | commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout); | |
b2130d58 | 2775 | } |
95dc7ff4 | 2776 | ++incoming_sockets_accepted; |
62e76326 | 2777 | |
89aec9b6 | 2778 | // Socket is ready, setup the connection manager to start using it |
5e77f674 AJ |
2779 | auto *srv = Https::NewServer(xact); |
2780 | AsyncJob::Start(srv); // usually async-calls postHttpsAccept() | |
92ae4c86 | 2781 | } |
62e76326 | 2782 | |
92ae4c86 AR |
2783 | void |
2784 | ConnStateData::postHttpsAccept() | |
2785 | { | |
b3cb9958 | 2786 | if (port->flags.tunnelSslBumping) { |
51e09c08 | 2787 | #if USE_OPENSSL |
e7ce227f | 2788 | debugs(33, 5, "accept transparent connection: " << clientConnection); |
62e76326 | 2789 | |
379e8c1c | 2790 | if (!Config.accessList.ssl_bump) { |
b3cb9958 | 2791 | httpsSslBumpAccessCheckDone(ACCESS_DENIED, this); |
379e8c1c AR |
2792 | return; |
2793 | } | |
87f237a9 | 2794 | |
5ceaee75 CT |
2795 | MasterXaction::Pointer mx = new MasterXaction(XactionInitiator::initClient); |
2796 | mx->tcpClient = clientConnection; | |
379e8c1c | 2797 | // Create a fake HTTP request for ssl_bump ACL check, |
38450a50 | 2798 | // using tproxy/intercept provided destination IP and port. |
5ceaee75 | 2799 | HttpRequest *request = new HttpRequest(mx); |
379e8c1c | 2800 | static char ip[MAX_IPSTRLEN]; |
92ae4c86 | 2801 | assert(clientConnection->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION)); |
851feda6 | 2802 | request->url.host(clientConnection->local.toStr(ip, sizeof(ip))); |
5c51bffb | 2803 | request->url.port(clientConnection->local.port()); |
b3cb9958 | 2804 | request->myportname = port->name; |
87f237a9 | 2805 | |
379e8c1c | 2806 | ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL); |
92ae4c86 | 2807 | acl_checklist->src_addr = clientConnection->remote; |
b3cb9958 | 2808 | acl_checklist->my_addr = port->s; |
d4ddb3e6 CT |
2809 | // Build a local AccessLogEntry to allow requiresAle() acls work |
2810 | acl_checklist->al = new AccessLogEntry; | |
2811 | acl_checklist->al->cache.start_time = current_time; | |
2812 | acl_checklist->al->tcpClient = clientConnection; | |
2813 | acl_checklist->al->cache.port = port; | |
2814 | acl_checklist->al->cache.caddr = log_addr; | |
542e1a7a | 2815 | HTTPMSGUNLOCK(acl_checklist->al->request); |
d4ddb3e6 CT |
2816 | acl_checklist->al->request = request; |
2817 | HTTPMSGLOCK(acl_checklist->al->request); | |
cb365059 EB |
2818 | Http::StreamPointer context = pipeline.front(); |
2819 | ClientHttpRequest *http = context ? context->http : nullptr; | |
2820 | const char *log_uri = http ? http->log_uri : nullptr; | |
2821 | acl_checklist->syncAle(request, log_uri); | |
b3cb9958 | 2822 | acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, this); |
51e09c08 AJ |
2823 | #else |
2824 | fatal("FATAL: SSL-Bump requires --with-openssl"); | |
2825 | #endif | |
379e8c1c AR |
2826 | return; |
2827 | } else { | |
0476ec45 | 2828 | httpsEstablish(this, port->secure.staticContext); |
379e8c1c | 2829 | } |
1f7c9178 | 2830 | } |
2831 | ||
51e09c08 | 2832 | #if USE_OPENSSL |
95d2589c | 2833 | void |
24438ec5 | 2834 | ConnStateData::sslCrtdHandleReplyWrapper(void *data, const Helper::Reply &reply) |
ae7ff0b8 | 2835 | { |
95d2589c CT |
2836 | ConnStateData * state_data = (ConnStateData *)(data); |
2837 | state_data->sslCrtdHandleReply(reply); | |
2838 | } | |
ae7ff0b8 | 2839 | |
95d2589c | 2840 | void |
24438ec5 | 2841 | ConnStateData::sslCrtdHandleReply(const Helper::Reply &reply) |
95d2589c | 2842 | { |
b418d9c8 CT |
2843 | if (!isOpen()) { |
2844 | debugs(33, 3, "Connection gone while waiting for ssl_crtd helper reply; helper reply:" << reply); | |
2845 | return; | |
2846 | } | |
2847 | ||
2428ce02 | 2848 | if (reply.result == Helper::BrokenHelper) { |
5955f162 AJ |
2849 | debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply); |
2850 | } else if (!reply.other().hasContent()) { | |
2851 | debugs(1, DBG_IMPORTANT, HERE << "\"ssl_crtd\" helper returned <NULL> reply."); | |
95d2589c | 2852 | } else { |
ff2d7d92 | 2853 | Ssl::CrtdMessage reply_message(Ssl::CrtdMessage::REPLY); |
0272dd08 | 2854 | if (reply_message.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK) { |
fb2178bb | 2855 | debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect"); |
95d2589c | 2856 | } else { |
2428ce02 | 2857 | if (reply.result != Helper::Okay) { |
fb2178bb | 2858 | debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody()); |
95d2589c | 2859 | } else { |
fb2178bb | 2860 | debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd"); |
a9c2dd2f | 2861 | if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) { |
d620ae0e | 2862 | doPeekAndSpliceStep(); |
33cc0629 | 2863 | auto ssl = fd_table[clientConnection->fd].ssl.get(); |
d620ae0e CT |
2864 | bool ret = Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl, reply_message.getBody().c_str(), *port); |
2865 | if (!ret) | |
e4f14091 | 2866 | debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode"); |
d8f0ceab | 2867 | |
1c1fae0f | 2868 | Security::ContextPointer ctx(Security::GetFrom(fd_table[clientConnection->fd].ssl)); |
b23f5f9c | 2869 | Ssl::configureUnconfiguredSslContext(ctx, signAlgorithm, *port); |
d620ae0e | 2870 | } else { |
cf487124 | 2871 | Security::ContextPointer ctx(Ssl::GenerateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str(), port->secure, (signAlgorithm == Ssl::algSignTrusted))); |
5107d2c4 CT |
2872 | if (ctx && !sslBumpCertKey.isEmpty()) |
2873 | storeTlsContextToCache(sslBumpCertKey, ctx); | |
2874 | getSslContextDone(ctx); | |
d620ae0e | 2875 | } |
95d2589c CT |
2876 | return; |
2877 | } | |
2878 | } | |
2879 | } | |
0476ec45 AJ |
2880 | Security::ContextPointer nil; |
2881 | getSslContextDone(nil); | |
95d2589c | 2882 | } |
ae7ff0b8 | 2883 | |
06997a38 | 2884 | void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties) |
fb2178bb | 2885 | { |
69f69080 | 2886 | certProperties.commonName = sslCommonName_.isEmpty() ? sslConnectHostOrIp.termedBuf() : sslCommonName_.c_str(); |
fb2178bb | 2887 | |
5107d2c4 CT |
2888 | const bool connectedOk = sslServerBump && sslServerBump->connectedOk(); |
2889 | if (connectedOk) { | |
fd4624d7 | 2890 | if (X509 *mimicCert = sslServerBump->serverCert.get()) |
59a49556 CT |
2891 | certProperties.mimicCert.resetAndLock(mimicCert); |
2892 | ||
b248c2a3 | 2893 | ACLFilledChecklist checklist(NULL, sslServerBump->request.getRaw(), |
59a49556 | 2894 | clientConnection != NULL ? clientConnection->rfc931 : dash_str); |
088f0761 | 2895 | checklist.sslErrors = cbdataReference(sslServerBump->sslErrors()); |
59a49556 CT |
2896 | |
2897 | for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) { | |
7a957a93 | 2898 | // If the algorithm already set, then ignore it. |
a06042fa | 2899 | if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) || |
87f237a9 A |
2900 | (ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) || |
2901 | (ca->alg == Ssl::algSetValidBefore && certProperties.setValidBefore) ) | |
a06042fa CT |
2902 | continue; |
2903 | ||
06bf5384 | 2904 | if (ca->aclList && checklist.fastCheck(ca->aclList).allowed()) { |
59a49556 CT |
2905 | const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg]; |
2906 | const char *param = ca->param; | |
87f237a9 | 2907 | |
7a957a93 AR |
2908 | // For parameterless CN adaptation, use hostname from the |
2909 | // CONNECT request. | |
a06042fa | 2910 | if (ca->alg == Ssl::algSetCommonName) { |
59a49556 CT |
2911 | if (!param) |
2912 | param = sslConnectHostOrIp.termedBuf(); | |
2913 | certProperties.commonName = param; | |
2914 | certProperties.setCommonName = true; | |
87f237a9 | 2915 | } else if (ca->alg == Ssl::algSetValidAfter) |
59a49556 | 2916 | certProperties.setValidAfter = true; |
87f237a9 | 2917 | else if (ca->alg == Ssl::algSetValidBefore) |
59a49556 CT |
2918 | certProperties.setValidBefore = true; |
2919 | ||
87f237a9 | 2920 | debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " << |
8f9720ce | 2921 | alg << " param: " << (param ? param : "-")); |
aebe6888 | 2922 | } |
fb2178bb | 2923 | } |
aebe6888 | 2924 | |
59a49556 CT |
2925 | certProperties.signAlgorithm = Ssl::algSignEnd; |
2926 | for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) { | |
06bf5384 | 2927 | if (sg->aclList && checklist.fastCheck(sg->aclList).allowed()) { |
59a49556 CT |
2928 | certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg; |
2929 | break; | |
2930 | } | |
aebe6888 | 2931 | } |
6b2b6cfe CT |
2932 | } else {// did not try to connect (e.g. client-first) or failed to connect |
2933 | // In case of an error while connecting to the secure server, use a | |
2934 | // trusted certificate, with no mimicked fields and no adaptation | |
2935 | // algorithms. There is nothing we can mimic, so we want to minimize the | |
2936 | // number of warnings the user will have to see to get to the error page. | |
2937 | // We will close the connection, so that the trust is not extended to | |
2938 | // non-Squid content. | |
59a49556 | 2939 | certProperties.signAlgorithm = Ssl::algSignTrusted; |
aebe6888 CT |
2940 | } |
2941 | ||
10d914f6 | 2942 | assert(certProperties.signAlgorithm != Ssl::algSignEnd); |
aebe6888 CT |
2943 | |
2944 | if (certProperties.signAlgorithm == Ssl::algSignUntrusted) { | |
51e09c08 AJ |
2945 | assert(port->secure.untrustedSigningCa.cert); |
2946 | certProperties.signWithX509.resetAndLock(port->secure.untrustedSigningCa.cert.get()); | |
2947 | certProperties.signWithPkey.resetAndLock(port->secure.untrustedSigningCa.pkey.get()); | |
87f237a9 | 2948 | } else { |
51e09c08 AJ |
2949 | assert(port->secure.signingCa.cert.get()); |
2950 | certProperties.signWithX509.resetAndLock(port->secure.signingCa.cert.get()); | |
aebe6888 | 2951 | |
51e09c08 AJ |
2952 | if (port->secure.signingCa.pkey) |
2953 | certProperties.signWithPkey.resetAndLock(port->secure.signingCa.pkey.get()); | |
aebe6888 CT |
2954 | } |
2955 | signAlgorithm = certProperties.signAlgorithm; | |
3c26b00a CT |
2956 | |
2957 | certProperties.signHash = Ssl::DefaultSignHash; | |
fb2178bb CT |
2958 | } |
2959 | ||
5107d2c4 CT |
2960 | Security::ContextPointer |
2961 | ConnStateData::getTlsContextFromCache(const SBuf &cacheKey, const Ssl::CertificateProperties &certProperties) | |
2962 | { | |
2963 | debugs(33, 5, "Finding SSL certificate for " << cacheKey << " in cache"); | |
2964 | Ssl::LocalContextStorage * ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s); | |
2965 | if (Security::ContextPointer *ctx = ssl_ctx_cache ? ssl_ctx_cache->get(cacheKey) : nullptr) { | |
2966 | if (Ssl::verifySslCertificate(*ctx, certProperties)) { | |
2967 | debugs(33, 5, "Cached SSL certificate for " << certProperties.commonName << " is valid"); | |
2968 | return *ctx; | |
2969 | } else { | |
2970 | debugs(33, 5, "Cached SSL certificate for " << certProperties.commonName << " is out of date. Delete this certificate from cache"); | |
2971 | if (ssl_ctx_cache) | |
2972 | ssl_ctx_cache->del(cacheKey); | |
2973 | } | |
2974 | } | |
2975 | return Security::ContextPointer(nullptr); | |
2976 | } | |
2977 | ||
2978 | void | |
2979 | ConnStateData::storeTlsContextToCache(const SBuf &cacheKey, Security::ContextPointer &ctx) | |
2980 | { | |
2981 | Ssl::LocalContextStorage *ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s); | |
2982 | if (!ssl_ctx_cache || !ssl_ctx_cache->add(cacheKey, new Security::ContextPointer(ctx))) { | |
2983 | // If it is not in storage delete after using. Else storage deleted it. | |
2984 | fd_table[clientConnection->fd].dynamicTlsContext = ctx; | |
2985 | } | |
2986 | } | |
2987 | ||
1ce2822d | 2988 | void |
95d2589c CT |
2989 | ConnStateData::getSslContextStart() |
2990 | { | |
08a8a70b AR |
2991 | // If we are called, then CONNECT has succeeded. Finalize it. |
2992 | if (auto xact = pipeline.front()) { | |
2993 | if (xact->http && xact->http->request && xact->http->request->method == Http::METHOD_CONNECT) | |
2994 | xact->finished(); | |
2995 | // cannot proceed with encryption if requests wait for plain responses | |
2996 | Must(pipeline.empty()); | |
2997 | } | |
2998 | /* careful: finished() above frees request, host, etc. */ | |
129fe2a1 | 2999 | |
cf487124 | 3000 | if (port->secure.generateHostCertificates) { |
aebe6888 | 3001 | Ssl::CertificateProperties certProperties; |
06997a38 | 3002 | buildSslCertGenerationParams(certProperties); |
fb2178bb | 3003 | |
d620ae0e | 3004 | // Disable caching for bumpPeekAndSplice mode |
a9c2dd2f | 3005 | if (!(sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare))) { |
5107d2c4 CT |
3006 | sslBumpCertKey.clear(); |
3007 | Ssl::InRamCertificateDbKey(certProperties, sslBumpCertKey); | |
3008 | assert(!sslBumpCertKey.isEmpty()); | |
3009 | ||
3010 | Security::ContextPointer ctx(getTlsContextFromCache(sslBumpCertKey, certProperties)); | |
3011 | if (ctx) { | |
3012 | getSslContextDone(ctx); | |
3013 | return; | |
95d2589c | 3014 | } |
95d2589c CT |
3015 | } |
3016 | ||
b5faa519 | 3017 | #if USE_SSL_CRTD |
00fc192d | 3018 | try { |
87f237a9 | 3019 | debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd."); |
ff2d7d92 | 3020 | Ssl::CrtdMessage request_message(Ssl::CrtdMessage::REQUEST); |
87f237a9 A |
3021 | request_message.setCode(Ssl::CrtdMessage::code_new_certificate); |
3022 | request_message.composeRequest(certProperties); | |
3023 | debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str()); | |
23da195f | 3024 | Ssl::Helper::Submit(request_message, sslCrtdHandleReplyWrapper, this); |
87f237a9 A |
3025 | return; |
3026 | } catch (const std::exception &e) { | |
00fc192d AR |
3027 | debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " << |
3028 | "request for " << certProperties.commonName << | |
3029 | " certificate: " << e.what() << "; will now block to " << | |
3030 | "generate that certificate."); | |
3031 | // fall through to do blocking in-process generation. | |
3032 | } | |
3033 | #endif // USE_SSL_CRTD | |
3034 | ||
aebe6888 | 3035 | debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName); |
a9c2dd2f | 3036 | if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) { |
d620ae0e | 3037 | doPeekAndSpliceStep(); |
33cc0629 | 3038 | auto ssl = fd_table[clientConnection->fd].ssl.get(); |
d620ae0e | 3039 | if (!Ssl::configureSSL(ssl, certProperties, *port)) |
e4f14091 | 3040 | debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode"); |
d8f0ceab | 3041 | |
1c1fae0f | 3042 | Security::ContextPointer ctx(Security::GetFrom(fd_table[clientConnection->fd].ssl)); |
b23f5f9c | 3043 | Ssl::configureUnconfiguredSslContext(ctx, certProperties.signAlgorithm, *port); |
d620ae0e | 3044 | } else { |
cf487124 | 3045 | Security::ContextPointer dynCtx(Ssl::GenerateSslContext(certProperties, port->secure, (signAlgorithm == Ssl::algSignTrusted))); |
5107d2c4 CT |
3046 | if (dynCtx && !sslBumpCertKey.isEmpty()) |
3047 | storeTlsContextToCache(sslBumpCertKey, dynCtx); | |
3048 | getSslContextDone(dynCtx); | |
d620ae0e | 3049 | } |
1ce2822d | 3050 | return; |
95d2589c | 3051 | } |
0476ec45 AJ |
3052 | |
3053 | Security::ContextPointer nil; | |
3054 | getSslContextDone(nil); | |
95d2589c CT |
3055 | } |
3056 | ||
1ce2822d | 3057 | void |
5107d2c4 | 3058 | ConnStateData::getSslContextDone(Security::ContextPointer &ctx) |
95d2589c | 3059 | { |
cf487124 | 3060 | if (port->secure.generateHostCertificates && !ctx) { |
1700fab7 | 3061 | debugs(33, 2, "Failed to generate TLS context for " << sslConnectHostOrIp); |
95d2589c CT |
3062 | } |
3063 | ||
3064 | // If generated ssl context = NULL, try to use static ssl context. | |
0476ec45 | 3065 | if (!ctx) { |
80b5995a AJ |
3066 | if (!port->secure.staticContext) { |
3067 | debugs(83, DBG_IMPORTANT, "Closing " << clientConnection->remote << " as lacking TLS context"); | |
73c36fd9 | 3068 | clientConnection->close(); |
1ce2822d | 3069 | return; |
95d2589c | 3070 | } else { |
80b5995a | 3071 | debugs(33, 5, "Using static TLS context."); |
0476ec45 | 3072 | ctx = port->secure.staticContext; |
95d2589c CT |
3073 | } |
3074 | } | |
ae7ff0b8 | 3075 | |
0476ec45 | 3076 | if (!httpsCreate(clientConnection, ctx)) |
1ce2822d | 3077 | return; |
ae7ff0b8 | 3078 | |
4e67d484 CT |
3079 | // bumped intercepted conns should already have Config.Timeout.request set |
3080 | // but forwarded connections may only have Config.Timeout.lifetime. [Re]set | |
3081 | // to make sure the connection does not get stuck on non-SSL clients. | |
3082 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; | |
3083 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer, | |
3899de60 | 3084 | this, ConnStateData::requestTimeout); |
4e67d484 | 3085 | commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall); |
ae7ff0b8 | 3086 | |
ae7ff0b8 | 3087 | switchedToHttps_ = true; |
36698640 CT |
3088 | |
3089 | auto ssl = fd_table[clientConnection->fd].ssl.get(); | |
3090 | BIO *b = SSL_get_rbio(ssl); | |
2a268a06 | 3091 | Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b)); |
36698640 CT |
3092 | bio->setReadBufData(inBuf); |
3093 | inBuf.clear(); | |
3094 | clientNegotiateSSL(clientConnection->fd, this); | |
ae7ff0b8 | 3095 | } |
3096 | ||
1ce2822d | 3097 | void |
caf3666d | 3098 | ConnStateData::switchToHttps(HttpRequest *request, Ssl::BumpMode bumpServerMode) |
95d2589c CT |
3099 | { |
3100 | assert(!switchedToHttps_); | |
3101 | ||
5c51bffb | 3102 | sslConnectHostOrIp = request->url.host(); |
82b04b16 | 3103 | tlsConnectPort = request->url.port(); |
5c51bffb | 3104 | resetSslCommonName(request->url.host()); |
95d2589c | 3105 | |
83d4cd15 CT |
3106 | // We are going to read new request |
3107 | flags.readMore = true; | |
73c36fd9 | 3108 | debugs(33, 5, HERE << "converting " << clientConnection << " to SSL"); |
95d2589c | 3109 | |
4599cded AJ |
3110 | // keep version major.minor details the same. |
3111 | // but we are now performing the HTTPS handshake traffic | |
3112 | transferProtocol.protocol = AnyP::PROTO_HTTPS; | |
3113 | ||
2bd84e5f CT |
3114 | // If sslServerBump is set, then we have decided to deny CONNECT |
3115 | // and now want to switch to SSL to send the error to the client | |
3116 | // without even peeking at the origin server certificate. | |
caf3666d | 3117 | if (bumpServerMode == Ssl::bumpServerFirst && !sslServerBump) { |
e857372a | 3118 | request->flags.sslPeek = true; |
65ba7f04 | 3119 | sslServerBump = new Ssl::ServerBump(request); |
e1f72a8b | 3120 | } else if (bumpServerMode == Ssl::bumpPeek || bumpServerMode == Ssl::bumpStare) { |
d620ae0e | 3121 | request->flags.sslPeek = true; |
5d65362c | 3122 | sslServerBump = new Ssl::ServerBump(request, NULL, bumpServerMode); |
36698640 | 3123 | } |
3cae14a6 | 3124 | |
36698640 CT |
3125 | // commSetConnTimeout() was called for this request before we switched. |
3126 | // Fix timeout to request_start_timeout | |
3127 | typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer; | |
3128 | AsyncCall::Pointer timeoutCall = JobCallback(33, 5, | |
fde0b2ca | 3129 | TimeoutDialer, this, ConnStateData::requestTimeout); |
36698640 CT |
3130 | commSetConnTimeout(clientConnection, Config.Timeout.request_start_timeout, timeoutCall); |
3131 | // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have | |
3132 | // a bumbed "connect" request on non transparent port. | |
3133 | receivedFirstByte_ = false; | |
3134 | // Get more data to peek at Tls | |
d20cf186 | 3135 | parsingTlsHandshake = true; |
36698640 CT |
3136 | readSomeData(); |
3137 | } | |
3138 | ||
3139 | void | |
d20cf186 | 3140 | ConnStateData::parseTlsHandshake() |
36698640 | 3141 | { |
d20cf186 AR |
3142 | Must(parsingTlsHandshake); |
3143 | ||
3144 | assert(!inBuf.isEmpty()); | |
36698640 | 3145 | receivedFirstByte(); |
d20cf186 AR |
3146 | fd_note(clientConnection->fd, "Parsing TLS handshake"); |
3147 | ||
3148 | bool unsupportedProtocol = false; | |
3149 | try { | |
3150 | if (!tlsParser.parseHello(inBuf)) { | |
3151 | // need more data to finish parsing | |
3152 | readSomeData(); | |
3153 | return; | |
3154 | } | |
3155 | } | |
3156 | catch (const std::exception &ex) { | |
3157 | debugs(83, 2, "error on FD " << clientConnection->fd << ": " << ex.what()); | |
3158 | unsupportedProtocol = true; | |
3159 | } | |
36698640 | 3160 | |
d20cf186 | 3161 | parsingTlsHandshake = false; |
36698640 | 3162 | |
75f6c253 CT |
3163 | // client data may be needed for splicing and for |
3164 | // tunneling unsupportedProtocol after an error | |
3165 | preservedClientData = inBuf; | |
6b2b6cfe | 3166 | |
d20cf186 AR |
3167 | // Even if the parser failed, each TLS detail should either be set |
3168 | // correctly or still be "unknown"; copying unknown detail is a no-op. | |
8d9e6d7f CT |
3169 | Security::TlsDetails::Pointer const &details = tlsParser.details; |
3170 | clientConnection->tlsNegotiations()->retrieveParsedInfo(details); | |
3171 | if (details && !details->serverName.isEmpty()) { | |
3172 | resetSslCommonName(details->serverName.c_str()); | |
4f6990ec | 3173 | tlsClientSni_ = details->serverName; |
8d9e6d7f | 3174 | } |
36698640 CT |
3175 | |
3176 | // We should disable read/write handlers | |
508e3438 | 3177 | Comm::ResetSelect(clientConnection->fd); |
36698640 | 3178 | |
6b2b6cfe CT |
3179 | if (unsupportedProtocol) { |
3180 | Http::StreamPointer context = pipeline.front(); | |
3181 | Must(context && context->http); | |
3182 | HttpRequest::Pointer request = context->http->request; | |
3183 | debugs(83, 5, "Got something other than TLS Client Hello. Cannot SslBump."); | |
bf352fb2 CT |
3184 | sslBumpMode = Ssl::bumpSplice; |
3185 | context->http->al->ssl.bumpMode = Ssl::bumpSplice; | |
6b2b6cfe CT |
3186 | if (!clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_PROTOCOL_UNKNOWN)) |
3187 | clientConnection->close(); | |
3188 | return; | |
3189 | } | |
3190 | ||
3191 | if (!sslServerBump || sslServerBump->act.step1 == Ssl::bumpClientFirst) { // Either means client-first. | |
36698640 | 3192 | getSslContextStart(); |
e1f72a8b | 3193 | return; |
36698640 CT |
3194 | } else if (sslServerBump->act.step1 == Ssl::bumpServerFirst) { |
3195 | // will call httpsPeeked() with certificate and connection, eventually | |
3196 | FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw()); | |
3197 | } else { | |
3198 | Must(sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare); | |
6b2b6cfe | 3199 | startPeekAndSplice(); |
3248e962 | 3200 | } |
d620ae0e CT |
3201 | } |
3202 | ||
5d65362c CT |
3203 | void httpsSslBumpStep2AccessCheckDone(allow_t answer, void *data) |
3204 | { | |
3205 | ConnStateData *connState = (ConnStateData *) data; | |
3206 | ||
3207 | // if the connection is closed or closing, just return. | |
3208 | if (!connState->isOpen()) | |
3209 | return; | |
3210 | ||
e4f14091 | 3211 | debugs(33, 5, "Answer: " << answer << " kind:" << answer.kind); |
a9c2dd2f CT |
3212 | assert(connState->serverBump()); |
3213 | Ssl::BumpMode bumpAction; | |
06bf5384 | 3214 | if (answer.allowed()) { |
640fe8fb | 3215 | bumpAction = (Ssl::BumpMode)answer.kind; |
a9c2dd2f CT |
3216 | } else |
3217 | bumpAction = Ssl::bumpSplice; | |
3218 | ||
3219 | connState->serverBump()->act.step2 = bumpAction; | |
3220 | connState->sslBumpMode = bumpAction; | |
bf352fb2 CT |
3221 | Http::StreamPointer context = connState->pipeline.front(); |
3222 | if (ClientHttpRequest *http = (context ? context->http : nullptr)) | |
3223 | http->al->ssl.bumpMode = bumpAction; | |
a9c2dd2f CT |
3224 | |
3225 | if (bumpAction == Ssl::bumpTerminate) { | |
b54a7c5a | 3226 | connState->clientConnection->close(); |
a9c2dd2f | 3227 | } else if (bumpAction != Ssl::bumpSplice) { |
6b2b6cfe | 3228 | connState->startPeekAndSplice(); |
efda53c5 CT |
3229 | } else if (!connState->splice()) |
3230 | connState->clientConnection->close(); | |
3248e962 | 3231 | } |
5d65362c | 3232 | |
efda53c5 | 3233 | bool |
3248e962 CT |
3234 | ConnStateData::splice() |
3235 | { | |
33cc0629 | 3236 | // normally we can splice here, because we just got client hello message |
2bcab852 | 3237 | |
8abcff99 | 3238 | if (fd_table[clientConnection->fd].ssl.get()) { |
d9219c2b | 3239 | // Restore default read methods |
3cae14a6 CT |
3240 | fd_table[clientConnection->fd].read_method = &default_read_method; |
3241 | fd_table[clientConnection->fd].write_method = &default_write_method; | |
3cae14a6 | 3242 | } |
3248e962 | 3243 | |
6b2b6cfe CT |
3244 | // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with... |
3245 | // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process) | |
3246 | transferProtocol = Http::ProtocolVersion(); | |
3247 | assert(!pipeline.empty()); | |
3248 | Http::StreamPointer context = pipeline.front(); | |
75f6c253 CT |
3249 | Must(context); |
3250 | Must(context->http); | |
6b2b6cfe | 3251 | ClientHttpRequest *http = context->http; |
75f6c253 CT |
3252 | HttpRequest::Pointer request = http->request; |
3253 | context->finished(); | |
3254 | if (transparent()) { | |
3255 | // For transparent connections, make a new fake CONNECT request, now | |
3256 | // with SNI as target. doCallout() checks, adaptations may need that. | |
3257 | return fakeAConnectRequest("splice", preservedClientData); | |
3258 | } else { | |
3259 | // For non transparent connections make a new tunneled CONNECT, which | |
3260 | // also sets the HttpRequest::flags::forceTunnel flag to avoid | |
3261 | // respond with "Connection Established" to the client. | |
3262 | // This fake CONNECT request required to allow use of SNI in | |
3263 | // doCallout() checks and adaptations. | |
3264 | return initiateTunneledRequest(request, Http::METHOD_CONNECT, "splice", preservedClientData); | |
3265 | } | |
5d65362c CT |
3266 | } |
3267 | ||
d620ae0e | 3268 | void |
6b2b6cfe | 3269 | ConnStateData::startPeekAndSplice() |
d620ae0e | 3270 | { |
5d65362c CT |
3271 | // This is the Step2 of the SSL bumping |
3272 | assert(sslServerBump); | |
d4ddb3e6 | 3273 | Http::StreamPointer context = pipeline.front(); |
2f0d171f | 3274 | ClientHttpRequest *http = context ? context->http : nullptr; |
d4ddb3e6 | 3275 | |
5d65362c CT |
3276 | if (sslServerBump->step == Ssl::bumpStep1) { |
3277 | sslServerBump->step = Ssl::bumpStep2; | |
3278 | // Run a accessList check to check if want to splice or continue bumping | |
3279 | ||
2f0d171f AJ |
3280 | ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, sslServerBump->request.getRaw(), nullptr); |
3281 | acl_checklist->al = http ? http->al : nullptr; | |
5d65362c CT |
3282 | //acl_checklist->src_addr = params.conn->remote; |
3283 | //acl_checklist->my_addr = s->s; | |
640fe8fb CT |
3284 | acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpNone)); |
3285 | acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpClientFirst)); | |
3286 | acl_checklist->banAction(allow_t(ACCESS_ALLOWED, Ssl::bumpServerFirst)); | |
cb365059 EB |
3287 | const char *log_uri = http ? http->log_uri : nullptr; |
3288 | acl_checklist->syncAle(sslServerBump->request.getRaw(), log_uri); | |
5d65362c CT |
3289 | acl_checklist->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone, this); |
3290 | return; | |
3291 | } | |
3292 | ||
3cae14a6 | 3293 | // will call httpsPeeked() with certificate and connection, eventually |
51e09c08 | 3294 | Security::ContextPointer unConfiguredCTX(Ssl::createSSLContext(port->secure.signingCa.cert, port->secure.signingCa.pkey, port->secure)); |
0476ec45 | 3295 | fd_table[clientConnection->fd].dynamicTlsContext = unConfiguredCTX; |
3cae14a6 CT |
3296 | |
3297 | if (!httpsCreate(clientConnection, unConfiguredCTX)) | |
3298 | return; | |
3299 | ||
3300 | switchedToHttps_ = true; | |
3301 | ||
3302 | auto ssl = fd_table[clientConnection->fd].ssl.get(); | |
3303 | BIO *b = SSL_get_rbio(ssl); | |
2a268a06 | 3304 | Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b)); |
3cae14a6 | 3305 | bio->setReadBufData(inBuf); |
3cae14a6 CT |
3306 | bio->hold(true); |
3307 | ||
fde0b2ca | 3308 | // Here squid should have all of the client hello message so the |
1700fab7 | 3309 | // tlsAttemptHandshake() should return 0. |
3cae14a6 CT |
3310 | // This block exist only to force openSSL parse client hello and detect |
3311 | // ERR_SECURE_ACCEPT_FAIL error, which should be checked and splice if required. | |
1700fab7 | 3312 | if (tlsAttemptHandshake(this, nullptr) < 0) { |
51e09c08 | 3313 | debugs(83, 2, "TLS handshake failed."); |
2f0d171f | 3314 | HttpRequest::Pointer request(http ? http->request : nullptr); |
6b2b6cfe | 3315 | if (!clientTunnelOnError(this, context, request, HttpRequestMethod(), ERR_SECURE_ACCEPT_FAIL)) |
3cae14a6 CT |
3316 | clientConnection->close(); |
3317 | return; | |
3318 | } | |
3319 | ||
56dacaca CT |
3320 | // We need to reset inBuf here, to be used by incoming requests in the case |
3321 | // of SSL bump | |
8abcff99 | 3322 | inBuf.clear(); |
3cae14a6 CT |
3323 | |
3324 | debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! "); | |
d4ddb3e6 | 3325 | FwdState::Start(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw(), http ? http->al : NULL); |
d620ae0e CT |
3326 | } |
3327 | ||
3328 | void | |
3329 | ConnStateData::doPeekAndSpliceStep() | |
3330 | { | |
33cc0629 | 3331 | auto ssl = fd_table[clientConnection->fd].ssl.get(); |
d620ae0e CT |
3332 | BIO *b = SSL_get_rbio(ssl); |
3333 | assert(b); | |
2a268a06 | 3334 | Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(BIO_get_data(b)); |
d620ae0e | 3335 | |
e4f14091 | 3336 | debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl)); |
d620ae0e CT |
3337 | bio->hold(false); |
3338 | ||
3339 | Comm::SetSelect(clientConnection->fd, COMM_SELECT_WRITE, clientNegotiateSSL, this, 0); | |
3340 | switchedToHttps_ = true; | |
3341 | } | |
3342 | ||
d7ce0bcd | 3343 | void |
801cfc26 | 3344 | ConnStateData::httpsPeeked(PinnedIdleContext pic) |
d7ce0bcd | 3345 | { |
fd4624d7 | 3346 | Must(sslServerBump != NULL); |
801cfc26 CT |
3347 | Must(sslServerBump->request == pic.request); |
3348 | Must(pipeline.empty() || pipeline.front()->http == nullptr || pipeline.front()->http->request == pic.request.getRaw()); | |
819c207f | 3349 | |
801cfc26 CT |
3350 | if (Comm::IsConnOpen(pic.connection)) { |
3351 | notePinnedConnectionBecameIdle(pic); | |
fb2178bb | 3352 | debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp); |
801cfc26 | 3353 | } else |
13858f50 | 3354 | debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp); |
129fe2a1 | 3355 | |
1ce2822d | 3356 | getSslContextStart(); |
95d2589c CT |
3357 | } |
3358 | ||
cb4f4424 | 3359 | #endif /* USE_OPENSSL */ |
1f7c9178 | 3360 | |
efda53c5 | 3361 | bool |
6b2b6cfe | 3362 | ConnStateData::initiateTunneledRequest(HttpRequest::Pointer const &cause, Http::MethodType const method, const char *reason, const SBuf &payload) |
0bd3c2a3 AJ |
3363 | { |
3364 | // fake a CONNECT request to force connState to tunnel | |
e88bdb0e | 3365 | SBuf connectHost; |
6b2b6cfe CT |
3366 | unsigned short connectPort = 0; |
3367 | ||
3368 | if (pinning.serverConnection != nullptr) { | |
3369 | static char ip[MAX_IPSTRLEN]; | |
e9b219a0 TA |
3370 | pinning.serverConnection->remote.toHostStr(ip, sizeof(ip)); |
3371 | connectHost.assign(ip); | |
6b2b6cfe CT |
3372 | connectPort = pinning.serverConnection->remote.port(); |
3373 | } else if (cause && cause->method == Http::METHOD_CONNECT) { | |
3374 | // We are inside a (not fully established) CONNECT request | |
3375 | connectHost = cause->url.host(); | |
3376 | connectPort = cause->url.port(); | |
3377 | } else { | |
3378 | debugs(33, 2, "Not able to compute URL, abort request tunneling for " << reason); | |
3379 | return false; | |
3380 | } | |
3381 | ||
3382 | debugs(33, 2, "Request tunneling for " << reason); | |
3383 | ClientHttpRequest *http = buildFakeRequest(method, connectHost, connectPort, payload); | |
3384 | HttpRequest::Pointer request = http->request; | |
3385 | request->flags.forceTunnel = true; | |
3386 | http->calloutContext = new ClientRequestContext(http); | |
3387 | http->doCallouts(); | |
3388 | clientProcessRequestFinished(this, request); | |
3389 | return true; | |
3390 | } | |
3391 | ||
3392 | bool | |
3393 | ConnStateData::fakeAConnectRequest(const char *reason, const SBuf &payload) | |
3394 | { | |
3395 | debugs(33, 2, "fake a CONNECT request to force connState to tunnel for " << reason); | |
3396 | ||
3397 | SBuf connectHost; | |
3398 | assert(transparent()); | |
3399 | const unsigned short connectPort = clientConnection->local.port(); | |
3400 | ||
65e0c910 | 3401 | #if USE_OPENSSL |
4f6990ec CT |
3402 | if (!tlsClientSni_.isEmpty()) |
3403 | connectHost.assign(tlsClientSni_); | |
6b2b6cfe | 3404 | else |
65e0c910 CT |
3405 | #endif |
3406 | { | |
e88bdb0e | 3407 | static char ip[MAX_IPSTRLEN]; |
e9b219a0 TA |
3408 | clientConnection->local.toHostStr(ip, sizeof(ip)); |
3409 | connectHost.assign(ip); | |
0bd3c2a3 | 3410 | } |
6b2b6cfe CT |
3411 | |
3412 | ClientHttpRequest *http = buildFakeRequest(Http::METHOD_CONNECT, connectHost, connectPort, payload); | |
3413 | ||
3414 | http->calloutContext = new ClientRequestContext(http); | |
3415 | HttpRequest::Pointer request = http->request; | |
3416 | http->doCallouts(); | |
3417 | clientProcessRequestFinished(this, request); | |
efda53c5 | 3418 | return true; |
0bd3c2a3 AJ |
3419 | } |
3420 | ||
6b2b6cfe CT |
3421 | ClientHttpRequest * |
3422 | ConnStateData::buildFakeRequest(Http::MethodType const method, SBuf &useHost, unsigned short usePort, const SBuf &payload) | |
3423 | { | |
3424 | ClientHttpRequest *http = new ClientHttpRequest(this); | |
3425 | Http::Stream *stream = new Http::Stream(clientConnection, http); | |
3426 | ||
3427 | StoreIOBuffer tempBuffer; | |
3428 | tempBuffer.data = stream->reqbuf; | |
3429 | tempBuffer.length = HTTP_REQBUF_SZ; | |
3430 | ||
3431 | ClientStreamData newServer = new clientReplyContext(http); | |
3432 | ClientStreamData newClient = stream; | |
3433 | clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach, | |
3434 | clientReplyStatus, newServer, clientSocketRecipient, | |
3435 | clientSocketDetach, newClient, tempBuffer); | |
3436 | ||
3437 | http->uri = SBufToCstring(useHost); | |
3438 | stream->flags.parsed_ok = 1; // Do we need it? | |
3439 | stream->mayUseConnection(true); | |
aff439e0 | 3440 | |
6b2b6cfe | 3441 | AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout", |
aff439e0 | 3442 | CommTimeoutCbPtrFun(clientLifetimeTimeout, stream->http)); |
6b2b6cfe CT |
3443 | commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall); |
3444 | ||
3445 | stream->registerWithConn(); | |
3446 | ||
5ceaee75 CT |
3447 | MasterXaction::Pointer mx = new MasterXaction(XactionInitiator::initClient); |
3448 | mx->tcpClient = clientConnection; | |
6b2b6cfe CT |
3449 | // Setup Http::Request object. Maybe should be replaced by a call to (modified) |
3450 | // clientProcessRequest | |
5ceaee75 | 3451 | HttpRequest::Pointer request = new HttpRequest(mx); |
6b2b6cfe CT |
3452 | AnyP::ProtocolType proto = (method == Http::METHOD_NONE) ? AnyP::PROTO_AUTHORITY_FORM : AnyP::PROTO_HTTP; |
3453 | request->url.setScheme(proto, nullptr); | |
3454 | request->method = method; | |
3455 | request->url.host(useHost.c_str()); | |
3456 | request->url.port(usePort); | |
bec110e4 | 3457 | http->initRequest(request.getRaw()); |
6b2b6cfe | 3458 | |
cd4a5c60 | 3459 | request->manager(this, http->al); |
6b2b6cfe CT |
3460 | |
3461 | if (proto == AnyP::PROTO_HTTP) | |
3462 | request->header.putStr(Http::HOST, useHost.c_str()); | |
cd4a5c60 | 3463 | |
63df1d28 | 3464 | request->sources |= ((switchedToHttps() || port->transport.protocol == AnyP::PROTO_HTTPS) ? Http::Message::srcHttps : Http::Message::srcHttp); |
6b2b6cfe CT |
3465 | #if USE_AUTH |
3466 | if (getAuth()) | |
3467 | request->auth_user_request = getAuth(); | |
3468 | #endif | |
6b2b6cfe CT |
3469 | |
3470 | inBuf = payload; | |
3471 | flags.readMore = false; | |
3472 | ||
6b2b6cfe CT |
3473 | return http; |
3474 | } | |
3475 | ||
00516be1 AR |
3476 | /// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed |
3477 | static bool | |
73c36fd9 | 3478 | OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType) |
00516be1 | 3479 | { |
73c36fd9 | 3480 | if (!Comm::IsConnOpen(c)) { |
00516be1 AR |
3481 | Must(NHttpSockets > 0); // we tried to open some |
3482 | --NHttpSockets; // there will be fewer sockets than planned | |
3483 | Must(HttpSockets[NHttpSockets] < 0); // no extra fds received | |
3484 | ||
3485 | if (!NHttpSockets) // we could not open any listen sockets at all | |
cbff89ba | 3486 | fatalf("Unable to open %s",FdNote(portType)); |
00516be1 AR |
3487 | |
3488 | return false; | |
3489 | } | |
3490 | return true; | |
3491 | } | |
3492 | ||
3493 | /// find any unused HttpSockets[] slot and store fd there or return false | |
3494 | static bool | |
e0d28505 | 3495 | AddOpenedHttpSocket(const Comm::ConnectionPointer &conn) |
00516be1 AR |
3496 | { |
3497 | bool found = false; | |
95dc7ff4 | 3498 | for (int i = 0; i < NHttpSockets && !found; ++i) { |
00516be1 | 3499 | if ((found = HttpSockets[i] < 0)) |
e0d28505 | 3500 | HttpSockets[i] = conn->fd; |
00516be1 AR |
3501 | } |
3502 | return found; | |
3503 | } | |
15df8349 | 3504 | |
d193a436 | 3505 | static void |
15df8349 | 3506 | clientHttpConnectionsOpen(void) |
3507 | { | |
fa720bfb | 3508 | for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) { |
d31d59d8 | 3509 | const SBuf &scheme = AnyP::UriScheme(s->transport.protocol).image(); |
339e4d7a | 3510 | |
65d448bc | 3511 | if (MAXTCPLISTENPORTS == NHttpSockets) { |
339e4d7a | 3512 | debugs(1, DBG_IMPORTANT, "WARNING: You have too many '" << scheme << "_port' lines."); |
e0236918 | 3513 | debugs(1, DBG_IMPORTANT, " The limit is " << MAXTCPLISTENPORTS << " HTTP ports."); |
62e76326 | 3514 | continue; |
3515 | } | |
3516 | ||
cb4f4424 | 3517 | #if USE_OPENSSL |
6a25a046 | 3518 | if (s->flags.tunnelSslBumping) { |
339e4d7a AJ |
3519 | if (!Config.accessList.ssl_bump) { |
3520 | debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << scheme << "_port " << s->s); | |
3521 | s->flags.tunnelSslBumping = false; | |
3522 | } | |
cf487124 | 3523 | if (!s->secure.staticContext && !s->secure.generateHostCertificates) { |
339e4d7a AJ |
3524 | debugs(1, DBG_IMPORTANT, "Will not bump SSL at " << scheme << "_port " << s->s << " due to TLS initialization failure."); |
3525 | s->flags.tunnelSslBumping = false; | |
3526 | if (s->transport.protocol == AnyP::PROTO_HTTP) | |
3527 | s->secure.encryptTransport = false; | |
3528 | } | |
3529 | if (s->flags.tunnelSslBumping) { | |
3530 | // Create ssl_ctx cache for this port. | |
cf487124 | 3531 | Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->secure.dynamicCertMemCacheSize); |
339e4d7a | 3532 | } |
95d2589c | 3533 | } |
51e09c08 | 3534 | #endif |
ae7ff0b8 | 3535 | |
80b5995a | 3536 | if (s->secure.encryptTransport && !s->secure.staticContext) { |
339e4d7a AJ |
3537 | debugs(1, DBG_CRITICAL, "ERROR: Ignoring " << scheme << "_port " << s->s << " due to TLS context initialization failure."); |
3538 | continue; | |
3539 | } | |
3540 | ||
e0d28505 | 3541 | // Fill out a Comm::Connection which IPC will open as a listener for us |
8bbb16e3 | 3542 | // then pass back when active so we can start a TcpAcceptor subscription. |
e0d28505 AJ |
3543 | s->listenConn = new Comm::Connection; |
3544 | s->listenConn->local = s->s; | |
c303f6e3 | 3545 | |
339e4d7a AJ |
3546 | s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) | |
3547 | (s->flags.natIntercept ? COMM_INTERCEPTION : 0); | |
62e76326 | 3548 | |
339e4d7a AJ |
3549 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; |
3550 | if (s->transport.protocol == AnyP::PROTO_HTTP) { | |
3551 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP | |
3552 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, CommAcceptCbParams(NULL))); | |
3553 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
62e76326 | 3554 | |
339e4d7a AJ |
3555 | AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened", |
3556 | ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub)); | |
3557 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall); | |
d193a436 | 3558 | |
339e4d7a AJ |
3559 | } else if (s->transport.protocol == AnyP::PROTO_HTTPS) { |
3560 | // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS | |
3561 | RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, CommAcceptCbParams(NULL))); | |
3562 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
3563 | ||
3564 | AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened", | |
3565 | ListeningStartedDialer(&clientListenerConnectionOpened, | |
3566 | s, Ipc::fdnHttpsSocket, sub)); | |
3567 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall); | |
d7ce0bcd AR |
3568 | } |
3569 | ||
339e4d7a | 3570 | HttpSockets[NHttpSockets] = -1; // set in clientListenerConnectionOpened |
a38ec4b1 | 3571 | ++NHttpSockets; |
cbff89ba | 3572 | } |
d193a436 | 3573 | } |
d193a436 | 3574 | |
92ae4c86 | 3575 | void |
27c841f6 AR |
3576 | clientStartListeningOn(AnyP::PortCfgPointer &port, const RefCount< CommCbFunPtrCallT<CommAcceptCbPtrFun> > &subCall, const Ipc::FdNoteId fdNote) |
3577 | { | |
92ae4c86 AR |
3578 | // Fill out a Comm::Connection which IPC will open as a listener for us |
3579 | port->listenConn = new Comm::Connection; | |
3580 | port->listenConn->local = port->s; | |
e7ce227f AR |
3581 | port->listenConn->flags = |
3582 | COMM_NONBLOCKING | | |
3583 | (port->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) | | |
3584 | (port->flags.natIntercept ? COMM_INTERCEPTION : 0); | |
92ae4c86 AR |
3585 | |
3586 | // route new connections to subCall | |
3587 | typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall; | |
3588 | Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall); | |
e7ce227f AR |
3589 | AsyncCall::Pointer listenCall = |
3590 | asyncCall(33, 2, "clientListenerConnectionOpened", | |
3591 | ListeningStartedDialer(&clientListenerConnectionOpened, | |
3592 | port, fdNote, sub)); | |
92ae4c86 | 3593 | Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, port->listenConn, fdNote, listenCall); |
434a79b0 | 3594 | |
92ae4c86 AR |
3595 | assert(NHttpSockets < MAXTCPLISTENPORTS); |
3596 | HttpSockets[NHttpSockets] = -1; | |
3597 | ++NHttpSockets; | |
434a79b0 DK |
3598 | } |
3599 | ||
e0d28505 | 3600 | /// process clientHttpConnectionsOpen result |
00516be1 | 3601 | static void |
fa720bfb | 3602 | clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub) |
00516be1 | 3603 | { |
fa720bfb AJ |
3604 | Must(s != NULL); |
3605 | ||
8bbb16e3 | 3606 | if (!OpenedHttpSocket(s->listenConn, portTypeNote)) |
00516be1 | 3607 | return; |
62e76326 | 3608 | |
e0d28505 | 3609 | Must(Comm::IsConnOpen(s->listenConn)); |
62e76326 | 3610 | |
8bbb16e3 | 3611 | // TCP: setup a job to handle accept() with subscribed handler |
fa720bfb | 3612 | AsyncJob::Start(new Comm::TcpAcceptor(s, FdNote(portTypeNote), sub)); |
8bbb16e3 | 3613 | |
e0236918 | 3614 | debugs(1, DBG_IMPORTANT, "Accepting " << |
6a25a046 | 3615 | (s->flags.natIntercept ? "NAT intercepted " : "") << |
0d901ef4 | 3616 | (s->flags.tproxyIntercept ? "TPROXY intercepted " : "") << |
6a25a046 FC |
3617 | (s->flags.tunnelSslBumping ? "SSL bumped " : "") << |
3618 | (s->flags.accelSurrogate ? "reverse-proxy " : "") | |
8bbb16e3 AJ |
3619 | << FdNote(portTypeNote) << " connections at " |
3620 | << s->listenConn); | |
62e76326 | 3621 | |
e0d28505 | 3622 | Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for |
d193a436 | 3623 | } |
3624 | ||
d193a436 | 3625 | void |
3626 | clientOpenListenSockets(void) | |
3627 | { | |
3628 | clientHttpConnectionsOpen(); | |
92ae4c86 | 3629 | Ftp::StartListening(); |
62e76326 | 3630 | |
15df8349 | 3631 | if (NHttpSockets < 1) |
e7ce227f | 3632 | fatal("No HTTP, HTTPS, or FTP ports configured"); |
15df8349 | 3633 | } |
edce4d98 | 3634 | |
c0fbae16 | 3635 | void |
e7ce227f | 3636 | clientConnectionsClose() |
c0fbae16 | 3637 | { |
fa720bfb | 3638 | for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) { |
00406b24 | 3639 | if (s->listenConn != NULL) { |
339e4d7a | 3640 | debugs(1, DBG_IMPORTANT, "Closing HTTP(S) port " << s->listenConn->local); |
00406b24 AJ |
3641 | s->listenConn->close(); |
3642 | s->listenConn = NULL; | |
04f55905 AJ |
3643 | } |
3644 | } | |
62e76326 | 3645 | |
92ae4c86 | 3646 | Ftp::StopListening(); |
434a79b0 | 3647 | |
04f55905 | 3648 | // TODO see if we can drop HttpSockets array entirely */ |
95dc7ff4 | 3649 | for (int i = 0; i < NHttpSockets; ++i) { |
04f55905 AJ |
3650 | HttpSockets[i] = -1; |
3651 | } | |
62e76326 | 3652 | |
c0fbae16 | 3653 | NHttpSockets = 0; |
3654 | } | |
f66a9ef4 | 3655 | |
3656 | int | |
190154cf | 3657 | varyEvaluateMatch(StoreEntry * entry, HttpRequest * request) |
f66a9ef4 | 3658 | { |
90ab8f20 | 3659 | SBuf vary(request->vary_headers); |
789217a2 | 3660 | int has_vary = entry->getReply()->header.has(Http::HdrType::VARY); |
f66a9ef4 | 3661 | #if X_ACCELERATOR_VARY |
62e76326 | 3662 | |
edce4d98 | 3663 | has_vary |= |
789217a2 | 3664 | entry->getReply()->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY); |
f66a9ef4 | 3665 | #endif |
62e76326 | 3666 | |
90ab8f20 AJ |
3667 | if (!has_vary || entry->mem_obj->vary_headers.isEmpty()) { |
3668 | if (!vary.isEmpty()) { | |
62e76326 | 3669 | /* Oops... something odd is going on here.. */ |
e0236918 | 3670 | debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" << |
c877c0bc | 3671 | entry->mem_obj->urlXXX() << "' '" << vary << "'"); |
90ab8f20 | 3672 | request->vary_headers.clear(); |
62e76326 | 3673 | return VARY_CANCEL; |
3674 | } | |
3675 | ||
3676 | if (!has_vary) { | |
3677 | /* This is not a varying object */ | |
3678 | return VARY_NONE; | |
3679 | } | |
3680 | ||
3681 | /* virtual "vary" object found. Calculate the vary key and | |
3682 | * continue the search | |
3683 | */ | |
3684 | vary = httpMakeVaryMark(request, entry->getReply()); | |
3685 | ||
90ab8f20 AJ |
3686 | if (!vary.isEmpty()) { |
3687 | request->vary_headers = vary; | |
62e76326 | 3688 | return VARY_OTHER; |
3689 | } else { | |
3690 | /* Ouch.. we cannot handle this kind of variance */ | |
3691 | /* XXX This cannot really happen, but just to be complete */ | |
3692 | return VARY_CANCEL; | |
3693 | } | |
f66a9ef4 | 3694 | } else { |
90ab8f20 | 3695 | if (vary.isEmpty()) { |
62e76326 | 3696 | vary = httpMakeVaryMark(request, entry->getReply()); |
3697 | ||
90ab8f20 AJ |
3698 | if (!vary.isEmpty()) |
3699 | request->vary_headers = vary; | |
62e76326 | 3700 | } |
3701 | ||
90ab8f20 | 3702 | if (vary.isEmpty()) { |
62e76326 | 3703 | /* Ouch.. we cannot handle this kind of variance */ |
3704 | /* XXX This cannot really happen, but just to be complete */ | |
3705 | return VARY_CANCEL; | |
90ab8f20 | 3706 | } else if (vary.cmp(entry->mem_obj->vary_headers) == 0) { |
62e76326 | 3707 | return VARY_MATCH; |
3708 | } else { | |
3709 | /* Oops.. we have already been here and still haven't | |
3710 | * found the requested variant. Bail out | |
3711 | */ | |
e0236918 | 3712 | debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" << |
c877c0bc | 3713 | entry->mem_obj->urlXXX() << "' '" << vary << "'"); |
62e76326 | 3714 | return VARY_CANCEL; |
3715 | } | |
f66a9ef4 | 3716 | } |
3717 | } | |
28d4805a | 3718 | |
c0941a6a | 3719 | ACLFilledChecklist * |
59a1efb2 | 3720 | clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http) |
28d4805a | 3721 | { |
819be284 EB |
3722 | const auto checklist = new ACLFilledChecklist(acl, nullptr, nullptr); |
3723 | clientAclChecklistFill(*checklist, http); | |
3724 | return checklist; | |
3725 | } | |
3726 | ||
3727 | void | |
3728 | clientAclChecklistFill(ACLFilledChecklist &checklist, ClientHttpRequest *http) | |
3729 | { | |
3730 | checklist.setRequest(http->request); | |
3731 | checklist.al = http->al; | |
cb365059 | 3732 | checklist.syncAle(http->request, http->log_uri); |
819be284 EB |
3733 | |
3734 | // TODO: If http->getConn is always http->request->clientConnectionManager, | |
3735 | // then call setIdent() inside checklist.setRequest(). Otherwise, restore | |
3736 | // USE_IDENT lost in commit 94439e4. | |
1cf238db | 3737 | ConnStateData * conn = http->getConn(); |
819be284 EB |
3738 | const char *ident = (cbdataReferenceValid(conn) && |
3739 | conn && conn->clientConnection) ? | |
3740 | conn->clientConnection->rfc931 : dash_str; | |
3741 | checklist.setIdent(ident); | |
28d4805a | 3742 | } |
a46d2c0e | 3743 | |
a46d2c0e | 3744 | bool |
3745 | ConnStateData::transparent() const | |
3746 | { | |
40d34a62 | 3747 | return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION)); |
a46d2c0e | 3748 | } |
3749 | ||
5f8252d2 | 3750 | BodyPipe::Pointer |
3e62bd58 | 3751 | ConnStateData::expectRequestBody(int64_t size) |
5f8252d2 | 3752 | { |
3753 | bodyPipe = new BodyPipe(this); | |
39cb8c41 AR |
3754 | if (size >= 0) |
3755 | bodyPipe->setBodySize(size); | |
3756 | else | |
3757 | startDechunkingRequest(); | |
5f8252d2 | 3758 | return bodyPipe; |
3759 | } | |
3760 | ||
39cb8c41 AR |
3761 | int64_t |
3762 | ConnStateData::mayNeedToReadMoreBody() const | |
3763 | { | |
3764 | if (!bodyPipe) | |
3765 | return 0; // request without a body or read/produced all body bytes | |
3766 | ||
3767 | if (!bodyPipe->bodySizeKnown()) | |
3768 | return -1; // probably need to read more, but we cannot be sure | |
3769 | ||
3770 | const int64_t needToProduce = bodyPipe->unproducedSize(); | |
fcc444e3 | 3771 | const int64_t haveAvailable = static_cast<int64_t>(inBuf.length()); |
39cb8c41 AR |
3772 | |
3773 | if (needToProduce <= haveAvailable) | |
3774 | return 0; // we have read what we need (but are waiting for pipe space) | |
3775 | ||
3776 | return needToProduce - haveAvailable; | |
3777 | } | |
3778 | ||
55e44db9 | 3779 | void |
cf6eb29e | 3780 | ConnStateData::stopReceiving(const char *error) |
55e44db9 | 3781 | { |
cf6eb29e CT |
3782 | debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error << |
3783 | "; old sending error: " << | |
3784 | (stoppedSending() ? stoppedSending_ : "none")); | |
5f8252d2 | 3785 | |
cf6eb29e CT |
3786 | if (const char *oldError = stoppedReceiving()) { |
3787 | debugs(33, 3, HERE << "already stopped receiving: " << oldError); | |
3788 | return; // nothing has changed as far as this connection is concerned | |
3789 | } | |
5f8252d2 | 3790 | |
cf6eb29e | 3791 | stoppedReceiving_ = error; |
5f8252d2 | 3792 | |
cf6eb29e CT |
3793 | if (const char *sendError = stoppedSending()) { |
3794 | debugs(33, 3, HERE << "closing because also stopped sending: " << sendError); | |
3795 | clientConnection->close(); | |
3796 | } | |
55e44db9 | 3797 | } |
3798 | ||
eb44b2d7 | 3799 | void |
e29ccb57 A |
3800 | ConnStateData::expectNoForwarding() |
3801 | { | |
eb44b2d7 CT |
3802 | if (bodyPipe != NULL) { |
3803 | debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status()); | |
3804 | bodyPipe->expectNoConsumption(); | |
3805 | } | |
3806 | } | |
3807 | ||
39cb8c41 | 3808 | /// initialize dechunking state |
3ff65596 | 3809 | void |
39cb8c41 | 3810 | ConnStateData::startDechunkingRequest() |
3ff65596 | 3811 | { |
39cb8c41 AR |
3812 | Must(bodyPipe != NULL); |
3813 | debugs(33, 5, HERE << "start dechunking" << bodyPipe->status()); | |
fcc444e3 AJ |
3814 | assert(!bodyParser); |
3815 | bodyParser = new Http1::TeChunkedParser; | |
3ff65596 AR |
3816 | } |
3817 | ||
39cb8c41 | 3818 | /// put parsed content into input buffer and clean up |
3ff65596 | 3819 | void |
39cb8c41 | 3820 | ConnStateData::finishDechunkingRequest(bool withSuccess) |
3ff65596 | 3821 | { |
39cb8c41 | 3822 | debugs(33, 5, HERE << "finish dechunking: " << withSuccess); |
3ff65596 | 3823 | |
39cb8c41 AR |
3824 | if (bodyPipe != NULL) { |
3825 | debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status()); | |
3826 | BodyPipe::Pointer myPipe = bodyPipe; | |
3827 | stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize() | |
3828 | Must(!bodyPipe); // we rely on it being nil after we are done with body | |
3829 | if (withSuccess) { | |
3830 | Must(myPipe->bodySizeKnown()); | |
d3dddfb5 | 3831 | Http::StreamPointer context = pipeline.front(); |
39cb8c41 AR |
3832 | if (context != NULL && context->http && context->http->request) |
3833 | context->http->request->setContentLength(myPipe->bodySize()); | |
3834 | } | |
3ff65596 | 3835 | } |
3ff65596 | 3836 | |
fcc444e3 AJ |
3837 | delete bodyParser; |
3838 | bodyParser = NULL; | |
a46d2c0e | 3839 | } |
d67acb4e | 3840 | |
139a1d68 | 3841 | // XXX: this is an HTTP/1-only operation |
655daa06 AR |
3842 | void |
3843 | ConnStateData::sendControlMsg(HttpControlMsg msg) | |
3844 | { | |
eedd4182 AR |
3845 | if (!isOpen()) { |
3846 | debugs(33, 3, HERE << "ignoring 1xx due to earlier closure"); | |
655daa06 AR |
3847 | return; |
3848 | } | |
3849 | ||
84540b47 | 3850 | // HTTP/1 1xx status messages are only valid when there is a transaction to trigger them |
139a1d68 | 3851 | if (!pipeline.empty()) { |
84540b47 AJ |
3852 | HttpReply::Pointer rep(msg.reply); |
3853 | Must(rep); | |
3854 | // remember the callback | |
3855 | cbControlMsgSent = msg.cbSuccess; | |
3856 | ||
3857 | typedef CommCbMemFunT<HttpControlMsgSink, CommIoCbParams> Dialer; | |
3858 | AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, HttpControlMsgSink::wroteControlMsg); | |
3859 | ||
2f97ab10 CT |
3860 | if (!writeControlMsgAndCall(rep.getRaw(), call)) { |
3861 | // but still inform the caller (so it may resume its operation) | |
3862 | doneWithControlMsg(); | |
3863 | } | |
655daa06 AR |
3864 | return; |
3865 | } | |
3866 | ||
3867 | debugs(33, 3, HERE << " closing due to missing context for 1xx"); | |
73c36fd9 | 3868 | clientConnection->close(); |
655daa06 AR |
3869 | } |
3870 | ||
24e1fd72 | 3871 | void |
2f97ab10 | 3872 | ConnStateData::doneWithControlMsg() |
24e1fd72 | 3873 | { |
2f97ab10 | 3874 | HttpControlMsgSink::doneWithControlMsg(); |
24e1fd72 CT |
3875 | |
3876 | if (Http::StreamPointer deferredRequest = pipeline.front()) { | |
3877 | debugs(33, 3, clientConnection << ": calling PushDeferredIfNeeded after control msg wrote"); | |
3878 | ClientSocketContextPushDeferredIfNeeded(deferredRequest, this); | |
3879 | } | |
3880 | } | |
3881 | ||
d7ce0bcd | 3882 | /// Our close handler called by Comm when the pinned connection is closed |
d67acb4e AJ |
3883 | void |
3884 | ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io) | |
3885 | { | |
7a957a93 AR |
3886 | // FwdState might repin a failed connection sooner than this close |
3887 | // callback is called for the failed connection. | |
693cb033 CT |
3888 | assert(pinning.serverConnection == io.conn); |
3889 | pinning.closeHandler = NULL; // Comm unregisters handlers before calling | |
3890 | const bool sawZeroReply = pinning.zeroReply; // reset when unpinning | |
b54a7c5a | 3891 | pinning.serverConnection->noteClosure(); |
89b1d7a2 | 3892 | unpinConnection(false); |
f8e4867b | 3893 | |
7ac40923 | 3894 | if (sawZeroReply && clientConnection != NULL) { |
693cb033 CT |
3895 | debugs(33, 3, "Closing client connection on pinned zero reply."); |
3896 | clientConnection->close(); | |
85563fd9 | 3897 | } |
f8e4867b | 3898 | |
d67acb4e AJ |
3899 | } |
3900 | ||
b1cf2350 | 3901 | void |
801cfc26 | 3902 | ConnStateData::pinBusyConnection(const Comm::ConnectionPointer &pinServer, const HttpRequest::Pointer &request) |
9e008dda | 3903 | { |
801cfc26 CT |
3904 | pinConnection(pinServer, *request); |
3905 | } | |
d67acb4e | 3906 | |
801cfc26 CT |
3907 | void |
3908 | ConnStateData::notePinnedConnectionBecameIdle(PinnedIdleContext pic) | |
3909 | { | |
3910 | Must(pic.connection); | |
3911 | Must(pic.request); | |
3912 | pinConnection(pic.connection, *pic.request); | |
3913 | ||
3914 | // monitor pinned server connection for remote-end closures. | |
3915 | startPinnedConnectionMonitoring(); | |
3916 | ||
3917 | if (pipeline.empty()) | |
3918 | kick(); // in case clientParseRequests() was blocked by a busy pic.connection | |
89b1d7a2 | 3919 | } |
9e008dda | 3920 | |
801cfc26 | 3921 | /// Forward future client requests using the given server connection. |
89b1d7a2 | 3922 | void |
801cfc26 | 3923 | ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, const HttpRequest &request) |
89b1d7a2 | 3924 | { |
801cfc26 CT |
3925 | if (Comm::IsConnOpen(pinning.serverConnection) && |
3926 | pinning.serverConnection->fd == pinServer->fd) { | |
3927 | debugs(33, 3, "already pinned" << pinServer); | |
3928 | return; | |
3929 | } | |
3930 | ||
89b1d7a2 | 3931 | unpinConnection(true); // closes pinned connection, if any, and resets fields |
9e008dda | 3932 | |
73c36fd9 | 3933 | pinning.serverConnection = pinServer; |
d7ce0bcd | 3934 | |
85563fd9 AR |
3935 | debugs(33, 3, HERE << pinning.serverConnection); |
3936 | ||
89b1d7a2 AR |
3937 | Must(pinning.serverConnection != NULL); |
3938 | ||
d7ce0bcd | 3939 | const char *pinnedHost = "[unknown]"; |
801cfc26 CT |
3940 | pinning.host = xstrdup(request.url.host()); |
3941 | pinning.port = request.url.port(); | |
3942 | pinnedHost = pinning.host; | |
d67acb4e | 3943 | pinning.pinned = true; |
801cfc26 | 3944 | if (CachePeer *aPeer = pinServer->getPeer()) |
8bcf08e0 | 3945 | pinning.peer = cbdataReference(aPeer); |
801cfc26 | 3946 | pinning.auth = request.flags.connectionAuth; |
e3a4aecc | 3947 | char stmp[MAX_IPSTRLEN]; |
89b1d7a2 | 3948 | char desc[FD_DESC_SZ]; |
e3a4aecc | 3949 | snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)", |
801cfc26 | 3950 | (pinning.auth || !pinning.peer) ? pinnedHost : pinning.peer->name, |
4dd643d5 | 3951 | clientConnection->remote.toUrl(stmp,MAX_IPSTRLEN), |
d7ce0bcd | 3952 | clientConnection->fd); |
73c36fd9 | 3953 | fd_note(pinning.serverConnection->fd, desc); |
9e008dda | 3954 | |
d67acb4e | 3955 | typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer; |
4299f876 | 3956 | pinning.closeHandler = JobCallback(33, 5, |
4cb2536f | 3957 | Dialer, this, ConnStateData::clientPinnedConnectionClosed); |
85563fd9 AR |
3958 | // remember the pinned connection so that cb does not unpin a fresher one |
3959 | typedef CommCloseCbParams Params; | |
3960 | Params ¶ms = GetCommParams<Params>(pinning.closeHandler); | |
3961 | params.conn = pinning.serverConnection; | |
73c36fd9 | 3962 | comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler); |
7ac40923 AR |
3963 | } |
3964 | ||
e7ce227f AR |
3965 | /// [re]start monitoring pinned connection for peer closures so that we can |
3966 | /// propagate them to an _idle_ client pinned to that peer | |
7ac40923 AR |
3967 | void |
3968 | ConnStateData::startPinnedConnectionMonitoring() | |
3969 | { | |
3970 | if (pinning.readHandler != NULL) | |
3971 | return; // already monitoring | |
3972 | ||
3973 | typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer; | |
3974 | pinning.readHandler = JobCallback(33, 3, | |
3975 | Dialer, this, ConnStateData::clientPinnedConnectionRead); | |
7e66d5e2 | 3976 | Comm::Read(pinning.serverConnection, pinning.readHandler); |
7ac40923 AR |
3977 | } |
3978 | ||
3979 | void | |
3980 | ConnStateData::stopPinnedConnectionMonitoring() | |
3981 | { | |
3982 | if (pinning.readHandler != NULL) { | |
7e66d5e2 | 3983 | Comm::ReadCancel(pinning.serverConnection->fd, pinning.readHandler); |
7ac40923 AR |
3984 | pinning.readHandler = NULL; |
3985 | } | |
3986 | } | |
3987 | ||
96aedee5 CT |
3988 | #if USE_OPENSSL |
3989 | bool | |
3990 | ConnStateData::handleIdleClientPinnedTlsRead() | |
3991 | { | |
3992 | // A ready-for-reading connection means that the TLS server either closed | |
3993 | // the connection, sent us some unexpected HTTP data, or started TLS | |
3994 | // renegotiations. We should close the connection except for the last case. | |
3995 | ||
3996 | Must(pinning.serverConnection != nullptr); | |
33cc0629 | 3997 | auto ssl = fd_table[pinning.serverConnection->fd].ssl.get(); |
96aedee5 CT |
3998 | if (!ssl) |
3999 | return false; | |
4000 | ||
4001 | char buf[1]; | |
4002 | const int readResult = SSL_read(ssl, buf, sizeof(buf)); | |
4003 | ||
4004 | if (readResult > 0 || SSL_pending(ssl) > 0) { | |
4005 | debugs(83, 2, pinning.serverConnection << " TLS application data read"); | |
4006 | return false; | |
4007 | } | |
4008 | ||
4009 | switch(const int error = SSL_get_error(ssl, readResult)) { | |
4010 | case SSL_ERROR_WANT_WRITE: | |
4011 | debugs(83, DBG_IMPORTANT, pinning.serverConnection << " TLS SSL_ERROR_WANT_WRITE request for idle pinned connection"); | |
737ace5a | 4012 | // fall through to restart monitoring, for now |
96aedee5 CT |
4013 | case SSL_ERROR_NONE: |
4014 | case SSL_ERROR_WANT_READ: | |
4015 | startPinnedConnectionMonitoring(); | |
4016 | return true; | |
4017 | ||
4018 | default: | |
4019 | debugs(83, 2, pinning.serverConnection << " TLS error: " << error); | |
4020 | return false; | |
4021 | } | |
4022 | ||
4023 | // not reached | |
4024 | return true; | |
4025 | } | |
4026 | #endif | |
4027 | ||
7ac40923 AR |
4028 | /// Our read handler called by Comm when the server either closes an idle pinned connection or |
4029 | /// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection. | |
4030 | void | |
4031 | ConnStateData::clientPinnedConnectionRead(const CommIoCbParams &io) | |
4032 | { | |
4033 | pinning.readHandler = NULL; // Comm unregisters handlers before calling | |
4034 | ||
c8407295 | 4035 | if (io.flag == Comm::ERR_CLOSING) |
7ac40923 AR |
4036 | return; // close handler will clean up |
4037 | ||
96aedee5 CT |
4038 | Must(pinning.serverConnection == io.conn); |
4039 | ||
4040 | #if USE_OPENSSL | |
4041 | if (handleIdleClientPinnedTlsRead()) | |
4042 | return; | |
4043 | #endif | |
4044 | ||
e500cc89 | 4045 | const bool clientIsIdle = pipeline.empty(); |
7ac40923 AR |
4046 | |
4047 | debugs(33, 3, "idle pinned " << pinning.serverConnection << " read " << | |
4048 | io.size << (clientIsIdle ? " with idle client" : "")); | |
4049 | ||
7ac40923 AR |
4050 | pinning.serverConnection->close(); |
4051 | ||
4052 | // If we are still sending data to the client, do not close now. When we are done sending, | |
4a4fbcef | 4053 | // ConnStateData::kick() checks pinning.serverConnection and will close. |
7ac40923 AR |
4054 | // However, if we are idle, then we must close to inform the idle client and minimize races. |
4055 | if (clientIsIdle && clientConnection != NULL) | |
4056 | clientConnection->close(); | |
d67acb4e AJ |
4057 | } |
4058 | ||
e3a4aecc | 4059 | const Comm::ConnectionPointer |
a3c6762c | 4060 | ConnStateData::validatePinnedConnection(HttpRequest *request, const CachePeer *aPeer) |
d67acb4e | 4061 | { |
85563fd9 AR |
4062 | debugs(33, 7, HERE << pinning.serverConnection); |
4063 | ||
d67acb4e | 4064 | bool valid = true; |
73c36fd9 | 4065 | if (!Comm::IsConnOpen(pinning.serverConnection)) |
e3a4aecc | 4066 | valid = false; |
5c51bffb | 4067 | else if (pinning.auth && pinning.host && request && strcasecmp(pinning.host, request->url.host()) != 0) |
9e008dda | 4068 | valid = false; |
5c51bffb | 4069 | else if (request && pinning.port != request->url.port()) |
9e008dda | 4070 | valid = false; |
6de3828e | 4071 | else if (pinning.peer && !cbdataReferenceValid(pinning.peer)) |
9e008dda | 4072 | valid = false; |
6de3828e | 4073 | else if (aPeer != pinning.peer) |
9e008dda | 4074 | valid = false; |
d67acb4e | 4075 | |
9e008dda | 4076 | if (!valid) { |
b1cf2350 | 4077 | /* The pinning info is not safe, remove any pinning info */ |
89b1d7a2 | 4078 | unpinConnection(true); |
d67acb4e AJ |
4079 | } |
4080 | ||
73c36fd9 | 4081 | return pinning.serverConnection; |
d67acb4e AJ |
4082 | } |
4083 | ||
89b1d7a2 AR |
4084 | Comm::ConnectionPointer |
4085 | ConnStateData::borrowPinnedConnection(HttpRequest *request, const CachePeer *aPeer) | |
4086 | { | |
4087 | debugs(33, 7, pinning.serverConnection); | |
4088 | if (validatePinnedConnection(request, aPeer) != NULL) | |
f8e4867b | 4089 | stopPinnedConnectionMonitoring(); |
89b1d7a2 AR |
4090 | |
4091 | return pinning.serverConnection; // closed if validation failed | |
4092 | } | |
4093 | ||
b1cf2350 | 4094 | void |
89b1d7a2 | 4095 | ConnStateData::unpinConnection(const bool andClose) |
d67acb4e | 4096 | { |
85563fd9 AR |
4097 | debugs(33, 3, HERE << pinning.serverConnection); |
4098 | ||
9e008dda AJ |
4099 | if (pinning.peer) |
4100 | cbdataReferenceDone(pinning.peer); | |
d67acb4e | 4101 | |
d7ce0bcd | 4102 | if (Comm::IsConnOpen(pinning.serverConnection)) { |
87f237a9 A |
4103 | if (pinning.closeHandler != NULL) { |
4104 | comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler); | |
4105 | pinning.closeHandler = NULL; | |
4106 | } | |
89b1d7a2 | 4107 | |
f8e4867b | 4108 | stopPinnedConnectionMonitoring(); |
89b1d7a2 AR |
4109 | |
4110 | // close the server side socket if requested | |
4111 | if (andClose) | |
4112 | pinning.serverConnection->close(); | |
4113 | pinning.serverConnection = NULL; | |
d67acb4e | 4114 | } |
d7ce0bcd | 4115 | |
d67acb4e | 4116 | safe_free(pinning.host); |
e3a4aecc | 4117 | |
693cb033 CT |
4118 | pinning.zeroReply = false; |
4119 | ||
e3a4aecc AJ |
4120 | /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host |
4121 | * connection has gone away */ | |
d67acb4e | 4122 | } |
44352c16 | 4123 | |
da6dbcd1 EB |
4124 | void |
4125 | ConnStateData::checkLogging() | |
4126 | { | |
4127 | // if we are parsing request body, its request is responsible for logging | |
4128 | if (bodyPipe) | |
4129 | return; | |
4130 | ||
4131 | // a request currently using this connection is responsible for logging | |
4132 | if (!pipeline.empty() && pipeline.back()->mayUseConnection()) | |
4133 | return; | |
4134 | ||
4135 | /* Either we are waiting for the very first transaction, or | |
4136 | * we are done with the Nth transaction and are waiting for N+1st. | |
4137 | * XXX: We assume that if anything was added to inBuf, then it could | |
4138 | * only be consumed by actions already covered by the above checks. | |
4139 | */ | |
4140 | ||
4141 | // do not log connections that closed after a transaction (it is normal) | |
4142 | // TODO: access_log needs ACLs to match received-no-bytes connections | |
6b2b6cfe | 4143 | if (pipeline.nrequests && inBuf.isEmpty()) |
da6dbcd1 EB |
4144 | return; |
4145 | ||
4146 | /* Create a temporary ClientHttpRequest object. Its destructor will log. */ | |
4147 | ClientHttpRequest http(this); | |
4148 | http.req_sz = inBuf.length(); | |
801cfc26 | 4149 | // XXX: Or we died while waiting for the pinned connection to become idle. |
bec110e4 | 4150 | http.setErrorUri("error:transaction-end-before-headers"); |
da6dbcd1 | 4151 | } |
a6678149 | 4152 | |
6b2b6cfe CT |
4153 | bool |
4154 | ConnStateData::mayTunnelUnsupportedProto() | |
4155 | { | |
4156 | return Config.accessList.on_unsupported_protocol | |
4157 | #if USE_OPENSSL | |
aff439e0 SM |
4158 | && |
4159 | ((port->flags.isIntercepted() && port->flags.tunnelSslBumping) | |
4160 | || (serverBump() && pinning.serverConnection)) | |
6b2b6cfe | 4161 | #endif |
aff439e0 | 4162 | ; |
6b2b6cfe | 4163 | } |
aff439e0 | 4164 | |
75d47340 CT |
4165 | NotePairs::Pointer |
4166 | ConnStateData::notes() | |
4167 | { | |
4168 | if (!theNotes) | |
4169 | theNotes = new NotePairs; | |
4170 | return theNotes; | |
4171 | } | |
4172 | ||
801cfc26 CT |
4173 | std::ostream & |
4174 | operator <<(std::ostream &os, const ConnStateData::PinnedIdleContext &pic) | |
4175 | { | |
4176 | return os << pic.connection << ", request=" << pic.request; | |
4177 | } | |
9f107d9a | 4178 |