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