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