]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side_request.cc
Boilerplate: update copyright blurbs on Squid helpers
[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;
fa720bfb 167 al->cache.port = aConn->port;
d4806c91
CT
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{
190154cf 948 HttpRequest *request = http->request;
60745f24 949 HttpRequestMethod method = request->method;
edce4d98 950
2962f8b8 951 // intercepted requests MUST NOT (yet) be sent to peers unless verified
0d901ef4 952 if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy))
2962f8b8
AJ
953 return 0;
954
69660be0 955 /*
956 * IMS needs a private key, so we can use the hierarchy for IMS only if our
957 * neighbors support private keys
958 */
62e76326 959
45e5102d 960 if (request->flags.ims && !neighbors_do_private_keys)
62e76326 961 return 0;
962
69660be0 963 /*
964 * This is incorrect: authenticating requests can be sent via a hierarchy
06b97e72 965 * (they can even be cached if the correct headers are set on the reply)
edce4d98 966 */
45e5102d 967 if (request->flags.auth)
62e76326 968 return 0;
969
c2a7cefd 970 if (method == Http::METHOD_TRACE)
62e76326 971 return 1;
972
c2a7cefd 973 if (method != Http::METHOD_GET)
62e76326 974 return 0;
975
450fe1cb 976 if (request->flags.loopDetected)
62e76326 977 return 0;
978
4e3f4dc7 979 if (request->url.getScheme() == AnyP::PROTO_HTTP)
c2a7cefd 980 return method.respMaybeCacheable();
62e76326 981
4e3f4dc7 982 if (request->url.getScheme() == AnyP::PROTO_GOPHER)
62e76326 983 return gopherCachable(request);
984
4e3f4dc7 985 if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT)
62e76326 986 return 0;
987
edce4d98 988 return 1;
989}
990
46a1f562
HN
991static void
992clientCheckPinning(ClientHttpRequest * http)
993{
994 HttpRequest *request = http->request;
995 HttpHeader *req_hdr = &request->header;
996 ConnStateData *http_conn = http->getConn();
997
998 /* Internal requests such as those from ESI includes may be without
999 * a client connection
1000 */
1001 if (!http_conn)
f54f527e 1002 return;
46a1f562 1003
450fe1cb
FC
1004 request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled;
1005 if (!request->flags.connectionAuthDisabled) {
73c36fd9 1006 if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {
46a1f562 1007 if (http_conn->pinning.auth) {
e857372a
FC
1008 request->flags.connectionAuth = true;
1009 request->flags.auth = true;
46a1f562 1010 } else {
e857372a 1011 request->flags.connectionProxyAuth = true;
46a1f562 1012 }
b1cf2350
AJ
1013 // These should already be linked correctly.
1014 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
1015 }
1016 }
1017
1018 /* check if connection auth is used, and flag as candidate for pinning
45e5102d 1019 * in such case.
450fe1cb 1020 * Note: we may need to set flags.connectionAuth even if the connection
46a1f562
HN
1021 * is already pinned if it was pinned earlier due to proxy auth
1022 */
450fe1cb 1023 if (!request->flags.connectionAuth) {
46a1f562
HN
1024 if (req_hdr->has(HDR_AUTHORIZATION) || req_hdr->has(HDR_PROXY_AUTHORIZATION)) {
1025 HttpHeaderPos pos = HttpHeaderInitPos;
1026 HttpHeaderEntry *e;
1027 int may_pin = 0;
1028 while ((e = req_hdr->getEntry(&pos))) {
1029 if (e->id == HDR_AUTHORIZATION || e->id == HDR_PROXY_AUTHORIZATION) {
1030 const char *value = e->value.rawBuf();
1031 if (strncasecmp(value, "NTLM ", 5) == 0
1032 ||
1033 strncasecmp(value, "Negotiate ", 10) == 0
1034 ||
1035 strncasecmp(value, "Kerberos ", 9) == 0) {
1036 if (e->id == HDR_AUTHORIZATION) {
e857372a 1037 request->flags.connectionAuth = true;
46a1f562
HN
1038 may_pin = 1;
1039 } else {
e857372a 1040 request->flags.connectionProxyAuth = true;
46a1f562
HN
1041 may_pin = 1;
1042 }
1043 }
1044 }
1045 }
1046 if (may_pin && !request->pinnedConnection()) {
b1cf2350
AJ
1047 // These should already be linked correctly. Just need the ServerConnection to pinn.
1048 assert(request->clientConnectionManager == http_conn);
46a1f562
HN
1049 }
1050 }
1051 }
1052}
1053
edce4d98 1054static void
59a1efb2 1055clientInterpretRequestHeaders(ClientHttpRequest * http)
edce4d98 1056{
190154cf 1057 HttpRequest *request = http->request;
0ef77270 1058 HttpHeader *req_hdr = &request->header;
5086523e 1059 bool no_cache = false;
edce4d98 1060 const char *str;
62e76326 1061
edce4d98 1062 request->imslen = -1;
a9925b40 1063 request->ims = req_hdr->getTime(HDR_IF_MODIFIED_SINCE);
62e76326 1064
edce4d98 1065 if (request->ims > 0)
e857372a 1066 request->flags.ims = true;
62e76326 1067
450fe1cb 1068 if (!request->flags.ignoreCc) {
47fbd2a7 1069 if (request->cache_control) {
1259f9cf 1070 if (request->cache_control->hasNoCache())
5086523e 1071 no_cache=true;
62e76326 1072
adc2a453 1073 // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing
47fbd2a7 1074 } else if (req_hdr->has(HDR_PRAGMA))
cdf55306
AJ
1075 no_cache = req_hdr->hasListMember(HDR_PRAGMA,"no-cache",',');
1076
432bc83c
HN
1077 /*
1078 * Work around for supporting the Reload button in IE browsers when Squid
1079 * is used as an accelerator or transparent proxy, by turning accelerated
1080 * IMS request to no-cache requests. Now knows about IE 5.5 fix (is
1081 * actually only fixed in SP1, but we can't tell whether we are talking to
1082 * SP1 or not so all 5.5 versions are treated 'normally').
1083 */
1084 if (Config.onoff.ie_refresh) {
45e5102d 1085 if (http->flags.accel && request->flags.ims) {
432bc83c
HN
1086 if ((str = req_hdr->getStr(HDR_USER_AGENT))) {
1087 if (strstr(str, "MSIE 5.01") != NULL)
5086523e 1088 no_cache=true;
432bc83c 1089 else if (strstr(str, "MSIE 5.0") != NULL)
5086523e 1090 no_cache=true;
432bc83c 1091 else if (strstr(str, "MSIE 4.") != NULL)
5086523e 1092 no_cache=true;
432bc83c 1093 else if (strstr(str, "MSIE 3.") != NULL)
5086523e 1094 no_cache=true;
432bc83c 1095 }
62e76326 1096 }
1097 }
edce4d98 1098 }
914b89a2 1099
c2a7cefd 1100 if (request->method == Http::METHOD_OTHER) {
5086523e 1101 no_cache=true;
60745f24 1102 }
62e76326 1103
edce4d98 1104 if (no_cache) {
626096be 1105#if USE_HTTP_VIOLATIONS
62e76326 1106
1107 if (Config.onoff.reload_into_ims)
e857372a 1108 request->flags.nocacheHack = true;
62e76326 1109 else if (refresh_nocache_hack)
e857372a 1110 request->flags.nocacheHack = true;
62e76326 1111 else
edce4d98 1112#endif
62e76326 1113
e857372a 1114 request->flags.noCache = true;
edce4d98 1115 }
62e76326 1116
0ef77270 1117 /* ignore range header in non-GETs or non-HEADs */
c2a7cefd 1118 if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) {
56713d9a
AR
1119 // XXX: initialize if we got here without HttpRequest::parseHeader()
1120 if (!request->range)
1121 request->range = req_hdr->getRange();
62e76326 1122
1123 if (request->range) {
e857372a 1124 request->flags.isRanged = true;
62e76326 1125 clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data;
1126 /* XXX: This is suboptimal. We should give the stream the range set,
1127 * and thereby let the top of the stream set the offset when the
26ac0430 1128 * size becomes known. As it is, we will end up requesting from 0
62e76326 1129 * for evey -X range specification.
1130 * RBC - this may be somewhat wrong. We should probably set the range
1131 * iter up at this point.
1132 */
1133 node->readBuffer.offset = request->range->lowestOffset(0);
1134 http->range_iter.pos = request->range->begin();
24a8eaae 1135 http->range_iter.end = request->range->end();
62e76326 1136 http->range_iter.valid = true;
1137 }
edce4d98 1138 }
62e76326 1139
0ef77270 1140 /* Only HEAD and GET requests permit a Range or Request-Range header.
1141 * If these headers appear on any other type of request, delete them now.
1142 */
1143 else {
1144 req_hdr->delById(HDR_RANGE);
1145 req_hdr->delById(HDR_REQUEST_RANGE);
f0baf149 1146 request->ignoreRange("neither HEAD nor GET");
0ef77270 1147 }
1148
a9925b40 1149 if (req_hdr->has(HDR_AUTHORIZATION))
e857372a 1150 request->flags.auth = true;
62e76326 1151
46a1f562 1152 clientCheckPinning(http);
d67acb4e 1153
edce4d98 1154 if (request->login[0] != '\0')
e857372a 1155 request->flags.auth = true;
62e76326 1156
a9925b40 1157 if (req_hdr->has(HDR_VIA)) {
30abd221 1158 String s = req_hdr->getList(HDR_VIA);
62e76326 1159 /*
3c4fcf0f 1160 * ThisCache cannot be a member of Via header, "1.1 ThisCache" can.
62e76326 1161 * Note ThisCache2 has a space prepended to the hostname so we don't
1162 * accidentally match super-domains.
1163 */
1164
1165 if (strListIsSubstr(&s, ThisCache2, ',')) {
1166 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
1167 request, (ObjPackMethod) & httpRequestPack);
e857372a 1168 request->flags.loopDetected = true;
62e76326 1169 }
1170
21f6708d 1171#if USE_FORW_VIA_DB
bb790702 1172 fvdbCountVia(s.termedBuf());
62e76326 1173
edce4d98 1174#endif
62e76326 1175
30abd221 1176 s.clean();
edce4d98 1177 }
62e76326 1178
21f6708d 1179#if USE_FORW_VIA_DB
62e76326 1180
a9925b40 1181 if (req_hdr->has(HDR_X_FORWARDED_FOR)) {
30abd221 1182 String s = req_hdr->getList(HDR_X_FORWARDED_FOR);
bb790702 1183 fvdbCountForw(s.termedBuf());
30abd221 1184 s.clean();
edce4d98 1185 }
62e76326 1186
edce4d98 1187#endif
62e76326 1188
c2a7cefd 1189 request->flags.cachable = http->request->maybeCacheable();
62e76326 1190
edce4d98 1191 if (clientHierarchical(http))
e857372a 1192 request->flags.hierarchical = true;
62e76326 1193
bf8fe701 1194 debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " <<
450fe1cb 1195 (request->flags.noCache ? "SET" : "NOT SET"));
bf8fe701 1196 debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " <<
45e5102d 1197 (request->flags.cachable ? "SET" : "NOT SET"));
bf8fe701 1198 debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " <<
45e5102d 1199 (request->flags.hierarchical ? "SET" : "NOT SET"));
62e76326 1200
edce4d98 1201}
1202
1203void
e166785a 1204clientRedirectDoneWrapper(void *data, const HelperReply &result)
edce4d98 1205{
de31d06f 1206 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
db02222f 1207
de31d06f 1208 if (!calloutContext->httpStateIsValid())
62e76326 1209 return;
62e76326 1210
de31d06f 1211 calloutContext->clientRedirectDone(result);
1212}
1213
a8a0b1c2
EC
1214void
1215clientStoreIdDoneWrapper(void *data, const HelperReply &result)
1216{
1217 ClientRequestContext *calloutContext = (ClientRequestContext *)data;
1218
1219 if (!calloutContext->httpStateIsValid())
1220 return;
1221
1222 calloutContext->clientStoreIdDone(result);
1223}
1224
de31d06f 1225void
e166785a 1226ClientRequestContext::clientRedirectDone(const HelperReply &reply)
de31d06f 1227{
190154cf 1228 HttpRequest *old_request = http->request;
e166785a 1229 debugs(85, 5, HERE << "'" << http->uri << "' result=" << reply);
de31d06f 1230 assert(redirect_state == REDIRECT_PENDING);
1231 redirect_state = REDIRECT_DONE;
62e76326 1232
cf9f0261 1233 // Put helper response Notes into the transaction state record (ALE) eventually
d06e17ea 1234 // do it early to ensure that no matter what the outcome the notes are present.
457857fe
CT
1235 if (http->al != NULL)
1236 (void)SyncNotes(*http->al, *old_request);
1237
1238 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
d06e17ea 1239
63fc9fb5 1240 switch (reply.result) {
d06e17ea
AJ
1241 case HelperReply::Unknown:
1242 case HelperReply::TT:
1243 // Handler in redirect.cc should have already mapped Unknown
1244 // IF it contained valid entry for the old URL-rewrite helper protocol
1245 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply);
1246 break;
1247
1248 case HelperReply::BrokenHelper:
1249 debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: " << reply << ", attempt #" << (redirect_fail_count+1) << " of 2");
1250 if (redirect_fail_count < 2) { // XXX: make this configurable ?
1251 ++redirect_fail_count;
1252 // reset state flag to try redirector again from scratch.
1253 redirect_done = false;
1254 }
1255 break;
1256
1257 case HelperReply::Error:
1258 // no change to be done.
1259 break;
62e76326 1260
d06e17ea
AJ
1261 case HelperReply::Okay: {
1262 // #1: redirect with a specific status code OK status=NNN url="..."
1263 // #2: redirect with a default status code OK url="..."
1264 // #3: re-write the URL OK rewrite-url="..."
1265
cf9f0261
CT
1266 const char *statusNote = reply.notes.findFirst("status");
1267 const char *urlNote = reply.notes.findFirst("url");
d06e17ea
AJ
1268
1269 if (urlNote != NULL) {
1270 // HTTP protocol redirect to be done.
1271
1272 // TODO: change default redirect status for appropriate requests
1273 // Squid defaults to 302 status for now for better compatibility with old clients.
f11c8e2f 1274 // HTTP/1.0 client should get 302 (Http::scFound)
955394ce
AJ
1275 // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
1276 // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
f11c8e2f 1277 Http::StatusCode status = Http::scFound;
d06e17ea 1278 if (statusNote != NULL) {
cf9f0261 1279 const char * result = statusNote;
955394ce 1280 status = static_cast<Http::StatusCode>(atoi(result));
d06e17ea 1281 }
62e76326 1282
955394ce 1283 if (status == Http::scMovedPermanently
f11c8e2f 1284 || status == Http::scFound
955394ce
AJ
1285 || status == Http::scSeeOther
1286 || status == Http::scPermanentRedirect
1287 || status == Http::scTemporaryRedirect) {
62e76326 1288 http->redirect.status = status;
cf9f0261 1289 http->redirect.location = xstrdup(urlNote);
e5b677f0 1290 // TODO: validate the URL produced here is RFC 2616 compliant absolute URI
62e76326 1291 } else {
cf9f0261 1292 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << urlNote);
62e76326 1293 }
d06e17ea
AJ
1294 } else {
1295 // URL-rewrite wanted. Ew.
cf9f0261 1296 urlNote = reply.notes.findFirst("rewrite-url");
d06e17ea
AJ
1297
1298 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
cf9f0261 1299 if (urlNote != NULL && strcmp(urlNote, http->uri)) {
d06e17ea
AJ
1300 // XXX: validate the URL properly *without* generating a whole new request object right here.
1301 // XXX: the clone() should be done only AFTER we know the new URL is valid.
1302 HttpRequest *new_request = old_request->clone();
cf9f0261 1303 if (urlParse(old_request->method, const_cast<char*>(urlNote), new_request)) {
d06e17ea
AJ
1304 debugs(61,2, HERE << "URL-rewriter diverts URL from " << urlCanonical(old_request) << " to " << urlCanonical(new_request));
1305
1306 // update the new request to flag the re-writing was done on it
e857372a 1307 new_request->flags.redirected = true;
d06e17ea
AJ
1308
1309 // unlink bodypipe from the old request. Not needed there any longer.
1310 if (old_request->body_pipe != NULL) {
1311 old_request->body_pipe = NULL;
1312 debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
1313 " from request " << old_request << " to " << new_request);
1314 }
9be14530 1315
d06e17ea
AJ
1316 // update the current working ClientHttpRequest fields
1317 safe_free(http->uri);
1318 http->uri = xstrdup(urlCanonical(new_request));
1319 HTTPMSGUNLOCK(old_request);
b248c2a3
AJ
1320 http->request = new_request;
1321 HTTPMSGLOCK(http->request);
d06e17ea
AJ
1322 } else {
1323 debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " <<
cf9f0261 1324 old_request->method << " " << urlNote << " " << old_request->http_ver);
d06e17ea
AJ
1325 delete new_request;
1326 }
9be14530 1327 }
74b48915 1328 }
edce4d98 1329 }
d06e17ea
AJ
1330 break;
1331 }
62e76326 1332
edce4d98 1333 /* FIXME PIPELINE: This is innacurate during pipelining */
62e76326 1334
73c36fd9
AJ
1335 if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
1336 fd_note(http->getConn()->clientConnection->fd, http->uri);
62e76326 1337
c8be6d7b 1338 assert(http->uri);
62e76326 1339
de31d06f 1340 http->doCallouts();
edce4d98 1341}
1342
a8a0b1c2
EC
1343/**
1344 * This method handles the different replies from StoreID helper.
1345 */
1346void
1347ClientRequestContext::clientStoreIdDone(const HelperReply &reply)
1348{
1349 HttpRequest *old_request = http->request;
1350 debugs(85, 5, "'" << http->uri << "' result=" << reply);
1351 assert(store_id_state == REDIRECT_PENDING);
1352 store_id_state = REDIRECT_DONE;
1353
cf9f0261 1354 // Put helper response Notes into the transaction state record (ALE) eventually
a8a0b1c2 1355 // do it early to ensure that no matter what the outcome the notes are present.
457857fe
CT
1356 if (http->al != NULL)
1357 (void)SyncNotes(*http->al, *old_request);
1358
1359 UpdateRequestNotes(http->getConn(), *old_request, reply.notes);
a8a0b1c2
EC
1360
1361 switch (reply.result) {
1362 case HelperReply::Unknown:
1363 case HelperReply::TT:
1364 // Handler in redirect.cc should have already mapped Unknown
1365 // IF it contained valid entry for the old helper protocol
1366 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply);
1367 break;
1368
1369 case HelperReply::BrokenHelper:
1370 debugs(85, DBG_IMPORTANT, "ERROR: storeID helper: " << reply << ", attempt #" << (store_id_fail_count+1) << " of 2");
1371 if (store_id_fail_count < 2) { // XXX: make this configurable ?
1372 ++store_id_fail_count;
1373 // reset state flag to try StoreID again from scratch.
1374 store_id_done = false;
1375 }
1376 break;
1377
1378 case HelperReply::Error:
1379 // no change to be done.
1380 break;
1381
1382 case HelperReply::Okay: {
cf9f0261 1383 const char *urlNote = reply.notes.findFirst("store-id");
a8a0b1c2
EC
1384
1385 // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
cf9f0261 1386 if (urlNote != NULL && strcmp(urlNote, http->uri) ) {
a8a0b1c2 1387 // Debug section required for some very specific cases.
cf9f0261
CT
1388 debugs(85, 9, "Setting storeID with: " << urlNote );
1389 http->request->store_id = urlNote;
1390 http->store_id = urlNote;
a8a0b1c2
EC
1391 }
1392 }
1393 break;
1394 }
1395
1396 http->doCallouts();
1397}
1398
b50e327b
AJ
1399/** Test cache allow/deny configuration
1400 * Sets flags.cachable=1 if caching is not denied.
1401 */
edce4d98 1402void
8e2745f4 1403ClientRequestContext::checkNoCache()
edce4d98 1404{
b50e327b
AJ
1405 if (Config.accessList.noCache) {
1406 acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http);
1407 acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this);
1408 } else {
1409 /* unless otherwise specified, we try to cache. */
2efeb0b7 1410 checkNoCacheDone(ACCESS_ALLOWED);
b50e327b 1411 }
edce4d98 1412}
1413
de31d06f 1414static void
2efeb0b7 1415checkNoCacheDoneWrapper(allow_t answer, void *data)
edce4d98 1416{
de31d06f 1417 ClientRequestContext *calloutContext = (ClientRequestContext *) data;
e4a67a80 1418
de31d06f 1419 if (!calloutContext->httpStateIsValid())
1420 return;
1421
1422 calloutContext->checkNoCacheDone(answer);
8e2745f4 1423}
4fb35c3c 1424
8e2745f4 1425void
2efeb0b7 1426ClientRequestContext::checkNoCacheDone(const allow_t &answer)
62e76326 1427{
8e2745f4 1428 acl_checklist = NULL;
45e5102d 1429 http->request->flags.cachable = (answer == ACCESS_ALLOWED);
de31d06f 1430 http->doCallouts();
edce4d98 1431}
1432
cb4f4424 1433#if USE_OPENSSL
e0c0d54c
CT
1434bool
1435ClientRequestContext::sslBumpAccessCheck()
1436{
08097970
AR
1437 // If SSL connection tunneling or bumping decision has been made, obey it.
1438 const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode;
1439 if (bumpMode != Ssl::bumpEnd) {
1440 debugs(85, 5, HERE << "SslBump already decided (" << bumpMode <<
1441 "), " << "ignoring ssl_bump for " << http->getConn());
71cae389 1442 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
08097970
AR
1443 return false;
1444 }
e0c0d54c 1445
08097970
AR
1446 // If we have not decided yet, decide whether to bump now.
1447
1448 // Bumping here can only start with a CONNECT request on a bumping port
1449 // (bumping of intercepted SSL conns is decided before we get 1st request).
1450 // We also do not bump redirected CONNECT requests.
c2a7cefd 1451 if (http->request->method != Http::METHOD_CONNECT || http->redirect.status ||
6a25a046
FC
1452 !Config.accessList.ssl_bump ||
1453 !http->getConn()->port->flags.tunnelSslBumping) {
71cae389 1454 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
08097970 1455 debugs(85, 5, HERE << "cannot SslBump this request");
e0c0d54c
CT
1456 return false;
1457 }
08097970
AR
1458
1459 // Do not bump during authentication: clients would not proxy-authenticate
1460 // if we delay a 407 response and respond with 200 OK to CONNECT.
955394ce 1461 if (error && error->httpStatus == Http::scProxyAuthenticationRequired) {
71cae389 1462 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
08097970
AR
1463 debugs(85, 5, HERE << "no SslBump during proxy authentication");
1464 return false;
1465 }
1466
1467 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1468
eb898410
AJ
1469 ACLFilledChecklist *aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1470 aclChecklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
08097970 1471 return true;
e0c0d54c
CT
1472}
1473
f8901ea9 1474/**
e0c0d54c
CT
1475 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1476 * as ACLFilledChecklist callback
1477 */
1478static void
2efeb0b7 1479sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
e0c0d54c
CT
1480{
1481 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
9d5e7196
AJ
1482
1483 if (!calloutContext->httpStateIsValid())
1484 return;
ed6163ef 1485 calloutContext->sslBumpAccessCheckDone(answer);
e0c0d54c
CT
1486}
1487
1488void
ed6163ef 1489ClientRequestContext::sslBumpAccessCheckDone(const allow_t &answer)
e0c0d54c 1490{
ed6163ef
AJ
1491 if (!httpStateIsValid())
1492 return;
1493
08097970 1494 const Ssl::BumpMode bumpMode = answer == ACCESS_ALLOWED ?
87f237a9 1495 static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpNone;
08097970 1496 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
71cae389 1497 http->al->ssl.bumpMode = bumpMode; // for logging
caf3666d 1498
e0c0d54c
CT
1499 http->doCallouts();
1500}
1501#endif
1502
69660be0 1503/*
1504 * Identify requests that do not go through the store and client side stream
1505 * and forward them to the appropriate location. All other requests, request
1506 * them.
edce4d98 1507 */
1508void
8e2745f4 1509ClientHttpRequest::processRequest()
edce4d98 1510{
7f06a3d8 1511 debugs(85, 4, request->method << ' ' << uri);
62e76326 1512
c2a7cefd 1513 if (request->method == Http::METHOD_CONNECT && !redirect.status) {
cb4f4424 1514#if USE_OPENSSL
31281814
AJ
1515 if (sslBumpNeeded()) {
1516 sslBumpStart();
1517 return;
1518 }
3712be3f 1519#endif
f84dd7eb 1520 getConn()->stopReading(); // tunnels read for themselves
06521a10 1521 tunnelStart(this, &out.size, &al->http.code, al);
62e76326 1522 return;
edce4d98 1523 }
62e76326 1524
8e2745f4 1525 httpStart();
1526}
1527
1528void
1529ClientHttpRequest::httpStart()
1530{
559da936 1531 PROF_start(httpStart);
8e2745f4 1532 logType = LOG_TAG_NONE;
02c8dde5 1533 debugs(85, 4, LogTags_str[logType] << " for '" << uri << "'");
bf8fe701 1534
edce4d98 1535 /* no one should have touched this */
8e2745f4 1536 assert(out.offset == 0);
edce4d98 1537 /* Use the Stream Luke */
8e2745f4 1538 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1539 clientStreamRead(node, this, node->readBuffer);
559da936 1540 PROF_stop(httpStart);
edce4d98 1541}
0655fa4d 1542
cb4f4424 1543#if USE_OPENSSL
3712be3f 1544
e0c0d54c 1545void
08097970 1546ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode)
e0c0d54c 1547{
caf3666d 1548 debugs(83, 3, HERE << "sslBump required: "<< Ssl::bumpMode(mode));
08097970 1549 sslBumpNeed_ = mode;
3712be3f 1550}
1551
1552// called when comm_write has completed
1553static void
c8407295 1554SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
3712be3f 1555{
1556 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1557 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1558
1559 assert(r && cbdataReferenceValid(r));
1560 r->sslBumpEstablish(errflag);
1561}
1562
1563void
c8407295 1564ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag)
3712be3f 1565{
c8407295
AJ
1566 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1567 if (errflag == Comm::ERR_CLOSING)
3712be3f 1568 return;
1569
1570 if (errflag) {
1fa35be8 1571 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
bbc83914 1572 getConn()->clientConnection->close();
3712be3f 1573 return;
1574 }
1575
40d8be97
AR
1576 // We lack HttpReply which logRequest() uses to log the status code.
1577 // TODO: Use HttpReply instead of the "200 Connection established" string.
71cae389 1578 al->http.code = 200;
40d8be97 1579
21512911
CT
1580#if USE_AUTH
1581 // Preserve authentication info for the ssl-bumped request
1582 if (request->auth_user_request != NULL)
cc1e110a 1583 getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
21512911 1584#endif
03f00a11 1585
08097970
AR
1586 assert(sslBumpNeeded());
1587 getConn()->switchToHttps(request, sslBumpNeed_);
3712be3f 1588}
1589
1590void
1591ClientHttpRequest::sslBumpStart()
1592{
08097970
AR
1593 debugs(85, 5, HERE << "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
1594 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1595 getConn()->sslBumpMode = sslBumpNeed_;
3712be3f 1596
08097970 1597 // send an HTTP 200 response to kick client SSL negotiation
3712be3f 1598 // TODO: Unify with tunnel.cc and add a Server(?) header
b0388924 1599 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
ec41b64c
AJ
1600 AsyncCall::Pointer call = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1601 CommIoCbPtrFun(&SslBumpEstablish, this));
73c36fd9 1602 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), call, NULL);
3712be3f 1603}
1604
1605#endif
1606
0655fa4d 1607bool
1608ClientHttpRequest::gotEnough() const
1609{
86a2f789 1610 /** TODO: should be querying the stream. */
7173d5b0 1611 int64_t contentLength =
06a5ae20 1612 memObject()->getReply()->bodySize(request->method);
0655fa4d 1613 assert(contentLength >= 0);
1614
1615 if (out.offset < contentLength)
1616 return false;
1617
1618 return true;
1619}
1620
86a2f789 1621void
1622ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1623{
1624 entry_ = newEntry;
1625}
1626
0976f8db 1627void
1628ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1629{
1630 if (loggingEntry_)
1bfe9ade 1631 loggingEntry_->unlock("ClientHttpRequest::loggingEntry");
0976f8db 1632
1633 loggingEntry_ = newEntry;
1634
1635 if (loggingEntry_)
1bfe9ade 1636 loggingEntry_->lock("ClientHttpRequest::loggingEntry");
0976f8db 1637}
86a2f789 1638
de31d06f 1639/*
1640 * doCallouts() - This function controls the order of "callout"
1641 * executions, including non-blocking access control checks, the
1642 * redirector, and ICAP. Previously, these callouts were chained
1643 * together such that "clientAccessCheckDone()" would call
1644 * "clientRedirectStart()" and so on.
1645 *
1646 * The ClientRequestContext (aka calloutContext) class holds certain
1647 * state data for the callout/callback operations. Previously
1648 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1649 * for a short time. ClientRequestContext would then delete itself
1650 * and pass control back to ClientHttpRequest when all callouts
1651 * were finished.
1652 *
1653 * This caused some problems for ICAP because we want to make the
1654 * ICAP callout after checking ACLs, but before checking the no_cache
1655 * list. We can't stuff the ICAP state into the ClientRequestContext
1656 * class because we still need the ICAP state after ClientRequestContext
1657 * goes away.
1658 *
1659 * Note that ClientRequestContext is created before the first call
1660 * to doCallouts().
1661 *
1662 * If one of the callouts notices that ClientHttpRequest is no
1663 * longer valid, it should call cbdataReferenceDone() so that
1664 * ClientHttpRequest's reference count goes to zero and it will get
1665 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1666 *
1667 * Note that we set the _done flags here before actually starting
1668 * the callout. This is strictly for convenience.
1669 */
1670
82afb125
FC
1671tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1672nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
057f5854 1673
de31d06f 1674void
1675ClientHttpRequest::doCallouts()
1676{
1677 assert(calloutContext);
1678
6fca33e0 1679 /*Save the original request for logging purposes*/
b248c2a3
AJ
1680 if (!calloutContext->http->al->request) {
1681 calloutContext->http->al->request = request;
1682 HTTPMSGLOCK(calloutContext->http->al->request);
457857fe
CT
1683
1684 NotePairs &notes = SyncNotes(*calloutContext->http->al, *calloutContext->http->request);
1685 // Make the previously set client connection ID available as annotation.
1686 if (ConnStateData *csd = calloutContext->http->getConn()) {
1687 if (!csd->connectionTag().isEmpty())
1688 notes.add("clt_conn_tag", SBuf(csd->connectionTag()).c_str());
1689 }
b248c2a3 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