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