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