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