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