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