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