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