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