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