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