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