]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
Regression fix: Accept-Language header parse
[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";
528b2c61 1281 else if ((rep->sline.status != HTTP_OK) && (rep->sline.status != HTTP_PARTIAL_CONTENT))
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. */
1314 httpStatusLineSet(&rep->sline, rep->sline.version,
1315 HTTP_PARTIAL_CONTENT, NULL);
fedd1531 1316 // web server responded with a valid, but unexpected range.
1317 // will (try-to) forward as-is.
1318 //TODO: we should cope with multirange request/responses
1319 bool replyMatchRequest = rep->content_range != NULL ?
1320 request->range->contains(rep->content_range->spec) :
1321 true;
62e76326 1322 const int spec_count = http->request->range->specs.count;
47f6e231 1323 int64_t actual_clen = -1;
62e76326 1324
47f6e231 1325 debugs(33, 3, "clientBuildRangeHeader: range spec count: " <<
9e008dda 1326 spec_count << " virgin clen: " << rep->content_length);
62e76326 1327 assert(spec_count > 0);
62e76326 1328 /* append appropriate header(s) */
1329
1330 if (spec_count == 1) {
fedd1531 1331 if (!replyMatchRequest) {
1332 hdr->delById(HDR_CONTENT_RANGE);
1333 hdr->putContRange(rep->content_range);
1334 actual_clen = rep->content_length;
1335 //http->range_iter.pos = rep->content_range->spec.begin();
1336 (*http->range_iter.pos)->offset = rep->content_range->spec.offset;
1337 (*http->range_iter.pos)->length = rep->content_range->spec.length;
1338
1339 } else {
1340 HttpHdrRange::iterator pos = http->request->range->begin();
1341 assert(*pos);
1342 /* append Content-Range */
1343
1344 if (!hdr->has(HDR_CONTENT_RANGE)) {
1345 /* No content range, so this was a full object we are
1346 * sending parts of.
1347 */
1348 httpHeaderAddContRange(hdr, **pos, rep->content_length);
1349 }
1350
1351 /* set new Content-Length to the actual number of bytes
1352 * transmitted in the message-body */
1353 actual_clen = (*pos)->length;
62e76326 1354 }
62e76326 1355 } else {
1356 /* multipart! */
1357 /* generate boundary string */
1358 http->range_iter.boundary = http->rangeBoundaryStr();
1359 /* delete old Content-Type, add ours */
a9925b40 1360 hdr->delById(HDR_CONTENT_TYPE);
62e76326 1361 httpHeaderPutStrf(hdr, HDR_CONTENT_TYPE,
826a1fed
FC
1362 "multipart/byteranges; boundary=\"" SQUIDSTRINGPH "\"",
1363 SQUIDSTRINGPRINT(http->range_iter.boundary));
62e76326 1364 /* Content-Length is not required in multipart responses
1365 * but it is always nice to have one */
1366 actual_clen = http->mRangeCLen();
2512d159 1367 /* http->out needs to start where we want data at */
1368 http->out.offset = http->range_iter.currentSpec()->offset;
62e76326 1369 }
1370
1371 /* replace Content-Length header */
1372 assert(actual_clen >= 0);
1373
a9925b40 1374 hdr->delById(HDR_CONTENT_LENGTH);
62e76326 1375
47f6e231 1376 hdr->putInt64(HDR_CONTENT_LENGTH, actual_clen);
62e76326 1377
bf8fe701 1378 debugs(33, 3, "clientBuildRangeHeader: actual content length: " << actual_clen);
62e76326 1379
1380 /* And start the range iter off */
1381 http->range_iter.updateSpec();
c8be6d7b 1382 }
528b2c61 1383}
1384
1385void
1386ClientSocketContext::prepareReply(HttpReply * rep)
1387{
fedd1531 1388 reply = rep;
1389
528b2c61 1390 if (http->request->range)
62e76326 1391 buildRangeHeader(rep);
528b2c61 1392}
1393
1394void
1395ClientSocketContext::sendStartOfMessage(HttpReply * rep, StoreIOBuffer bodyData)
1396{
1397 prepareReply(rep);
528b2c61 1398 assert (rep);
06a5ae20 1399 MemBuf *mb = rep->pack();
1ce34ddd
AJ
1400
1401 // dump now, so we dont output any body.
1402 debugs(11, 2, "HTTP Client " << clientConnection);
1403 debugs(11, 2, "HTTP Client REPLY:\n---------\n" << mb->buf << "\n----------");
1404
528b2c61 1405 /* Save length of headers for persistent conn checks */
032785bf 1406 http->out.headers_sz = mb->contentSize();
528b2c61 1407#if HEADERS_LOG
62e76326 1408
528b2c61 1409 headersLog(0, 0, http->request->method, rep);
1410#endif
62e76326 1411
c8be6d7b 1412 if (bodyData.data && bodyData.length) {
4ad60609
AR
1413 if (multipartRangeRequest())
1414 packRange(bodyData, mb);
450fe1cb 1415 else if (http->request->flags.chunkedReply) {
4ad60609
AR
1416 packChunk(bodyData, *mb);
1417 } else {
2512d159 1418 size_t length = lengthToSend(bodyData.range());
62e76326 1419 noteSentBodyBytes (length);
1420
2fe7eff9 1421 mb->append(bodyData.data, length);
62e76326 1422 }
c8be6d7b 1423 }
62e76326 1424
c8be6d7b 1425 /* write */
425802c8 1426 debugs(33,7, HERE << "sendStartOfMessage schedules clientWriteComplete");
9e008dda
AJ
1427 AsyncCall::Pointer call = commCbCall(33, 5, "clientWriteComplete",
1428 CommIoCbPtrFun(clientWriteComplete, this));
73c36fd9 1429 Comm::Write(clientConnection, mb, call);
032785bf 1430 delete mb;
c8be6d7b 1431}
1432
63be0a78 1433/**
7dc5f514 1434 * Write a chunk of data to a client socket. If the reply is present,
1435 * send the reply headers down the wire too, and clean them up when
1436 * finished.
9e008dda 1437 * Pre-condition:
edce4d98 1438 * The request is one backed by a connection, not an internal request.
1439 * data context is not NULL
1440 * There are no more entries in the stream chain.
2246b732 1441 */
edce4d98 1442static void
59a1efb2 1443clientSocketRecipient(clientStreamNode * node, ClientHttpRequest * http,
2324cda2 1444 HttpReply * rep, StoreIOBuffer receivedData)
edce4d98 1445{
edce4d98 1446 /* Test preconditions */
1447 assert(node != NULL);
559da936 1448 PROF_start(clientSocketRecipient);
62e76326 1449 /* TODO: handle this rather than asserting
9e008dda
AJ
1450 * - it should only ever happen if we cause an abort and
1451 * the callback chain loops back to here, so we can simply return.
1452 * However, that itself shouldn't happen, so it stays as an assert for now.
edce4d98 1453 */
1454 assert(cbdataReferenceValid(node));
edce4d98 1455 assert(node->node.next == NULL);
0655fa4d 1456 ClientSocketContext::Pointer context = dynamic_cast<ClientSocketContext *>(node->data.getRaw());
94a396a3 1457 assert(context != NULL);
98242069 1458 assert(connIsUsable(http->getConn()));
5c336a3b 1459
528b2c61 1460 /* TODO: check offset is what we asked for */
62e76326 1461
98242069 1462 if (context != http->getConn()->getCurrentContext()) {
2324cda2 1463 context->deferRecipientForLater(node, rep, receivedData);
559da936 1464 PROF_stop(clientSocketRecipient);
62e76326 1465 return;
edce4d98 1466 }
62e76326 1467
4ad60609
AR
1468 // After sending Transfer-Encoding: chunked (at least), always send
1469 // the last-chunk if there was no error, ignoring responseFinishedOrFailed.
450fe1cb
FC
1470 const bool mustSendLastChunk = http->request->flags.chunkedReply &&
1471 !http->request->flags.streamError && !context->startOfOutput();
4ad60609 1472 if (responseFinishedOrFailed(rep, receivedData) && !mustSendLastChunk) {
73c36fd9 1473 context->writeComplete(context->clientConnection, NULL, 0, COMM_OK);
559da936 1474 PROF_stop(clientSocketRecipient);
62e76326 1475 return;
edce4d98 1476 }
62e76326 1477
0655fa4d 1478 if (!context->startOfOutput())
2324cda2 1479 context->sendBody(rep, receivedData);
7684c4b1 1480 else {
a4785954 1481 assert(rep);
b248c2a3
AJ
1482 http->al->reply = rep;
1483 HTTPMSGLOCK(http->al->reply);
2324cda2 1484 context->sendStartOfMessage(rep, receivedData);
7684c4b1 1485 }
fc68f6b1 1486
559da936 1487 PROF_stop(clientSocketRecipient);
edce4d98 1488}
1489
63be0a78 1490/**
1491 * Called when a downstream node is no longer interested in
edce4d98 1492 * our data. As we are a terminal node, this means on aborts
1493 * only
1494 */
1495void
59a1efb2 1496clientSocketDetach(clientStreamNode * node, ClientHttpRequest * http)
edce4d98 1497{
edce4d98 1498 /* Test preconditions */
1499 assert(node != NULL);
62e76326 1500 /* TODO: handle this rather than asserting
9e008dda
AJ
1501 * - it should only ever happen if we cause an abort and
1502 * the callback chain loops back to here, so we can simply return.
edce4d98 1503 * However, that itself shouldn't happen, so it stays as an assert for now.
1504 */
1505 assert(cbdataReferenceValid(node));
1506 /* Set null by ContextFree */
edce4d98 1507 assert(node->node.next == NULL);
0655fa4d 1508 /* this is the assert discussed above */
e4a67a80 1509 assert(NULL == dynamic_cast<ClientSocketContext *>(node->data.getRaw()));
edce4d98 1510 /* We are only called when the client socket shutsdown.
1511 * Tell the prev pipeline member we're finished
1512 */
1513 clientStreamDetach(node, http);
7a2f978b 1514}
1515
f4f278b5 1516static void
e0d28505 1517clientWriteBodyComplete(const Comm::ConnectionPointer &conn, char *buf, size_t size, comm_err_t errflag, int xerrno, void *data)
f4f278b5 1518{
425802c8 1519 debugs(33,7, HERE << "clientWriteBodyComplete schedules clientWriteComplete");
e0d28505 1520 clientWriteComplete(conn, NULL, size, errflag, xerrno, data);
c8be6d7b 1521}
1522
1523void
a46d2c0e 1524ConnStateData::readNextRequest()
c8be6d7b 1525{
73c36fd9 1526 debugs(33, 5, HERE << clientConnection << " reading next req");
bf8fe701 1527
97b32442 1528 fd_note(clientConnection->fd, "Idle client: Waiting for next request");
63be0a78 1529 /**
c8be6d7b 1530 * Set the timeout BEFORE calling clientReadRequest().
1531 */
1cf238db 1532 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 1533 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
4cb2536f 1534 TimeoutDialer, this, ConnStateData::requestTimeout);
97b32442 1535 commSetConnTimeout(clientConnection, Config.Timeout.clientIdlePconn, timeoutCall);
1cf238db 1536
a46d2c0e 1537 readSomeData();
63be0a78 1538 /** Please don't do anything with the FD past here! */
c8be6d7b 1539}
1540
09d3938c 1541static void
1cf238db 1542ClientSocketContextPushDeferredIfNeeded(ClientSocketContext::Pointer deferredRequest, ConnStateData * conn)
c8be6d7b 1543{
73c36fd9 1544 debugs(33, 2, HERE << conn->clientConnection << " Sending next");
bf8fe701 1545
63be0a78 1546 /** If the client stream is waiting on a socket write to occur, then */
62e76326 1547
c8be6d7b 1548 if (deferredRequest->flags.deferred) {
63be0a78 1549 /** NO data is allowed to have been sent. */
62e76326 1550 assert(deferredRequest->http->out.size == 0);
63be0a78 1551 /** defer now. */
62e76326 1552 clientSocketRecipient(deferredRequest->deferredparams.node,
1553 deferredRequest->http,
1554 deferredRequest->deferredparams.rep,
1555 deferredRequest->deferredparams.queuedBuffer);
c8be6d7b 1556 }
62e76326 1557
63be0a78 1558 /** otherwise, the request is still active in a callbacksomewhere,
c8be6d7b 1559 * and we are done
f4f278b5 1560 */
f4f278b5 1561}
1562
cf6eb29e 1563/// called when we have successfully finished writing the response
0655fa4d 1564void
1565ClientSocketContext::keepaliveNextRequest()
1a92a1e2 1566{
1cf238db 1567 ConnStateData * conn = http->getConn();
bd4e6ec8 1568
73c36fd9 1569 debugs(33, 3, HERE << "ConnnStateData(" << conn->clientConnection << "), Context(" << clientConnection << ")");
0655fa4d 1570 connIsFinished();
1571
73c36fd9
AJ
1572 if (conn->pinning.pinned && !Comm::IsConnOpen(conn->pinning.serverConnection)) {
1573 debugs(33, 2, HERE << conn->clientConnection << " Connection was pinned but server side gone. Terminating client connection");
1574 conn->clientConnection->close();
d67acb4e
AJ
1575 return;
1576 }
1577
cf6eb29e
CT
1578 /** \par
1579 * We are done with the response, and we are either still receiving request
1580 * body (early response!) or have already stopped receiving anything.
1581 *
1582 * If we are still receiving, then clientParseRequest() below will fail.
1583 * (XXX: but then we will call readNextRequest() which may succeed and
1584 * execute a smuggled request as we are not done with the current request).
1585 *
1586 * If we stopped because we got everything, then try the next request.
1587 *
1588 * If we stopped receiving because of an error, then close now to avoid
1589 * getting stuck and to prevent accidental request smuggling.
1590 */
1591
1592 if (const char *reason = conn->stoppedReceiving()) {
1593 debugs(33, 3, HERE << "closing for earlier request error: " << reason);
1594 conn->clientConnection->close();
1595 return;
1596 }
1597
63be0a78 1598 /** \par
f900210a 1599 * Attempt to parse a request from the request buffer.
1600 * If we've been fed a pipelined request it may already
1601 * be in our read buffer.
1602 *
63be0a78 1603 \par
f900210a 1604 * This needs to fall through - if we're unlucky and parse the _last_ request
1605 * from our read buffer we may never re-register for another client read.
1606 */
1607
f35961af 1608 if (conn->clientParseRequests()) {
73c36fd9 1609 debugs(33, 3, HERE << conn->clientConnection << ": parsed next request from buffer");
f900210a 1610 }
1611
63be0a78 1612 /** \par
f900210a 1613 * Either we need to kick-start another read or, if we have
1614 * a half-closed connection, kill it after the last request.
1615 * This saves waiting for half-closed connections to finished being
1616 * half-closed _AND_ then, sometimes, spending "Timeout" time in
1617 * the keepalive "Waiting for next request" state.
1618 */
73c36fd9 1619 if (commIsHalfClosed(conn->clientConnection->fd) && (conn->getConcurrentRequestCount() == 0)) {
bf8fe701 1620 debugs(33, 3, "ClientSocketContext::keepaliveNextRequest: half-closed client with no pending requests, closing");
73c36fd9 1621 conn->clientConnection->close();
f900210a 1622 return;
1623 }
1624
0655fa4d 1625 ClientSocketContext::Pointer deferredRequest;
62e76326 1626
63be0a78 1627 /** \par
f900210a 1628 * At this point we either have a parsed request (which we've
1629 * kicked off the processing for) or not. If we have a deferred
1630 * request (parsed but deferred for pipeling processing reasons)
1631 * then look at processing it. If not, simply kickstart
1632 * another read.
1633 */
1634
1635 if ((deferredRequest = conn->getCurrentContext()).getRaw()) {
73c36fd9 1636 debugs(33, 3, HERE << conn->clientConnection << ": calling PushDeferredIfNeeded");
62e76326 1637 ClientSocketContextPushDeferredIfNeeded(deferredRequest, conn);
f35961af 1638 } else if (conn->flags.readMore) {
73c36fd9 1639 debugs(33, 3, HERE << conn->clientConnection << ": calling conn->readNextRequest()");
f900210a 1640 conn->readNextRequest();
f35961af
AR
1641 } else {
1642 // XXX: Can this happen? CONNECT tunnels have deferredRequest set.
1b76e6c1 1643 debugs(33, DBG_IMPORTANT, HERE << "abandoning " << conn->clientConnection);
f900210a 1644 }
1a92a1e2 1645}
1646
c8be6d7b 1647void
02c8dde5 1648clientUpdateSocketStats(LogTags logType, size_t size)
c8be6d7b 1649{
1650 if (size == 0)
62e76326 1651 return;
1652
c8be6d7b 1653 kb_incr(&statCounter.client_http.kbytes_out, size);
62e76326 1654
c8be6d7b 1655 if (logTypeIsATcpHit(logType))
62e76326 1656 kb_incr(&statCounter.client_http.hit_kbytes_out, size);
c8be6d7b 1657}
1658
63be0a78 1659/**
528b2c61 1660 * increments iterator "i"
63be0a78 1661 * used by clientPackMoreRanges
1662 *
1663 \retval true there is still data available to pack more ranges
9e008dda 1664 \retval false
63be0a78 1665 */
528b2c61 1666bool
1667ClientSocketContext::canPackMoreRanges() const
1668{
63be0a78 1669 /** first update iterator "i" if needed */
62e76326 1670
528b2c61 1671 if (!http->range_iter.debt()) {
73c36fd9 1672 debugs(33, 5, HERE << "At end of current range spec for " << clientConnection);
62e76326 1673
1674 if (http->range_iter.pos.incrementable())
1675 ++http->range_iter.pos;
1676
1677 http->range_iter.updateSpec();
528b2c61 1678 }
62e76326 1679
528b2c61 1680 assert(!http->range_iter.debt() == !http->range_iter.currentSpec());
63be0a78 1681
528b2c61 1682 /* paranoid sync condition */
1683 /* continue condition: need_more_data */
bf8fe701 1684 debugs(33, 5, "ClientSocketContext::canPackMoreRanges: returning " << (http->range_iter.currentSpec() ? true : false));
528b2c61 1685 return http->range_iter.currentSpec() ? true : false;
1686}
1687
47f6e231 1688int64_t
528b2c61 1689ClientSocketContext::getNextRangeOffset() const
1690{
1691 if (http->request->range) {
62e76326 1692 /* offset in range specs does not count the prefix of an http msg */
47f6e231 1693 debugs (33, 5, "ClientSocketContext::getNextRangeOffset: http offset " << http->out.offset);
62e76326 1694 /* check: reply was parsed and range iterator was initialized */
1695 assert(http->range_iter.valid);
1696 /* filter out data according to range specs */
1697 assert (canPackMoreRanges());
1698 {
47f6e231 1699 int64_t start; /* offset of still missing data */
62e76326 1700 assert(http->range_iter.currentSpec());
1701 start = http->range_iter.currentSpec()->offset + http->range_iter.currentSpec()->length - http->range_iter.debt();
47f6e231 1702 debugs(33, 3, "clientPackMoreRanges: in: offset: " << http->out.offset);
1703 debugs(33, 3, "clientPackMoreRanges: out:"
9e008dda
AJ
1704 " start: " << start <<
1705 " spec[" << http->range_iter.pos - http->request->range->begin() << "]:" <<
1706 " [" << http->range_iter.currentSpec()->offset <<
1707 ", " << http->range_iter.currentSpec()->offset + http->range_iter.currentSpec()->length << "),"
1708 " len: " << http->range_iter.currentSpec()->length <<
1709 " debt: " << http->range_iter.debt());
62e76326 1710 if (http->range_iter.currentSpec()->length != -1)
1711 assert(http->out.offset <= start); /* we did not miss it */
1712
1713 return start;
1714 }
1715
fedd1531 1716 } else if (reply && reply->content_range) {
1717 /* request does not have ranges, but reply does */
63be0a78 1718 /** \todo FIXME: should use range_iter_pos on reply, as soon as reply->content_range
1719 * becomes HttpHdrRange rather than HttpHdrRangeSpec.
1720 */
fedd1531 1721 return http->out.offset + reply->content_range->spec.offset;
528b2c61 1722 }
1723
1724 return http->out.offset;
1725}
1726
c8be6d7b 1727void
528b2c61 1728ClientSocketContext::pullData()
c8be6d7b 1729{
73c36fd9 1730 debugs(33, 5, HERE << clientConnection << " attempting to pull upstream data");
bf8fe701 1731
c8be6d7b 1732 /* More data will be coming from the stream. */
528b2c61 1733 StoreIOBuffer readBuffer;
1734 /* XXX: Next requested byte in the range sequence */
1735 /* XXX: length = getmaximumrangelenfgth */
1736 readBuffer.offset = getNextRangeOffset();
c8be6d7b 1737 readBuffer.length = HTTP_REQBUF_SZ;
528b2c61 1738 readBuffer.data = reqbuf;
1739 /* we may note we have reached the end of the wanted ranges */
1740 clientStreamRead(getTail(), http, readBuffer);
1741}
1742
62e76326 1743clientStream_status_t
528b2c61 1744ClientSocketContext::socketState()
1745{
1746 switch (clientStreamStatus(getTail(), http)) {
62e76326 1747
1748 case STREAM_NONE:
528b2c61 1749 /* check for range support ending */
62e76326 1750
528b2c61 1751 if (http->request->range) {
62e76326 1752 /* check: reply was parsed and range iterator was initialized */
1753 assert(http->range_iter.valid);
1754 /* filter out data according to range specs */
1755
1756 if (!canPackMoreRanges()) {
920ba08d 1757 debugs(33, 5, HERE << "Range request at end of returnable " <<
73c36fd9 1758 "range sequence on " << clientConnection);
62e76326 1759
450fe1cb 1760 if (http->request->flags.proxyKeepalive)
62e76326 1761 return STREAM_COMPLETE;
1762 else
1763 return STREAM_UNPLANNED_COMPLETE;
1764 }
fedd1531 1765 } else if (reply && reply->content_range) {
425802c8 1766 /* reply has content-range, but Squid is not managing ranges */
1767 const int64_t &bytesSent = http->out.offset;
1768 const int64_t &bytesExpected = reply->content_range->spec.length;
fedd1531 1769
425802c8 1770 debugs(33, 7, HERE << "body bytes sent vs. expected: " <<
9e008dda
AJ
1771 bytesSent << " ? " << bytesExpected << " (+" <<
1772 reply->content_range->spec.offset << ")");
425802c8 1773
1774 // did we get at least what we expected, based on range specs?
1775
65058d64 1776 if (bytesSent == bytesExpected) { // got everything
450fe1cb 1777 if (http->request->flags.proxyKeepalive)
65058d64
CT
1778 return STREAM_COMPLETE;
1779 else
1780 return STREAM_UNPLANNED_COMPLETE;
1781 }
425802c8 1782
1783 // The logic below is not clear: If we got more than we
1784 // expected why would persistency matter? Should not this
1785 // always be an error?
1786 if (bytesSent > bytesExpected) { // got extra
450fe1cb 1787 if (http->request->flags.proxyKeepalive)
fedd1531 1788 return STREAM_COMPLETE;
1789 else
1790 return STREAM_UNPLANNED_COMPLETE;
1791 }
425802c8 1792
1793 // did not get enough yet, expecting more
62e76326 1794 }
1795
1796 return STREAM_NONE;
1797
1798 case STREAM_COMPLETE:
528b2c61 1799 return STREAM_COMPLETE;
62e76326 1800
1801 case STREAM_UNPLANNED_COMPLETE:
1802 return STREAM_UNPLANNED_COMPLETE;
1803
1804 case STREAM_FAILED:
1805 return STREAM_FAILED;
528b2c61 1806 }
62e76326 1807
528b2c61 1808 fatal ("unreachable code\n");
1809 return STREAM_NONE;
c8be6d7b 1810}
edce4d98 1811
63be0a78 1812/**
1813 * A write has just completed to the client, or we have just realised there is
edce4d98 1814 * no more data to send.
1815 */
e6ccf245 1816void
e0d28505 1817clientWriteComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag, int xerrno, void *data)
7a2f978b 1818{
528b2c61 1819 ClientSocketContext *context = (ClientSocketContext *)data;
e0d28505 1820 context->writeComplete(conn, bufnotused, size, errflag);
0655fa4d 1821}
1822
f692498b
AJ
1823/// remembers the abnormal connection termination for logging purposes
1824void
1825ClientSocketContext::noteIoError(const int xerrno)
1826{
1827 if (http) {
1828 if (xerrno == ETIMEDOUT)
41ebd397 1829 http->al->http.timedout = true;
f692498b 1830 else // even if xerrno is zero (which means read abort/eof)
41ebd397 1831 http->al->http.aborted = true;
f692498b
AJ
1832 }
1833}
1834
55e44db9 1835void
1836ClientSocketContext::doClose()
1837{
73c36fd9 1838 clientConnection->close();
55e44db9 1839}
1840
cf6eb29e 1841/// called when we encounter a response-related error
55e44db9 1842void
5f8252d2 1843ClientSocketContext::initiateClose(const char *reason)
55e44db9 1844{
cf6eb29e
CT
1845 http->getConn()->stopSending(reason); // closes ASAP
1846}
5f8252d2 1847
cf6eb29e
CT
1848void
1849ConnStateData::stopSending(const char *error)
1850{
1851 debugs(33, 4, HERE << "sending error (" << clientConnection << "): " << error <<
1852 "; old receiving error: " <<
1853 (stoppedReceiving() ? stoppedReceiving_ : "none"));
fc68f6b1 1854
cf6eb29e
CT
1855 if (const char *oldError = stoppedSending()) {
1856 debugs(33, 3, HERE << "already stopped sending: " << oldError);
1857 return; // nothing has changed as far as this connection is concerned
1858 }
1859 stoppedSending_ = error;
fc68f6b1 1860
cf6eb29e
CT
1861 if (!stoppedReceiving()) {
1862 if (const int64_t expecting = mayNeedToReadMoreBody()) {
1863 debugs(33, 5, HERE << "must still read " << expecting <<
1864 " request body bytes with " << in.notYetUsed << " unused");
1865 return; // wait for the request receiver to finish reading
3b299123 1866 }
55e44db9 1867 }
1868
cf6eb29e 1869 clientConnection->close();
55e44db9 1870}
1871
0655fa4d 1872void
e0d28505 1873ClientSocketContext::writeComplete(const Comm::ConnectionPointer &conn, char *bufnotused, size_t size, comm_err_t errflag)
0655fa4d 1874{
5ad038e1 1875 const StoreEntry *entry = http->storeEntry();
7a2f978b 1876 http->out.size += size;
e0d28505 1877 debugs(33, 5, HERE << conn << ", sz " << size <<
e4049756 1878 ", err " << errflag << ", off " << http->out.size << ", len " <<
5ad038e1 1879 (entry ? entry->objectLen() : 0));
c8be6d7b 1880 clientUpdateSocketStats(http->logType, size);
62e76326 1881
5f8252d2 1882 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
fc68f6b1 1883
24bf76b5 1884 if (errflag == COMM_ERR_CLOSING || !Comm::IsConnOpen(conn))
5f8252d2 1885 return;
1886
e0d28505 1887 if (errflag || clientHttpRequestStatus(conn->fd, http)) {
5f8252d2 1888 initiateClose("failure or true request status");
62e76326 1889 /* Do we leak here ? */
1890 return;
edce4d98 1891 }
62e76326 1892
0655fa4d 1893 switch (socketState()) {
62e76326 1894
edce4d98 1895 case STREAM_NONE:
0655fa4d 1896 pullData();
62e76326 1897 break;
1898
edce4d98 1899 case STREAM_COMPLETE:
e0d28505 1900 debugs(33, 5, HERE << conn << " Keeping Alive");
0655fa4d 1901 keepaliveNextRequest();
62e76326 1902 return;
1903
edce4d98 1904 case STREAM_UNPLANNED_COMPLETE:
6e1d409c
AR
1905 initiateClose("STREAM_UNPLANNED_COMPLETE");
1906 return;
62e76326 1907
edce4d98 1908 case STREAM_FAILED:
6e1d409c 1909 initiateClose("STREAM_FAILED");
62e76326 1910 return;
1911
edce4d98 1912 default:
62e76326 1913 fatal("Hit unreachable code in clientWriteComplete\n");
7a2f978b 1914 }
1915}
1916
82afb125
FC
1917SQUIDCEXTERN CSR clientGetMoreData;
1918SQUIDCEXTERN CSS clientReplyStatus;
1919SQUIDCEXTERN CSD clientReplyDetach;
edce4d98 1920
528b2c61 1921static ClientSocketContext *
be364179 1922parseHttpRequestAbort(ConnStateData * csd, const char *uri)
038eb4ed 1923{
59a1efb2 1924 ClientHttpRequest *http;
528b2c61 1925 ClientSocketContext *context;
1926 StoreIOBuffer tempBuffer;
be364179
AJ
1927 http = new ClientHttpRequest(csd);
1928 http->req_sz = csd->in.notYetUsed;
edce4d98 1929 http->uri = xstrdup(uri);
c4b7a5a9 1930 setLogUri (http, uri);
73c36fd9 1931 context = ClientSocketContextNew(csd->clientConnection, http);
c8be6d7b 1932 tempBuffer.data = context->reqbuf;
1933 tempBuffer.length = HTTP_REQBUF_SZ;
edce4d98 1934 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 1935 clientReplyStatus, new clientReplyContext(http), clientSocketRecipient,
62e76326 1936 clientSocketDetach, context, tempBuffer);
edce4d98 1937 return context;
038eb4ed 1938}
1939
c8be6d7b 1940char *
1941skipLeadingSpace(char *aString)
1942{
1943 char *result = aString;
62e76326 1944
c8be6d7b 1945 while (xisspace(*aString))
62e76326 1946 ++aString;
1947
c8be6d7b 1948 return result;
1949}
1950
63be0a78 1951/**
d4a04ed5 1952 * 'end' defaults to NULL for backwards compatibility
1953 * remove default value if we ever get rid of NULL-terminated
1954 * request buffers.
1955 */
1956const char *
1957findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end)
c8be6d7b 1958{
d4a04ed5 1959 if (NULL == end) {
1960 end = uriAndHTTPVersion + strcspn(uriAndHTTPVersion, "\r\n");
1961 assert(end);
1962 }
62e76326 1963
5e263176 1964 for (; end > uriAndHTTPVersion; --end) {
d4a04ed5 1965 if (*end == '\n' || *end == '\r')
62e76326 1966 continue;
1967
d4a04ed5 1968 if (xisspace(*end)) {
1969 if (strncasecmp(end + 1, "HTTP/", 5) == 0)
1970 return end + 1;
62e76326 1971 else
1972 break;
1973 }
c8be6d7b 1974 }
62e76326 1975
3f38a55e 1976 return NULL;
c8be6d7b 1977}
1978
c8be6d7b 1979void
727552f4 1980setLogUri(ClientHttpRequest * http, char const *uri, bool cleanUrl)
c8be6d7b 1981{
a46d0227 1982 safe_free(http->log_uri);
62e76326 1983
727552f4
CT
1984 if (!cleanUrl)
1985 // The uri is already clean just dump it.
62e76326 1986 http->log_uri = xstrndup(uri, MAX_URL);
727552f4 1987 else {
2bea559d
A
1988 int flags = 0;
1989 switch (Config.uri_whitespace) {
1990 case URI_WHITESPACE_ALLOW:
1991 flags |= RFC1738_ESCAPE_NOSPACE;
1992
1993 case URI_WHITESPACE_ENCODE:
1994 flags |= RFC1738_ESCAPE_UNESCAPED;
1995 http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL);
1996 break;
727552f4 1997
2bea559d
A
1998 case URI_WHITESPACE_CHOP: {
1999 flags |= RFC1738_ESCAPE_NOSPACE;
2000 flags |= RFC1738_ESCAPE_UNESCAPED;
2001 http->log_uri = xstrndup(rfc1738_do_escape(uri, flags), MAX_URL);
2002 int pos = strcspn(http->log_uri, w_space);
2003 http->log_uri[pos] = '\0';
2004 }
2005 break;
2006
2007 case URI_WHITESPACE_DENY:
2008 case URI_WHITESPACE_STRIP:
2009 default: {
2010 const char *t;
2011 char *tmp_uri = static_cast<char*>(xmalloc(strlen(uri) + 1));
2012 char *q = tmp_uri;
2013 t = uri;
2014 while (*t) {
a38ec4b1
FC
2015 if (!xisspace(*t)) {
2016 *q = *t;
2017 ++q;
2018 }
95dc7ff4 2019 ++t;
727552f4 2020 }
2bea559d
A
2021 *q = '\0';
2022 http->log_uri = xstrndup(rfc1738_escape_unescaped(tmp_uri), MAX_URL);
2023 xfree(tmp_uri);
2024 }
2025 break;
2026 }
727552f4 2027 }
c8be6d7b 2028}
2029
3f38a55e 2030static void
1cf238db 2031prepareAcceleratedURL(ConnStateData * conn, ClientHttpRequest *http, char *url, const char *req_hdr)
62e76326 2032{
3f38a55e 2033 int vhost = conn->port->vhost;
2034 int vport = conn->port->vport;
2035 char *host;
de12d836 2036 char ipbuf[MAX_IPSTRLEN];
c8be6d7b 2037
be4d35dc 2038 http->flags.accel = true;
c8be6d7b 2039
3f38a55e 2040 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
c8be6d7b 2041
34399323 2042 if (strncasecmp(url, "cache_object://", 15) == 0)
2043 return; /* already in good shape */
2044
3f38a55e 2045 if (*url != '/') {
62e76326 2046 if (conn->port->vhost)
2047 return; /* already in good shape */
2048
2049 /* else we need to ignore the host name */
2050 url = strstr(url, "//");
2051
3f38a55e 2052#if SHOULD_REJECT_UNKNOWN_URLS
62e76326 2053
719c7e0a
AJ
2054 if (!url) {
2055 hp->request_parse_status = HTTP_BAD_REQUEST;
62e76326 2056 return parseHttpRequestAbort(conn, "error:invalid-request");
719c7e0a 2057 }
c8be6d7b 2058#endif
62e76326 2059
2060 if (url)
2061 url = strchr(url + 2, '/');
2062
2063 if (!url)
2064 url = (char *) "/";
3f38a55e 2065 }
2066
5463e4b9
AJ
2067 if (vport < 0)
2068 vport = http->getConn()->clientConnection->local.GetPort();
2069
ae7ff0b8 2070 const bool switchedToHttps = conn->switchedToHttps();
2071 const bool tryHostHeader = vhost || switchedToHttps;
2072 if (tryHostHeader && (host = mime_get_header(req_hdr, "Host")) != NULL) {
5463e4b9
AJ
2073 debugs(33, 5, "ACCEL VHOST REWRITE: vhost=" << host << " + vport=" << vport);
2074 char thost[256];
2075 if (vport > 0) {
2076 thost[0] = '\0';
2077 char *t = NULL;
2078 if (host[strlen(host)] != ']' && (t = strrchr(host,':')) != NULL) {
2079 strncpy(thost, host, (t-host));
2080 snprintf(thost+(t-host), sizeof(thost)-(t-host), ":%d", vport);
2081 host = thost;
2082 } else if (!t) {
2083 snprintf(thost, sizeof(thost), "%s:%d",host, vport);
2084 host = thost;
2085 }
2086 } // else nothing to alter port-wise.
62e76326 2087 int url_sz = strlen(url) + 32 + Config.appendDomainLen +
2088 strlen(host);
2089 http->uri = (char *)xcalloc(url_sz, 1);
ae7ff0b8 2090 const char *protocol = switchedToHttps ?
9e008dda 2091 "https" : conn->port->protocol;
ae7ff0b8 2092 snprintf(http->uri, url_sz, "%s://%s%s", protocol, host, url);
bf8fe701 2093 debugs(33, 5, "ACCEL VHOST REWRITE: '" << http->uri << "'");
5463e4b9
AJ
2094 } else if (conn->port->defaultsite /* && !vhost */) {
2095 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: defaultsite=" << conn->port->defaultsite << " + vport=" << vport);
62e76326 2096 int url_sz = strlen(url) + 32 + Config.appendDomainLen +
2097 strlen(conn->port->defaultsite);
2098 http->uri = (char *)xcalloc(url_sz, 1);
5463e4b9
AJ
2099 char vportStr[32];
2100 vportStr[0] = '\0';
2101 if (vport > 0) {
2102 snprintf(vportStr, sizeof(vportStr),":%d",vport);
2103 }
2104 snprintf(http->uri, url_sz, "%s://%s%s%s",
2105 conn->port->protocol, conn->port->defaultsite, vportStr, url);
bf8fe701 2106 debugs(33, 5, "ACCEL DEFAULTSITE REWRITE: '" << http->uri <<"'");
5463e4b9
AJ
2107 } else if (vport > 0 /* && (!vhost || no Host:) */) {
2108 debugs(33, 5, "ACCEL VPORT REWRITE: http_port IP + vport=" << vport);
2109 /* Put the local socket IP address as the hostname, with whatever vport we found */
62e76326 2110 int url_sz = strlen(url) + 32 + Config.appendDomainLen;
2111 http->uri = (char *)xcalloc(url_sz, 1);
73c36fd9 2112 http->getConn()->clientConnection->local.ToHostname(ipbuf,MAX_IPSTRLEN);
62e76326 2113 snprintf(http->uri, url_sz, "%s://%s:%d%s",
98242069 2114 http->getConn()->port->protocol,
de12d836 2115 ipbuf, vport, url);
bf8fe701 2116 debugs(33, 5, "ACCEL VPORT REWRITE: '" << http->uri << "'");
3f38a55e 2117 }
2118}
2119
2120static void
1cf238db 2121prepareTransparentURL(ConnStateData * conn, ClientHttpRequest *http, char *url, const char *req_hdr)
62e76326 2122{
3f38a55e 2123 char *host;
de12d836 2124 char ipbuf[MAX_IPSTRLEN];
3f38a55e 2125
3f38a55e 2126 if (*url != '/')
62e76326 2127 return; /* already in good shape */
3f38a55e 2128
2129 /* BUG: Squid cannot deal with '*' URLs (RFC2616 5.1.2) */
2130
f024c970 2131 if ((host = mime_get_header(req_hdr, "Host")) != NULL) {
62e76326 2132 int url_sz = strlen(url) + 32 + Config.appendDomainLen +
2133 strlen(host);
2134 http->uri = (char *)xcalloc(url_sz, 1);
60b2e919 2135 snprintf(http->uri, url_sz, "%s://%s%s", conn->port->protocol, host, url);
bf8fe701 2136 debugs(33, 5, "TRANSPARENT HOST REWRITE: '" << http->uri <<"'");
c8be6d7b 2137 } else {
62e76326 2138 /* Put the local socket IP address as the hostname. */
2139 int url_sz = strlen(url) + 32 + Config.appendDomainLen;
2140 http->uri = (char *)xcalloc(url_sz, 1);
60b2e919
CT
2141 http->getConn()->clientConnection->local.ToHostname(ipbuf,MAX_IPSTRLEN);
2142 snprintf(http->uri, url_sz, "%s://%s:%d%s",
2143 http->getConn()->port->protocol,
73c36fd9 2144 ipbuf, http->getConn()->clientConnection->local.GetPort(), url);
bf8fe701 2145 debugs(33, 5, "TRANSPARENT REWRITE: '" << http->uri << "'");
c8be6d7b 2146 }
c8be6d7b 2147}
2148
7830d88a 2149/** Parse an HTTP request
9e008dda 2150 *
7830d88a
FC
2151 * \note Sets result->flags.parsed_ok to 0 if failed to parse the request,
2152 * to 1 if the request was correctly parsed.
2153 * \param[in] csd a ConnStateData. The caller must make sure it is not null
2154 * \param[in] hp an HttpParser
2155 * \param[out] mehtod_p will be set as a side-effect of the parsing.
2156 * Pointed-to value will be set to Http::METHOD_NONE in case of
2157 * parsing failure
2158 * \param[out] http_ver will be set as a side-effect of the parsing
2159 * \return NULL on incomplete requests,
2160 * a ClientSocketContext structure on success or failure.
7a2f978b 2161 */
528b2c61 2162static ClientSocketContext *
be364179 2163parseHttpRequest(ConnStateData *csd, HttpParser *hp, HttpRequestMethod * method_p, HttpVersion *http_ver)
7a2f978b 2164{
7a2f978b 2165 char *req_hdr = NULL;
2334c194 2166 char *end;
c68e9c6b 2167 size_t req_sz;
59a1efb2 2168 ClientHttpRequest *http;
528b2c61 2169 ClientSocketContext *result;
2170 StoreIOBuffer tempBuffer;
84cc2635 2171 int r;
7a2f978b 2172
6792f0d3 2173 /* pre-set these values to make aborting simpler */
c2a7cefd 2174 *method_p = Http::METHOD_NONE;
6792f0d3 2175
7ed7d3da
AJ
2176 /* NP: don't be tempted to move this down or remove again.
2177 * It's the only DDoS protection old-String has against long URL */
2178 if ( hp->bufsiz <= 0) {
2179 debugs(33, 5, "Incomplete request, waiting for end of request line");
2180 return NULL;
e1381638 2181 } else if ( (size_t)hp->bufsiz >= Config.maxRequestHeaderSize && headersEnd(hp->buf, Config.maxRequestHeaderSize) == 0) {
7ed7d3da 2182 debugs(33, 5, "parseHttpRequest: Too large request");
719c7e0a 2183 hp->request_parse_status = HTTP_HEADER_TOO_LARGE;
be364179 2184 return parseHttpRequestAbort(csd, "error:request-too-large");
7ed7d3da
AJ
2185 }
2186
84cc2635 2187 /* Attempt to parse the first line; this'll define the method, url, version and header begin */
2188 r = HttpParserParseReqLine(hp);
fc68f6b1 2189
84cc2635 2190 if (r == 0) {
bf8fe701 2191 debugs(33, 5, "Incomplete request, waiting for end of request line");
fc68f6b1 2192 return NULL;
7a2f978b 2193 }
fc68f6b1 2194
84cc2635 2195 if (r == -1) {
be364179 2196 return parseHttpRequestAbort(csd, "error:invalid-request");
84cc2635 2197 }
fc68f6b1 2198
84cc2635 2199 /* Request line is valid here .. */
74f478f8 2200 *http_ver = HttpVersion(hp->req.v_maj, hp->req.v_min);
62e76326 2201
52512f28 2202 /* This call scans the entire request, not just the headers */
74f478f8 2203 if (hp->req.v_maj > 0) {
a5baffba 2204 if ((req_sz = headersEnd(hp->buf, hp->bufsiz)) == 0) {
bf8fe701 2205 debugs(33, 5, "Incomplete request, waiting for end of headers");
62e76326 2206 return NULL;
2207 }
3f38a55e 2208 } else {
bf8fe701 2209 debugs(33, 3, "parseHttpRequest: Missing HTTP identifier");
84cc2635 2210 req_sz = HttpParserReqSz(hp);
3f38a55e 2211 }
2212
bb790702 2213 /* We know the whole request is in hp->buf now */
52512f28 2214
a5baffba 2215 assert(req_sz <= (size_t) hp->bufsiz);
fc68f6b1 2216
a5baffba 2217 /* Will the following be true with HTTP/0.9 requests? probably not .. */
2218 /* So the rest of the code will need to deal with '0'-byte headers (ie, none, so don't try parsing em) */
2219 assert(req_sz > 0);
fc68f6b1 2220
a5baffba 2221 hp->hdr_end = req_sz - 1;
fc68f6b1 2222
74f478f8 2223 hp->hdr_start = hp->req.end + 1;
3f38a55e 2224
5b648f60 2225 /* Enforce max_request_size */
5b648f60 2226 if (req_sz >= Config.maxRequestHeaderSize) {
bf8fe701 2227 debugs(33, 5, "parseHttpRequest: Too large request");
719c7e0a 2228 hp->request_parse_status = HTTP_HEADER_TOO_LARGE;
be364179 2229 return parseHttpRequestAbort(csd, "error:request-too-large");
5b648f60 2230 }
2231
84cc2635 2232 /* Set method_p */
74f478f8 2233 *method_p = HttpRequestMethod(&hp->buf[hp->req.m_start], &hp->buf[hp->req.m_end]+1);
fc68f6b1 2234
adf29627 2235 /* deny CONNECT via accelerated ports */
6a25a046 2236 if (*method_p == Http::METHOD_CONNECT && csd->port && csd->port->flags.accelSurrogate) {
be364179 2237 debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << csd->port->protocol << " Accelerator port " << csd->port->s.GetPort() );
adf29627
AJ
2238 /* XXX need a way to say "this many character length string" */
2239 debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->buf);
719c7e0a 2240 hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED;
be364179 2241 return parseHttpRequestAbort(csd, "error:method-not-allowed");
adf29627
AJ
2242 }
2243
c2a7cefd 2244 if (*method_p == Http::METHOD_NONE) {
fc68f6b1 2245 /* XXX need a way to say "this many character length string" */
e0236918 2246 debugs(33, DBG_IMPORTANT, "clientParseRequestMethod: Unsupported method in request '" << hp->buf << "'");
719c7e0a 2247 hp->request_parse_status = HTTP_METHOD_NOT_ALLOWED;
be364179 2248 return parseHttpRequestAbort(csd, "error:unsupported-request-method");
3f38a55e 2249 }
7a2f978b 2250
c68e9c6b 2251 /*
2252 * Process headers after request line
c8be6d7b 2253 * TODO: Use httpRequestParse here.
c68e9c6b 2254 */
84cc2635 2255 /* XXX this code should be modified to take a const char * later! */
74f478f8 2256 req_hdr = (char *) hp->buf + hp->req.end + 1;
fc68f6b1 2257
bf8fe701 2258 debugs(33, 3, "parseHttpRequest: req_hdr = {" << req_hdr << "}");
fc68f6b1 2259
52512f28 2260 end = (char *) hp->buf + hp->hdr_end;
fc68f6b1 2261
bf8fe701 2262 debugs(33, 3, "parseHttpRequest: end = {" << end << "}");
99edd1c3 2263
bf8fe701 2264 debugs(33, 3, "parseHttpRequest: prefix_sz = " <<
2265 (int) HttpParserRequestLen(hp) << ", req_line_sz = " <<
2266 HttpParserReqSz(hp));
62e76326 2267
7a2f978b 2268 /* Ok, all headers are received */
be364179 2269 http = new ClientHttpRequest(csd);
62e76326 2270
a5baffba 2271 http->req_sz = HttpParserRequestLen(hp);
73c36fd9 2272 result = ClientSocketContextNew(csd->clientConnection, http);
c8be6d7b 2273 tempBuffer.data = result->reqbuf;
2274 tempBuffer.length = HTTP_REQBUF_SZ;
62e76326 2275
0655fa4d 2276 ClientStreamData newServer = new clientReplyContext(http);
0655fa4d 2277 ClientStreamData newClient = result;
edce4d98 2278 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 2279 clientReplyStatus, newServer, clientSocketRecipient,
2280 clientSocketDetach, newClient, tempBuffer);
62e76326 2281
bf8fe701 2282 debugs(33, 5, "parseHttpRequest: Request Header is\n" <<(hp->buf) + hp->hdr_start);
3f38a55e 2283
3ff65596
AR
2284 /* set url */
2285 /*
2286 * XXX this should eventually not use a malloc'ed buffer; the transformation code
2287 * below needs to be modified to not expect a mutable nul-terminated string.
2288 */
74f478f8 2289 char *url = (char *)xmalloc(hp->req.u_end - hp->req.u_start + 16);
3ff65596 2290
74f478f8 2291 memcpy(url, hp->buf + hp->req.u_start, hp->req.u_end - hp->req.u_start + 1);
3ff65596 2292
74f478f8 2293 url[hp->req.u_end - hp->req.u_start + 1] = '\0';
3ff65596 2294
ba9ebd0a 2295#if THIS_VIOLATES_HTTP_SPECS_ON_URL_TRANSFORMATION
62e76326 2296
7a2f978b 2297 if ((t = strchr(url, '#'))) /* remove HTML anchors */
62e76326 2298 *t = '\0';
2299
ba9ebd0a 2300#endif
7a2f978b 2301
6a25a046 2302 debugs(33,5, HERE << "repare absolute URL from " <<
2ee34428 2303 (csd->transparent()?"intercept":(csd->port->flags.accelSurrogate ? "accel":"")));
3f38a55e 2304 /* Rewrite the URL in transparent or accelerator mode */
89272111
AJ
2305 /* NP: there are several cases to traverse here:
2306 * - standard mode (forward proxy)
2307 * - transparent mode (TPROXY)
2308 * - transparent mode with failures
2309 * - intercept mode (NAT)
2310 * - intercept mode with failures
2311 * - accelerator mode (reverse proxy)
2312 * - internal URL
2313 * - mixed combos of the above with internal URL
2314 */
be364179 2315 if (csd->transparent()) {
89272111 2316 /* intercept or transparent mode, properly working with no failures */
be364179 2317 prepareTransparentURL(csd, http, url, req_hdr);
89272111 2318
2f2749d7 2319 } else if (internalCheck(url)) {
89272111 2320 /* internal URL mode */
2f2749d7 2321 /* prepend our name & port */
2322 http->uri = xstrdup(internalLocalUri(NULL, url));
59c59acf
AJ
2323 // We just re-wrote the URL. Must replace the Host: header.
2324 // But have not parsed there yet!! flag for local-only handling.
be4d35dc 2325 http->flags.internal = true;
59c59acf 2326
6a25a046 2327 } else if (csd->port->flags.accelSurrogate || csd->switchedToHttps()) {
59c59acf
AJ
2328 /* accelerator mode */
2329 prepareAcceleratedURL(csd, http, url, req_hdr);
3f38a55e 2330 }
2331
2332 if (!http->uri) {
62e76326 2333 /* No special rewrites have been applied above, use the
2334 * requested url. may be rewritten later, so make extra room */
2335 int url_sz = strlen(url) + Config.appendDomainLen + 5;
2336 http->uri = (char *)xcalloc(url_sz, 1);
2337 strcpy(http->uri, url);
3f38a55e 2338 }
62e76326 2339
bf8fe701 2340 debugs(33, 5, "parseHttpRequest: Complete request received");
1ce34ddd
AJ
2341
2342 // XXX: crop this dump at the end of headers. No need for extras
2343 debugs(11, 2, "HTTP Client " << csd->clientConnection);
2344 debugs(11, 2, "HTTP Client REQUEST:\n---------\n" << (hp->buf) + hp->req.m_start << "\n----------");
2345
c4b7a5a9 2346 result->flags.parsed_ok = 1;
84cc2635 2347 xfree(url);
c8be6d7b 2348 return result;
7a2f978b 2349}
2350
c8be6d7b 2351int
a46d2c0e 2352ConnStateData::getAvailableBufferLength() const
c8be6d7b 2353{
f5f9e44c
AR
2354 assert (in.allocatedSize > in.notYetUsed); // allocated more than used
2355 const size_t result = in.allocatedSize - in.notYetUsed - 1;
2356 // huge request_header_max_size may lead to more than INT_MAX unused space
2357 assert (static_cast<ssize_t>(result) <= INT_MAX);
1a419b96 2358 return result;
c8be6d7b 2359}
2360
1368d115
CT
2361bool
2362ConnStateData::maybeMakeSpaceAvailable()
c8be6d7b 2363{
a46d2c0e 2364 if (getAvailableBufferLength() < 2) {
90737510
A
2365 size_t newSize;
2366 if (in.allocatedSize >= Config.maxRequestBufferSize) {
2367 debugs(33, 4, "request buffer full: client_request_buffer_max_size=" << Config.maxRequestBufferSize);
2368 return false;
2369 }
2370 if ((newSize=in.allocatedSize * 2) > Config.maxRequestBufferSize) {
2371 newSize=Config.maxRequestBufferSize;
2372 }
2373 in.buf = (char *)memReallocBuf(in.buf, newSize, &in.allocatedSize);
2374 debugs(33, 2, "growing request buffer: notYetUsed=" << in.notYetUsed << " size=" << in.allocatedSize);
c8be6d7b 2375 }
1368d115 2376 return true;
c8be6d7b 2377}
2378
2379void
0655fa4d 2380ConnStateData::addContextToQueue(ClientSocketContext * context)
c8be6d7b 2381{
0655fa4d 2382 ClientSocketContext::Pointer *S;
62e76326 2383
0655fa4d 2384 for (S = (ClientSocketContext::Pointer *) & currentobject; S->getRaw();
3d0ac046 2385 S = &(*S)->next);
c8be6d7b 2386 *S = context;
62e76326 2387
0655fa4d 2388 ++nrequests;
c8be6d7b 2389}
2390
2391int
0655fa4d 2392ConnStateData::getConcurrentRequestCount() const
c8be6d7b 2393{
2394 int result = 0;
0655fa4d 2395 ClientSocketContext::Pointer *T;
62e76326 2396
0655fa4d 2397 for (T = (ClientSocketContext::Pointer *) &currentobject;
3d0ac046 2398 T->getRaw(); T = &(*T)->next, ++result);
c8be6d7b 2399 return result;
2400}
2401
2402int
1cf238db 2403ConnStateData::connReadWasError(comm_err_t flag, int size, int xerrno)
c8be6d7b 2404{
c4b7a5a9 2405 if (flag != COMM_OK) {
73c36fd9 2406 debugs(33, 2, "connReadWasError: FD " << clientConnection << ": got flag " << flag);
62e76326 2407 return 1;
c4b7a5a9 2408 }
62e76326 2409
c8be6d7b 2410 if (size < 0) {
f3400a93 2411 if (!ignoreErrno(xerrno)) {
73c36fd9 2412 debugs(33, 2, "connReadWasError: FD " << clientConnection << ": " << xstrerr(xerrno));
62e76326 2413 return 1;
1cf238db 2414 } else if (in.notYetUsed == 0) {
73c36fd9 2415 debugs(33, 2, "connReadWasError: FD " << clientConnection << ": no data to process (" << xstrerr(xerrno) << ")");
62e76326 2416 }
c8be6d7b 2417 }
62e76326 2418
c8be6d7b 2419 return 0;
2420}
2421
2422int
1cf238db 2423ConnStateData::connFinishedWithConn(int size)
c8be6d7b 2424{
2425 if (size == 0) {
1cf238db 2426 if (getConcurrentRequestCount() == 0 && in.notYetUsed == 0) {
62e76326 2427 /* no current or pending requests */
73c36fd9 2428 debugs(33, 4, HERE << clientConnection << " closed");
62e76326 2429 return 1;
2430 } else if (!Config.onoff.half_closed_clients) {
2431 /* admin doesn't want to support half-closed client sockets */
73c36fd9 2432 debugs(33, 3, HERE << clientConnection << " aborted (half_closed_clients disabled)");
f692498b 2433 notifyAllContexts(0); // no specific error implies abort
62e76326 2434 return 1;
2435 }
c8be6d7b 2436 }
62e76326 2437
c8be6d7b 2438 return 0;
2439}
2440
2441void
3b299123 2442connNoteUseOfBuffer(ConnStateData* conn, size_t byteCount)
c8be6d7b 2443{
2444 assert(byteCount > 0 && byteCount <= conn->in.notYetUsed);
2445 conn->in.notYetUsed -= byteCount;
d5fa7219 2446 debugs(33, 5, HERE << "conn->in.notYetUsed = " << conn->in.notYetUsed);
c8be6d7b 2447 /*
9e008dda 2448 * If there is still data that will be used,
c8be6d7b 2449 * move it to the beginning.
2450 */
62e76326 2451
c8be6d7b 2452 if (conn->in.notYetUsed > 0)
41d00cd3 2453 memmove(conn->in.buf, conn->in.buf + byteCount, conn->in.notYetUsed);
c8be6d7b 2454}
2455
39cb8c41
AR
2456/// respond with ERR_TOO_BIG if request header exceeds request_header_max_size
2457void
2458ConnStateData::checkHeaderLimits()
c8be6d7b 2459{
39cb8c41
AR
2460 if (in.notYetUsed < Config.maxRequestHeaderSize)
2461 return; // can accumulte more header data
3ff65596 2462
39cb8c41 2463 debugs(33, 3, "Request header is too large (" << in.notYetUsed << " > " <<
de48b288 2464 Config.maxRequestHeaderSize << " bytes)");
c8be6d7b 2465
39cb8c41 2466 ClientSocketContext *context = parseHttpRequestAbort(this, "error:request-too-large");
528b2c61 2467 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2468 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2469 assert (repContext);
2470 repContext->setReplyToError(ERR_TOO_BIG,
c2a7cefd 2471 HTTP_BAD_REQUEST, Http::METHOD_NONE, NULL,
73c36fd9 2472 clientConnection->remote, NULL, NULL, NULL);
0655fa4d 2473 context->registerWithConn();
528b2c61 2474 context->pullData();
c8be6d7b 2475}
2476
1cf238db 2477void
f35961af 2478ConnStateData::clientAfterReadingRequests()
c4b7a5a9 2479{
39cb8c41 2480 // Were we expecting to read more request body from half-closed connection?
73c36fd9
AJ
2481 if (mayNeedToReadMoreBody() && commIsHalfClosed(clientConnection->fd)) {
2482 debugs(33, 3, HERE << "truncated body: closing half-closed " << clientConnection);
2483 clientConnection->close();
39cb8c41 2484 return;
c4b7a5a9 2485 }
2486
f35961af
AR
2487 if (flags.readMore)
2488 readSomeData();
c4b7a5a9 2489}
2490
84c77748
AR
2491void
2492ConnStateData::quitAfterError(HttpRequest *request)
2493{
2494 // From HTTP p.o.v., we do not have to close after every error detected
2495 // at the client-side, but many such errors do require closure and the
2496 // client-side code is bad at handling errors so we play it safe.
2497 if (request)
e857372a 2498 request->flags.proxyKeepalive = false;
84c77748
AR
2499 flags.readMore = false;
2500 debugs(33,4, HERE << "Will close after error: " << clientConnection);
2501}
2502
8eb0a7ee
CT
2503#if USE_SSL
2504bool ConnStateData::serveDelayedError(ClientSocketContext *context)
2505{
2506 ClientHttpRequest *http = context->http;
fd4624d7
CT
2507
2508 if (!sslServerBump)
8eb0a7ee
CT
2509 return false;
2510
fd4624d7 2511 assert(sslServerBump->entry);
7a957a93 2512 // Did we create an error entry while processing CONNECT?
fd4624d7 2513 if (!sslServerBump->entry->isEmpty()) {
84c77748
AR
2514 quitAfterError(http->request);
2515
7a957a93
AR
2516 // Get the saved error entry and send it to the client by replacing the
2517 // ClientHttpRequest store entry with it.
8eb0a7ee
CT
2518 clientStreamNode *node = context->getClientReplyContext();
2519 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
7a957a93
AR
2520 assert(repContext);
2521 debugs(33, 5, "Responding with delated error for " << http->uri);
fd4624d7 2522 repContext->setReplyToStoreEntry(sslServerBump->entry);
7a957a93
AR
2523
2524 // save the original request for logging purposes
b248c2a3
AJ
2525 if (!context->http->al->request) {
2526 context->http->al->request = http->request;
2527 HTTPMSGLOCK(context->http->al->request);
2528 }
7a957a93
AR
2529
2530 // Get error details from the fake certificate-peeking request.
129fe2a1 2531 http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
8eb0a7ee 2532 context->pullData();
8eb0a7ee
CT
2533 return true;
2534 }
2535
7a957a93
AR
2536 // In bump-server-first mode, we have not necessarily seen the intended
2537 // server name at certificate-peeking time. Check for domain mismatch now,
2538 // when we can extract the intended name from the bumped HTTP request.
2539 if (sslServerBump->serverCert.get()) {
8eb0a7ee 2540 HttpRequest *request = http->request;
fd4624d7 2541 if (!Ssl::checkX509ServerValidity(sslServerBump->serverCert.get(), request->GetHost())) {
7a957a93
AR
2542 debugs(33, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " <<
2543 "does not match domainname " << request->GetHost());
8eb0a7ee
CT
2544
2545 ACLFilledChecklist check(Config.ssl_client.cert_error, request, dash_str);
7a957a93 2546 check.sslErrors = new Ssl::Errors(SQUID_X509_V_ERR_DOMAIN_MISMATCH);
7a957a93
AR
2547 const bool allowDomainMismatch =
2548 check.fastCheck() == ACCESS_ALLOWED;
2549 delete check.sslErrors;
2550 check.sslErrors = NULL;
8eb0a7ee 2551
7d82c5b8 2552 if (!allowDomainMismatch) {
84c77748
AR
2553 quitAfterError(request);
2554
8eb0a7ee
CT
2555 clientStreamNode *node = context->getClientReplyContext();
2556 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2557 assert (repContext);
2558
7a957a93 2559 // Fill the server IP and hostname for error page generation.
fd4624d7
CT
2560 HttpRequest::Pointer const & peekerRequest = sslServerBump->request;
2561 request->hier.note(peekerRequest->hier.tcpServer, request->GetHost());
7a957a93 2562
8eb0a7ee 2563 // Create an error object and fill it
03f00a11 2564 ErrorState *err = new ErrorState(ERR_SECURE_CONNECT_FAIL, HTTP_SERVICE_UNAVAILABLE, request);
8eb0a7ee 2565 err->src_addr = clientConnection->remote;
7a957a93
AR
2566 Ssl::ErrorDetail *errDetail = new Ssl::ErrorDetail(
2567 SQUID_X509_V_ERR_DOMAIN_MISMATCH,
2568 sslServerBump->serverCert.get(), NULL);
8eb0a7ee 2569 err->detail = errDetail;
7a957a93 2570 // Save the original request for logging purposes.
b248c2a3
AJ
2571 if (!context->http->al->request) {
2572 context->http->al->request = request;
2573 HTTPMSGLOCK(context->http->al->request);
2574 }
8eb0a7ee
CT
2575 repContext->setReplyToError(request->method, err);
2576 assert(context->http->out.offset == 0);
2577 context->pullData();
8eb0a7ee
CT
2578 return true;
2579 }
2580 }
2581 }
2582
2583 return false;
2584}
7a957a93 2585#endif // USE_SSL
8eb0a7ee 2586
c4b7a5a9 2587static void
1cf238db 2588clientProcessRequest(ConnStateData *conn, HttpParser *hp, ClientSocketContext *context, const HttpRequestMethod& method, HttpVersion http_ver)
c4b7a5a9 2589{
59a1efb2 2590 ClientHttpRequest *http = context->http;
10dbb3cd 2591 HttpRequest::Pointer request;
5f8252d2 2592 bool notedUseOfBuffer = false;
39cb8c41 2593 bool chunked = false;
e18b8316 2594 bool mustReplyToOptions = false;
3ff65596 2595 bool unsupportedTe = false;
39cb8c41 2596 bool expectBody = false;
5f8252d2 2597
c4b7a5a9 2598 /* We have an initial client stream in place should it be needed */
2599 /* setup our private context */
0655fa4d 2600 context->registerWithConn();
c4b7a5a9 2601
2602 if (context->flags.parsed_ok == 0) {
62e76326 2603 clientStreamNode *node = context->getClientReplyContext();
f4762666 2604 debugs(33, 2, "clientProcessRequest: Invalid Request");
84c77748 2605 conn->quitAfterError(NULL);
727552f4
CT
2606 // setLogUri should called before repContext->setReplyToError
2607 setLogUri(http, http->uri, true);
0655fa4d 2608 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2609 assert (repContext);
e212e5e3 2610 switch (hp->request_parse_status) {
719c7e0a 2611 case HTTP_HEADER_TOO_LARGE:
73c36fd9 2612 repContext->setReplyToError(ERR_TOO_BIG, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, conn->in.buf, NULL);
719c7e0a
AJ
2613 break;
2614 case HTTP_METHOD_NOT_ALLOWED:
be364179 2615 repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_METHOD_NOT_ALLOWED, method, http->uri,
73c36fd9 2616 conn->clientConnection->remote, NULL, conn->in.buf, NULL);
719c7e0a
AJ
2617 break;
2618 default:
9815f129 2619 repContext->setReplyToError(ERR_INVALID_REQ, hp->request_parse_status, method, http->uri,
73c36fd9 2620 conn->clientConnection->remote, NULL, conn->in.buf, NULL);
719c7e0a 2621 }
62e76326 2622 assert(context->http->out.offset == 0);
2623 context->pullData();
fc68f6b1 2624 goto finish;
c4b7a5a9 2625 }
2626
c21ad0f5 2627 if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) {
62e76326 2628 clientStreamNode *node = context->getClientReplyContext();
bf8fe701 2629 debugs(33, 5, "Invalid URL: " << http->uri);
b248c2a3 2630 conn->quitAfterError(request.getRaw());
727552f4
CT
2631 // setLogUri should called before repContext->setReplyToError
2632 setLogUri(http, http->uri, true);
0655fa4d 2633 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2634 assert (repContext);
73c36fd9 2635 repContext->setReplyToError(ERR_INVALID_URL, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL);
62e76326 2636 assert(context->http->out.offset == 0);
2637 context->pullData();
fc68f6b1 2638 goto finish;
62e76326 2639 }
c4b7a5a9 2640
e57c1885
AJ
2641 /* RFC 2616 section 10.5.6 : handle unsupported HTTP versions cleanly. */
2642 /* We currently only accept 0.9, 1.0, 1.1 */
2643 if ( (http_ver.major == 0 && http_ver.minor != 9) ||
af6a12ee
AJ
2644 (http_ver.major == 1 && http_ver.minor > 1 ) ||
2645 (http_ver.major > 1) ) {
e57c1885
AJ
2646
2647 clientStreamNode *node = context->getClientReplyContext();
2648 debugs(33, 5, "Unsupported HTTP version discovered. :\n" << HttpParserHdrBuf(hp));
b248c2a3 2649 conn->quitAfterError(request.getRaw());
727552f4
CT
2650 // setLogUri should called before repContext->setReplyToError
2651 setLogUri(http, http->uri, true);
e57c1885
AJ
2652 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2653 assert (repContext);
be364179 2654 repContext->setReplyToError(ERR_UNSUP_HTTPVERSION, HTTP_HTTP_VERSION_NOT_SUPPORTED, method, http->uri,
73c36fd9 2655 conn->clientConnection->remote, NULL, HttpParserHdrBuf(hp), NULL);
e57c1885
AJ
2656 assert(context->http->out.offset == 0);
2657 context->pullData();
e57c1885
AJ
2658 goto finish;
2659 }
2660
528b2c61 2661 /* compile headers */
2662 /* we should skip request line! */
666f514b 2663 /* XXX should actually know the damned buffer size here */
38e82382 2664 if (http_ver.major >= 1 && !request->parseHeader(HttpParserHdrBuf(hp), HttpParserHdrSz(hp))) {
47ac2ebe 2665 clientStreamNode *node = context->getClientReplyContext();
bf8fe701 2666 debugs(33, 5, "Failed to parse request headers:\n" << HttpParserHdrBuf(hp));
b248c2a3 2667 conn->quitAfterError(request.getRaw());
727552f4
CT
2668 // setLogUri should called before repContext->setReplyToError
2669 setLogUri(http, http->uri, true);
47ac2ebe 2670 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2671 assert (repContext);
73c36fd9 2672 repContext->setReplyToError(ERR_INVALID_REQ, HTTP_BAD_REQUEST, method, http->uri, conn->clientConnection->remote, NULL, NULL, NULL);
47ac2ebe 2673 assert(context->http->out.offset == 0);
2674 context->pullData();
fc68f6b1 2675 goto finish;
47ac2ebe 2676 }
c4b7a5a9 2677
40d34a62
AJ
2678 request->clientConnectionManager = conn;
2679
c4b7a5a9 2680 request->flags.accelerated = http->flags.accel;
450fe1cb 2681 request->flags.sslBumped=conn->switchedToHttps();
450fe1cb 2682 request->flags.ignoreCc = conn->port->ignore_cc;
7fb65ee4 2683 // TODO: decouple http->flags.accel from request->flags.sslBumped
450fe1cb 2684 request->flags.noDirect = (request->flags.accelerated && !request->flags.sslBumped) ?
e4a14600 2685 !conn->port->allow_direct : 0;
21512911
CT
2686#if USE_AUTH
2687 if (request->flags.sslBumped) {
2688 if (conn->auth_user_request != NULL)
2689 request->auth_user_request = conn->auth_user_request;
2690 }
2691#endif
2ad20b4f
AJ
2692
2693 /** \par
2694 * If transparent or interception mode is working clone the transparent and interception flags
2695 * from the port settings to the request.
2696 */
40d34a62 2697 if (http->clientConnection != NULL) {
304a6180 2698 request->flags.intercepted = ((http->clientConnection->flags & COMM_INTERCEPTION) != 0);
450fe1cb 2699 request->flags.spoofClientIp = ((http->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
2ad20b4f 2700 }
fc68f6b1 2701
5b4117d8 2702 if (internalCheck(request->urlpath.termedBuf())) {
cc192b50 2703 if (internalHostnameIs(request->GetHost()) &&
f024c970 2704 request->port == getMyPort()) {
be4d35dc 2705 http->flags.internal = true;
9c175897 2706 } else if (Config.onoff.global_internal_static && internalStaticCheck(request->urlpath.termedBuf())) {
cc192b50 2707 request->SetHost(internalHostname());
f024c970 2708 request->port = getMyPort();
be4d35dc 2709 http->flags.internal = true;
62e76326 2710 }
f024c970 2711 }
e72a0ec0 2712
f024c970 2713 if (http->flags.internal) {
0c3d3f65 2714 request->protocol = AnyP::PROTO_HTTP;
f024c970 2715 request->login[0] = '\0';
c4b7a5a9 2716 }
2717
c4b7a5a9 2718 request->flags.internal = http->flags.internal;
b248c2a3 2719 setLogUri (http, urlCanonicalClean(request.getRaw()));
73c36fd9 2720 request->client_addr = conn->clientConnection->remote; // XXX: remove reuest->client_addr member.
3d674977 2721#if FOLLOW_X_FORWARDED_FOR
40d34a62
AJ
2722 // indirect client gets stored here because it is an HTTP header result (from X-Forwarded-For:)
2723 // not a details about teh TCP connection itself
73c36fd9 2724 request->indirect_client_addr = conn->clientConnection->remote;
3d674977 2725#endif /* FOLLOW_X_FORWARDED_FOR */
73c36fd9 2726 request->my_addr = conn->clientConnection->local;
35fb56c9 2727 request->myportname = conn->port->name;
8ae66e43 2728 request->http_ver = http_ver;
62e76326 2729
9174ba3d
AJ
2730 // Link this HttpRequest to ConnStateData relatively early so the following complex handling can use it
2731 // TODO: this effectively obsoletes a lot of conn->FOO copying. That needs cleaning up later.
2732 request->clientConnectionManager = conn;
2733
39cb8c41
AR
2734 if (request->header.chunked()) {
2735 chunked = true;
2736 } else if (request->header.has(HDR_TRANSFER_ENCODING)) {
2737 const String te = request->header.getList(HDR_TRANSFER_ENCODING);
2738 // HTTP/1.1 requires chunking to be the last encoding if there is one
2739 unsupportedTe = te.size() && te != "identity";
2740 } // else implied identity coding
de48b288 2741
c2a7cefd 2742 mustReplyToOptions = (method == Http::METHOD_OPTIONS) &&
d916dcb8 2743 (request->header.getInt64(HDR_MAX_FORWARDS) == 0);
b248c2a3 2744 if (!urlCheckRequest(request.getRaw()) || mustReplyToOptions || unsupportedTe) {
62e76326 2745 clientStreamNode *node = context->getClientReplyContext();
b248c2a3 2746 conn->quitAfterError(request.getRaw());
0655fa4d 2747 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2748 assert (repContext);
be364179 2749 repContext->setReplyToError(ERR_UNSUP_REQ, HTTP_NOT_IMPLEMENTED, request->method, NULL,
b248c2a3 2750 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2751 assert(context->http->out.offset == 0);
2752 context->pullData();
fc68f6b1 2753 goto finish;
c4b7a5a9 2754 }
2755
b248c2a3 2756 if (!chunked && !clientIsContentLengthValid(request.getRaw())) {
62e76326 2757 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2758 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2759 assert (repContext);
b248c2a3 2760 conn->quitAfterError(request.getRaw());
0655fa4d 2761 repContext->setReplyToError(ERR_INVALID_REQ,
2762 HTTP_LENGTH_REQUIRED, request->method, NULL,
b248c2a3 2763 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
62e76326 2764 assert(context->http->out.offset == 0);
2765 context->pullData();
fc68f6b1 2766 goto finish;
c4b7a5a9 2767 }
2768
52b601ff 2769 if (request->header.has(HDR_EXPECT)) {
655daa06
AR
2770 const String expect = request->header.getList(HDR_EXPECT);
2771 const bool supportedExpect = (expect.caseCmp("100-continue") == 0);
2772 if (!supportedExpect) {
52b601ff
AJ
2773 clientStreamNode *node = context->getClientReplyContext();
2774 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2775 assert (repContext);
b248c2a3 2776 conn->quitAfterError(request.getRaw());
be364179 2777 repContext->setReplyToError(ERR_INVALID_REQ, HTTP_EXPECTATION_FAILED, request->method, http->uri,
b248c2a3 2778 conn->clientConnection->remote, request.getRaw(), NULL, NULL);
52b601ff
AJ
2779 assert(context->http->out.offset == 0);
2780 context->pullData();
2781 goto finish;
2782 }
2783 }
2784
b248c2a3
AJ
2785 http->request = request.getRaw();
2786 HTTPMSGLOCK(http->request);
c4b7a5a9 2787 clientSetKeepaliveFlag(http);
62e76326 2788
f35961af 2789 // Let tunneling code be fully responsible for CONNECT requests
c2a7cefd 2790 if (http->request->method == Http::METHOD_CONNECT) {
b66e0e86 2791 context->mayUseConnection(true);
f35961af
AR
2792 conn->flags.readMore = false;
2793 }
fc68f6b1 2794
061bbdec 2795#if USE_SSL
8eb0a7ee 2796 if (conn->switchedToHttps() && conn->serveDelayedError(context))
061bbdec 2797 goto finish;
061bbdec
CT
2798#endif
2799
b66e0e86 2800 /* Do we expect a request-body? */
39cb8c41
AR
2801 expectBody = chunked || request->content_length > 0;
2802 if (!context->mayUseConnection() && expectBody) {
2803 request->body_pipe = conn->expectRequestBody(
de48b288 2804 chunked ? -1 : request->content_length);
5f8252d2 2805
2806 // consume header early so that body pipe gets just the body
1cf238db 2807 connNoteUseOfBuffer(conn, http->req_sz);
5f8252d2 2808 notedUseOfBuffer = true;
2809
62e76326 2810 /* Is it too large? */
39cb8c41 2811 if (!chunked && // if chunked, we will check as we accumulate
de48b288 2812 clientIsRequestBodyTooLargeForPolicy(request->content_length)) {
62e76326 2813 clientStreamNode *node = context->getClientReplyContext();
0655fa4d 2814 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2815 assert (repContext);
b248c2a3 2816 conn->quitAfterError(request.getRaw());
0655fa4d 2817 repContext->setReplyToError(ERR_TOO_BIG,
c2a7cefd 2818 HTTP_REQUEST_ENTITY_TOO_LARGE, Http::METHOD_NONE, NULL,
73c36fd9 2819 conn->clientConnection->remote, http->request, NULL, NULL);
62e76326 2820 assert(context->http->out.offset == 0);
2821 context->pullData();
5f8252d2 2822 goto finish;
62e76326 2823 }
2824
39cb8c41
AR
2825 // We may stop producing, comm_close, and/or call setReplyToError()
2826 // below, so quit on errors to avoid http->doCallouts()
2827 if (!conn->handleRequestBodyData())
de48b288 2828 goto finish;
39cb8c41 2829
f35961af
AR
2830 if (!request->body_pipe->productionEnded()) {
2831 debugs(33, 5, HERE << "need more request body");
2832 context->mayUseConnection(true);
2833 assert(conn->flags.readMore);
2834 }
c4b7a5a9 2835 }
2836
de31d06f 2837 http->calloutContext = new ClientRequestContext(http);
2838
2839 http->doCallouts();
9e008dda 2840
4c29340e 2841finish:
5f8252d2 2842 if (!notedUseOfBuffer)
1cf238db 2843 connNoteUseOfBuffer(conn, http->req_sz);
52c2c8a8 2844
2845 /*
2846 * DPW 2007-05-18
2847 * Moved the TCP_RESET feature from clientReplyContext::sendMoreData
2848 * to here because calling comm_reset_close() causes http to
2849 * be freed and the above connNoteUseOfBuffer() would hit an
2850 * assertion, not to mention that we were accessing freed memory.
2851 */
b248c2a3 2852 if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
73c36fd9 2853 debugs(33, 3, HERE << "Sending TCP RST on " << conn->clientConnection);
f35961af 2854 conn->flags.readMore = false;
73c36fd9 2855 comm_reset_close(conn->clientConnection);
52c2c8a8 2856 }
c4b7a5a9 2857}
2858
2859static void
1cf238db 2860connStripBufferWhitespace (ConnStateData * conn)
c4b7a5a9 2861{
2862 while (conn->in.notYetUsed > 0 && xisspace(conn->in.buf[0])) {
41d00cd3 2863 memmove(conn->in.buf, conn->in.buf + 1, conn->in.notYetUsed - 1);
5e263176 2864 -- conn->in.notYetUsed;
c4b7a5a9 2865 }
2866}
2867
2868static int
1cf238db 2869connOkToAddRequest(ConnStateData * conn)
c4b7a5a9 2870{
0655fa4d 2871 int result = conn->getConcurrentRequestCount() < (Config.onoff.pipeline_prefetch ? 2 : 1);
62e76326 2872
c4b7a5a9 2873 if (!result) {
73c36fd9
AJ
2874 debugs(33, 3, HERE << conn->clientConnection << " max concurrent requests reached");
2875 debugs(33, 5, HERE << conn->clientConnection << " defering new request until one is done");
c4b7a5a9 2876 }
62e76326 2877
c4b7a5a9 2878 return result;
2879}
2880
63be0a78 2881/**
f900210a 2882 * Attempt to parse one or more requests from the input buffer.
2883 * If a request is successfully parsed, even if the next request
2884 * is only partially parsed, it will return TRUE.
f900210a 2885 */
4959e21e 2886bool
f35961af 2887ConnStateData::clientParseRequests()
f900210a 2888{
60745f24 2889 HttpRequestMethod method;
f900210a 2890 bool parsed_req = false;
8ae66e43 2891 HttpVersion http_ver;
f900210a 2892
1b76e6c1 2893 debugs(33, 5, HERE << clientConnection << ": attempting to parse");
f900210a 2894
39cb8c41 2895 // Loop while we have read bytes that are not needed for producing the body
f35961af
AR
2896 // On errors, bodyPipe may become nil, but readMore will be cleared
2897 while (in.notYetUsed > 0 && !bodyPipe && flags.readMore) {
4959e21e 2898 connStripBufferWhitespace(this);
f900210a 2899
fc68f6b1 2900 /* Don't try to parse if the buffer is empty */
4959e21e 2901 if (in.notYetUsed == 0)
fc68f6b1 2902 break;
4681057e 2903
f900210a 2904 /* Limit the number of concurrent requests to 2 */
4959e21e 2905 if (!connOkToAddRequest(this)) {
f900210a 2906 break;
2907 }
2908
2909 /* Should not be needed anymore */
2910 /* Terminate the string */
4959e21e 2911 in.buf[in.notYetUsed] = '\0';
f900210a 2912
fc68f6b1 2913 /* Begin the parsing */
fc68f6b1 2914 PROF_start(parseHttpRequest);
4959e21e 2915 HttpParserInit(&parser_, in.buf, in.notYetUsed);
fc68f6b1 2916
4959e21e
AJ
2917 /* Process request */
2918 ClientSocketContext *context = parseHttpRequest(this, &parser_, &method, &http_ver);
fc68f6b1 2919 PROF_stop(parseHttpRequest);
f900210a 2920
2921 /* partial or incomplete request */
2922 if (!context) {
39cb8c41
AR
2923 // TODO: why parseHttpRequest can just return parseHttpRequestAbort
2924 // (which becomes context) but checkHeaderLimits cannot?
4959e21e 2925 checkHeaderLimits();
f900210a 2926 break;
2927 }
2928
2929 /* status -1 or 1 */
2930 if (context) {
1b76e6c1 2931 debugs(33, 5, HERE << clientConnection << ": parsed a request");
8d77a37c 2932 AsyncCall::Pointer timeoutCall = commCbCall(5, 4, "clientLifetimeTimeout",
dc49061a 2933 CommTimeoutCbPtrFun(clientLifetimeTimeout, context->http));
1b76e6c1 2934 commSetConnTimeout(clientConnection, Config.Timeout.lifetime, timeoutCall);
f900210a 2935
4959e21e 2936 clientProcessRequest(this, &parser_, context, method, http_ver);
f900210a 2937
4959e21e 2938 parsed_req = true; // XXX: do we really need to parse everything right NOW ?
f900210a 2939
2940 if (context->mayUseConnection()) {
f35961af 2941 debugs(33, 3, HERE << "Not parsing new requests, as this request may need the connection");
f900210a 2942 break;
2943 }
f900210a 2944 }
39cb8c41 2945 }
fc68f6b1 2946
a5baffba 2947 /* XXX where to 'finish' the parsing pass? */
f900210a 2948 return parsed_req;
2949}
2950
1cf238db 2951void
2952ConnStateData::clientReadRequest(const CommIoCbParams &io)
c4b7a5a9 2953{
be364179 2954 debugs(33,5,HERE << io.conn << " size " << io.size);
f84dd7eb
AR
2955 Must(reading());
2956 reader = NULL;
c4b7a5a9 2957
c4b7a5a9 2958 /* Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up */
62e76326 2959
1cf238db 2960 if (io.flag == COMM_ERR_CLOSING) {
be364179 2961 debugs(33,5, HERE << io.conn << " closing Bailout.");
c4b7a5a9 2962 return;
2963 }
62e76326 2964
73c36fd9
AJ
2965 assert(Comm::IsConnOpen(clientConnection));
2966 assert(io.conn->fd == clientConnection->fd);
5c336a3b 2967
44db45e8 2968 /*
2969 * Don't reset the timeout value here. The timeout value will be
2970 * set to Config.Timeout.request by httpAccept() and
2971 * clientWriteComplete(), and should apply to the request as a
2972 * whole, not individual read() calls. Plus, it breaks our
2973 * lame half-close detection
2974 */
1cf238db 2975 if (connReadWasError(io.flag, io.size, io.xerrno)) {
f692498b 2976 notifyAllContexts(io.xerrno);
be364179 2977 io.conn->close();
62e76326 2978 return;
7a2f978b 2979 }
c4b7a5a9 2980
1cf238db 2981 if (io.flag == COMM_OK) {
2982 if (io.size > 0) {
e4f1fdae 2983 kb_incr(&(statCounter.client_http.kbytes_in), io.size);
3b299123 2984
39cb8c41
AR
2985 // may comm_close or setReplyToError
2986 if (!handleReadData(io.buf, io.size))
9e008dda 2987 return;
a31a78fb 2988
1cf238db 2989 } else if (io.size == 0) {
be364179 2990 debugs(33, 5, HERE << io.conn << " closed?");
62e76326 2991
1cf238db 2992 if (connFinishedWithConn(io.size)) {
73c36fd9 2993 clientConnection->close();
62e76326 2994 return;
2995 }
2996
2997 /* It might be half-closed, we can't tell */
be4d35dc 2998 fd_table[io.conn->fd].flags.socket_eof = true;
62e76326 2999
be364179 3000 commMarkHalfClosed(io.conn->fd);
a46d2c0e 3001
be364179 3002 fd_note(io.conn->fd, "half-closed");
62e76326 3003
3004 /* There is one more close check at the end, to detect aborted
3005 * (partial) requests. At this point we can't tell if the request
3006 * is partial.
3007 */
3008 /* Continue to process previously read data */
3009 }
c4b7a5a9 3010 }
3011
94439e4e 3012 /* Process next request */
1cf238db 3013 if (getConcurrentRequestCount() == 0)
5c336a3b 3014 fd_note(io.fd, "Reading next request");
c8be6d7b 3015
f35961af 3016 if (!clientParseRequests()) {
9e008dda
AJ
3017 if (!isOpen())
3018 return;
f900210a 3019 /*
3020 * If the client here is half closed and we failed
3021 * to parse a request, close the connection.
3022 * The above check with connFinishedWithConn() only
3023 * succeeds _if_ the buffer is empty which it won't
3024 * be if we have an incomplete request.
6e1d409c 3025 * XXX: This duplicates ClientSocketContext::keepaliveNextRequest
f900210a 3026 */
5c336a3b 3027 if (getConcurrentRequestCount() == 0 && commIsHalfClosed(io.fd)) {
be364179 3028 debugs(33, 5, HERE << io.conn << ": half-closed connection, no completed request parsed, connection closing.");
73c36fd9 3029 clientConnection->close();
ee6f0213 3030 return;
62e76326 3031 }
f900210a 3032 }
ee6f0213 3033
1cf238db 3034 if (!isOpen())
2e216b1d 3035 return;
3036
f35961af 3037 clientAfterReadingRequests();
94439e4e 3038}
3039
63be0a78 3040/**
3041 * called when new request data has been read from the socket
39cb8c41
AR
3042 *
3043 * \retval false called comm_close or setReplyToError (the caller should bail)
3044 * \retval true we did not call comm_close or setReplyToError
63be0a78 3045 */
39cb8c41 3046bool
5f8252d2 3047ConnStateData::handleReadData(char *buf, size_t size)
94439e4e 3048{
5f8252d2 3049 char *current_buf = in.addressToReadInto();
62e76326 3050
5f8252d2 3051 if (buf != current_buf)
41d00cd3 3052 memmove(current_buf, buf, size);
3b299123 3053
5f8252d2 3054 in.notYetUsed += size;
fc68f6b1 3055
5f8252d2 3056 in.buf[in.notYetUsed] = '\0'; /* Terminate the string */
3b299123 3057
5f8252d2 3058 // if we are reading a body, stuff data into the body pipe
3059 if (bodyPipe != NULL)
39cb8c41
AR
3060 return handleRequestBodyData();
3061 return true;
94439e4e 3062}
3063
63be0a78 3064/**
bb790702 3065 * called when new request body data has been buffered in in.buf
63be0a78 3066 * may close the connection if we were closing and piped everything out
39cb8c41
AR
3067 *
3068 * \retval false called comm_close or setReplyToError (the caller should bail)
3069 * \retval true we did not call comm_close or setReplyToError
63be0a78 3070 */
39cb8c41 3071bool
5f8252d2 3072ConnStateData::handleRequestBodyData()
94439e4e 3073{
5f8252d2 3074 assert(bodyPipe != NULL);
3075
e1381638 3076 size_t putSize = 0;
3ff65596 3077
39cb8c41
AR
3078 if (in.bodyParser) { // chunked encoding
3079 if (const err_type error = handleChunkedRequestBody(putSize)) {
3080 abortChunkedRequestBody(error);
3081 return false;
3ff65596 3082 }
39cb8c41 3083 } else { // identity encoding
73c36fd9 3084 debugs(33,5, HERE << "handling plain request body for " << clientConnection);
3ff65596
AR
3085 putSize = bodyPipe->putMoreData(in.buf, in.notYetUsed);
3086 if (!bodyPipe->mayNeedMoreData()) {
3087 // BodyPipe will clear us automagically when we produced everything
3088 bodyPipe = NULL;
3089 }
3090 }
3091
3092 if (putSize > 0)
3093 connNoteUseOfBuffer(this, putSize);
5f8252d2 3094
3ff65596 3095 if (!bodyPipe) {
73c36fd9 3096 debugs(33,5, HERE << "produced entire request body for " << clientConnection);
62e76326 3097
cf6eb29e 3098 if (const char *reason = stoppedSending()) {
5f8252d2 3099 /* we've finished reading like good clients,
3100 * now do the close that initiateClose initiated.
5f8252d2 3101 */
cf6eb29e 3102 debugs(33, 3, HERE << "closing for earlier sending error: " << reason);
73c36fd9 3103 clientConnection->close();
39cb8c41
AR
3104 return false;
3105 }
3106 }
3107
3108 return true;
3109}
3110
3111/// parses available chunked encoded body bytes, checks size, returns errors
3112err_type
3113ConnStateData::handleChunkedRequestBody(size_t &putSize)
3114{
73c36fd9 3115 debugs(33,7, HERE << "chunked from " << clientConnection << ": " << in.notYetUsed);
39cb8c41
AR
3116
3117 try { // the parser will throw on errors
3118
3119 if (!in.notYetUsed) // nothing to do (MemBuf::init requires this check)
3120 return ERR_NONE;
3121
3122 MemBuf raw; // ChunkedCodingParser only works with MemBufs
3123 // add one because MemBuf will assert if it cannot 0-terminate
3124 raw.init(in.notYetUsed, in.notYetUsed+1);
3125 raw.append(in.buf, in.notYetUsed);
3126
3127 const mb_size_t wasContentSize = raw.contentSize();
3128 BodyPipeCheckout bpc(*bodyPipe);
3129 const bool parsed = in.bodyParser->parse(&raw, &bpc.buf);
3130 bpc.checkIn();
3131 putSize = wasContentSize - raw.contentSize();
3132
3133 // dechunk then check: the size limit applies to _dechunked_ content
3134 if (clientIsRequestBodyTooLargeForPolicy(bodyPipe->producedSize()))
3135 return ERR_TOO_BIG;
3136
3137 if (parsed) {
3138 finishDechunkingRequest(true);
3139 Must(!bodyPipe);
3140 return ERR_NONE; // nil bodyPipe implies body end for the caller
5f8252d2 3141 }
39cb8c41
AR
3142
3143 // if chunk parser needs data, then the body pipe must need it too
3144 Must(!in.bodyParser->needsMoreData() || bodyPipe->mayNeedMoreData());
3145
3146 // if parser needs more space and we can consume nothing, we will stall
3147 Must(!in.bodyParser->needsMoreSpace() || bodyPipe->buf().hasContent());
3148 } catch (...) { // TODO: be more specific
3149 debugs(33, 3, HERE << "malformed chunks" << bodyPipe->status());
3150 return ERR_INVALID_REQ;
94439e4e 3151 }
39cb8c41
AR
3152
3153 debugs(33, 7, HERE << "need more chunked data" << *bodyPipe->status());
3154 return ERR_NONE;
3155}
3156
3157/// quit on errors related to chunked request body handling
3158void
3159ConnStateData::abortChunkedRequestBody(const err_type error)
3160{
3161 finishDechunkingRequest(false);
3162
3163 // XXX: The code below works if we fail during initial request parsing,
3164 // but if we fail when the server-side works already, the server may send
3165 // us its response too, causing various assertions. How to prevent that?
3166#if WE_KNOW_HOW_TO_SEND_ERRORS
3167 ClientSocketContext::Pointer context = getCurrentContext();
3168 if (context != NULL && !context->http->out.offset) { // output nothing yet
3169 clientStreamNode *node = context->getClientReplyContext();
3170 clientReplyContext *repContext = dynamic_cast<clientReplyContext*>(node->data.getRaw());
3171 assert(repContext);
3172 const http_status scode = (error == ERR_TOO_BIG) ?
de48b288 3173 HTTP_REQUEST_ENTITY_TOO_LARGE : HTTP_BAD_REQUEST;
39cb8c41
AR
3174 repContext->setReplyToError(error, scode,
3175 repContext->http->request->method,
3176 repContext->http->uri,
a3c6762c 3177 CachePeer,
39cb8c41
AR
3178 repContext->http->request,
3179 in.buf, NULL);
3180 context->pullData();
3181 } else {
3182 // close or otherwise we may get stuck as nobody will notice the error?
73c36fd9 3183 comm_reset_close(clientConnection);
39cb8c41
AR
3184 }
3185#else
3186 debugs(33, 3, HERE << "aborting chunked request without error " << error);
73c36fd9 3187 comm_reset_close(clientConnection);
39cb8c41 3188#endif
f35961af 3189 flags.readMore = false;
5f8252d2 3190}
55e44db9 3191
5f8252d2 3192void
1cf238db 3193ConnStateData::noteMoreBodySpaceAvailable(BodyPipe::Pointer )
5f8252d2 3194{
90737510 3195 if (!handleRequestBodyData())
1368d115
CT
3196 return;
3197
6bec3b16 3198 // too late to read more body
cf6eb29e 3199 if (!isOpen() || stoppedReceiving())
6bec3b16
AR
3200 return;
3201
1368d115 3202 readSomeData();
5f8252d2 3203}
3204
3205void
1cf238db 3206ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer )
5f8252d2 3207{
cf6eb29e
CT
3208 // request reader may get stuck waiting for space if nobody consumes body
3209 if (bodyPipe != NULL)
3210 bodyPipe->enableAutoConsumption();
3211
3212 stopReceiving("virgin request body consumer aborted"); // closes ASAP
94439e4e 3213}
3214
63be0a78 3215/** general lifetime handler for HTTP requests */
1cf238db 3216void
3217ConnStateData::requestTimeout(const CommTimeoutCbParams &io)
7a2f978b 3218{
ad63ceea 3219#if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
1cf238db 3220 debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired.");
62e76326 3221
1cf238db 3222 if (COMMIO_FD_WRITECB(io.fd)->active) {
dec5db5d 3223 /* FIXME: If this code is reinstated, check the conn counters,
3224 * not the fd table state
3225 */
62e76326 3226 /*
3227 * Some data has been sent to the client, just close the FD
3228 */
73c36fd9 3229 clientConnection->close();
1cf238db 3230 } else if (nrequests) {
62e76326 3231 /*
3232 * assume its a persistent connection; just close it
3233 */
73c36fd9 3234 clientConnection->close();
7a2f978b 3235 } else {
62e76326 3236 /*
3237 * Generate an error
3238 */
59a1efb2 3239 ClientHttpRequest **H;
62e76326 3240 clientStreamNode *node;
719c7e0a 3241 ClientHttpRequest *http = parseHttpRequestAbort(this, "error:Connection%20lifetime%20expired");
62e76326 3242 node = http->client_stream.tail->prev->data;
0655fa4d 3243 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
3244 assert (repContext);
3245 repContext->setReplyToError(ERR_LIFETIME_EXP,
c2a7cefd 3246 HTTP_REQUEST_TIMEOUT, Http::METHOD_NONE, "N/A", &CachePeer.sin_addr,
0655fa4d 3247 NULL, NULL, NULL);
62e76326 3248 /* No requests can be outstanded */
1cf238db 3249 assert(chr == NULL);
62e76326 3250 /* add to the client request queue */
3251
3d0ac046 3252 for (H = &chr; *H; H = &(*H)->next);
62e76326 3253 *H = http;
3254
3255 clientStreamRead(http->client_stream.tail->data, http, 0,
3256 HTTP_REQBUF_SZ, context->reqbuf);
3257
3258 /*
3259 * if we don't close() here, we still need a timeout handler!
3260 */
9e008dda 3261 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876
AR
3262 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
3263 TimeoutDialer, this, ConnStateData::requestTimeout);
8d77a37c 3264 commSetConnTimeout(io.conn, 30, timeoutCall);
62e76326 3265
3266 /*
3267 * Aha, but we don't want a read handler!
3268 */
d841c88d 3269 Comm::SetSelect(io.fd, COMM_SELECT_READ, NULL, NULL, 0);
7a2f978b 3270 }
62e76326 3271
af57a2e3 3272#else
3273 /*
62e76326 3274 * Just close the connection to not confuse browsers
3275 * using persistent connections. Some browsers opens
3276 * an connection and then does not use it until much
3277 * later (presumeably because the request triggering
3278 * the open has already been completed on another
3279 * connection)
3280 */
1cf238db 3281 debugs(33, 3, "requestTimeout: FD " << io.fd << ": lifetime is expired.");
8d77a37c 3282 io.conn->close();
af57a2e3 3283#endif
7a2f978b 3284}
3285
b5c39993 3286static void
8d77a37c 3287clientLifetimeTimeout(const CommTimeoutCbParams &io)
b5c39993 3288{
8d77a37c 3289 ClientHttpRequest *http = static_cast<ClientHttpRequest *>(io.data);
cb61ec47
AJ
3290 debugs(33, DBG_IMPORTANT, "WARNING: Closing client connection due to lifetime timeout");
3291 debugs(33, DBG_IMPORTANT, "\t" << http->uri);
41ebd397 3292 http->al->http.timedout = true;
8d77a37c
AJ
3293 if (Comm::IsConnOpen(io.conn))
3294 io.conn->close();
b5c39993 3295}
3296
c8be6d7b 3297ConnStateData *
65d448bc 3298connStateCreate(const Comm::ConnectionPointer &client, AnyP::PortCfg *port)
c8be6d7b 3299{
a46d2c0e 3300 ConnStateData *result = new ConnStateData;
2ad20b4f 3301
73c36fd9 3302 result->clientConnection = client;
be364179 3303 result->log_addr = client->remote;
055421ee 3304 result->log_addr.ApplyMask(Config.Addrs.client_netmask);
e6ccf245 3305 result->in.buf = (char *)memAllocBuf(CLIENT_REQ_BUF_SZ, &result->in.allocatedSize);
3f38a55e 3306 result->port = cbdataReference(port);
62e76326 3307
5529ca8a 3308 if (port->disable_pmtu_discovery != DISABLE_PMTU_OFF &&
9e008dda 3309 (result->transparent() || port->disable_pmtu_discovery == DISABLE_PMTU_ALWAYS)) {
5529ca8a 3310#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
3311 int i = IP_PMTUDISC_DONT;
9bb67276
AJ
3312 if (setsockopt(client->fd, SOL_IP, IP_MTU_DISCOVER, &i, sizeof(i)) < 0)
3313 debugs(33, 2, "WARNING: Path MTU discovery disabling failed on " << client << " : " << xstrerror());
5529ca8a 3314#else
9bb67276 3315 static bool reported = false;
5529ca8a 3316
3317 if (!reported) {
9bb67276
AJ
3318 debugs(33, DBG_IMPORTANT, "NOTICE: Path MTU discovery disabling is not supported on your platform.");
3319 reported = true;
5529ca8a 3320 }
89aec9b6
AJ
3321#endif
3322 }
5529ca8a 3323
89aec9b6
AJ
3324 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
3325 AsyncCall::Pointer call = JobCallback(33, 5, Dialer, result, ConnStateData::connStateClosed);
3326 comm_add_close_handler(client->fd, call);
5529ca8a 3327
89aec9b6
AJ
3328 if (Config.onoff.log_fqdn)
3329 fqdncache_gethostbyaddr(client->remote, FQDN_LOOKUP_IF_MISS);
3330
3331#if USE_IDENT
3332 if (Ident::TheConfig.identLookup) {
3333 ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL);
3334 identChecklist.src_addr = client->remote;
3335 identChecklist.my_addr = client->local;
2efeb0b7 3336 if (identChecklist.fastCheck() == ACCESS_ALLOWED)
89aec9b6
AJ
3337 Ident::Start(client, clientIdentDone, result);
3338 }
5529ca8a 3339#endif
3340
89aec9b6
AJ
3341#if USE_SQUID_EUI
3342 if (Eui::TheConfig.euiLookup) {
3343 if (client->remote.IsIPv4()) {
3344 result->clientConnection->remoteEui48.lookup(client->remote);
3345 } else if (client->remote.IsIPv6()) {
3346 result->clientConnection->remoteEui64.lookup(client->remote);
3347 }
5529ca8a 3348 }
89aec9b6
AJ
3349#endif
3350
3351 clientdbEstablished(client->remote, 1);
5529ca8a 3352
f35961af 3353 result->flags.readMore = true;
c8be6d7b 3354 return result;
3355}
3356
63be0a78 3357/** Handle a new connection on HTTP socket. */
7a2f978b 3358void
449f0115 3359httpAccept(const CommAcceptCbParams &params)
7a2f978b 3360{
65d448bc 3361 AnyP::PortCfg *s = static_cast<AnyP::PortCfg *>(params.data);
02d1422b 3362
449f0115 3363 if (params.flag != COMM_OK) {
cbff89ba 3364 // Its possible the call was still queued when the client disconnected
449f0115 3365 debugs(33, 2, "httpAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
62e76326 3366 return;
3367 }
3368
449f0115
AJ
3369 debugs(33, 4, HERE << params.conn << ": accepted");
3370 fd_note(params.conn->fd, "client http connect");
1cf238db 3371
89aec9b6 3372 if (s->tcp_keepalive.enabled) {
449f0115 3373 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
89aec9b6 3374 }
62e76326 3375
95dc7ff4 3376 ++ incoming_sockets_accepted;
89aec9b6
AJ
3377
3378 // Socket is ready, setup the connection manager to start using it
449f0115 3379 ConnStateData *connState = connStateCreate(params.conn, s);
62e76326 3380
9e008dda 3381 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
4299f876 3382 AsyncCall::Pointer timeoutCall = JobCallback(33, 5,
4cb2536f 3383 TimeoutDialer, connState, ConnStateData::requestTimeout);
6b2a2108 3384 commSetConnTimeout(params.conn, Config.Timeout.request, timeoutCall);
b2130d58 3385
a46d2c0e 3386 connState->readSomeData();
62e76326 3387
9a0a18de 3388#if USE_DELAY_POOLS
449f0115 3389 fd_table[params.conn->fd].clientInfo = NULL;
b4cd430a 3390
f33d34a8 3391 if (Config.onoff.client_db) {
b4cd430a
CT
3392 /* it was said several times that client write limiter does not work if client_db is disabled */
3393
3394 ClientDelayPools& pools(Config.ClientDelay.pools);
2efeb0b7 3395 ACLFilledChecklist ch(NULL, NULL, NULL);
b4cd430a 3396
2efeb0b7
AJ
3397 // TODO: we check early to limit error response bandwith but we
3398 // should recheck when we can honor delay_pool_uses_indirect
3399 // TODO: we should also pass the port details for myportname here.
449f0115
AJ
3400 ch.src_addr = params.conn->remote;
3401 ch.my_addr = params.conn->local;
b4cd430a 3402
95dc7ff4 3403 for (unsigned int pool = 0; pool < pools.size(); ++pool) {
b4cd430a 3404
2efeb0b7
AJ
3405 /* pools require explicit 'allow' to assign a client into them */
3406 if (pools[pool].access) {
3407 ch.accessList = pools[pool].access;
3408 allow_t answer = ch.fastCheck();
3409 if (answer == ACCESS_ALLOWED) {
3410
3411 /* request client information from db after we did all checks
3412 this will save hash lookup if client failed checks */
449f0115 3413 ClientInfo * cli = clientdbGetInfo(params.conn->remote);
2efeb0b7
AJ
3414 assert(cli);
3415
3416 /* put client info in FDE */
449f0115 3417 fd_table[params.conn->fd].clientInfo = cli;
2efeb0b7
AJ
3418
3419 /* setup write limiter for this request */
3420 const double burst = floor(0.5 +
3421 (pools[pool].highwatermark * Config.ClientDelay.initial)/100.0);
3422 cli->setWriteLimiter(pools[pool].rate, burst, pools[pool].highwatermark);
3423 break;
3424 } else {
3425 debugs(83, 4, HERE << "Delay pool " << pool << " skipped because ACL " << answer);
3426 }
b4cd430a
CT
3427 }
3428 }
3429 }
3430#endif
7a2f978b 3431}
3432
1f7c9178 3433#if USE_SSL
3434
63be0a78 3435/** Create SSL connection structure and update fd_table */
ae7ff0b8 3436static SSL *
449f0115 3437httpsCreate(const Comm::ConnectionPointer &conn, SSL_CTX *sslContext)
ae7ff0b8 3438{
3439 SSL *ssl = SSL_new(sslContext);
3440
3441 if (!ssl) {
3442 const int ssl_error = ERR_get_error();
449f0115
AJ
3443 debugs(83, DBG_IMPORTANT, "ERROR: httpsAccept: Error allocating handle: " << ERR_error_string(ssl_error, NULL) );
3444 conn->close();
ae7ff0b8 3445 return NULL;
3446 }
3447
449f0115
AJ
3448 SSL_set_fd(ssl, conn->fd);
3449 fd_table[conn->fd].ssl = ssl;
3450 fd_table[conn->fd].read_method = &ssl_read_method;
3451 fd_table[conn->fd].write_method = &ssl_write_method;
ae7ff0b8 3452
449f0115
AJ
3453 debugs(33, 5, "httpsCreate: will negotate SSL on " << conn);
3454 fd_note(conn->fd, "client https start");
ae7ff0b8 3455
3456 return ssl;
3457}
3458
63be0a78 3459/** negotiate an SSL connection */
1f7c9178 3460static void
3461clientNegotiateSSL(int fd, void *data)
3462{
e6ccf245 3463 ConnStateData *conn = (ConnStateData *)data;
1f7c9178 3464 X509 *client_cert;
a7ad6e4e 3465 SSL *ssl = fd_table[fd].ssl;
1f7c9178 3466 int ret;
3467
a7ad6e4e 3468 if ((ret = SSL_accept(ssl)) <= 0) {
62e76326 3469 int ssl_error = SSL_get_error(ssl, ret);
3470
3471 switch (ssl_error) {
3472
3473 case SSL_ERROR_WANT_READ:
d841c88d 3474 Comm::SetSelect(fd, COMM_SELECT_READ, clientNegotiateSSL, conn, 0);
62e76326 3475 return;
3476
3477 case SSL_ERROR_WANT_WRITE:
d841c88d 3478 Comm::SetSelect(fd, COMM_SELECT_WRITE, clientNegotiateSSL, conn, 0);
62e76326 3479 return;
3480
6de9e64b 3481 case SSL_ERROR_SYSCALL:
3482
3483 if (ret == 0) {
bf8fe701 3484 debugs(83, 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Aborted by client");
6de9e64b 3485 comm_close(fd);
3486 return;
3487 } else {
3488 int hard = 1;
3489
3490 if (errno == ECONNRESET)
3491 hard = 0;
3492
9e008dda 3493 debugs(83, hard ? 1 : 2, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
bf8fe701 3494 fd << ": " << strerror(errno) << " (" << errno << ")");
6de9e64b 3495
3496 comm_close(fd);
3497
3498 return;
3499 }
3500
3501 case SSL_ERROR_ZERO_RETURN:
e0236918 3502 debugs(83, DBG_IMPORTANT, "clientNegotiateSSL: Error negotiating SSL connection on FD " << fd << ": Closed by client");
6de9e64b 3503 comm_close(fd);
3504 return;
3505
62e76326 3506 default:
e0236918 3507 debugs(83, DBG_IMPORTANT, "clientNegotiateSSL: Error negotiating SSL connection on FD " <<
9e008dda
AJ
3508 fd << ": " << ERR_error_string(ERR_get_error(), NULL) <<
3509 " (" << ssl_error << "/" << ret << ")");
62e76326 3510 comm_close(fd);
3511 return;
3512 }
3513
3514 /* NOTREACHED */
1f7c9178 3515 }
62e76326 3516
6de9e64b 3517 if (SSL_session_reused(ssl)) {
bf8fe701 3518 debugs(83, 2, "clientNegotiateSSL: Session " << SSL_get_session(ssl) <<
3519 " reused on FD " << fd << " (" << fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port << ")");
6de9e64b 3520 } else {
3521 if (do_debug(83, 4)) {
3522 /* Write out the SSL session details.. actually the call below, but
3523 * OpenSSL headers do strange typecasts confusing GCC.. */
3524 /* PEM_write_SSL_SESSION(debug_log, SSL_get_session(ssl)); */
afdd443f 3525#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00908000L
9f3de01a 3526 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 3527
0fd2205b 3528#elif (ALLOW_ALWAYS_SSL_SESSION_DETAIL == 1)
2930f303 3529
0fd2205b 3530 /* When using gcc 3.3.x and OpenSSL 0.9.7x sometimes a compile error can occur here.
3531 * This is caused by an unpredicatble gcc behaviour on a cast of the first argument
3532 * of PEM_ASN1_write(). For this reason this code section is disabled. To enable it,
3533 * define ALLOW_ALWAYS_SSL_SESSION_DETAIL=1.
3534 * Because there are two possible usable cast, if you get an error here, try the other
3535 * commented line. */
3536
3537 PEM_ASN1_write((int(*)())i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL);
3538 /* PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION, debug_log, (char *)SSL_get_session(ssl), NULL,NULL,0,NULL,NULL); */
2930f303 3539
0e33d58c 3540#else
3541
bf8fe701 3542 debugs(83, 4, "With " OPENSSL_VERSION_TEXT ", session details are available only defining ALLOW_ALWAYS_SSL_SESSION_DETAIL=1 in the source." );
0fd2205b 3543
0e33d58c 3544#endif
6de9e64b 3545 /* Note: This does not automatically fflush the log file.. */
3546 }
3547
bf8fe701 3548 debugs(83, 2, "clientNegotiateSSL: New session " <<
3549 SSL_get_session(ssl) << " on FD " << fd << " (" <<
3550 fd_table[fd].ipaddr << ":" << (int)fd_table[fd].remote_port <<
3551 ")");
6de9e64b 3552 }
3553
bf8fe701 3554 debugs(83, 3, "clientNegotiateSSL: FD " << fd << " negotiated cipher " <<
3555 SSL_get_cipher(ssl));
1f7c9178 3556
6de9e64b 3557 client_cert = SSL_get_peer_certificate(ssl);
62e76326 3558
1f7c9178 3559 if (client_cert != NULL) {
bf8fe701 3560 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3561 " client certificate: subject: " <<
3562 X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0));
3563
3564 debugs(83, 3, "clientNegotiateSSL: FD " << fd <<
3565 " client certificate: issuer: " <<
3566 X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0));
1f7c9178 3567
62e76326 3568 X509_free(client_cert);
1f7c9178 3569 } else {
bf8fe701 3570 debugs(83, 5, "clientNegotiateSSL: FD " << fd <<
3571 " has no certificate.");
1f7c9178 3572 }
3573
a46d2c0e 3574 conn->readSomeData();
1f7c9178 3575}
3576
379e8c1c 3577/**
ab2e0682
CT
3578 * If SSL_CTX is given, starts reading the SSL handshake.
3579 * Otherwise, calls switchToHttps to generate a dynamic SSL_CTX.
379e8c1c
AR
3580 */
3581static void
caf3666d 3582httpsEstablish(ConnStateData *connState, SSL_CTX *sslContext, Ssl::BumpMode bumpMode)
379e8c1c
AR
3583{
3584 SSL *ssl = NULL;
3585 assert(connState);
3586 const Comm::ConnectionPointer &details = connState->clientConnection;
3587
3588 if (sslContext && !(ssl = httpsCreate(details, sslContext)))
3589 return;
3590
7a957a93
AR
3591 typedef CommCbMemFunT<ConnStateData, CommTimeoutCbParams> TimeoutDialer;
3592 AsyncCall::Pointer timeoutCall = JobCallback(33, 5, TimeoutDialer,
87f237a9 3593 connState, ConnStateData::requestTimeout);
379e8c1c
AR
3594 commSetConnTimeout(details, Config.Timeout.request, timeoutCall);
3595
87f237a9 3596 if (ssl)
379e8c1c
AR
3597 Comm::SetSelect(details->fd, COMM_SELECT_READ, clientNegotiateSSL, connState, 0);
3598 else {
3599 char buf[MAX_IPSTRLEN];
caf3666d 3600 assert(bumpMode != Ssl::bumpNone && bumpMode != Ssl::bumpEnd);
65ba7f04
CT
3601 HttpRequest *fakeRequest = new HttpRequest;
3602 fakeRequest->SetHost(details->local.NtoA(buf, sizeof(buf)));
3603 fakeRequest->port = details->local.GetPort();
3604 fakeRequest->clientConnectionManager = connState;
3605 fakeRequest->client_addr = connState->clientConnection->remote;
3606#if FOLLOW_X_FORWARDED_FOR
3607 fakeRequest->indirect_client_addr = connState->clientConnection->remote;
3608#endif
3609 fakeRequest->my_addr = connState->clientConnection->local;
450fe1cb 3610 fakeRequest->flags.spoofClientIp = ((connState->clientConnection->flags & COMM_TRANSPARENT) != 0 ) ;
6df4ecae 3611 fakeRequest->flags.intercepted = ((connState->clientConnection->flags & COMM_INTERCEPTION) != 0);
379e8c1c 3612 debugs(33, 4, HERE << details << " try to generate a Dynamic SSL CTX");
caf3666d 3613 connState->switchToHttps(fakeRequest, bumpMode);
379e8c1c
AR
3614 }
3615}
3616
3617/**
87f237a9 3618 * A callback function to use with the ACLFilledChecklist callback.
7a957a93
AR
3619 * In the case of ACCES_ALLOWED answer initializes a bumped SSL connection,
3620 * else reverts the connection to tunnel mode.
379e8c1c
AR
3621 */
3622static void
3623httpsSslBumpAccessCheckDone(allow_t answer, void *data)
3624{
3625 ConnStateData *connState = (ConnStateData *) data;
3626
7a957a93 3627 // if the connection is closed or closing, just return.
379e8c1c
AR
3628 if (!connState->isOpen())
3629 return;
3630
7a957a93 3631 // Require both a match and a positive bump mode to work around exceptional
caf3666d
AR
3632 // cases where ACL code may return ACCESS_ALLOWED with zero answer.kind.
3633 if (answer == ACCESS_ALLOWED && answer.kind != Ssl::bumpNone) {
08097970
AR
3634 debugs(33, 2, HERE << "sslBump needed for " << connState->clientConnection);
3635 connState->sslBumpMode = static_cast<Ssl::BumpMode>(answer.kind);
caf3666d 3636 httpsEstablish(connState, NULL, (Ssl::BumpMode)answer.kind);
379e8c1c 3637 } else {
08097970
AR
3638 debugs(33, 2, HERE << "sslBump not needed for " << connState->clientConnection);
3639 connState->sslBumpMode = Ssl::bumpNone;
379e8c1c 3640
08097970 3641 // fake a CONNECT request to force connState to tunnel
379e8c1c
AR
3642 static char ip[MAX_IPSTRLEN];
3643 static char reqStr[MAX_IPSTRLEN + 80];
3644 connState->clientConnection->local.NtoA(ip, sizeof(ip));
ab2e0682 3645 snprintf(reqStr, sizeof(reqStr), "CONNECT %s:%d HTTP/1.1\r\nHost: %s\r\n\r\n", ip, connState->clientConnection->local.GetPort(), ip);
379e8c1c
AR
3646 bool ret = connState->handleReadData(reqStr, strlen(reqStr));
3647 if (ret)
3648 ret = connState->clientParseRequests();
3649
3650 if (!ret) {
3651 debugs(33, 2, HERE << "Failed to start fake CONNECT request for ssl bumped connection: " << connState->clientConnection);
3652 connState->clientConnection->close();
3653 }
3654 }
3655}
3656
63be0a78 3657/** handle a new HTTPS connection */
1f7c9178 3658static void
449f0115 3659httpsAccept(const CommAcceptCbParams &params)
1f7c9178 3660{
65d448bc 3661 AnyP::PortCfg *s = static_cast<AnyP::PortCfg *>(params.data);
c4b7a5a9 3662
449f0115 3663 if (params.flag != COMM_OK) {
cbff89ba 3664 // Its possible the call was still queued when the client disconnected
449f0115 3665 debugs(33, 2, "httpsAccept: " << s->listenConn << ": accept failure: " << xstrerr(params.xerrno));
62e76326 3666 return;
c4b7a5a9 3667 }
62e76326 3668
449f0115
AJ
3669 debugs(33, 4, HERE << params.conn << " accepted, starting SSL negotiation.");
3670 fd_note(params.conn->fd, "client https connect");
62e76326 3671
859741ed
AJ
3672 if (s->tcp_keepalive.enabled) {
3673 commSetTcpKeepalive(params.conn->fd, s->tcp_keepalive.idle, s->tcp_keepalive.interval, s->tcp_keepalive.timeout);
b2130d58 3674 }
3675
95dc7ff4 3676 ++incoming_sockets_accepted;
62e76326 3677
89aec9b6 3678 // Socket is ready, setup the connection manager to start using it
859741ed 3679 ConnStateData *connState = connStateCreate(params.conn, s);
62e76326 3680
6a25a046 3681 if (s->flags.tunnelSslBumping) {
379e8c1c 3682 debugs(33, 5, "httpsAccept: accept transparent connection: " << params.conn);
62e76326 3683
379e8c1c
AR
3684 if (!Config.accessList.ssl_bump) {
3685 httpsSslBumpAccessCheckDone(ACCESS_DENIED, connState);
3686 return;
3687 }
87f237a9 3688
379e8c1c 3689 // Create a fake HTTP request for ssl_bump ACL check,
38450a50 3690 // using tproxy/intercept provided destination IP and port.
379e8c1c
AR
3691 HttpRequest *request = new HttpRequest();
3692 static char ip[MAX_IPSTRLEN];
d7ce0bcd 3693 assert(params.conn->flags & (COMM_TRANSPARENT | COMM_INTERCEPTION));
379e8c1c
AR
3694 request->SetHost(params.conn->local.NtoA(ip, sizeof(ip)));
3695 request->port = params.conn->local.GetPort();
3696 request->myportname = s->name;
87f237a9 3697
379e8c1c
AR
3698 ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL);
3699 acl_checklist->src_addr = params.conn->remote;
3700 acl_checklist->my_addr = s->s;
3701 acl_checklist->nonBlockingCheck(httpsSslBumpAccessCheckDone, connState);
3702 return;
3703 } else {
3704 SSL_CTX *sslContext = s->staticSslContext.get();
caf3666d 3705 httpsEstablish(connState, sslContext, Ssl::bumpNone);
379e8c1c 3706 }
1f7c9178 3707}
3708
95d2589c 3709void
0272dd08 3710ConnStateData::sslCrtdHandleReplyWrapper(void *data, const HelperReply &reply)
ae7ff0b8 3711{
95d2589c
CT
3712 ConnStateData * state_data = (ConnStateData *)(data);
3713 state_data->sslCrtdHandleReply(reply);
3714}
ae7ff0b8 3715
95d2589c 3716void
0272dd08 3717ConnStateData::sslCrtdHandleReply(const HelperReply &reply)
95d2589c 3718{
5955f162
AJ
3719 if (reply.result == HelperReply::BrokenHelper) {
3720 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply);
3721 } else if (!reply.other().hasContent()) {
3722 debugs(1, DBG_IMPORTANT, HERE << "\"ssl_crtd\" helper returned <NULL> reply.");
95d2589c 3723 } else {
ff2d7d92 3724 Ssl::CrtdMessage reply_message(Ssl::CrtdMessage::REPLY);
0272dd08 3725 if (reply_message.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK) {
fb2178bb 3726 debugs(33, 5, HERE << "Reply from ssl_crtd for " << sslConnectHostOrIp << " is incorrect");
95d2589c 3727 } else {
0272dd08 3728 if (reply.result != HelperReply::Okay) {
fb2178bb 3729 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " cannot be generated. ssl_crtd response: " << reply_message.getBody());
95d2589c 3730 } else {
fb2178bb 3731 debugs(33, 5, HERE << "Certificate for " << sslConnectHostOrIp << " was successfully recieved from ssl_crtd");
86660d64 3732 SSL_CTX *ctx = Ssl::generateSslContextUsingPkeyAndCertFromMemory(reply_message.getBody().c_str(), *port);
a594dbfa 3733 getSslContextDone(ctx, true);
95d2589c
CT
3734 return;
3735 }
3736 }
3737 }
3738 getSslContextDone(NULL);
3739}
ae7ff0b8 3740
06997a38 3741void ConnStateData::buildSslCertGenerationParams(Ssl::CertificateProperties &certProperties)
fb2178bb 3742{
06997a38 3743 certProperties.commonName = sslCommonName.defined() ? sslCommonName.termedBuf() : sslConnectHostOrIp.termedBuf();
fb2178bb
CT
3744
3745 // fake certificate adaptation requires bump-server-first mode
caf3666d
AR
3746 if (!sslServerBump) {
3747 assert(port->signingCert.get());
3748 certProperties.signWithX509.resetAndLock(port->signingCert.get());
3749 if (port->signPkey.get())
3750 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3751 certProperties.signAlgorithm = Ssl::algSignTrusted;
fb2178bb 3752 return;
caf3666d 3753 }
fb2178bb 3754
7a957a93
AR
3755 // In case of an error while connecting to the secure server, use a fake
3756 // trusted certificate, with no mimicked fields and no adaptation
3757 // algorithms. There is nothing we can mimic so we want to minimize the
3758 // number of warnings the user will have to see to get to the error page.
fd4624d7
CT
3759 assert(sslServerBump->entry);
3760 if (sslServerBump->entry->isEmpty()) {
3761 if (X509 *mimicCert = sslServerBump->serverCert.get())
59a49556
CT
3762 certProperties.mimicCert.resetAndLock(mimicCert);
3763
b248c2a3 3764 ACLFilledChecklist checklist(NULL, sslServerBump->request.getRaw(),
59a49556 3765 clientConnection != NULL ? clientConnection->rfc931 : dash_str);
7a957a93 3766 checklist.sslErrors = cbdataReference(sslServerBump->sslErrors);
59a49556
CT
3767
3768 for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) {
7a957a93 3769 // If the algorithm already set, then ignore it.
a06042fa 3770 if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) ||
87f237a9
A
3771 (ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) ||
3772 (ca->alg == Ssl::algSetValidBefore && certProperties.setValidBefore) )
a06042fa
CT
3773 continue;
3774
59a49556
CT
3775 if (ca->aclList && checklist.fastCheck(ca->aclList) == ACCESS_ALLOWED) {
3776 const char *alg = Ssl::CertAdaptAlgorithmStr[ca->alg];
3777 const char *param = ca->param;
87f237a9 3778
7a957a93
AR
3779 // For parameterless CN adaptation, use hostname from the
3780 // CONNECT request.
a06042fa 3781 if (ca->alg == Ssl::algSetCommonName) {
59a49556
CT
3782 if (!param)
3783 param = sslConnectHostOrIp.termedBuf();
3784 certProperties.commonName = param;
3785 certProperties.setCommonName = true;
87f237a9 3786 } else if (ca->alg == Ssl::algSetValidAfter)
59a49556 3787 certProperties.setValidAfter = true;
87f237a9 3788 else if (ca->alg == Ssl::algSetValidBefore)
59a49556
CT
3789 certProperties.setValidBefore = true;
3790
87f237a9 3791 debugs(33, 5, HERE << "Matches certificate adaptation aglorithm: " <<
8f9720ce 3792 alg << " param: " << (param ? param : "-"));
aebe6888 3793 }
fb2178bb 3794 }
aebe6888 3795
59a49556
CT
3796 certProperties.signAlgorithm = Ssl::algSignEnd;
3797 for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) {
3798 if (sg->aclList && checklist.fastCheck(sg->aclList) == ACCESS_ALLOWED) {
3799 certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg;
3800 break;
3801 }
aebe6888 3802 }
fd4624d7 3803 } else {// if (!sslServerBump->entry->isEmpty())
59a49556
CT
3804 // Use trusted certificate for a Squid-generated error
3805 // or the user would have to add a security exception
3806 // just to see the error page. We will close the connection
3807 // so that the trust is not extended to non-Squid content.
3808 certProperties.signAlgorithm = Ssl::algSignTrusted;
aebe6888
CT
3809 }
3810
10d914f6 3811 assert(certProperties.signAlgorithm != Ssl::algSignEnd);
aebe6888
CT
3812
3813 if (certProperties.signAlgorithm == Ssl::algSignUntrusted) {
f4e4d4d6 3814 assert(port->untrustedSigningCert.get());
95588170
CT
3815 certProperties.signWithX509.resetAndLock(port->untrustedSigningCert.get());
3816 certProperties.signWithPkey.resetAndLock(port->untrustedSignPkey.get());
87f237a9 3817 } else {
f4e4d4d6
CT
3818 assert(port->signingCert.get());
3819 certProperties.signWithX509.resetAndLock(port->signingCert.get());
aebe6888
CT
3820
3821 if (port->signPkey.get())
3822 certProperties.signWithPkey.resetAndLock(port->signPkey.get());
3823 }
3824 signAlgorithm = certProperties.signAlgorithm;
fb2178bb
CT
3825}
3826
1ce2822d 3827void
95d2589c
CT
3828ConnStateData::getSslContextStart()
3829{
129fe2a1
CT
3830 assert(areAllContextsForThisConnection());
3831 freeAllContexts();
3832 /* careful: freeAllContexts() above frees request, host, etc. */
3833
fb2178bb 3834 if (port->generateHostCertificates) {
aebe6888 3835 Ssl::CertificateProperties certProperties;
06997a38
CT
3836 buildSslCertGenerationParams(certProperties);
3837 sslBumpCertKey = certProperties.dbKey().c_str();
fb2178bb
CT
3838 assert(sslBumpCertKey.defined() && sslBumpCertKey[0] != '\0');
3839
aebe6888 3840 debugs(33, 5, HERE << "Finding SSL certificate for " << sslBumpCertKey << " in cache");
95d2589c 3841 Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s));
14798e73
CT
3842 SSL_CTX * dynCtx = NULL;
3843 Ssl::SSL_CTX_Pointer *cachedCtx = ssl_ctx_cache.get(sslBumpCertKey.termedBuf());
3844 if (cachedCtx && (dynCtx = cachedCtx->get())) {
fb2178bb 3845 debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " have found in cache");
4ece76b2 3846 if (Ssl::verifySslCertificate(dynCtx, certProperties)) {
fb2178bb 3847 debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is valid");
1ce2822d
AR
3848 getSslContextDone(dynCtx);
3849 return;
95d2589c 3850 } else {
fb2178bb 3851 debugs(33, 5, HERE << "Cached SSL certificate for " << sslBumpCertKey << " is out of date. Delete this certificate from cache");
14798e73 3852 ssl_ctx_cache.del(sslBumpCertKey.termedBuf());
95d2589c
CT
3853 }
3854 } else {
fb2178bb 3855 debugs(33, 5, HERE << "SSL certificate for " << sslBumpCertKey << " haven't found in cache");
95d2589c
CT
3856 }
3857
b5faa519 3858#if USE_SSL_CRTD
00fc192d 3859 try {
87f237a9 3860 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName << " using ssl_crtd.");
ff2d7d92 3861 Ssl::CrtdMessage request_message(Ssl::CrtdMessage::REQUEST);
87f237a9
A
3862 request_message.setCode(Ssl::CrtdMessage::code_new_certificate);
3863 request_message.composeRequest(certProperties);
3864 debugs(33, 5, HERE << "SSL crtd request: " << request_message.compose().c_str());
3865 Ssl::Helper::GetInstance()->sslSubmit(request_message, sslCrtdHandleReplyWrapper, this);
3866 return;
3867 } catch (const std::exception &e) {
00fc192d
AR
3868 debugs(33, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtd " <<
3869 "request for " << certProperties.commonName <<
3870 " certificate: " << e.what() << "; will now block to " <<
3871 "generate that certificate.");
3872 // fall through to do blocking in-process generation.
3873 }
3874#endif // USE_SSL_CRTD
3875
aebe6888 3876 debugs(33, 5, HERE << "Generating SSL certificate for " << certProperties.commonName);
86660d64 3877 dynCtx = Ssl::generateSslContext(certProperties, *port);
1ce2822d
AR
3878 getSslContextDone(dynCtx, true);
3879 return;
95d2589c 3880 }
1ce2822d 3881 getSslContextDone(NULL);
95d2589c
CT
3882}
3883
1ce2822d 3884void
95d2589c
CT
3885ConnStateData::getSslContextDone(SSL_CTX * sslContext, bool isNew)
3886{
3887 // Try to add generated ssl context to storage.
3888 if (port->generateHostCertificates && isNew) {
a594dbfa 3889
aebe6888
CT
3890 if (signAlgorithm == Ssl::algSignTrusted)
3891 Ssl::addChainToSslContext(sslContext, port->certsToChain.get());
3892 //else it is self-signed or untrusted do not attrach any certificate
a594dbfa 3893
95d2589c 3894 Ssl::LocalContextStorage & ssl_ctx_cache(Ssl::TheGlobalContextStorage.getLocalStorage(port->s));
fb2178bb
CT
3895 assert(sslBumpCertKey.defined() && sslBumpCertKey[0] != '\0');
3896 if (sslContext) {
14798e73 3897 if (!ssl_ctx_cache.add(sslBumpCertKey.termedBuf(), new Ssl::SSL_CTX_Pointer(sslContext))) {
95d2589c 3898 // If it is not in storage delete after using. Else storage deleted it.
73c36fd9 3899 fd_table[clientConnection->fd].dynamicSslContext = sslContext;
95d2589c
CT
3900 }
3901 } else {
fb2178bb 3902 debugs(33, 2, HERE << "Failed to generate SSL cert for " << sslConnectHostOrIp);
95d2589c
CT
3903 }
3904 }
3905
3906 // If generated ssl context = NULL, try to use static ssl context.
3907 if (!sslContext) {
3908 if (!port->staticSslContext) {
e0236918 3909 debugs(83, DBG_IMPORTANT, "Closing SSL " << clientConnection->remote << " as lacking SSL context");
73c36fd9 3910 clientConnection->close();
1ce2822d 3911 return;
95d2589c
CT
3912 } else {
3913 debugs(33, 5, HERE << "Using static ssl context.");
3914 sslContext = port->staticSslContext.get();
3915 }
3916 }
ae7ff0b8 3917
a9b1d8c6 3918 if (!httpsCreate(clientConnection, sslContext))
1ce2822d 3919 return;
ae7ff0b8 3920
8d77a37c 3921 // commSetConnTimeout() was called for this request before we switched.
ae7ff0b8 3922
a3c6762c 3923 // Disable the client read handler until CachePeer selection is complete
73c36fd9
AJ
3924 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
3925 Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, clientNegotiateSSL, this, 0);
ae7ff0b8 3926 switchedToHttps_ = true;
ae7ff0b8 3927}
3928
1ce2822d 3929void
caf3666d 3930ConnStateData::switchToHttps(HttpRequest *request, Ssl::BumpMode bumpServerMode)
95d2589c
CT
3931{
3932 assert(!switchedToHttps_);
3933
65ba7f04
CT
3934 sslConnectHostOrIp = request->GetHost();
3935 sslCommonName = request->GetHost();
95d2589c 3936
83d4cd15
CT
3937 // We are going to read new request
3938 flags.readMore = true;
73c36fd9 3939 debugs(33, 5, HERE << "converting " << clientConnection << " to SSL");
95d2589c 3940
2bd84e5f
CT
3941 // If sslServerBump is set, then we have decided to deny CONNECT
3942 // and now want to switch to SSL to send the error to the client
3943 // without even peeking at the origin server certificate.
caf3666d 3944 if (bumpServerMode == Ssl::bumpServerFirst && !sslServerBump) {
e857372a 3945 request->flags.sslPeek = true;
65ba7f04 3946 sslServerBump = new Ssl::ServerBump(request);
fd4624d7 3947
d7ce0bcd 3948 // will call httpsPeeked() with certificate and connection, eventually
b248c2a3 3949 FwdState::fwdStart(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw());
d7ce0bcd
AR
3950 return;
3951 }
3952
fb2178bb 3953 // otherwise, use sslConnectHostOrIp
d7ce0bcd
AR
3954 getSslContextStart();
3955}
3956
3957void
3958ConnStateData::httpsPeeked(Comm::ConnectionPointer serverConnection)
3959{
fd4624d7 3960 Must(sslServerBump != NULL);
819c207f 3961
061bbdec
CT
3962 if (Comm::IsConnOpen(serverConnection)) {
3963 SSL *ssl = fd_table[serverConnection->fd].ssl;
3964 assert(ssl);
3965 Ssl::X509_Pointer serverCert(SSL_get_peer_certificate(ssl));
3966 assert(serverCert.get() != NULL);
fb2178bb 3967 sslCommonName = Ssl::CommonHostName(serverCert.get());
87f237a9 3968 debugs(33, 5, HERE << "HTTPS server CN: " << sslCommonName <<
59a49556 3969 " bumped: " << *serverConnection);
061bbdec
CT
3970
3971 pinConnection(serverConnection, NULL, NULL, false);
3972
fb2178bb 3973 debugs(33, 5, HERE << "bumped HTTPS server: " << sslConnectHostOrIp);
59a49556 3974 } else {
13858f50 3975 debugs(33, 5, HERE << "Error while bumping: " << sslConnectHostOrIp);
8499a1de
CT
3976 Ip::Address intendedDest;
3977 intendedDest = sslConnectHostOrIp.termedBuf();
c3d24490 3978 const bool isConnectRequest = !port->flags.isIntercepted();
35cd4281 3979
8499a1de
CT
3980 // Squid serves its own error page and closes, so we want
3981 // a CN that causes no additional browser errors. Possible
35cd4281
CT
3982 // only when bumping CONNECT with a user-typed address.
3983 if (intendedDest.IsAnyAddr() || isConnectRequest)
8499a1de 3984 sslCommonName = sslConnectHostOrIp;
fd4624d7
CT
3985 else if (sslServerBump->serverCert.get())
3986 sslCommonName = Ssl::CommonHostName(sslServerBump->serverCert.get());
129fe2a1
CT
3987
3988 // copy error detail from bump-server-first request to CONNECT request
3989 if (currentobject != NULL && currentobject->http != NULL && currentobject->http->request)
3990 currentobject->http->request->detailError(sslServerBump->request->errType, sslServerBump->request->errDetail);
59a49556 3991 }
061bbdec 3992
1ce2822d 3993 getSslContextStart();
95d2589c
CT
3994}
3995
1f7c9178 3996#endif /* USE_SSL */
3997
00516be1
AR
3998/// check FD after clientHttp[s]ConnectionOpened, adjust HttpSockets as needed
3999static bool
73c36fd9 4000OpenedHttpSocket(const Comm::ConnectionPointer &c, const Ipc::FdNoteId portType)
00516be1 4001{
73c36fd9 4002 if (!Comm::IsConnOpen(c)) {
00516be1
AR
4003 Must(NHttpSockets > 0); // we tried to open some
4004 --NHttpSockets; // there will be fewer sockets than planned
4005 Must(HttpSockets[NHttpSockets] < 0); // no extra fds received
4006
4007 if (!NHttpSockets) // we could not open any listen sockets at all
cbff89ba 4008 fatalf("Unable to open %s",FdNote(portType));
00516be1
AR
4009
4010 return false;
4011 }
4012 return true;
4013}
4014
4015/// find any unused HttpSockets[] slot and store fd there or return false
4016static bool
e0d28505 4017AddOpenedHttpSocket(const Comm::ConnectionPointer &conn)
00516be1
AR
4018{
4019 bool found = false;
95dc7ff4 4020 for (int i = 0; i < NHttpSockets && !found; ++i) {
00516be1 4021 if ((found = HttpSockets[i] < 0))
e0d28505 4022 HttpSockets[i] = conn->fd;
00516be1
AR
4023 }
4024 return found;
4025}
15df8349 4026
d193a436 4027static void
15df8349 4028clientHttpConnectionsOpen(void)
4029{
65d448bc 4030 AnyP::PortCfg *s = NULL;
62e76326 4031
7e3ce7b9 4032 for (s = Config.Sockaddr.http; s; s = s->next) {
65d448bc 4033 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4034 debugs(1, DBG_IMPORTANT, "WARNING: You have too many 'http_port' lines.");
4035 debugs(1, DBG_IMPORTANT, " The limit is " << MAXTCPLISTENPORTS << " HTTP ports.");
62e76326 4036 continue;
4037 }
4038
ae7ff0b8 4039#if USE_SSL
6a25a046 4040 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
859741ed 4041 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s->protocol << "_port " << s->s);
6a25a046 4042 s->flags.tunnelSslBumping = false;
3d61b18e
AJ
4043 }
4044
6a25a046 4045 if (s->flags.tunnelSslBumping &&
2ee34428
A
4046 !s->staticSslContext &&
4047 !s->generateHostCertificates) {
859741ed 4048 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4049 s->flags.tunnelSslBumping = false;
ae7ff0b8 4050 }
6a25a046 4051 if (s->flags.tunnelSslBumping) {
95d2589c
CT
4052 // Create ssl_ctx cache for this port.
4053 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4054 }
ae7ff0b8 4055#endif
4056
e0d28505 4057 // Fill out a Comm::Connection which IPC will open as a listener for us
8bbb16e3 4058 // then pass back when active so we can start a TcpAcceptor subscription.
e0d28505
AJ
4059 s->listenConn = new Comm::Connection;
4060 s->listenConn->local = s->s;
6a25a046 4061 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) | (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
c303f6e3 4062
cbff89ba
AJ
4063 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTP
4064 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
4065 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpAccept", CommAcceptCbPtrFun(httpAccept, s));
4066 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4067
cbff89ba 4068 AsyncCall::Pointer listenCall = asyncCall(33,2, "clientListenerConnectionOpened",
8bbb16e3
AJ
4069 ListeningStartedDialer(&clientListenerConnectionOpened, s, Ipc::fdnHttpSocket, sub));
4070 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpSocket, listenCall);
62e76326 4071
a38ec4b1
FC
4072 HttpSockets[NHttpSockets] = -1; // set in clientListenerConnectionOpened
4073 ++NHttpSockets;
15df8349 4074 }
d193a436 4075}
4076
4077#if USE_SSL
4078static void
4079clientHttpsConnectionsOpen(void)
4080{
65d448bc 4081 AnyP::PortCfg *s;
62e76326 4082
859741ed 4083 for (s = Config.Sockaddr.https; s; s = s->next) {
65d448bc 4084 if (MAXTCPLISTENPORTS == NHttpSockets) {
e0236918
FC
4085 debugs(1, DBG_IMPORTANT, "Ignoring 'https_port' lines exceeding the limit.");
4086 debugs(1, DBG_IMPORTANT, "The limit is " << MAXTCPLISTENPORTS << " HTTPS ports.");
62e76326 4087 continue;
4088 }
4089
95d2589c 4090 if (!s->staticSslContext) {
e0236918 4091 debugs(1, DBG_IMPORTANT, "Ignoring https_port " << s->s <<
ae7ff0b8 4092 " due to SSL initialization failure.");
4093 continue;
f9ad0106 4094 }
4095
d7ce0bcd 4096 // TODO: merge with similar code in clientHttpConnectionsOpen()
6a25a046 4097 if (s->flags.tunnelSslBumping && !Config.accessList.ssl_bump) {
03f00a11 4098 debugs(33, DBG_IMPORTANT, "WARNING: No ssl_bump configured. Disabling ssl-bump on " << s->protocol << "_port " << s->s);
6a25a046 4099 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4100 }
4101
6a25a046 4102 if (s->flags.tunnelSslBumping && !s->staticSslContext && !s->generateHostCertificates) {
03f00a11 4103 debugs(1, DBG_IMPORTANT, "Will not bump SSL at http_port " << s->s << " due to SSL initialization failure.");
6a25a046 4104 s->flags.tunnelSslBumping = false;
d7ce0bcd
AR
4105 }
4106
6a25a046 4107 if (s->flags.tunnelSslBumping) {
d7ce0bcd
AR
4108 // Create ssl_ctx cache for this port.
4109 Ssl::TheGlobalContextStorage.addLocalStorage(s->s, s->dynamicCertMemCacheSize == std::numeric_limits<size_t>::max() ? 4194304 : s->dynamicCertMemCacheSize);
4110 }
4111
e0d28505 4112 // Fill out a Comm::Connection which IPC will open as a listener for us
859741ed
AJ
4113 s->listenConn = new Comm::Connection;
4114 s->listenConn->local = s->s;
6a25a046
FC
4115 s->listenConn->flags = COMM_NONBLOCKING | (s->flags.tproxyIntercept ? COMM_TRANSPARENT : 0) |
4116 (s->flags.natIntercept ? COMM_INTERCEPTION : 0);
62e76326 4117
cbff89ba
AJ
4118 // setup the subscriptions such that new connections accepted by listenConn are handled by HTTPS
4119 typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
4120 RefCount<AcceptCall> subCall = commCbCall(5, 5, "httpsAccept", CommAcceptCbPtrFun(httpsAccept, s));
4121 Subscription::Pointer sub = new CallSubscription<AcceptCall>(subCall);
62e76326 4122
cbff89ba 4123 AsyncCall::Pointer listenCall = asyncCall(33, 2, "clientListenerConnectionOpened",
8bbb16e3 4124 ListeningStartedDialer(&clientListenerConnectionOpened,
859741ed 4125 s, Ipc::fdnHttpsSocket, sub));
8bbb16e3 4126 Ipc::StartListening(SOCK_STREAM, IPPROTO_TCP, s->listenConn, Ipc::fdnHttpsSocket, listenCall);
a38ec4b1
FC
4127 HttpSockets[NHttpSockets] = -1;
4128 ++NHttpSockets;
cbff89ba 4129 }
d193a436 4130}
d193a436 4131#endif
4132
e0d28505 4133/// process clientHttpConnectionsOpen result
00516be1 4134static void
65d448bc 4135clientListenerConnectionOpened(AnyP::PortCfg *s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub)
00516be1 4136{
8bbb16e3 4137 if (!OpenedHttpSocket(s->listenConn, portTypeNote))
00516be1 4138 return;
62e76326 4139
00516be1 4140 Must(s);
e0d28505 4141 Must(Comm::IsConnOpen(s->listenConn));
62e76326 4142
8bbb16e3
AJ
4143 // TCP: setup a job to handle accept() with subscribed handler
4144 AsyncJob::Start(new Comm::TcpAcceptor(s->listenConn, FdNote(portTypeNote), sub));
4145
e0236918 4146 debugs(1, DBG_IMPORTANT, "Accepting " <<
6a25a046
FC
4147 (s->flags.natIntercept ? "NAT intercepted " : "") <<
4148 (s->flags.tproxyIntercept ? "TPROXY spoofing " : "") <<
4149 (s->flags.tunnelSslBumping ? "SSL bumped " : "") <<
4150 (s->flags.accelSurrogate ? "reverse-proxy " : "")
8bbb16e3
AJ
4151 << FdNote(portTypeNote) << " connections at "
4152 << s->listenConn);
62e76326 4153
e0d28505 4154 Must(AddOpenedHttpSocket(s->listenConn)); // otherwise, we have received a fd we did not ask for
d193a436 4155}
4156
d193a436 4157void
4158clientOpenListenSockets(void)
4159{
4160 clientHttpConnectionsOpen();
4161#if USE_SSL
4162 clientHttpsConnectionsOpen();
1f7c9178 4163#endif
62e76326 4164
15df8349 4165 if (NHttpSockets < 1)
598c41da 4166 fatal("No HTTP or HTTPS ports configured");
15df8349 4167}
edce4d98 4168
c0fbae16 4169void
4170clientHttpConnectionsClose(void)
4171{
65d448bc 4172 for (AnyP::PortCfg *s = Config.Sockaddr.http; s; s = s->next) {
00406b24 4173 if (s->listenConn != NULL) {
e0236918 4174 debugs(1, DBG_IMPORTANT, "Closing HTTP port " << s->listenConn->local);
00406b24
AJ
4175 s->listenConn->close();
4176 s->listenConn = NULL;
04f55905
AJ
4177 }
4178 }
62e76326 4179
04f55905 4180#if USE_SSL
65d448bc 4181 for (AnyP::PortCfg *s = Config.Sockaddr.https; s; s = s->next) {
00406b24 4182 if (s->listenConn != NULL) {
e0236918 4183 debugs(1, DBG_IMPORTANT, "Closing HTTPS port " << s->listenConn->local);
00406b24
AJ
4184 s->listenConn->close();
4185 s->listenConn = NULL;
62e76326 4186 }
c0fbae16 4187 }
04f55905
AJ
4188#endif
4189
4190 // TODO see if we can drop HttpSockets array entirely */
95dc7ff4 4191 for (int i = 0; i < NHttpSockets; ++i) {
04f55905
AJ
4192 HttpSockets[i] = -1;
4193 }
62e76326 4194
c0fbae16 4195 NHttpSockets = 0;
4196}
f66a9ef4 4197
4198int
190154cf 4199varyEvaluateMatch(StoreEntry * entry, HttpRequest * request)
f66a9ef4 4200{
4201 const char *vary = request->vary_headers;
a9925b40 4202 int has_vary = entry->getReply()->header.has(HDR_VARY);
f66a9ef4 4203#if X_ACCELERATOR_VARY
62e76326 4204
edce4d98 4205 has_vary |=
a9925b40 4206 entry->getReply()->header.has(HDR_X_ACCELERATOR_VARY);
f66a9ef4 4207#endif
62e76326 4208
f66a9ef4 4209 if (!has_vary || !entry->mem_obj->vary_headers) {
62e76326 4210 if (vary) {
4211 /* Oops... something odd is going on here.. */
e0236918 4212 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary object on second attempt, '" <<
9e008dda 4213 entry->mem_obj->url << "' '" << vary << "'");
62e76326 4214 safe_free(request->vary_headers);
4215 return VARY_CANCEL;
4216 }
4217
4218 if (!has_vary) {
4219 /* This is not a varying object */
4220 return VARY_NONE;
4221 }
4222
4223 /* virtual "vary" object found. Calculate the vary key and
4224 * continue the search
4225 */
4226 vary = httpMakeVaryMark(request, entry->getReply());
4227
4228 if (vary) {
4229 request->vary_headers = xstrdup(vary);
4230 return VARY_OTHER;
4231 } else {
4232 /* Ouch.. we cannot handle this kind of variance */
4233 /* XXX This cannot really happen, but just to be complete */
4234 return VARY_CANCEL;
4235 }
f66a9ef4 4236 } else {
62e76326 4237 if (!vary) {
4238 vary = httpMakeVaryMark(request, entry->getReply());
4239
4240 if (vary)
4241 request->vary_headers = xstrdup(vary);
4242 }
4243
4244 if (!vary) {
4245 /* Ouch.. we cannot handle this kind of variance */
4246 /* XXX This cannot really happen, but just to be complete */
4247 return VARY_CANCEL;
4248 } else if (strcmp(vary, entry->mem_obj->vary_headers) == 0) {
4249 return VARY_MATCH;
4250 } else {
4251 /* Oops.. we have already been here and still haven't
4252 * found the requested variant. Bail out
4253 */
e0236918 4254 debugs(33, DBG_IMPORTANT, "varyEvaluateMatch: Oops. Not a Vary match on second attempt, '" <<
9e008dda 4255 entry->mem_obj->url << "' '" << vary << "'");
62e76326 4256 return VARY_CANCEL;
4257 }
f66a9ef4 4258 }
4259}
28d4805a 4260
c0941a6a 4261ACLFilledChecklist *
59a1efb2 4262clientAclChecklistCreate(const acl_access * acl, ClientHttpRequest * http)
28d4805a 4263{
1cf238db 4264 ConnStateData * conn = http->getConn();
c0941a6a 4265 ACLFilledChecklist *ch = new ACLFilledChecklist(acl, http->request,
73c36fd9 4266 cbdataReferenceValid(conn) && conn != NULL && conn->clientConnection != NULL ? conn->clientConnection->rfc931 : dash_str);
28d4805a 4267
4268 /*
4269 * hack for ident ACL. It needs to get full addresses, and a place to store
4270 * the ident result on persistent connections...
4271 */
4272 /* connection oriented auth also needs these two lines for it's operation. */
28d4805a 4273 return ch;
4274}
a46d2c0e 4275
4276CBDATA_CLASS_INIT(ConnStateData);
4277
5c336a3b
AJ
4278ConnStateData::ConnStateData() :
4279 AsyncJob("ConnStateData"),
061bbdec 4280#if USE_SSL
08097970 4281 sslBumpMode(Ssl::bumpEnd),
cf6eb29e 4282 switchedToHttps_(false),
fd4624d7 4283 sslServerBump(NULL),
061bbdec 4284#endif
cf6eb29e
CT
4285 stoppedSending_(NULL),
4286 stoppedReceiving_(NULL)
b65351fa 4287{
693cb033
CT
4288 pinning.host = NULL;
4289 pinning.port = -1;
d67acb4e
AJ
4290 pinning.pinned = false;
4291 pinning.auth = false;
693cb033
CT
4292 pinning.zeroReply = false;
4293 pinning.peer = NULL;
b65351fa 4294}
a46d2c0e 4295
4296bool
4297ConnStateData::transparent() const
4298{
40d34a62 4299 return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
a46d2c0e 4300}
4301
4302bool
4303ConnStateData::reading() const
4304{
f84dd7eb 4305 return reader != NULL;
a46d2c0e 4306}
4307
4308void
f84dd7eb 4309ConnStateData::stopReading()
a46d2c0e 4310{
f84dd7eb 4311 if (reading()) {
73c36fd9 4312 comm_read_cancel(clientConnection->fd, reader);
f84dd7eb
AR
4313 reader = NULL;
4314 }
a46d2c0e 4315}
4316
5f8252d2 4317BodyPipe::Pointer
3e62bd58 4318ConnStateData::expectRequestBody(int64_t size)
5f8252d2 4319{
4320 bodyPipe = new BodyPipe(this);
39cb8c41
AR
4321 if (size >= 0)
4322 bodyPipe->setBodySize(size);
4323 else
4324 startDechunkingRequest();
5f8252d2 4325 return bodyPipe;
4326}
4327
39cb8c41
AR
4328int64_t
4329ConnStateData::mayNeedToReadMoreBody() const
4330{
4331 if (!bodyPipe)
4332 return 0; // request without a body or read/produced all body bytes
4333
4334 if (!bodyPipe->bodySizeKnown())
4335 return -1; // probably need to read more, but we cannot be sure
4336
4337 const int64_t needToProduce = bodyPipe->unproducedSize();
4338 const int64_t haveAvailable = static_cast<int64_t>(in.notYetUsed);
4339
4340 if (needToProduce <= haveAvailable)
4341 return 0; // we have read what we need (but are waiting for pipe space)
4342
4343 return needToProduce - haveAvailable;
4344}
4345
55e44db9 4346void
cf6eb29e 4347ConnStateData::stopReceiving(const char *error)
55e44db9 4348{
cf6eb29e
CT
4349 debugs(33, 4, HERE << "receiving error (" << clientConnection << "): " << error <<
4350 "; old sending error: " <<
4351 (stoppedSending() ? stoppedSending_ : "none"));
5f8252d2 4352
cf6eb29e
CT
4353 if (const char *oldError = stoppedReceiving()) {
4354 debugs(33, 3, HERE << "already stopped receiving: " << oldError);
4355 return; // nothing has changed as far as this connection is concerned
4356 }
5f8252d2 4357
cf6eb29e 4358 stoppedReceiving_ = error;
5f8252d2 4359
cf6eb29e
CT
4360 if (const char *sendError = stoppedSending()) {
4361 debugs(33, 3, HERE << "closing because also stopped sending: " << sendError);
4362 clientConnection->close();
4363 }
55e44db9 4364}
4365
eb44b2d7 4366void
e29ccb57
A
4367ConnStateData::expectNoForwarding()
4368{
eb44b2d7
CT
4369 if (bodyPipe != NULL) {
4370 debugs(33, 4, HERE << "no consumer for virgin body " << bodyPipe->status());
4371 bodyPipe->expectNoConsumption();
4372 }
4373}
4374
39cb8c41 4375/// initialize dechunking state
3ff65596 4376void
39cb8c41 4377ConnStateData::startDechunkingRequest()
3ff65596 4378{
39cb8c41
AR
4379 Must(bodyPipe != NULL);
4380 debugs(33, 5, HERE << "start dechunking" << bodyPipe->status());
3ff65596
AR
4381 assert(!in.bodyParser);
4382 in.bodyParser = new ChunkedCodingParser;
3ff65596
AR
4383}
4384
39cb8c41 4385/// put parsed content into input buffer and clean up
3ff65596 4386void
39cb8c41 4387ConnStateData::finishDechunkingRequest(bool withSuccess)
3ff65596 4388{
39cb8c41 4389 debugs(33, 5, HERE << "finish dechunking: " << withSuccess);
3ff65596 4390
39cb8c41
AR
4391 if (bodyPipe != NULL) {
4392 debugs(33, 7, HERE << "dechunked tail: " << bodyPipe->status());
4393 BodyPipe::Pointer myPipe = bodyPipe;
4394 stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize()
4395 Must(!bodyPipe); // we rely on it being nil after we are done with body
4396 if (withSuccess) {
4397 Must(myPipe->bodySizeKnown());
4398 ClientSocketContext::Pointer context = getCurrentContext();
4399 if (context != NULL && context->http && context->http->request)
4400 context->http->request->setContentLength(myPipe->bodySize());
4401 }
3ff65596 4402 }
3ff65596 4403
39cb8c41
AR
4404 delete in.bodyParser;
4405 in.bodyParser = NULL;
3ff65596
AR
4406}
4407
a46d2c0e 4408char *
4409ConnStateData::In::addressToReadInto() const
4410{
4411 return buf + notYetUsed;
4412}
4413
3ff65596 4414ConnStateData::In::In() : bodyParser(NULL),
39cb8c41 4415 buf (NULL), notYetUsed (0), allocatedSize (0)
a46d2c0e 4416{}
4417
4418ConnStateData::In::~In()
4419{
4420 if (allocatedSize)
4421 memFreeBuf(allocatedSize, buf);
39cb8c41 4422 delete bodyParser; // TODO: pool
a46d2c0e 4423}
d67acb4e 4424
655daa06
AR
4425void
4426ConnStateData::sendControlMsg(HttpControlMsg msg)
4427{
eedd4182
AR
4428 if (!isOpen()) {
4429 debugs(33, 3, HERE << "ignoring 1xx due to earlier closure");
655daa06
AR
4430 return;
4431 }
4432
eedd4182
AR
4433 ClientSocketContext::Pointer context = getCurrentContext();
4434 if (context != NULL) {
4435 context->writeControlMsg(msg); // will call msg.cbSuccess
655daa06
AR
4436 return;
4437 }
4438
4439 debugs(33, 3, HERE << " closing due to missing context for 1xx");
73c36fd9 4440 clientConnection->close();
655daa06
AR
4441}
4442
d7ce0bcd 4443/// Our close handler called by Comm when the pinned connection is closed
d67acb4e
AJ
4444void
4445ConnStateData::clientPinnedConnectionClosed(const CommCloseCbParams &io)
4446{
7a957a93
AR
4447 // FwdState might repin a failed connection sooner than this close
4448 // callback is called for the failed connection.
693cb033
CT
4449 assert(pinning.serverConnection == io.conn);
4450 pinning.closeHandler = NULL; // Comm unregisters handlers before calling
4451 const bool sawZeroReply = pinning.zeroReply; // reset when unpinning
4452 unpinConnection();
4453 if (sawZeroReply) {
4454 debugs(33, 3, "Closing client connection on pinned zero reply.");
4455 clientConnection->close();
85563fd9 4456 }
d67acb4e
AJ
4457}
4458
b1cf2350 4459void
a3c6762c 4460ConnStateData::pinConnection(const Comm::ConnectionPointer &pinServer, HttpRequest *request, CachePeer *aPeer, bool auth)
9e008dda 4461{
d67acb4e
AJ
4462 char desc[FD_DESC_SZ];
4463
73c36fd9
AJ
4464 if (Comm::IsConnOpen(pinning.serverConnection)) {
4465 if (pinning.serverConnection->fd == pinServer->fd)
e3a4aecc 4466 return;
d7ce0bcd 4467 }
9e008dda 4468
7a957a93 4469 unpinConnection(); // closes pinned connection, if any, and resets fields
9e008dda 4470
73c36fd9 4471 pinning.serverConnection = pinServer;
d7ce0bcd 4472
85563fd9
AR
4473 debugs(33, 3, HERE << pinning.serverConnection);
4474
d7ce0bcd
AR
4475 // when pinning an SSL bumped connection, the request may be NULL
4476 const char *pinnedHost = "[unknown]";
4477 if (request) {
4478 pinning.host = xstrdup(request->GetHost());
4479 pinning.port = request->port;
4480 pinnedHost = pinning.host;
4481 } else {
4482 pinning.port = pinServer->remote.GetPort();
4483 }
d67acb4e 4484 pinning.pinned = true;
8bcf08e0
FC
4485 if (aPeer)
4486 pinning.peer = cbdataReference(aPeer);
d67acb4e 4487 pinning.auth = auth;
e3a4aecc
AJ
4488 char stmp[MAX_IPSTRLEN];
4489 snprintf(desc, FD_DESC_SZ, "%s pinned connection for %s (%d)",
d7ce0bcd
AR
4490 (auth || !aPeer) ? pinnedHost : aPeer->name,
4491 clientConnection->remote.ToURL(stmp,MAX_IPSTRLEN),
4492 clientConnection->fd);
73c36fd9 4493 fd_note(pinning.serverConnection->fd, desc);
9e008dda 4494
d67acb4e 4495 typedef CommCbMemFunT<ConnStateData, CommCloseCbParams> Dialer;
4299f876 4496 pinning.closeHandler = JobCallback(33, 5,
4cb2536f 4497 Dialer, this, ConnStateData::clientPinnedConnectionClosed);
85563fd9
AR
4498 // remember the pinned connection so that cb does not unpin a fresher one
4499 typedef CommCloseCbParams Params;
4500 Params &params = GetCommParams<Params>(pinning.closeHandler);
4501 params.conn = pinning.serverConnection;
73c36fd9 4502 comm_add_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
d67acb4e
AJ
4503}
4504
e3a4aecc 4505const Comm::ConnectionPointer
a3c6762c 4506ConnStateData::validatePinnedConnection(HttpRequest *request, const CachePeer *aPeer)
d67acb4e 4507{
85563fd9
AR
4508 debugs(33, 7, HERE << pinning.serverConnection);
4509
d67acb4e 4510 bool valid = true;
73c36fd9 4511 if (!Comm::IsConnOpen(pinning.serverConnection))
e3a4aecc 4512 valid = false;
d67acb4e 4513 if (pinning.auth && request && strcasecmp(pinning.host, request->GetHost()) != 0) {
9e008dda 4514 valid = false;
d67acb4e 4515 }
9e008dda
AJ
4516 if (request && pinning.port != request->port) {
4517 valid = false;
d67acb4e 4518 }
9e008dda
AJ
4519 if (pinning.peer && !cbdataReferenceValid(pinning.peer)) {
4520 valid = false;
d67acb4e 4521 }
8bcf08e0 4522 if (aPeer != pinning.peer) {
9e008dda 4523 valid = false;
d67acb4e
AJ
4524 }
4525
9e008dda 4526 if (!valid) {
b1cf2350 4527 /* The pinning info is not safe, remove any pinning info */
9e008dda 4528 unpinConnection();
d67acb4e
AJ
4529 }
4530
73c36fd9 4531 return pinning.serverConnection;
d67acb4e
AJ
4532}
4533
b1cf2350
AJ
4534void
4535ConnStateData::unpinConnection()
d67acb4e 4536{
85563fd9
AR
4537 debugs(33, 3, HERE << pinning.serverConnection);
4538
9e008dda
AJ
4539 if (pinning.peer)
4540 cbdataReferenceDone(pinning.peer);
d67acb4e 4541
d7ce0bcd 4542 if (Comm::IsConnOpen(pinning.serverConnection)) {
87f237a9
A
4543 if (pinning.closeHandler != NULL) {
4544 comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
4545 pinning.closeHandler = NULL;
4546 }
4547 /// also close the server side socket, we should not use it for any future requests...
4548 // TODO: do not close if called from our close handler?
4549 pinning.serverConnection->close();
d67acb4e 4550 }
d7ce0bcd 4551
d67acb4e 4552 safe_free(pinning.host);
e3a4aecc 4553
693cb033
CT
4554 pinning.zeroReply = false;
4555
e3a4aecc
AJ
4556 /* NOTE: pinning.pinned should be kept. This combined with fd == -1 at the end of a request indicates that the host
4557 * connection has gone away */
d67acb4e 4558}