]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Fill access log's %error_detail when responding with
[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
45#include "squid.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
725void
2efeb0b7 726ClientRequestContext::clientAccessCheckDone(const allow_t &answer)
de31d06f 727{
728 acl_checklist = NULL;
edce4d98 729 err_type page_id;
730 http_status status;
26ac0430
AJ
731 debugs(85, 2, "The request " <<
732 RequestMethodStr(http->request->method) << " " <<
2efeb0b7 733 http->uri << " is " << answer <<
26ac0430
AJ
734 ", because it matched '" <<
735 (AclMatchedName ? AclMatchedName : "NO ACL's") << "'" );
f5691f9c 736
2f1431ea
AJ
737#if USE_AUTH
738 char const *proxy_auth_msg = "<null>";
94a396a3 739 if (http->getConn() != NULL && http->getConn()->auth_user_request != NULL)
f5691f9c 740 proxy_auth_msg = http->getConn()->auth_user_request->denyMessage("<null>");
741 else if (http->request->auth_user_request != NULL)
742 proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
2f1431ea 743#endif
62e76326 744
309347ef
AJ
745 if (answer != ACCESS_ALLOWED && answer != ACCESS_AUTH_EXPIRED_OK) {
746 // auth has a grace period where credentials can be expired but okay not to challenge.
747
748 /* Send an auth challenge or error */
749 // XXX: do we still need aclIsProxyAuth() ?
750 bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || answer == ACCESS_AUTH_EXPIRED_BAD || aclIsProxyAuth(AclMatchedName));
bf8fe701 751 debugs(85, 5, "Access Denied: " << http->uri);
752 debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
2f1431ea 753#if USE_AUTH
309347ef 754 if (auth_challenge)
bf8fe701 755 debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
2f1431ea 756#endif
9ce7856a 757
62e76326 758 /*
759 * NOTE: get page_id here, based on AclMatchedName because if
760 * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
761 * the clientCreateStoreEntry() call just below. Pedro Ribeiro
762 * <pribeiro@isel.pt>
763 */
7dfddb79 764 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);
9ce7856a 765
62e76326 766 http->logType = LOG_TCP_DENIED;
767
309347ef 768 if (auth_challenge) {
2f1431ea 769#if USE_AUTH
62e76326 770 if (!http->flags.accel) {
771 /* Proxy authorisation needed */
772 status = HTTP_PROXY_AUTHENTICATION_REQUIRED;
773 } else {
774 /* WWW authorisation needed */
775 status = HTTP_UNAUTHORIZED;
776 }
2f1431ea
AJ
777#else
778 // need auth, but not possible to do.
779 status = HTTP_FORBIDDEN;
780#endif
62e76326 781 if (page_id == ERR_NONE)
782 page_id = ERR_CACHE_ACCESS_DENIED;
783 } else {
784 status = HTTP_FORBIDDEN;
785
786 if (page_id == ERR_NONE)
787 page_id = ERR_ACCESS_DENIED;
788 }
789
de31d06f 790 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
0655fa4d 791 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
792 assert (repContext);
b7ac5457 793 Ip::Address tmpnoaddr;
26ac0430 794 tmpnoaddr.SetNoAddr();
0655fa4d 795 repContext->setReplyToError(page_id, status,
796 http->request->method, NULL,
73c36fd9 797 http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,
cc192b50 798 http->request,
799 NULL,
2f1431ea 800#if USE_AUTH
a33a428a 801 http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
cc192b50 802 http->getConn()->auth_user_request : http->request->auth_user_request);
2f1431ea
AJ
803#else
804 NULL);
805#endif
6b355e5a 806 http->getConn()->flags.readMore = true; // resume any pipeline reads.
62e76326 807 node = (clientStreamNode *)http->client_stream.tail->data;
808 clientStreamRead(node, http, node->readBuffer);
a546b04b 809 return;
edce4d98 810 }
de31d06f 811
309347ef 812 /* ACCESS_ALLOWED (or auth in grace period ACCESS_AUTH_EXPIRED_OK) continues here ... */
de31d06f 813 safe_free(http->uri);
814
815 http->uri = xstrdup(urlCanonical(http->request));
816
817 http->doCallouts();
818}
819
a83c6ed6 820#if USE_ADAPTATION
de31d06f 821void
79628299 822ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
de31d06f 823{
a83c6ed6 824 debugs(93,3,HERE << this << " adaptationAclCheckDone called");
6ec67de9 825
e1381638 826#if ICAP_CLIENT
79628299 827 Adaptation::Icap::History::Pointer ih = request->icapHistory();
e1381638 828 if (ih != NULL) {
79628299
CT
829 if (getConn() != NULL) {
830 ih->rfc931 = getConn()->clientConnection->rfc931;
e1381638 831#if USE_SSL
79628299
CT
832 assert(getConn()->clientConnection != NULL);
833 ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl);
e1381638 834#endif
3ff65596 835 }
79628299
CT
836 ih->log_uri = log_uri;
837 ih->req_sz = req_sz;
3ff65596
AR
838 }
839#endif
840
a22e6cd3
AR
841 if (!g) {
842 debugs(85,3, HERE << "no adaptation needed");
79628299 843 doCallouts();
5f8252d2 844 return;
845 }
de31d06f 846
79628299 847 startAdaptation(g);
edce4d98 848}
849
de31d06f 850#endif
851
14cc8559 852static void
2efeb0b7 853clientRedirectAccessCheckDone(allow_t answer, void *data)
14cc8559 854{
855 ClientRequestContext *context = (ClientRequestContext *)data;
59a1efb2 856 ClientHttpRequest *http = context->http;
14cc8559 857 context->acl_checklist = NULL;
858
859 if (answer == ACCESS_ALLOWED)
de31d06f 860 redirectStart(http, clientRedirectDoneWrapper, context);
14cc8559 861 else
de31d06f 862 context->clientRedirectDone(NULL);
14cc8559 863}
864
de31d06f 865void
866ClientRequestContext::clientRedirectStart()
14cc8559 867{
48e7baac 868 debugs(33, 5, HERE << "'" << http->uri << "'");
14cc8559 869
14cc8559 870 if (Config.accessList.redirector) {
de31d06f 871 acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
872 acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
14cc8559 873 } else
de31d06f 874 redirectStart(http, clientRedirectDoneWrapper, this);
14cc8559 875}
876
edce4d98 877static int
59a1efb2 878clientHierarchical(ClientHttpRequest * http)
edce4d98 879{
880 const char *url = http->uri;
190154cf 881 HttpRequest *request = http->request;
60745f24 882 HttpRequestMethod method = request->method;
edce4d98 883 const wordlist *p = NULL;
884
69660be0 885 /*
886 * IMS needs a private key, so we can use the hierarchy for IMS only if our
887 * neighbors support private keys
888 */
62e76326 889
edce4d98 890 if (request->flags.ims && !neighbors_do_private_keys)
62e76326 891 return 0;
892
69660be0 893 /*
894 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 895 * (they can even be cached if the correct headers are set on the reply)
edce4d98 896 */
897 if (request->flags.auth)
62e76326 898 return 0;
899
edce4d98 900 if (method == METHOD_TRACE)
62e76326 901 return 1;
902
edce4d98 903 if (method != METHOD_GET)
62e76326 904 return 0;
905
edce4d98 906 /* scan hierarchy_stoplist */
907 for (p = Config.hierarchy_stoplist; p; p = p->next)
62e76326 908 if (strstr(url, p->key))
909 return 0;
910
edce4d98 911 if (request->flags.loopdetect)
62e76326 912 return 0;
913
0c3d3f65 914 if (request->protocol == AnyP::PROTO_HTTP)
62e76326 915 return httpCachable(method);
916
0c3d3f65 917 if (request->protocol == AnyP::PROTO_GOPHER)
62e76326 918 return gopherCachable(request);
919
39a19cb7 920 if (request->protocol == AnyP::PROTO_CACHE_OBJECT)
62e76326 921 return 0;
922
edce4d98 923 return 1;
924}
925
46a1f562
HN
926static void
927clientCheckPinning(ClientHttpRequest * http)
928{
929 HttpRequest *request = http->request;
930 HttpHeader *req_hdr = &request->header;
931 ConnStateData *http_conn = http->getConn();
932
933 /* Internal requests such as those from ESI includes may be without
934 * a client connection
935 */
936 if (!http_conn)
f54f527e 937 return;
46a1f562
HN
938
939 request->flags.connection_auth_disabled = http_conn->port->connection_auth_disabled;
940 if (!request->flags.connection_auth_disabled) {
73c36fd9 941 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562
HN
942 if (http_conn->pinning.auth) {
943 request->flags.connection_auth = 1;
944 request->flags.auth = 1;
945 } else {
946 request->flags.connection_proxy_auth = 1;
947 }
b1cf2350
AJ
948 // These should already be linked correctly.
949 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
950 }
951 }
952
953 /* check if connection auth is used, and flag as candidate for pinning
954 * in such case.
955 * Note: we may need to set flags.connection_auth even if the connection
956 * is already pinned if it was pinned earlier due to proxy auth
957 */
958 if (!request->flags.connection_auth) {
959 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
960 HttpHeaderPos pos = HttpHeaderInitPos;
961 HttpHeaderEntry *e;
962 int may_pin = 0;
963 while ((e = req_hdr->getEntry(&pos))) {
964 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
965 const char *value = e->value.rawBuf();
966 if (strncasecmp(value, "NTLM ", 5) == 0
967 ||
968 strncasecmp(value, "Negotiate ", 10) == 0
969 ||
970 strncasecmp(value, "Kerberos ", 9) == 0) {
971 if (e->id == HDR_AUTHORIZATION) {
972 request->flags.connection_auth = 1;
973 may_pin = 1;
974 } else {
975 request->flags.connection_proxy_auth = 1;
976 may_pin = 1;
977 }
978 }
979 }
980 }
981 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
982 // These should already be linked correctly. Just need the ServerConnection to pinn.
983 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
984 }
985 }
986 }
987}
988
edce4d98 989static void
59a1efb2 990clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 991{
190154cf 992 HttpRequest *request = http->request;
0ef77270 993 HttpHeader *req_hdr = &request->header;
edce4d98 994 int no_cache = 0;
edce4d98 995 const char *str;
62e76326 996
edce4d98 997 request->imslen = -1;
a9925b40 998 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 999
edce4d98 1000 if (request->ims > 0)
62e76326 1001 request->flags.ims = 1;
1002
432bc83c
HN
1003 if (!request->flags.ignore_cc) {
1004 if (req_hdr->has(HDR_PRAGMA)) {
1005 String s = req_hdr->getList(HDR_PRAGMA);
62e76326 1006
432bc83c
HN
1007 if (strListIsMember(&s, "no-cache", ','))
1008 no_cache++;
30abd221 1009
432bc83c
HN
1010 s.clean();
1011 }
62e76326 1012
432bc83c 1013 if (request->cache_control)
4ce6e3b5 1014 if (request->cache_control->noCache())
432bc83c 1015 no_cache++;
62e76326 1016
432bc83c
HN
1017 /*
1018 * Work around for supporting the Reload button in IE browsers when Squid
1019 * is used as an accelerator or transparent proxy, by turning accelerated
1020 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
1021 * actually only fixed in SP1, but we can't tell whether we are talking to
1022 * SP1 or not so all 5.5 versions are treated 'normally').
1023 */
1024 if (Config.onoff.ie_refresh) {
1025 if (http->flags.accel && request->flags.ims) {
1026 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
1027 if (strstr(str, "MSIE 5.01") != NULL)
1028 no_cache++;
1029 else if (strstr(str, "MSIE 5.0") != NULL)
1030 no_cache++;
1031 else if (strstr(str, "MSIE 4.") != NULL)
1032 no_cache++;
1033 else if (strstr(str, "MSIE 3.") != NULL)
1034 no_cache++;
1035 }
62e76326 1036 }
1037 }
edce4d98 1038 }
914b89a2 1039
1040 if (request->method == METHOD_OTHER) {
26ac0430 1041 no_cache++;
60745f24 1042 }
62e76326 1043
edce4d98 1044 if (no_cache) {
626096be 1045#if USE_HTTP_VIOLATIONS
62e76326 1046
1047 if (Config.onoff.reload_into_ims)
1048 request->flags.nocache_hack = 1;
1049 else if (refresh_nocache_hack)
1050 request->flags.nocache_hack = 1;
1051 else
edce4d98 1052#endif
62e76326 1053
1054 request->flags.nocache = 1;
edce4d98 1055 }
62e76326 1056
0ef77270 1057 /* ignore range header in non-GETs or non-HEADs */
1058 if (request->method == METHOD_GET || request->method == METHOD_HEAD) {
56713d9a
AR
1059 // XXX: initialize if we got here without HttpRequest::parseHeader()
1060 if (!request->range)
1061 request->range = req_hdr->getRange();
62e76326 1062
1063 if (request->range) {
1064 request->flags.range = 1;
1065 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1066 /* XXX: This is suboptimal. We should give the stream the range set,
1067 * and thereby let the top of the stream set the offset when the
26ac0430 1068 * size becomes known. As it is, we will end up requesting from 0
62e76326 1069 * for evey -X range specification.
1070 * RBC - this may be somewhat wrong. We should probably set the range
1071 * iter up at this point.
1072 */
1073 node->readBuffer.offset = request->range->lowestOffset(0);
1074 http->range_iter.pos = request->range->begin();
1075 http->range_iter.valid = true;
1076 }
edce4d98 1077 }
62e76326 1078
0ef77270 1079 /* Only HEAD and GET requests permit a Range or Request-Range header.
1080 * If these headers appear on any other type of request, delete them now.
1081 */
1082 else {
1083 req_hdr->delById(HDR_RANGE);
1084 req_hdr->delById(HDR_REQUEST_RANGE);
56713d9a 1085 delete request->range;
0ef77270 1086 request->range = NULL;
1087 }
1088
a9925b40 1089 if (req_hdr->has(HDR_AUTHORIZATION))
62e76326 1090 request->flags.auth = 1;
1091
46a1f562 1092 clientCheckPinning(http);
d67acb4e 1093
edce4d98 1094 if (request->login[0] != '\0')
62e76326 1095 request->flags.auth = 1;
1096
a9925b40 1097 if (req_hdr->has(HDR_VIA)) {
30abd221 1098 String s = req_hdr->getList(HDR_VIA);
62e76326 1099 /*
3c4fcf0f 1100 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1101 * Note ThisCache2 has a space prepended to the hostname so we don't
1102 * accidentally match super-domains.
1103 */
1104
1105 if (strListIsSubstr(&s, ThisCache2, ',')) {
1106 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
1107 request, (ObjPackMethod) & httpRequestPack);
1108 request->flags.loopdetect = 1;
1109 }
1110
21f6708d 1111#if USE_FORW_VIA_DB
bb790702 1112 fvdbCountVia(s.termedBuf());
62e76326 1113
edce4d98 1114#endif
62e76326 1115
30abd221 1116 s.clean();
edce4d98 1117 }
62e76326 1118
21f6708d 1119#if USE_FORW_VIA_DB
62e76326 1120
a9925b40 1121 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 1122 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 1123 fvdbCountForw(s.termedBuf());
30abd221 1124 s.clean();
edce4d98 1125 }
62e76326 1126
edce4d98 1127#endif
62e76326 1128
610ee341 1129 request->flags.cachable = http->request->cacheable();
62e76326 1130
edce4d98 1131 if (clientHierarchical(http))
62e76326 1132 request->flags.hierarchical = 1;
1133
bf8fe701 1134 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
1135 (request->flags.nocache ? "SET" : "NOT SET"));
1136 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
1137 (request->flags.cachable ? "SET" : "NOT SET"));
1138 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
1139 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 1140
edce4d98 1141}
1142
1143void
de31d06f 1144clientRedirectDoneWrapper(void *data, char *result)
edce4d98 1145{
de31d06f 1146 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1147
de31d06f 1148 if (!calloutContext->httpStateIsValid())
62e76326 1149 return;
62e76326 1150
de31d06f 1151 calloutContext->clientRedirectDone(result);
1152}
1153
1154void
1155ClientRequestContext::clientRedirectDone(char *result)
1156{
190154cf 1157 HttpRequest *old_request = http->request;
bf8fe701 1158 debugs(85, 5, "clientRedirectDone: '" << http->uri << "' result=" << (result ? result : "NULL"));
de31d06f 1159 assert(redirect_state == REDIRECT_PENDING);
1160 redirect_state = REDIRECT_DONE;
62e76326 1161
edce4d98 1162 if (result) {
62e76326 1163 http_status status = (http_status) atoi(result);
1164
1165 if (status == HTTP_MOVED_PERMANENTLY
1166 || status == HTTP_MOVED_TEMPORARILY
1167 || status == HTTP_SEE_OTHER
1168 || status == HTTP_TEMPORARY_REDIRECT) {
1169 char *t = result;
1170
1171 if ((t = strchr(result, ':')) != NULL) {
1172 http->redirect.status = status;
1173 http->redirect.location = xstrdup(t + 1);
e5b677f0 1174 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1175 } else {
e5b677f0
AJ
1176 if (old_request->http_ver < HttpVersion(1,1))
1177 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 302 redirect Location: " << result);
1178 else
1179 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid 303 redirect Location: " << result);
62e76326 1180 }
e5b677f0 1181 } else if (strcmp(result, http->uri)) {
9be14530
AJ
1182 // XXX: validate the URL properly *without* generating a whole new request object right here.
1183 // XXX: the clone() should be done only AFTER we know the new URL is valid.
1184 HttpRequest *new_request = old_request->clone();
1185 if (urlParse(old_request->method, result, new_request)) {
1186 debugs(61,2, HERE << "URL-rewriter diverts URL from " << urlCanonical(old_request) << " to " << urlCanonical(new_request));
1187
1188 // update the new request to flag the re-writing was done on it
1189 new_request->flags.redirected = 1;
1190
1191 // unlink bodypipe from the old request. Not needed there any longer.
1192 if (old_request->body_pipe != NULL) {
1193 old_request->body_pipe = NULL;
1194 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1195 " from request " << old_request << " to " << new_request);
1196 }
1197
1198 // update the current working ClientHttpRequest fields
1199 safe_free(http->uri);
1200 http->uri = xstrdup(urlCanonical(new_request));
1201 HTTPMSGUNLOCK(old_request);
1202 http->request = HTTPMSGLOCK(new_request);
1203 } else {
e5b677f0 1204 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
c9fd01b4 1205 old_request->method << " " << result << " " << old_request->http_ver);
9be14530
AJ
1206 delete new_request;
1207 }
74b48915 1208 }
edce4d98 1209 }
62e76326 1210
edce4d98 1211 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1212
73c36fd9
AJ
1213 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1214 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1215
c8be6d7b 1216 assert(http->uri);
62e76326 1217
de31d06f 1218 http->doCallouts();
edce4d98 1219}
1220
b50e327b
AJ
1221/** Test cache allow/deny configuration
1222 * Sets flags.cachable=1 if caching is not denied.
1223 */
edce4d98 1224void
8e2745f4 1225ClientRequestContext::checkNoCache()
edce4d98 1226{
b50e327b
AJ
1227 if (Config.accessList.noCache) {
1228 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1229 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1230 } else {
1231 /* unless otherwise specified, we try to cache. */
2efeb0b7 1232 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1233 }
edce4d98 1234}
1235
de31d06f 1236static void
2efeb0b7 1237checkNoCacheDoneWrapper(allow_t answer, void *data)
edce4d98 1238{
de31d06f 1239 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1240
de31d06f 1241 if (!calloutContext->httpStateIsValid())
1242 return;
1243
1244 calloutContext->checkNoCacheDone(answer);
8e2745f4 1245}
4fb35c3c 1246
8e2745f4 1247void
2efeb0b7 1248ClientRequestContext::checkNoCacheDone(const allow_t &answer)
62e76326 1249{
8e2745f4 1250 acl_checklist = NULL;
2efeb0b7 1251 http->request->flags.cachable = (answer == ACCESS_ALLOWED);
de31d06f 1252 http->doCallouts();
edce4d98 1253}
1254
e0c0d54c
CT
1255#if USE_SSL
1256bool
1257ClientRequestContext::sslBumpAccessCheck()
1258{
1259 if (http->request->method == METHOD_CONNECT &&
f8901ea9 1260 Config.accessList.ssl_bump && http->getConn()->port->sslBump) {
e0c0d54c
CT
1261 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1262
1263 ACLFilledChecklist *acl_checklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1264 acl_checklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1265 return true;
f8901ea9 1266 } else {
e0c0d54c
CT
1267 http->sslBumpNeeded(false);
1268 return false;
1269 }
1270}
1271
f8901ea9 1272/**
e0c0d54c
CT
1273 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1274 * as ACLFilledChecklist callback
1275 */
1276static void
2efeb0b7 1277sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
e0c0d54c
CT
1278{
1279 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
1280
1281 if (!calloutContext->httpStateIsValid())
1282 return;
1283 calloutContext->sslBumpAccessCheckDone(answer == ACCESS_ALLOWED);
1284}
1285
1286void
1287ClientRequestContext::sslBumpAccessCheckDone(bool doSslBump)
1288{
1289 http->sslBumpNeeded(doSslBump);
1290 http->doCallouts();
1291}
1292#endif
1293
69660be0 1294/*
1295 * Identify requests that do not go through the store and client side stream
1296 * and forward them to the appropriate location. All other requests, request
1297 * them.
edce4d98 1298 */
1299void
8e2745f4 1300ClientHttpRequest::processRequest()
edce4d98 1301{
60745f24 1302 debugs(85, 4, "clientProcessRequest: " << RequestMethodStr(request->method) << " '" << uri << "'");
62e76326 1303
31281814 1304 if (request->method == METHOD_CONNECT && !redirect.status) {
3712be3f 1305#if USE_SSL
31281814
AJ
1306 if (sslBumpNeeded()) {
1307 sslBumpStart();
1308 return;
1309 }
3712be3f 1310#endif
62e76326 1311 logType = LOG_TCP_MISS;
f84dd7eb 1312 getConn()->stopReading(); // tunnels read for themselves
11007d4b 1313 tunnelStart(this, &out.size, &al.http.code);
62e76326 1314 return;
edce4d98 1315 }
62e76326 1316
8e2745f4 1317 httpStart();
1318}
1319
1320void
1321ClientHttpRequest::httpStart()
1322{
559da936 1323 PROF_start(httpStart);
8e2745f4 1324 logType = LOG_TAG_NONE;
38e16f92 1325 debugs(85, 4, "ClientHttpRequest::httpStart: " << Format::log_tags[logType] << " for '" << uri << "'");
bf8fe701 1326
edce4d98 1327 /* no one should have touched this */
8e2745f4 1328 assert(out.offset == 0);
edce4d98 1329 /* Use the Stream Luke */
8e2745f4 1330 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1331 clientStreamRead(node, this, node->readBuffer);
559da936 1332 PROF_stop(httpStart);
edce4d98 1333}
0655fa4d 1334
3712be3f 1335#if USE_SSL
1336
3712be3f 1337bool
26ac0430
AJ
1338ClientHttpRequest::sslBumpNeeded() const
1339{
e0c0d54c
CT
1340 assert(sslBumpNeed != needUnknown);
1341 return (sslBumpNeed == needConfirmed);
1342}
3712be3f 1343
e0c0d54c
CT
1344void
1345ClientHttpRequest::sslBumpNeeded(bool isNeeded)
1346{
1347 debugs(83, 3, HERE << "sslBump required: "<< (isNeeded ? "Yes" : "No"));
1348 sslBumpNeed = (isNeeded ? needConfirmed : needNot);
3712be3f 1349}
1350
1351// called when comm_write has completed
1352static void
e0d28505 1353SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, comm_err_t errflag, int, void *data)
3712be3f 1354{
1355 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1356 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1357
1358 assert(r && cbdataReferenceValid(r));
1359 r->sslBumpEstablish(errflag);
1360}
1361
1362void
1363ClientHttpRequest::sslBumpEstablish(comm_err_t errflag)
1364{
1365 // Bail out quickly on COMM_ERR_CLOSING - close handlers will tidy up
1366 if (errflag == COMM_ERR_CLOSING)
1367 return;
1368
1369 if (errflag) {
1fa35be8 1370 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
bbc83914 1371 getConn()->clientConnection->close();
3712be3f 1372 return;
1373 }
1374
95d2589c 1375 getConn()->switchToHttps(request->GetHost());
3712be3f 1376}
1377
1378void
1379ClientHttpRequest::sslBumpStart()
1380{
73c36fd9 1381 debugs(85, 5, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1382 // send an HTTP 200 response to kick client SSL negotiation
73c36fd9 1383 debugs(33, 7, HERE << "Confirming CONNECT tunnel on FD " << getConn()->clientConnection);
3712be3f 1384
1385 // TODO: Unify with tunnel.cc and add a Server(?) header
b0388924 1386 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1387 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1388 CommIoCbPtrFun(&SslBumpEstablish, this));
73c36fd9 1389 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), call, NULL);
3712be3f 1390}
1391
1392#endif
1393
0655fa4d 1394bool
1395ClientHttpRequest::gotEnough() const
1396{
86a2f789 1397 /** TODO: should be querying the stream. */
7173d5b0 1398 int64_t contentLength =
06a5ae20 1399 memObject()->getReply()->bodySize(request->method);
0655fa4d 1400 assert(contentLength >= 0);
1401
1402 if (out.offset < contentLength)
1403 return false;
1404
1405 return true;
1406}
1407
86a2f789 1408void
1409ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1410{
1411 entry_ = newEntry;
1412}
1413
0976f8db 1414void
1415ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1416{
1417 if (loggingEntry_)
97b5e68f 1418 loggingEntry_->unlock();
0976f8db 1419
1420 loggingEntry_ = newEntry;
1421
1422 if (loggingEntry_)
3d0ac046 1423 loggingEntry_->lock();
0976f8db 1424}
86a2f789 1425
de31d06f 1426/*
1427 * doCallouts() - This function controls the order of "callout"
1428 * executions, including non-blocking access control checks, the
1429 * redirector, and ICAP. Previously, these callouts were chained
1430 * together such that "clientAccessCheckDone()" would call
1431 * "clientRedirectStart()" and so on.
1432 *
1433 * The ClientRequestContext (aka calloutContext) class holds certain
1434 * state data for the callout/callback operations. Previously
1435 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1436 * for a short time. ClientRequestContext would then delete itself
1437 * and pass control back to ClientHttpRequest when all callouts
1438 * were finished.
1439 *
1440 * This caused some problems for ICAP because we want to make the
1441 * ICAP callout after checking ACLs, but before checking the no_cache
1442 * list. We can't stuff the ICAP state into the ClientRequestContext
1443 * class because we still need the ICAP state after ClientRequestContext
1444 * goes away.
1445 *
1446 * Note that ClientRequestContext is created before the first call
1447 * to doCallouts().
1448 *
1449 * If one of the callouts notices that ClientHttpRequest is no
1450 * longer valid, it should call cbdataReferenceDone() so that
1451 * ClientHttpRequest's reference count goes to zero and it will get
1452 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1453 *
1454 * Note that we set the _done flags here before actually starting
1455 * the callout. This is strictly for convenience.
1456 */
1457
425de4c8
AJ
1458extern tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1459extern nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1460
de31d06f 1461void
1462ClientHttpRequest::doCallouts()
1463{
1464 assert(calloutContext);
1465
6fca33e0
CT
1466 /*Save the original request for logging purposes*/
1467 if (!calloutContext->http->al.request)
105d1937 1468 calloutContext->http->al.request = HTTPMSGLOCK(request);
6fca33e0 1469
fe97983f
AJ
1470 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1471 if (!calloutContext->host_header_verify_done) {
1472 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1473 calloutContext->host_header_verify_done = true;
1474 calloutContext->hostHeaderVerify();
1475 return;
1476 }
1477
de31d06f 1478 if (!calloutContext->http_access_done) {
3712be3f 1479 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
57abaac0 1480 calloutContext->http_access_done = true;
de31d06f 1481 calloutContext->clientAccessCheck();
1482 return;
1483 }
1484
a83c6ed6 1485#if USE_ADAPTATION
abd4b611 1486 if (!calloutContext->adaptation_acl_check_done) {
a83c6ed6 1487 calloutContext->adaptation_acl_check_done = true;
abd4b611 1488 if (Adaptation::AccessCheck::Start(
26ac0430 1489 Adaptation::methodReqmod, Adaptation::pointPreCache,
79628299 1490 request, NULL, this))
abd4b611 1491 return; // will call callback
de31d06f 1492 }
de31d06f 1493#endif
1494
1495 if (!calloutContext->redirect_done) {
57abaac0 1496 calloutContext->redirect_done = true;
de31d06f 1497 assert(calloutContext->redirect_state == REDIRECT_NONE);
1498
1499 if (Config.Program.redirect) {
3712be3f 1500 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
de31d06f 1501 calloutContext->redirect_state = REDIRECT_PENDING;
1502 calloutContext->clientRedirectStart();
1503 return;
1504 }
1505 }
1506
533493da
AJ
1507 if (!calloutContext->adapted_http_access_done) {
1508 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1509 calloutContext->adapted_http_access_done = true;
1510 calloutContext->clientAccessCheck2();
1511 return;
1512 }
1513
57abaac0 1514 if (!calloutContext->interpreted_req_hdrs) {
3712be3f 1515 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
57abaac0 1516 calloutContext->interpreted_req_hdrs = 1;
1517 clientInterpretRequestHeaders(this);
1518 }
1519
de31d06f 1520 if (!calloutContext->no_cache_done) {
57abaac0 1521 calloutContext->no_cache_done = true;
de31d06f 1522
1523 if (Config.accessList.noCache && request->flags.cachable) {
3712be3f 1524 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
de31d06f 1525 calloutContext->checkNoCache();
1526 return;
1527 }
1528 }
1529
425de4c8
AJ
1530 if (!calloutContext->tosToClientDone) {
1531 calloutContext->tosToClientDone = true;
73c36fd9 1532 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
c0941a6a 1533 ACLFilledChecklist ch(NULL, request, NULL);
057f5854 1534 ch.src_addr = request->client_addr;
1535 ch.my_addr = request->my_addr;
425de4c8 1536 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
3712be3f 1537 if (tos)
73c36fd9 1538 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
425de4c8
AJ
1539 }
1540 }
1541
1542 if (!calloutContext->nfmarkToClientDone) {
1543 calloutContext->nfmarkToClientDone = true;
73c36fd9 1544 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
425de4c8
AJ
1545 ACLFilledChecklist ch(NULL, request, NULL);
1546 ch.src_addr = request->client_addr;
1547 ch.my_addr = request->my_addr;
1548 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1549 if (mark)
73c36fd9 1550 Ip::Qos::setSockNfmark(getConn()->clientConnection, mark);
3712be3f 1551 }
057f5854 1552 }
1553
d2565320 1554#if USE_SSL
e0c0d54c
CT
1555 if (!calloutContext->sslBumpCheckDone) {
1556 calloutContext->sslBumpCheckDone = true;
1557 if (calloutContext->sslBumpAccessCheck())
1558 return;
1559 /* else no ssl bump required*/
1560 }
d2565320 1561#endif
e0c0d54c 1562
de31d06f 1563 cbdataReferenceDone(calloutContext->http);
1564 delete calloutContext;
1565 calloutContext = NULL;
de31d06f 1566#if HEADERS_LOG
1567
1568 headersLog(0, 1, request->method, request);
1569#endif
1570
58d7150d 1571 debugs(83, 3, HERE << "calling processRequest()");
de31d06f 1572 processRequest();
3ff65596
AR
1573
1574#if ICAP_CLIENT
1575 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1576 if (ih != NULL)
1577 ih->logType = logType;
1578#endif
de31d06f 1579}
1580
32d002cb 1581#if !_USE_INLINE_
86a2f789 1582#include "client_side_request.cci"
1583#endif
de31d06f 1584
a83c6ed6 1585#if USE_ADAPTATION
a22e6cd3
AR
1586/// Initiate an asynchronous adaptation transaction which will call us back.
1587void
1588ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
3b299123 1589{
a22e6cd3 1590 debugs(85, 3, HERE << "adaptation needed for " << this);
a83c6ed6
AR
1591 assert(!virginHeadSource);
1592 assert(!adaptedBodySource);
a22e6cd3 1593 virginHeadSource = initiateAdaptation(
4cb2536f 1594 new Adaptation::Iterator(request, NULL, g));
a83c6ed6 1595
e1381638 1596 // we could try to guess whether we can bypass this adaptation
a22e6cd3 1597 // initiation failure, but it should not really happen
4299f876 1598 Must(initiated(virginHeadSource));
de31d06f 1599}
1600
1601void
3af10ac0 1602ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
de31d06f 1603{
de31d06f 1604 assert(cbdataReferenceValid(this)); // indicates bug
3af10ac0
AR
1605 clearAdaptation(virginHeadSource);
1606 assert(!adaptedBodySource);
1607
1608 switch (answer.kind) {
1609 case Adaptation::Answer::akForward:
1610 handleAdaptedHeader(answer.message);
1611 break;
1612
1613 case Adaptation::Answer::akBlock:
1614 handleAdaptationBlock(answer);
1615 break;
1616
1617 case Adaptation::Answer::akError:
1618 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1619 break;
1620 }
1621}
1622
1623void
ec4d1a1d 1624ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg)
3af10ac0 1625{
5f8252d2 1626 assert(msg);
1627
b044675d 1628 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
200ac359 1629 /*
5f8252d2 1630 * Replace the old request with the new request.
200ac359 1631 */
6dd9f4bd 1632 HTTPMSGUNLOCK(request);
1633 request = HTTPMSGLOCK(new_req);
200ac359 1634 /*
1635 * Store the new URI for logging
1636 */
1637 xfree(uri);
1638 uri = xstrdup(urlCanonical(request));
1639 setLogUri(this, urlCanonicalClean(request));
914b89a2 1640 assert(request->method.id());
b044675d 1641 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1642 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1643
5f8252d2 1644 // subscribe to receive reply body
1645 if (new_rep->body_pipe != NULL) {
a83c6ed6 1646 adaptedBodySource = new_rep->body_pipe;
d222a56c
HN
1647 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1648 assert(consumer_ok);
5f8252d2 1649 }
1650
b044675d 1651 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1652 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1653 repContext->createStoreEntry(request->method, request->flags);
1654
1655 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1656 request_satisfaction_mode = true;
1657 request_satisfaction_offset = 0;
1658 storeEntry()->replaceHttpReply(new_rep);
97ae5196 1659 storeEntry()->timestampsSet();
cb4c4288 1660
a83c6ed6 1661 if (!adaptedBodySource) // no body
cb4c4288 1662 storeEntry()->complete();
b044675d 1663 clientGetMoreData(node, this);
200ac359 1664 }
de31d06f 1665
5f8252d2 1666 // we are done with getting headers (but may be receiving body)
a83c6ed6 1667 clearAdaptation(virginHeadSource);
5f8252d2 1668
b044675d 1669 if (!request_satisfaction_mode)
1670 doCallouts();
de31d06f 1671}
1672
1673void
3af10ac0 1674ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
de31d06f 1675{
3af10ac0
AR
1676 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1677 AclMatchedName = answer.ruleId.termedBuf();
1678 assert(calloutContext);
1679 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1680 AclMatchedName = NULL;
de31d06f 1681}
1682
1683void
1cf238db 1684ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
de31d06f 1685{
5f8252d2 1686 assert(request_satisfaction_mode);
a83c6ed6 1687 assert(adaptedBodySource != NULL);
5f8252d2 1688
4ce0e99b 1689 if (const size_t contentSize = adaptedBodySource->buf().contentSize()) {
a83c6ed6 1690 BodyPipeCheckout bpc(*adaptedBodySource);
4ce0e99b 1691 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset);
5f8252d2 1692 storeEntry()->write(ioBuf);
1693 // assume can write everything
1694 request_satisfaction_offset += contentSize;
4ce0e99b 1695 bpc.buf.consume(contentSize);
5f8252d2 1696 bpc.checkIn();
1697 }
1698
a83c6ed6 1699 if (adaptedBodySource->exhausted())
5f8252d2 1700 endRequestSatisfaction();
1701 // else wait for more body data
de31d06f 1702}
1703
1704void
1cf238db 1705ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
de31d06f 1706{
a83c6ed6
AR
1707 assert(!virginHeadSource);
1708 if (adaptedBodySource != NULL) { // did not end request satisfaction yet
26ac0430 1709 // We do not expect more because noteMoreBodyDataAvailable always
5f8252d2 1710 // consumes everything. We do not even have a mechanism to consume
1711 // leftovers after noteMoreBodyDataAvailable notifications seize.
a83c6ed6 1712 assert(adaptedBodySource->exhausted());
5f8252d2 1713 endRequestSatisfaction();
1714 }
1715}
3b299123 1716
5f8252d2 1717void
26ac0430
AJ
1718ClientHttpRequest::endRequestSatisfaction()
1719{
5f8252d2 1720 debugs(85,4, HERE << this << " ends request satisfaction");
1721 assert(request_satisfaction_mode);
a83c6ed6 1722 stopConsumingFrom(adaptedBodySource);
3b299123 1723
5f8252d2 1724 // TODO: anything else needed to end store entry formation correctly?
1725 storeEntry()->complete();
1726}
de31d06f 1727
5f8252d2 1728void
1cf238db 1729ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
5f8252d2 1730{
a83c6ed6
AR
1731 assert(!virginHeadSource);
1732 stopConsumingFrom(adaptedBodySource);
eae3a9a6
AR
1733
1734 debugs(85,3, HERE << "REQMOD body production failed");
1735 if (request_satisfaction_mode) { // too late to recover or serve an error
1736 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
73c36fd9 1737 const Comm::ConnectionPointer c = getConn()->clientConnection;
e7cea0ed
AJ
1738 Must(Comm::IsConnOpen(c));
1739 c->close(); // drastic, but we may be writing a response already
eae3a9a6
AR
1740 } else {
1741 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
1742 }
5f8252d2 1743}
3b299123 1744
5f8252d2 1745void
64b66b76 1746ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
5f8252d2 1747{
a83c6ed6 1748 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
3b299123 1749
5f8252d2 1750 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
1751 const bool usedPipe = request->body_pipe != NULL &&
26ac0430 1752 request->body_pipe->consumedSize() > 0;
3b299123 1753
9d4d7c5e 1754 if (bypassable && !usedStore && !usedPipe) {
1755 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
5f8252d2 1756 if (calloutContext)
1757 doCallouts();
1758 return;
1759 }
3b299123 1760
5f8252d2 1761 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
3b299123 1762
5f8252d2 1763 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1764 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1765 assert(repContext);
de31d06f 1766
26ac0430 1767 // The original author of the code also wanted to pass an errno to
5f8252d2 1768 // setReplyToError, but it seems unlikely that the errno reflects the
1769 // true cause of the error at this point, so I did not pass it.
b7ac5457 1770 Ip::Address noAddr;
b70ba605 1771 noAddr.SetNoAddr();
1cf238db 1772 ConnStateData * c = getConn();
5f8252d2 1773 repContext->setReplyToError(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR,
26ac0430 1774 request->method, NULL,
73c36fd9 1775 (c != NULL ? c->clientConnection->remote : noAddr), request, NULL,
79fc6915 1776#if USE_AUTH
a33a428a 1777 (c != NULL && c->auth_user_request != NULL ?
26ac0430 1778 c->auth_user_request : request->auth_user_request));
79fc6915
AJ
1779#else
1780 NULL);
1781#endif
de31d06f 1782
64b66b76 1783 request->detailError(ERR_ICAP_FAILURE, errDetail);
378e20f3 1784 c->flags.readMore = true;
eb44b2d7 1785 c->expectNoForwarding();
5f8252d2 1786 node = (clientStreamNode *)client_stream.tail->data;
1787 clientStreamRead(node, this, node->readBuffer);
de31d06f 1788}
1789
1790#endif