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