]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
Portability: remove short macro MB
[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
655daa06
AR
357 // remember the callback
358 cbControlMsgSent = msg.cbSuccess;
359
655daa06
AR
360 AsyncCall::Pointer call = commCbCall(33, 5, "ClientSocketContext::wroteControlMsg",
361 CommIoCbPtrFun(&WroteControlMsg, this));
655daa06 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 ?
90a8964c 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;
86c63190 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 2095 } else if (vport > 0 /* && (!vhost || no Host:) */) {
3cc0f4e7 2096 debugs(33, 5, "ACCEL VPORT REWRITE: *_port IP + vport=" << vport);
5463e4b9 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 }
e0133005 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 */
3cc0f4e7 2615 /* TODO: move HTTP-specific processing into servers/HttpServer and such */
e57c1885 2616 if ( (http_ver.major == 0 && http_ver.minor != 9) ||
af6a12ee 2617 (http_ver.major > 1) ) {
e57c1885
AJ
2618
2619 clientStreamNode *node = context->getClientReplyContext();
2620 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp));
b248c2a3 2621 conn->quitAfterError(request.getRaw());
727552f4
CT
2622 // setLogUri should called before repContext->setReplyToError
2623 setLogUri(http, http->uri, true);
e57c1885
AJ
2624 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2625 assert (repContext);
955394ce 2626 repContext->setReplyToError(ERR_UNSUP_HTTPVERSION, Http::scHttpVersionNotSupported, method, http->uri,
73c36fd9 2627 conn->clientConnection->remote, NULL, HttpParserHdrBuf(hp), NULL);
e57c1885
AJ
2628 assert(context->http->out.offset == 0);
2629 context->pullData();
e57c1885
AJ
2630 goto finish;
2631 }
2632
528b2c61 2633 /* compile headers */
2634 /* we should skip request line! */
666f514b 2635 /* XXX should actually know the damned buffer size here */
38e82382 2636 if (http_ver.major >= 1 && !request->parseHeader(HttpParserHdrBuf(hp), HttpParserHdrSz(hp))) {
47ac2ebe 2637 clientStreamNode *node = context->getClientReplyContext();
bf8fe701 2638 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp));
b248c2a3 2639 conn->quitAfterError(request.getRaw());
727552f4
CT
2640 // setLogUri should called before repContext->setReplyToError
2641 setLogUri(http, http->uri, true);
47ac2ebe 2642 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2643 assert (repContext);
955394ce 2644 repContext->setReplyToError(ERR_INVALID_REQ, Http::scBadRequest, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL);
47ac2ebe 2645 assert(context->http->out.offset == 0);
2646 context->pullData();
fc68f6b1 2647 goto finish;
47ac2ebe 2648 }
c4b7a5a9 2649
92ae4c86
AR
2650doFtpAndHttp:
2651 // Some blobs below are still HTTP-specific, but we would have to rewrite
2652 // this entire function to remove them from the FTP code path. Connection
2653 // setup and body_pipe preparation blobs are needed for FTP.
2654
40d34a62
AJ
2655 request->clientConnectionManager = conn;
2656
c4b7a5a9 2657 request->flags.accelerated = http->flags.accel;
450fe1cb 2658 request->flags.sslBumped=conn->switchedToHttps();
450fe1cb 2659 request->flags.ignoreCc = conn->port->ignore_cc;
7fb65ee4 2660 // TODO: decouple http->flags.accel from request->flags.sslBumped
450fe1cb 2661 request->flags.noDirect = (request->flags.accelerated && !request->flags.sslBumped) ?
e4a14600 2662 !conn->port->allow_direct : 0;
21512911
CT
2663#if USE_AUTH
2664 if (request->flags.sslBumped) {
cc1e110a
AJ
2665 if (conn->getAuth() != NULL)
2666 request->auth_user_request = conn->getAuth();
21512911
CT
2667 }
2668#endif
2ad20b4f
AJ
2669
2670 /** \par
2671 * If transparent or interception mode is working clone the transparent and interception flags
2672 * from the port settings to the request.
2673 */
40d34a62 2674 if (http->clientConnection != NULL) {
304a6180 2675 request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0);
0d901ef4
SH
2676 request->flags.interceptTproxy = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
2677 if (request->flags.interceptTproxy) {
2678 if (Config.accessList.spoof_client_ip) {
2679 ACLFilledChecklist *checklist = clientAclChecklistCreate(Config.accessList.spoof_client_ip, http);
2680 request->flags.spoofClientIp = (checklist->fastCheck() == ACCESS_ALLOWED);
2681 delete checklist;
2682 } else
2683 request->flags.spoofClientIp = true;
2684 } else
2685 request->flags.spoofClientIp = false;
2ad20b4f 2686 }
fc68f6b1 2687
5b4117d8 2688 if (internalCheck(request->urlpath.termedBuf())) {
4e3f4dc7
AJ
2689 if (internalHostnameIs(request->GetHost()) && request->port == getMyPort()) {
2690 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2691 ':' << request->port);
be4d35dc 2692 http->flags.internal = true;
9c175897 2693 } else if (Config.onoff.global_internal_static && internalStaticCheck(request->urlpath.termedBuf())) {
4e3f4dc7
AJ
2694 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2695 ':' << request->port << " (global_internal_static on)");
cc192b50 2696 request->SetHost(internalHostname());
f024c970 2697 request->port = getMyPort();
be4d35dc 2698 http->flags.internal = true;
4e3f4dc7
AJ
2699 } else
2700 debugs(33, 2, "internal URL found: " << request->url.getScheme() << "://" << request->GetHost() <<
2701 ':' << request->port << " (not this proxy)");
f024c970 2702 }
e72a0ec0 2703
4e3f4dc7 2704 if (http->flags.internal)
f024c970 2705 request->login[0] = '\0';
c4b7a5a9 2706
c4b7a5a9 2707 request->flags.internal = http->flags.internal;
b248c2a3 2708 setLogUri (http, urlCanonicalClean(request.getRaw()));
73c36fd9 2709 request->client_addr = conn->clientConnection->remote; // XXX: remove reuest->client_addr member.
3d674977 2710#if FOLLOW_X_FORWARDED_FOR
40d34a62
AJ
2711 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2712 // not a details about teh TCP connection itself
73c36fd9 2713 request->indirect_client_addr = conn->clientConnection->remote;
3d674977 2714#endif /* FOLLOW_X_FORWARDED_FOR */
73c36fd9 2715 request->my_addr = conn->clientConnection->local;
35fb56c9 2716 request->myportname = conn->port->name;
8ae66e43 2717 request->http_ver = http_ver;
62e76326 2718
9174ba3d
AJ
2719 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2720 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2721 request->clientConnectionManager = conn;
2722
39cb8c41
AR
2723 if (request->header.chunked()) {
2724 chunked = true;
2725 } else if (request->header.has(HDR_TRANSFER_ENCODING)) {
2726 const String te = request->header.getList(HDR_TRANSFER_ENCODING);
2727 // HTTP/1.1 requires chunking to be the last encoding if there is one
2728 unsupportedTe = te.size() && te != "identity";
2729 } // else implied identity coding
de48b288 2730
c2a7cefd 2731 mustReplyToOptions = (method == Http::METHOD_OPTIONS) &&
d916dcb8 2732 (request->header.getInt64(HDR_MAX_FORWARDS) == 0);
b248c2a3 2733 if (!urlCheckRequest(request.getRaw()) || mustReplyToOptions || unsupportedTe) {
62e76326 2734 clientStreamNode *node = context->getClientReplyContext();
b248c2a3 2735 conn->quitAfterError(request.getRaw());
0655fa4d 2736 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2737 assert (repContext);
955394ce 2738 repContext->setReplyToError(ERR_UNSUP_REQ, Http::scNotImplemented, request->method, NULL,
b248c2a3 2739 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2740 assert(context->http->out.offset == 0);
2741 context->pullData();
fc68f6b1 2742 goto finish;
c4b7a5a9 2743 }
2744
b248c2a3 2745 if (!chunked && !clientIsContentLengthValid(request.getRaw())) {
62e76326 2746 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2747 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2748 assert (repContext);
b248c2a3 2749 conn->quitAfterError(request.getRaw());
0655fa4d 2750 repContext->setReplyToError(ERR_INVALID_REQ,
955394ce 2751 Http::scLengthRequired, request->method, NULL,
b248c2a3 2752 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2753 assert(context->http->out.offset == 0);
2754 context->pullData();
fc68f6b1 2755 goto finish;
c4b7a5a9 2756 }
2757
52b601ff 2758 if (request->header.has(HDR_EXPECT)) {
655daa06
AR
2759 const String expect = request->header.getList(HDR_EXPECT);
2760 const bool supportedExpect = (expect.caseCmp("100-continue") == 0);
2761 if (!supportedExpect) {
52b601ff
AJ
2762 clientStreamNode *node = context->getClientReplyContext();
2763 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2764 assert (repContext);
b248c2a3 2765 conn->quitAfterError(request.getRaw());
955394ce 2766 repContext->setReplyToError(ERR_INVALID_REQ, Http::scExpectationFailed, request->method, http->uri,
b248c2a3 2767 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
52b601ff
AJ
2768 assert(context->http->out.offset == 0);
2769 context->pullData();
2770 goto finish;
2771 }
2772 }
2773
92ae4c86 2774 if (!isFtp) {
434a79b0
DK
2775 http->request = request.getRaw();
2776 HTTPMSGLOCK(http->request);
2777 }
62e76326 2778
92ae4c86 2779 clientSetKeepaliveFlag(http);
f35961af 2780 // Let tunneling code be fully responsible for CONNECT requests
c2a7cefd 2781 if (http->request->method == Http::METHOD_CONNECT) {
b66e0e86 2782 context->mayUseConnection(true);
f35961af 2783 conn->flags.readMore = false;
6c420975
AJ
2784
2785 // consume header early so that tunnel gets just the body
2786 connNoteUseOfBuffer(conn, http->req_sz);
2787 notedUseOfBuffer = true;
f35961af 2788 }
fc68f6b1 2789
cb4f4424 2790#if USE_OPENSSL
8eb0a7ee 2791 if (conn->switchedToHttps() && conn->serveDelayedError(context))
061bbdec 2792 goto finish;
061bbdec
CT
2793#endif
2794
b66e0e86 2795 /* Do we expect a request-body? */
39cb8c41
AR
2796 expectBody = chunked || request->content_length > 0;
2797 if (!context->mayUseConnection() && expectBody) {
2798 request->body_pipe = conn->expectRequestBody(
de48b288 2799 chunked ? -1 : request->content_length);
5f8252d2 2800
e7ce227f 2801 if (!isFtp) {
c8059ea9
DK
2802 // consume header early so that body pipe gets just the body
2803 connNoteUseOfBuffer(conn, http->req_sz);
2804 notedUseOfBuffer = true;
2805 }
5f8252d2 2806
62e76326 2807 /* Is it too large? */
39cb8c41 2808 if (!chunked && // if chunked, we will check as we accumulate
de48b288 2809 clientIsRequestBodyTooLargeForPolicy(request->content_length)) {
62e76326 2810 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2811 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2812 assert (repContext);
b248c2a3 2813 conn->quitAfterError(request.getRaw());
0655fa4d 2814 repContext->setReplyToError(ERR_TOO_BIG,
f11c8e2f 2815 Http::scPayloadTooLarge, Http::METHOD_NONE, NULL,
73c36fd9 2816 conn->clientConnection->remote, http->request, NULL, NULL);
62e76326 2817 assert(context->http->out.offset == 0);
2818 context->pullData();
5f8252d2 2819 goto finish;
62e76326 2820 }
2821
92ae4c86 2822 if (!isFtp) {
a5d444a5
DK
2823 // We may stop producing, comm_close, and/or call setReplyToError()
2824 // below, so quit on errors to avoid http->doCallouts()
2825 if (!conn->handleRequestBodyData())
2826 goto finish;
39cb8c41 2827
a5d444a5 2828 if (!request->body_pipe->productionEnded()) {
e7ce227f 2829 debugs(33, 5, "need more request body");
a5d444a5
DK
2830 context->mayUseConnection(true);
2831 assert(conn->flags.readMore);
2832 }
f35961af 2833 }
c4b7a5a9 2834 }
2835
de31d06f 2836 http->calloutContext = new ClientRequestContext(http);
2837
2838 http->doCallouts();
9e008dda 2839
4c29340e 2840finish:
5f8252d2 2841 if (!notedUseOfBuffer)
1cf238db 2842 connNoteUseOfBuffer(conn, http->req_sz);
52c2c8a8 2843
2844 /*
2845 * DPW 2007-05-18
2846 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2847 * to here because calling comm_reset_close() causes http to
2848 * be freed and the above connNoteUseOfBuffer() would hit an
2849 * assertion, not to mention that we were accessing freed memory.
2850 */
b248c2a3 2851 if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
73c36fd9 2852 debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection);
f35961af 2853 conn->flags.readMore = false;
73c36fd9 2854 comm_reset_close(conn->clientConnection);
52c2c8a8 2855 }
c4b7a5a9 2856}
2857
2858static void
1cf238db 2859connStripBufferWhitespace (ConnStateData * conn)
c4b7a5a9 2860{
e7287625
AJ
2861 // XXX: kill this whole function.
2862 while (!conn->in.buf.isEmpty() && xisspace(conn->in.buf.at(0))) {
2863 conn->in.buf.consume(1);
c4b7a5a9 2864 }
2865}
2866
92ae4c86
AR
2867int
2868ConnStateData::pipelinePrefetchMax() const
2869{
2870 return Config.pipeline_max_prefetch;
2871}
2872
079a8480
AJ
2873/**
2874 * Limit the number of concurrent requests.
2875 * \return true when there are available position(s) in the pipeline queue for another request.
2876 * \return false when the pipeline queue is full or disabled.
2877 */
2878bool
2879ConnStateData::concurrentRequestQueueFilled() const
c4b7a5a9 2880{
079a8480 2881 const int existingRequestCount = getConcurrentRequestCount();
62e76326 2882
079a8480
AJ
2883 // default to the configured pipeline size.
2884 // add 1 because the head of pipeline is counted in concurrent requests and not prefetch queue
92ae4c86 2885 const int concurrentRequestLimit = pipelinePrefetchMax() + 1;
62e76326 2886
079a8480
AJ
2887 // when queue filled already we cant add more.
2888 if (existingRequestCount >= concurrentRequestLimit) {
2889 debugs(33, 3, clientConnection << " max concurrent requests reached (" << concurrentRequestLimit << ")");
2890 debugs(33, 5, clientConnection << " deferring new request until one is done");
2891 return true;
c4b7a5a9 2892 }
62e76326 2893
079a8480 2894 return false;
c4b7a5a9 2895}
2896
63be0a78 2897/**
f900210a 2898 * Attempt to parse one or more requests from the input buffer.
2899 * If a request is successfully parsed, even if the next request
2900 * is only partially parsed, it will return TRUE.
f900210a 2901 */
4959e21e 2902bool
f35961af 2903ConnStateData::clientParseRequests()
f900210a 2904{
f900210a 2905 bool parsed_req = false;
2906
1b76e6c1 2907 debugs(33, 5, HERE << clientConnection << ": attempting to parse");
f900210a 2908
39cb8c41 2909 // Loop while we have read bytes that are not needed for producing the body
f35961af 2910 // On errors, bodyPipe may become nil, but readMore will be cleared
e7287625 2911 while (!in.buf.isEmpty() && !bodyPipe && flags.readMore) {
4959e21e 2912 connStripBufferWhitespace(this);
f900210a 2913
fc68f6b1 2914 /* Don't try to parse if the buffer is empty */
e7287625 2915 if (in.buf.isEmpty())
fc68f6b1 2916 break;
4681057e 2917
079a8480
AJ
2918 /* Limit the number of concurrent requests */
2919 if (concurrentRequestQueueFilled())
f900210a 2920 break;
f900210a 2921
526ed14e 2922 Http::ProtocolVersion http_ver;
92ae4c86 2923 ClientSocketContext *context = parseOneRequest(http_ver);
f900210a 2924
2925 /* partial or incomplete request */
2926 if (!context) {
39cb8c41
AR
2927 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2928 // (which becomes context) but checkHeaderLimits cannot?
4959e21e 2929 checkHeaderLimits();
f900210a 2930 break;
2931 }
2932
2933 /* status -1 or 1 */
2934 if (context) {
1b76e6c1 2935 debugs(33, 5, HERE << clientConnection << ": parsed a request");
8d77a37c 2936 AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout",
dc49061a 2937 CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http));
1b76e6c1 2938 commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall);
f900210a 2939
92ae4c86 2940 processParsedRequest(context, http_ver);
f900210a 2941
4959e21e 2942 parsed_req = true; // XXX: do we really need to parse everything right NOW ?
f900210a 2943
2944 if (context->mayUseConnection()) {
f35961af 2945 debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection");
f900210a 2946 break;
2947 }
f900210a 2948 }
39cb8c41 2949 }
fc68f6b1 2950
a5baffba 2951 /* XXX where to 'finish' the parsing pass? */
f900210a 2952 return parsed_req;
2953}
2954
1cf238db 2955void
2956ConnStateData::clientReadRequest(const CommIoCbParams &io)
c4b7a5a9 2957{
7e66d5e2 2958 debugs(33,5, io.conn);
f84dd7eb
AR
2959 Must(reading());
2960 reader = NULL;
c4b7a5a9 2961
c8407295
AJ
2962 /* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
2963 if (io.flag == Comm::ERR_CLOSING) {
7e66d5e2 2964 debugs(33,5, io.conn << " closing Bailout.");
c4b7a5a9 2965 return;
2966 }
62e76326 2967
73c36fd9
AJ
2968 assert(Comm::IsConnOpen(clientConnection));
2969 assert(io.conn->fd == clientConnection->fd);
5c336a3b 2970
44db45e8 2971 /*
7e66d5e2
AJ
2972 * Don't reset the timeout value here. The value should be
2973 * counting Config.Timeout.request and applies to the request
2974 * as a whole, not individual read() calls.
2975 * Plus, it breaks our lame *HalfClosed() detection
44db45e8 2976 */
7e66d5e2
AJ
2977
2978 CommIoCbParams rd(this); // will be expanded with ReadNow results
2979 rd.conn = io.conn;
470b1598 2980 switch (Comm::ReadNow(rd, in.buf)) {
c8407295 2981 case Comm::INPROGRESS:
7e66d5e2
AJ
2982 if (in.buf.isEmpty())
2983 debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno));
2984 readSomeData();
62e76326 2985 return;
c4b7a5a9 2986
c8407295 2987 case Comm::OK:
7e66d5e2
AJ
2988 kb_incr(&(statCounter.client_http.kbytes_in), rd.size);
2989 // may comm_close or setReplyToError
2990 if (!handleReadData())
2991 return;
3b299123 2992
7e66d5e2
AJ
2993 /* Continue to process previously read data */
2994 break;
a31a78fb 2995
c8407295 2996 case Comm::ENDFILE: // close detected by 0-byte read
7e66d5e2 2997 debugs(33, 5, io.conn << " closed?");
62e76326 2998
7e66d5e2
AJ
2999 if (connFinishedWithConn(rd.size)) {
3000 clientConnection->close();
3001 return;
3002 }
62e76326 3003
7e66d5e2
AJ
3004 /* It might be half-closed, we can't tell */
3005 fd_table[io.conn->fd].flags.socket_eof = true;
3006 commMarkHalfClosed(io.conn->fd);
3007 fd_note(io.conn->fd, "half-closed");
62e76326 3008
7e66d5e2
AJ
3009 /* There is one more close check at the end, to detect aborted
3010 * (partial) requests. At this point we can't tell if the request
3011 * is partial.
3012 */
a46d2c0e 3013
7e66d5e2
AJ
3014 /* Continue to process previously read data */
3015 break;
62e76326 3016
4ee57cbe 3017 // case Comm::COMM_ERROR:
7e66d5e2
AJ
3018 default: // no other flags should ever occur
3019 debugs(33, 2, io.conn << ": got flag " << rd.flag << "; " << xstrerr(rd.xerrno));
3020 notifyAllContexts(rd.xerrno);
3021 io.conn->close();
3022 return;
c4b7a5a9 3023 }
3024
94439e4e 3025 /* Process next request */
1cf238db 3026 if (getConcurrentRequestCount() == 0)
5c336a3b 3027 fd_note(io.fd, "Reading next request");
c8be6d7b 3028
f35961af 3029 if (!clientParseRequests()) {
9e008dda
AJ
3030 if (!isOpen())
3031 return;
f900210a 3032 /*
3033 * If the client here is half closed and we failed
3034 * to parse a request, close the connection.
3035 * The above check with connFinishedWithConn() only
3036 * succeeds _if_ the buffer is empty which it won't
3037 * be if we have an incomplete request.
6e1d409c 3038 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
f900210a 3039 */
5c336a3b 3040 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io.fd)) {
be364179 3041 debugs(33, 5, HERE << io.conn << ": half-closed connection, no completed request parsed, connection closing.");
73c36fd9 3042 clientConnection->close();
ee6f0213 3043 return;
62e76326 3044 }
f900210a 3045 }
ee6f0213 3046
1cf238db 3047 if (!isOpen())
2e216b1d 3048 return;
3049
f35961af 3050 clientAfterReadingRequests();
94439e4e 3051}
3052
63be0a78 3053/**
3054 * called when new request data has been read from the socket
39cb8c41
AR
3055 *
3056 * \retval false called comm_close or setReplyToError (the caller should bail)
3057 * \retval true we did not call comm_close or setReplyToError
63be0a78 3058 */
39cb8c41 3059bool
7e66d5e2 3060ConnStateData::handleReadData()
94439e4e 3061{
5f8252d2 3062 // if we are reading a body, stuff data into the body pipe
3063 if (bodyPipe != NULL)
39cb8c41
AR
3064 return handleRequestBodyData();
3065 return true;
94439e4e 3066}
3067
63be0a78 3068/**
bb790702 3069 * called when new request body data has been buffered in in.buf
63be0a78 3070 * may close the connection if we were closing and piped everything out
39cb8c41
AR
3071 *
3072 * \retval false called comm_close or setReplyToError (the caller should bail)
3073 * \retval true we did not call comm_close or setReplyToError
63be0a78 3074 */
39cb8c41 3075bool
5f8252d2 3076ConnStateData::handleRequestBodyData()
94439e4e 3077{
5f8252d2 3078 assert(bodyPipe != NULL);
3079
e1381638 3080 size_t putSize = 0;
3ff65596 3081
39cb8c41
AR
3082 if (in.bodyParser) { // chunked encoding
3083 if (const err_type error = handleChunkedRequestBody(putSize)) {
3084 abortChunkedRequestBody(error);
3085 return false;
3ff65596 3086 }
39cb8c41 3087 } else { // identity encoding
73c36fd9 3088 debugs(33,5, HERE << "handling plain request body for " << clientConnection);
e7287625 3089 putSize = bodyPipe->putMoreData(in.buf.c_str(), in.buf.length());
3ff65596
AR
3090 if (!bodyPipe->mayNeedMoreData()) {
3091 // BodyPipe will clear us automagically when we produced everything
3092 bodyPipe = NULL;
3093 }
3094 }
3095
3096 if (putSize > 0)
3097 connNoteUseOfBuffer(this, putSize);
5f8252d2 3098
3ff65596 3099 if (!bodyPipe) {
73c36fd9 3100 debugs(33,5, HERE << "produced entire request body for " << clientConnection);
62e76326 3101
cf6eb29e 3102 if (const char *reason = stoppedSending()) {
5f8252d2 3103 /* we've finished reading like good clients,
3104 * now do the close that initiateClose initiated.
5f8252d2 3105 */
cf6eb29e 3106 debugs(33, 3, HERE << "closing for earlier sending error: " << reason);
73c36fd9 3107 clientConnection->close();
39cb8c41
AR
3108 return false;
3109 }
3110 }
3111
3112 return true;
3113}
3114
3115/// parses available chunked encoded body bytes, checks size, returns errors
3116err_type
3117ConnStateData::handleChunkedRequestBody(size_t &putSize)
3118{
e7287625 3119 debugs(33, 7, "chunked from " << clientConnection << ": " << in.buf.length());
39cb8c41
AR
3120
3121 try { // the parser will throw on errors
3122
e7287625 3123 if (in.buf.isEmpty()) // nothing to do
39cb8c41
AR
3124 return ERR_NONE;
3125
3126 MemBuf raw; // ChunkedCodingParser only works with MemBufs
3127 // add one because MemBuf will assert if it cannot 0-terminate
e7287625
AJ
3128 raw.init(in.buf.length(), in.buf.length()+1);
3129 raw.append(in.buf.c_str(), in.buf.length());
39cb8c41
AR
3130
3131 const mb_size_t wasContentSize = raw.contentSize();
3132 BodyPipeCheckout bpc(*bodyPipe);
3133 const bool parsed = in.bodyParser->parse(&raw, &bpc.buf);
3134 bpc.checkIn();
3135 putSize = wasContentSize - raw.contentSize();
3136
3137 // dechunk then check: the size limit applies to _dechunked_ content
3138 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize()))
3139 return ERR_TOO_BIG;
3140
3141 if (parsed) {
3142 finishDechunkingRequest(true);
3143 Must(!bodyPipe);
3144 return ERR_NONE; // nil bodyPipe implies body end for the caller
5f8252d2 3145 }
39cb8c41
AR
3146
3147 // if chunk parser needs data, then the body pipe must need it too
3148 Must(!in.bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData());
3149
3150 // if parser needs more space and we can consume nothing, we will stall
3151 Must(!in.bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent());
3152 } catch (...) { // TODO: be more specific
3153 debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status());
3154 return ERR_INVALID_REQ;
94439e4e 3155 }
39cb8c41
AR
3156
3157 debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status());
3158 return ERR_NONE;
3159}
3160
3161/// quit on errors related to chunked request body handling
3162void
3163ConnStateData::abortChunkedRequestBody(const err_type error)
3164{
3165 finishDechunkingRequest(false);
3166
3167 // XXX: The code below works if we fail during initial request parsing,
3168 // but if we fail when the server-side works already, the server may send
3169 // us its response too, causing various assertions. How to prevent that?
3170#if WE_KNOW_HOW_TO_SEND_ERRORS
3171 ClientSocketContext::Pointer context = getCurrentContext();
3172 if (context != NULL && !context->http->out.offset) { // output nothing yet
3173 clientStreamNode *node = context->getClientReplyContext();
3174 clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw());
3175 assert(repContext);
955394ce 3176 const Http::StatusCode scode = (error == ERR_TOO_BIG) ?
f11c8e2f 3177 Http::scPayloadTooLarge : HTTP_BAD_REQUEST;
39cb8c41
AR
3178 repContext->setReplyToError(error, scode,
3179 repContext->http->request->method,
3180 repContext->http->uri,
a3c6762c 3181 CachePeer,
39cb8c41
AR
3182 repContext->http->request,
3183 in.buf, NULL);
3184 context->pullData();
3185 } else {
3186 // close or otherwise we may get stuck as nobody will notice the error?
73c36fd9 3187 comm_reset_close(clientConnection);
39cb8c41
AR
3188 }
3189#else
3190 debugs(33, 3, HERE << "aborting chunked request without error " << error);
73c36fd9 3191 comm_reset_close(clientConnection);
39cb8c41 3192#endif
f35961af 3193 flags.readMore = false;
5f8252d2 3194}
55e44db9 3195
5f8252d2 3196void
1cf238db 3197ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer )
5f8252d2 3198{
cf6eb29e
CT
3199 // request reader may get stuck waiting for space if nobody consumes body
3200 if (bodyPipe != NULL)
3201 bodyPipe->enableAutoConsumption();
3202
92ae4c86 3203 // kids extend
94439e4e 3204}
3205
63be0a78 3206/** general lifetime handler for HTTP requests */
1cf238db 3207void
3208ConnStateData::requestTimeout(const CommTimeoutCbParams &io)
7a2f978b 3209{
af57a2e3 3210 /*
62e76326 3211 * Just close the connection to not confuse browsers
6177a89f
HN
3212 * using persistent connections. Some browsers open
3213 * a connection and then do not use it until much
62e76326 3214 * later (presumeably because the request triggering
3215 * the open has already been completed on another
3216 * connection)
3217 */
1cf238db 3218 debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired.");
8d77a37c 3219 io.conn->close();
7a2f978b 3220}
3221
b5c39993 3222static void
8d77a37c 3223clientLifetimeTimeout(const CommTimeoutCbParams &io)
b5c39993 3224{
8d77a37c 3225 ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data);
cb61ec47
AJ
3226 debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout");
3227 debugs(33, DBG_IMPORTANT, "\t" << http->uri);
41ebd397 3228 http->al->http.timedout = true;
8d77a37c
AJ
3229 if (Comm::IsConnOpen(io.conn))
3230 io.conn->close();
b5c39993 3231}
3232
94bfd31f 3233ConnStateData::ConnStateData(const MasterXaction::Pointer &xact) :
92ae4c86 3234 AsyncJob("ConnStateData"), // kids overwrite
cb4f4424 3235#if USE_OPENSSL
94bfd31f
AJ
3236 sslBumpMode(Ssl::bumpEnd),
3237 switchedToHttps_(false),
3238 sslServerBump(NULL),
3239#endif
3240 stoppedSending_(NULL),
3241 stoppedReceiving_(NULL)
c8be6d7b 3242{
94bfd31f
AJ
3243 pinning.host = NULL;
3244 pinning.port = -1;
3245 pinning.pinned = false;
3246 pinning.auth = false;
3247 pinning.zeroReply = false;
3248 pinning.peer = NULL;
3249
3250 // store the details required for creating more MasterXaction objects as new requests come in
3251 clientConnection = xact->tcpClient;
fa720bfb 3252 port = xact->squidPort;
94bfd31f
AJ
3253 log_addr = xact->tcpClient->remote;
3254 log_addr.applyMask(Config.Addrs.client_netmask);
2ad20b4f 3255
92ae4c86
AR
3256 flags.readMore = true; // kids may overwrite
3257}
3258
3259void
3260ConnStateData::start()
3261{
3262 BodyProducer::start();
3263 HttpControlMsgSink::start();
3264
50ae17d6
AJ
3265 // ensure a buffer is present for this connection
3266 in.maybeMakeSpaceAvailable();
62e76326 3267
5529ca8a 3268 if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF &&
94bfd31f 3269 (transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) {
5529ca8a 3270#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3271 int i = IP_PMTUDISC_DONT;
94bfd31f
AJ
3272 if (setsockopt(clientConnection->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof(i)) < 0)
3273 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << clientConnection << " : " << xstrerror());
5529ca8a 3274#else
9bb67276 3275 static bool reported = false;
5529ca8a 3276
3277 if (!reported) {
9bb67276
AJ
3278 debugs(33, DBG_IMPORTANT, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3279 reported = true;
5529ca8a 3280 }
89aec9b6
AJ
3281#endif
3282 }
5529ca8a 3283
89aec9b6 3284 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
94bfd31f
AJ
3285 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, this, ConnStateData::connStateClosed);
3286 comm_add_close_handler(clientConnection->fd, call);
5529ca8a 3287
89aec9b6 3288 if (Config.onoff.log_fqdn)
94bfd31f 3289 fqdncache_gethostbyaddr(clientConnection->remote, FQDN_LOOKUP_IF_MISS);
89aec9b6
AJ
3290
3291#if USE_IDENT
3292 if (Ident::TheConfig.identLookup) {
3293 ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL);
92ae4c86
AR
3294 identChecklist.src_addr = clientConnection->remote;
3295 identChecklist.my_addr = clientConnection->local;
2efeb0b7 3296 if (identChecklist.fastCheck() == ACCESS_ALLOWED)
92ae4c86 3297 Ident::Start(clientConnection, clientIdentDone, this);
89aec9b6 3298 }
5529ca8a 3299#endif
3300
94bfd31f 3301 clientdbEstablished(clientConnection->remote, 1);
89aec9b6 3302
9a0a18de 3303#if USE_DELAY_POOLS
92ae4c86 3304 fd_table[clientConnection->fd].clientInfo = NULL;
b4cd430a 3305
f33d34a8 3306 if (Config.onoff.client_db) {
b4cd430a
CT
3307 /* it was said several times that client write limiter does not work if client_db is disabled */
3308
3309 ClientDelayPools& pools(Config.ClientDelay.pools);
2efeb0b7 3310 ACLFilledChecklist ch(NULL, NULL, NULL);
b4cd430a 3311
2efeb0b7
AJ
3312 // TODO: we check early to limit error response bandwith but we
3313 // should recheck when we can honor delay_pool_uses_indirect
3314 // TODO: we should also pass the port details for myportname here.
92ae4c86
AR
3315 ch.src_addr = clientConnection->remote;
3316 ch.my_addr = clientConnection->local;
b4cd430a 3317
95dc7ff4 3318 for (unsigned int pool = 0; pool < pools.size(); ++pool) {
b4cd430a 3319
2efeb0b7
AJ
3320 /* pools require explicit 'allow' to assign a client into them */
3321 if (pools[pool].access) {
3322 ch.accessList = pools[pool].access;
3323 allow_t answer = ch.fastCheck();
3324 if (answer == ACCESS_ALLOWED) {
3325
3326 /* request client information from db after we did all checks
3327 this will save hash lookup if client failed checks */
92ae4c86 3328 ClientInfo * cli = clientdbGetInfo(clientConnection->remote);
2efeb0b7
AJ
3329 assert(cli);
3330
3331 /* put client info in FDE */
92ae4c86 3332 fd_table[clientConnection->fd].clientInfo = cli;
2efeb0b7
AJ
3333
3334 /* setup write limiter for this request */
3335 const double burst = floor(0.5 +
3336 (pools[pool].highwatermark * Config.ClientDelay.initial)/100.0);
3337 cli->setWriteLimiter(pools[pool].rate, burst, pools[pool].highwatermark);
3338 break;
3339 } else {
3340 debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer);
3341 }
b4cd430a
CT
3342 }
3343 }
3344 }
3345#endif
92ae4c86
AR
3346
3347 // kids must extend to actually start doing something (e.g., reading)
7a2f978b 3348}
3349
e7ce227f 3350/** Handle a new connection on an HTTP socket. */
92ae4c86
AR
3351void
3352httpAccept(const CommAcceptCbParams &params)
6afea0a4
AR
3353{
3354 MasterXaction::Pointer xact = params.xaction;
3355 AnyP::PortCfgPointer s = xact->squidPort;
3356
3357 // NP: it is possible the port was reconfigured when the call or accept() was queued.
3358
3359 if (params.flag != Comm::OK) {
3360 // Its possible the call was still queued when the client disconnected
e7ce227f 3361 debugs(33, 2, s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
6afea0a4
AR
3362 return;
3363 }
3364
e7ce227f 3365 debugs(33, 4, params.conn << ": accepted");
92ae4c86 3366 fd_note(params.conn->fd, "client http connect");
6afea0a4 3367
e7ce227f 3368 if (s->tcp_keepalive.enabled)
6afea0a4 3369 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
6afea0a4 3370
e7ce227f 3371 ++incoming_sockets_accepted;
6afea0a4
AR
3372
3373 // Socket is ready, setup the connection manager to start using it
92ae4c86 3374 ConnStateData *connState = Http::NewServer(xact);
e7ce227f 3375 AsyncJob::Start(connState); // usually async-calls readSomeData()
7a2f978b 3376}
3377
cb4f4424 3378#if USE_OPENSSL
1f7c9178 3379
63be0a78 3380/** Create SSL connection structure and update fd_table */
ae7ff0b8 3381static SSL *
449f0115 3382httpsCreate(const Comm::ConnectionPointer &conn, SSL_CTX *sslContext)
ae7ff0b8 3383{
3384 SSL *ssl = SSL_new(sslContext);
3385
3386 if (!ssl) {
3387 const int ssl_error = ERR_get_error();
449f0115
AJ
3388 debugs(83, DBG_IMPORTANT, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error, NULL) );
3389 conn->close();
ae7ff0b8 3390 return NULL;
3391 }
3392
449f0115
AJ
3393 SSL_set_fd(ssl, conn->fd);
3394 fd_table[conn->fd].ssl = ssl;
3395 fd_table[conn->fd].read_method = &ssl_read_method;
3396 fd_table[conn->fd].write_method = &ssl_write_method;
ae7ff0b8 3397
449f0115
AJ
3398 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn);
3399 fd_note(conn->fd, "client https start");
ae7ff0b8 3400
3401 return ssl;
3402}
3403
63be0a78 3404/** negotiate an SSL connection */
1f7c9178 3405static void
3406clientNegotiateSSL(int fd, void *data)
3407{
e6ccf245 3408 ConnStateData *conn = (ConnStateData *)data;
1f7c9178 3409 X509 *client_cert;
a7ad6e4e 3410 SSL *ssl = fd_table[fd].ssl;
1f7c9178 3411 int ret;
3412
a7ad6e4e 3413 if ((ret = SSL_accept(ssl)) <= 0) {
62e76326 3414 int ssl_error = SSL_get_error(ssl, ret);
3415
3416 switch (ssl_error) {
3417
3418 case SSL_ERROR_WANT_READ:
d841c88d 3419 Comm::SetSelect(fd, COMM_SELECT_READ, clientNegotiateSSL, conn, 0);
62e76326 3420 return;
3421
3422 case SSL_ERROR_WANT_WRITE:
d841c88d 3423 Comm::SetSelect(fd, COMM_SELECT_WRITE, clientNegotiateSSL, conn, 0);
62e76326 3424 return;
3425
6de9e64b 3426 case SSL_ERROR_SYSCALL:
3427
3428 if (ret == 0) {
bf8fe701 3429 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Aborted by client");
6de9e64b 3430 comm_close(fd);
3431 return;
3432 } else {
3433 int hard = 1;
3434
3435 if (errno == ECONNRESET)
3436 hard = 0;
3437
9e008dda 3438 debugs(83, hard ? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
bf8fe701 3439 fd << ": " << strerror(errno) << " (" << errno << ")");
6de9e64b 3440
3441 comm_close(fd);
3442
3443 return;
3444 }
3445
3446 case SSL_ERROR_ZERO_RETURN:
e0236918 3447 debugs(83, DBG_IMPORTANT, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Closed by client");
6de9e64b 3448 comm_close(fd);
3449 return;
3450
62e76326 3451 default:
e0236918 3452 debugs(83, DBG_IMPORTANT, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
9e008dda
AJ
3453 fd << ": " << ERR_error_string(ERR_get_error(), NULL) <<
3454 " (" << ssl_error << "/" << ret << ")");
62e76326 3455 comm_close(fd);
3456 return;
3457 }
3458
3459 /* NOTREACHED */
1f7c9178 3460 }
62e76326 3461
6de9e64b 3462 if (SSL_session_reused(ssl)) {
bf8fe701 3463 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl) <<
3464 " reused on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << ")");
6de9e64b 3465 } else {
3466 if (do_debug(83, 4)) {
3467 /* Write out the SSL session details.. actually the call below, but
3468 * OpenSSL headers do strange typecasts confusing GCC.. */
3469 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
afdd443f 3470#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
9f3de01a 3471 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 3472
0fd2205b 3473#elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2930f303 3474
0fd2205b 3475 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3476 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3477 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3478 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3479 * Because there are two possible usable cast, if you get an error here, try the other
3480 * commented line. */
3481
3482 PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL);
3483 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2930f303 3484
0e33d58c 3485#else
3486
bf8fe701 3487 debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
0fd2205b 3488
0e33d58c 3489#endif
6de9e64b 3490 /* Note: This does not automatically fflush the log file.. */
3491 }
3492
bf8fe701 3493 debugs(83, 2, "clientNegotiateSSL: New session " <<
3494 SSL_get_session(ssl) << " on FD " << fd << " (" <<
3495 fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port <<
3496 ")");
6de9e64b 3497 }
3498
bf8fe701 3499 debugs(83, 3, "clientNegotiateSSL: FD " << fd << " negotiated cipher " <<
3500 SSL_get_cipher(ssl));
1f7c9178 3501
6de9e64b 3502 client_cert = SSL_get_peer_certificate(ssl);
62e76326 3503
1f7c9178 3504 if (client_cert != NULL) {
bf8fe701 3505 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3506 " client certificate: subject: " <<
3507 X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0));
3508
3509 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3510 " client certificate: issuer: " <<
3511 X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0));
1f7c9178 3512
62e76326 3513 X509_free(client_cert);
1f7c9178 3514 } else {
bf8fe701 3515 debugs(83, 5, "clientNegotiateSSL: FD " << fd <<
3516 " has no certificate.");
1f7c9178 3517 }
3518
a46d2c0e 3519 conn->readSomeData();
1f7c9178 3520}
3521
379e8c1c 3522/**
ab2e0682
CT
3523 * If SSL_CTX is given, starts reading the SSL handshake.
3524 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
379e8c1c
AR
3525 */
3526static void
caf3666d 3527httpsEstablish(ConnStateData *connState, SSL_CTX *sslContext, Ssl::BumpMode bumpMode)
379e8c1c
AR
3528{
3529 SSL *ssl = NULL;
3530 assert(connState);
3531 const Comm::ConnectionPointer &details = connState->clientConnection;
3532
3533 if (sslContext && !(ssl = httpsCreate(details, sslContext)))
3534 return;
3535
7a957a93
AR
3536 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3537 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
87f237a9 3538 connState, ConnStateData::requestTimeout);
379e8c1c
AR
3539 commSetConnTimeout(details, Config.Timeout.request, timeoutCall);
3540
87f237a9 3541 if (ssl)
379e8c1c
AR
3542 Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0);
3543 else {
3544 char buf[MAX_IPSTRLEN];
caf3666d 3545 assert(bumpMode != Ssl::bumpNone && bumpMode != Ssl::bumpEnd);
0d901ef4 3546 HttpRequest::Pointer fakeRequest(new HttpRequest);
4dd643d5
AJ
3547 fakeRequest->SetHost(details->local.toStr(buf, sizeof(buf)));
3548 fakeRequest->port = details->local.port();
65ba7f04
CT
3549 fakeRequest->clientConnectionManager = connState;
3550 fakeRequest->client_addr = connState->clientConnection->remote;
3551#if FOLLOW_X_FORWARDED_FOR
3552 fakeRequest->indirect_client_addr = connState->clientConnection->remote;
3553#endif
3554 fakeRequest->my_addr = connState->clientConnection->local;
0d901ef4 3555 fakeRequest->flags.interceptTproxy = ((connState->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
6df4ecae 3556 fakeRequest->flags.intercepted = ((connState->clientConnection->flags & COMM_INTERCEPTION) != 0);
0d901ef4
SH
3557 fakeRequest->myportname = connState->port->name;
3558 if (fakeRequest->flags.interceptTproxy) {
3559 if (Config.accessList.spoof_client_ip) {
3560 ACLFilledChecklist checklist(Config.accessList.spoof_client_ip, fakeRequest.getRaw(), NULL);
3561 fakeRequest->flags.spoofClientIp = (checklist.fastCheck() == ACCESS_ALLOWED);
3562 } else
3563 fakeRequest->flags.spoofClientIp = true;
3564 } else
3565 fakeRequest->flags.spoofClientIp = false;
379e8c1c 3566 debugs(33, 4, HERE << details << " try to generate a Dynamic SSL CTX");
0d901ef4 3567 connState->switchToHttps(fakeRequest.getRaw(), bumpMode);
379e8c1c
AR
3568 }
3569}
3570
3571/**
87f237a9 3572 * A callback function to use with the ACLFilledChecklist callback.
94bfd31f 3573 * In the case of ACCESS_ALLOWED answer initializes a bumped SSL connection,
7a957a93 3574 * else reverts the connection to tunnel mode.
379e8c1c
AR
3575 */
3576static void
3577httpsSslBumpAccessCheckDone(allow_t answer, void *data)
3578{
3579 ConnStateData *connState = (ConnStateData *) data;
3580
7a957a93 3581 // if the connection is closed or closing, just return.
379e8c1c
AR
3582 if (!connState->isOpen())
3583 return;
3584
7a957a93 3585 // Require both a match and a positive bump mode to work around exceptional
caf3666d
AR
3586 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3587 if (answer == ACCESS_ALLOWED && answer.kind != Ssl::bumpNone) {
08097970
AR
3588 debugs(33, 2, HERE << "sslBump needed for " << connState->clientConnection);
3589 connState->sslBumpMode = static_cast<Ssl::BumpMode>(answer.kind);
caf3666d 3590 httpsEstablish(connState, NULL, (Ssl::BumpMode)answer.kind);
379e8c1c 3591 } else {
08097970
AR
3592 debugs(33, 2, HERE << "sslBump not needed for " << connState->clientConnection);
3593 connState->sslBumpMode = Ssl::bumpNone;
379e8c1c 3594
08097970 3595 // fake a CONNECT request to force connState to tunnel
379e8c1c 3596 static char ip[MAX_IPSTRLEN];
4dd643d5 3597 connState->clientConnection->local.toUrl(ip, sizeof(ip));
bcf9fd86 3598 // Pre-pend this fake request to the TLS bits already in the buffer
a55cc69e
CT
3599 SBuf retStr;
3600 retStr.append("CONNECT ").append(ip).append(" HTTP/1.1\r\nHost: ").append(ip).append("\r\n\r\n");
bcf9fd86 3601 connState->in.buf = retStr.append(connState->in.buf);
7e66d5e2 3602 bool ret = connState->handleReadData();
379e8c1c
AR
3603 if (ret)
3604 ret = connState->clientParseRequests();
73042f2e
AJ
3605
3606 if (!ret) {
379e8c1c
AR
3607 debugs(33, 2, HERE << "Failed to start fake CONNECT request for ssl bumped connection: " << connState->clientConnection);
3608 connState->clientConnection->close();
3609 }
3610 }
3611}
3612
63be0a78 3613/** handle a new HTTPS connection */
1f7c9178 3614static void
449f0115 3615httpsAccept(const CommAcceptCbParams &params)
1f7c9178 3616{
94bfd31f
AJ
3617 MasterXaction::Pointer xact = params.xaction;
3618 const AnyP::PortCfgPointer s = xact->squidPort;
3619
c0ff709f 3620 // NP: it is possible the port was reconfigured when the call or accept() was queued.
c4b7a5a9 3621
c8407295 3622 if (params.flag != Comm::OK) {
cbff89ba 3623 // Its possible the call was still queued when the client disconnected
449f0115 3624 debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
62e76326 3625 return;
c4b7a5a9 3626 }
62e76326 3627
449f0115
AJ
3628 debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation.");
3629 fd_note(params.conn->fd, "client https connect");
62e76326 3630
859741ed
AJ
3631 if (s->tcp_keepalive.enabled) {
3632 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
b2130d58 3633 }
3634
95dc7ff4 3635 ++incoming_sockets_accepted;
62e76326 3636
89aec9b6 3637 // Socket is ready, setup the connection manager to start using it
92ae4c86 3638 ConnStateData *connState = Https::NewServer(xact);
e7ce227f 3639 AsyncJob::Start(connState); // usually async-calls postHttpsAccept()
92ae4c86 3640}
62e76326 3641
92ae4c86
AR
3642void
3643ConnStateData::postHttpsAccept()
3644{
b3cb9958 3645 if (port->flags.tunnelSslBumping) {
e7ce227f 3646 debugs(33, 5, "accept transparent connection: " << clientConnection);
62e76326 3647
379e8c1c 3648 if (!Config.accessList.ssl_bump) {
b3cb9958 3649 httpsSslBumpAccessCheckDone(ACCESS_DENIED, this);
379e8c1c
AR
3650 return;
3651 }
87f237a9 3652
379e8c1c 3653 // Create a fake HTTP request for ssl_bump ACL check,
38450a50 3654 // using tproxy/intercept provided destination IP and port.
379e8c1c
AR
3655 HttpRequest *request = new HttpRequest();
3656 static char ip[MAX_IPSTRLEN];
92ae4c86
AR
3657 assert(clientConnection->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION));
3658 request->SetHost(clientConnection->local.toStr(ip, sizeof(ip)));
3659 request->port = clientConnection->local.port();
b3cb9958 3660 request->myportname = port->name;
87f237a9 3661
379e8c1c 3662 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL);
92ae4c86 3663 acl_checklist->src_addr = clientConnection->remote;
b3cb9958
AR
3664 acl_checklist->my_addr = port->s;
3665 acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, this);
379e8c1c
AR
3666 return;
3667 } else {
b3cb9958
AR
3668 SSL_CTX *sslContext = port->staticSslContext.get();
3669 httpsEstablish(this, sslContext, Ssl::bumpNone);
379e8c1c 3670 }
1f7c9178 3671}
3672
95d2589c 3673void
0272dd08 3674ConnStateData::sslCrtdHandleReplyWrapper(void *data, const HelperReply &reply)
ae7ff0b8 3675{
95d2589c
CT
3676 ConnStateData * state_data = (ConnStateData *)(data);
3677 state_data->sslCrtdHandleReply(reply);
3678}
ae7ff0b8 3679
95d2589c 3680void
0272dd08 3681ConnStateData::sslCrtdHandleReply(const HelperReply &reply)
95d2589c 3682{
5955f162
AJ
3683 if (reply.result == HelperReply::BrokenHelper) {
3684 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply);
3685 } else if (!reply.other().hasContent()) {
3686 debugs(1, DBG_IMPORTANT, HERE << "\"ssl_crtd\" helper returned <NULL> reply.");
95d2589c 3687 } else {
ff2d7d92 3688 Ssl::CrtdMessage reply_message(Ssl::CrtdMessage::REPLY);
0272dd08 3689 if (reply_message.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK) {
fb2178bb 3690 debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect");
95d2589c 3691 } else {
0272dd08 3692 if (reply.result != HelperReply::Okay) {
fb2178bb 3693 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody());
95d2589c 3694 } else {
fb2178bb 3695 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd");
86660d64 3696 SSL_CTX *ctx = Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str(), *port);
a594dbfa 3697 getSslContextDone(ctx, true);
95d2589c
CT
3698 return;
3699 }
3700 }
3701 }
3702 getSslContextDone(NULL);
3703}
ae7ff0b8 3704
06997a38 3705void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties)
fb2178bb 3706{
b38b26cb 3707 certProperties.commonName = sslCommonName.size() > 0 ? sslCommonName.termedBuf() : sslConnectHostOrIp.termedBuf();
fb2178bb
CT
3708
3709 // fake certificate adaptation requires bump-server-first mode
caf3666d
AR
3710 if (!sslServerBump) {
3711 assert(port->signingCert.get());
3712 certProperties.signWithX509.resetAndLock(port->signingCert.get());
3713 if (port->signPkey.get())
3714 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3715 certProperties.signAlgorithm = Ssl::algSignTrusted;
fb2178bb 3716 return;
caf3666d 3717 }
fb2178bb 3718
7a957a93
AR
3719 // In case of an error while connecting to the secure server, use a fake
3720 // trusted certificate, with no mimicked fields and no adaptation
3721 // algorithms. There is nothing we can mimic so we want to minimize the
3722 // number of warnings the user will have to see to get to the error page.
fd4624d7
CT
3723 assert(sslServerBump->entry);
3724 if (sslServerBump->entry->isEmpty()) {
3725 if (X509 *mimicCert = sslServerBump->serverCert.get())
59a49556
CT
3726 certProperties.mimicCert.resetAndLock(mimicCert);
3727
b248c2a3 3728 ACLFilledChecklist checklist(NULL, sslServerBump->request.getRaw(),
59a49556 3729 clientConnection != NULL ? clientConnection->rfc931 : dash_str);
7a957a93 3730 checklist.sslErrors = cbdataReference(sslServerBump->sslErrors);
59a49556
CT
3731
3732 for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) {
7a957a93 3733 // If the algorithm already set, then ignore it.
a06042fa 3734 if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) ||
87f237a9
A
3735 (ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) ||
3736 (ca->alg == Ssl::algSetValidBefore && certProperties.setValidBefore) )
a06042fa
CT
3737 continue;
3738
59a49556
CT
3739 if (ca->aclList && checklist.fastCheck(ca->aclList) == ACCESS_ALLOWED) {
3740 const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg];
3741 const char *param = ca->param;
87f237a9 3742
7a957a93
AR
3743 // For parameterless CN adaptation, use hostname from the
3744 // CONNECT request.
a06042fa 3745 if (ca->alg == Ssl::algSetCommonName) {
59a49556
CT
3746 if (!param)
3747 param = sslConnectHostOrIp.termedBuf();
3748 certProperties.commonName = param;
3749 certProperties.setCommonName = true;
87f237a9 3750 } else if (ca->alg == Ssl::algSetValidAfter)
59a49556 3751 certProperties.setValidAfter = true;
87f237a9 3752 else if (ca->alg == Ssl::algSetValidBefore)
59a49556
CT
3753 certProperties.setValidBefore = true;
3754
87f237a9 3755 debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " <<
8f9720ce 3756 alg << " param: " << (param ? param : "-"));
aebe6888 3757 }
fb2178bb 3758 }
aebe6888 3759
59a49556
CT
3760 certProperties.signAlgorithm = Ssl::algSignEnd;
3761 for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) {
3762 if (sg->aclList && checklist.fastCheck(sg->aclList) == ACCESS_ALLOWED) {
3763 certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg;
3764 break;
3765 }
aebe6888 3766 }
fd4624d7 3767 } else {// if (!sslServerBump->entry->isEmpty())
59a49556
CT
3768 // Use trusted certificate for a Squid-generated error
3769 // or the user would have to add a security exception
3770 // just to see the error page. We will close the connection
3771 // so that the trust is not extended to non-Squid content.
3772 certProperties.signAlgorithm = Ssl::algSignTrusted;
aebe6888
CT
3773 }
3774
10d914f6 3775 assert(certProperties.signAlgorithm != Ssl::algSignEnd);
aebe6888
CT
3776
3777 if (certProperties.signAlgorithm == Ssl::algSignUntrusted) {
f4e4d4d6 3778 assert(port->untrustedSigningCert.get());
95588170
CT
3779 certProperties.signWithX509.resetAndLock(port->untrustedSigningCert.get());
3780 certProperties.signWithPkey.resetAndLock(port->untrustedSignPkey.get());
87f237a9 3781 } else {
f4e4d4d6
CT
3782 assert(port->signingCert.get());
3783 certProperties.signWithX509.resetAndLock(port->signingCert.get());
aebe6888
CT
3784
3785 if (port->signPkey.get())
3786 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3787 }
3788 signAlgorithm = certProperties.signAlgorithm;
fb2178bb
CT
3789}
3790
1ce2822d 3791void
95d2589c
CT
3792ConnStateData::getSslContextStart()
3793{
129fe2a1
CT
3794 assert(areAllContextsForThisConnection());
3795 freeAllContexts();
3796 /* careful: freeAllContexts() above frees request, host, etc. */
3797
fb2178bb 3798 if (port->generateHostCertificates) {
aebe6888 3799 Ssl::CertificateProperties certProperties;
06997a38
CT
3800 buildSslCertGenerationParams(certProperties);
3801 sslBumpCertKey = certProperties.dbKey().c_str();
b38b26cb 3802 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
fb2178bb 3803
aebe6888 3804 debugs(33, 5, HERE << "Finding SSL certificate for " << sslBumpCertKey << " in cache");
9873e378 3805 Ssl::LocalContextStorage *ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
14798e73 3806 SSL_CTX * dynCtx = NULL;
9873e378 3807 Ssl::SSL_CTX_Pointer *cachedCtx = ssl_ctx_cache ? ssl_ctx_cache->get(sslBumpCertKey.termedBuf()) : NULL;
14798e73 3808 if (cachedCtx && (dynCtx = cachedCtx->get())) {
fb2178bb 3809 debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " have found in cache");
4ece76b2 3810 if (Ssl::verifySslCertificate(dynCtx, certProperties)) {
fb2178bb 3811 debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is valid");
1ce2822d
AR
3812 getSslContextDone(dynCtx);
3813 return;
95d2589c 3814 } else {
fb2178bb 3815 debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is out of date. Delete this certificate from cache");
9873e378
CT
3816 if (ssl_ctx_cache)
3817 ssl_ctx_cache->del(sslBumpCertKey.termedBuf());
95d2589c
CT
3818 }
3819 } else {
fb2178bb 3820 debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " haven't found in cache");
95d2589c
CT
3821 }
3822
b5faa519 3823#if USE_SSL_CRTD
00fc192d 3824 try {
87f237a9 3825 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd.");
ff2d7d92 3826 Ssl::CrtdMessage request_message(Ssl::CrtdMessage::REQUEST);
87f237a9
A
3827 request_message.setCode(Ssl::CrtdMessage::code_new_certificate);
3828 request_message.composeRequest(certProperties);
3829 debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str());
3830 Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this);
3831 return;
3832 } catch (const std::exception &e) {
00fc192d
AR
3833 debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " <<
3834 "request for " << certProperties.commonName <<
3835 " certificate: " << e.what() << "; will now block to " <<
3836 "generate that certificate.");
3837 // fall through to do blocking in-process generation.
3838 }
3839#endif // USE_SSL_CRTD
3840
aebe6888 3841 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName);
86660d64 3842 dynCtx = Ssl::generateSslContext(certProperties, *port);
1ce2822d
AR
3843 getSslContextDone(dynCtx, true);
3844 return;
95d2589c 3845 }
1ce2822d 3846 getSslContextDone(NULL);
95d2589c
CT
3847}
3848
1ce2822d 3849void
95d2589c
CT
3850ConnStateData::getSslContextDone(SSL_CTX * sslContext, bool isNew)
3851{
3852 // Try to add generated ssl context to storage.
3853 if (port->generateHostCertificates && isNew) {
a594dbfa 3854
a411d213
CT
3855 if (signAlgorithm == Ssl::algSignTrusted) {
3856 // Add signing certificate to the certificates chain
3857 X509 *cert = port->signingCert.get();
3858 if (SSL_CTX_add_extra_chain_cert(sslContext, cert)) {
3859 // increase the certificate lock
3860 CRYPTO_add(&(cert->references),1,CRYPTO_LOCK_X509);
3861 } else {
3862 const int ssl_error = ERR_get_error();
3863 debugs(33, DBG_IMPORTANT, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
3864 }
aebe6888 3865 Ssl::addChainToSslContext(sslContext, port->certsToChain.get());
a411d213 3866 }
aebe6888 3867 //else it is self-signed or untrusted do not attrach any certificate
a594dbfa 3868
9873e378 3869 Ssl::LocalContextStorage *ssl_ctx_cache = Ssl::TheGlobalContextStorage.getLocalStorage(port->s);
b38b26cb 3870 assert(sslBumpCertKey.size() > 0 && sslBumpCertKey[0] != '\0');
fb2178bb 3871 if (sslContext) {
9873e378 3872 if (!ssl_ctx_cache || !ssl_ctx_cache->add(sslBumpCertKey.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext))) {
95d2589c 3873 // If it is not in storage delete after using. Else storage deleted it.
73c36fd9 3874 fd_table[clientConnection->fd].dynamicSslContext = sslContext;
95d2589c
CT
3875 }
3876 } else {
fb2178bb 3877 debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslConnectHostOrIp);
95d2589c
CT
3878 }
3879 }
3880
3881 // If generated ssl context = NULL, try to use static ssl context.
3882 if (!sslContext) {
3883 if (!port->staticSslContext) {
e0236918 3884 debugs(83, DBG_IMPORTANT, "Closing SSL " << clientConnection->remote << " as lacking SSL context");
73c36fd9 3885 clientConnection->close();
1ce2822d 3886 return;
95d2589c
CT
3887 } else {
3888 debugs(33, 5, HERE << "Using static ssl context.");
3889 sslContext = port->staticSslContext.get();
3890 }
3891 }
ae7ff0b8 3892
a9b1d8c6 3893 if (!httpsCreate(clientConnection, sslContext))
1ce2822d 3894 return;
ae7ff0b8 3895
4e67d484
CT
3896 // bumped intercepted conns should already have Config.Timeout.request set
3897 // but forwarded connections may only have Config.Timeout.lifetime. [Re]set
3898 // to make sure the connection does not get stuck on non-SSL clients.
3899 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3900 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
3899de60 3901 this, ConnStateData::requestTimeout);
4e67d484 3902 commSetConnTimeout(clientConnection, Config.Timeout.request, timeoutCall);
ae7ff0b8 3903
a3c6762c 3904 // Disable the client read handler until CachePeer selection is complete
73c36fd9
AJ
3905 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
3906 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientNegotiateSSL, this, 0);
ae7ff0b8 3907 switchedToHttps_ = true;
ae7ff0b8 3908}
3909
1ce2822d 3910void
caf3666d 3911ConnStateData::switchToHttps(HttpRequest *request, Ssl::BumpMode bumpServerMode)
95d2589c
CT
3912{
3913 assert(!switchedToHttps_);
3914
65ba7f04
CT
3915 sslConnectHostOrIp = request->GetHost();
3916 sslCommonName = request->GetHost();
95d2589c 3917
83d4cd15
CT
3918 // We are going to read new request
3919 flags.readMore = true;
73c36fd9 3920 debugs(33, 5, HERE << "converting " << clientConnection << " to SSL");
95d2589c 3921
2bd84e5f
CT
3922 // If sslServerBump is set, then we have decided to deny CONNECT
3923 // and now want to switch to SSL to send the error to the client
3924 // without even peeking at the origin server certificate.
caf3666d 3925 if (bumpServerMode == Ssl::bumpServerFirst && !sslServerBump) {
e857372a 3926 request->flags.sslPeek = true;
65ba7f04 3927 sslServerBump = new Ssl::ServerBump(request);
fd4624d7 3928
d7ce0bcd 3929 // will call httpsPeeked() with certificate and connection, eventually
b248c2a3 3930 FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw());
d7ce0bcd
AR
3931 return;
3932 }
3933
fb2178bb 3934 // otherwise, use sslConnectHostOrIp
d7ce0bcd
AR
3935 getSslContextStart();
3936}
3937
3938void
3939ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection)
3940{
fd4624d7 3941 Must(sslServerBump != NULL);
819c207f 3942
061bbdec
CT
3943 if (Comm::IsConnOpen(serverConnection)) {
3944 SSL *ssl = fd_table[serverConnection->fd].ssl;
3945 assert(ssl);
3946 Ssl::X509_Pointer serverCert(SSL_get_peer_certificate(ssl));
3947 assert(serverCert.get() != NULL);
fb2178bb 3948 sslCommonName = Ssl::CommonHostName(serverCert.get());
87f237a9 3949 debugs(33, 5, HERE << "HTTPS server CN: " << sslCommonName <<
59a49556 3950 " bumped: " << *serverConnection);
061bbdec
CT
3951
3952 pinConnection(serverConnection, NULL, NULL, false);
3953
fb2178bb 3954 debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp);
59a49556 3955 } else {
13858f50 3956 debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp);
8499a1de
CT
3957 Ip::Address intendedDest;
3958 intendedDest = sslConnectHostOrIp.termedBuf();
c3d24490 3959 const bool isConnectRequest = !port->flags.isIntercepted();
35cd4281 3960
8499a1de
CT
3961 // Squid serves its own error page and closes, so we want
3962 // a CN that causes no additional browser errors. Possible
35cd4281 3963 // only when bumping CONNECT with a user-typed address.
4dd643d5 3964 if (intendedDest.isAnyAddr() || isConnectRequest)
8499a1de 3965 sslCommonName = sslConnectHostOrIp;
fd4624d7
CT
3966 else if (sslServerBump->serverCert.get())
3967 sslCommonName = Ssl::CommonHostName(sslServerBump->serverCert.get());
129fe2a1
CT
3968
3969 // copy error detail from bump-server-first request to CONNECT request
3970 if (currentobject != NULL && currentobject->http != NULL && currentobject->http->request)
3971 currentobject->http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
59a49556 3972 }
061bbdec 3973
1ce2822d 3974 getSslContextStart();
95d2589c
CT
3975}
3976
cb4f4424 3977#endif /* USE_OPENSSL */
1f7c9178 3978
00516be1
AR
3979/// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3980static bool
73c36fd9 3981OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType)
00516be1 3982{
73c36fd9 3983 if (!Comm::IsConnOpen(c)) {
00516be1
AR
3984 Must(NHttpSockets > 0); // we tried to open some
3985 --NHttpSockets; // there will be fewer sockets than planned
3986 Must(HttpSockets[NHttpSockets] < 0); // no extra fds received
3987
3988 if (!NHttpSockets) // we could not open any listen sockets at all
cbff89ba 3989 fatalf("Unable to open %s",FdNote(portType));
00516be1
AR
3990
3991 return false;
3992 }
3993 return true;
3994}
3995
3996/// find any unused HttpSockets[] slot and store fd there or return false
3997static bool
e0d28505 3998AddOpenedHttpSocket(const Comm::ConnectionPointer &conn)
00516be1
AR
3999{
4000 bool found = false;
95dc7ff4 4001 for (int i = 0; i < NHttpSockets && !found; ++i) {
00516be1 4002 if ((found = HttpSockets[i] < 0))
e0d28505 4003 HttpSockets[i] = conn->fd;
00516be1
AR
4004 }
4005 return found;
4006}
15df8349 4007
d193a436 4008static void
15df8349 4009clientHttpConnectionsOpen(void)
4010{
fa720bfb 4011 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
65d448bc 4012 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4013 debugs(1, DBG_IMPORTANT, "WARNING: You have too many 'http_port' lines.");
4014 debugs(1, DBG_IMPORTANT, " The limit is " << MAXTCPLISTENPORTS << " HTTP ports.");
62e76326 4015 continue;
4016 }
4017
cb4f4424 4018#if USE_OPENSSL
6a25a046 4019 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
1ca54a54 4020 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s);
6a25a046 4021 s->flags.tunnelSslBumping = false;
3d61b18e
AJ
4022 }
4023
6a25a046 4024 if (s->flags.tunnelSslBumping &&
2ee34428
A
4025 !s->staticSslContext &&
4026 !s->generateHostCertificates) {
859741ed 4027 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4028 s->flags.tunnelSslBumping = false;
ae7ff0b8 4029 }
6a25a046 4030 if (s->flags.tunnelSslBumping) {
95d2589c
CT
4031 // Create ssl_ctx cache for this port.
4032 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4033 }
ae7ff0b8 4034#endif
4035
e0d28505 4036 // Fill out a Comm::Connection which IPC will open as a listener for us
8bbb16e3 4037 // then pass back when active so we can start a TcpAcceptor subscription.
e0d28505
AJ
4038 s->listenConn = new Comm::Connection;
4039 s->listenConn->local = s->s;
6a25a046 4040 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) | (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
c303f6e3 4041
cbff89ba
AJ
4042 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4043 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
fa720bfb 4044 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, CommAcceptCbParams(NULL)));
cbff89ba 4045 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4046
cbff89ba 4047 AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened",
8bbb16e3
AJ
4048 ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub));
4049 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall);
62e76326 4050
a38ec4b1
FC
4051 HttpSockets[NHttpSockets] = -1; // set in clientListenerConnectionOpened
4052 ++NHttpSockets;
15df8349 4053 }
d193a436 4054}
4055
cb4f4424 4056#if USE_OPENSSL
d193a436 4057static void
4058clientHttpsConnectionsOpen(void)
4059{
fa720bfb 4060 for (AnyP::PortCfgPointer s = HttpsPortList; s != NULL; s = s->next) {
65d448bc 4061 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4062 debugs(1, DBG_IMPORTANT, "Ignoring 'https_port' lines exceeding the limit.");
4063 debugs(1, DBG_IMPORTANT, "The limit is " << MAXTCPLISTENPORTS << " HTTPS ports.");
62e76326 4064 continue;
4065 }
4066
95d2589c 4067 if (!s->staticSslContext) {
e0236918 4068 debugs(1, DBG_IMPORTANT, "Ignoring https_port " << s->s <<
ae7ff0b8 4069 " due to SSL initialization failure.");
4070 continue;
f9ad0106 4071 }
4072
d7ce0bcd 4073 // TODO: merge with similar code in clientHttpConnectionsOpen()
6a25a046 4074 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
1ca54a54 4075 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s);
6a25a046 4076 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4077 }
4078
6a25a046 4079 if (s->flags.tunnelSslBumping && !s->staticSslContext && !s->generateHostCertificates) {
03f00a11 4080 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4081 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4082 }
4083
6a25a046 4084 if (s->flags.tunnelSslBumping) {
d7ce0bcd
AR
4085 // Create ssl_ctx cache for this port.
4086 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4087 }
4088
e0d28505 4089 // Fill out a Comm::Connection which IPC will open as a listener for us
859741ed
AJ
4090 s->listenConn = new Comm::Connection;
4091 s->listenConn->local = s->s;
6a25a046
FC
4092 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
4093 (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
62e76326 4094
cbff89ba
AJ
4095 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4096 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
fa720bfb 4097 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, CommAcceptCbParams(NULL)));
cbff89ba 4098 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4099
cbff89ba 4100 AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened",
8bbb16e3 4101 ListeningStartedDialer(&clientListenerConnectionOpened,
859741ed 4102 s, Ipc::fdnHttpsSocket, sub));
8bbb16e3 4103 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall);
a38ec4b1
FC
4104 HttpSockets[NHttpSockets] = -1;
4105 ++NHttpSockets;
cbff89ba 4106 }
d193a436 4107}
d193a436 4108#endif
4109
92ae4c86 4110void
27c841f6
AR
4111clientStartListeningOn(AnyP::PortCfgPointer &port, const RefCount< CommCbFunPtrCallT<CommAcceptCbPtrFun> > &subCall, const Ipc::FdNoteId fdNote)
4112{
92ae4c86
AR
4113 // Fill out a Comm::Connection which IPC will open as a listener for us
4114 port->listenConn = new Comm::Connection;
4115 port->listenConn->local = port->s;
e7ce227f
AR
4116 port->listenConn->flags =
4117 COMM_NONBLOCKING |
4118 (port->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
4119 (port->flags.natIntercept ? COMM_INTERCEPTION : 0);
92ae4c86
AR
4120
4121 // route new connections to subCall
4122 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
4123 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
e7ce227f
AR
4124 AsyncCall::Pointer listenCall =
4125 asyncCall(33, 2, "clientListenerConnectionOpened",
4126 ListeningStartedDialer(&clientListenerConnectionOpened,
4127 port, fdNote, sub));
92ae4c86 4128 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, port->listenConn, fdNote, listenCall);
434a79b0 4129
92ae4c86
AR
4130 assert(NHttpSockets < MAXTCPLISTENPORTS);
4131 HttpSockets[NHttpSockets] = -1;
4132 ++NHttpSockets;
434a79b0
DK
4133}
4134
e0d28505 4135/// process clientHttpConnectionsOpen result
00516be1 4136static void
fa720bfb 4137clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub)
00516be1 4138{
fa720bfb
AJ
4139 Must(s != NULL);
4140
8bbb16e3 4141 if (!OpenedHttpSocket(s->listenConn, portTypeNote))
00516be1 4142 return;
62e76326 4143
e0d28505 4144 Must(Comm::IsConnOpen(s->listenConn));
62e76326 4145
8bbb16e3 4146 // TCP: setup a job to handle accept() with subscribed handler
fa720bfb 4147 AsyncJob::Start(new Comm::TcpAcceptor(s, FdNote(portTypeNote), sub));
8bbb16e3 4148
e0236918 4149 debugs(1, DBG_IMPORTANT, "Accepting " <<
6a25a046 4150 (s->flags.natIntercept ? "NAT intercepted " : "") <<
0d901ef4 4151 (s->flags.tproxyIntercept ? "TPROXY intercepted " : "") <<
6a25a046
FC
4152 (s->flags.tunnelSslBumping ? "SSL bumped " : "") <<
4153 (s->flags.accelSurrogate ? "reverse-proxy " : "")
8bbb16e3
AJ
4154 << FdNote(portTypeNote) << " connections at "
4155 << s->listenConn);
62e76326 4156
e0d28505 4157 Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for
d193a436 4158}
4159
d193a436 4160void
4161clientOpenListenSockets(void)
4162{
4163 clientHttpConnectionsOpen();
cb4f4424 4164#if USE_OPENSSL
d193a436 4165 clientHttpsConnectionsOpen();
1f7c9178 4166#endif
92ae4c86 4167 Ftp::StartListening();
62e76326 4168
15df8349 4169 if (NHttpSockets < 1)
e7ce227f 4170 fatal("No HTTP, HTTPS, or FTP ports configured");
15df8349 4171}
edce4d98 4172
c0fbae16 4173void
e7ce227f 4174clientConnectionsClose()
c0fbae16 4175{
fa720bfb 4176 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
00406b24 4177 if (s->listenConn != NULL) {
e0236918 4178 debugs(1, DBG_IMPORTANT, "Closing HTTP port " << s->listenConn->local);
00406b24
AJ
4179 s->listenConn->close();
4180 s->listenConn = NULL;
04f55905
AJ
4181 }
4182 }
62e76326 4183
cb4f4424 4184#if USE_OPENSSL
fa720bfb 4185 for (AnyP::PortCfgPointer s = HttpsPortList; s != NULL; s = s->next) {
00406b24 4186 if (s->listenConn != NULL) {
e0236918 4187 debugs(1, DBG_IMPORTANT, "Closing HTTPS port " << s->listenConn->local);
00406b24
AJ
4188 s->listenConn->close();
4189 s->listenConn = NULL;
62e76326 4190 }
c0fbae16 4191 }
04f55905
AJ
4192#endif
4193
92ae4c86 4194 Ftp::StopListening();
434a79b0 4195
04f55905 4196 // TODO see if we can drop HttpSockets array entirely */
95dc7ff4 4197 for (int i = 0; i < NHttpSockets; ++i) {
04f55905
AJ
4198 HttpSockets[i] = -1;
4199 }
62e76326 4200
c0fbae16 4201 NHttpSockets = 0;
4202}
f66a9ef4 4203
4204int
190154cf 4205varyEvaluateMatch(StoreEntry * entry, HttpRequest * request)
f66a9ef4 4206{
4207 const char *vary = request->vary_headers;
a9925b40 4208 int has_vary = entry->getReply()->header.has(HDR_VARY);
f66a9ef4 4209#if X_ACCELERATOR_VARY
62e76326 4210
edce4d98 4211 has_vary |=
a9925b40 4212 entry->getReply()->header.has(HDR_X_ACCELERATOR_VARY);
f66a9ef4 4213#endif
62e76326 4214
f66a9ef4 4215 if (!has_vary || !entry->mem_obj->vary_headers) {
62e76326 4216 if (vary) {
4217 /* Oops... something odd is going on here.. */
e0236918 4218 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
c877c0bc 4219 entry->mem_obj->urlXXX() << "' '" << vary << "'");
62e76326 4220 safe_free(request->vary_headers);
4221 return VARY_CANCEL;
4222 }
4223
4224 if (!has_vary) {
4225 /* This is not a varying object */
4226 return VARY_NONE;
4227 }
4228
4229 /* virtual "vary" object found. Calculate the vary key and
4230 * continue the search
4231 */
4232 vary = httpMakeVaryMark(request, entry->getReply());
4233
4234 if (vary) {
4235 request->vary_headers = xstrdup(vary);
4236 return VARY_OTHER;
4237 } else {
4238 /* Ouch.. we cannot handle this kind of variance */
4239 /* XXX This cannot really happen, but just to be complete */
4240 return VARY_CANCEL;
4241 }
f66a9ef4 4242 } else {
62e76326 4243 if (!vary) {
4244 vary = httpMakeVaryMark(request, entry->getReply());
4245
4246 if (vary)
4247 request->vary_headers = xstrdup(vary);
4248 }
4249
4250 if (!vary) {
4251 /* Ouch.. we cannot handle this kind of variance */
4252 /* XXX This cannot really happen, but just to be complete */
4253 return VARY_CANCEL;
4254 } else if (strcmp(vary, entry->mem_obj->vary_headers) == 0) {
4255 return VARY_MATCH;
4256 } else {
4257 /* Oops.. we have already been here and still haven't
4258 * found the requested variant. Bail out
4259 */
e0236918 4260 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
c877c0bc 4261 entry->mem_obj->urlXXX() << "' '" << vary << "'");
62e76326 4262 return VARY_CANCEL;
4263 }
f66a9ef4 4264 }
4265}
28d4805a 4266
c0941a6a 4267ACLFilledChecklist *
59a1efb2 4268clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http)
28d4805a 4269{
1cf238db 4270 ConnStateData * conn = http->getConn();
c0941a6a 4271 ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request,
73c36fd9 4272 cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str);
d4806c91 4273 ch->al = http->al;
28d4805a 4274 /*
4275 * hack for ident ACL. It needs to get full addresses, and a place to store
4276 * the ident result on persistent connections...
4277 */
4278 /* connection oriented auth also needs these two lines for it's operation. */
28d4805a 4279 return ch;
4280}
a46d2c0e 4281
a46d2c0e 4282bool
4283ConnStateData::transparent() const
4284{
40d34a62 4285 return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
a46d2c0e 4286}
4287
4288bool
4289ConnStateData::reading() const
4290{
f84dd7eb 4291 return reader != NULL;
a46d2c0e 4292}
4293
4294void
f84dd7eb 4295ConnStateData::stopReading()
a46d2c0e 4296{
f84dd7eb 4297 if (reading()) {
7e66d5e2 4298 Comm::ReadCancel(clientConnection->fd, reader);
f84dd7eb
AR
4299 reader = NULL;
4300 }
a46d2c0e 4301}
4302
5f8252d2 4303BodyPipe::Pointer
3e62bd58 4304ConnStateData::expectRequestBody(int64_t size)
5f8252d2 4305{
4306 bodyPipe = new BodyPipe(this);
39cb8c41
AR
4307 if (size >= 0)
4308 bodyPipe->setBodySize(size);
4309 else
4310 startDechunkingRequest();
5f8252d2 4311 return bodyPipe;
4312}
4313
39cb8c41
AR
4314int64_t
4315ConnStateData::mayNeedToReadMoreBody() const
4316{
4317 if (!bodyPipe)
4318 return 0; // request without a body or read/produced all body bytes
4319
4320 if (!bodyPipe->bodySizeKnown())
4321 return -1; // probably need to read more, but we cannot be sure
4322
4323 const int64_t needToProduce = bodyPipe->unproducedSize();
e7287625 4324 const int64_t haveAvailable = static_cast<int64_t>(in.buf.length());
39cb8c41
AR
4325
4326 if (needToProduce <= haveAvailable)
4327 return 0; // we have read what we need (but are waiting for pipe space)
4328
4329 return needToProduce - haveAvailable;
4330}
4331
55e44db9 4332void
cf6eb29e 4333ConnStateData::stopReceiving(const char *error)
55e44db9 4334{
cf6eb29e
CT
4335 debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error <<
4336 "; old sending error: " <<
4337 (stoppedSending() ? stoppedSending_ : "none"));
5f8252d2 4338
cf6eb29e
CT
4339 if (const char *oldError = stoppedReceiving()) {
4340 debugs(33, 3, HERE << "already stopped receiving: " << oldError);
4341 return; // nothing has changed as far as this connection is concerned
4342 }
5f8252d2 4343
cf6eb29e 4344 stoppedReceiving_ = error;
5f8252d2 4345
cf6eb29e
CT
4346 if (const char *sendError = stoppedSending()) {
4347 debugs(33, 3, HERE << "closing because also stopped sending: " << sendError);
4348 clientConnection->close();
4349 }
55e44db9 4350}
4351
eb44b2d7 4352void
e29ccb57
A
4353ConnStateData::expectNoForwarding()
4354{
eb44b2d7
CT
4355 if (bodyPipe != NULL) {
4356 debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status());
4357 bodyPipe->expectNoConsumption();
4358 }
4359}
4360
39cb8c41 4361/// initialize dechunking state
3ff65596 4362void
39cb8c41 4363ConnStateData::startDechunkingRequest()
3ff65596 4364{
39cb8c41
AR
4365 Must(bodyPipe != NULL);
4366 debugs(33, 5, HERE << "start dechunking" << bodyPipe->status());
3ff65596
AR
4367 assert(!in.bodyParser);
4368 in.bodyParser = new ChunkedCodingParser;
3ff65596
AR
4369}
4370
39cb8c41 4371/// put parsed content into input buffer and clean up
3ff65596 4372void
39cb8c41 4373ConnStateData::finishDechunkingRequest(bool withSuccess)
3ff65596 4374{
39cb8c41 4375 debugs(33, 5, HERE << "finish dechunking: " << withSuccess);
3ff65596 4376
39cb8c41
AR
4377 if (bodyPipe != NULL) {
4378 debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status());
4379 BodyPipe::Pointer myPipe = bodyPipe;
4380 stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize()
4381 Must(!bodyPipe); // we rely on it being nil after we are done with body
4382 if (withSuccess) {
4383 Must(myPipe->bodySizeKnown());
4384 ClientSocketContext::Pointer context = getCurrentContext();
4385 if (context != NULL && context->http && context->http->request)
4386 context->http->request->setContentLength(myPipe->bodySize());
4387 }
3ff65596 4388 }
3ff65596 4389
39cb8c41
AR
4390 delete in.bodyParser;
4391 in.bodyParser = NULL;
3ff65596
AR
4392}
4393
e7287625
AJ
4394ConnStateData::In::In() :
4395 bodyParser(NULL),
4396 buf()
a46d2c0e 4397{}
4398
4399ConnStateData::In::~In()
4400{
39cb8c41 4401 delete bodyParser; // TODO: pool
a46d2c0e 4402}
d67acb4e 4403
655daa06
AR
4404void
4405ConnStateData::sendControlMsg(HttpControlMsg msg)
4406{
eedd4182
AR
4407 if (!isOpen()) {
4408 debugs(33, 3, HERE << "ignoring 1xx due to earlier closure");
655daa06
AR
4409 return;
4410 }
4411
eedd4182
AR
4412 ClientSocketContext::Pointer context = getCurrentContext();
4413 if (context != NULL) {
4414 context->writeControlMsg(msg); // will call msg.cbSuccess
655daa06
AR
4415 return;
4416 }
4417
4418 debugs(33, 3, HERE << " closing due to missing context for 1xx");
73c36fd9 4419 clientConnection->close();
655daa06
AR
4420}
4421
d7ce0bcd 4422/// Our close handler called by Comm when the pinned connection is closed
d67acb4e
AJ
4423void
4424ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io)
4425{
7a957a93
AR
4426 // FwdState might repin a failed connection sooner than this close
4427 // callback is called for the failed connection.
693cb033
CT
4428 assert(pinning.serverConnection == io.conn);
4429 pinning.closeHandler = NULL; // Comm unregisters handlers before calling
4430 const bool sawZeroReply = pinning.zeroReply; // reset when unpinning
89b1d7a2 4431 unpinConnection(false);
f8e4867b 4432
7ac40923 4433 if (sawZeroReply && clientConnection != NULL) {
693cb033
CT
4434 debugs(33, 3, "Closing client connection on pinned zero reply.");
4435 clientConnection->close();
85563fd9 4436 }
f8e4867b 4437
d67acb4e
AJ
4438}
4439
b1cf2350 4440void
f8e4867b 4441ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth, bool monitor)
9e008dda 4442{
e7ce227f 4443 if (!Comm::IsConnOpen(pinning.serverConnection) ||
27c841f6 4444 pinning.serverConnection->fd != pinServer->fd)
89b1d7a2 4445 pinNewConnection(pinServer, request, aPeer, auth);
d67acb4e 4446
f8e4867b
AR
4447 if (monitor)
4448 startPinnedConnectionMonitoring();
89b1d7a2 4449}
9e008dda 4450
89b1d7a2
AR
4451void
4452ConnStateData::pinNewConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth)
4453{
4454 unpinConnection(true); // closes pinned connection, if any, and resets fields
9e008dda 4455
73c36fd9 4456 pinning.serverConnection = pinServer;
d7ce0bcd 4457
85563fd9
AR
4458 debugs(33, 3, HERE << pinning.serverConnection);
4459
89b1d7a2
AR
4460 Must(pinning.serverConnection != NULL);
4461
d7ce0bcd
AR
4462 // when pinning an SSL bumped connection, the request may be NULL
4463 const char *pinnedHost = "[unknown]";
4464 if (request) {
4465 pinning.host = xstrdup(request->GetHost());
4466 pinning.port = request->port;
4467 pinnedHost = pinning.host;
4468 } else {
4dd643d5 4469 pinning.port = pinServer->remote.port();
d7ce0bcd 4470 }
d67acb4e 4471 pinning.pinned = true;
8bcf08e0
FC
4472 if (aPeer)
4473 pinning.peer = cbdataReference(aPeer);
d67acb4e 4474 pinning.auth = auth;
e3a4aecc 4475 char stmp[MAX_IPSTRLEN];
89b1d7a2 4476 char desc[FD_DESC_SZ];
e3a4aecc 4477 snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)",
d7ce0bcd 4478 (auth || !aPeer) ? pinnedHost : aPeer->name,
4dd643d5 4479 clientConnection->remote.toUrl(stmp,MAX_IPSTRLEN),
d7ce0bcd 4480 clientConnection->fd);
73c36fd9 4481 fd_note(pinning.serverConnection->fd, desc);
9e008dda 4482
d67acb4e 4483 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
4299f876 4484 pinning.closeHandler = JobCallback(33, 5,
4cb2536f 4485 Dialer, this, ConnStateData::clientPinnedConnectionClosed);
85563fd9
AR
4486 // remember the pinned connection so that cb does not unpin a fresher one
4487 typedef CommCloseCbParams Params;
4488 Params &params = GetCommParams<Params>(pinning.closeHandler);
4489 params.conn = pinning.serverConnection;
73c36fd9 4490 comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
7ac40923
AR
4491}
4492
e7ce227f
AR
4493/// [re]start monitoring pinned connection for peer closures so that we can
4494/// propagate them to an _idle_ client pinned to that peer
7ac40923
AR
4495void
4496ConnStateData::startPinnedConnectionMonitoring()
4497{
4498 if (pinning.readHandler != NULL)
4499 return; // already monitoring
4500
4501 typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer;
4502 pinning.readHandler = JobCallback(33, 3,
4503 Dialer, this, ConnStateData::clientPinnedConnectionRead);
7e66d5e2 4504 Comm::Read(pinning.serverConnection, pinning.readHandler);
7ac40923
AR
4505}
4506
4507void
4508ConnStateData::stopPinnedConnectionMonitoring()
4509{
4510 if (pinning.readHandler != NULL) {
7e66d5e2 4511 Comm::ReadCancel(pinning.serverConnection->fd, pinning.readHandler);
7ac40923
AR
4512 pinning.readHandler = NULL;
4513 }
4514}
4515
4516/// Our read handler called by Comm when the server either closes an idle pinned connection or
4517/// perhaps unexpectedly sends something on that idle (from Squid p.o.v.) connection.
4518void
4519ConnStateData::clientPinnedConnectionRead(const CommIoCbParams &io)
4520{
4521 pinning.readHandler = NULL; // Comm unregisters handlers before calling
4522
c8407295 4523 if (io.flag == Comm::ERR_CLOSING)
7ac40923
AR
4524 return; // close handler will clean up
4525
4526 // We could use getConcurrentRequestCount(), but this may be faster.
4527 const bool clientIsIdle = !getCurrentContext();
4528
4529 debugs(33, 3, "idle pinned " << pinning.serverConnection << " read " <<
4530 io.size << (clientIsIdle ? " with idle client" : ""));
4531
4532 assert(pinning.serverConnection == io.conn);
4533 pinning.serverConnection->close();
4534
4535 // If we are still sending data to the client, do not close now. When we are done sending,
4536 // ClientSocketContext::keepaliveNextRequest() checks pinning.serverConnection and will close.
4537 // However, if we are idle, then we must close to inform the idle client and minimize races.
4538 if (clientIsIdle && clientConnection != NULL)
4539 clientConnection->close();
d67acb4e
AJ
4540}
4541
e3a4aecc 4542const Comm::ConnectionPointer
a3c6762c 4543ConnStateData::validatePinnedConnection(HttpRequest *request, const CachePeer *aPeer)
d67acb4e 4544{
85563fd9
AR
4545 debugs(33, 7, HERE << pinning.serverConnection);
4546
d67acb4e 4547 bool valid = true;
73c36fd9 4548 if (!Comm::IsConnOpen(pinning.serverConnection))
e3a4aecc 4549 valid = false;
6de3828e 4550 else if (pinning.auth && pinning.host && request && strcasecmp(pinning.host, request->GetHost()) != 0)
9e008dda 4551 valid = false;
6de3828e 4552 else if (request && pinning.port != request->port)
9e008dda 4553 valid = false;
6de3828e 4554 else if (pinning.peer && !cbdataReferenceValid(pinning.peer))
9e008dda 4555 valid = false;
6de3828e 4556 else if (aPeer != pinning.peer)
9e008dda 4557 valid = false;
d67acb4e 4558
9e008dda 4559 if (!valid) {
b1cf2350 4560 /* The pinning info is not safe, remove any pinning info */
89b1d7a2 4561 unpinConnection(true);
d67acb4e
AJ
4562 }
4563
73c36fd9 4564 return pinning.serverConnection;
d67acb4e
AJ
4565}
4566
89b1d7a2
AR
4567Comm::ConnectionPointer
4568ConnStateData::borrowPinnedConnection(HttpRequest *request, const CachePeer *aPeer)
4569{
4570 debugs(33, 7, pinning.serverConnection);
4571 if (validatePinnedConnection(request, aPeer) != NULL)
f8e4867b 4572 stopPinnedConnectionMonitoring();
89b1d7a2
AR
4573
4574 return pinning.serverConnection; // closed if validation failed
4575}
4576
b1cf2350 4577void
89b1d7a2 4578ConnStateData::unpinConnection(const bool andClose)
d67acb4e 4579{
85563fd9
AR
4580 debugs(33, 3, HERE << pinning.serverConnection);
4581
9e008dda
AJ
4582 if (pinning.peer)
4583 cbdataReferenceDone(pinning.peer);
d67acb4e 4584
d7ce0bcd 4585 if (Comm::IsConnOpen(pinning.serverConnection)) {
87f237a9
A
4586 if (pinning.closeHandler != NULL) {
4587 comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
4588 pinning.closeHandler = NULL;
4589 }
89b1d7a2 4590
f8e4867b 4591 stopPinnedConnectionMonitoring();
89b1d7a2
AR
4592
4593 // close the server side socket if requested
4594 if (andClose)
4595 pinning.serverConnection->close();
4596 pinning.serverConnection = NULL;
d67acb4e 4597 }
d7ce0bcd 4598
d67acb4e 4599 safe_free(pinning.host);
e3a4aecc 4600
693cb033
CT
4601 pinning.zeroReply = false;
4602
e3a4aecc
AJ
4603 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4604 * connection has gone away */
d67acb4e 4605}