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