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