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