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