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