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