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