]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Language: fr updates
[thirdparty/squid.git] / src / client_side_request.cc
CommitLineData
edce4d98 1
2/*
262a0e14 3 * $Id$
26ac0430 4 *
ae45c4de 5 * DEBUG: section 85 Client-side Request Routines
6 * AUTHOR: Robert Collins (Originally Duane Wessels in client_side.c)
26ac0430 7 *
edce4d98 8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
0a9297f6 10 *
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.
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
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
edce4d98 34 */
35
36
69660be0 37/*
38 * General logic of request processing:
26ac0430 39 *
69660be0 40 * We run a series of tests to determine if access will be permitted, and to do
41 * any redirection. Then we call into the result clientStream to retrieve data.
42 * From that point on it's up to reply management.
edce4d98 43 */
44
f7f3304a 45#include "squid-old.h"
c0941a6a
AR
46#include "acl/FilledChecklist.h"
47#include "acl/Gadgets.h"
a83c6ed6 48#if USE_ADAPTATION
62c7f90e 49#include "adaptation/AccessCheck.h"
1adcebc3 50#include "adaptation/Answer.h"
a22e6cd3 51#include "adaptation/Iterator.h"
abd4b611 52#include "adaptation/Service.h"
3ff65596
AR
53#if ICAP_CLIENT
54#include "adaptation/icap/History.h"
55#endif
de31d06f 56#endif
2f1431ea 57#if USE_AUTH
27bc2077 58#include "auth/UserRequest.h"
2f1431ea 59#endif
27bc2077
AJ
60#include "clientStream.h"
61#include "client_side.h"
62#include "client_side_reply.h"
63#include "client_side_request.h"
64#include "ClientRequestContext.h"
5c336a3b 65#include "comm/Connection.h"
ec41b64c 66#include "comm/Write.h"
27bc2077
AJ
67#include "compat/inet_pton.h"
68#include "fde.h"
31971e6a 69#include "format/Token.h"
ce394734 70#include "HttpHdrCc.h"
27bc2077
AJ
71#include "HttpReply.h"
72#include "HttpRequest.h"
425de4c8 73#include "ip/QosConfig.h"
27bc2077
AJ
74#include "MemObject.h"
75#include "ProtoPort.h"
76#include "Store.h"
77#include "SquidTime.h"
78#include "wordlist.h"
64b66b76 79#include "err_detail_type.h"
4db984be
CT
80#if USE_SSL
81#include "ssl/support.h"
82#endif
3ff65596
AR
83
84
edce4d98 85#if LINGERING_CLOSE
86#define comm_close comm_lingering_close
87#endif
88
89static const char *const crlf = "\r\n";
90
609c620a 91#if FOLLOW_X_FORWARDED_FOR
2efeb0b7 92static void clientFollowXForwardedForCheck(allow_t answer, void *data);
609c620a 93#endif /* FOLLOW_X_FORWARDED_FOR */
3d674977 94
8e2745f4 95CBDATA_CLASS_INIT(ClientRequestContext);
96
97void *
98ClientRequestContext::operator new (size_t size)
99{
100 assert (size == sizeof(ClientRequestContext));
101 CBDATA_INIT_TYPE(ClientRequestContext);
102 ClientRequestContext *result = cbdataAlloc(ClientRequestContext);
aa625860 103 return result;
8e2745f4 104}
62e76326 105
8e2745f4 106void
107ClientRequestContext::operator delete (void *address)
108{
109 ClientRequestContext *t = static_cast<ClientRequestContext *>(address);
aa625860 110 cbdataFree(t);
8e2745f4 111}
112
edce4d98 113/* Local functions */
edce4d98 114/* other */
2efeb0b7 115static void clientAccessCheckDoneWrapper(allow_t, void *);
e0c0d54c 116#if USE_SSL
2efeb0b7 117static void sslBumpAccessCheckDoneWrapper(allow_t, void *);
e0c0d54c 118#endif
59a1efb2 119static int clientHierarchical(ClientHttpRequest * http);
120static void clientInterpretRequestHeaders(ClientHttpRequest * http);
de31d06f 121static RH clientRedirectDoneWrapper;
2efeb0b7 122static void checkNoCacheDoneWrapper(allow_t, void *);
e6ccf245 123extern "C" CSR clientGetMoreData;
124extern "C" CSS clientReplyStatus;
125extern "C" CSD clientReplyDetach;
528b2c61 126static void checkFailureRatio(err_type, hier_code);
edce4d98 127
8e2745f4 128ClientRequestContext::~ClientRequestContext()
129{
de31d06f 130 /*
a546b04b 131 * Release our "lock" on our parent, ClientHttpRequest, if we
132 * still have one
de31d06f 133 */
a546b04b 134
135 if (http)
136 cbdataReferenceDone(http);
62e76326 137
5f8252d2 138 debugs(85,3, HERE << this << " ClientRequestContext destructed");
8e2745f4 139}
140
4e2eb5c3 141ClientRequestContext::ClientRequestContext(ClientHttpRequest *anHttp) : http(cbdataReference(anHttp)), acl_checklist (NULL), redirect_state (REDIRECT_NONE)
edce4d98 142{
57abaac0 143 http_access_done = false;
144 redirect_done = false;
145 no_cache_done = false;
146 interpreted_req_hdrs = false;
e0c0d54c
CT
147#if USE_SSL
148 sslBumpCheckDone = false;
149#endif
0b86805b 150 debugs(85,3, HERE << this << " ClientRequestContext constructed");
edce4d98 151}
152
528b2c61 153CBDATA_CLASS_INIT(ClientHttpRequest);
8e2745f4 154
528b2c61 155void *
156ClientHttpRequest::operator new (size_t size)
157{
158 assert (size == sizeof (ClientHttpRequest));
159 CBDATA_INIT_TYPE(ClientHttpRequest);
160 ClientHttpRequest *result = cbdataAlloc(ClientHttpRequest);
aa625860 161 return result;
528b2c61 162}
163
62e76326 164void
528b2c61 165ClientHttpRequest::operator delete (void *address)
166{
aa625860 167 ClientHttpRequest *t = static_cast<ClientHttpRequest *>(address);
168 cbdataFree(t);
528b2c61 169}
170
26ac0430 171ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) :
a83c6ed6 172#if USE_ADAPTATION
26ac0430 173 AsyncJob("ClientHttpRequest"),
1cf238db 174#endif
26ac0430 175 loggingEntry_(NULL)
528b2c61 176{
1cf238db 177 start_time = current_time;
a0355e95 178 setConn(aConn);
a14f38d0 179 al.tcpClient = clientConnection = aConn->clientConnection;
a0355e95 180 dlinkAdd(this, &active, &ClientActiveRequests);
a83c6ed6 181#if USE_ADAPTATION
b044675d 182 request_satisfaction_mode = false;
183#endif
e0c0d54c
CT
184#if USE_SSL
185 sslBumpNeed = needUnknown;
186#endif
528b2c61 187}
188
0655fa4d 189/*
190 * returns true if client specified that the object must come from the cache
191 * without contacting origin server
192 */
193bool
194ClientHttpRequest::onlyIfCached()const
195{
196 assert(request);
197 return request->cache_control &&
4ce6e3b5 198 request->cache_control->onlyIfCached();
0655fa4d 199}
200
528b2c61 201/*
202 * This function is designed to serve a fairly specific purpose.
203 * Occasionally our vBNS-connected caches can talk to each other, but not
204 * the rest of the world. Here we try to detect frequent failures which
205 * make the cache unusable (e.g. DNS lookup and connect() failures). If
206 * the failure:success ratio goes above 1.0 then we go into "hit only"
207 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
208 * will only fetch HITs from us if they are using the ICP protocol. We
209 * stay in this mode for 5 minutes.
26ac0430 210 *
528b2c61 211 * Duane W., Sept 16, 1996
212 */
213
214#define FAILURE_MODE_TIME 300
215
216static void
217checkFailureRatio(err_type etype, hier_code hcode)
218{
219 static double magic_factor = 100.0;
220 double n_good;
221 double n_bad;
62e76326 222
528b2c61 223 if (hcode == HIER_NONE)
62e76326 224 return;
225
528b2c61 226 n_good = magic_factor / (1.0 + request_failure_ratio);
62e76326 227
528b2c61 228 n_bad = magic_factor - n_good;
62e76326 229
528b2c61 230 switch (etype) {
62e76326 231
528b2c61 232 case ERR_DNS_FAIL:
62e76326 233
528b2c61 234 case ERR_CONNECT_FAIL:
3712be3f 235 case ERR_SECURE_CONNECT_FAIL:
62e76326 236
528b2c61 237 case ERR_READ_ERROR:
62e76326 238 n_bad++;
239 break;
240
528b2c61 241 default:
62e76326 242 n_good++;
528b2c61 243 }
62e76326 244
528b2c61 245 request_failure_ratio = n_bad / n_good;
62e76326 246
528b2c61 247 if (hit_only_mode_until > squid_curtime)
62e76326 248 return;
249
528b2c61 250 if (request_failure_ratio < 1.0)
62e76326 251 return;
252
bf8fe701 253 debugs(33, 0, "Failure Ratio at "<< std::setw(4)<<
254 std::setprecision(3) << request_failure_ratio);
62e76326 255
bf8fe701 256 debugs(33, 0, "Going into hit-only-mode for " <<
257 FAILURE_MODE_TIME / 60 << " minutes...");
62e76326 258
528b2c61 259 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
62e76326 260
528b2c61 261 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
262}
263
264ClientHttpRequest::~ClientHttpRequest()
265{
bf8fe701 266 debugs(33, 3, "httpRequestFree: " << uri);
72bdee4c 267 PROF_start(httpRequestFree);
62e76326 268
5f8252d2 269 // Even though freeResources() below may destroy the request,
270 // we no longer set request->body_pipe to NULL here
271 // because we did not initiate that pipe (ConnStateData did)
62e76326 272
528b2c61 273 /* the ICP check here was erroneous
26ac0430 274 * - StoreEntry::releaseRequest was always called if entry was valid
528b2c61 275 */
276 assert(logType < LOG_TYPE_MAX);
9ce7856a 277
528b2c61 278 logRequest();
9ce7856a 279
0976f8db 280 loggingEntry(NULL);
281
528b2c61 282 if (request)
62e76326 283 checkFailureRatio(request->errType, al.hier.code);
284
528b2c61 285 freeResources();
62e76326 286
a83c6ed6
AR
287#if USE_ADAPTATION
288 announceInitiatorAbort(virginHeadSource);
9d4d7c5e 289
a83c6ed6
AR
290 if (adaptedBodySource != NULL)
291 stopConsumingFrom(adaptedBodySource);
de31d06f 292#endif
9ce7856a 293
de31d06f 294 if (calloutContext)
295 delete calloutContext;
296
be364179
AJ
297 clientConnection = NULL;
298
26ac0430
AJ
299 if (conn_)
300 cbdataReferenceDone(conn_);
1cf238db 301
528b2c61 302 /* moving to the next connection is handled by the context free */
303 dlinkDelete(&active, &ClientActiveRequests);
9ce7856a 304
72bdee4c 305 PROF_stop(httpRequestFree);
528b2c61 306}
62e76326 307
11992b6f
AJ
308/**
309 * Create a request and kick it off
310 *
311 * \retval 0 success
312 * \retval -1 failure
313 *
69660be0 314 * TODO: Pass in the buffers to be used in the inital Read request, as they are
315 * determined by the user
edce4d98 316 */
11992b6f 317int
60745f24 318clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
0655fa4d 319 CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *header,
62e76326 320 char *tailbuf, size_t taillen)
edce4d98 321{
322 size_t url_sz;
a0355e95 323 ClientHttpRequest *http = new ClientHttpRequest(NULL);
190154cf 324 HttpRequest *request;
528b2c61 325 StoreIOBuffer tempBuffer;
1cf238db 326 http->start_time = current_time;
edce4d98 327 /* this is only used to adjust the connection offset in client_side.c */
328 http->req_sz = 0;
c8be6d7b 329 tempBuffer.length = taillen;
330 tempBuffer.data = tailbuf;
edce4d98 331 /* client stream setup */
332 clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
0655fa4d 333 clientReplyStatus, new clientReplyContext(http), streamcallback,
62e76326 334 streamdetach, streamdata, tempBuffer);
edce4d98 335 /* make it visible in the 'current acctive requests list' */
edce4d98 336 /* Set flags */
a46d2c0e 337 /* internal requests only makes sense in an
338 * accelerator today. TODO: accept flags ? */
339 http->flags.accel = 1;
edce4d98 340 /* allow size for url rewriting */
341 url_sz = strlen(url) + Config.appendDomainLen + 5;
e6ccf245 342 http->uri = (char *)xcalloc(url_sz, 1);
edce4d98 343 strcpy(http->uri, url);
344
c21ad0f5 345 if ((request = HttpRequest::CreateFromUrlAndMethod(http->uri, method)) == NULL) {
bf8fe701 346 debugs(85, 5, "Invalid URL: " << http->uri);
62e76326 347 return -1;
edce4d98 348 }
62e76326 349
69660be0 350 /*
11992b6f 351 * now update the headers in request with our supplied headers. urlParse
69660be0 352 * should return a blank header set, but we use Update to be sure of
353 * correctness.
edce4d98 354 */
355 if (header)
a9925b40 356 request->header.update(header, NULL);
62e76326 357
edce4d98 358 http->log_uri = xstrdup(urlCanonicalClean(request));
62e76326 359
edce4d98 360 /* http struct now ready */
361
69660be0 362 /*
363 * build new header list *? TODO
edce4d98 364 */
365 request->flags.accelerated = http->flags.accel;
62e76326 366
a46d2c0e 367 request->flags.internalclient = 1;
368
369 /* this is an internally created
370 * request, not subject to acceleration
371 * target overrides */
69660be0 372 /*
373 * FIXME? Do we want to detect and handle internal requests of internal
374 * objects ?
375 */
edce4d98 376
377 /* Internally created requests cannot have bodies today */
378 request->content_length = 0;
62e76326 379
cc192b50 380 request->client_addr.SetNoAddr();
62e76326 381
3d674977
AJ
382#if FOLLOW_X_FORWARDED_FOR
383 request->indirect_client_addr.SetNoAddr();
384#endif /* FOLLOW_X_FORWARDED_FOR */
26ac0430 385
cc192b50 386 request->my_addr.SetNoAddr(); /* undefined for internal requests */
62e76326 387
cc192b50 388 request->my_addr.SetPort(0);
62e76326 389
3872be7c
AJ
390 /* Our version is HTTP/1.1 */
391 HttpVersion http_ver(1,1);
edce4d98 392 request->http_ver = http_ver;
62e76326 393
6dd9f4bd 394 http->request = HTTPMSGLOCK(request);
edce4d98 395
396 /* optional - skip the access check ? */
de31d06f 397 http->calloutContext = new ClientRequestContext(http);
398
57abaac0 399 http->calloutContext->http_access_done = false;
de31d06f 400
57abaac0 401 http->calloutContext->redirect_done = true;
de31d06f 402
57abaac0 403 http->calloutContext->no_cache_done = true;
de31d06f 404
405 http->doCallouts();
62e76326 406
edce4d98 407 return 0;
408}
409
de31d06f 410bool
411ClientRequestContext::httpStateIsValid()
412{
413 ClientHttpRequest *http_ = http;
414
415 if (cbdataReferenceValid(http_))
416 return true;
417
418 http = NULL;
419
420 cbdataReferenceDone(http_);
421
422 return false;
423}
424
3d674977
AJ
425#if FOLLOW_X_FORWARDED_FOR
426/**
a9044668 427 * clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
3d674977
AJ
428 * against the followXFF ACL, or cleans up and passes control to
429 * clientAccessCheck().
d096ace1
AJ
430 *
431 * The trust model here is a little ambiguous. So to clarify the logic:
432 * - we may always use the direct client address as the client IP.
a9044668 433 * - these trust tests merey tell whether we trust given IP enough to believe the
d096ace1
AJ
434 * IP string which it appended to the X-Forwarded-For: header.
435 * - if at any point we don't trust what an IP adds we stop looking.
436 * - at that point the current contents of indirect_client_addr are the value set
437 * by the last previously trusted IP.
438 * ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
3d674977 439 */
3d674977 440static void
2efeb0b7 441clientFollowXForwardedForCheck(allow_t answer, void *data)
3d674977
AJ
442{
443 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
3d674977
AJ
444
445 if (!calloutContext->httpStateIsValid())
446 return;
447
d096ace1
AJ
448 ClientHttpRequest *http = calloutContext->http;
449 HttpRequest *request = http->request;
450
3d674977
AJ
451 /*
452 * answer should be be ACCESS_ALLOWED or ACCESS_DENIED if we are
453 * called as a result of ACL checks, or -1 if we are called when
454 * there's nothing left to do.
455 */
456 if (answer == ACCESS_ALLOWED &&
26ac0430 457 request->x_forwarded_for_iterator.size () != 0) {
d096ace1 458
3d674977 459 /*
d096ace1
AJ
460 * Remove the last comma-delimited element from the
461 * x_forwarded_for_iterator and use it to repeat the cycle.
462 */
3d674977
AJ
463 const char *p;
464 const char *asciiaddr;
465 int l;
b7ac5457 466 Ip::Address addr;
bb790702 467 p = request->x_forwarded_for_iterator.termedBuf();
3d674977
AJ
468 l = request->x_forwarded_for_iterator.size();
469
470 /*
471 * XXX x_forwarded_for_iterator should really be a list of
472 * IP addresses, but it's a String instead. We have to
473 * walk backwards through the String, biting off the last
474 * comma-delimited part each time. As long as the data is in
475 * a String, we should probably implement and use a variant of
476 * strListGetItem() that walks backwards instead of forwards
477 * through a comma-separated list. But we don't even do that;
478 * we just do the work in-line here.
479 */
480 /* skip trailing space and commas */
481 while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
482 l--;
483 request->x_forwarded_for_iterator.cut(l);
484 /* look for start of last item in list */
485 while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
486 l--;
487 asciiaddr = p+l;
fafd0efa 488 if ((addr = asciiaddr)) {
3d674977
AJ
489 request->indirect_client_addr = addr;
490 request->x_forwarded_for_iterator.cut(l);
d096ace1
AJ
491 calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
492 if (!Config.onoff.acl_uses_indirect_client) {
493 /* override the default src_addr tested if we have to go deeper than one level into XFF */
494 Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
3d674977 495 }
d096ace1 496 calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
3d674977
AJ
497 return;
498 }
499 } /*if (answer == ACCESS_ALLOWED &&
500 request->x_forwarded_for_iterator.size () != 0)*/
501
502 /* clean up, and pass control to clientAccessCheck */
26ac0430 503 if (Config.onoff.log_uses_indirect_client) {
3d674977
AJ
504 /*
505 * Ensure that the access log shows the indirect client
506 * instead of the direct client.
507 */
508 ConnStateData *conn = http->getConn();
509 conn->log_addr = request->indirect_client_addr;
510 }
511 request->x_forwarded_for_iterator.clean();
512 request->flags.done_follow_x_forwarded_for = 1;
513
d096ace1
AJ
514 if (answer != ACCESS_ALLOWED && answer != ACCESS_DENIED) {
515 debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
493d3865
AJ
516 }
517
518 /* process actual access ACL as normal. */
519 calloutContext->clientAccessCheck();
3d674977
AJ
520}
521#endif /* FOLLOW_X_FORWARDED_FOR */
522
fe97983f
AJ
523static void
524hostHeaderIpVerifyWrapper(const ipcache_addrs* ia, const DnsLookupDetails &dns, void *data)
525{
526 ClientRequestContext *c = static_cast<ClientRequestContext*>(data);
527 c->hostHeaderIpVerify(ia, dns);
528}
529
530void
531ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs* ia, const DnsLookupDetails &dns)
532{
533 Comm::ConnectionPointer clientConn = http->getConn()->clientConnection;
534
535 // note the DNS details for the transaction stats.
536 http->request->recordLookup(dns);
537
538 if (ia != NULL && ia->count > 0) {
539 // Is the NAT destination IP in DNS?
540 for (int i = 0; i < ia->count; i++) {
541 if (clientConn->local.matchIPAddr(ia->in_addrs[i]) == 0) {
542 debugs(85, 3, HERE << "validate IP " << clientConn->local << " possible from Host:");
543 http->doCallouts();
544 return;
545 }
546 debugs(85, 3, HERE << "validate IP " << clientConn->local << " non-match from Host: IP " << ia->in_addrs[i]);
547 }
548 }
549 debugs(85, 3, HERE << "FAIL: validate IP " << clientConn->local << " possible from Host:");
05b28f84 550 hostHeaderVerifyFailed("local IP", "any domain IP");
fe97983f
AJ
551}
552
553void
05b28f84 554ClientRequestContext::hostHeaderVerifyFailed(const char *A, const char *B)
fe97983f 555{
8f489ad7
AJ
556 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: Host header forgery detected on " <<
557 http->getConn()->clientConnection << " (" << A << " does not match " << B << ")");
558 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: By user agent: " << http->request->header.getStr(HDR_USER_AGENT));
559 debugs(85, DBG_IMPORTANT, "SECURITY ALERT: on URL: " << urlCanonical(http->request));
fe97983f
AJ
560
561 // IP address validation for Host: failed. reject the connection.
562 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
563 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
564 assert (repContext);
565 repContext->setReplyToError(ERR_INVALID_REQ, HTTP_CONFLICT,
566 http->request->method, NULL,
567 http->getConn()->clientConnection->remote,
568 http->request,
569 NULL,
570#if USE_AUTH
571 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
572 http->getConn()->auth_user_request : http->request->auth_user_request);
573#else
574 NULL);
575#endif
576 node = (clientStreamNode *)http->client_stream.tail->data;
577 clientStreamRead(node, http, node->readBuffer);
578}
579
580void
581ClientRequestContext::hostHeaderVerify()
582{
583 // Require a Host: header.
584 const char *host = http->request->header.getStr(HDR_HOST);
fe97983f
AJ
585
586 if (!host) {
587 // TODO: dump out the HTTP/1.1 error about missing host header.
588 // otherwise this is fine, can't forge a header value when its not even set.
589 debugs(85, 3, HERE << "validate skipped with no Host: header present.");
590 http->doCallouts();
591 return;
592 }
593
8f489ad7
AJ
594 if (http->request->flags.internal) {
595 // TODO: kill this when URL handling allows partial URLs out of accel mode
596 // and we no longer screw with the URL just to add our internal host there
597 debugs(85, 6, HERE << "validate skipped due to internal composite URL.");
598 http->doCallouts();
599 return;
600 }
601
fe97983f
AJ
602 // Locate if there is a port attached, strip ready for IP lookup
603 char *portStr = NULL;
91663dce
AJ
604 char *hostB = xstrdup(host);
605 host = hostB;
fe97983f
AJ
606 if (host[0] == '[') {
607 // IPv6 literal.
fe97983f 608 portStr = strchr(hostB, ']');
91663dce
AJ
609 if (portStr && *(++portStr) != ':') {
610 portStr = NULL;
fe97983f 611 }
91663dce 612 } else {
fe97983f 613 // Domain or IPv4 literal with port
fe97983f 614 portStr = strrchr(hostB, ':');
91663dce
AJ
615 }
616
617 uint16_t port = 0;
618 if (portStr) {
619 *portStr = '\0'; // strip the ':'
620 if (*(++portStr) != '\0')
621 port = xatoi(portStr);
fe97983f
AJ
622 }
623
624 debugs(85, 3, HERE << "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
625 if (http->request->flags.intercepted || http->request->flags.spoof_client_ip) {
ba4d9da0 626 // verify the Host: port (if any) matches the apparent destination
fe97983f 627 if (portStr && port != http->getConn()->clientConnection->local.GetPort()) {
05b28f84
AJ
628 debugs(85, 3, HERE << "FAIL on validate port " << http->getConn()->clientConnection->local.GetPort() <<
629 " matches Host: port " << port << " (" << portStr << ")");
630 hostHeaderVerifyFailed("intercepted port", portStr);
ba4d9da0
AJ
631 } else {
632 // XXX: match the scheme default port against the apparent destination
fe97983f 633
ba4d9da0
AJ
634 // verify the destination DNS is one of the Host: headers IPs
635 ipcache_nbgethostbyname(host, hostHeaderIpVerifyWrapper, this);
636 }
06059513 637 } else if (!Config.onoff.hostStrictVerify) {
90529125
AJ
638 debugs(85, 3, HERE << "validate skipped.");
639 http->doCallouts();
8f489ad7
AJ
640 } else if (strlen(host) != strlen(http->request->GetHost())) {
641 // Verify forward-proxy requested URL domain matches the Host: header
642 debugs(85, 3, HERE << "FAIL on validate URL domain length " << http->request->GetHost() << " matches Host: " << host);
643 hostHeaderVerifyFailed(host, http->request->GetHost());
644 } else if (matchDomainName(host, http->request->GetHost()) != 0) {
ba4d9da0 645 // Verify forward-proxy requested URL domain matches the Host: header
fe97983f 646 debugs(85, 3, HERE << "FAIL on validate URL domain " << http->request->GetHost() << " matches Host: " << host);
05b28f84 647 hostHeaderVerifyFailed(host, http->request->GetHost());
ba4d9da0
AJ
648 } else if (portStr && port != http->request->port) {
649 // Verify forward-proxy requested URL domain matches the Host: header
650 debugs(85, 3, HERE << "FAIL on validate URL port " << http->request->port << " matches Host: port " << portStr);
651 hostHeaderVerifyFailed("URL port", portStr);
65d2fdbf 652 } else if (!portStr && http->request->method != METHOD_CONNECT && http->request->port != urlDefaultPort(http->request->protocol)) {
ba4d9da0 653 // Verify forward-proxy requested URL domain matches the Host: header
65d2fdbf 654 // Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
ba4d9da0
AJ
655 debugs(85, 3, HERE << "FAIL on validate URL port " << http->request->port << " matches Host: default port " << urlDefaultPort(http->request->protocol));
656 hostHeaderVerifyFailed("URL port", "default port");
657 } else {
658 // Okay no problem.
659 debugs(85, 3, HERE << "validate passed.");
660 http->doCallouts();
fe97983f 661 }
ba4d9da0 662 safe_free(hostB);
fe97983f
AJ
663}
664
edce4d98 665/* This is the entry point for external users of the client_side routines */
666void
de31d06f 667ClientRequestContext::clientAccessCheck()
edce4d98 668{
3d674977
AJ
669#if FOLLOW_X_FORWARDED_FOR
670 if (!http->request->flags.done_follow_x_forwarded_for &&
26ac0430
AJ
671 Config.accessList.followXFF &&
672 http->request->header.has(HDR_X_FORWARDED_FOR)) {
d096ace1
AJ
673
674 /* we always trust the direct client address for actual use */
675 http->request->indirect_client_addr = http->request->client_addr;
fafd0efa 676 http->request->indirect_client_addr.SetPort(0);
d096ace1
AJ
677
678 /* setup the XFF iterator for processing */
679 http->request->x_forwarded_for_iterator = http->request->header.getList(HDR_X_FORWARDED_FOR);
680
681 /* begin by checking to see if we trust direct client enough to walk XFF */
682 acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
683 acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
3d674977
AJ
684 return;
685 }
686#endif /* FOLLOW_X_FORWARDED_FOR */
493d3865 687
b50e327b
AJ
688 if (Config.accessList.http) {
689 acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
690 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
691 } else {
692 debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
693 clientAccessCheckDone(ACCESS_DENIED);
694 }
edce4d98 695}
696
533493da
AJ
697/**
698 * Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
699 * The default here is to allow all. Since the earlier http_access should do a default deny all.
700 * This check is just for a last-minute denial based on adapted request headers.
701 */
702void
703ClientRequestContext::clientAccessCheck2()
704{
705 if (Config.accessList.adapted_http) {
706 acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
707 acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
708 } else {
327e2131 709 debugs(85, 2, HERE << "No adapted_http_access configuration. default: ALLOW");
533493da
AJ
710 clientAccessCheckDone(ACCESS_ALLOWED);
711 }
712}
713
edce4d98 714void
2efeb0b7 715clientAccessCheckDoneWrapper(allow_t answer, void *data)
edce4d98 716{
de31d06f 717 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
fbade053 718
de31d06f 719 if (!calloutContext->httpStateIsValid())
62e76326 720 return;
62e76326 721
de31d06f 722 calloutContext->clientAccessCheckDone(answer);
723}
724
ed6163ef
AJ
725bool
726ClientRequestContext::maybeSendAuthChallenge(const allow_t &answer)
de31d06f 727{
728 acl_checklist = NULL;
edce4d98 729 err_type page_id;
730 http_status status;
f5691f9c 731
2f1431ea
AJ
732#if USE_AUTH
733 char const *proxy_auth_msg = "<null>";
94a396a3 734 if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
f5691f9c 735 proxy_auth_msg = http->getConn()->auth_user_request->denyMessage("<null>");
736 else if (http->request->auth_user_request != NULL)
737 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
2f1431ea 738#endif
62e76326 739
ed6163ef
AJ
740 bool auth_challenge = false;
741 switch (answer) {
742 case ACCESS_ALLOWED:
743 case ACCESS_AUTH_EXPIRED_OK:
744 // No authentication challenge on these ACL results
745 return auth_challenge;
746
747 case ACCESS_DENIED:
748 case ACCESS_DUNNO:
749 // MAYBE challenge on these ACL results
750 auth_challenge |= aclIsProxyAuth(AclMatchedName);
751 break;
752
753 case ACCESS_AUTH_REQUIRED:
754 case ACCESS_AUTH_EXPIRED_BAD:
755 // Send an auth challenge or error
756 auth_challenge = true;
757 }
309347ef 758
ed6163ef
AJ
759 // auth has a grace period where credentials can be expired but okay not to challenge.
760 debugs(85, 5, "Access Denied: " << http->uri);
761 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
2f1431ea 762#if USE_AUTH
ed6163ef
AJ
763 if (auth_challenge)
764 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
2f1431ea 765#endif
9ce7856a 766
ed6163ef
AJ
767 /*
768 * NOTE: get page_id here, based on AclMatchedName because if
769 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
770 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
771 * <pribeiro@isel.pt>
772 */
773 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, auth_challenge);
9ce7856a 774
ed6163ef 775 http->logType = LOG_TCP_DENIED;
62e76326 776
ed6163ef 777 if (auth_challenge) {
2f1431ea 778#if USE_AUTH
ed6163ef
AJ
779 if (http->request->flags.sslBumped) {
780 /*SSL Bumped request, authentication is not possible*/
2f1431ea 781 status = HTTP_FORBIDDEN;
ed6163ef
AJ
782 } else if (!http->flags.accel) {
783 /* Proxy authorisation needed */
784 status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
62e76326 785 } else {
ed6163ef
AJ
786 /* WWW authorisation needed */
787 status = HTTP_UNAUTHORIZED;
62e76326 788 }
ed6163ef
AJ
789#else
790 // need auth, but not possible to do.
791 status = HTTP_FORBIDDEN;
792#endif
793 if (page_id == ERR_NONE)
794 page_id = ERR_CACHE_ACCESS_DENIED;
795 } else {
796 status = HTTP_FORBIDDEN;
797
798 if (page_id == ERR_NONE)
799 page_id = ERR_ACCESS_DENIED;
800 }
62e76326 801
ed6163ef
AJ
802 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
803 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
804 assert (repContext);
805 Ip::Address tmpnoaddr;
806 tmpnoaddr.SetNoAddr();
807 repContext->setReplyToError(page_id, status,
808 http->request->method,
809 NULL,
810 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,
811 http->request,
812 NULL,
2f1431ea 813#if USE_AUTH
ed6163ef
AJ
814 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
815 http->getConn()->auth_user_request : http->request->auth_user_request);
2f1431ea 816#else
ed6163ef 817 NULL);
2f1431ea 818#endif
ed6163ef
AJ
819 http->getConn()->flags.readMore = true; // resume any pipeline reads.
820 node = (clientStreamNode *)http->client_stream.tail->data;
821 clientStreamRead(node, http, node->readBuffer);
822 return true;
823}
824
825void
826ClientRequestContext::clientAccessCheckDone(const allow_t &answer)
827{
828 debugs(85, 2, "The request " <<
829 RequestMethodStr(http->request->method) << " " <<
830 http->uri << " is " << answer <<
831 ", because it matched '" <<
832 (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
833
834 if (maybeSendAuthChallenge(answer))
a546b04b 835 return;
de31d06f 836
309347ef 837 /* ACCESS_ALLOWED (or auth in grace period ACCESS_AUTH_EXPIRED_OK) continues here ... */
de31d06f 838 safe_free(http->uri);
839
840 http->uri = xstrdup(urlCanonical(http->request));
841
842 http->doCallouts();
843}
844
a83c6ed6 845#if USE_ADAPTATION
de31d06f 846void
79628299 847ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
de31d06f 848{
a83c6ed6 849 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
6ec67de9 850
e1381638 851#if ICAP_CLIENT
79628299 852 Adaptation::Icap::History::Pointer ih = request->icapHistory();
e1381638 853 if (ih != NULL) {
79628299
CT
854 if (getConn() != NULL) {
855 ih->rfc931 = getConn()->clientConnection->rfc931;
e1381638 856#if USE_SSL
79628299
CT
857 assert(getConn()->clientConnection != NULL);
858 ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl);
e1381638 859#endif
3ff65596 860 }
79628299
CT
861 ih->log_uri = log_uri;
862 ih->req_sz = req_sz;
3ff65596
AR
863 }
864#endif
865
a22e6cd3
AR
866 if (!g) {
867 debugs(85,3, HERE << "no adaptation needed");
79628299 868 doCallouts();
5f8252d2 869 return;
870 }
de31d06f 871
79628299 872 startAdaptation(g);
edce4d98 873}
874
de31d06f 875#endif
876
14cc8559 877static void
2efeb0b7 878clientRedirectAccessCheckDone(allow_t answer, void *data)
14cc8559 879{
880 ClientRequestContext *context = (ClientRequestContext *)data;
ed6163ef
AJ
881
882 if (context->maybeSendAuthChallenge(answer))
883 return;
14cc8559 884
885 if (answer == ACCESS_ALLOWED)
ed6163ef 886 redirectStart(context->http, clientRedirectDoneWrapper, context);
14cc8559 887 else
de31d06f 888 context->clientRedirectDone(NULL);
14cc8559 889}
890
de31d06f 891void
892ClientRequestContext::clientRedirectStart()
14cc8559 893{
48e7baac 894 debugs(33, 5, HERE << "'" << http->uri << "'");
14cc8559 895
14cc8559 896 if (Config.accessList.redirector) {
de31d06f 897 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
898 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
14cc8559 899 } else
de31d06f 900 redirectStart(http, clientRedirectDoneWrapper, this);
14cc8559 901}
902
edce4d98 903static int
59a1efb2 904clientHierarchical(ClientHttpRequest * http)
edce4d98 905{
906 const char *url = http->uri;
190154cf 907 HttpRequest *request = http->request;
60745f24 908 HttpRequestMethod method = request->method;
edce4d98 909 const wordlist *p = NULL;
910
69660be0 911 /*
912 * IMS needs a private key, so we can use the hierarchy for IMS only if our
913 * neighbors support private keys
914 */
62e76326 915
edce4d98 916 if (request->flags.ims && !neighbors_do_private_keys)
62e76326 917 return 0;
918
69660be0 919 /*
920 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 921 * (they can even be cached if the correct headers are set on the reply)
edce4d98 922 */
923 if (request->flags.auth)
62e76326 924 return 0;
925
edce4d98 926 if (method == METHOD_TRACE)
62e76326 927 return 1;
928
edce4d98 929 if (method != METHOD_GET)
62e76326 930 return 0;
931
edce4d98 932 /* scan hierarchy_stoplist */
933 for (p = Config.hierarchy_stoplist; p; p = p->next)
62e76326 934 if (strstr(url, p->key))
935 return 0;
936
edce4d98 937 if (request->flags.loopdetect)
62e76326 938 return 0;
939
0c3d3f65 940 if (request->protocol == AnyP::PROTO_HTTP)
62e76326 941 return httpCachable(method);
942
0c3d3f65 943 if (request->protocol == AnyP::PROTO_GOPHER)
62e76326 944 return gopherCachable(request);
945
39a19cb7 946 if (request->protocol == AnyP::PROTO_CACHE_OBJECT)
62e76326 947 return 0;
948
edce4d98 949 return 1;
950}
951
46a1f562
HN
952static void
953clientCheckPinning(ClientHttpRequest * http)
954{
955 HttpRequest *request = http->request;
956 HttpHeader *req_hdr = &request->header;
957 ConnStateData *http_conn = http->getConn();
958
959 /* Internal requests such as those from ESI includes may be without
960 * a client connection
961 */
962 if (!http_conn)
f54f527e 963 return;
46a1f562
HN
964
965 request->flags.connection_auth_disabled = http_conn->port->connection_auth_disabled;
966 if (!request->flags.connection_auth_disabled) {
73c36fd9 967 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562
HN
968 if (http_conn->pinning.auth) {
969 request->flags.connection_auth = 1;
970 request->flags.auth = 1;
971 } else {
972 request->flags.connection_proxy_auth = 1;
973 }
b1cf2350
AJ
974 // These should already be linked correctly.
975 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
976 }
977 }
978
979 /* check if connection auth is used, and flag as candidate for pinning
980 * in such case.
981 * Note: we may need to set flags.connection_auth even if the connection
982 * is already pinned if it was pinned earlier due to proxy auth
983 */
984 if (!request->flags.connection_auth) {
985 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
986 HttpHeaderPos pos = HttpHeaderInitPos;
987 HttpHeaderEntry *e;
988 int may_pin = 0;
989 while ((e = req_hdr->getEntry(&pos))) {
990 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
991 const char *value = e->value.rawBuf();
992 if (strncasecmp(value, "NTLM ", 5) == 0
993 ||
994 strncasecmp(value, "Negotiate ", 10) == 0
995 ||
996 strncasecmp(value, "Kerberos ", 9) == 0) {
997 if (e->id == HDR_AUTHORIZATION) {
998 request->flags.connection_auth = 1;
999 may_pin = 1;
1000 } else {
1001 request->flags.connection_proxy_auth = 1;
1002 may_pin = 1;
1003 }
1004 }
1005 }
1006 }
1007 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
1008 // These should already be linked correctly. Just need the ServerConnection to pinn.
1009 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
1010 }
1011 }
1012 }
1013}
1014
edce4d98 1015static void
59a1efb2 1016clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 1017{
190154cf 1018 HttpRequest *request = http->request;
0ef77270 1019 HttpHeader *req_hdr = &request->header;
edce4d98 1020 int no_cache = 0;
edce4d98 1021 const char *str;
62e76326 1022
edce4d98 1023 request->imslen = -1;
a9925b40 1024 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 1025
edce4d98 1026 if (request->ims > 0)
62e76326 1027 request->flags.ims = 1;
1028
432bc83c
HN
1029 if (!request->flags.ignore_cc) {
1030 if (req_hdr->has(HDR_PRAGMA)) {
1031 String s = req_hdr->getList(HDR_PRAGMA);
62e76326 1032
432bc83c
HN
1033 if (strListIsMember(&s, "no-cache", ','))
1034 no_cache++;
30abd221 1035
432bc83c
HN
1036 s.clean();
1037 }
62e76326 1038
432bc83c 1039 if (request->cache_control)
4ce6e3b5 1040 if (request->cache_control->noCache())
432bc83c 1041 no_cache++;
62e76326 1042
432bc83c
HN
1043 /*
1044 * Work around for supporting the Reload button in IE browsers when Squid
1045 * is used as an accelerator or transparent proxy, by turning accelerated
1046 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
1047 * actually only fixed in SP1, but we can't tell whether we are talking to
1048 * SP1 or not so all 5.5 versions are treated 'normally').
1049 */
1050 if (Config.onoff.ie_refresh) {
1051 if (http->flags.accel && request->flags.ims) {
1052 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
1053 if (strstr(str, "MSIE 5.01") != NULL)
1054 no_cache++;
1055 else if (strstr(str, "MSIE 5.0") != NULL)
1056 no_cache++;
1057 else if (strstr(str, "MSIE 4.") != NULL)
1058 no_cache++;
1059 else if (strstr(str, "MSIE 3.") != NULL)
1060 no_cache++;
1061 }
62e76326 1062 }
1063 }
edce4d98 1064 }
914b89a2 1065
1066 if (request->method == METHOD_OTHER) {
26ac0430 1067 no_cache++;
60745f24 1068 }
62e76326 1069
edce4d98 1070 if (no_cache) {
626096be 1071#if USE_HTTP_VIOLATIONS
62e76326 1072
1073 if (Config.onoff.reload_into_ims)
1074 request->flags.nocache_hack = 1;
1075 else if (refresh_nocache_hack)
1076 request->flags.nocache_hack = 1;
1077 else
edce4d98 1078#endif
62e76326 1079
1080 request->flags.nocache = 1;
edce4d98 1081 }
62e76326 1082
0ef77270 1083 /* ignore range header in non-GETs or non-HEADs */
1084 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
56713d9a
AR
1085 // XXX: initialize if we got here without HttpRequest::parseHeader()
1086 if (!request->range)
1087 request->range = req_hdr->getRange();
62e76326 1088
1089 if (request->range) {
1090 request->flags.range = 1;
1091 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1092 /* XXX: This is suboptimal. We should give the stream the range set,
1093 * and thereby let the top of the stream set the offset when the
26ac0430 1094 * size becomes known. As it is, we will end up requesting from 0
62e76326 1095 * for evey -X range specification.
1096 * RBC - this may be somewhat wrong. We should probably set the range
1097 * iter up at this point.
1098 */
1099 node->readBuffer.offset = request->range->lowestOffset(0);
1100 http->range_iter.pos = request->range->begin();
1101 http->range_iter.valid = true;
1102 }
edce4d98 1103 }
62e76326 1104
0ef77270 1105 /* Only HEAD and GET requests permit a Range or Request-Range header.
1106 * If these headers appear on any other type of request, delete them now.
1107 */
1108 else {
1109 req_hdr->delById(HDR_RANGE);
1110 req_hdr->delById(HDR_REQUEST_RANGE);
56713d9a 1111 delete request->range;
0ef77270 1112 request->range = NULL;
1113 }
1114
a9925b40 1115 if (req_hdr->has(HDR_AUTHORIZATION))
62e76326 1116 request->flags.auth = 1;
1117
46a1f562 1118 clientCheckPinning(http);
d67acb4e 1119
edce4d98 1120 if (request->login[0] != '\0')
62e76326 1121 request->flags.auth = 1;
1122
a9925b40 1123 if (req_hdr->has(HDR_VIA)) {
30abd221 1124 String s = req_hdr->getList(HDR_VIA);
62e76326 1125 /*
3c4fcf0f 1126 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1127 * Note ThisCache2 has a space prepended to the hostname so we don't
1128 * accidentally match super-domains.
1129 */
1130
1131 if (strListIsSubstr(&s, ThisCache2, ',')) {
1132 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
1133 request, (ObjPackMethod) & httpRequestPack);
1134 request->flags.loopdetect = 1;
1135 }
1136
21f6708d 1137#if USE_FORW_VIA_DB
bb790702 1138 fvdbCountVia(s.termedBuf());
62e76326 1139
edce4d98 1140#endif
62e76326 1141
30abd221 1142 s.clean();
edce4d98 1143 }
62e76326 1144
21f6708d 1145#if USE_FORW_VIA_DB
62e76326 1146
a9925b40 1147 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 1148 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 1149 fvdbCountForw(s.termedBuf());
30abd221 1150 s.clean();
edce4d98 1151 }
62e76326 1152
edce4d98 1153#endif
62e76326 1154
610ee341 1155 request->flags.cachable = http->request->cacheable();
62e76326 1156
edce4d98 1157 if (clientHierarchical(http))
62e76326 1158 request->flags.hierarchical = 1;
1159
bf8fe701 1160 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1161 (request->flags.nocache ? "SET" : "NOT SET"));
1162 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1163 (request->flags.cachable ? "SET" : "NOT SET"));
1164 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1165 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 1166
edce4d98 1167}
1168
1169void
de31d06f 1170clientRedirectDoneWrapper(void *data, char *result)
edce4d98 1171{
de31d06f 1172 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1173
de31d06f 1174 if (!calloutContext->httpStateIsValid())
62e76326 1175 return;
62e76326 1176
de31d06f 1177 calloutContext->clientRedirectDone(result);
1178}
1179
1180void
1181ClientRequestContext::clientRedirectDone(char *result)
1182{
190154cf 1183 HttpRequest *old_request = http->request;
bf8fe701 1184 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
de31d06f 1185 assert(redirect_state == REDIRECT_PENDING);
1186 redirect_state = REDIRECT_DONE;
62e76326 1187
edce4d98 1188 if (result) {
62e76326 1189 http_status status = (http_status) atoi(result);
1190
1191 if (status == HTTP_MOVED_PERMANENTLY
1192 || status == HTTP_MOVED_TEMPORARILY
1193 || status == HTTP_SEE_OTHER
1194 || status == HTTP_TEMPORARY_REDIRECT) {
1195 char *t = result;
1196
1197 if ((t = strchr(result, ':')) != NULL) {
1198 http->redirect.status = status;
1199 http->redirect.location = xstrdup(t + 1);
e5b677f0 1200 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1201 } else {
e5b677f0
AJ
1202 if (old_request->http_ver < HttpVersion(1,1))
1203 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 302 redirect Location: " << result);
1204 else
1205 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 303 redirect Location: " << result);
62e76326 1206 }
e5b677f0 1207 } else if (strcmp(result, http->uri)) {
9be14530
AJ
1208 // XXX: validate the URL properly *without* generating a whole new request object right here.
1209 // XXX: the clone() should be done only AFTER we know the new URL is valid.
1210 HttpRequest *new_request = old_request->clone();
1211 if (urlParse(old_request->method, result, new_request)) {
1212 debugs(61,2, HERE << "URL-rewriter diverts URL from " << urlCanonical(old_request) << " to " << urlCanonical(new_request));
1213
1214 // update the new request to flag the re-writing was done on it
1215 new_request->flags.redirected = 1;
1216
1217 // unlink bodypipe from the old request. Not needed there any longer.
1218 if (old_request->body_pipe != NULL) {
1219 old_request->body_pipe = NULL;
1220 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1221 " from request " << old_request << " to " << new_request);
1222 }
1223
1224 // update the current working ClientHttpRequest fields
1225 safe_free(http->uri);
1226 http->uri = xstrdup(urlCanonical(new_request));
1227 HTTPMSGUNLOCK(old_request);
1228 http->request = HTTPMSGLOCK(new_request);
1229 } else {
e5b677f0 1230 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
c9fd01b4 1231 old_request->method << " " << result << " " << old_request->http_ver);
9be14530
AJ
1232 delete new_request;
1233 }
74b48915 1234 }
edce4d98 1235 }
62e76326 1236
edce4d98 1237 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1238
73c36fd9
AJ
1239 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1240 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1241
c8be6d7b 1242 assert(http->uri);
62e76326 1243
de31d06f 1244 http->doCallouts();
edce4d98 1245}
1246
b50e327b
AJ
1247/** Test cache allow/deny configuration
1248 * Sets flags.cachable=1 if caching is not denied.
1249 */
edce4d98 1250void
8e2745f4 1251ClientRequestContext::checkNoCache()
edce4d98 1252{
b50e327b
AJ
1253 if (Config.accessList.noCache) {
1254 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1255 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1256 } else {
1257 /* unless otherwise specified, we try to cache. */
2efeb0b7 1258 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1259 }
edce4d98 1260}
1261
de31d06f 1262static void
2efeb0b7 1263checkNoCacheDoneWrapper(allow_t answer, void *data)
edce4d98 1264{
de31d06f 1265 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1266
de31d06f 1267 if (!calloutContext->httpStateIsValid())
1268 return;
1269
1270 calloutContext->checkNoCacheDone(answer);
8e2745f4 1271}
4fb35c3c 1272
8e2745f4 1273void
2efeb0b7 1274ClientRequestContext::checkNoCacheDone(const allow_t &answer)
62e76326 1275{
8e2745f4 1276 acl_checklist = NULL;
2efeb0b7 1277 http->request->flags.cachable = (answer == ACCESS_ALLOWED);
de31d06f 1278 http->doCallouts();
edce4d98 1279}
1280
e0c0d54c
CT
1281#if USE_SSL
1282bool
1283ClientRequestContext::sslBumpAccessCheck()
1284{
1285 if (http->request->method == METHOD_CONNECT &&
f8901ea9 1286 Config.accessList.ssl_bump && http->getConn()->port->sslBump) {
e0c0d54c
CT
1287 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1288
1289 ACLFilledChecklist *acl_checklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1290 acl_checklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1291 return true;
f8901ea9 1292 } else {
e0c0d54c
CT
1293 http->sslBumpNeeded(false);
1294 return false;
1295 }
1296}
1297
f8901ea9 1298/**
e0c0d54c
CT
1299 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1300 * as ACLFilledChecklist callback
1301 */
1302static void
2efeb0b7 1303sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
e0c0d54c
CT
1304{
1305 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
ed6163ef 1306 calloutContext->sslBumpAccessCheckDone(answer);
e0c0d54c
CT
1307}
1308
1309void
ed6163ef 1310ClientRequestContext::sslBumpAccessCheckDone(const allow_t &answer)
e0c0d54c 1311{
ed6163ef
AJ
1312 if (!httpStateIsValid())
1313 return;
1314
1315 if (maybeSendAuthChallenge(answer))
1316 return;
1317
1318 http->sslBumpNeeded(answer == ACCESS_ALLOWED);
e0c0d54c
CT
1319 http->doCallouts();
1320}
1321#endif
1322
69660be0 1323/*
1324 * Identify requests that do not go through the store and client side stream
1325 * and forward them to the appropriate location. All other requests, request
1326 * them.
edce4d98 1327 */
1328void
8e2745f4 1329ClientHttpRequest::processRequest()
edce4d98 1330{
60745f24 1331 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
62e76326 1332
31281814 1333 if (request->method == METHOD_CONNECT && !redirect.status) {
3712be3f 1334#if USE_SSL
31281814
AJ
1335 if (sslBumpNeeded()) {
1336 sslBumpStart();
1337 return;
1338 }
3712be3f 1339#endif
62e76326 1340 logType = LOG_TCP_MISS;
f84dd7eb 1341 getConn()->stopReading(); // tunnels read for themselves
11007d4b 1342 tunnelStart(this, &out.size, &al.http.code);
62e76326 1343 return;
edce4d98 1344 }
62e76326 1345
8e2745f4 1346 httpStart();
1347}
1348
1349void
1350ClientHttpRequest::httpStart()
1351{
559da936 1352 PROF_start(httpStart);
8e2745f4 1353 logType = LOG_TAG_NONE;
38e16f92 1354 debugs(85, 4, "ClientHttpRequest::httpStart: " << Format::log_tags[logType] << " for '" << uri << "'");
bf8fe701 1355
edce4d98 1356 /* no one should have touched this */
8e2745f4 1357 assert(out.offset == 0);
edce4d98 1358 /* Use the Stream Luke */
8e2745f4 1359 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1360 clientStreamRead(node, this, node->readBuffer);
559da936 1361 PROF_stop(httpStart);
edce4d98 1362}
0655fa4d 1363
3712be3f 1364#if USE_SSL
1365
3712be3f 1366bool
26ac0430
AJ
1367ClientHttpRequest::sslBumpNeeded() const
1368{
e0c0d54c
CT
1369 assert(sslBumpNeed != needUnknown);
1370 return (sslBumpNeed == needConfirmed);
1371}
3712be3f 1372
e0c0d54c
CT
1373void
1374ClientHttpRequest::sslBumpNeeded(bool isNeeded)
1375{
1376 debugs(83, 3, HERE << "sslBump required: "<< (isNeeded ? "Yes" : "No"));
1377 sslBumpNeed = (isNeeded ? needConfirmed : needNot);
3712be3f 1378}
1379
1380// called when comm_write has completed
1381static void
e0d28505 1382SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, comm_err_t errflag, int, void *data)
3712be3f 1383{
1384 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1385 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1386
1387 assert(r && cbdataReferenceValid(r));
1388 r->sslBumpEstablish(errflag);
1389}
1390
1391void
1392ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1393{
1394 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1395 if (errflag == COMM_ERR_CLOSING)
1396 return;
1397
1398 if (errflag) {
1fa35be8 1399 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
bbc83914 1400 getConn()->clientConnection->close();
3712be3f 1401 return;
1402 }
1403
21512911
CT
1404#if USE_AUTH
1405 // Preserve authentication info for the ssl-bumped request
1406 if (request->auth_user_request != NULL)
1407 getConn()->auth_user_request = request->auth_user_request;
1408#endif
95d2589c 1409 getConn()->switchToHttps(request->GetHost());
3712be3f 1410}
1411
1412void
1413ClientHttpRequest::sslBumpStart()
1414{
73c36fd9 1415 debugs(85, 5, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1416 // send an HTTP 200 response to kick client SSL negotiation
73c36fd9 1417 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1418
1419 // TODO: Unify with tunnel.cc and add a Server(?) header
b0388924 1420 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1421 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1422 CommIoCbPtrFun(&SslBumpEstablish, this));
73c36fd9 1423 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), call, NULL);
3712be3f 1424}
1425
1426#endif
1427
0655fa4d 1428bool
1429ClientHttpRequest::gotEnough() const
1430{
86a2f789 1431 /** TODO: should be querying the stream. */
7173d5b0 1432 int64_t contentLength =
06a5ae20 1433 memObject()->getReply()->bodySize(request->method);
0655fa4d 1434 assert(contentLength >= 0);
1435
1436 if (out.offset < contentLength)
1437 return false;
1438
1439 return true;
1440}
1441
86a2f789 1442void
1443ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1444{
1445 entry_ = newEntry;
1446}
1447
0976f8db 1448void
1449ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1450{
1451 if (loggingEntry_)
97b5e68f 1452 loggingEntry_->unlock();
0976f8db 1453
1454 loggingEntry_ = newEntry;
1455
1456 if (loggingEntry_)
3d0ac046 1457 loggingEntry_->lock();
0976f8db 1458}
86a2f789 1459
de31d06f 1460/*
1461 * doCallouts() - This function controls the order of "callout"
1462 * executions, including non-blocking access control checks, the
1463 * redirector, and ICAP. Previously, these callouts were chained
1464 * together such that "clientAccessCheckDone()" would call
1465 * "clientRedirectStart()" and so on.
1466 *
1467 * The ClientRequestContext (aka calloutContext) class holds certain
1468 * state data for the callout/callback operations. Previously
1469 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1470 * for a short time. ClientRequestContext would then delete itself
1471 * and pass control back to ClientHttpRequest when all callouts
1472 * were finished.
1473 *
1474 * This caused some problems for ICAP because we want to make the
1475 * ICAP callout after checking ACLs, but before checking the no_cache
1476 * list. We can't stuff the ICAP state into the ClientRequestContext
1477 * class because we still need the ICAP state after ClientRequestContext
1478 * goes away.
1479 *
1480 * Note that ClientRequestContext is created before the first call
1481 * to doCallouts().
1482 *
1483 * If one of the callouts notices that ClientHttpRequest is no
1484 * longer valid, it should call cbdataReferenceDone() so that
1485 * ClientHttpRequest's reference count goes to zero and it will get
1486 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1487 *
1488 * Note that we set the _done flags here before actually starting
1489 * the callout. This is strictly for convenience.
1490 */
1491
425de4c8
AJ
1492extern tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1493extern nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1494
de31d06f 1495void
1496ClientHttpRequest::doCallouts()
1497{
1498 assert(calloutContext);
1499
6fca33e0
CT
1500 /*Save the original request for logging purposes*/
1501 if (!calloutContext->http->al.request)
105d1937 1502 calloutContext->http->al.request = HTTPMSGLOCK(request);
6fca33e0 1503
fe97983f
AJ
1504 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1505 if (!calloutContext->host_header_verify_done) {
1506 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1507 calloutContext->host_header_verify_done = true;
1508 calloutContext->hostHeaderVerify();
1509 return;
1510 }
1511
de31d06f 1512 if (!calloutContext->http_access_done) {
3712be3f 1513 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
57abaac0 1514 calloutContext->http_access_done = true;
de31d06f 1515 calloutContext->clientAccessCheck();
1516 return;
1517 }
1518
a83c6ed6 1519#if USE_ADAPTATION
abd4b611 1520 if (!calloutContext->adaptation_acl_check_done) {
a83c6ed6 1521 calloutContext->adaptation_acl_check_done = true;
abd4b611 1522 if (Adaptation::AccessCheck::Start(
26ac0430 1523 Adaptation::methodReqmod, Adaptation::pointPreCache,
79628299 1524 request, NULL, this))
abd4b611 1525 return; // will call callback
de31d06f 1526 }
de31d06f 1527#endif
1528
1529 if (!calloutContext->redirect_done) {
57abaac0 1530 calloutContext->redirect_done = true;
de31d06f 1531 assert(calloutContext->redirect_state == REDIRECT_NONE);
1532
1533 if (Config.Program.redirect) {
3712be3f 1534 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
de31d06f 1535 calloutContext->redirect_state = REDIRECT_PENDING;
1536 calloutContext->clientRedirectStart();
1537 return;
1538 }
1539 }
1540
533493da
AJ
1541 if (!calloutContext->adapted_http_access_done) {
1542 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1543 calloutContext->adapted_http_access_done = true;
1544 calloutContext->clientAccessCheck2();
1545 return;
1546 }
1547
57abaac0 1548 if (!calloutContext->interpreted_req_hdrs) {
3712be3f 1549 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
57abaac0 1550 calloutContext->interpreted_req_hdrs = 1;
1551 clientInterpretRequestHeaders(this);
1552 }
1553
de31d06f 1554 if (!calloutContext->no_cache_done) {
57abaac0 1555 calloutContext->no_cache_done = true;
de31d06f 1556
1557 if (Config.accessList.noCache && request->flags.cachable) {
3712be3f 1558 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
de31d06f 1559 calloutContext->checkNoCache();
1560 return;
1561 }
1562 }
1563
425de4c8
AJ
1564 if (!calloutContext->tosToClientDone) {
1565 calloutContext->tosToClientDone = true;
73c36fd9 1566 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
c0941a6a 1567 ACLFilledChecklist ch(NULL, request, NULL);
057f5854 1568 ch.src_addr = request->client_addr;
1569 ch.my_addr = request->my_addr;
425de4c8 1570 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1571 if (tos)
73c36fd9 1572 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
425de4c8
AJ
1573 }
1574 }
1575
1576 if (!calloutContext->nfmarkToClientDone) {
1577 calloutContext->nfmarkToClientDone = true;
73c36fd9 1578 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
425de4c8
AJ
1579 ACLFilledChecklist ch(NULL, request, NULL);
1580 ch.src_addr = request->client_addr;
1581 ch.my_addr = request->my_addr;
1582 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1583 if (mark)
73c36fd9 1584 Ip::Qos::setSockNfmark(getConn()->clientConnection, mark);
3712be3f 1585 }
057f5854 1586 }
1587
d2565320 1588#if USE_SSL
e0c0d54c
CT
1589 if (!calloutContext->sslBumpCheckDone) {
1590 calloutContext->sslBumpCheckDone = true;
1591 if (calloutContext->sslBumpAccessCheck())
1592 return;
1593 /* else no ssl bump required*/
1594 }
d2565320 1595#endif
e0c0d54c 1596
de31d06f 1597 cbdataReferenceDone(calloutContext->http);
1598 delete calloutContext;
1599 calloutContext = NULL;
de31d06f 1600#if HEADERS_LOG
1601
1602 headersLog(0, 1, request->method, request);
1603#endif
1604
58d7150d 1605 debugs(83, 3, HERE << "calling processRequest()");
de31d06f 1606 processRequest();
3ff65596
AR
1607
1608#if ICAP_CLIENT
1609 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1610 if (ih != NULL)
1611 ih->logType = logType;
1612#endif
de31d06f 1613}
1614
32d002cb 1615#if !_USE_INLINE_
86a2f789 1616#include "client_side_request.cci"
1617#endif
de31d06f 1618
a83c6ed6 1619#if USE_ADAPTATION
a22e6cd3
AR
1620/// Initiate an asynchronous adaptation transaction which will call us back.
1621void
1622ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1623{
a22e6cd3 1624 debugs(85, 3, HERE << "adaptation needed for " << this);
a83c6ed6
AR
1625 assert(!virginHeadSource);
1626 assert(!adaptedBodySource);
a22e6cd3 1627 virginHeadSource = initiateAdaptation(
4cb2536f 1628 new Adaptation::Iterator(request, NULL, g));
a83c6ed6 1629
e1381638 1630 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1631 // initiation failure, but it should not really happen
4299f876 1632 Must(initiated(virginHeadSource));
de31d06f 1633}
1634
1635void
3af10ac0 1636ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1637{
de31d06f 1638 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1639 clearAdaptation(virginHeadSource);
1640 assert(!adaptedBodySource);
1641
1642 switch (answer.kind) {
1643 case Adaptation::Answer::akForward:
1644 handleAdaptedHeader(answer.message);
1645 break;
1646
1647 case Adaptation::Answer::akBlock:
1648 handleAdaptationBlock(answer);
1649 break;
1650
1651 case Adaptation::Answer::akError:
1652 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1653 break;
1654 }
1655}
1656
1657void
ec4d1a1d 1658ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg)
3af10ac0 1659{
5f8252d2 1660 assert(msg);
1661
b044675d 1662 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
200ac359 1663 /*
5f8252d2 1664 * Replace the old request with the new request.
200ac359 1665 */
6dd9f4bd 1666 HTTPMSGUNLOCK(request);
1667 request = HTTPMSGLOCK(new_req);
200ac359 1668 /*
1669 * Store the new URI for logging
1670 */
1671 xfree(uri);
1672 uri = xstrdup(urlCanonical(request));
1673 setLogUri(this, urlCanonicalClean(request));
914b89a2 1674 assert(request->method.id());
b044675d 1675 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1676 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1677
5f8252d2 1678 // subscribe to receive reply body
1679 if (new_rep->body_pipe != NULL) {
a83c6ed6 1680 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
1681 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1682 assert(consumer_ok);
5f8252d2 1683 }
1684
b044675d 1685 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1686 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1687 repContext->createStoreEntry(request->method, request->flags);
1688
1689 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1690 request_satisfaction_mode = true;
1691 request_satisfaction_offset = 0;
1692 storeEntry()->replaceHttpReply(new_rep);
97ae5196 1693 storeEntry()->timestampsSet();
cb4c4288 1694
a83c6ed6 1695 if (!adaptedBodySource) // no body
cb4c4288 1696 storeEntry()->complete();
b044675d 1697 clientGetMoreData(node, this);
200ac359 1698 }
de31d06f 1699
5f8252d2 1700 // we are done with getting headers (but may be receiving body)
a83c6ed6 1701 clearAdaptation(virginHeadSource);
5f8252d2 1702
b044675d 1703 if (!request_satisfaction_mode)
1704 doCallouts();
de31d06f 1705}
1706
1707void
3af10ac0 1708ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 1709{
3af10ac0
AR
1710 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1711 AclMatchedName = answer.ruleId.termedBuf();
1712 assert(calloutContext);
1713 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1714 AclMatchedName = NULL;
de31d06f 1715}
1716
0ad2b63b
CT
1717void
1718ClientHttpRequest::resumeBodyStorage()
1719{
e83cdc25 1720 if (!adaptedBodySource)
0ad2b63b
CT
1721 return;
1722
1723 noteMoreBodyDataAvailable(adaptedBodySource);
1724}
1725
de31d06f 1726void
1cf238db 1727ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 1728{
5f8252d2 1729 assert(request_satisfaction_mode);
a83c6ed6 1730 assert(adaptedBodySource != NULL);
5f8252d2 1731
0ad2b63b
CT
1732 if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
1733 // XXX: entry->bytesWanted returns contentSize-1 if entry can accept data.
1734 // We have to add 1 to avoid suspending forever.
1735 const size_t bytesWanted = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
1736 const size_t spaceAvailable = bytesWanted > 0 ? (bytesWanted + 1) : 0;
1737
1738 if (spaceAvailable < contentSize ) {
1739 // No or partial body data consuming
1740 typedef NullaryMemFunT<ClientHttpRequest> Dialer;
1741 AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
1742 Dialer(this, &ClientHttpRequest::resumeBodyStorage));
1743 storeEntry()->deferProducer(call);
1744 }
1745
1746 // XXX: bytesWanted API does not allow us to write just one byte!
1747 if (!spaceAvailable && contentSize > 1)
1748 return;
1749
1750 if (spaceAvailable < contentSize )
1751 contentSize = spaceAvailable;
1752
a83c6ed6 1753 BodyPipeCheckout bpc(*adaptedBodySource);
0ad2b63b 1754 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
5f8252d2 1755 storeEntry()->write(ioBuf);
0ad2b63b
CT
1756 // assume StoreEntry::write() writes the entire ioBuf
1757 request_satisfaction_offset += ioBuf.length;
4ce0e99b 1758 bpc.buf.consume(contentSize);
5f8252d2 1759 bpc.checkIn();
1760 }
1761
a83c6ed6 1762 if (adaptedBodySource->exhausted())
5f8252d2 1763 endRequestSatisfaction();
1764 // else wait for more body data
de31d06f 1765}
1766
1767void
1cf238db 1768ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 1769{
a83c6ed6 1770 assert(!virginHeadSource);
0ad2b63b
CT
1771 // should we end request satisfaction now?
1772 if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
5f8252d2 1773 endRequestSatisfaction();
5f8252d2 1774}
3b299123 1775
5f8252d2 1776void
26ac0430
AJ
1777ClientHttpRequest::endRequestSatisfaction()
1778{
5f8252d2 1779 debugs(85,4, HERE << this << " ends request satisfaction");
1780 assert(request_satisfaction_mode);
a83c6ed6 1781 stopConsumingFrom(adaptedBodySource);
3b299123 1782
5f8252d2 1783 // TODO: anything else needed to end store entry formation correctly?
1784 storeEntry()->complete();
1785}
de31d06f 1786
5f8252d2 1787void
1cf238db 1788ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 1789{
a83c6ed6
AR
1790 assert(!virginHeadSource);
1791 stopConsumingFrom(adaptedBodySource);
eae3a9a6
AR
1792
1793 debugs(85,3, HERE << "REQMOD body production failed");
1794 if (request_satisfaction_mode) { // too late to recover or serve an error
1795 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
73c36fd9 1796 const Comm::ConnectionPointer c = getConn()->clientConnection;
e7cea0ed
AJ
1797 Must(Comm::IsConnOpen(c));
1798 c->close(); // drastic, but we may be writing a response already
eae3a9a6
AR
1799 } else {
1800 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
1801 }
5f8252d2 1802}
3b299123 1803
5f8252d2 1804void
64b66b76 1805ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
5f8252d2 1806{
a83c6ed6 1807 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
3b299123 1808
5f8252d2 1809 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1810 const bool usedPipe = request->body_pipe != NULL &&
26ac0430 1811 request->body_pipe->consumedSize() > 0;
3b299123 1812
9d4d7c5e 1813 if (bypassable && !usedStore && !usedPipe) {
1814 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 1815 if (calloutContext)
1816 doCallouts();
1817 return;
1818 }
3b299123 1819
5f8252d2 1820 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
3b299123 1821
5f8252d2 1822 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1823 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1824 assert(repContext);
de31d06f 1825
26ac0430 1826 // The original author of the code also wanted to pass an errno to
5f8252d2 1827 // setReplyToError, but it seems unlikely that the errno reflects the
1828 // true cause of the error at this point, so I did not pass it.
b7ac5457 1829 Ip::Address noAddr;
b70ba605 1830 noAddr.SetNoAddr();
1cf238db 1831 ConnStateData * c = getConn();
5f8252d2 1832 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
26ac0430 1833 request->method, NULL,
73c36fd9 1834 (c != NULL ? c->clientConnection->remote : noAddr), request, NULL,
79fc6915 1835#if USE_AUTH
a33a428a 1836 (c != NULL && c->auth_user_request != NULL ?
26ac0430 1837 c->auth_user_request : request->auth_user_request));
79fc6915
AJ
1838#else
1839 NULL);
1840#endif
de31d06f 1841
64b66b76 1842 request->detailError(ERR_ICAP_FAILURE, errDetail);
378e20f3 1843 c->flags.readMore = true;
eb44b2d7 1844 c->expectNoForwarding();
5f8252d2 1845 node = (clientStreamNode *)client_stream.tail->data;
1846 clientStreamRead(node, this, node->readBuffer);
de31d06f 1847}
1848
1849#endif