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