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