]> git.ipfire.org Git - thirdparty/squid.git/blob - src/client_side_request.cc
Second adaptation missing for CONNECTs
[thirdparty/squid.git] / src / client_side_request.cc
1 /*
2 * Copyright (C) 1996-2017 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 http->al->syncNotes(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)
1210 http->al->syncNotes(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)
1333 http->al->syncNotes(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 if (answer == ACCESS_DENIED) {
1403 http->request->flags.noCache = true; // dont read reply from cache
1404 http->request->flags.cachable = false; // dont store reply into cache
1405 }
1406 http->doCallouts();
1407 }
1408
1409 #if USE_OPENSSL
1410 bool
1411 ClientRequestContext::sslBumpAccessCheck()
1412 {
1413 if (!http->getConn()) {
1414 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1415 return false;
1416 }
1417
1418 const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode;
1419 if (http->request->flags.forceTunnel) {
1420 debugs(85, 5, "not needed; already decided to tunnel " << http->getConn());
1421 if (bumpMode != Ssl::bumpEnd)
1422 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1423 return false;
1424 }
1425
1426 // If SSL connection tunneling or bumping decision has been made, obey it.
1427 if (bumpMode != Ssl::bumpEnd) {
1428 debugs(85, 5, HERE << "SslBump already decided (" << bumpMode <<
1429 "), " << "ignoring ssl_bump for " << http->getConn());
1430 if (!http->getConn()->serverBump())
1431 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed and not already bumped
1432 http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection
1433 return false;
1434 }
1435
1436 // If we have not decided yet, decide whether to bump now.
1437
1438 // Bumping here can only start with a CONNECT request on a bumping port
1439 // (bumping of intercepted SSL conns is decided before we get 1st request).
1440 // We also do not bump redirected CONNECT requests.
1441 if (http->request->method != Http::METHOD_CONNECT || http->redirect.status ||
1442 !Config.accessList.ssl_bump ||
1443 !http->getConn()->port->flags.tunnelSslBumping) {
1444 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1445 debugs(85, 5, HERE << "cannot SslBump this request");
1446 return false;
1447 }
1448
1449 // Do not bump during authentication: clients would not proxy-authenticate
1450 // if we delay a 407 response and respond with 200 OK to CONNECT.
1451 if (error && error->httpStatus == Http::scProxyAuthenticationRequired) {
1452 http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log -
1453 debugs(85, 5, HERE << "no SslBump during proxy authentication");
1454 return false;
1455 }
1456
1457 if (error) {
1458 debugs(85, 5, "SslBump applies. Force bump action on error " << errorTypeName(error->type));
1459 http->sslBumpNeed(Ssl::bumpBump);
1460 http->al->ssl.bumpMode = Ssl::bumpBump;
1461 return false;
1462 }
1463
1464 debugs(85, 5, HERE << "SslBump possible, checking ACL");
1465
1466 ACLFilledChecklist *aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http);
1467 aclChecklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this);
1468 return true;
1469 }
1470
1471 /**
1472 * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method
1473 * as ACLFilledChecklist callback
1474 */
1475 static void
1476 sslBumpAccessCheckDoneWrapper(allow_t answer, void *data)
1477 {
1478 ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data);
1479
1480 if (!calloutContext->httpStateIsValid())
1481 return;
1482 calloutContext->sslBumpAccessCheckDone(answer);
1483 }
1484
1485 void
1486 ClientRequestContext::sslBumpAccessCheckDone(const allow_t &answer)
1487 {
1488 if (!httpStateIsValid())
1489 return;
1490
1491 const Ssl::BumpMode bumpMode = answer == ACCESS_ALLOWED ?
1492 static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpNone;
1493 http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed
1494 http->al->ssl.bumpMode = bumpMode; // for logging
1495
1496 http->doCallouts();
1497 }
1498 #endif
1499
1500 /*
1501 * Identify requests that do not go through the store and client side stream
1502 * and forward them to the appropriate location. All other requests, request
1503 * them.
1504 */
1505 void
1506 ClientHttpRequest::processRequest()
1507 {
1508 debugs(85, 4, request->method << ' ' << uri);
1509
1510 const bool untouchedConnect = request->method == Http::METHOD_CONNECT && !redirect.status;
1511
1512 #if USE_OPENSSL
1513 if (untouchedConnect && sslBumpNeeded()) {
1514 assert(!request->flags.forceTunnel);
1515 sslBumpStart();
1516 return;
1517 }
1518 #endif
1519
1520 if (untouchedConnect || request->flags.forceTunnel) {
1521 getConn()->stopReading(); // tunnels read for themselves
1522 tunnelStart(this);
1523 return;
1524 }
1525
1526 httpStart();
1527 }
1528
1529 void
1530 ClientHttpRequest::httpStart()
1531 {
1532 PROF_start(httpStart);
1533 logType = LOG_TAG_NONE;
1534 debugs(85, 4, logType.c_str() << " for '" << uri << "'");
1535
1536 /* no one should have touched this */
1537 assert(out.offset == 0);
1538 /* Use the Stream Luke */
1539 clientStreamNode *node = (clientStreamNode *)client_stream.tail->data;
1540 clientStreamRead(node, this, node->readBuffer);
1541 PROF_stop(httpStart);
1542 }
1543
1544 #if USE_OPENSSL
1545
1546 void
1547 ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode)
1548 {
1549 debugs(83, 3, HERE << "sslBump required: "<< Ssl::bumpMode(mode));
1550 sslBumpNeed_ = mode;
1551 }
1552
1553 // called when comm_write has completed
1554 static void
1555 SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data)
1556 {
1557 ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data);
1558 debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag);
1559
1560 assert(r && cbdataReferenceValid(r));
1561 r->sslBumpEstablish(errflag);
1562 }
1563
1564 void
1565 ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag)
1566 {
1567 // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up
1568 if (errflag == Comm::ERR_CLOSING)
1569 return;
1570
1571 if (errflag) {
1572 debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag);
1573 getConn()->clientConnection->close();
1574 return;
1575 }
1576
1577 // We lack HttpReply which logRequest() uses to log the status code.
1578 // TODO: Use HttpReply instead of the "200 Connection established" string.
1579 al->http.code = 200;
1580
1581 #if USE_AUTH
1582 // Preserve authentication info for the ssl-bumped request
1583 if (request->auth_user_request != NULL)
1584 getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
1585 #endif
1586
1587 assert(sslBumpNeeded());
1588 getConn()->switchToHttps(request, sslBumpNeed_);
1589 }
1590
1591 void
1592 ClientHttpRequest::sslBumpStart()
1593 {
1594 debugs(85, 5, HERE << "Confirming " << Ssl::bumpMode(sslBumpNeed_) <<
1595 "-bumped CONNECT tunnel on FD " << getConn()->clientConnection);
1596 getConn()->sslBumpMode = sslBumpNeed_;
1597
1598 AsyncCall::Pointer bumpCall = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish",
1599 CommIoCbPtrFun(&SslBumpEstablish, this));
1600
1601 if (request->flags.interceptTproxy || request->flags.intercepted) {
1602 CommIoCbParams &params = GetCommParams<CommIoCbParams>(bumpCall);
1603 params.flag = Comm::OK;
1604 params.conn = getConn()->clientConnection;
1605 ScheduleCallHere(bumpCall);
1606 return;
1607 }
1608
1609 // send an HTTP 200 response to kick client SSL negotiation
1610 // TODO: Unify with tunnel.cc and add a Server(?) header
1611 static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n";
1612 Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), bumpCall, NULL);
1613 }
1614
1615 #endif
1616
1617 bool
1618 ClientHttpRequest::gotEnough() const
1619 {
1620 /** TODO: should be querying the stream. */
1621 int64_t contentLength =
1622 memObject()->getReply()->bodySize(request->method);
1623 assert(contentLength >= 0);
1624
1625 if (out.offset < contentLength)
1626 return false;
1627
1628 return true;
1629 }
1630
1631 void
1632 ClientHttpRequest::storeEntry(StoreEntry *newEntry)
1633 {
1634 entry_ = newEntry;
1635 }
1636
1637 void
1638 ClientHttpRequest::loggingEntry(StoreEntry *newEntry)
1639 {
1640 if (loggingEntry_)
1641 loggingEntry_->unlock("ClientHttpRequest::loggingEntry");
1642
1643 loggingEntry_ = newEntry;
1644
1645 if (loggingEntry_)
1646 loggingEntry_->lock("ClientHttpRequest::loggingEntry");
1647 }
1648
1649 /*
1650 * doCallouts() - This function controls the order of "callout"
1651 * executions, including non-blocking access control checks, the
1652 * redirector, and ICAP. Previously, these callouts were chained
1653 * together such that "clientAccessCheckDone()" would call
1654 * "clientRedirectStart()" and so on.
1655 *
1656 * The ClientRequestContext (aka calloutContext) class holds certain
1657 * state data for the callout/callback operations. Previously
1658 * ClientHttpRequest would sort of hand off control to ClientRequestContext
1659 * for a short time. ClientRequestContext would then delete itself
1660 * and pass control back to ClientHttpRequest when all callouts
1661 * were finished.
1662 *
1663 * This caused some problems for ICAP because we want to make the
1664 * ICAP callout after checking ACLs, but before checking the no_cache
1665 * list. We can't stuff the ICAP state into the ClientRequestContext
1666 * class because we still need the ICAP state after ClientRequestContext
1667 * goes away.
1668 *
1669 * Note that ClientRequestContext is created before the first call
1670 * to doCallouts().
1671 *
1672 * If one of the callouts notices that ClientHttpRequest is no
1673 * longer valid, it should call cbdataReferenceDone() so that
1674 * ClientHttpRequest's reference count goes to zero and it will get
1675 * deleted. ClientHttpRequest will then delete ClientRequestContext.
1676 *
1677 * Note that we set the _done flags here before actually starting
1678 * the callout. This is strictly for convenience.
1679 */
1680
1681 tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch);
1682 nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch);
1683
1684 void
1685 ClientHttpRequest::doCallouts()
1686 {
1687 assert(calloutContext);
1688
1689 auto &ale = calloutContext->http->al;
1690 /*Save the original request for logging purposes*/
1691 if (!ale->request) {
1692 ale->request = request;
1693 HTTPMSGLOCK(ale->request);
1694
1695 // Make the previously set client connection ID available as annotation.
1696 if (ConnStateData *csd = calloutContext->http->getConn()) {
1697 if (!csd->notes()->empty())
1698 calloutContext->http->request->notes()->appendNewOnly(csd->notes().getRaw());
1699 }
1700 ale->syncNotes(calloutContext->http->request);
1701 }
1702
1703 if (!calloutContext->error) {
1704 // CVE-2009-0801: verify the Host: header is consistent with other known details.
1705 if (!calloutContext->host_header_verify_done) {
1706 debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()");
1707 calloutContext->host_header_verify_done = true;
1708 calloutContext->hostHeaderVerify();
1709 return;
1710 }
1711
1712 if (!calloutContext->http_access_done) {
1713 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()");
1714 calloutContext->http_access_done = true;
1715 calloutContext->clientAccessCheck();
1716 return;
1717 }
1718
1719 #if USE_ADAPTATION
1720 if (!calloutContext->adaptation_acl_check_done) {
1721 calloutContext->adaptation_acl_check_done = true;
1722 if (Adaptation::AccessCheck::Start(
1723 Adaptation::methodReqmod, Adaptation::pointPreCache,
1724 request, NULL, calloutContext->http->al, this))
1725 return; // will call callback
1726 }
1727 #endif
1728
1729 if (!calloutContext->redirect_done) {
1730 calloutContext->redirect_done = true;
1731
1732 if (Config.Program.redirect) {
1733 debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()");
1734 calloutContext->redirect_state = REDIRECT_PENDING;
1735 calloutContext->clientRedirectStart();
1736 return;
1737 }
1738 }
1739
1740 if (!calloutContext->adapted_http_access_done) {
1741 debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()");
1742 calloutContext->adapted_http_access_done = true;
1743 calloutContext->clientAccessCheck2();
1744 return;
1745 }
1746
1747 if (!calloutContext->store_id_done) {
1748 calloutContext->store_id_done = true;
1749
1750 if (Config.Program.store_id) {
1751 debugs(83, 3,"Doing calloutContext->clientStoreIdStart()");
1752 calloutContext->store_id_state = REDIRECT_PENDING;
1753 calloutContext->clientStoreIdStart();
1754 return;
1755 }
1756 }
1757
1758 if (!calloutContext->interpreted_req_hdrs) {
1759 debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()");
1760 calloutContext->interpreted_req_hdrs = 1;
1761 clientInterpretRequestHeaders(this);
1762 }
1763
1764 if (!calloutContext->no_cache_done) {
1765 calloutContext->no_cache_done = true;
1766
1767 if (Config.accessList.noCache && request->flags.cachable) {
1768 debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()");
1769 calloutContext->checkNoCache();
1770 return;
1771 }
1772 }
1773 } // if !calloutContext->error
1774
1775 if (!calloutContext->tosToClientDone) {
1776 calloutContext->tosToClientDone = true;
1777 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
1778 ACLFilledChecklist ch(NULL, request, NULL);
1779 ch.src_addr = request->client_addr;
1780 ch.my_addr = request->my_addr;
1781 tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch);
1782 if (tos)
1783 Ip::Qos::setSockTos(getConn()->clientConnection, tos);
1784 }
1785 }
1786
1787 if (!calloutContext->nfmarkToClientDone) {
1788 calloutContext->nfmarkToClientDone = true;
1789 if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) {
1790 ACLFilledChecklist ch(NULL, request, NULL);
1791 ch.src_addr = request->client_addr;
1792 ch.my_addr = request->my_addr;
1793 nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch);
1794 if (mark)
1795 Ip::Qos::setSockNfmark(getConn()->clientConnection, mark);
1796 }
1797 }
1798
1799 #if USE_OPENSSL
1800 // Even with calloutContext->error, we call sslBumpAccessCheck() to decide
1801 // whether SslBump applies to this transaction. If it applies, we will
1802 // attempt to bump the client to serve the error.
1803 if (!calloutContext->sslBumpCheckDone) {
1804 calloutContext->sslBumpCheckDone = true;
1805 if (calloutContext->sslBumpAccessCheck())
1806 return;
1807 /* else no ssl bump required*/
1808 }
1809 #endif
1810
1811 if (calloutContext->error) {
1812 // XXX: prformance regression. c_str() reallocates
1813 SBuf storeUriBuf(request->storeId());
1814 const char *storeUri = storeUriBuf.c_str();
1815 StoreEntry *e = storeCreateEntry(storeUri, storeUri, request->flags, request->method);
1816 #if USE_OPENSSL
1817 if (sslBumpNeeded()) {
1818 // We have to serve an error, so bump the client first.
1819 sslBumpNeed(Ssl::bumpClientFirst);
1820 // set final error but delay sending until we bump
1821 Ssl::ServerBump *srvBump = new Ssl::ServerBump(request, e, Ssl::bumpClientFirst);
1822 errorAppendEntry(e, calloutContext->error);
1823 calloutContext->error = NULL;
1824 getConn()->setServerBump(srvBump);
1825 e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
1826 } else
1827 #endif
1828 {
1829 // send the error to the client now
1830 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1831 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1832 assert (repContext);
1833 repContext->setReplyToStoreEntry(e, "immediate SslBump error");
1834 errorAppendEntry(e, calloutContext->error);
1835 calloutContext->error = NULL;
1836 if (calloutContext->readNextRequest && getConn())
1837 getConn()->flags.readMore = true; // resume any pipeline reads.
1838 node = (clientStreamNode *)client_stream.tail->data;
1839 clientStreamRead(node, this, node->readBuffer);
1840 e->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded");
1841 return;
1842 }
1843 }
1844
1845 cbdataReferenceDone(calloutContext->http);
1846 delete calloutContext;
1847 calloutContext = NULL;
1848 #if HEADERS_LOG
1849
1850 headersLog(0, 1, request->method, request);
1851 #endif
1852
1853 debugs(83, 3, HERE << "calling processRequest()");
1854 processRequest();
1855
1856 #if ICAP_CLIENT
1857 Adaptation::Icap::History::Pointer ih = request->icapHistory();
1858 if (ih != NULL)
1859 ih->logType = logType;
1860 #endif
1861 }
1862
1863 #if USE_ADAPTATION
1864 /// Initiate an asynchronous adaptation transaction which will call us back.
1865 void
1866 ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g)
1867 {
1868 debugs(85, 3, HERE << "adaptation needed for " << this);
1869 assert(!virginHeadSource);
1870 assert(!adaptedBodySource);
1871 virginHeadSource = initiateAdaptation(
1872 new Adaptation::Iterator(request, NULL, al, g));
1873
1874 // we could try to guess whether we can bypass this adaptation
1875 // initiation failure, but it should not really happen
1876 Must(initiated(virginHeadSource));
1877 }
1878
1879 void
1880 ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer)
1881 {
1882 assert(cbdataReferenceValid(this)); // indicates bug
1883 clearAdaptation(virginHeadSource);
1884 assert(!adaptedBodySource);
1885
1886 switch (answer.kind) {
1887 case Adaptation::Answer::akForward:
1888 handleAdaptedHeader(const_cast<Http::Message*>(answer.message.getRaw()));
1889 break;
1890
1891 case Adaptation::Answer::akBlock:
1892 handleAdaptationBlock(answer);
1893 break;
1894
1895 case Adaptation::Answer::akError:
1896 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final);
1897 break;
1898 }
1899 }
1900
1901 void
1902 ClientHttpRequest::handleAdaptedHeader(Http::Message *msg)
1903 {
1904 assert(msg);
1905
1906 if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) {
1907 /*
1908 * Replace the old request with the new request.
1909 */
1910 HTTPMSGUNLOCK(request);
1911 request = new_req;
1912 HTTPMSGLOCK(request);
1913
1914 // update the new message to flag whether URL re-writing was done on it
1915 if (request->effectiveRequestUri().cmp(uri) != 0)
1916 request->flags.redirected = 1;
1917
1918 /*
1919 * Store the new URI for logging
1920 */
1921 xfree(uri);
1922 uri = SBufToCstring(request->effectiveRequestUri());
1923 setLogUri(this, urlCanonicalClean(request));
1924 assert(request->method.id());
1925 } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) {
1926 debugs(85,3,HERE << "REQMOD reply is HTTP reply");
1927
1928 // subscribe to receive reply body
1929 if (new_rep->body_pipe != NULL) {
1930 adaptedBodySource = new_rep->body_pipe;
1931 int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
1932 assert(consumer_ok);
1933 }
1934
1935 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
1936 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
1937 assert(repContext);
1938 repContext->createStoreEntry(request->method, request->flags);
1939
1940 EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT);
1941 request_satisfaction_mode = true;
1942 request_satisfaction_offset = 0;
1943 storeEntry()->replaceHttpReply(new_rep);
1944 storeEntry()->timestampsSet();
1945
1946 if (!adaptedBodySource) // no body
1947 storeEntry()->complete();
1948 clientGetMoreData(node, this);
1949 }
1950
1951 // we are done with getting headers (but may be receiving body)
1952 clearAdaptation(virginHeadSource);
1953
1954 if (!request_satisfaction_mode)
1955 doCallouts();
1956 }
1957
1958 void
1959 ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer)
1960 {
1961 request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK);
1962 AclMatchedName = answer.ruleId.termedBuf();
1963 assert(calloutContext);
1964 calloutContext->clientAccessCheckDone(ACCESS_DENIED);
1965 AclMatchedName = NULL;
1966 }
1967
1968 void
1969 ClientHttpRequest::resumeBodyStorage()
1970 {
1971 if (!adaptedBodySource)
1972 return;
1973
1974 noteMoreBodyDataAvailable(adaptedBodySource);
1975 }
1976
1977 void
1978 ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
1979 {
1980 assert(request_satisfaction_mode);
1981 assert(adaptedBodySource != NULL);
1982
1983 if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
1984 const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
1985
1986 if (spaceAvailable < contentSize ) {
1987 // No or partial body data consuming
1988 typedef NullaryMemFunT<ClientHttpRequest> Dialer;
1989 AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage",
1990 Dialer(this, &ClientHttpRequest::resumeBodyStorage));
1991 storeEntry()->deferProducer(call);
1992 }
1993
1994 if (!spaceAvailable)
1995 return;
1996
1997 if (spaceAvailable < contentSize )
1998 contentSize = spaceAvailable;
1999
2000 BodyPipeCheckout bpc(*adaptedBodySource);
2001 const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize);
2002 storeEntry()->write(ioBuf);
2003 // assume StoreEntry::write() writes the entire ioBuf
2004 request_satisfaction_offset += ioBuf.length;
2005 bpc.buf.consume(contentSize);
2006 bpc.checkIn();
2007 }
2008
2009 if (adaptedBodySource->exhausted())
2010 endRequestSatisfaction();
2011 // else wait for more body data
2012 }
2013
2014 void
2015 ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer)
2016 {
2017 assert(!virginHeadSource);
2018 // should we end request satisfaction now?
2019 if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
2020 endRequestSatisfaction();
2021 }
2022
2023 void
2024 ClientHttpRequest::endRequestSatisfaction()
2025 {
2026 debugs(85,4, HERE << this << " ends request satisfaction");
2027 assert(request_satisfaction_mode);
2028 stopConsumingFrom(adaptedBodySource);
2029
2030 // TODO: anything else needed to end store entry formation correctly?
2031 storeEntry()->complete();
2032 }
2033
2034 void
2035 ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer)
2036 {
2037 assert(!virginHeadSource);
2038 stopConsumingFrom(adaptedBodySource);
2039
2040 debugs(85,3, HERE << "REQMOD body production failed");
2041 if (request_satisfaction_mode) { // too late to recover or serve an error
2042 request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY);
2043 const Comm::ConnectionPointer c = getConn()->clientConnection;
2044 Must(Comm::IsConnOpen(c));
2045 c->close(); // drastic, but we may be writing a response already
2046 } else {
2047 handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY);
2048 }
2049 }
2050
2051 void
2052 ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable)
2053 {
2054 debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")");
2055
2056 const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
2057 const bool usedPipe = request->body_pipe != NULL &&
2058 request->body_pipe->consumedSize() > 0;
2059
2060 if (bypassable && !usedStore && !usedPipe) {
2061 debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext);
2062 if (calloutContext)
2063 doCallouts();
2064 return;
2065 }
2066
2067 debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error");
2068
2069 clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data;
2070 clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
2071 assert(repContext);
2072
2073 calloutsError(ERR_ICAP_FAILURE, errDetail);
2074
2075 if (calloutContext)
2076 doCallouts();
2077 }
2078
2079 void
2080 ClientHttpRequest::callException(const std::exception &ex)
2081 {
2082 if (const auto clientConn = getConn() ? getConn()->clientConnection : nullptr) {
2083 if (Comm::IsConnOpen(clientConn)) {
2084 debugs(85, 3, "closing after exception: " << ex.what());
2085 clientConn->close(); // initiate orderly top-to-bottom cleanup
2086 return;
2087 }
2088 }
2089 debugs(85, DBG_IMPORTANT, "ClientHttpRequest exception without connection. Ignoring " << ex.what());
2090 // XXX: Normally, we mustStop() but we cannot do that here because it is
2091 // likely to leave Http::Stream and ConnStateData with a dangling http
2092 // pointer. See r13480 or XXX in Http::Stream class description.
2093 }
2094 #endif
2095
2096 // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too.
2097 void
2098 ClientHttpRequest::calloutsError(const err_type error, const int errDetail)
2099 {
2100 // The original author of the code also wanted to pass an errno to
2101 // setReplyToError, but it seems unlikely that the errno reflects the
2102 // true cause of the error at this point, so I did not pass it.
2103 if (calloutContext) {
2104 Ip::Address noAddr;
2105 noAddr.setNoAddr();
2106 ConnStateData * c = getConn();
2107 calloutContext->error = clientBuildError(error, Http::scInternalServerError,
2108 NULL,
2109 c != NULL ? c->clientConnection->remote : noAddr,
2110 request
2111 );
2112 #if USE_AUTH
2113 calloutContext->error->auth_user_request =
2114 c != NULL && c->getAuth() != NULL ? c->getAuth() : request->auth_user_request;
2115 #endif
2116 calloutContext->error->detailError(errDetail);
2117 calloutContext->readNextRequest = true;
2118 if (c != NULL)
2119 c->expectNoForwarding();
2120 }
2121 //else if(calloutContext == NULL) is it possible?
2122 }
2123