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