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