]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
Non-HTTP bypass
[thirdparty/squid.git] / src / client_side.cc
CommitLineData
dd11e0b7 1/*
bde978a6 2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
dd11e0b7 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
dd11e0b7 7 */
f88bb09c 8
bbc27441
AJ
9/* DEBUG: section 33 Client-side Routines */
10
63be0a78 11/**
12 \defgroup ClientSide Client-Side Logics
13 *
d85b8894 14 \section cserrors Errors and client side
edce4d98 15 *
63be0a78 16 \par Problem the first:
17 * the store entry is no longer authoritative on the
edce4d98 18 * reply status. EBITTEST (E_ABORT) is no longer a valid test outside
19 * of client_side_reply.c.
20 * Problem the second: resources are wasted if we delay in cleaning up.
21 * Problem the third we can't depend on a connection close to clean up.
9e008dda 22 *
63be0a78 23 \par Nice thing the first:
9e008dda 24 * Any step in the stream can callback with data
edce4d98 25 * representing an error.
26 * Nice thing the second: once you stop requesting reads from upstream,
27 * upstream can be stopped too.
28 *
63be0a78 29 \par Solution #1:
30 * Error has a callback mechanism to hand over a membuf
9e008dda 31 * with the error content. The failing node pushes that back as the
edce4d98 32 * reply. Can this be generalised to reduce duplicate efforts?
33 * A: Possibly. For now, only one location uses this.
34 * How to deal with pre-stream errors?
35 * Tell client_side_reply that we *want* an error page before any
36 * stream calls occur. Then we simply read as normal.
63be0a78 37 *
38 *
d85b8894 39 \section pconn_logic Persistent connection logic:
63be0a78 40 *
41 \par
42 * requests (httpClientRequest structs) get added to the connection
43 * list, with the current one being chr
9e008dda 44 *
63be0a78 45 \par
46 * The request is *immediately* kicked off, and data flows through
47 * to clientSocketRecipient.
9e008dda 48 *
63be0a78 49 \par
50 * If the data that arrives at clientSocketRecipient is not for the current
51 * request, clientSocketRecipient simply returns, without requesting more
52 * data, or sending it.
53 *
54 \par
9e008dda
AJ
55 * ClientKeepAliveNextRequest will then detect the presence of data in
56 * the next ClientHttpRequest, and will send it, restablishing the
63be0a78 57 * data flow.
edce4d98 58 */
59
582c2af2 60#include "squid.h"
04f55905 61#include "acl/FilledChecklist.h"
65d448bc 62#include "anyp/PortCfg.h"
00406b24 63#include "base/Subscription.h"
d841c88d 64#include "base/TextException.h"
a011edee 65#include "CachePeer.h"
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
148class ListeningStartedDialer: public CallDialer, public Ipc::StartListeningCb
149{
150public:
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
163public:
164 Handler handler;
165
166private:
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 172static void clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub);
fe090a86 173
edce4d98 174/* our socket-related context */
62e76326 175
0655fa4d 176CBDATA_CLASS_INIT(ClientSocketContext);
62e76326 177
edce4d98 178/* Local functions */
2b663917 179static IOCB clientWriteComplete;
180static IOCB clientWriteBodyComplete;
e0d28505 181static IOACB httpAccept;
cb4f4424 182#if USE_OPENSSL
e0d28505 183static IOACB httpsAccept;
40d34a62 184#endif
8d77a37c 185static CTCB clientLifetimeTimeout;
3898f57f 186#if USE_IDENT
05832ae1 187static IDCB clientIdentDone;
3898f57f 188#endif
190154cf 189static int clientIsContentLengthValid(HttpRequest * r);
47f6e231 190static int clientIsRequestBodyTooLargeForPolicy(int64_t bodyLength);
50c09fc4 191
02c8dde5
AJ
192static void clientUpdateStatHistCounters(LogTags logType, int svc_time);
193static void clientUpdateStatCounters(LogTags logType);
c8be6d7b 194static void clientUpdateHierCounters(HierarchyLogEntry *);
528b2c61 195static bool clientPingHasFinished(ping_data const *aPing);
41ebd397 196void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry::Pointer &);
e4a67a80 197#ifndef PURIFY
5c336a3b 198static bool connIsUsable(ConnStateData * conn);
e4a67a80 199#endif
1cf238db 200static void ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest, ConnStateData * conn);
02c8dde5 201static void clientUpdateSocketStats(LogTags logType, size_t size);
c8be6d7b 202
84cc2635 203char *skipLeadingSpace(char *aString);
62e76326 204
c8be6d7b 205clientStreamNode *
528b2c61 206ClientSocketContext::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
214clientStreamNode *
528b2c61 215ClientSocketContext::getClientReplyContext() const
c8be6d7b 216{
528b2c61 217 return (clientStreamNode *)http->client_stream.tail->prev->data;
c8be6d7b 218}
219
434a79b0
DK
220ConnStateData *
221ClientSocketContext::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 */
230void
a46d2c0e 231ConnStateData::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 246void
1cf238db 247ClientSocketContext::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 267ClientSocketContext::~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 290void
291ClientSocketContext::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
300void
301ClientSocketContext::deRegisterWithConn()
302{
303 assert (connRegistered_);
98242069 304 removeFromConnectionList(http->getConn());
0655fa4d 305 connRegistered_ = false;
306}
307
308void
309ClientSocketContext::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 318ClientSocketContext::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
335void
336ClientSocketContext::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
351void
c8407295 352ClientSocketContext::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
375void
c8407295 376ClientSocketContext::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 383static void
edce4d98 384clientIdentDone(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 391void
02c8dde5 392clientUpdateStatCounters(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
405void
02c8dde5 406clientUpdateStatHistCounters(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 446bool
c8be6d7b 447clientPingHasFinished(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
455void
456clientUpdateHierCounters(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 500void
501ClientHttpRequest::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 514void
41ebd397 515prepareLogWithRequestDetails(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
576void
528b2c61 577ClientHttpRequest::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 &notes = 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
669void
528b2c61 670ClientHttpRequest::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
682void
683httpRequestFree(void *data)
684{
59a1efb2 685 ClientHttpRequest *http = (ClientHttpRequest *)data;
c8be6d7b 686 assert(http != NULL);
528b2c61 687 delete http;
7a2f978b 688}
689
a46d2c0e 690bool
691ConnStateData::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
705void
a46d2c0e 706ConnStateData::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
719void
720ConnStateData::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() */
ced8def3 728void ConnStateData::connStateClosed(const CommCloseCbParams &)
7a2f978b 729{
6e1d409c 730 deleteThis("ConnStateData::connStateClosed");
a46d2c0e 731}
62e76326 732
cc1e110a
AJ
733#if USE_AUTH
734void
735ConnStateData::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 815void
6e1d409c 816ConnStateData::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
838bool
839ConnStateData::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
846ConnStateData::~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 870void
59a1efb2 871clientSetKeepaliveFlag(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 882static int
190154cf 883clientIsContentLengthValid(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 901int
47f6e231 902clientIsRequestBodyTooLargeForPolicy(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 912bool
1cf238db 913connIsUsable(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 924ClientSocketContext::Pointer
925ConnStateData::getCurrentContext() const
c8be6d7b 926{
0655fa4d 927 return currentobject;
c8be6d7b 928}
929
930void
2324cda2 931ClientSocketContext::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 942bool
943ClientSocketContext::startOfOutput() const
c8be6d7b 944{
0655fa4d 945 return http->out.size == 0;
c8be6d7b 946}
947
528b2c61 948size_t
47f6e231 949ClientSocketContext::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 971void
528b2c61 972ClientSocketContext::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 988bool
989ClientHttpRequest::multipartRangeRequest() const
990{
991 return request->multipartRangeRequest();
992}
993
994bool
995ClientSocketContext::multipartRangeRequest() const
996{
997 return http->multipartRangeRequest();
998}
999
1000void
1001ClientSocketContext::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 */
1034void
1035ClientSocketContext::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 1047static void
30abd221 1048clientPackTermBound(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 1055static void
30abd221 1056clientPackRangeHdr(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 1091void
2512d159 1092ClientSocketContext::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 */
1176int
1177ClientHttpRequest::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 */
1216static int
59a1efb2 1217clientIfRangeMatch(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 1254String
528b2c61 1255ClientHttpRequest::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 1266void
1267ClientSocketContext::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
1380void
1381ClientSocketContext::prepareReply(HttpReply * rep)
1382{
fedd1531 1383 reply = rep;
1384
528b2c61 1385 if (http->request->range)
62e76326 1386 buildRangeHeader(rep);
528b2c61 1387}
1388
1389void
1390ClientSocketContext::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 1437void
59a1efb2 1438clientSocketRecipient(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 */
1470void
59a1efb2 1471clientSocketDetach(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 1491static void
ced8def3 1492clientWriteBodyComplete(const Comm::ConnectionPointer &conn, char *, size_t size, Comm::Flag errflag, int xerrno, void *data)
f4f278b5 1493{
ced8def3 1494 debugs(33,7, "schedule clientWriteComplete");
e0d28505 1495 clientWriteComplete(conn, NULL, size, errflag, xerrno, data);
c8be6d7b 1496}
1497
1498void
a46d2c0e 1499ConnStateData::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);
c5c06f02 1510 commSetConnTimeout(clientConnection, clientConnection->timeLeft(idleTimeout()), timeoutCall);
1cf238db 1511
a46d2c0e 1512 readSomeData();
63be0a78 1513 /** Please don't do anything with the FD past here! */
c8be6d7b 1514}
1515
09d3938c 1516static void
1cf238db 1517ClientSocketContextPushDeferredIfNeeded(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 1539void
1540ClientSocketContext::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 1622void
02c8dde5 1623clientUpdateSocketStats(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 1641bool
1642ClientSocketContext::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 1663int64_t
528b2c61 1664ClientSocketContext::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 1709void
528b2c61 1710ClientSocketContext::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 1728clientStream_status_t
528b2c61 1729ClientSocketContext::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 1785void
ced8def3 1786clientWriteComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, Comm::Flag errflag, int, 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
1793void
1794ClientSocketContext::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 1804void
1805ClientSocketContext::doClose()
1806{
73c36fd9 1807 clientConnection->close();
55e44db9 1808}
1809
cf6eb29e 1810/// called when we encounter a response-related error
55e44db9 1811void
5f8252d2 1812ClientSocketContext::initiateClose(const char *reason)
55e44db9 1813{
cf6eb29e
CT
1814 http->getConn()->stopSending(reason); // closes ASAP
1815}
5f8252d2 1816
cf6eb29e
CT
1817void
1818ConnStateData::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 1841void
ced8def3 1842ClientSocketContext::writeComplete(const Comm::ConnectionPointer &conn, char *, 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
1889ClientSocketContext *
1890ConnStateData::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 1906char *
1907skipLeadingSpace(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 */
1922const char *
1923findTrailingHTTPVersion(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 1945void
727552f4 1946setLogUri(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 1996static void
9bafa70d 1997prepareAcceleratedURL(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
2106static void
9bafa70d 2107prepareTransparentURL(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 2148ClientSocketContext *
9bafa70d 2149parseHttpRequest(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
3248e962
CT
2155 if (csd->port->flags.isIntercepted() && Config.accessList.on_unsupported_protocol)
2156 csd->preservedClientData = csd->in.buf;
36a9c964 2157 // sync the buffers after parsing.
9bafa70d 2158 csd->in.buf = hp->remaining();
7a4fa6a0 2159
9bafa70d 2160 if (hp->needsMoreData()) {
87abd755
AJ
2161 debugs(33, 5, "Incomplete request, waiting for end of request line");
2162 return NULL;
2163 }
fc68f6b1 2164
016a316b 2165 if (!parsedOk) {
a4c74dd8 2166 if (hp->request_parse_status == Http::scRequestHeaderFieldsTooLarge || hp->request_parse_status == Http::scUriTooLong)
943cdf6d 2167 return csd->abortRequestParsing("error:request-too-large");
016a316b 2168
943cdf6d 2169 return csd->abortRequestParsing("error:invalid-request");
016a316b 2170 }
84cc2635 2171 }
fc68f6b1 2172
6d0613b2
AJ
2173 /* We know the whole request is in parser now */
2174 debugs(11, 2, "HTTP Client " << csd->clientConnection);
2175 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" <<
9bafa70d
AJ
2176 hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol() << "\n" <<
2177 hp->mimeHeader() <<
6d0613b2 2178 "\n----------");
fc68f6b1 2179
adf29627 2180 /* deny CONNECT via accelerated ports */
9bafa70d 2181 if (hp->method() == Http::METHOD_CONNECT && csd->port != NULL && csd->port->flags.accelSurrogate) {
4599cded 2182 debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->transferProtocol << " Accelerator port " << csd->port->s.port());
9bafa70d
AJ
2183 debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
2184 hp->request_parse_status = Http::scMethodNotAllowed;
eacfca83 2185 return csd->abortRequestParsing("error:method-not-allowed");
adf29627
AJ
2186 }
2187
5de5c2d0
AJ
2188 /* draft-ietf-httpbis-http2-16 section 11.6 registers the method PRI as HTTP/2 specific
2189 * Deny "PRI" method if used in HTTP/1.x or 0.9 versions.
2190 * If seen it signals a broken client or proxy has corrupted the traffic.
2191 */
2192 if (hp->method() == Http::METHOD_PRI && hp->messageProtocol() < Http::ProtocolVersion(2,0)) {
2193 debugs(33, DBG_IMPORTANT, "WARNING: PRI method received on " << csd->transferProtocol << " port " << csd->port->s.port());
2194 debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
2195 hp->request_parse_status = Http::scMethodNotAllowed;
2196 return csd->abortRequestParsing("error:method-not-allowed");
2197 }
2198
9bafa70d
AJ
2199 if (hp->method() == Http::METHOD_NONE) {
2200 debugs(33, DBG_IMPORTANT, "WARNING: Unsupported method: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
2201 hp->request_parse_status = Http::scMethodNotAllowed;
eacfca83 2202 return csd->abortRequestParsing("error:unsupported-request-method");
3f38a55e 2203 }
7a2f978b 2204
6d0613b2
AJ
2205 // Process headers after request line
2206 debugs(33, 3, "complete request received. " <<
9bafa70d
AJ
2207 "prefix_sz = " << hp->messageHeaderSize() <<
2208 ", request-line-size=" << hp->firstLineSize() <<
2209 ", mime-header-size=" << hp->headerBlockSize() <<
2210 ", mime header block:\n" << hp->mimeHeader() << "\n----------");
62e76326 2211
7a2f978b 2212 /* Ok, all headers are received */
9ff1b8ca
AJ
2213 ClientHttpRequest *http = new ClientHttpRequest(csd);
2214
9bafa70d 2215 http->req_sz = hp->messageHeaderSize();
b9f85998 2216 ClientSocketContext *result = new ClientSocketContext(csd->clientConnection, http);
62e76326 2217
9ff1b8ca 2218 StoreIOBuffer tempBuffer;
c8be6d7b 2219 tempBuffer.data = result->reqbuf;
2220 tempBuffer.length = HTTP_REQBUF_SZ;
62e76326 2221
0655fa4d 2222 ClientStreamData newServer = new clientReplyContext(http);
0655fa4d 2223 ClientStreamData newClient = result;
edce4d98 2224 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 2225 clientReplyStatus, newServer, clientSocketRecipient,
2226 clientSocketDetach, newClient, tempBuffer);
62e76326 2227
3ff65596 2228 /* set url */
b1cef121
AJ
2229 // XXX: c_str() does re-allocate but here replaces explicit malloc/free.
2230 // when internalCheck() accepts SBuf removing this will be a net gain for performance.
f9688132
AJ
2231 SBuf tmp(hp->requestUri());
2232 const char *url = tmp.c_str();
7a2f978b 2233
6a25a046 2234 debugs(33,5, HERE << "repare absolute URL from " <<
2ee34428 2235 (csd->transparent()?"intercept":(csd->port->flags.accelSurrogate ? "accel":"")));
3f38a55e 2236 /* Rewrite the URL in transparent or accelerator mode */
89272111
AJ
2237 /* NP: there are several cases to traverse here:
2238 * - standard mode (forward proxy)
2239 * - transparent mode (TPROXY)
2240 * - transparent mode with failures
2241 * - intercept mode (NAT)
2242 * - intercept mode with failures
2243 * - accelerator mode (reverse proxy)
2244 * - internal URL
2245 * - mixed combos of the above with internal URL
151ba0d4
AJ
2246 * - remote interception with PROXY protocol
2247 * - remote reverse-proxy with PROXY protocol
89272111 2248 */
be364179 2249 if (csd->transparent()) {
89272111 2250 /* intercept or transparent mode, properly working with no failures */
5f3cc9a2 2251 prepareTransparentURL(csd, http, hp);
89272111 2252
2f2749d7 2253 } else if (internalCheck(url)) {
89272111 2254 /* internal URL mode */
2f2749d7 2255 /* prepend our name & port */
2256 http->uri = xstrdup(internalLocalUri(NULL, url));
59c59acf
AJ
2257 // We just re-wrote the URL. Must replace the Host: header.
2258 // But have not parsed there yet!! flag for local-only handling.
be4d35dc 2259 http->flags.internal = true;
59c59acf 2260
6a25a046 2261 } else if (csd->port->flags.accelSurrogate || csd->switchedToHttps()) {
59c59acf 2262 /* accelerator mode */
5f3cc9a2 2263 prepareAcceleratedURL(csd, http, hp);
3f38a55e 2264 }
2265
2266 if (!http->uri) {
62e76326 2267 /* No special rewrites have been applied above, use the
2268 * requested url. may be rewritten later, so make extra room */
9bafa70d 2269 int url_sz = hp->requestUri().length() + Config.appendDomainLen + 5;
62e76326 2270 http->uri = (char *)xcalloc(url_sz, 1);
2271 strcpy(http->uri, url);
3f38a55e 2272 }
62e76326 2273
c4b7a5a9 2274 result->flags.parsed_ok = 1;
c8be6d7b 2275 return result;
7a2f978b 2276}
2277
1368d115 2278bool
8a64f7f1 2279ConnStateData::In::maybeMakeSpaceAvailable()
c8be6d7b 2280{
8a64f7f1
AJ
2281 if (buf.spaceSize() < 2) {
2282 const SBuf::size_type haveCapacity = buf.length() + buf.spaceSize();
e7287625 2283 if (haveCapacity >= Config.maxRequestBufferSize) {
90737510
A
2284 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config.maxRequestBufferSize);
2285 return false;
2286 }
50ae17d6
AJ
2287 if (haveCapacity == 0) {
2288 // haveCapacity is based on the SBuf visible window of the MemBlob buffer, which may fill up.
2289 // at which point bump the buffer back to default. This allocates a new MemBlob with any un-parsed bytes.
2290 buf.reserveCapacity(CLIENT_REQ_BUF_SZ);
2291 } else {
2292 const SBuf::size_type wantCapacity = min(static_cast<SBuf::size_type>(Config.maxRequestBufferSize), haveCapacity*2);
2293 buf.reserveCapacity(wantCapacity);
2294 }
8a64f7f1 2295 debugs(33, 2, "growing request buffer: available=" << buf.spaceSize() << " used=" << buf.length());
c8be6d7b 2296 }
8a64f7f1 2297 return (buf.spaceSize() >= 2);
c8be6d7b 2298}
2299
2300void
0655fa4d 2301ConnStateData::addContextToQueue(ClientSocketContext * context)
c8be6d7b 2302{
0655fa4d 2303 ClientSocketContext::Pointer *S;
62e76326 2304
0655fa4d 2305 for (S = (ClientSocketContext::Pointer *) & currentobject; S->getRaw();
3d0ac046 2306 S = &(*S)->next);
c8be6d7b 2307 *S = context;
62e76326 2308
0655fa4d 2309 ++nrequests;
c8be6d7b 2310}
2311
2312int
0655fa4d 2313ConnStateData::getConcurrentRequestCount() const
c8be6d7b 2314{
2315 int result = 0;
0655fa4d 2316 ClientSocketContext::Pointer *T;
62e76326 2317
0655fa4d 2318 for (T = (ClientSocketContext::Pointer *) &currentobject;
3d0ac046 2319 T->getRaw(); T = &(*T)->next, ++result);
c8be6d7b 2320 return result;
2321}
2322
c8be6d7b 2323int
1cf238db 2324ConnStateData::connFinishedWithConn(int size)
c8be6d7b 2325{
2326 if (size == 0) {
e7287625 2327 if (getConcurrentRequestCount() == 0 && in.buf.isEmpty()) {
62e76326 2328 /* no current or pending requests */
73c36fd9 2329 debugs(33, 4, HERE << clientConnection << " closed");
62e76326 2330 return 1;
2331 } else if (!Config.onoff.half_closed_clients) {
2332 /* admin doesn't want to support half-closed client sockets */
73c36fd9 2333 debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)");
f692498b 2334 notifyAllContexts(0); // no specific error implies abort
62e76326 2335 return 1;
2336 }
c8be6d7b 2337 }
62e76326 2338
c8be6d7b 2339 return 0;
2340}
2341
92ae4c86
AR
2342void
2343ConnStateData::consumeInput(const size_t byteCount)
2344{
2345 assert(byteCount > 0 && byteCount <= in.buf.length());
2346 in.buf.consume(byteCount);
2347 debugs(33, 5, "in.buf has " << in.buf.length() << " unused bytes");
2348}
2349
1cf238db 2350void
f35961af 2351ConnStateData::clientAfterReadingRequests()
c4b7a5a9 2352{
39cb8c41 2353 // Were we expecting to read more request body from half-closed connection?
73c36fd9
AJ
2354 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) {
2355 debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection);
2356 clientConnection->close();
39cb8c41 2357 return;
c4b7a5a9 2358 }
2359
f35961af
AR
2360 if (flags.readMore)
2361 readSomeData();
c4b7a5a9 2362}
2363
84c77748
AR
2364void
2365ConnStateData::quitAfterError(HttpRequest *request)
2366{
2367 // From HTTP p.o.v., we do not have to close after every error detected
2368 // at the client-side, but many such errors do require closure and the
2369 // client-side code is bad at handling errors so we play it safe.
2370 if (request)
e857372a 2371 request->flags.proxyKeepalive = false;
84c77748
AR
2372 flags.readMore = false;
2373 debugs(33,4, HERE << "Will close after error: " << clientConnection);
2374}
2375
cb4f4424 2376#if USE_OPENSSL
8eb0a7ee
CT
2377bool ConnStateData::serveDelayedError(ClientSocketContext *context)
2378{
2379 ClientHttpRequest *http = context->http;
fd4624d7
CT
2380
2381 if (!sslServerBump)
8eb0a7ee
CT
2382 return false;
2383
fd4624d7 2384 assert(sslServerBump->entry);
7a957a93 2385 // Did we create an error entry while processing CONNECT?
fd4624d7 2386 if (!sslServerBump->entry->isEmpty()) {
84c77748
AR
2387 quitAfterError(http->request);
2388
7a957a93
AR
2389 // Get the saved error entry and send it to the client by replacing the
2390 // ClientHttpRequest store entry with it.
8eb0a7ee
CT
2391 clientStreamNode *node = context->getClientReplyContext();
2392 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
7a957a93
AR
2393 assert(repContext);
2394 debugs(33, 5, "Responding with delated error for " << http->uri);
f0baf149 2395 repContext->setReplyToStoreEntry(sslServerBump->entry, "delayed SslBump error");
7a957a93
AR
2396
2397 // save the original request for logging purposes
b248c2a3
AJ
2398 if (!context->http->al->request) {
2399 context->http->al->request = http->request;
2400 HTTPMSGLOCK(context->http->al->request);
2401 }
7a957a93
AR
2402
2403 // Get error details from the fake certificate-peeking request.
129fe2a1 2404 http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
8eb0a7ee 2405 context->pullData();
8eb0a7ee
CT
2406 return true;
2407 }
2408
7a957a93
AR
2409 // In bump-server-first mode, we have not necessarily seen the intended
2410 // server name at certificate-peeking time. Check for domain mismatch now,
2411 // when we can extract the intended name from the bumped HTTP request.
62a7607e 2412 if (X509 *srvCert = sslServerBump->serverCert.get()) {
8eb0a7ee 2413 HttpRequest *request = http->request;
62a7607e 2414 if (!Ssl::checkX509ServerValidity(srvCert, request->GetHost())) {
7a957a93
AR
2415 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2416 "does not match domainname " << request->GetHost());
8eb0a7ee 2417
d4a56c34 2418 bool allowDomainMismatch = false;
638402dd
AJ
2419 if (Config.ssl_client.cert_error) {
2420 ACLFilledChecklist check(Config.ssl_client.cert_error, request, dash_str);
62a7607e 2421 check.sslErrors = new Ssl::CertErrors(Ssl::CertError(SQUID_X509_V_ERR_DOMAIN_MISMATCH, srvCert));
d4a56c34 2422 allowDomainMismatch = (check.fastCheck() == ACCESS_ALLOWED);
638402dd
AJ
2423 delete check.sslErrors;
2424 check.sslErrors = NULL;
2425 }
8eb0a7ee 2426
7d82c5b8 2427 if (!allowDomainMismatch) {
84c77748
AR
2428 quitAfterError(request);
2429
8eb0a7ee
CT
2430 clientStreamNode *node = context->getClientReplyContext();
2431 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2432 assert (repContext);
2433
7a957a93 2434 // Fill the server IP and hostname for error page generation.
fd4624d7
CT
2435 HttpRequest::Pointer const & peekerRequest = sslServerBump->request;
2436 request->hier.note(peekerRequest->hier.tcpServer, request->GetHost());
7a957a93 2437
8eb0a7ee 2438 // Create an error object and fill it
955394ce 2439 ErrorState *err = new ErrorState(ERR_SECURE_CONNECT_FAIL, Http::scServiceUnavailable, request);
8eb0a7ee 2440 err->src_addr = clientConnection->remote;
7a957a93
AR
2441 Ssl::ErrorDetail *errDetail = new Ssl::ErrorDetail(
2442 SQUID_X509_V_ERR_DOMAIN_MISMATCH,
62a7607e 2443 srvCert, NULL);
8eb0a7ee 2444 err->detail = errDetail;
7a957a93 2445 // Save the original request for logging purposes.
b248c2a3
AJ
2446 if (!context->http->al->request) {
2447 context->http->al->request = request;
2448 HTTPMSGLOCK(context->http->al->request);
2449 }
8eb0a7ee
CT
2450 repContext->setReplyToError(request->method, err);
2451 assert(context->http->out.offset == 0);
2452 context->pullData();
8eb0a7ee
CT
2453 return true;
2454 }
2455 }
2456 }
2457
2458 return false;
2459}
cb4f4424 2460#endif // USE_OPENSSL
8eb0a7ee 2461
3248e962
CT
2462/**
2463 * Check on_unsupported_protocol checklist and return true if tunnel mode selected
2464 * or false otherwise
2465 */
2466bool
2467clientTunnelOnError(ConnStateData *conn, ClientSocketContext *context, HttpRequest *request, const HttpRequestMethod& method, err_type requestError, Http::StatusCode errStatusCode, const char *requestErrorBytes)
2468{
2469 if (conn->port->flags.isIntercepted() &&
2470 Config.accessList.on_unsupported_protocol && conn->nrequests <= 1) {
2471 ACLFilledChecklist checklist(Config.accessList.on_unsupported_protocol, request, NULL);
2472 checklist.requestErrorType = requestError;
2473 checklist.src_addr = conn->clientConnection->remote;
2474 checklist.my_addr = conn->clientConnection->local;
2475 checklist.conn(conn);
2476 allow_t answer = checklist.fastCheck();
2477 if (answer == ACCESS_ALLOWED && answer.kind == 1) {
2478 debugs(33, 3, "Request will be tunneled to server");
2479 if (context)
2480 context->removeFromConnectionList(conn);
2481 Comm::SetSelect(conn->clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
2482
2483 SBuf preReadData;
2484 if (conn->preservedClientData.length())
2485 preReadData.append(conn->preservedClientData);
2486 static char ip[MAX_IPSTRLEN];
2487 conn->clientConnection->local.toUrl(ip, sizeof(ip));
2488 conn->in.buf.assign("CONNECT ").append(ip).append(" HTTP/1.1\r\nHost: ").append(ip).append("\r\n\r\n").append(preReadData);
2489
2490 bool ret = conn->handleReadData();
2491 if (ret)
2492 ret = conn->clientParseRequests();
2493
2494 if (!ret) {
2495 debugs(33, 2, "Failed to start fake CONNECT request for on_unsupported_protocol: " << conn->clientConnection);
2496 conn->clientConnection->close();
2497 }
2498 return true;
2499 } else {
2500 debugs(33, 3, "Continue with returning the error: " << requestError);
2501 }
2502 }
2503
2504 if (context) {
2505 conn->quitAfterError(request);
2506 clientStreamNode *node = context->getClientReplyContext();
2507 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2508 assert (repContext);
2509
2510 repContext->setReplyToError(requestError, errStatusCode, method, context->http->uri, conn->clientConnection->remote, NULL, requestErrorBytes, NULL);
2511
2512 assert(context->http->out.offset == 0);
2513 context->pullData();
2514 } // else Probably an ERR_REQUEST_START_TIMEOUT error so just return.
2515 return false;
2516}
2517
ec69bdb2 2518void
28fd6d0b
AJ
2519clientProcessRequestFinished(ConnStateData *conn, const HttpRequest::Pointer &request)
2520{
2521 /*
2522 * DPW 2007-05-18
2523 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2524 * to here because calling comm_reset_close() causes http to
48a37aee 2525 * be freed before accessing.
28fd6d0b
AJ
2526 */
2527 if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
2528 debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection);
2529 conn->flags.readMore = false;
2530 comm_reset_close(conn->clientConnection);
2531 }
2532}
2533
9bafa70d
AJ
2534void
2535clientProcessRequest(ConnStateData *conn, const Http1::RequestParserPointer &hp, ClientSocketContext *context)
c4b7a5a9 2536{
59a1efb2 2537 ClientHttpRequest *http = context->http;
39cb8c41 2538 bool chunked = false;
e18b8316 2539 bool mustReplyToOptions = false;
3ff65596 2540 bool unsupportedTe = false;
39cb8c41 2541 bool expectBody = false;
5f8252d2 2542
ec69bdb2
CT
2543 // We already have the request parsed and checked, so we
2544 // only need to go through the final body/conn setup to doCallouts().
2545 assert(http->request);
2546 HttpRequest::Pointer request = http->request;
2547
92ae4c86 2548 // temporary hack to avoid splitting this huge function with sensitive code
f9688132 2549 const bool isFtp = !hp;
9bafa70d 2550
92ae4c86
AR
2551 // Some blobs below are still HTTP-specific, but we would have to rewrite
2552 // this entire function to remove them from the FTP code path. Connection
2553 // setup and body_pipe preparation blobs are needed for FTP.
2554
40d34a62
AJ
2555 request->clientConnectionManager = conn;
2556
c4b7a5a9 2557 request->flags.accelerated = http->flags.accel;
450fe1cb 2558 request->flags.sslBumped=conn->switchedToHttps();
450fe1cb 2559 request->flags.ignoreCc = conn->port->ignore_cc;
7fb65ee4 2560 // TODO: decouple http->flags.accel from request->flags.sslBumped
450fe1cb 2561 request->flags.noDirect = (request->flags.accelerated && !request->flags.sslBumped) ?
e4a14600 2562 !conn->port->allow_direct : 0;
21512911
CT
2563#if USE_AUTH
2564 if (request->flags.sslBumped) {
cc1e110a
AJ
2565 if (conn->getAuth() != NULL)
2566 request->auth_user_request = conn->getAuth();
21512911
CT
2567 }
2568#endif
2ad20b4f
AJ
2569
2570 /** \par
2571 * If transparent or interception mode is working clone the transparent and interception flags
2572 * from the port settings to the request.
2573 */
40d34a62 2574 if (http->clientConnection != NULL) {
304a6180 2575 request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0);
0d901ef4 2576 request->flags.interceptTproxy = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
13edf4cc
AJ
2577 static const bool proxyProtocolPort = (conn->port != NULL) ? conn->port->flags.proxySurrogate : false;
2578 if (request->flags.interceptTproxy && !proxyProtocolPort) {
0d901ef4
SH
2579 if (Config.accessList.spoof_client_ip) {
2580 ACLFilledChecklist *checklist = clientAclChecklistCreate(Config.accessList.spoof_client_ip, http);
2581 request->flags.spoofClientIp = (checklist->fastCheck() == ACCESS_ALLOWED);
2582 delete checklist;
2583 } else
2584 request->flags.spoofClientIp = true;
2585 } else
2586 request->flags.spoofClientIp = false;
2ad20b4f 2587 }
fc68f6b1 2588
5b4117d8 2589 if (internalCheck(request->urlpath.termedBuf())) {
4e3f4dc7
AJ
2590 if (internalHostnameIs(request->GetHost()) && request->port == getMyPort()) {
2591 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2592 ':' << request->port);
be4d35dc 2593 http->flags.internal = true;
9c175897 2594 } else if (Config.onoff.global_internal_static && internalStaticCheck(request->urlpath.termedBuf())) {
4e3f4dc7
AJ
2595 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2596 ':' << request->port << " (global_internal_static on)");
cc192b50 2597 request->SetHost(internalHostname());
f024c970 2598 request->port = getMyPort();
be4d35dc 2599 http->flags.internal = true;
4e3f4dc7
AJ
2600 } else
2601 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2602 ':' << request->port << " (not this proxy)");
f024c970 2603 }
e72a0ec0 2604
c4b7a5a9 2605 request->flags.internal = http->flags.internal;
b248c2a3 2606 setLogUri (http, urlCanonicalClean(request.getRaw()));
73c36fd9 2607 request->client_addr = conn->clientConnection->remote; // XXX: remove reuest->client_addr member.
3d674977 2608#if FOLLOW_X_FORWARDED_FOR
40d34a62
AJ
2609 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2610 // not a details about teh TCP connection itself
73c36fd9 2611 request->indirect_client_addr = conn->clientConnection->remote;
3d674977 2612#endif /* FOLLOW_X_FORWARDED_FOR */
73c36fd9 2613 request->my_addr = conn->clientConnection->local;
35fb56c9 2614 request->myportname = conn->port->name;
9bafa70d
AJ
2615
2616 if (!isFtp) {
2617 // XXX: for non-HTTP messages instantiate a different HttpMsg child type
2618 // for now Squid only supports HTTP requests
2619 const AnyP::ProtocolVersion &http_ver = hp->messageProtocol();
2620 assert(request->http_ver.protocol == http_ver.protocol);
2621 request->http_ver.major = http_ver.major;
2622 request->http_ver.minor = http_ver.minor;
2623 }
62e76326 2624
9174ba3d
AJ
2625 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2626 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2627 request->clientConnectionManager = conn;
2628
39cb8c41
AR
2629 if (request->header.chunked()) {
2630 chunked = true;
2631 } else if (request->header.has(HDR_TRANSFER_ENCODING)) {
2632 const String te = request->header.getList(HDR_TRANSFER_ENCODING);
2633 // HTTP/1.1 requires chunking to be the last encoding if there is one
2634 unsupportedTe = te.size() && te != "identity";
2635 } // else implied identity coding
de48b288 2636
f9688132 2637 mustReplyToOptions = (request->method == Http::METHOD_OPTIONS) &&
d916dcb8 2638 (request->header.getInt64(HDR_MAX_FORWARDS) == 0);
b248c2a3 2639 if (!urlCheckRequest(request.getRaw()) || mustReplyToOptions || unsupportedTe) {
62e76326 2640 clientStreamNode *node = context->getClientReplyContext();
b248c2a3 2641 conn->quitAfterError(request.getRaw());
0655fa4d 2642 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2643 assert (repContext);
955394ce 2644 repContext->setReplyToError(ERR_UNSUP_REQ, Http::scNotImplemented, request->method, NULL,
b248c2a3 2645 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2646 assert(context->http->out.offset == 0);
2647 context->pullData();
28fd6d0b
AJ
2648 clientProcessRequestFinished(conn, request);
2649 return;
c4b7a5a9 2650 }
2651
b248c2a3 2652 if (!chunked && !clientIsContentLengthValid(request.getRaw())) {
62e76326 2653 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2654 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2655 assert (repContext);
b248c2a3 2656 conn->quitAfterError(request.getRaw());
0655fa4d 2657 repContext->setReplyToError(ERR_INVALID_REQ,
955394ce 2658 Http::scLengthRequired, request->method, NULL,
b248c2a3 2659 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2660 assert(context->http->out.offset == 0);
2661 context->pullData();
28fd6d0b
AJ
2662 clientProcessRequestFinished(conn, request);
2663 return;
c4b7a5a9 2664 }
2665
52b601ff 2666 if (request->header.has(HDR_EXPECT)) {
655daa06
AR
2667 const String expect = request->header.getList(HDR_EXPECT);
2668 const bool supportedExpect = (expect.caseCmp("100-continue") == 0);
2669 if (!supportedExpect) {
52b601ff
AJ
2670 clientStreamNode *node = context->getClientReplyContext();
2671 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2672 assert (repContext);
b248c2a3 2673 conn->quitAfterError(request.getRaw());
955394ce 2674 repContext->setReplyToError(ERR_INVALID_REQ, Http::scExpectationFailed, request->method, http->uri,
b248c2a3 2675 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
52b601ff
AJ
2676 assert(context->http->out.offset == 0);
2677 context->pullData();
28fd6d0b
AJ
2678 clientProcessRequestFinished(conn, request);
2679 return;
52b601ff
AJ
2680 }
2681 }
2682
92ae4c86 2683 clientSetKeepaliveFlag(http);
f35961af 2684 // Let tunneling code be fully responsible for CONNECT requests
c2a7cefd 2685 if (http->request->method == Http::METHOD_CONNECT) {
b66e0e86 2686 context->mayUseConnection(true);
f35961af
AR
2687 conn->flags.readMore = false;
2688 }
fc68f6b1 2689
cb4f4424 2690#if USE_OPENSSL
28fd6d0b 2691 if (conn->switchedToHttps() && conn->serveDelayedError(context)) {
28fd6d0b
AJ
2692 clientProcessRequestFinished(conn, request);
2693 return;
2694 }
061bbdec
CT
2695#endif
2696
b66e0e86 2697 /* Do we expect a request-body? */
39cb8c41
AR
2698 expectBody = chunked || request->content_length > 0;
2699 if (!context->mayUseConnection() && expectBody) {
2700 request->body_pipe = conn->expectRequestBody(
de48b288 2701 chunked ? -1 : request->content_length);
5f8252d2 2702
62e76326 2703 /* Is it too large? */
39cb8c41 2704 if (!chunked && // if chunked, we will check as we accumulate
de48b288 2705 clientIsRequestBodyTooLargeForPolicy(request->content_length)) {
62e76326 2706 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2707 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2708 assert (repContext);
b248c2a3 2709 conn->quitAfterError(request.getRaw());
0655fa4d 2710 repContext->setReplyToError(ERR_TOO_BIG,
f11c8e2f 2711 Http::scPayloadTooLarge, Http::METHOD_NONE, NULL,
73c36fd9 2712 conn->clientConnection->remote, http->request, NULL, NULL);
62e76326 2713 assert(context->http->out.offset == 0);
2714 context->pullData();
28fd6d0b
AJ
2715 clientProcessRequestFinished(conn, request);
2716 return;
62e76326 2717 }
2718
92ae4c86 2719 if (!isFtp) {
a5d444a5
DK
2720 // We may stop producing, comm_close, and/or call setReplyToError()
2721 // below, so quit on errors to avoid http->doCallouts()
28fd6d0b
AJ
2722 if (!conn->handleRequestBodyData()) {
2723 clientProcessRequestFinished(conn, request);
2724 return;
2725 }
39cb8c41 2726
a5d444a5 2727 if (!request->body_pipe->productionEnded()) {
e7ce227f 2728 debugs(33, 5, "need more request body");
a5d444a5
DK
2729 context->mayUseConnection(true);
2730 assert(conn->flags.readMore);
2731 }
f35961af 2732 }
c4b7a5a9 2733 }
2734
de31d06f 2735 http->calloutContext = new ClientRequestContext(http);
2736
2737 http->doCallouts();
9e008dda 2738
28fd6d0b 2739 clientProcessRequestFinished(conn, request);
c4b7a5a9 2740}
2741
92ae4c86
AR
2742int
2743ConnStateData::pipelinePrefetchMax() const
2744{
2745 return Config.pipeline_max_prefetch;
2746}
2747
079a8480
AJ
2748/**
2749 * Limit the number of concurrent requests.
2750 * \return true when there are available position(s) in the pipeline queue for another request.
2751 * \return false when the pipeline queue is full or disabled.
2752 */
2753bool
2754ConnStateData::concurrentRequestQueueFilled() const
c4b7a5a9 2755{
079a8480
AJ
2756 const int existingRequestCount = getConcurrentRequestCount();
2757
2758 // default to the configured pipeline size.
2759 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
92ae4c86 2760 const int concurrentRequestLimit = pipelinePrefetchMax() + 1;
62e76326 2761
079a8480
AJ
2762 // when queue filled already we cant add more.
2763 if (existingRequestCount >= concurrentRequestLimit) {
2764 debugs(33, 3, clientConnection << " max concurrent requests reached (" << concurrentRequestLimit << ")");
2765 debugs(33, 5, clientConnection << " deferring new request until one is done");
2766 return true;
c4b7a5a9 2767 }
62e76326 2768
079a8480 2769 return false;
c4b7a5a9 2770}
2771
00d0ce87 2772/**
d3d92daa 2773 * Perform proxy_protocol_access ACL tests on the client which
3bd97e7e
AJ
2774 * connected to PROXY protocol port to see if we trust the
2775 * sender enough to accept their PROXY header claim.
00d0ce87 2776 */
6658cc16 2777bool
00d0ce87
AJ
2778ConnStateData::proxyProtocolValidateClient()
2779{
d3d92daa
AJ
2780 if (!Config.accessList.proxyProtocol)
2781 return proxyProtocolError("PROXY client not permitted by default ACL");
2782
2783 ACLFilledChecklist ch(Config.accessList.proxyProtocol, NULL, clientConnection->rfc931);
00d0ce87
AJ
2784 ch.src_addr = clientConnection->remote;
2785 ch.my_addr = clientConnection->local;
6658cc16 2786 ch.conn(this);
00d0ce87 2787
3bd97e7e
AJ
2788 if (ch.fastCheck() != ACCESS_ALLOWED)
2789 return proxyProtocolError("PROXY client not permitted by ACLs");
2790
6658cc16 2791 return true;
00d0ce87
AJ
2792}
2793
2794/**
2795 * Perform cleanup on PROXY protocol errors.
2796 * If header parsing hits a fatal error terminate the connection,
2797 * otherwise wait for more data.
2798 */
2799bool
3bd97e7e 2800ConnStateData::proxyProtocolError(const char *msg)
00d0ce87 2801{
3c082dbe 2802 if (msg) {
70a16fea
AJ
2803 // This is important to know, but maybe not so much that flooding the log is okay.
2804#if QUIET_PROXY_PROTOCOL
2805 // display the first of every 32 occurances at level 1, the others at level 2.
2806 static uint8_t hide = 0;
2807 debugs(33, (hide++ % 32 == 0 ? DBG_IMPORTANT : 2), msg << " from " << clientConnection);
2808#else
2809 debugs(33, DBG_IMPORTANT, msg << " from " << clientConnection);
2810#endif
3bd97e7e 2811 mustStop(msg);
3c082dbe 2812 }
00d0ce87
AJ
2813 return false;
2814}
2815
3bd97e7e 2816/// magic octet prefix for PROXY protocol version 1
70a16fea 2817static const SBuf Proxy1p0magic("PROXY ", 6);
3bd97e7e
AJ
2818
2819/// magic octet prefix for PROXY protocol version 2
70a16fea 2820static const SBuf Proxy2p0magic("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A", 12);
3bd97e7e 2821
00d0ce87 2822/**
3bd97e7e
AJ
2823 * Test the connection read buffer for PROXY protocol header.
2824 * Version 1 and 2 header currently supported.
00d0ce87
AJ
2825 */
2826bool
3d74cb1f 2827ConnStateData::parseProxyProtocolHeader()
00d0ce87 2828{
00d0ce87 2829 // http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt
cbae7ab9 2830
70a16fea
AJ
2831 // detect and parse PROXY/2.0 protocol header
2832 if (in.buf.startsWith(Proxy2p0magic))
2833 return parseProxy2p0();
00d0ce87 2834
70a16fea
AJ
2835 // detect and parse PROXY/1.0 protocol header
2836 if (in.buf.startsWith(Proxy1p0magic))
bd1be2ae 2837 return parseProxy1p0();
00d0ce87 2838
70a16fea
AJ
2839 // detect and terminate other protocols
2840 if (in.buf.length() >= Proxy2p0magic.length()) {
2841 // PROXY/1.0 magic is shorter, so we know that
2842 // the input does not start with any PROXY magic
3bd97e7e
AJ
2843 return proxyProtocolError("PROXY protocol error: invalid header");
2844 }
00d0ce87 2845
3d74cb1f
AJ
2846 // TODO: detect short non-magic prefixes earlier to avoid
2847 // waiting for more data which may never come
2848
3bd97e7e
AJ
2849 // not enough bytes to parse yet.
2850 return false;
2851}
00d0ce87 2852
3bd97e7e
AJ
2853/// parse the PROXY/1.0 protocol header from the connection read buffer
2854bool
70a16fea 2855ConnStateData::parseProxy1p0()
3bd97e7e
AJ
2856{
2857 ::Parser::Tokenizer tok(in.buf);
70a16fea 2858 tok.skip(Proxy1p0magic);
3bd97e7e 2859
154ea566
AJ
2860 // skip to first LF (assumes it is part of CRLF)
2861 static const CharacterSet lineContent = CharacterSet::LF.complement("non-LF");
2862 SBuf line;
2863 if (tok.prefix(line, lineContent, 107-Proxy1p0magic.length())) {
2864 if (tok.skip('\n')) {
2865 // found valid header
2866 in.buf = tok.remaining();
2867 needProxyProtocolHeader_ = false;
2868 // reset the tokenizer to work on found line only.
2869 tok.reset(line);
2870 } else
2871 return false; // no LF yet
2872
2873 } else // protocol error only if there are more than 107 bytes prefix header
2874 return proxyProtocolError(in.buf.length() > 107? "PROXY/1.0 error: missing CRLF" : NULL);
2875
1689cdbc
AJ
2876 static const SBuf unknown("UNKNOWN"), tcpName("TCP");
2877 if (tok.skip(tcpName)) {
3bd97e7e 2878
1689cdbc
AJ
2879 // skip TCP/IP version number
2880 static const CharacterSet tcpVersions("TCP-version","46");
bd1be2ae 2881 if (!tok.skipOne(tcpVersions))
154ea566 2882 return proxyProtocolError("PROXY/1.0 error: missing TCP version");
00d0ce87 2883
3bd97e7e
AJ
2884 // skip SP after protocol version
2885 if (!tok.skip(' '))
154ea566 2886 return proxyProtocolError("PROXY/1.0 error: missing SP");
00d0ce87 2887
3bd97e7e
AJ
2888 SBuf ipa, ipb;
2889 int64_t porta, portb;
1689cdbc
AJ
2890 static const CharacterSet ipChars = CharacterSet("IP Address",".:") + CharacterSet::HEXDIG;
2891
2892 // parse: src-IP SP dst-IP SP src-port SP dst-port CR
2893 // leave the LF until later.
2894 const bool correct = tok.prefix(ipa, ipChars) && tok.skip(' ') &&
2895 tok.prefix(ipb, ipChars) && tok.skip(' ') &&
2896 tok.int64(porta) && tok.skip(' ') &&
2897 tok.int64(portb) &&
2898 tok.skip('\r');
2899 if (!correct)
154ea566 2900 return proxyProtocolError("PROXY/1.0 error: invalid syntax");
00d0ce87 2901
3bd97e7e
AJ
2902 // parse IP and port strings
2903 Ip::Address originalClient, originalDest;
00d0ce87 2904
3bd97e7e
AJ
2905 if (!originalClient.GetHostByName(ipa.c_str()))
2906 return proxyProtocolError("PROXY/1.0 error: invalid src-IP address");
00d0ce87 2907
3bd97e7e
AJ
2908 if (!originalDest.GetHostByName(ipb.c_str()))
2909 return proxyProtocolError("PROXY/1.0 error: invalid dst-IP address");
00d0ce87 2910
3bd97e7e
AJ
2911 if (porta > 0 && porta <= 0xFFFF) // max uint16_t
2912 originalClient.port(static_cast<uint16_t>(porta));
2913 else
2914 return proxyProtocolError("PROXY/1.0 error: invalid src port");
cbae7ab9 2915
3bd97e7e
AJ
2916 if (portb > 0 && portb <= 0xFFFF) // max uint16_t
2917 originalDest.port(static_cast<uint16_t>(portb));
2918 else
2919 return proxyProtocolError("PROXY/1.0 error: invalid dst port");
cbae7ab9 2920
3bd97e7e
AJ
2921 // we have original client and destination details now
2922 // replace the client connection values
2923 debugs(33, 5, "PROXY/1.0 protocol on connection " << clientConnection);
2924 clientConnection->local = originalDest;
2925 clientConnection->remote = originalClient;
151ba0d4 2926 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e 2927 debugs(33, 5, "PROXY/1.0 upgrade: " << clientConnection);
cbae7ab9 2928
3bd97e7e
AJ
2929 // repeat fetch ensuring the new client FQDN can be logged
2930 if (Config.onoff.log_fqdn)
2931 fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS);
cbae7ab9 2932
3bd97e7e 2933 return true;
1689cdbc
AJ
2934
2935 } else if (tok.skip(unknown)) {
154ea566
AJ
2936 // found valid but unusable header
2937 return true;
1689cdbc
AJ
2938
2939 } else
154ea566 2940 return proxyProtocolError("PROXY/1.0 error: invalid protocol family");
cbae7ab9 2941
3bd97e7e
AJ
2942 return false;
2943}
cbae7ab9 2944
3bd97e7e
AJ
2945/// parse the PROXY/2.0 protocol header from the connection read buffer
2946bool
70a16fea 2947ConnStateData::parseProxy2p0()
3bd97e7e 2948{
1689cdbc
AJ
2949 static const SBuf::size_type prefixLen = Proxy2p0magic.length();
2950 if (in.buf.length() < prefixLen + 4)
2951 return false; // need more bytes
2952
2953 if ((in.buf[prefixLen] & 0xF0) != 0x20) // version == 2 is mandatory
3bd97e7e 2954 return proxyProtocolError("PROXY/2.0 error: invalid version");
cbae7ab9 2955
1689cdbc 2956 const char command = (in.buf[prefixLen] & 0x0F);
3bd97e7e
AJ
2957 if ((command & 0xFE) != 0x00) // values other than 0x0-0x1 are invalid
2958 return proxyProtocolError("PROXY/2.0 error: invalid command");
cbae7ab9 2959
1689cdbc 2960 const char family = (in.buf[prefixLen+1] & 0xF0) >>4;
3bd97e7e
AJ
2961 if (family > 0x3) // values other than 0x0-0x3 are invalid
2962 return proxyProtocolError("PROXY/2.0 error: invalid family");
cbae7ab9 2963
1689cdbc 2964 const char proto = (in.buf[prefixLen+1] & 0x0F);
3bd97e7e
AJ
2965 if (proto > 0x2) // values other than 0x0-0x2 are invalid
2966 return proxyProtocolError("PROXY/2.0 error: invalid protocol type");
cbae7ab9 2967
1689cdbc 2968 const char *clen = in.buf.rawContent() + prefixLen + 2;
17954dbd
AJ
2969 uint16_t len;
2970 memcpy(&len, clen, sizeof(len));
2971 len = ntohs(len);
cbae7ab9 2972
1689cdbc 2973 if (in.buf.length() < prefixLen + 4 + len)
3bd97e7e 2974 return false; // need more bytes
cbae7ab9 2975
1689cdbc 2976 in.buf.consume(prefixLen + 4); // 4 being the extra bytes
3bd97e7e
AJ
2977 const SBuf extra = in.buf.consume(len);
2978 needProxyProtocolHeader_ = false; // found successfully
cbae7ab9 2979
3bd97e7e
AJ
2980 // LOCAL connections do nothing with the extras
2981 if (command == 0x00/* LOCAL*/)
cbae7ab9
AJ
2982 return true;
2983
1689cdbc 2984 union pax {
3bd97e7e
AJ
2985 struct { /* for TCP/UDP over IPv4, len = 12 */
2986 struct in_addr src_addr;
2987 struct in_addr dst_addr;
2988 uint16_t src_port;
2989 uint16_t dst_port;
2990 } ipv4_addr;
2991 struct { /* for TCP/UDP over IPv6, len = 36 */
bd1be2ae
A
2992 struct in6_addr src_addr;
2993 struct in6_addr dst_addr;
2994 uint16_t src_port;
2995 uint16_t dst_port;
3bd97e7e
AJ
2996 } ipv6_addr;
2997#if NOT_SUPPORTED
2998 struct { /* for AF_UNIX sockets, len = 216 */
bd1be2ae
A
2999 uint8_t src_addr[108];
3000 uint8_t dst_addr[108];
3bd97e7e
AJ
3001 } unix_addr;
3002#endif
1689cdbc 3003 };
3bd97e7e 3004
17954dbd
AJ
3005 pax ipu;
3006 memcpy(&ipu, extra.rawContent(), sizeof(pax));
3bd97e7e
AJ
3007
3008 // replace the client connection values
3009 debugs(33, 5, "PROXY/2.0 protocol on connection " << clientConnection);
bd1be2ae 3010 switch (family) {
3bd97e7e 3011 case 0x1: // IPv4
17954dbd
AJ
3012 clientConnection->local = ipu.ipv4_addr.dst_addr;
3013 clientConnection->local.port(ntohs(ipu.ipv4_addr.dst_port));
3014 clientConnection->remote = ipu.ipv4_addr.src_addr;
3015 clientConnection->remote.port(ntohs(ipu.ipv4_addr.src_port));
151ba0d4 3016 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e
AJ
3017 break;
3018 case 0x2: // IPv6
17954dbd
AJ
3019 clientConnection->local = ipu.ipv6_addr.dst_addr;
3020 clientConnection->local.port(ntohs(ipu.ipv6_addr.dst_port));
3021 clientConnection->remote = ipu.ipv6_addr.src_addr;
3022 clientConnection->remote.port(ntohs(ipu.ipv6_addr.src_port));
151ba0d4 3023 clientConnection->flags ^= COMM_TRANSPARENT; // prevent TPROXY spoofing of this new IP.
3bd97e7e
AJ
3024 break;
3025 default: // do nothing
3026 break;
00d0ce87 3027 }
3bd97e7e 3028 debugs(33, 5, "PROXY/2.0 upgrade: " << clientConnection);
00d0ce87 3029
3bd97e7e
AJ
3030 // repeat fetch ensuring the new client FQDN can be logged
3031 if (Config.onoff.log_fqdn)
3032 fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS);
3033
3034 return true;
00d0ce87
AJ
3035}
3036
3248e962
CT
3037void
3038ConnStateData::receivedFirstByte()
3039{
3040 if (receivedFirstByte_)
3041 return;
3042
3043 receivedFirstByte_ = true;
3044 // Set timeout to Config.Timeout.request
3045 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3046 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
3047 TimeoutDialer, this, ConnStateData::requestTimeout);
3048 commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall);
3049}
3050
63be0a78 3051/**
f900210a 3052 * Attempt to parse one or more requests from the input buffer.
eacfca83
AR
3053 * Returns true after completing parsing of at least one request [header]. That
3054 * includes cases where parsing ended with an error (e.g., a huge request).
f900210a 3055 */
4959e21e 3056bool
f35961af 3057ConnStateData::clientParseRequests()
f900210a 3058{
f900210a 3059 bool parsed_req = false;
3060
1b76e6c1 3061 debugs(33, 5, HERE << clientConnection << ": attempting to parse");
f900210a 3062
39cb8c41 3063 // Loop while we have read bytes that are not needed for producing the body
f35961af 3064 // On errors, bodyPipe may become nil, but readMore will be cleared
e7287625 3065 while (!in.buf.isEmpty() && !bodyPipe && flags.readMore) {
f900210a 3066
fc68f6b1 3067 /* Don't try to parse if the buffer is empty */
e7287625 3068 if (in.buf.isEmpty())
fc68f6b1 3069 break;
4681057e 3070
079a8480
AJ
3071 /* Limit the number of concurrent requests */
3072 if (concurrentRequestQueueFilled())
f900210a 3073 break;
f900210a 3074
c5c06f02
CT
3075 /*Do not read more requests if persistent connection lifetime exceeded*/
3076 if (Config.Timeout.pconnLifetime && clientConnection->lifeTime() > Config.Timeout.pconnLifetime) {
3077 flags.readMore = false;
3078 break;
3079 }
3080
00d0ce87 3081 // try to parse the PROXY protocol header magic bytes
3d74cb1f 3082 if (needProxyProtocolHeader_ && !parseProxyProtocolHeader())
00d0ce87
AJ
3083 break;
3084
db5a5382 3085 if (ClientSocketContext *context = parseOneRequest()) {
eacfca83 3086 debugs(33, 5, clientConnection << ": done parsing a request");
f900210a 3087
8d77a37c 3088 AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout",
dc49061a 3089 CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http));
1b76e6c1 3090 commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall);
f900210a 3091
eacfca83
AR
3092 context->registerWithConn();
3093
9bafa70d 3094 processParsedRequest(context);
f900210a 3095
4959e21e 3096 parsed_req = true; // XXX: do we really need to parse everything right NOW ?
f900210a 3097
3098 if (context->mayUseConnection()) {
f35961af 3099 debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection");
f900210a 3100 break;
3101 }
eacfca83
AR
3102 } else {
3103 debugs(33, 5, clientConnection << ": not enough request data: " <<
3104 in.buf.length() << " < " << Config.maxRequestHeaderSize);
3105 Must(in.buf.length() < Config.maxRequestHeaderSize);
3106 break;
f900210a 3107 }
39cb8c41 3108 }
fc68f6b1 3109
a5baffba 3110 /* XXX where to 'finish' the parsing pass? */
f900210a 3111 return parsed_req;
3112}
3113
1cf238db 3114void
3115ConnStateData::clientReadRequest(const CommIoCbParams &io)
c4b7a5a9 3116{
7e66d5e2 3117 debugs(33,5, io.conn);
f84dd7eb
AR
3118 Must(reading());
3119 reader = NULL;
c4b7a5a9 3120
c8407295
AJ
3121 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
3122 if (io.flag == Comm::ERR_CLOSING) {
7e66d5e2 3123 debugs(33,5, io.conn << " closing Bailout.");
c4b7a5a9 3124 return;
3125 }
62e76326 3126
73c36fd9
AJ
3127 assert(Comm::IsConnOpen(clientConnection));
3128 assert(io.conn->fd == clientConnection->fd);
5c336a3b 3129
44db45e8 3130 /*
7e66d5e2
AJ
3131 * Don't reset the timeout value here. The value should be
3132 * counting Config.Timeout.request and applies to the request
3133 * as a whole, not individual read() calls.
3134 * Plus, it breaks our lame *HalfClosed() detection
44db45e8 3135 */
7e66d5e2
AJ
3136
3137 CommIoCbParams rd(this); // will be expanded with ReadNow results
3138 rd.conn = io.conn;
470b1598 3139 switch (Comm::ReadNow(rd, in.buf)) {
c8407295 3140 case Comm::INPROGRESS:
7e66d5e2
AJ
3141 if (in.buf.isEmpty())
3142 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
3143 readSomeData();
62e76326 3144 return;
c4b7a5a9 3145
c8407295 3146 case Comm::OK:
7e66d5e2 3147 kb_incr(&(statCounter.client_http.kbytes_in), rd.size);
3248e962
CT
3148 if (!receivedFirstByte_)
3149 receivedFirstByte();
7e66d5e2
AJ
3150 // may comm_close or setReplyToError
3151 if (!handleReadData())
3152 return;
3b299123 3153
7e66d5e2
AJ
3154 /* Continue to process previously read data */
3155 break;
a31a78fb 3156
c8407295 3157 case Comm::ENDFILE: // close detected by 0-byte read
7e66d5e2 3158 debugs(33, 5, io.conn << " closed?");
62e76326 3159
7e66d5e2
AJ
3160 if (connFinishedWithConn(rd.size)) {
3161 clientConnection->close();
3162 return;
3163 }
62e76326 3164
7e66d5e2
AJ
3165 /* It might be half-closed, we can't tell */
3166 fd_table[io.conn->fd].flags.socket_eof = true;
3167 commMarkHalfClosed(io.conn->fd);
3168 fd_note(io.conn->fd, "half-closed");
62e76326 3169
7e66d5e2
AJ
3170 /* There is one more close check at the end, to detect aborted
3171 * (partial) requests. At this point we can't tell if the request
3172 * is partial.
3173 */
a46d2c0e 3174
7e66d5e2
AJ
3175 /* Continue to process previously read data */
3176 break;
62e76326 3177
f53969cc 3178 // case Comm::COMM_ERROR:
7e66d5e2
AJ
3179 default: // no other flags should ever occur
3180 debugs(33, 2, io.conn << ": got flag " << rd.flag << "; " << xstrerr(rd.xerrno));
3181 notifyAllContexts(rd.xerrno);
3182 io.conn->close();
3183 return;
c4b7a5a9 3184 }
3185
94439e4e 3186 /* Process next request */
1cf238db 3187 if (getConcurrentRequestCount() == 0)
5c336a3b 3188 fd_note(io.fd, "Reading next request");
c8be6d7b 3189
f35961af 3190 if (!clientParseRequests()) {
9e008dda
AJ
3191 if (!isOpen())
3192 return;
f900210a 3193 /*
3194 * If the client here is half closed and we failed
3195 * to parse a request, close the connection.
3196 * The above check with connFinishedWithConn() only
3197 * succeeds _if_ the buffer is empty which it won't
3198 * be if we have an incomplete request.
6e1d409c 3199 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
f900210a 3200 */
5c336a3b 3201 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io.fd)) {
be364179 3202 debugs(33, 5, HERE << io.conn << ": half-closed connection, no completed request parsed, connection closing.");
73c36fd9 3203 clientConnection->close();
ee6f0213 3204 return;
62e76326 3205 }
f900210a 3206 }
ee6f0213 3207
1cf238db 3208 if (!isOpen())
2e216b1d 3209 return;
3210
f35961af 3211 clientAfterReadingRequests();
94439e4e 3212}
3213
63be0a78 3214/**
3215 * called when new request data has been read from the socket
39cb8c41
AR
3216 *
3217 * \retval false called comm_close or setReplyToError (the caller should bail)
3218 * \retval true we did not call comm_close or setReplyToError
63be0a78 3219 */
39cb8c41 3220bool
7e66d5e2 3221ConnStateData::handleReadData()
94439e4e 3222{
5f8252d2 3223 // if we are reading a body, stuff data into the body pipe
3224 if (bodyPipe != NULL)
39cb8c41
AR
3225 return handleRequestBodyData();
3226 return true;
94439e4e 3227}
3228
63be0a78 3229/**
bb790702 3230 * called when new request body data has been buffered in in.buf
63be0a78 3231 * may close the connection if we were closing and piped everything out
39cb8c41
AR
3232 *
3233 * \retval false called comm_close or setReplyToError (the caller should bail)
3234 * \retval true we did not call comm_close or setReplyToError
63be0a78 3235 */
39cb8c41 3236bool
5f8252d2 3237ConnStateData::handleRequestBodyData()
94439e4e 3238{
5f8252d2 3239 assert(bodyPipe != NULL);
3240
e1381638 3241 size_t putSize = 0;
3ff65596 3242
39cb8c41
AR
3243 if (in.bodyParser) { // chunked encoding
3244 if (const err_type error = handleChunkedRequestBody(putSize)) {
3245 abortChunkedRequestBody(error);
3246 return false;
3ff65596 3247 }
39cb8c41 3248 } else { // identity encoding
73c36fd9 3249 debugs(33,5, HERE << "handling plain request body for " << clientConnection);
e7287625 3250 putSize = bodyPipe->putMoreData(in.buf.c_str(), in.buf.length());
3ff65596
AR
3251 if (!bodyPipe->mayNeedMoreData()) {
3252 // BodyPipe will clear us automagically when we produced everything
3253 bodyPipe = NULL;
3254 }
3255 }
3256
3257 if (putSize > 0)
48a37aee 3258 consumeInput(putSize);
5f8252d2 3259
3ff65596 3260 if (!bodyPipe) {
73c36fd9 3261 debugs(33,5, HERE << "produced entire request body for " << clientConnection);
62e76326 3262
cf6eb29e 3263 if (const char *reason = stoppedSending()) {
5f8252d2 3264 /* we've finished reading like good clients,
3265 * now do the close that initiateClose initiated.
5f8252d2 3266 */
cf6eb29e 3267 debugs(33, 3, HERE << "closing for earlier sending error: " << reason);
73c36fd9 3268 clientConnection->close();
39cb8c41
AR
3269 return false;
3270 }
3271 }
3272
3273 return true;
3274}
3275
3276/// parses available chunked encoded body bytes, checks size, returns errors
3277err_type
3278ConnStateData::handleChunkedRequestBody(size_t &putSize)
3279{
e7287625 3280 debugs(33, 7, "chunked from " << clientConnection << ": " << in.buf.length());
39cb8c41
AR
3281
3282 try { // the parser will throw on errors
3283
e7287625 3284 if (in.buf.isEmpty()) // nothing to do
39cb8c41
AR
3285 return ERR_NONE;
3286
3287 MemBuf raw; // ChunkedCodingParser only works with MemBufs
3288 // add one because MemBuf will assert if it cannot 0-terminate
e7287625
AJ
3289 raw.init(in.buf.length(), in.buf.length()+1);
3290 raw.append(in.buf.c_str(), in.buf.length());
39cb8c41
AR
3291
3292 const mb_size_t wasContentSize = raw.contentSize();
3293 BodyPipeCheckout bpc(*bodyPipe);
3294 const bool parsed = in.bodyParser->parse(&raw, &bpc.buf);
3295 bpc.checkIn();
3296 putSize = wasContentSize - raw.contentSize();
3297
3298 // dechunk then check: the size limit applies to _dechunked_ content
3299 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize()))
3300 return ERR_TOO_BIG;
3301
3302 if (parsed) {
3303 finishDechunkingRequest(true);
3304 Must(!bodyPipe);
3305 return ERR_NONE; // nil bodyPipe implies body end for the caller
5f8252d2 3306 }
39cb8c41
AR
3307
3308 // if chunk parser needs data, then the body pipe must need it too
3309 Must(!in.bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData());
3310
3311 // if parser needs more space and we can consume nothing, we will stall
3312 Must(!in.bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent());
3313 } catch (...) { // TODO: be more specific
3314 debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status());
3315 return ERR_INVALID_REQ;
94439e4e 3316 }
39cb8c41
AR
3317
3318 debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status());
3319 return ERR_NONE;
3320}
3321
3322/// quit on errors related to chunked request body handling
3323void
3324ConnStateData::abortChunkedRequestBody(const err_type error)
3325{
3326 finishDechunkingRequest(false);
3327
3328 // XXX: The code below works if we fail during initial request parsing,
d5430dc8 3329 // but if we fail when the server connection is used already, the server may send
39cb8c41
AR
3330 // us its response too, causing various assertions. How to prevent that?
3331#if WE_KNOW_HOW_TO_SEND_ERRORS
3332 ClientSocketContext::Pointer context = getCurrentContext();
3333 if (context != NULL && !context->http->out.offset) { // output nothing yet
3334 clientStreamNode *node = context->getClientReplyContext();
3335 clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw());
3336 assert(repContext);
955394ce 3337 const Http::StatusCode scode = (error == ERR_TOO_BIG) ?
f11c8e2f 3338 Http::scPayloadTooLarge : HTTP_BAD_REQUEST;
39cb8c41
AR
3339 repContext->setReplyToError(error, scode,
3340 repContext->http->request->method,
3341 repContext->http->uri,
a3c6762c 3342 CachePeer,
39cb8c41
AR
3343 repContext->http->request,
3344 in.buf, NULL);
3345 context->pullData();
3346 } else {
3347 // close or otherwise we may get stuck as nobody will notice the error?
73c36fd9 3348 comm_reset_close(clientConnection);
39cb8c41
AR
3349 }
3350#else
3351 debugs(33, 3, HERE << "aborting chunked request without error " << error);
73c36fd9 3352 comm_reset_close(clientConnection);
39cb8c41 3353#endif
f35961af 3354 flags.readMore = false;
5f8252d2 3355}
55e44db9 3356
5f8252d2 3357void
1cf238db 3358ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer )
5f8252d2 3359{
cf6eb29e
CT
3360 // request reader may get stuck waiting for space if nobody consumes body
3361 if (bodyPipe != NULL)
3362 bodyPipe->enableAutoConsumption();
3363
92ae4c86 3364 // kids extend
94439e4e 3365}
3366
63be0a78 3367/** general lifetime handler for HTTP requests */
1cf238db 3368void
3369ConnStateData::requestTimeout(const CommTimeoutCbParams &io)
7a2f978b 3370{
3248e962
CT
3371 if (Config.accessList.on_unsupported_protocol && !receivedFirstByte_) {
3372#if USE_OPENSSL
3373 if (serverBump() && (serverBump()->act.step1 == Ssl::bumpPeek || serverBump()->act.step1 == Ssl::bumpStare)) {
3374 if (spliceOnError(ERR_REQUEST_START_TIMEOUT)) {
3375 receivedFirstByte();
3376 return;
3377 }
3378 } else if (fd_table[io.conn->fd].ssl == NULL)
3379#endif
3380 {
3381 const HttpRequestMethod method;
3382 if (clientTunnelOnError(this, NULL, NULL, method, ERR_REQUEST_START_TIMEOUT, Http::scNone, NULL)) {
3383 // Tunnel established. Set receivedFirstByte to avoid loop.
3384 receivedFirstByte();
3385 return;
3386 }
3387 }
3388 }
af57a2e3 3389 /*
62e76326 3390 * Just close the connection to not confuse browsers
6177a89f
HN
3391 * using persistent connections. Some browsers open
3392 * a connection and then do not use it until much
62e76326 3393 * later (presumeably because the request triggering
3394 * the open has already been completed on another
3395 * connection)
3396 */
1cf238db 3397 debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired.");
8d77a37c 3398 io.conn->close();
7a2f978b 3399}
3400
b5c39993 3401static void
8d77a37c 3402clientLifetimeTimeout(const CommTimeoutCbParams &io)
b5c39993 3403{
8d77a37c 3404 ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data);
cb61ec47
AJ
3405 debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout");
3406 debugs(33, DBG_IMPORTANT, "\t" << http->uri);
41ebd397 3407 http->al->http.timedout = true;
8d77a37c
AJ
3408 if (Comm::IsConnOpen(io.conn))
3409 io.conn->close();
b5c39993 3410}
3411
94bfd31f 3412ConnStateData::ConnStateData(const MasterXaction::Pointer &xact) :
f53969cc
SM
3413 AsyncJob("ConnStateData"), // kids overwrite
3414 nrequests(0),
cb4f4424 3415#if USE_OPENSSL
f53969cc 3416 sslBumpMode(Ssl::bumpEnd),
4579a6d0 3417#endif
f53969cc 3418 needProxyProtocolHeader_(false),
4579a6d0 3419#if USE_OPENSSL
f53969cc
SM
3420 switchedToHttps_(false),
3421 sslServerBump(NULL),
3422 signAlgorithm(Ssl::algSignTrusted),
94bfd31f 3423#endif
f53969cc 3424 stoppedSending_(NULL),
3248e962
CT
3425 stoppedReceiving_(NULL),
3426 receivedFirstByte_(false)
c8be6d7b 3427{
4579a6d0
AJ
3428 flags.readMore = true; // kids may overwrite
3429 flags.swanSang = false;
3430
94bfd31f
AJ
3431 pinning.host = NULL;
3432 pinning.port = -1;
3433 pinning.pinned = false;
3434 pinning.auth = false;
3435 pinning.zeroReply = false;
3436 pinning.peer = NULL;
3437
3438 // store the details required for creating more MasterXaction objects as new requests come in
3439 clientConnection = xact->tcpClient;
fa720bfb 3440 port = xact->squidPort;
4599cded 3441 transferProtocol = port->transport; // default to the *_port protocol= setting. may change later.
94bfd31f
AJ
3442 log_addr = xact->tcpClient->remote;
3443 log_addr.applyMask(Config.Addrs.client_netmask);
92ae4c86
AR
3444}
3445
3446void
3447ConnStateData::start()
3448{
3449 BodyProducer::start();
3450 HttpControlMsgSink::start();
3451
50ae17d6
AJ
3452 // ensure a buffer is present for this connection
3453 in.maybeMakeSpaceAvailable();
62e76326 3454
5529ca8a 3455 if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF &&
94bfd31f 3456 (transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) {
5529ca8a 3457#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3458 int i = IP_PMTUDISC_DONT;
94bfd31f
AJ
3459 if (setsockopt(clientConnection->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof(i)) < 0)
3460 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection << " : " << xstrerror());
5529ca8a 3461#else
9bb67276 3462 static bool reported = false;
5529ca8a 3463
3464 if (!reported) {
9bb67276
AJ
3465 debugs(33, DBG_IMPORTANT, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3466 reported = true;
5529ca8a 3467 }
89aec9b6
AJ
3468#endif
3469 }
5529ca8a 3470
89aec9b6 3471 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
94bfd31f
AJ
3472 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, ConnStateData::connStateClosed);
3473 comm_add_close_handler(clientConnection->fd, call);
5529ca8a 3474
89aec9b6 3475 if (Config.onoff.log_fqdn)
94bfd31f 3476 fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS);
89aec9b6
AJ
3477
3478#if USE_IDENT
3479 if (Ident::TheConfig.identLookup) {
3480 ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL);
92ae4c86
AR
3481 identChecklist.src_addr = clientConnection->remote;
3482 identChecklist.my_addr = clientConnection->local;
2efeb0b7 3483 if (identChecklist.fastCheck() == ACCESS_ALLOWED)
92ae4c86 3484 Ident::Start(clientConnection, clientIdentDone, this);
89aec9b6 3485 }
5529ca8a 3486#endif
3487
94bfd31f 3488 clientdbEstablished(clientConnection->remote, 1);
5529ca8a 3489
6658cc16
AJ
3490 needProxyProtocolHeader_ = port->flags.proxySurrogate;
3491 if (needProxyProtocolHeader_) {
3492 if (!proxyProtocolValidateClient()) // will close the connection on failure
3493 return;
3494 }
3495
9a0a18de 3496#if USE_DELAY_POOLS
92ae4c86 3497 fd_table[clientConnection->fd].clientInfo = NULL;
b4cd430a 3498
f33d34a8 3499 if (Config.onoff.client_db) {
b4cd430a
CT
3500 /* it was said several times that client write limiter does not work if client_db is disabled */
3501
3502 ClientDelayPools& pools(Config.ClientDelay.pools);
2efeb0b7 3503 ACLFilledChecklist ch(NULL, NULL, NULL);
b4cd430a 3504
2efeb0b7
AJ
3505 // TODO: we check early to limit error response bandwith but we
3506 // should recheck when we can honor delay_pool_uses_indirect
3507 // TODO: we should also pass the port details for myportname here.
92ae4c86
AR
3508 ch.src_addr = clientConnection->remote;
3509 ch.my_addr = clientConnection->local;
b4cd430a 3510
95dc7ff4 3511 for (unsigned int pool = 0; pool < pools.size(); ++pool) {
b4cd430a 3512
2efeb0b7
AJ
3513 /* pools require explicit 'allow' to assign a client into them */
3514 if (pools[pool].access) {
3515 ch.accessList = pools[pool].access;
3516 allow_t answer = ch.fastCheck();
3517 if (answer == ACCESS_ALLOWED) {
3518
3519 /* request client information from db after we did all checks
3520 this will save hash lookup if client failed checks */
92ae4c86 3521 ClientInfo * cli = clientdbGetInfo(clientConnection->remote);
2efeb0b7
AJ
3522 assert(cli);
3523
3524 /* put client info in FDE */
92ae4c86 3525 fd_table[clientConnection->fd].clientInfo = cli;
2efeb0b7
AJ
3526
3527 /* setup write limiter for this request */
3528 const double burst = floor(0.5 +
3529 (pools[pool].highwatermark * Config.ClientDelay.initial)/100.0);
3530 cli->setWriteLimiter(pools[pool].rate, burst, pools[pool].highwatermark);
3531 break;
3532 } else {
3533 debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer);
3534 }
b4cd430a
CT
3535 }
3536 }
3537 }
3538#endif
92ae4c86
AR
3539
3540 // kids must extend to actually start doing something (e.g., reading)
7a2f978b 3541}
3542
e7ce227f 3543/** Handle a new connection on an HTTP socket. */
92ae4c86
AR
3544void
3545httpAccept(const CommAcceptCbParams &params)
6afea0a4
AR
3546{
3547 MasterXaction::Pointer xact = params.xaction;
3548 AnyP::PortCfgPointer s = xact->squidPort;
3549
3550 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3551
3552 if (params.flag != Comm::OK) {
3553 // Its possible the call was still queued when the client disconnected
e7ce227f 3554 debugs(33, 2, s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
6afea0a4
AR
3555 return;
3556 }
3557
e7ce227f 3558 debugs(33, 4, params.conn << ": accepted");
92ae4c86 3559 fd_note(params.conn->fd, "client http connect");
6afea0a4 3560
e7ce227f 3561 if (s->tcp_keepalive.enabled)
6afea0a4 3562 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
6afea0a4 3563
e7ce227f 3564 ++incoming_sockets_accepted;
6afea0a4
AR
3565
3566 // Socket is ready, setup the connection manager to start using it
92ae4c86 3567 ConnStateData *connState = Http::NewServer(xact);
e7ce227f 3568 AsyncJob::Start(connState); // usually async-calls readSomeData()
7a2f978b 3569}
3570
cb4f4424 3571#if USE_OPENSSL
1f7c9178 3572
63be0a78 3573/** Create SSL connection structure and update fd_table */
ae7ff0b8 3574static SSL *
449f0115 3575httpsCreate(const Comm::ConnectionPointer &conn, SSL_CTX *sslContext)
ae7ff0b8 3576{
d620ae0e 3577 if (SSL *ssl = Ssl::CreateServer(sslContext, conn->fd, "client https start")) {
8693472e 3578 debugs(33, 5, "will negotate SSL on " << conn);
b3a8ae1b 3579 return ssl;
ae7ff0b8 3580 }
3581
b3a8ae1b
AR
3582 conn->close();
3583 return NULL;
ae7ff0b8 3584}
3585
3248e962
CT
3586/**
3587 *
3588 * \retval 1 on success
3589 * \retval 0 when needs more data
3590 * \retval -1 on error
3591 */
3592static int
d620ae0e 3593Squid_SSL_accept(ConnStateData *conn, PF *callback)
1f7c9178 3594{
d620ae0e 3595 int fd = conn->clientConnection->fd;
a7ad6e4e 3596 SSL *ssl = fd_table[fd].ssl;
1f7c9178 3597 int ret;
3598
a7ad6e4e 3599 if ((ret = SSL_accept(ssl)) <= 0) {
62e76326 3600 int ssl_error = SSL_get_error(ssl, ret);
3601
3602 switch (ssl_error) {
3603
3604 case SSL_ERROR_WANT_READ:
d620ae0e 3605 Comm::SetSelect(fd, COMM_SELECT_READ, callback, conn, 0);
3248e962 3606 return 0;
62e76326 3607
3608 case SSL_ERROR_WANT_WRITE:
d620ae0e 3609 Comm::SetSelect(fd, COMM_SELECT_WRITE, callback, conn, 0);
3248e962 3610 return 0;
62e76326 3611
6de9e64b 3612 case SSL_ERROR_SYSCALL:
3613
3614 if (ret == 0) {
d620ae0e 3615 debugs(83, 2, "Error negotiating SSL connection on FD " << fd << ": Aborted by client: " << ssl_error);
6de9e64b 3616 } else {
3617 int hard = 1;
3618
3619 if (errno == ECONNRESET)
3620 hard = 0;
3621
d620ae0e 3622 debugs(83, hard ? 1 : 2, "Error negotiating SSL connection on FD " <<
bf8fe701 3623 fd << ": " << strerror(errno) << " (" << errno << ")");
6de9e64b 3624 }
3248e962 3625 return -1;
6de9e64b 3626
3627 case SSL_ERROR_ZERO_RETURN:
d620ae0e 3628 debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " << fd << ": Closed by client");
3248e962 3629 return -1;
6de9e64b 3630
62e76326 3631 default:
d620ae0e 3632 debugs(83, DBG_IMPORTANT, "Error negotiating SSL connection on FD " <<
9e008dda
AJ
3633 fd << ": " << ERR_error_string(ERR_get_error(), NULL) <<
3634 " (" << ssl_error << "/" << ret << ")");
3248e962 3635 return -1;
62e76326 3636 }
3637
3638 /* NOTREACHED */
1f7c9178 3639 }
3248e962 3640 return 1;
d620ae0e
CT
3641}
3642
3643/** negotiate an SSL connection */
3644static void
3645clientNegotiateSSL(int fd, void *data)
3646{
3647 ConnStateData *conn = (ConnStateData *)data;
3648 X509 *client_cert;
3649 SSL *ssl = fd_table[fd].ssl;
3650
3248e962
CT
3651 int ret;
3652 if ((ret = Squid_SSL_accept(conn, clientNegotiateSSL)) <= 0) {
3653 if (ret < 0) // An error
3654 comm_close(fd);
d620ae0e 3655 return;
3248e962 3656 }
62e76326 3657
6de9e64b 3658 if (SSL_session_reused(ssl)) {
bf8fe701 3659 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl) <<
3660 " reused on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << ")");
6de9e64b 3661 } else {
3662 if (do_debug(83, 4)) {
3663 /* Write out the SSL session details.. actually the call below, but
3664 * OpenSSL headers do strange typecasts confusing GCC.. */
3665 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
afdd443f 3666#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
9f3de01a 3667 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 3668
0fd2205b 3669#elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2930f303 3670
0fd2205b 3671 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3672 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3673 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3674 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3675 * Because there are two possible usable cast, if you get an error here, try the other
3676 * commented line. */
3677
3678 PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL);
3679 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2930f303 3680
0e33d58c 3681#else
3682
bf8fe701 3683 debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
0fd2205b 3684
0e33d58c 3685#endif
6de9e64b 3686 /* Note: This does not automatically fflush the log file.. */
3687 }
3688
bf8fe701 3689 debugs(83, 2, "clientNegotiateSSL: New session " <<
3690 SSL_get_session(ssl) << " on FD " << fd << " (" <<
3691 fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port <<
3692 ")");
6de9e64b 3693 }
3694
bf8fe701 3695 debugs(83, 3, "clientNegotiateSSL: FD " << fd << " negotiated cipher " <<
3696 SSL_get_cipher(ssl));
1f7c9178 3697
6de9e64b 3698 client_cert = SSL_get_peer_certificate(ssl);
62e76326 3699
1f7c9178 3700 if (client_cert != NULL) {
bf8fe701 3701 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3702 " client certificate: subject: " <<
3703 X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0));
3704
3705 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3706 " client certificate: issuer: " <<
3707 X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0));
1f7c9178 3708
62e76326 3709 X509_free(client_cert);
1f7c9178 3710 } else {
bf8fe701 3711 debugs(83, 5, "clientNegotiateSSL: FD " << fd <<
3712 " has no certificate.");
1f7c9178 3713 }
3714
a46d2c0e 3715 conn->readSomeData();
1f7c9178 3716}
3717
379e8c1c 3718/**
ab2e0682
CT
3719 * If SSL_CTX is given, starts reading the SSL handshake.
3720 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
379e8c1c
AR
3721 */
3722static void
caf3666d 3723httpsEstablish(ConnStateData *connState, SSL_CTX *sslContext, Ssl::BumpMode bumpMode)
379e8c1c
AR
3724{
3725 SSL *ssl = NULL;
3726 assert(connState);
3727 const Comm::ConnectionPointer &details = connState->clientConnection;
3728
3729 if (sslContext && !(ssl = httpsCreate(details, sslContext)))
3730 return;
3731
7a957a93
AR
3732 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3733 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
87f237a9 3734 connState, ConnStateData::requestTimeout);
379e8c1c
AR
3735 commSetConnTimeout(details, Config.Timeout.request, timeoutCall);
3736
87f237a9 3737 if (ssl)
379e8c1c
AR
3738 Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0);
3739 else {
3740 char buf[MAX_IPSTRLEN];
caf3666d 3741 assert(bumpMode != Ssl::bumpNone && bumpMode != Ssl::bumpEnd);
0d901ef4 3742 HttpRequest::Pointer fakeRequest(new HttpRequest);
4dd643d5
AJ
3743 fakeRequest->SetHost(details->local.toStr(buf, sizeof(buf)));
3744 fakeRequest->port = details->local.port();
65ba7f04
CT
3745 fakeRequest->clientConnectionManager = connState;
3746 fakeRequest->client_addr = connState->clientConnection->remote;
3747#if FOLLOW_X_FORWARDED_FOR
3748 fakeRequest->indirect_client_addr = connState->clientConnection->remote;
3749#endif
3750 fakeRequest->my_addr = connState->clientConnection->local;
0d901ef4 3751 fakeRequest->flags.interceptTproxy = ((connState->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
6df4ecae 3752 fakeRequest->flags.intercepted = ((connState->clientConnection->flags & COMM_INTERCEPTION) != 0);
0d901ef4
SH
3753 fakeRequest->myportname = connState->port->name;
3754 if (fakeRequest->flags.interceptTproxy) {
3755 if (Config.accessList.spoof_client_ip) {
3756 ACLFilledChecklist checklist(Config.accessList.spoof_client_ip, fakeRequest.getRaw(), NULL);
3757 fakeRequest->flags.spoofClientIp = (checklist.fastCheck() == ACCESS_ALLOWED);
3758 } else
3759 fakeRequest->flags.spoofClientIp = true;
3760 } else
3761 fakeRequest->flags.spoofClientIp = false;
379e8c1c 3762 debugs(33, 4, HERE << details << " try to generate a Dynamic SSL CTX");
0d901ef4 3763 connState->switchToHttps(fakeRequest.getRaw(), bumpMode);
379e8c1c
AR
3764 }
3765}
3766
3767/**
87f237a9 3768 * A callback function to use with the ACLFilledChecklist callback.
94bfd31f 3769 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
7a957a93 3770 * else reverts the connection to tunnel mode.
379e8c1c
AR
3771 */
3772static void
3773httpsSslBumpAccessCheckDone(allow_t answer, void *data)
3774{
3775 ConnStateData *connState = (ConnStateData *) data;
3776
7a957a93 3777 // if the connection is closed or closing, just return.
379e8c1c
AR
3778 if (!connState->isOpen())
3779 return;
3780
7a957a93 3781 // Require both a match and a positive bump mode to work around exceptional
caf3666d 3782 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
5d65362c 3783 if (answer == ACCESS_ALLOWED && (answer.kind != Ssl::bumpNone && answer.kind != Ssl::bumpSplice)) {
e4f14091 3784 debugs(33, 2, "sslBump needed for " << connState->clientConnection << " method " << answer.kind);
08097970 3785 connState->sslBumpMode = static_cast<Ssl::BumpMode>(answer.kind);
379e8c1c 3786 } else {
08097970
AR
3787 debugs(33, 2, HERE << "sslBump not needed for " << connState->clientConnection);
3788 connState->sslBumpMode = Ssl::bumpNone;
9e104535 3789 }
379e8c1c 3790
9e104535
CT
3791 // fake a CONNECT request to force connState to tunnel
3792 static char ip[MAX_IPSTRLEN];
3793 connState->clientConnection->local.toUrl(ip, sizeof(ip));
3794 // Pre-pend this fake request to the TLS bits already in the buffer
3795 SBuf retStr;
3796 retStr.append("CONNECT ").append(ip).append(" HTTP/1.1\r\nHost: ").append(ip).append("\r\n\r\n");
3797 connState->in.buf = retStr.append(connState->in.buf);
3798 bool ret = connState->handleReadData();
3799 if (ret)
3800 ret = connState->clientParseRequests();
3801
3802 if (!ret) {
3803 debugs(33, 2, "Failed to start fake CONNECT request for SSL bumped connection: " << connState->clientConnection);
3804 connState->clientConnection->close();
379e8c1c
AR
3805 }
3806}
3807
63be0a78 3808/** handle a new HTTPS connection */
1f7c9178 3809static void
449f0115 3810httpsAccept(const CommAcceptCbParams &params)
1f7c9178 3811{
94bfd31f
AJ
3812 MasterXaction::Pointer xact = params.xaction;
3813 const AnyP::PortCfgPointer s = xact->squidPort;
3814
c0ff709f 3815 // NP: it is possible the port was reconfigured when the call or accept() was queued.
c4b7a5a9 3816
c8407295 3817 if (params.flag != Comm::OK) {
cbff89ba 3818 // Its possible the call was still queued when the client disconnected
449f0115 3819 debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
62e76326 3820 return;
c4b7a5a9 3821 }
62e76326 3822
449f0115
AJ
3823 debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation.");
3824 fd_note(params.conn->fd, "client https connect");
62e76326 3825
859741ed
AJ
3826 if (s->tcp_keepalive.enabled) {
3827 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
b2130d58 3828 }
3829
95dc7ff4 3830 ++incoming_sockets_accepted;
62e76326 3831
89aec9b6 3832 // Socket is ready, setup the connection manager to start using it
92ae4c86 3833 ConnStateData *connState = Https::NewServer(xact);
e7ce227f 3834 AsyncJob::Start(connState); // usually async-calls postHttpsAccept()
92ae4c86 3835}
62e76326 3836
92ae4c86
AR
3837void
3838ConnStateData::postHttpsAccept()
3839{
b3cb9958 3840 if (port->flags.tunnelSslBumping) {
e7ce227f 3841 debugs(33, 5, "accept transparent connection: " << clientConnection);
62e76326 3842
379e8c1c 3843 if (!Config.accessList.ssl_bump) {
b3cb9958 3844 httpsSslBumpAccessCheckDone(ACCESS_DENIED, this);
379e8c1c
AR
3845 return;
3846 }
87f237a9 3847
379e8c1c 3848 // Create a fake HTTP request for ssl_bump ACL check,
38450a50 3849 // using tproxy/intercept provided destination IP and port.
379e8c1c
AR
3850 HttpRequest *request = new HttpRequest();
3851 static char ip[MAX_IPSTRLEN];
92ae4c86
AR
3852 assert(clientConnection->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION));
3853 request->SetHost(clientConnection->local.toStr(ip, sizeof(ip)));
3854 request->port = clientConnection->local.port();
b3cb9958 3855 request->myportname = port->name;
87f237a9 3856
379e8c1c 3857 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL);
92ae4c86 3858 acl_checklist->src_addr = clientConnection->remote;
b3cb9958
AR
3859 acl_checklist->my_addr = port->s;
3860 acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, this);
379e8c1c
AR
3861 return;
3862 } else {
b3cb9958
AR
3863 SSL_CTX *sslContext = port->staticSslContext.get();
3864 httpsEstablish(this, sslContext, Ssl::bumpNone);
379e8c1c 3865 }
1f7c9178 3866}
3867
95d2589c 3868void
24438ec5 3869ConnStateData::sslCrtdHandleReplyWrapper(void *data, const Helper::Reply &reply)
ae7ff0b8 3870{
95d2589c
CT
3871 ConnStateData * state_data = (ConnStateData *)(data);
3872 state_data->sslCrtdHandleReply(reply);
3873}
ae7ff0b8 3874
95d2589c 3875void
24438ec5 3876ConnStateData::sslCrtdHandleReply(const Helper::Reply &reply)
95d2589c 3877{
2428ce02 3878 if (reply.result == Helper::BrokenHelper) {
5955f162
AJ
3879 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply);
3880 } else if (!reply.other().hasContent()) {
3881 debugs(1, DBG_IMPORTANT, HERE << "\"ssl_crtd\" helper returned <NULL> reply.");
95d2589c 3882 } else {
ff2d7d92 3883 Ssl::CrtdMessage reply_message(Ssl::CrtdMessage::REPLY);
0272dd08 3884 if (reply_message.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK) {
fb2178bb 3885 debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect");
95d2589c 3886 } else {
2428ce02 3887 if (reply.result != Helper::Okay) {
fb2178bb 3888 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody());
95d2589c 3889 } else {
fb2178bb 3890 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd");
a9c2dd2f 3891 if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) {
d620ae0e
CT
3892 doPeekAndSpliceStep();
3893 SSL *ssl = fd_table[clientConnection->fd].ssl;
3894 bool ret = Ssl::configureSSLUsingPkeyAndCertFromMemory(ssl, reply_message.getBody().c_str(), *port);
3895 if (!ret)
e4f14091 3896 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
d620ae0e
CT
3897 } else {
3898 SSL_CTX *ctx = Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str(), *port);
3899 getSslContextDone(ctx, true);
3900 }
95d2589c
CT
3901 return;
3902 }
3903 }
3904 }
3905 getSslContextDone(NULL);
3906}
ae7ff0b8 3907
06997a38 3908void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties)
fb2178bb 3909{
b38b26cb 3910 certProperties.commonName = sslCommonName.size() > 0 ? sslCommonName.termedBuf() : sslConnectHostOrIp.termedBuf();
fb2178bb
CT
3911
3912 // fake certificate adaptation requires bump-server-first mode
caf3666d
AR
3913 if (!sslServerBump) {
3914 assert(port->signingCert.get());
3915 certProperties.signWithX509.resetAndLock(port->signingCert.get());
3916 if (port->signPkey.get())
3917 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3918 certProperties.signAlgorithm = Ssl::algSignTrusted;
fb2178bb 3919 return;
caf3666d 3920 }
fb2178bb 3921
7a957a93
AR
3922 // In case of an error while connecting to the secure server, use a fake
3923 // trusted certificate, with no mimicked fields and no adaptation
3924 // algorithms. There is nothing we can mimic so we want to minimize the
3925 // number of warnings the user will have to see to get to the error page.
fd4624d7
CT
3926 assert(sslServerBump->entry);
3927 if (sslServerBump->entry->isEmpty()) {
3928 if (X509 *mimicCert = sslServerBump->serverCert.get())
59a49556
CT
3929 certProperties.mimicCert.resetAndLock(mimicCert);
3930
b248c2a3 3931 ACLFilledChecklist checklist(NULL, sslServerBump->request.getRaw(),
59a49556 3932 clientConnection != NULL ? clientConnection->rfc931 : dash_str);
7a957a93 3933 checklist.sslErrors = cbdataReference(sslServerBump->sslErrors);
59a49556
CT
3934
3935 for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) {
7a957a93 3936 // If the algorithm already set, then ignore it.
a06042fa 3937 if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) ||
87f237a9
A
3938 (ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) ||
3939 (ca->alg == Ssl::algSetValidBefore && certProperties.setValidBefore) )
a06042fa
CT
3940 continue;
3941
59a49556
CT
3942 if (ca->aclList && checklist.fastCheck(ca->aclList) == ACCESS_ALLOWED) {
3943 const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg];
3944 const char *param = ca->param;
87f237a9 3945
7a957a93
AR
3946 // For parameterless CN adaptation, use hostname from the
3947 // CONNECT request.
a06042fa 3948 if (ca->alg == Ssl::algSetCommonName) {
59a49556
CT
3949 if (!param)
3950 param = sslConnectHostOrIp.termedBuf();
3951 certProperties.commonName = param;
3952 certProperties.setCommonName = true;
87f237a9 3953 } else if (ca->alg == Ssl::algSetValidAfter)
59a49556 3954 certProperties.setValidAfter = true;
87f237a9 3955 else if (ca->alg == Ssl::algSetValidBefore)
59a49556
CT
3956 certProperties.setValidBefore = true;
3957
87f237a9 3958 debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " <<
8f9720ce 3959 alg << " param: " << (param ? param : "-"));
aebe6888 3960 }
fb2178bb 3961 }
aebe6888 3962
59a49556
CT
3963 certProperties.signAlgorithm = Ssl::algSignEnd;
3964 for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) {
3965 if (sg->aclList && checklist.fastCheck(sg->aclList) == ACCESS_ALLOWED) {
3966 certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg;
3967 break;
3968 }
aebe6888 3969 }
fd4624d7 3970 } else {// if (!sslServerBump->entry->isEmpty())
59a49556
CT
3971 // Use trusted certificate for a Squid-generated error
3972 // or the user would have to add a security exception
3973 // just to see the error page. We will close the connection
3974 // so that the trust is not extended to non-Squid content.
3975 certProperties.signAlgorithm = Ssl::algSignTrusted;
aebe6888
CT
3976 }
3977
10d914f6 3978 assert(certProperties.signAlgorithm != Ssl::algSignEnd);
aebe6888
CT
3979
3980 if (certProperties.signAlgorithm == Ssl::algSignUntrusted) {
f4e4d4d6 3981 assert(port->untrustedSigningCert.get());
95588170
CT
3982 certProperties.signWithX509.resetAndLock(port->untrustedSigningCert.get());
3983 certProperties.signWithPkey.resetAndLock(port->untrustedSignPkey.get());
87f237a9 3984 } else {
f4e4d4d6
CT
3985 assert(port->signingCert.get());
3986 certProperties.signWithX509.resetAndLock(port->signingCert.get());
aebe6888
CT
3987
3988 if (port->signPkey.get())
3989 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3990 }
3991 signAlgorithm = certProperties.signAlgorithm;
3c26b00a
CT
3992
3993 certProperties.signHash = Ssl::DefaultSignHash;
fb2178bb
CT
3994}
3995
1ce2822d 3996void
95d2589c
CT
3997ConnStateData::getSslContextStart()
3998{
129fe2a1
CT
3999 assert(areAllContextsForThisConnection());
4000 freeAllContexts();
4001 /* careful: freeAllContexts() above frees request, host, etc. */
4002
fb2178bb 4003 if (port->generateHostCertificates) {
aebe6888 4004 Ssl::CertificateProperties certProperties;
06997a38
CT
4005 buildSslCertGenerationParams(certProperties);
4006 sslBumpCertKey = certProperties.dbKey().c_str();
b38b26cb 4007 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
fb2178bb 4008
d620ae0e 4009 // Disable caching for bumpPeekAndSplice mode
a9c2dd2f 4010 if (!(sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare))) {
e4f14091 4011 debugs(33, 5, "Finding SSL certificate for " << sslBumpCertKey << " in cache");
31855516 4012 Ssl::LocalContextStorage * ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
d620ae0e 4013 SSL_CTX * dynCtx = NULL;
31855516 4014 Ssl::SSL_CTX_Pointer *cachedCtx = ssl_ctx_cache ? ssl_ctx_cache->get(sslBumpCertKey.termedBuf()) : NULL;
d620ae0e 4015 if (cachedCtx && (dynCtx = cachedCtx->get())) {
e4f14091 4016 debugs(33, 5, "SSL certificate for " << sslBumpCertKey << " found in cache");
d620ae0e 4017 if (Ssl::verifySslCertificate(dynCtx, certProperties)) {
e4f14091 4018 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey << " is valid");
d620ae0e
CT
4019 getSslContextDone(dynCtx);
4020 return;
4021 } else {
e4f14091 4022 debugs(33, 5, "Cached SSL certificate for " << sslBumpCertKey << " is out of date. Delete this certificate from cache");
31855516
CT
4023 if (ssl_ctx_cache)
4024 ssl_ctx_cache->del(sslBumpCertKey.termedBuf());
d620ae0e 4025 }
95d2589c 4026 } else {
e4f14091 4027 debugs(33, 5, "SSL certificate for " << sslBumpCertKey << " haven't found in cache");
95d2589c 4028 }
95d2589c
CT
4029 }
4030
b5faa519 4031#if USE_SSL_CRTD
00fc192d 4032 try {
87f237a9 4033 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd.");
ff2d7d92 4034 Ssl::CrtdMessage request_message(Ssl::CrtdMessage::REQUEST);
87f237a9
A
4035 request_message.setCode(Ssl::CrtdMessage::code_new_certificate);
4036 request_message.composeRequest(certProperties);
4037 debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str());
4038 Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this);
4039 return;
4040 } catch (const std::exception &e) {
00fc192d
AR
4041 debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " <<
4042 "request for " << certProperties.commonName <<
4043 " certificate: " << e.what() << "; will now block to " <<
4044 "generate that certificate.");
4045 // fall through to do blocking in-process generation.
4046 }
4047#endif // USE_SSL_CRTD
4048
aebe6888 4049 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName);
a9c2dd2f 4050 if (sslServerBump && (sslServerBump->act.step1 == Ssl::bumpPeek || sslServerBump->act.step1 == Ssl::bumpStare)) {
d620ae0e
CT
4051 doPeekAndSpliceStep();
4052 SSL *ssl = fd_table[clientConnection->fd].ssl;
4053 if (!Ssl::configureSSL(ssl, certProperties, *port))
e4f14091 4054 debugs(33, 5, "Failed to set certificates to ssl object for PeekAndSplice mode");
d620ae0e
CT
4055 } else {
4056 SSL_CTX *dynCtx = Ssl::generateSslContext(certProperties, *port);
4057 getSslContextDone(dynCtx, true);
4058 }
1ce2822d 4059 return;
95d2589c 4060 }
1ce2822d 4061 getSslContextDone(NULL);
95d2589c
CT
4062}
4063
1ce2822d 4064void
95d2589c
CT
4065ConnStateData::getSslContextDone(SSL_CTX * sslContext, bool isNew)
4066{
4067 // Try to add generated ssl context to storage.
4068 if (port->generateHostCertificates && isNew) {
a594dbfa 4069
a411d213
CT
4070 if (signAlgorithm == Ssl::algSignTrusted) {
4071 // Add signing certificate to the certificates chain
4072 X509 *cert = port->signingCert.get();
4073 if (SSL_CTX_add_extra_chain_cert(sslContext, cert)) {
4074 // increase the certificate lock
4075 CRYPTO_add(&(cert->references),1,CRYPTO_LOCK_X509);
4076 } else {
4077 const int ssl_error = ERR_get_error();
4078 debugs(33, DBG_IMPORTANT, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
4079 }
aebe6888 4080 Ssl::addChainToSslContext(sslContext, port->certsToChain.get());
a411d213 4081 }
aebe6888 4082 //else it is self-signed or untrusted do not attrach any certificate
a594dbfa 4083
9873e378 4084 Ssl::LocalContextStorage *ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
b38b26cb 4085 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
fb2178bb 4086 if (sslContext) {
9873e378 4087 if (!ssl_ctx_cache || !ssl_ctx_cache->add(sslBumpCertKey.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext))) {
95d2589c 4088 // If it is not in storage delete after using. Else storage deleted it.
73c36fd9 4089 fd_table[clientConnection->fd].dynamicSslContext = sslContext;
95d2589c
CT
4090 }
4091 } else {
fb2178bb 4092 debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslConnectHostOrIp);
95d2589c
CT
4093 }
4094 }
4095
4096 // If generated ssl context = NULL, try to use static ssl context.
4097 if (!sslContext) {
4098 if (!port->staticSslContext) {
e0236918 4099 debugs(83, DBG_IMPORTANT, "Closing SSL " << clientConnection->remote << " as lacking SSL context");
73c36fd9 4100 clientConnection->close();
1ce2822d 4101 return;
95d2589c
CT
4102 } else {
4103 debugs(33, 5, HERE << "Using static ssl context.");
4104 sslContext = port->staticSslContext.get();
4105 }
4106 }
ae7ff0b8 4107
a9b1d8c6 4108 if (!httpsCreate(clientConnection, sslContext))
1ce2822d 4109 return;
ae7ff0b8 4110
4e67d484
CT
4111 // bumped intercepted conns should already have Config.Timeout.request set
4112 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
4113 // to make sure the connection does not get stuck on non-SSL clients.
4114 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4115 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
3899de60 4116 this, ConnStateData::requestTimeout);
4e67d484 4117 commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall);
ae7ff0b8 4118
a3c6762c 4119 // Disable the client read handler until CachePeer selection is complete
73c36fd9
AJ
4120 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
4121 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientNegotiateSSL, this, 0);
ae7ff0b8 4122 switchedToHttps_ = true;
ae7ff0b8 4123}
4124
1ce2822d 4125void
caf3666d 4126ConnStateData::switchToHttps(HttpRequest *request, Ssl::BumpMode bumpServerMode)
95d2589c
CT
4127{
4128 assert(!switchedToHttps_);
4129
65ba7f04
CT
4130 sslConnectHostOrIp = request->GetHost();
4131 sslCommonName = request->GetHost();
95d2589c 4132
83d4cd15
CT
4133 // We are going to read new request
4134 flags.readMore = true;
73c36fd9 4135 debugs(33, 5, HERE << "converting " << clientConnection << " to SSL");
95d2589c 4136
4599cded
AJ
4137 // keep version major.minor details the same.
4138 // but we are now performing the HTTPS handshake traffic
4139 transferProtocol.protocol = AnyP::PROTO_HTTPS;
4140
2bd84e5f
CT
4141 // If sslServerBump is set, then we have decided to deny CONNECT
4142 // and now want to switch to SSL to send the error to the client
4143 // without even peeking at the origin server certificate.
caf3666d 4144 if (bumpServerMode == Ssl::bumpServerFirst && !sslServerBump) {
e857372a 4145 request->flags.sslPeek = true;
65ba7f04 4146 sslServerBump = new Ssl::ServerBump(request);
fd4624d7 4147
d7ce0bcd 4148 // will call httpsPeeked() with certificate and connection, eventually
b248c2a3 4149 FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw());
d7ce0bcd 4150 return;
e1f72a8b 4151 } else if (bumpServerMode == Ssl::bumpPeek || bumpServerMode == Ssl::bumpStare) {
d620ae0e 4152 request->flags.sslPeek = true;
5d65362c 4153 sslServerBump = new Ssl::ServerBump(request, NULL, bumpServerMode);
d620ae0e 4154 startPeekAndSplice();
e1f72a8b 4155 return;
d7ce0bcd
AR
4156 }
4157
fb2178bb 4158 // otherwise, use sslConnectHostOrIp
d7ce0bcd
AR
4159 getSslContextStart();
4160}
4161
3248e962
CT
4162bool
4163ConnStateData::spliceOnError(const err_type err)
4164{
4165 if (Config.accessList.on_unsupported_protocol) {
4166 assert(serverBump());
4167 ACLFilledChecklist checklist(Config.accessList.on_unsupported_protocol, serverBump()->request.getRaw(), NULL);
4168 checklist.requestErrorType = err;
4169 checklist.conn(this);
4170 allow_t answer = checklist.fastCheck();
4171 if (answer == ACCESS_ALLOWED && answer.kind == 1) {
4172 splice();
4173 return true;
4174 }
4175 }
4176 return false;
4177}
4178
d620ae0e
CT
4179/** negotiate an SSL connection */
4180static void
4181clientPeekAndSpliceSSL(int fd, void *data)
4182{
4183 ConnStateData *conn = (ConnStateData *)data;
4184 SSL *ssl = fd_table[fd].ssl;
4185
8693472e 4186 debugs(83, 5, "Start peek and splice on FD " << fd);
d620ae0e 4187
3248e962
CT
4188 int ret = 0;
4189 if ((ret = Squid_SSL_accept(conn, clientPeekAndSpliceSSL)) < 0)
d620ae0e
CT
4190 debugs(83, 2, "SSL_accept failed.");
4191
4192 BIO *b = SSL_get_rbio(ssl);
4193 assert(b);
4194 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(b->ptr);
3248e962
CT
4195 if (ret < 0) {
4196 const err_type err = bio->noSslClient() ? ERR_PROTOCOL_UNKNOWN : ERR_SECURE_ACCEPT_FAIL;
4197 if (!conn->spliceOnError(err))
4198 conn->clientConnection->close();
4199 return;
4200 }
4201
4202 if (bio->rBufData().contentSize() > 0)
4203 conn->receivedFirstByte();
4204
d620ae0e 4205 if (bio->gotHello()) {
cedca6e7
CT
4206 if (conn->serverBump()) {
4207 Ssl::Bio::sslFeatures const &features = bio->getFeatures();
8693472e
CT
4208 if (!features.serverName.isEmpty())
4209 conn->serverBump()->clientSni = features.serverName;
cedca6e7
CT
4210 }
4211
e4f14091 4212 debugs(83, 5, "I got hello. Start forwarding the request!!! ");
d620ae0e
CT
4213 Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
4214 Comm::SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
4215 conn->startPeekAndSpliceDone();
4216 return;
4217 }
4218}
4219
4220void ConnStateData::startPeekAndSplice()
4221{
4222 // will call httpsPeeked() with certificate and connection, eventually
4223 SSL_CTX *unConfiguredCTX = Ssl::createSSLContext(port->signingCert, port->signPkey, *port);
4224 fd_table[clientConnection->fd].dynamicSslContext = unConfiguredCTX;
4225
4226 if (!httpsCreate(clientConnection, unConfiguredCTX))
4227 return;
4228
4229 // commSetConnTimeout() was called for this request before we switched.
3248e962
CT
4230 // Fix timeout to request_start_timeout
4231 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4232 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
4233 TimeoutDialer, this, ConnStateData::requestTimeout);
4234 commSetConnTimeout(clientConnection, Config.Timeout.request_start_timeout, timeoutCall);
4235 // Also reset receivedFirstByte_ flag to allow this timeout work in the case we have
4236 // a bumbed "connect" request on non transparent port.
4237 receivedFirstByte_ = false;
d620ae0e
CT
4238
4239 // Disable the client read handler until CachePeer selection is complete
4240 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
4241 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientPeekAndSpliceSSL, this, 0);
4242 switchedToHttps_ = true;
4243
4244 SSL *ssl = fd_table[clientConnection->fd].ssl;
4245 BIO *b = SSL_get_rbio(ssl);
4246 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(b->ptr);
4247 bio->hold(true);
4248}
4249
5d65362c
CT
4250void httpsSslBumpStep2AccessCheckDone(allow_t answer, void *data)
4251{
4252 ConnStateData *connState = (ConnStateData *) data;
4253
4254 // if the connection is closed or closing, just return.
4255 if (!connState->isOpen())
4256 return;
4257
e4f14091 4258 debugs(33, 5, "Answer: " << answer << " kind:" << answer.kind);
a9c2dd2f
CT
4259 assert(connState->serverBump());
4260 Ssl::BumpMode bumpAction;
4261 if (answer == ACCESS_ALLOWED) {
4262 if (answer.kind == Ssl::bumpNone)
4263 bumpAction = Ssl::bumpSplice;
4264 else if (answer.kind == Ssl::bumpClientFirst || answer.kind == Ssl::bumpServerFirst)
4265 bumpAction = Ssl::bumpBump;
4266 else
4267 bumpAction = (Ssl::BumpMode)answer.kind;
4268 } else
4269 bumpAction = Ssl::bumpSplice;
4270
4271 connState->serverBump()->act.step2 = bumpAction;
4272 connState->sslBumpMode = bumpAction;
4273
4274 if (bumpAction == Ssl::bumpTerminate) {
4275 comm_close(connState->clientConnection->fd);
4276 } else if (bumpAction != Ssl::bumpSplice) {
4277 connState->startPeekAndSpliceDone();
3248e962
CT
4278 } else
4279 connState->splice();
4280}
5d65362c 4281
3248e962
CT
4282void
4283ConnStateData::splice()
4284{
4285 //Normally we can splice here, because we just got client hello message
4286 SSL *ssl = fd_table[clientConnection->fd].ssl;
4287 BIO *b = SSL_get_rbio(ssl);
4288 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(b->ptr);
4289 MemBuf const &rbuf = bio->rBufData();
4290 debugs(83,5, "Bio for " << clientConnection << " read " << rbuf.contentSize() << " helo bytes");
4291 // Do splice:
4292 fd_table[clientConnection->fd].read_method = &default_read_method;
4293 fd_table[clientConnection->fd].write_method = &default_write_method;
4294
4295 if (transparent()) {
4296 // set the current protocol to something sensible (was "HTTPS" for the bumping process)
4297 // we are sending a faked-up HTTP/1.1 message wrapper, so go with that.
4298 transferProtocol = Http::ProtocolVersion();
4299 // fake a CONNECT request to force connState to tunnel
4300 static char ip[MAX_IPSTRLEN];
4301 clientConnection->local.toUrl(ip, sizeof(ip));
4302 in.buf.assign("CONNECT ").append(ip).append(" HTTP/1.1\r\nHost: ").append(ip).append("\r\n\r\n").append(rbuf.content(), rbuf.contentSize());
4303 bool ret = handleReadData();
4304 if (ret)
4305 ret = clientParseRequests();
4306
4307 if (!ret) {
4308 debugs(33, 2, "Failed to start fake CONNECT request for ssl spliced connection: " << clientConnection);
4309 clientConnection->close();
5d65362c 4310 }
3248e962
CT
4311 } else {
4312 // XXX: assuming that there was an HTTP/1.1 CONNECT to begin with...
4313
4314 // reset the current protocol to HTTP/1.1 (was "HTTPS" for the bumping process)
4315 transferProtocol = Http::ProtocolVersion();
4316 // in.buf still has the "CONNECT ..." request data, reset it to SSL hello message
4317 in.buf.append(rbuf.content(), rbuf.contentSize());
4318 ClientSocketContext::Pointer context = getCurrentContext();
4319 ClientHttpRequest *http = context->http;
4320 tunnelStart(http, &http->out.size, &http->al->http.code, http->al);
5d65362c
CT
4321 }
4322}
4323
d620ae0e
CT
4324void
4325ConnStateData::startPeekAndSpliceDone()
4326{
5d65362c
CT
4327 // This is the Step2 of the SSL bumping
4328 assert(sslServerBump);
4329 if (sslServerBump->step == Ssl::bumpStep1) {
4330 sslServerBump->step = Ssl::bumpStep2;
4331 // Run a accessList check to check if want to splice or continue bumping
4332
4333 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, sslServerBump->request.getRaw(), NULL);
4334 //acl_checklist->src_addr = params.conn->remote;
4335 //acl_checklist->my_addr = s->s;
4336 acl_checklist->nonBlockingCheck(httpsSslBumpStep2AccessCheckDone, this);
4337 return;
4338 }
4339
31855516 4340 FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw());
d620ae0e
CT
4341}
4342
4343void
4344ConnStateData::doPeekAndSpliceStep()
4345{
4346 SSL *ssl = fd_table[clientConnection->fd].ssl;
4347 BIO *b = SSL_get_rbio(ssl);
4348 assert(b);
4349 Ssl::ClientBio *bio = static_cast<Ssl::ClientBio *>(b->ptr);
4350
e4f14091 4351 debugs(33, 5, "PeekAndSplice mode, proceed with client negotiation. Currrent state:" << SSL_state_string_long(ssl));
d620ae0e
CT
4352 bio->hold(false);
4353
4354 Comm::SetSelect(clientConnection->fd, COMM_SELECT_WRITE, clientNegotiateSSL, this, 0);
4355 switchedToHttps_ = true;
4356}
4357
d7ce0bcd
AR
4358void
4359ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection)
4360{
fd4624d7 4361 Must(sslServerBump != NULL);
819c207f 4362
061bbdec
CT
4363 if (Comm::IsConnOpen(serverConnection)) {
4364 SSL *ssl = fd_table[serverConnection->fd].ssl;
4365 assert(ssl);
4366 Ssl::X509_Pointer serverCert(SSL_get_peer_certificate(ssl));
4367 assert(serverCert.get() != NULL);
fb2178bb 4368 sslCommonName = Ssl::CommonHostName(serverCert.get());
87f237a9 4369 debugs(33, 5, HERE << "HTTPS server CN: " << sslCommonName <<
59a49556 4370 " bumped: " << *serverConnection);
061bbdec
CT
4371
4372 pinConnection(serverConnection, NULL, NULL, false);
4373
fb2178bb 4374 debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp);
59a49556 4375 } else {
13858f50 4376 debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp);
8499a1de
CT
4377 Ip::Address intendedDest;
4378 intendedDest = sslConnectHostOrIp.termedBuf();
c3d24490 4379 const bool isConnectRequest = !port->flags.isIntercepted();
35cd4281 4380
8499a1de
CT
4381 // Squid serves its own error page and closes, so we want
4382 // a CN that causes no additional browser errors. Possible
35cd4281 4383 // only when bumping CONNECT with a user-typed address.
4dd643d5 4384 if (intendedDest.isAnyAddr() || isConnectRequest)
8499a1de 4385 sslCommonName = sslConnectHostOrIp;
fd4624d7
CT
4386 else if (sslServerBump->serverCert.get())
4387 sslCommonName = Ssl::CommonHostName(sslServerBump->serverCert.get());
129fe2a1
CT
4388
4389 // copy error detail from bump-server-first request to CONNECT request
4390 if (currentobject != NULL && currentobject->http != NULL && currentobject->http->request)
4391 currentobject->http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
59a49556 4392 }
061bbdec 4393
1ce2822d 4394 getSslContextStart();
95d2589c
CT
4395}
4396
cb4f4424 4397#endif /* USE_OPENSSL */
1f7c9178 4398
00516be1
AR
4399/// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
4400static bool
73c36fd9 4401OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType)
00516be1 4402{
73c36fd9 4403 if (!Comm::IsConnOpen(c)) {
00516be1
AR
4404 Must(NHttpSockets > 0); // we tried to open some
4405 --NHttpSockets; // there will be fewer sockets than planned
4406 Must(HttpSockets[NHttpSockets] < 0); // no extra fds received
4407
4408 if (!NHttpSockets) // we could not open any listen sockets at all
cbff89ba 4409 fatalf("Unable to open %s",FdNote(portType));
00516be1
AR
4410
4411 return false;
4412 }
4413 return true;
4414}
4415
4416/// find any unused HttpSockets[] slot and store fd there or return false
4417static bool
e0d28505 4418AddOpenedHttpSocket(const Comm::ConnectionPointer &conn)
00516be1
AR
4419{
4420 bool found = false;
95dc7ff4 4421 for (int i = 0; i < NHttpSockets && !found; ++i) {
00516be1 4422 if ((found = HttpSockets[i] < 0))
e0d28505 4423 HttpSockets[i] = conn->fd;
00516be1
AR
4424 }
4425 return found;
4426}
15df8349 4427
d193a436 4428static void
15df8349 4429clientHttpConnectionsOpen(void)
4430{
fa720bfb 4431 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
65d448bc 4432 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4433 debugs(1, DBG_IMPORTANT, "WARNING: You have too many 'http_port' lines.");
4434 debugs(1, DBG_IMPORTANT, " The limit is " << MAXTCPLISTENPORTS << " HTTP ports.");
62e76326 4435 continue;
4436 }
4437
cb4f4424 4438#if USE_OPENSSL
6a25a046 4439 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
1ca54a54 4440 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s);
6a25a046 4441 s->flags.tunnelSslBumping = false;
3d61b18e
AJ
4442 }
4443
6a25a046 4444 if (s->flags.tunnelSslBumping &&
2ee34428
A
4445 !s->staticSslContext &&
4446 !s->generateHostCertificates) {
859741ed 4447 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4448 s->flags.tunnelSslBumping = false;
ae7ff0b8 4449 }
6a25a046 4450 if (s->flags.tunnelSslBumping) {
95d2589c
CT
4451 // Create ssl_ctx cache for this port.
4452 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4453 }
ae7ff0b8 4454#endif
4455
e0d28505 4456 // Fill out a Comm::Connection which IPC will open as a listener for us
8bbb16e3 4457 // then pass back when active so we can start a TcpAcceptor subscription.
e0d28505
AJ
4458 s->listenConn = new Comm::Connection;
4459 s->listenConn->local = s->s;
6a25a046 4460 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) | (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
c303f6e3 4461
cbff89ba
AJ
4462 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4463 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
fa720bfb 4464 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, CommAcceptCbParams(NULL)));
cbff89ba 4465 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4466
cbff89ba 4467 AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened",
8bbb16e3
AJ
4468 ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub));
4469 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall);
62e76326 4470
a38ec4b1
FC
4471 HttpSockets[NHttpSockets] = -1; // set in clientListenerConnectionOpened
4472 ++NHttpSockets;
15df8349 4473 }
d193a436 4474}
4475
cb4f4424 4476#if USE_OPENSSL
d193a436 4477static void
4478clientHttpsConnectionsOpen(void)
4479{
fa720bfb 4480 for (AnyP::PortCfgPointer s = HttpsPortList; s != NULL; s = s->next) {
65d448bc 4481 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4482 debugs(1, DBG_IMPORTANT, "Ignoring 'https_port' lines exceeding the limit.");
4483 debugs(1, DBG_IMPORTANT, "The limit is " << MAXTCPLISTENPORTS << " HTTPS ports.");
62e76326 4484 continue;
4485 }
4486
95d2589c 4487 if (!s->staticSslContext) {
e0236918 4488 debugs(1, DBG_IMPORTANT, "Ignoring https_port " << s->s <<
ae7ff0b8 4489 " due to SSL initialization failure.");
4490 continue;
f9ad0106 4491 }
4492
d7ce0bcd 4493 // TODO: merge with similar code in clientHttpConnectionsOpen()
6a25a046 4494 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
1ca54a54 4495 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s);
6a25a046 4496 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4497 }
4498
6a25a046 4499 if (s->flags.tunnelSslBumping && !s->staticSslContext && !s->generateHostCertificates) {
03f00a11 4500 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4501 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4502 }
4503
6a25a046 4504 if (s->flags.tunnelSslBumping) {
d7ce0bcd
AR
4505 // Create ssl_ctx cache for this port.
4506 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4507 }
4508
e0d28505 4509 // Fill out a Comm::Connection which IPC will open as a listener for us
859741ed
AJ
4510 s->listenConn = new Comm::Connection;
4511 s->listenConn->local = s->s;
6a25a046
FC
4512 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
4513 (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
62e76326 4514
cbff89ba
AJ
4515 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4516 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
fa720bfb 4517 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, CommAcceptCbParams(NULL)));
cbff89ba 4518 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4519
cbff89ba 4520 AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened",
8bbb16e3 4521 ListeningStartedDialer(&clientListenerConnectionOpened,
f53969cc 4522 s, Ipc::fdnHttpsSocket, sub));
8bbb16e3 4523 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall);
a38ec4b1
FC
4524 HttpSockets[NHttpSockets] = -1;
4525 ++NHttpSockets;
cbff89ba 4526 }
d193a436 4527}
d193a436 4528#endif
4529
92ae4c86 4530void
27c841f6
AR
4531clientStartListeningOn(AnyP::PortCfgPointer &port, const RefCount< CommCbFunPtrCallT<CommAcceptCbPtrFun> > &subCall, const Ipc::FdNoteId fdNote)
4532{
92ae4c86
AR
4533 // Fill out a Comm::Connection which IPC will open as a listener for us
4534 port->listenConn = new Comm::Connection;
4535 port->listenConn->local = port->s;
e7ce227f
AR
4536 port->listenConn->flags =
4537 COMM_NONBLOCKING |
4538 (port->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
4539 (port->flags.natIntercept ? COMM_INTERCEPTION : 0);
92ae4c86
AR
4540
4541 // route new connections to subCall
4542 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
4543 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
e7ce227f
AR
4544 AsyncCall::Pointer listenCall =
4545 asyncCall(33, 2, "clientListenerConnectionOpened",
4546 ListeningStartedDialer(&clientListenerConnectionOpened,
4547 port, fdNote, sub));
92ae4c86 4548 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, port->listenConn, fdNote, listenCall);
434a79b0 4549
92ae4c86
AR
4550 assert(NHttpSockets < MAXTCPLISTENPORTS);
4551 HttpSockets[NHttpSockets] = -1;
4552 ++NHttpSockets;
434a79b0
DK
4553}
4554
e0d28505 4555/// process clientHttpConnectionsOpen result
00516be1 4556static void
fa720bfb 4557clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub)
00516be1 4558{
fa720bfb
AJ
4559 Must(s != NULL);
4560
8bbb16e3 4561 if (!OpenedHttpSocket(s->listenConn, portTypeNote))
00516be1 4562 return;
62e76326 4563
e0d28505 4564 Must(Comm::IsConnOpen(s->listenConn));
62e76326 4565
8bbb16e3 4566 // TCP: setup a job to handle accept() with subscribed handler
fa720bfb 4567 AsyncJob::Start(new Comm::TcpAcceptor(s, FdNote(portTypeNote), sub));
8bbb16e3 4568
e0236918 4569 debugs(1, DBG_IMPORTANT, "Accepting " <<
6a25a046 4570 (s->flags.natIntercept ? "NAT intercepted " : "") <<
0d901ef4 4571 (s->flags.tproxyIntercept ? "TPROXY intercepted " : "") <<
6a25a046
FC
4572 (s->flags.tunnelSslBumping ? "SSL bumped " : "") <<
4573 (s->flags.accelSurrogate ? "reverse-proxy " : "")
8bbb16e3
AJ
4574 << FdNote(portTypeNote) << " connections at "
4575 << s->listenConn);
62e76326 4576
e0d28505 4577 Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for
d193a436 4578}
4579
d193a436 4580void
4581clientOpenListenSockets(void)
4582{
4583 clientHttpConnectionsOpen();
cb4f4424 4584#if USE_OPENSSL
d193a436 4585 clientHttpsConnectionsOpen();
1f7c9178 4586#endif
92ae4c86 4587 Ftp::StartListening();
62e76326 4588
15df8349 4589 if (NHttpSockets < 1)
e7ce227f 4590 fatal("No HTTP, HTTPS, or FTP ports configured");
15df8349 4591}
edce4d98 4592
c0fbae16 4593void
e7ce227f 4594clientConnectionsClose()
c0fbae16 4595{
fa720bfb 4596 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
00406b24 4597 if (s->listenConn != NULL) {
e0236918 4598 debugs(1, DBG_IMPORTANT, "Closing HTTP port " << s->listenConn->local);
00406b24
AJ
4599 s->listenConn->close();
4600 s->listenConn = NULL;
04f55905
AJ
4601 }
4602 }
62e76326 4603
cb4f4424 4604#if USE_OPENSSL
fa720bfb 4605 for (AnyP::PortCfgPointer s = HttpsPortList; s != NULL; s = s->next) {
00406b24 4606 if (s->listenConn != NULL) {
e0236918 4607 debugs(1, DBG_IMPORTANT, "Closing HTTPS port " << s->listenConn->local);
00406b24
AJ
4608 s->listenConn->close();
4609 s->listenConn = NULL;
62e76326 4610 }
c0fbae16 4611 }
04f55905
AJ
4612#endif
4613
92ae4c86 4614 Ftp::StopListening();
434a79b0 4615
04f55905 4616 // TODO see if we can drop HttpSockets array entirely */
95dc7ff4 4617 for (int i = 0; i < NHttpSockets; ++i) {
04f55905
AJ
4618 HttpSockets[i] = -1;
4619 }
62e76326 4620
c0fbae16 4621 NHttpSockets = 0;
4622}
f66a9ef4 4623
4624int
190154cf 4625varyEvaluateMatch(StoreEntry * entry, HttpRequest * request)
f66a9ef4 4626{
4627 const char *vary = request->vary_headers;
a9925b40 4628 int has_vary = entry->getReply()->header.has(HDR_VARY);
f66a9ef4 4629#if X_ACCELERATOR_VARY
62e76326 4630
edce4d98 4631 has_vary |=
a9925b40 4632 entry->getReply()->header.has(HDR_X_ACCELERATOR_VARY);
f66a9ef4 4633#endif
62e76326 4634
f66a9ef4 4635 if (!has_vary || !entry->mem_obj->vary_headers) {
62e76326 4636 if (vary) {
4637 /* Oops... something odd is going on here.. */
e0236918 4638 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
c877c0bc 4639 entry->mem_obj->urlXXX() << "' '" << vary << "'");
62e76326 4640 safe_free(request->vary_headers);
4641 return VARY_CANCEL;
4642 }
4643
4644 if (!has_vary) {
4645 /* This is not a varying object */
4646 return VARY_NONE;
4647 }
4648
4649 /* virtual "vary" object found. Calculate the vary key and
4650 * continue the search
4651 */
4652 vary = httpMakeVaryMark(request, entry->getReply());
4653
4654 if (vary) {
4655 request->vary_headers = xstrdup(vary);
4656 return VARY_OTHER;
4657 } else {
4658 /* Ouch.. we cannot handle this kind of variance */
4659 /* XXX This cannot really happen, but just to be complete */
4660 return VARY_CANCEL;
4661 }
f66a9ef4 4662 } else {
62e76326 4663 if (!vary) {
4664 vary = httpMakeVaryMark(request, entry->getReply());
4665
4666 if (vary)
4667 request->vary_headers = xstrdup(vary);
4668 }
4669
4670 if (!vary) {
4671 /* Ouch.. we cannot handle this kind of variance */
4672 /* XXX This cannot really happen, but just to be complete */
4673 return VARY_CANCEL;
4674 } else if (strcmp(vary, entry->mem_obj->vary_headers) == 0) {
4675 return VARY_MATCH;
4676 } else {
4677 /* Oops.. we have already been here and still haven't
4678 * found the requested variant. Bail out
4679 */
e0236918 4680 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
c877c0bc 4681 entry->mem_obj->urlXXX() << "' '" << vary << "'");
62e76326 4682 return VARY_CANCEL;
4683 }
f66a9ef4 4684 }
4685}
28d4805a 4686
c0941a6a 4687ACLFilledChecklist *
59a1efb2 4688clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http)
28d4805a 4689{
1cf238db 4690 ConnStateData * conn = http->getConn();
c0941a6a 4691 ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request,
73c36fd9 4692 cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str);
d4806c91 4693 ch->al = http->al;
28d4805a 4694 /*
4695 * hack for ident ACL. It needs to get full addresses, and a place to store
4696 * the ident result on persistent connections...
4697 */
4698 /* connection oriented auth also needs these two lines for it's operation. */
28d4805a 4699 return ch;
4700}
a46d2c0e 4701
a46d2c0e 4702bool
4703ConnStateData::transparent() const
4704{
40d34a62 4705 return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
a46d2c0e 4706}
4707
4708bool
4709ConnStateData::reading() const
4710{
f84dd7eb 4711 return reader != NULL;
a46d2c0e 4712}
4713
4714void
f84dd7eb 4715ConnStateData::stopReading()
a46d2c0e 4716{
f84dd7eb 4717 if (reading()) {
7e66d5e2 4718 Comm::ReadCancel(clientConnection->fd, reader);
f84dd7eb
AR
4719 reader = NULL;
4720 }
a46d2c0e 4721}
4722
5f8252d2 4723BodyPipe::Pointer
3e62bd58 4724ConnStateData::expectRequestBody(int64_t size)
5f8252d2 4725{
4726 bodyPipe = new BodyPipe(this);
39cb8c41
AR
4727 if (size >= 0)
4728 bodyPipe->setBodySize(size);
4729 else
4730 startDechunkingRequest();
5f8252d2 4731 return bodyPipe;
4732}
4733
39cb8c41
AR
4734int64_t
4735ConnStateData::mayNeedToReadMoreBody() const
4736{
4737 if (!bodyPipe)
4738 return 0; // request without a body or read/produced all body bytes
4739
4740 if (!bodyPipe->bodySizeKnown())
4741 return -1; // probably need to read more, but we cannot be sure
4742
4743 const int64_t needToProduce = bodyPipe->unproducedSize();
e7287625 4744 const int64_t haveAvailable = static_cast<int64_t>(in.buf.length());
39cb8c41
AR
4745
4746 if (needToProduce <= haveAvailable)
4747 return 0; // we have read what we need (but are waiting for pipe space)
4748
4749 return needToProduce - haveAvailable;
4750}
4751
55e44db9 4752void
cf6eb29e 4753ConnStateData::stopReceiving(const char *error)
55e44db9 4754{
cf6eb29e
CT
4755 debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error <<
4756 "; old sending error: " <<
4757 (stoppedSending() ? stoppedSending_ : "none"));
5f8252d2 4758
cf6eb29e
CT
4759 if (const char *oldError = stoppedReceiving()) {
4760 debugs(33, 3, HERE << "already stopped receiving: " << oldError);
4761 return; // nothing has changed as far as this connection is concerned
4762 }
5f8252d2 4763
cf6eb29e 4764 stoppedReceiving_ = error;
5f8252d2 4765
cf6eb29e
CT
4766 if (const char *sendError = stoppedSending()) {
4767 debugs(33, 3, HERE << "closing because also stopped sending: " << sendError);
4768 clientConnection->close();
4769 }
55e44db9 4770}
4771
eb44b2d7 4772void
e29ccb57
A
4773ConnStateData::expectNoForwarding()
4774{
eb44b2d7
CT
4775 if (bodyPipe != NULL) {
4776 debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status());
4777 bodyPipe->expectNoConsumption();
4778 }
4779}
4780
39cb8c41 4781/// initialize dechunking state
3ff65596 4782void
39cb8c41 4783ConnStateData::startDechunkingRequest()
3ff65596 4784{
39cb8c41
AR
4785 Must(bodyPipe != NULL);
4786 debugs(33, 5, HERE << "start dechunking" << bodyPipe->status());
3ff65596
AR
4787 assert(!in.bodyParser);
4788 in.bodyParser = new ChunkedCodingParser;
3ff65596
AR
4789}
4790
39cb8c41 4791/// put parsed content into input buffer and clean up
3ff65596 4792void
39cb8c41 4793ConnStateData::finishDechunkingRequest(bool withSuccess)
3ff65596 4794{
39cb8c41 4795 debugs(33, 5, HERE << "finish dechunking: " << withSuccess);
3ff65596 4796
39cb8c41
AR
4797 if (bodyPipe != NULL) {
4798 debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status());
4799 BodyPipe::Pointer myPipe = bodyPipe;
4800 stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize()
4801 Must(!bodyPipe); // we rely on it being nil after we are done with body
4802 if (withSuccess) {
4803 Must(myPipe->bodySizeKnown());
4804 ClientSocketContext::Pointer context = getCurrentContext();
4805 if (context != NULL && context->http && context->http->request)
4806 context->http->request->setContentLength(myPipe->bodySize());
4807 }
3ff65596 4808 }
3ff65596 4809
39cb8c41
AR
4810 delete in.bodyParser;
4811 in.bodyParser = NULL;
3ff65596
AR
4812}
4813
e7287625 4814ConnStateData::In::In() :
f53969cc
SM
4815 bodyParser(NULL),
4816 buf()
a46d2c0e 4817{}
4818
4819ConnStateData::In::~In()
4820{
39cb8c41 4821 delete bodyParser; // TODO: pool
a46d2c0e 4822}
d67acb4e 4823
655daa06
AR
4824void
4825ConnStateData::sendControlMsg(HttpControlMsg msg)
4826{
eedd4182
AR
4827 if (!isOpen()) {
4828 debugs(33, 3, HERE << "ignoring 1xx due to earlier closure");
655daa06
AR
4829 return;
4830 }
4831
eedd4182
AR
4832 ClientSocketContext::Pointer context = getCurrentContext();
4833 if (context != NULL) {
4834 context->writeControlMsg(msg); // will call msg.cbSuccess
655daa06
AR
4835 return;
4836 }
4837
4838 debugs(33, 3, HERE << " closing due to missing context for 1xx");
73c36fd9 4839 clientConnection->close();
655daa06
AR
4840}
4841
d7ce0bcd 4842/// Our close handler called by Comm when the pinned connection is closed
d67acb4e
AJ
4843void
4844ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io)
4845{
7a957a93
AR
4846 // FwdState might repin a failed connection sooner than this close
4847 // callback is called for the failed connection.
693cb033
CT
4848 assert(pinning.serverConnection == io.conn);
4849 pinning.closeHandler = NULL; // Comm unregisters handlers before calling
4850 const bool sawZeroReply = pinning.zeroReply; // reset when unpinning
89b1d7a2 4851 unpinConnection(false);
f8e4867b 4852
7ac40923 4853 if (sawZeroReply && clientConnection != NULL) {
693cb033
CT
4854 debugs(33, 3, "Closing client connection on pinned zero reply.");
4855 clientConnection->close();
85563fd9 4856 }
f8e4867b 4857
d67acb4e
AJ
4858}
4859
b1cf2350 4860void
f8e4867b 4861ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth, bool monitor)
9e008dda 4862{
e7ce227f 4863 if (!Comm::IsConnOpen(pinning.serverConnection) ||
27c841f6 4864 pinning.serverConnection->fd != pinServer->fd)
89b1d7a2 4865 pinNewConnection(pinServer, request, aPeer, auth);
d67acb4e 4866
f8e4867b
AR
4867 if (monitor)
4868 startPinnedConnectionMonitoring();
89b1d7a2 4869}
9e008dda 4870
89b1d7a2
AR
4871void
4872ConnStateData::pinNewConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth)
4873{
4874 unpinConnection(true); // closes pinned connection, if any, and resets fields
9e008dda 4875
73c36fd9 4876 pinning.serverConnection = pinServer;
d7ce0bcd 4877
85563fd9
AR
4878 debugs(33, 3, HERE << pinning.serverConnection);
4879
89b1d7a2
AR
4880 Must(pinning.serverConnection != NULL);
4881
d7ce0bcd
AR
4882 // when pinning an SSL bumped connection, the request may be NULL
4883 const char *pinnedHost = "[unknown]";
4884 if (request) {
4885 pinning.host = xstrdup(request->GetHost());
4886 pinning.port = request->port;
4887 pinnedHost = pinning.host;
4888 } else {
4dd643d5 4889 pinning.port = pinServer->remote.port();
d7ce0bcd 4890 }
d67acb4e 4891 pinning.pinned = true;
8bcf08e0
FC
4892 if (aPeer)
4893 pinning.peer = cbdataReference(aPeer);
d67acb4e 4894 pinning.auth = auth;
e3a4aecc 4895 char stmp[MAX_IPSTRLEN];
89b1d7a2 4896 char desc[FD_DESC_SZ];
e3a4aecc 4897 snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)",
d7ce0bcd 4898 (auth || !aPeer) ? pinnedHost : aPeer->name,
4dd643d5 4899 clientConnection->remote.toUrl(stmp,MAX_IPSTRLEN),
d7ce0bcd 4900 clientConnection->fd);
73c36fd9 4901 fd_note(pinning.serverConnection->fd, desc);
9e008dda 4902
d67acb4e 4903 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
4299f876 4904 pinning.closeHandler = JobCallback(33, 5,
4cb2536f 4905 Dialer, this, ConnStateData::clientPinnedConnectionClosed);
85563fd9
AR
4906 // remember the pinned connection so that cb does not unpin a fresher one
4907 typedef CommCloseCbParams Params;
4908 Params &params = GetCommParams<Params>(pinning.closeHandler);
4909 params.conn = pinning.serverConnection;
73c36fd9 4910 comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
7ac40923
AR
4911}
4912
e7ce227f
AR
4913/// [re]start monitoring pinned connection for peer closures so that we can
4914/// propagate them to an _idle_ client pinned to that peer
7ac40923
AR
4915void
4916ConnStateData::startPinnedConnectionMonitoring()
4917{
4918 if (pinning.readHandler != NULL)
4919 return; // already monitoring
4920
4921 typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer;
4922 pinning.readHandler = JobCallback(33, 3,
4923 Dialer, this, ConnStateData::clientPinnedConnectionRead);
7e66d5e2 4924 Comm::Read(pinning.serverConnection, pinning.readHandler);
7ac40923
AR
4925}
4926
4927void
4928ConnStateData::stopPinnedConnectionMonitoring()
4929{
4930 if (pinning.readHandler != NULL) {
7e66d5e2 4931 Comm::ReadCancel(pinning.serverConnection->fd, pinning.readHandler);
7ac40923
AR
4932 pinning.readHandler = NULL;
4933 }
4934}
4935
4936/// Our read handler called by Comm when the server either closes an idle pinned connection or
4937/// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4938void
4939ConnStateData::clientPinnedConnectionRead(const CommIoCbParams &io)
4940{
4941 pinning.readHandler = NULL; // Comm unregisters handlers before calling
4942
c8407295 4943 if (io.flag == Comm::ERR_CLOSING)
7ac40923
AR
4944 return; // close handler will clean up
4945
4946 // We could use getConcurrentRequestCount(), but this may be faster.
4947 const bool clientIsIdle = !getCurrentContext();
4948
4949 debugs(33, 3, "idle pinned " << pinning.serverConnection << " read " <<
4950 io.size << (clientIsIdle ? " with idle client" : ""));
4951
4952 assert(pinning.serverConnection == io.conn);
4953 pinning.serverConnection->close();
4954
4955 // If we are still sending data to the client, do not close now. When we are done sending,
4956 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4957 // However, if we are idle, then we must close to inform the idle client and minimize races.
4958 if (clientIsIdle && clientConnection != NULL)
4959 clientConnection->close();
d67acb4e
AJ
4960}
4961
e3a4aecc 4962const Comm::ConnectionPointer
a3c6762c 4963ConnStateData::validatePinnedConnection(HttpRequest *request, const CachePeer *aPeer)
d67acb4e 4964{
85563fd9
AR
4965 debugs(33, 7, HERE << pinning.serverConnection);
4966
d67acb4e 4967 bool valid = true;
73c36fd9 4968 if (!Comm::IsConnOpen(pinning.serverConnection))
e3a4aecc 4969 valid = false;
6de3828e 4970 else if (pinning.auth && pinning.host && request && strcasecmp(pinning.host, request->GetHost()) != 0)
9e008dda 4971 valid = false;
6de3828e 4972 else if (request && pinning.port != request->port)
9e008dda 4973 valid = false;
6de3828e 4974 else if (pinning.peer && !cbdataReferenceValid(pinning.peer))
9e008dda 4975 valid = false;
6de3828e 4976 else if (aPeer != pinning.peer)
9e008dda 4977 valid = false;
d67acb4e 4978
9e008dda 4979 if (!valid) {
b1cf2350 4980 /* The pinning info is not safe, remove any pinning info */
89b1d7a2 4981 unpinConnection(true);
d67acb4e
AJ
4982 }
4983
73c36fd9 4984 return pinning.serverConnection;
d67acb4e
AJ
4985}
4986
89b1d7a2
AR
4987Comm::ConnectionPointer
4988ConnStateData::borrowPinnedConnection(HttpRequest *request, const CachePeer *aPeer)
4989{
4990 debugs(33, 7, pinning.serverConnection);
4991 if (validatePinnedConnection(request, aPeer) != NULL)
f8e4867b 4992 stopPinnedConnectionMonitoring();
89b1d7a2
AR
4993
4994 return pinning.serverConnection; // closed if validation failed
4995}
4996
b1cf2350 4997void
89b1d7a2 4998ConnStateData::unpinConnection(const bool andClose)
d67acb4e 4999{
85563fd9
AR
5000 debugs(33, 3, HERE << pinning.serverConnection);
5001
9e008dda
AJ
5002 if (pinning.peer)
5003 cbdataReferenceDone(pinning.peer);
d67acb4e 5004
d7ce0bcd 5005 if (Comm::IsConnOpen(pinning.serverConnection)) {
87f237a9
A
5006 if (pinning.closeHandler != NULL) {
5007 comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
5008 pinning.closeHandler = NULL;
5009 }
89b1d7a2 5010
f8e4867b 5011 stopPinnedConnectionMonitoring();
89b1d7a2
AR
5012
5013 // close the server side socket if requested
5014 if (andClose)
5015 pinning.serverConnection->close();
5016 pinning.serverConnection = NULL;
d67acb4e 5017 }
d7ce0bcd 5018
d67acb4e 5019 safe_free(pinning.host);
e3a4aecc 5020
693cb033
CT
5021 pinning.zeroReply = false;
5022
e3a4aecc
AJ
5023 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
5024 * connection has gone away */
d67acb4e 5025}