]>
Commit | Line | Data |
---|---|---|
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 | (void)SyncNotes(*http->al, *http->request); | |
898 | if (Config.accessList.redirector) { | |
899 | acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http); | |
900 | acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this); | |
901 | } else | |
902 | redirectStart(http, clientRedirectDoneWrapper, this); | |
903 | } | |
904 | ||
905 | /** | |
906 | * This methods handles Access checks result of StoreId access list. | |
907 | * Will handle as "ERR" (no change) in a case Access is not allowed. | |
908 | */ | |
909 | static void | |
910 | clientStoreIdAccessCheckDone(allow_t answer, void *data) | |
911 | { | |
912 | ClientRequestContext *context = static_cast<ClientRequestContext *>(data); | |
913 | ClientHttpRequest *http = context->http; | |
914 | context->acl_checklist = NULL; | |
915 | ||
916 | if (answer == ACCESS_ALLOWED) | |
917 | storeIdStart(http, clientStoreIdDoneWrapper, context); | |
918 | else { | |
919 | debugs(85, 3, "access denied expected ERR reply handling: " << answer); | |
920 | Helper::Reply const nilReply(Helper::Error); | |
921 | context->clientStoreIdDone(nilReply); | |
922 | } | |
923 | } | |
924 | ||
925 | /** | |
926 | * Start locating an alternative storeage ID string (if any) from admin | |
927 | * configured helper program. This is an asynchronous operation terminating in | |
928 | * ClientRequestContext::clientStoreIdDone() when completed. | |
929 | */ | |
930 | void | |
931 | ClientRequestContext::clientStoreIdStart() | |
932 | { | |
933 | debugs(33, 5,"'" << http->uri << "'"); | |
934 | ||
935 | if (Config.accessList.store_id) { | |
936 | acl_checklist = clientAclChecklistCreate(Config.accessList.store_id, http); | |
937 | acl_checklist->nonBlockingCheck(clientStoreIdAccessCheckDone, this); | |
938 | } else | |
939 | storeIdStart(http, clientStoreIdDoneWrapper, this); | |
940 | } | |
941 | ||
942 | static int | |
943 | clientHierarchical(ClientHttpRequest * http) | |
944 | { | |
945 | HttpRequest *request = http->request; | |
946 | HttpRequestMethod method = request->method; | |
947 | ||
948 | // intercepted requests MUST NOT (yet) be sent to peers unless verified | |
949 | if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy)) | |
950 | return 0; | |
951 | ||
952 | /* | |
953 | * IMS needs a private key, so we can use the hierarchy for IMS only if our | |
954 | * neighbors support private keys | |
955 | */ | |
956 | ||
957 | if (request->flags.ims && !neighbors_do_private_keys) | |
958 | return 0; | |
959 | ||
960 | /* | |
961 | * This is incorrect: authenticating requests can be sent via a hierarchy | |
962 | * (they can even be cached if the correct headers are set on the reply) | |
963 | */ | |
964 | if (request->flags.auth) | |
965 | return 0; | |
966 | ||
967 | if (method == Http::METHOD_TRACE) | |
968 | return 1; | |
969 | ||
970 | if (method != Http::METHOD_GET) | |
971 | return 0; | |
972 | ||
973 | if (request->flags.loopDetected) | |
974 | return 0; | |
975 | ||
976 | if (request->url.getScheme() == AnyP::PROTO_HTTP) | |
977 | return method.respMaybeCacheable(); | |
978 | ||
979 | if (request->url.getScheme() == AnyP::PROTO_GOPHER) | |
980 | return gopherCachable(request); | |
981 | ||
982 | if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT) | |
983 | return 0; | |
984 | ||
985 | return 1; | |
986 | } | |
987 | ||
988 | static void | |
989 | clientCheckPinning(ClientHttpRequest * http) | |
990 | { | |
991 | HttpRequest *request = http->request; | |
992 | HttpHeader *req_hdr = &request->header; | |
993 | ConnStateData *http_conn = http->getConn(); | |
994 | ||
995 | /* Internal requests such as those from ESI includes may be without | |
996 | * a client connection | |
997 | */ | |
998 | if (!http_conn) | |
999 | return; | |
1000 | ||
1001 | request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled; | |
1002 | if (!request->flags.connectionAuthDisabled) { | |
1003 | if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) { | |
1004 | if (http_conn->pinning.auth) { | |
1005 | request->flags.connectionAuth = true; | |
1006 | request->flags.auth = true; | |
1007 | } else { | |
1008 | request->flags.connectionProxyAuth = true; | |
1009 | } | |
1010 | // These should already be linked correctly. | |
1011 | assert(request->clientConnectionManager == http_conn); | |
1012 | } | |
1013 | } | |
1014 | ||
1015 | /* check if connection auth is used, and flag as candidate for pinning | |
1016 | * in such case. | |
1017 | * Note: we may need to set flags.connectionAuth even if the connection | |
1018 | * is already pinned if it was pinned earlier due to proxy auth | |
1019 | */ | |
1020 | if (!request->flags.connectionAuth) { | |
1021 | if (req_hdr->has(Http::HdrType::AUTHORIZATION) || req_hdr->has(Http::HdrType::PROXY_AUTHORIZATION)) { | |
1022 | HttpHeaderPos pos = HttpHeaderInitPos; | |
1023 | HttpHeaderEntry *e; | |
1024 | int may_pin = 0; | |
1025 | while ((e = req_hdr->getEntry(&pos))) { | |
1026 | if (e->id == Http::HdrType::AUTHORIZATION || e->id == Http::HdrType::PROXY_AUTHORIZATION) { | |
1027 | const char *value = e->value.rawBuf(); | |
1028 | if (strncasecmp(value, "NTLM ", 5) == 0 | |
1029 | || | |
1030 | strncasecmp(value, "Negotiate ", 10) == 0 | |
1031 | || | |
1032 | strncasecmp(value, "Kerberos ", 9) == 0) { | |
1033 | if (e->id == Http::HdrType::AUTHORIZATION) { | |
1034 | request->flags.connectionAuth = true; | |
1035 | may_pin = 1; | |
1036 | } else { | |
1037 | request->flags.connectionProxyAuth = true; | |
1038 | may_pin = 1; | |
1039 | } | |
1040 | } | |
1041 | } | |
1042 | } | |
1043 | if (may_pin && !request->pinnedConnection()) { | |
1044 | // These should already be linked correctly. Just need the ServerConnection to pinn. | |
1045 | assert(request->clientConnectionManager == http_conn); | |
1046 | } | |
1047 | } | |
1048 | } | |
1049 | } | |
1050 | ||
1051 | static void | |
1052 | clientInterpretRequestHeaders(ClientHttpRequest * http) | |
1053 | { | |
1054 | HttpRequest *request = http->request; | |
1055 | HttpHeader *req_hdr = &request->header; | |
1056 | bool no_cache = false; | |
1057 | ||
1058 | request->imslen = -1; | |
1059 | request->ims = req_hdr->getTime(Http::HdrType::IF_MODIFIED_SINCE); | |
1060 | ||
1061 | if (request->ims > 0) | |
1062 | request->flags.ims = true; | |
1063 | ||
1064 | if (!request->flags.ignoreCc) { | |
1065 | if (request->cache_control) { | |
1066 | if (request->cache_control->hasNoCache()) | |
1067 | no_cache=true; | |
1068 | ||
1069 | // RFC 2616: treat Pragma:no-cache as if it was Cache-Control:no-cache when Cache-Control is missing | |
1070 | } else if (req_hdr->has(Http::HdrType::PRAGMA)) | |
1071 | no_cache = req_hdr->hasListMember(Http::HdrType::PRAGMA,"no-cache",','); | |
1072 | } | |
1073 | ||
1074 | if (request->method == Http::METHOD_OTHER) { | |
1075 | no_cache=true; | |
1076 | } | |
1077 | ||
1078 | if (no_cache) { | |
1079 | #if USE_HTTP_VIOLATIONS | |
1080 | ||
1081 | if (Config.onoff.reload_into_ims) | |
1082 | request->flags.nocacheHack = true; | |
1083 | else if (refresh_nocache_hack) | |
1084 | request->flags.nocacheHack = true; | |
1085 | else | |
1086 | #endif | |
1087 | ||
1088 | request->flags.noCache = true; | |
1089 | } | |
1090 | ||
1091 | /* ignore range header in non-GETs or non-HEADs */ | |
1092 | if (request->method == Http::METHOD_GET || request->method == Http::METHOD_HEAD) { | |
1093 | // XXX: initialize if we got here without HttpRequest::parseHeader() | |
1094 | if (!request->range) | |
1095 | request->range = req_hdr->getRange(); | |
1096 | ||
1097 | if (request->range) { | |
1098 | request->flags.isRanged = true; | |
1099 | clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->data; | |
1100 | /* XXX: This is suboptimal. We should give the stream the range set, | |
1101 | * and thereby let the top of the stream set the offset when the | |
1102 | * size becomes known. As it is, we will end up requesting from 0 | |
1103 | * for evey -X range specification. | |
1104 | * RBC - this may be somewhat wrong. We should probably set the range | |
1105 | * iter up at this point. | |
1106 | */ | |
1107 | node->readBuffer.offset = request->range->lowestOffset(0); | |
1108 | http->range_iter.pos = request->range->begin(); | |
1109 | http->range_iter.end = request->range->end(); | |
1110 | http->range_iter.valid = true; | |
1111 | } | |
1112 | } | |
1113 | ||
1114 | /* Only HEAD and GET requests permit a Range or Request-Range header. | |
1115 | * If these headers appear on any other type of request, delete them now. | |
1116 | */ | |
1117 | else { | |
1118 | req_hdr->delById(Http::HdrType::RANGE); | |
1119 | req_hdr->delById(Http::HdrType::REQUEST_RANGE); | |
1120 | request->ignoreRange("neither HEAD nor GET"); | |
1121 | } | |
1122 | ||
1123 | if (req_hdr->has(Http::HdrType::AUTHORIZATION)) | |
1124 | request->flags.auth = true; | |
1125 | ||
1126 | clientCheckPinning(http); | |
1127 | ||
1128 | if (!request->url.userInfo().isEmpty()) | |
1129 | request->flags.auth = true; | |
1130 | ||
1131 | if (req_hdr->has(Http::HdrType::VIA)) { | |
1132 | String s = req_hdr->getList(Http::HdrType::VIA); | |
1133 | /* | |
1134 | * ThisCache cannot be a member of Via header, "1.1 ThisCache" can. | |
1135 | * Note ThisCache2 has a space prepended to the hostname so we don't | |
1136 | * accidentally match super-domains. | |
1137 | */ | |
1138 | ||
1139 | if (strListIsSubstr(&s, ThisCache2, ',')) { | |
1140 | debugObj(33, 1, "WARNING: Forwarding loop detected for:\n", | |
1141 | request, (ObjPackMethod) & httpRequestPack); | |
1142 | request->flags.loopDetected = true; | |
1143 | } | |
1144 | ||
1145 | #if USE_FORW_VIA_DB | |
1146 | fvdbCountVia(s.termedBuf()); | |
1147 | ||
1148 | #endif | |
1149 | ||
1150 | s.clean(); | |
1151 | } | |
1152 | ||
1153 | #if USE_FORW_VIA_DB | |
1154 | ||
1155 | if (req_hdr->has(Http::HdrType::X_FORWARDED_FOR)) { | |
1156 | String s = req_hdr->getList(Http::HdrType::X_FORWARDED_FOR); | |
1157 | fvdbCountForw(s.termedBuf()); | |
1158 | s.clean(); | |
1159 | } | |
1160 | ||
1161 | #endif | |
1162 | ||
1163 | request->flags.cachable = http->request->maybeCacheable(); | |
1164 | ||
1165 | if (clientHierarchical(http)) | |
1166 | request->flags.hierarchical = true; | |
1167 | ||
1168 | debugs(85, 5, "clientInterpretRequestHeaders: REQ_NOCACHE = " << | |
1169 | (request->flags.noCache ? "SET" : "NOT SET")); | |
1170 | debugs(85, 5, "clientInterpretRequestHeaders: REQ_CACHABLE = " << | |
1171 | (request->flags.cachable ? "SET" : "NOT SET")); | |
1172 | debugs(85, 5, "clientInterpretRequestHeaders: REQ_HIERARCHICAL = " << | |
1173 | (request->flags.hierarchical ? "SET" : "NOT SET")); | |
1174 | ||
1175 | } | |
1176 | ||
1177 | void | |
1178 | clientRedirectDoneWrapper(void *data, const Helper::Reply &result) | |
1179 | { | |
1180 | ClientRequestContext *calloutContext = (ClientRequestContext *)data; | |
1181 | ||
1182 | if (!calloutContext->httpStateIsValid()) | |
1183 | return; | |
1184 | ||
1185 | calloutContext->clientRedirectDone(result); | |
1186 | } | |
1187 | ||
1188 | void | |
1189 | clientStoreIdDoneWrapper(void *data, const Helper::Reply &result) | |
1190 | { | |
1191 | ClientRequestContext *calloutContext = (ClientRequestContext *)data; | |
1192 | ||
1193 | if (!calloutContext->httpStateIsValid()) | |
1194 | return; | |
1195 | ||
1196 | calloutContext->clientStoreIdDone(result); | |
1197 | } | |
1198 | ||
1199 | void | |
1200 | ClientRequestContext::clientRedirectDone(const Helper::Reply &reply) | |
1201 | { | |
1202 | HttpRequest *old_request = http->request; | |
1203 | debugs(85, 5, HERE << "'" << http->uri << "' result=" << reply); | |
1204 | assert(redirect_state == REDIRECT_PENDING); | |
1205 | redirect_state = REDIRECT_DONE; | |
1206 | ||
1207 | // Put helper response Notes into the transaction state record (ALE) eventually | |
1208 | // do it early to ensure that no matter what the outcome the notes are present. | |
1209 | if (http->al != NULL) | |
1210 | (void)SyncNotes(*http->al, *old_request); | |
1211 | ||
1212 | UpdateRequestNotes(http->getConn(), *old_request, reply.notes); | |
1213 | ||
1214 | switch (reply.result) { | |
1215 | case Helper::TimedOut: | |
1216 | if (Config.onUrlRewriteTimeout.action != toutActBypass) { | |
1217 | http->calloutsError(ERR_GATEWAY_FAILURE, ERR_DETAIL_REDIRECTOR_TIMEDOUT); | |
1218 | debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: Timedout"); | |
1219 | } | |
1220 | break; | |
1221 | ||
1222 | case Helper::Unknown: | |
1223 | case Helper::TT: | |
1224 | // Handler in redirect.cc should have already mapped Unknown | |
1225 | // IF it contained valid entry for the old URL-rewrite helper protocol | |
1226 | debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper returned invalid result code. Wrong helper? " << reply); | |
1227 | break; | |
1228 | ||
1229 | case Helper::BrokenHelper: | |
1230 | debugs(85, DBG_IMPORTANT, "ERROR: URL rewrite helper: " << reply); | |
1231 | break; | |
1232 | ||
1233 | case Helper::Error: | |
1234 | // no change to be done. | |
1235 | break; | |
1236 | ||
1237 | case Helper::Okay: { | |
1238 | // #1: redirect with a specific status code OK status=NNN url="..." | |
1239 | // #2: redirect with a default status code OK url="..." | |
1240 | // #3: re-write the URL OK rewrite-url="..." | |
1241 | ||
1242 | const char *statusNote = reply.notes.findFirst("status"); | |
1243 | const char *urlNote = reply.notes.findFirst("url"); | |
1244 | ||
1245 | if (urlNote != NULL) { | |
1246 | // HTTP protocol redirect to be done. | |
1247 | ||
1248 | // TODO: change default redirect status for appropriate requests | |
1249 | // Squid defaults to 302 status for now for better compatibility with old clients. | |
1250 | // HTTP/1.0 client should get 302 (Http::scFound) | |
1251 | // HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect) | |
1252 | // HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther) | |
1253 | Http::StatusCode status = Http::scFound; | |
1254 | if (statusNote != NULL) { | |
1255 | const char * result = statusNote; | |
1256 | status = static_cast<Http::StatusCode>(atoi(result)); | |
1257 | } | |
1258 | ||
1259 | if (status == Http::scMovedPermanently | |
1260 | || status == Http::scFound | |
1261 | || status == Http::scSeeOther | |
1262 | || status == Http::scPermanentRedirect | |
1263 | || status == Http::scTemporaryRedirect) { | |
1264 | http->redirect.status = status; | |
1265 | http->redirect.location = xstrdup(urlNote); | |
1266 | // TODO: validate the URL produced here is RFC 2616 compliant absolute URI | |
1267 | } else { | |
1268 | debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid " << status << " redirect Location: " << urlNote); | |
1269 | } | |
1270 | } else { | |
1271 | // URL-rewrite wanted. Ew. | |
1272 | urlNote = reply.notes.findFirst("rewrite-url"); | |
1273 | ||
1274 | // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write. | |
1275 | if (urlNote != NULL && strcmp(urlNote, http->uri)) { | |
1276 | // XXX: validate the URL properly *without* generating a whole new request object right here. | |
1277 | // XXX: the clone() should be done only AFTER we know the new URL is valid. | |
1278 | HttpRequest *new_request = old_request->clone(); | |
1279 | if (urlParse(old_request->method, const_cast<char*>(urlNote), new_request)) { | |
1280 | debugs(61, 2, "URL-rewriter diverts URL from " << old_request->effectiveRequestUri() << " to " << new_request->effectiveRequestUri()); | |
1281 | ||
1282 | // update the new request to flag the re-writing was done on it | |
1283 | new_request->flags.redirected = true; | |
1284 | ||
1285 | // unlink bodypipe from the old request. Not needed there any longer. | |
1286 | if (old_request->body_pipe != NULL) { | |
1287 | old_request->body_pipe = NULL; | |
1288 | debugs(61,2, HERE << "URL-rewriter diverts body_pipe " << new_request->body_pipe << | |
1289 | " from request " << old_request << " to " << new_request); | |
1290 | } | |
1291 | ||
1292 | // update the current working ClientHttpRequest fields | |
1293 | xfree(http->uri); | |
1294 | http->uri = SBufToCstring(new_request->effectiveRequestUri()); | |
1295 | HTTPMSGUNLOCK(old_request); | |
1296 | http->request = new_request; | |
1297 | HTTPMSGLOCK(http->request); | |
1298 | } else { | |
1299 | debugs(85, DBG_CRITICAL, "ERROR: URL-rewrite produces invalid request: " << | |
1300 | old_request->method << " " << urlNote << " " << old_request->http_ver); | |
1301 | delete new_request; | |
1302 | } | |
1303 | } | |
1304 | } | |
1305 | } | |
1306 | break; | |
1307 | } | |
1308 | ||
1309 | /* FIXME PIPELINE: This is innacurate during pipelining */ | |
1310 | ||
1311 | if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection)) | |
1312 | fd_note(http->getConn()->clientConnection->fd, http->uri); | |
1313 | ||
1314 | assert(http->uri); | |
1315 | ||
1316 | http->doCallouts(); | |
1317 | } | |
1318 | ||
1319 | /** | |
1320 | * This method handles the different replies from StoreID helper. | |
1321 | */ | |
1322 | void | |
1323 | ClientRequestContext::clientStoreIdDone(const Helper::Reply &reply) | |
1324 | { | |
1325 | HttpRequest *old_request = http->request; | |
1326 | debugs(85, 5, "'" << http->uri << "' result=" << reply); | |
1327 | assert(store_id_state == REDIRECT_PENDING); | |
1328 | store_id_state = REDIRECT_DONE; | |
1329 | ||
1330 | // Put helper response Notes into the transaction state record (ALE) eventually | |
1331 | // do it early to ensure that no matter what the outcome the notes are present. | |
1332 | if (http->al != NULL) | |
1333 | (void)SyncNotes(*http->al, *old_request); | |
1334 | ||
1335 | UpdateRequestNotes(http->getConn(), *old_request, reply.notes); | |
1336 | ||
1337 | switch (reply.result) { | |
1338 | case Helper::Unknown: | |
1339 | case Helper::TT: | |
1340 | // Handler in redirect.cc should have already mapped Unknown | |
1341 | // IF it contained valid entry for the old helper protocol | |
1342 | debugs(85, DBG_IMPORTANT, "ERROR: storeID helper returned invalid result code. Wrong helper? " << reply); | |
1343 | break; | |
1344 | ||
1345 | case Helper::TimedOut: | |
1346 | // Timeouts for storeID are not implemented | |
1347 | case Helper::BrokenHelper: | |
1348 | debugs(85, DBG_IMPORTANT, "ERROR: storeID helper: " << reply); | |
1349 | break; | |
1350 | ||
1351 | case Helper::Error: | |
1352 | // no change to be done. | |
1353 | break; | |
1354 | ||
1355 | case Helper::Okay: { | |
1356 | const char *urlNote = reply.notes.findFirst("store-id"); | |
1357 | ||
1358 | // prevent broken helpers causing too much damage. If old URL == new URL skip the re-write. | |
1359 | if (urlNote != NULL && strcmp(urlNote, http->uri) ) { | |
1360 | // Debug section required for some very specific cases. | |
1361 | debugs(85, 9, "Setting storeID with: " << urlNote ); | |
1362 | http->request->store_id = urlNote; | |
1363 | http->store_id = urlNote; | |
1364 | } | |
1365 | } | |
1366 | break; | |
1367 | } | |
1368 | ||
1369 | http->doCallouts(); | |
1370 | } | |
1371 | ||
1372 | /** Test cache allow/deny configuration | |
1373 | * Sets flags.cachable=1 if caching is not denied. | |
1374 | */ | |
1375 | void | |
1376 | ClientRequestContext::checkNoCache() | |
1377 | { | |
1378 | if (Config.accessList.noCache) { | |
1379 | acl_checklist = clientAclChecklistCreate(Config.accessList.noCache, http); | |
1380 | acl_checklist->nonBlockingCheck(checkNoCacheDoneWrapper, this); | |
1381 | } else { | |
1382 | /* unless otherwise specified, we try to cache. */ | |
1383 | checkNoCacheDone(ACCESS_ALLOWED); | |
1384 | } | |
1385 | } | |
1386 | ||
1387 | static void | |
1388 | checkNoCacheDoneWrapper(allow_t answer, void *data) | |
1389 | { | |
1390 | ClientRequestContext *calloutContext = (ClientRequestContext *) data; | |
1391 | ||
1392 | if (!calloutContext->httpStateIsValid()) | |
1393 | return; | |
1394 | ||
1395 | calloutContext->checkNoCacheDone(answer); | |
1396 | } | |
1397 | ||
1398 | void | |
1399 | ClientRequestContext::checkNoCacheDone(const allow_t &answer) | |
1400 | { | |
1401 | acl_checklist = NULL; | |
1402 | 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 | if (http->request->flags.forceTunnel) { | |
1419 | debugs(85, 5, "not needed; already decided to tunnel " << http->getConn()); | |
1420 | return false; | |
1421 | } | |
1422 | ||
1423 | // If SSL connection tunneling or bumping decision has been made, obey it. | |
1424 | const Ssl::BumpMode bumpMode = http->getConn()->sslBumpMode; | |
1425 | if (bumpMode != Ssl::bumpEnd) { | |
1426 | debugs(85, 5, HERE << "SslBump already decided (" << bumpMode << | |
1427 | "), " << "ignoring ssl_bump for " << http->getConn()); | |
1428 | if (!http->getConn()->serverBump()) | |
1429 | http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed and not already bumped | |
1430 | http->al->ssl.bumpMode = bumpMode; // inherited from bumped connection | |
1431 | return false; | |
1432 | } | |
1433 | ||
1434 | // If we have not decided yet, decide whether to bump now. | |
1435 | ||
1436 | // Bumping here can only start with a CONNECT request on a bumping port | |
1437 | // (bumping of intercepted SSL conns is decided before we get 1st request). | |
1438 | // We also do not bump redirected CONNECT requests. | |
1439 | if (http->request->method != Http::METHOD_CONNECT || http->redirect.status || | |
1440 | !Config.accessList.ssl_bump || | |
1441 | !http->getConn()->port->flags.tunnelSslBumping) { | |
1442 | http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log - | |
1443 | debugs(85, 5, HERE << "cannot SslBump this request"); | |
1444 | return false; | |
1445 | } | |
1446 | ||
1447 | // Do not bump during authentication: clients would not proxy-authenticate | |
1448 | // if we delay a 407 response and respond with 200 OK to CONNECT. | |
1449 | if (error && error->httpStatus == Http::scProxyAuthenticationRequired) { | |
1450 | http->al->ssl.bumpMode = Ssl::bumpEnd; // SslBump does not apply; log - | |
1451 | debugs(85, 5, HERE << "no SslBump during proxy authentication"); | |
1452 | return false; | |
1453 | } | |
1454 | ||
1455 | debugs(85, 5, HERE << "SslBump possible, checking ACL"); | |
1456 | ||
1457 | ACLFilledChecklist *aclChecklist = clientAclChecklistCreate(Config.accessList.ssl_bump, http); | |
1458 | aclChecklist->nonBlockingCheck(sslBumpAccessCheckDoneWrapper, this); | |
1459 | return true; | |
1460 | } | |
1461 | ||
1462 | /** | |
1463 | * A wrapper function to use the ClientRequestContext::sslBumpAccessCheckDone method | |
1464 | * as ACLFilledChecklist callback | |
1465 | */ | |
1466 | static void | |
1467 | sslBumpAccessCheckDoneWrapper(allow_t answer, void *data) | |
1468 | { | |
1469 | ClientRequestContext *calloutContext = static_cast<ClientRequestContext *>(data); | |
1470 | ||
1471 | if (!calloutContext->httpStateIsValid()) | |
1472 | return; | |
1473 | calloutContext->sslBumpAccessCheckDone(answer); | |
1474 | } | |
1475 | ||
1476 | void | |
1477 | ClientRequestContext::sslBumpAccessCheckDone(const allow_t &answer) | |
1478 | { | |
1479 | if (!httpStateIsValid()) | |
1480 | return; | |
1481 | ||
1482 | const Ssl::BumpMode bumpMode = answer == ACCESS_ALLOWED ? | |
1483 | static_cast<Ssl::BumpMode>(answer.kind) : Ssl::bumpNone; | |
1484 | http->sslBumpNeed(bumpMode); // for processRequest() to bump if needed | |
1485 | http->al->ssl.bumpMode = bumpMode; // for logging | |
1486 | ||
1487 | http->doCallouts(); | |
1488 | } | |
1489 | #endif | |
1490 | ||
1491 | /* | |
1492 | * Identify requests that do not go through the store and client side stream | |
1493 | * and forward them to the appropriate location. All other requests, request | |
1494 | * them. | |
1495 | */ | |
1496 | void | |
1497 | ClientHttpRequest::processRequest() | |
1498 | { | |
1499 | debugs(85, 4, request->method << ' ' << uri); | |
1500 | ||
1501 | const bool untouchedConnect = request->method == Http::METHOD_CONNECT && !redirect.status; | |
1502 | ||
1503 | #if USE_OPENSSL | |
1504 | if (untouchedConnect && sslBumpNeeded()) { | |
1505 | assert(!request->flags.forceTunnel); | |
1506 | sslBumpStart(); | |
1507 | return; | |
1508 | } | |
1509 | #endif | |
1510 | ||
1511 | if (untouchedConnect || request->flags.forceTunnel) { | |
1512 | getConn()->stopReading(); // tunnels read for themselves | |
1513 | tunnelStart(this); | |
1514 | return; | |
1515 | } | |
1516 | ||
1517 | httpStart(); | |
1518 | } | |
1519 | ||
1520 | void | |
1521 | ClientHttpRequest::httpStart() | |
1522 | { | |
1523 | PROF_start(httpStart); | |
1524 | logType = LOG_TAG_NONE; | |
1525 | debugs(85, 4, logType.c_str() << " for '" << uri << "'"); | |
1526 | ||
1527 | /* no one should have touched this */ | |
1528 | assert(out.offset == 0); | |
1529 | /* Use the Stream Luke */ | |
1530 | clientStreamNode *node = (clientStreamNode *)client_stream.tail->data; | |
1531 | clientStreamRead(node, this, node->readBuffer); | |
1532 | PROF_stop(httpStart); | |
1533 | } | |
1534 | ||
1535 | #if USE_OPENSSL | |
1536 | ||
1537 | void | |
1538 | ClientHttpRequest::sslBumpNeed(Ssl::BumpMode mode) | |
1539 | { | |
1540 | debugs(83, 3, HERE << "sslBump required: "<< Ssl::bumpMode(mode)); | |
1541 | sslBumpNeed_ = mode; | |
1542 | } | |
1543 | ||
1544 | // called when comm_write has completed | |
1545 | static void | |
1546 | SslBumpEstablish(const Comm::ConnectionPointer &, char *, size_t, Comm::Flag errflag, int, void *data) | |
1547 | { | |
1548 | ClientHttpRequest *r = static_cast<ClientHttpRequest*>(data); | |
1549 | debugs(85, 5, HERE << "responded to CONNECT: " << r << " ? " << errflag); | |
1550 | ||
1551 | assert(r && cbdataReferenceValid(r)); | |
1552 | r->sslBumpEstablish(errflag); | |
1553 | } | |
1554 | ||
1555 | void | |
1556 | ClientHttpRequest::sslBumpEstablish(Comm::Flag errflag) | |
1557 | { | |
1558 | // Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up | |
1559 | if (errflag == Comm::ERR_CLOSING) | |
1560 | return; | |
1561 | ||
1562 | if (errflag) { | |
1563 | debugs(85, 3, HERE << "CONNECT response failure in SslBump: " << errflag); | |
1564 | getConn()->clientConnection->close(); | |
1565 | return; | |
1566 | } | |
1567 | ||
1568 | // We lack HttpReply which logRequest() uses to log the status code. | |
1569 | // TODO: Use HttpReply instead of the "200 Connection established" string. | |
1570 | al->http.code = 200; | |
1571 | ||
1572 | #if USE_AUTH | |
1573 | // Preserve authentication info for the ssl-bumped request | |
1574 | if (request->auth_user_request != NULL) | |
1575 | getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT"); | |
1576 | #endif | |
1577 | ||
1578 | assert(sslBumpNeeded()); | |
1579 | getConn()->switchToHttps(request, sslBumpNeed_); | |
1580 | } | |
1581 | ||
1582 | void | |
1583 | ClientHttpRequest::sslBumpStart() | |
1584 | { | |
1585 | debugs(85, 5, HERE << "Confirming " << Ssl::bumpMode(sslBumpNeed_) << | |
1586 | "-bumped CONNECT tunnel on FD " << getConn()->clientConnection); | |
1587 | getConn()->sslBumpMode = sslBumpNeed_; | |
1588 | ||
1589 | AsyncCall::Pointer bumpCall = commCbCall(85, 5, "ClientSocketContext::sslBumpEstablish", | |
1590 | CommIoCbPtrFun(&SslBumpEstablish, this)); | |
1591 | ||
1592 | if (request->flags.interceptTproxy || request->flags.intercepted) { | |
1593 | CommIoCbParams ¶ms = GetCommParams<CommIoCbParams>(bumpCall); | |
1594 | params.flag = Comm::OK; | |
1595 | params.conn = getConn()->clientConnection; | |
1596 | ScheduleCallHere(bumpCall); | |
1597 | return; | |
1598 | } | |
1599 | ||
1600 | // send an HTTP 200 response to kick client SSL negotiation | |
1601 | // TODO: Unify with tunnel.cc and add a Server(?) header | |
1602 | static const char *const conn_established = "HTTP/1.1 200 Connection established\r\n\r\n"; | |
1603 | Comm::Write(getConn()->clientConnection, conn_established, strlen(conn_established), bumpCall, NULL); | |
1604 | } | |
1605 | ||
1606 | #endif | |
1607 | ||
1608 | bool | |
1609 | ClientHttpRequest::gotEnough() const | |
1610 | { | |
1611 | /** TODO: should be querying the stream. */ | |
1612 | int64_t contentLength = | |
1613 | memObject()->getReply()->bodySize(request->method); | |
1614 | assert(contentLength >= 0); | |
1615 | ||
1616 | if (out.offset < contentLength) | |
1617 | return false; | |
1618 | ||
1619 | return true; | |
1620 | } | |
1621 | ||
1622 | void | |
1623 | ClientHttpRequest::storeEntry(StoreEntry *newEntry) | |
1624 | { | |
1625 | entry_ = newEntry; | |
1626 | } | |
1627 | ||
1628 | void | |
1629 | ClientHttpRequest::loggingEntry(StoreEntry *newEntry) | |
1630 | { | |
1631 | if (loggingEntry_) | |
1632 | loggingEntry_->unlock("ClientHttpRequest::loggingEntry"); | |
1633 | ||
1634 | loggingEntry_ = newEntry; | |
1635 | ||
1636 | if (loggingEntry_) | |
1637 | loggingEntry_->lock("ClientHttpRequest::loggingEntry"); | |
1638 | } | |
1639 | ||
1640 | /* | |
1641 | * doCallouts() - This function controls the order of "callout" | |
1642 | * executions, including non-blocking access control checks, the | |
1643 | * redirector, and ICAP. Previously, these callouts were chained | |
1644 | * together such that "clientAccessCheckDone()" would call | |
1645 | * "clientRedirectStart()" and so on. | |
1646 | * | |
1647 | * The ClientRequestContext (aka calloutContext) class holds certain | |
1648 | * state data for the callout/callback operations. Previously | |
1649 | * ClientHttpRequest would sort of hand off control to ClientRequestContext | |
1650 | * for a short time. ClientRequestContext would then delete itself | |
1651 | * and pass control back to ClientHttpRequest when all callouts | |
1652 | * were finished. | |
1653 | * | |
1654 | * This caused some problems for ICAP because we want to make the | |
1655 | * ICAP callout after checking ACLs, but before checking the no_cache | |
1656 | * list. We can't stuff the ICAP state into the ClientRequestContext | |
1657 | * class because we still need the ICAP state after ClientRequestContext | |
1658 | * goes away. | |
1659 | * | |
1660 | * Note that ClientRequestContext is created before the first call | |
1661 | * to doCallouts(). | |
1662 | * | |
1663 | * If one of the callouts notices that ClientHttpRequest is no | |
1664 | * longer valid, it should call cbdataReferenceDone() so that | |
1665 | * ClientHttpRequest's reference count goes to zero and it will get | |
1666 | * deleted. ClientHttpRequest will then delete ClientRequestContext. | |
1667 | * | |
1668 | * Note that we set the _done flags here before actually starting | |
1669 | * the callout. This is strictly for convenience. | |
1670 | */ | |
1671 | ||
1672 | tos_t aclMapTOS (acl_tos * head, ACLChecklist * ch); | |
1673 | nfmark_t aclMapNfmark (acl_nfmark * head, ACLChecklist * ch); | |
1674 | ||
1675 | void | |
1676 | ClientHttpRequest::doCallouts() | |
1677 | { | |
1678 | assert(calloutContext); | |
1679 | ||
1680 | /*Save the original request for logging purposes*/ | |
1681 | if (!calloutContext->http->al->request) { | |
1682 | calloutContext->http->al->request = request; | |
1683 | HTTPMSGLOCK(calloutContext->http->al->request); | |
1684 | ||
1685 | NotePairs ¬es = SyncNotes(*calloutContext->http->al, *calloutContext->http->request); | |
1686 | // Make the previously set client connection ID available as annotation. | |
1687 | if (ConnStateData *csd = calloutContext->http->getConn()) { | |
1688 | if (!csd->connectionTag().isEmpty()) | |
1689 | notes.add("clt_conn_tag", SBuf(csd->connectionTag()).c_str()); | |
1690 | } | |
1691 | } | |
1692 | ||
1693 | if (!calloutContext->error) { | |
1694 | // CVE-2009-0801: verify the Host: header is consistent with other known details. | |
1695 | if (!calloutContext->host_header_verify_done) { | |
1696 | debugs(83, 3, HERE << "Doing calloutContext->hostHeaderVerify()"); | |
1697 | calloutContext->host_header_verify_done = true; | |
1698 | calloutContext->hostHeaderVerify(); | |
1699 | return; | |
1700 | } | |
1701 | ||
1702 | if (!calloutContext->http_access_done) { | |
1703 | debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck()"); | |
1704 | calloutContext->http_access_done = true; | |
1705 | calloutContext->clientAccessCheck(); | |
1706 | return; | |
1707 | } | |
1708 | ||
1709 | #if USE_ADAPTATION | |
1710 | if (!calloutContext->adaptation_acl_check_done) { | |
1711 | calloutContext->adaptation_acl_check_done = true; | |
1712 | if (Adaptation::AccessCheck::Start( | |
1713 | Adaptation::methodReqmod, Adaptation::pointPreCache, | |
1714 | request, NULL, calloutContext->http->al, this)) | |
1715 | return; // will call callback | |
1716 | } | |
1717 | #endif | |
1718 | ||
1719 | if (!calloutContext->redirect_done) { | |
1720 | calloutContext->redirect_done = true; | |
1721 | ||
1722 | if (Config.Program.redirect) { | |
1723 | debugs(83, 3, HERE << "Doing calloutContext->clientRedirectStart()"); | |
1724 | calloutContext->redirect_state = REDIRECT_PENDING; | |
1725 | calloutContext->clientRedirectStart(); | |
1726 | return; | |
1727 | } | |
1728 | } | |
1729 | ||
1730 | if (!calloutContext->adapted_http_access_done) { | |
1731 | debugs(83, 3, HERE << "Doing calloutContext->clientAccessCheck2()"); | |
1732 | calloutContext->adapted_http_access_done = true; | |
1733 | calloutContext->clientAccessCheck2(); | |
1734 | return; | |
1735 | } | |
1736 | ||
1737 | if (!calloutContext->store_id_done) { | |
1738 | calloutContext->store_id_done = true; | |
1739 | ||
1740 | if (Config.Program.store_id) { | |
1741 | debugs(83, 3,"Doing calloutContext->clientStoreIdStart()"); | |
1742 | calloutContext->store_id_state = REDIRECT_PENDING; | |
1743 | calloutContext->clientStoreIdStart(); | |
1744 | return; | |
1745 | } | |
1746 | } | |
1747 | ||
1748 | if (!calloutContext->interpreted_req_hdrs) { | |
1749 | debugs(83, 3, HERE << "Doing clientInterpretRequestHeaders()"); | |
1750 | calloutContext->interpreted_req_hdrs = 1; | |
1751 | clientInterpretRequestHeaders(this); | |
1752 | } | |
1753 | ||
1754 | if (!calloutContext->no_cache_done) { | |
1755 | calloutContext->no_cache_done = true; | |
1756 | ||
1757 | if (Config.accessList.noCache && request->flags.cachable) { | |
1758 | debugs(83, 3, HERE << "Doing calloutContext->checkNoCache()"); | |
1759 | calloutContext->checkNoCache(); | |
1760 | return; | |
1761 | } | |
1762 | } | |
1763 | } // if !calloutContext->error | |
1764 | ||
1765 | if (!calloutContext->tosToClientDone) { | |
1766 | calloutContext->tosToClientDone = true; | |
1767 | if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) { | |
1768 | ACLFilledChecklist ch(NULL, request, NULL); | |
1769 | ch.src_addr = request->client_addr; | |
1770 | ch.my_addr = request->my_addr; | |
1771 | tos_t tos = aclMapTOS(Ip::Qos::TheConfig.tosToClient, &ch); | |
1772 | if (tos) | |
1773 | Ip::Qos::setSockTos(getConn()->clientConnection, tos); | |
1774 | } | |
1775 | } | |
1776 | ||
1777 | if (!calloutContext->nfmarkToClientDone) { | |
1778 | calloutContext->nfmarkToClientDone = true; | |
1779 | if (getConn() != NULL && Comm::IsConnOpen(getConn()->clientConnection)) { | |
1780 | ACLFilledChecklist ch(NULL, request, NULL); | |
1781 | ch.src_addr = request->client_addr; | |
1782 | ch.my_addr = request->my_addr; | |
1783 | nfmark_t mark = aclMapNfmark(Ip::Qos::TheConfig.nfmarkToClient, &ch); | |
1784 | if (mark) | |
1785 | Ip::Qos::setSockNfmark(getConn()->clientConnection, mark); | |
1786 | } | |
1787 | } | |
1788 | ||
1789 | #if USE_OPENSSL | |
1790 | // We need to check for SslBump even if the calloutContext->error is set | |
1791 | // because bumping may require delaying the error until after CONNECT. | |
1792 | if (!calloutContext->sslBumpCheckDone) { | |
1793 | calloutContext->sslBumpCheckDone = true; | |
1794 | if (calloutContext->sslBumpAccessCheck()) | |
1795 | return; | |
1796 | /* else no ssl bump required*/ | |
1797 | } | |
1798 | #endif | |
1799 | ||
1800 | if (calloutContext->error) { | |
1801 | // XXX: prformance regression. c_str() reallocates | |
1802 | SBuf storeUriBuf(request->storeId()); | |
1803 | const char *storeUri = storeUriBuf.c_str(); | |
1804 | StoreEntry *e = storeCreateEntry(storeUri, storeUri, request->flags, request->method); | |
1805 | #if USE_OPENSSL | |
1806 | if (sslBumpNeeded()) { | |
1807 | // We have to serve an error, so bump the client first. | |
1808 | sslBumpNeed(Ssl::bumpClientFirst); | |
1809 | // set final error but delay sending until we bump | |
1810 | Ssl::ServerBump *srvBump = new Ssl::ServerBump(request, e, Ssl::bumpClientFirst); | |
1811 | errorAppendEntry(e, calloutContext->error); | |
1812 | calloutContext->error = NULL; | |
1813 | getConn()->setServerBump(srvBump); | |
1814 | e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded"); | |
1815 | } else | |
1816 | #endif | |
1817 | { | |
1818 | // send the error to the client now | |
1819 | clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data; | |
1820 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
1821 | assert (repContext); | |
1822 | repContext->setReplyToStoreEntry(e, "immediate SslBump error"); | |
1823 | errorAppendEntry(e, calloutContext->error); | |
1824 | calloutContext->error = NULL; | |
1825 | if (calloutContext->readNextRequest && getConn()) | |
1826 | getConn()->flags.readMore = true; // resume any pipeline reads. | |
1827 | node = (clientStreamNode *)client_stream.tail->data; | |
1828 | clientStreamRead(node, this, node->readBuffer); | |
1829 | e->unlock("ClientHttpRequest::doCallouts-sslBumpNeeded"); | |
1830 | return; | |
1831 | } | |
1832 | } | |
1833 | ||
1834 | cbdataReferenceDone(calloutContext->http); | |
1835 | delete calloutContext; | |
1836 | calloutContext = NULL; | |
1837 | #if HEADERS_LOG | |
1838 | ||
1839 | headersLog(0, 1, request->method, request); | |
1840 | #endif | |
1841 | ||
1842 | debugs(83, 3, HERE << "calling processRequest()"); | |
1843 | processRequest(); | |
1844 | ||
1845 | #if ICAP_CLIENT | |
1846 | Adaptation::Icap::History::Pointer ih = request->icapHistory(); | |
1847 | if (ih != NULL) | |
1848 | ih->logType = logType; | |
1849 | #endif | |
1850 | } | |
1851 | ||
1852 | #if !_USE_INLINE_ | |
1853 | #include "client_side_request.cci" | |
1854 | #endif | |
1855 | ||
1856 | #if USE_ADAPTATION | |
1857 | /// Initiate an asynchronous adaptation transaction which will call us back. | |
1858 | void | |
1859 | ClientHttpRequest::startAdaptation(const Adaptation::ServiceGroupPointer &g) | |
1860 | { | |
1861 | debugs(85, 3, HERE << "adaptation needed for " << this); | |
1862 | assert(!virginHeadSource); | |
1863 | assert(!adaptedBodySource); | |
1864 | virginHeadSource = initiateAdaptation( | |
1865 | new Adaptation::Iterator(request, NULL, al, g)); | |
1866 | ||
1867 | // we could try to guess whether we can bypass this adaptation | |
1868 | // initiation failure, but it should not really happen | |
1869 | Must(initiated(virginHeadSource)); | |
1870 | } | |
1871 | ||
1872 | void | |
1873 | ClientHttpRequest::noteAdaptationAnswer(const Adaptation::Answer &answer) | |
1874 | { | |
1875 | assert(cbdataReferenceValid(this)); // indicates bug | |
1876 | clearAdaptation(virginHeadSource); | |
1877 | assert(!adaptedBodySource); | |
1878 | ||
1879 | switch (answer.kind) { | |
1880 | case Adaptation::Answer::akForward: | |
1881 | handleAdaptedHeader(const_cast<HttpMsg*>(answer.message.getRaw())); | |
1882 | break; | |
1883 | ||
1884 | case Adaptation::Answer::akBlock: | |
1885 | handleAdaptationBlock(answer); | |
1886 | break; | |
1887 | ||
1888 | case Adaptation::Answer::akError: | |
1889 | handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_ABORT, !answer.final); | |
1890 | break; | |
1891 | } | |
1892 | } | |
1893 | ||
1894 | void | |
1895 | ClientHttpRequest::handleAdaptedHeader(HttpMsg *msg) | |
1896 | { | |
1897 | assert(msg); | |
1898 | ||
1899 | if (HttpRequest *new_req = dynamic_cast<HttpRequest*>(msg)) { | |
1900 | /* | |
1901 | * Replace the old request with the new request. | |
1902 | */ | |
1903 | HTTPMSGUNLOCK(request); | |
1904 | request = new_req; | |
1905 | HTTPMSGLOCK(request); | |
1906 | ||
1907 | // update the new message to flag whether URL re-writing was done on it | |
1908 | if (request->effectiveRequestUri().cmp(uri) != 0) | |
1909 | request->flags.redirected = 1; | |
1910 | ||
1911 | /* | |
1912 | * Store the new URI for logging | |
1913 | */ | |
1914 | xfree(uri); | |
1915 | uri = SBufToCstring(request->effectiveRequestUri()); | |
1916 | setLogUri(this, urlCanonicalClean(request)); | |
1917 | assert(request->method.id()); | |
1918 | } else if (HttpReply *new_rep = dynamic_cast<HttpReply*>(msg)) { | |
1919 | debugs(85,3,HERE << "REQMOD reply is HTTP reply"); | |
1920 | ||
1921 | // subscribe to receive reply body | |
1922 | if (new_rep->body_pipe != NULL) { | |
1923 | adaptedBodySource = new_rep->body_pipe; | |
1924 | int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this); | |
1925 | assert(consumer_ok); | |
1926 | } | |
1927 | ||
1928 | clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data; | |
1929 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
1930 | assert(repContext); | |
1931 | repContext->createStoreEntry(request->method, request->flags); | |
1932 | ||
1933 | EBIT_CLR(storeEntry()->flags, ENTRY_FWD_HDR_WAIT); | |
1934 | request_satisfaction_mode = true; | |
1935 | request_satisfaction_offset = 0; | |
1936 | storeEntry()->replaceHttpReply(new_rep); | |
1937 | storeEntry()->timestampsSet(); | |
1938 | ||
1939 | if (!adaptedBodySource) // no body | |
1940 | storeEntry()->complete(); | |
1941 | clientGetMoreData(node, this); | |
1942 | } | |
1943 | ||
1944 | // we are done with getting headers (but may be receiving body) | |
1945 | clearAdaptation(virginHeadSource); | |
1946 | ||
1947 | if (!request_satisfaction_mode) | |
1948 | doCallouts(); | |
1949 | } | |
1950 | ||
1951 | void | |
1952 | ClientHttpRequest::handleAdaptationBlock(const Adaptation::Answer &answer) | |
1953 | { | |
1954 | request->detailError(ERR_ACCESS_DENIED, ERR_DETAIL_REQMOD_BLOCK); | |
1955 | AclMatchedName = answer.ruleId.termedBuf(); | |
1956 | assert(calloutContext); | |
1957 | calloutContext->clientAccessCheckDone(ACCESS_DENIED); | |
1958 | AclMatchedName = NULL; | |
1959 | } | |
1960 | ||
1961 | void | |
1962 | ClientHttpRequest::resumeBodyStorage() | |
1963 | { | |
1964 | if (!adaptedBodySource) | |
1965 | return; | |
1966 | ||
1967 | noteMoreBodyDataAvailable(adaptedBodySource); | |
1968 | } | |
1969 | ||
1970 | void | |
1971 | ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer) | |
1972 | { | |
1973 | assert(request_satisfaction_mode); | |
1974 | assert(adaptedBodySource != NULL); | |
1975 | ||
1976 | if (size_t contentSize = adaptedBodySource->buf().contentSize()) { | |
1977 | const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize)); | |
1978 | ||
1979 | if (spaceAvailable < contentSize ) { | |
1980 | // No or partial body data consuming | |
1981 | typedef NullaryMemFunT<ClientHttpRequest> Dialer; | |
1982 | AsyncCall::Pointer call = asyncCall(93, 5, "ClientHttpRequest::resumeBodyStorage", | |
1983 | Dialer(this, &ClientHttpRequest::resumeBodyStorage)); | |
1984 | storeEntry()->deferProducer(call); | |
1985 | } | |
1986 | ||
1987 | if (!spaceAvailable) | |
1988 | return; | |
1989 | ||
1990 | if (spaceAvailable < contentSize ) | |
1991 | contentSize = spaceAvailable; | |
1992 | ||
1993 | BodyPipeCheckout bpc(*adaptedBodySource); | |
1994 | const StoreIOBuffer ioBuf(&bpc.buf, request_satisfaction_offset, contentSize); | |
1995 | storeEntry()->write(ioBuf); | |
1996 | // assume StoreEntry::write() writes the entire ioBuf | |
1997 | request_satisfaction_offset += ioBuf.length; | |
1998 | bpc.buf.consume(contentSize); | |
1999 | bpc.checkIn(); | |
2000 | } | |
2001 | ||
2002 | if (adaptedBodySource->exhausted()) | |
2003 | endRequestSatisfaction(); | |
2004 | // else wait for more body data | |
2005 | } | |
2006 | ||
2007 | void | |
2008 | ClientHttpRequest::noteBodyProductionEnded(BodyPipe::Pointer) | |
2009 | { | |
2010 | assert(!virginHeadSource); | |
2011 | // should we end request satisfaction now? | |
2012 | if (adaptedBodySource != NULL && adaptedBodySource->exhausted()) | |
2013 | endRequestSatisfaction(); | |
2014 | } | |
2015 | ||
2016 | void | |
2017 | ClientHttpRequest::endRequestSatisfaction() | |
2018 | { | |
2019 | debugs(85,4, HERE << this << " ends request satisfaction"); | |
2020 | assert(request_satisfaction_mode); | |
2021 | stopConsumingFrom(adaptedBodySource); | |
2022 | ||
2023 | // TODO: anything else needed to end store entry formation correctly? | |
2024 | storeEntry()->complete(); | |
2025 | } | |
2026 | ||
2027 | void | |
2028 | ClientHttpRequest::noteBodyProducerAborted(BodyPipe::Pointer) | |
2029 | { | |
2030 | assert(!virginHeadSource); | |
2031 | stopConsumingFrom(adaptedBodySource); | |
2032 | ||
2033 | debugs(85,3, HERE << "REQMOD body production failed"); | |
2034 | if (request_satisfaction_mode) { // too late to recover or serve an error | |
2035 | request->detailError(ERR_ICAP_FAILURE, ERR_DETAIL_CLT_REQMOD_RESP_BODY); | |
2036 | const Comm::ConnectionPointer c = getConn()->clientConnection; | |
2037 | Must(Comm::IsConnOpen(c)); | |
2038 | c->close(); // drastic, but we may be writing a response already | |
2039 | } else { | |
2040 | handleAdaptationFailure(ERR_DETAIL_CLT_REQMOD_REQ_BODY); | |
2041 | } | |
2042 | } | |
2043 | ||
2044 | void | |
2045 | ClientHttpRequest::handleAdaptationFailure(int errDetail, bool bypassable) | |
2046 | { | |
2047 | debugs(85,3, HERE << "handleAdaptationFailure(" << bypassable << ")"); | |
2048 | ||
2049 | const bool usedStore = storeEntry() && !storeEntry()->isEmpty(); | |
2050 | const bool usedPipe = request->body_pipe != NULL && | |
2051 | request->body_pipe->consumedSize() > 0; | |
2052 | ||
2053 | if (bypassable && !usedStore && !usedPipe) { | |
2054 | debugs(85,3, HERE << "ICAP REQMOD callout failed, bypassing: " << calloutContext); | |
2055 | if (calloutContext) | |
2056 | doCallouts(); | |
2057 | return; | |
2058 | } | |
2059 | ||
2060 | debugs(85,3, HERE << "ICAP REQMOD callout failed, responding with error"); | |
2061 | ||
2062 | clientStreamNode *node = (clientStreamNode *)client_stream.tail->prev->data; | |
2063 | clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw()); | |
2064 | assert(repContext); | |
2065 | ||
2066 | calloutsError(ERR_ICAP_FAILURE, errDetail); | |
2067 | ||
2068 | if (calloutContext) | |
2069 | doCallouts(); | |
2070 | } | |
2071 | ||
2072 | #endif | |
2073 | ||
2074 | // XXX: modify and use with ClientRequestContext::clientAccessCheckDone too. | |
2075 | void | |
2076 | ClientHttpRequest::calloutsError(const err_type error, const int errDetail) | |
2077 | { | |
2078 | // The original author of the code also wanted to pass an errno to | |
2079 | // setReplyToError, but it seems unlikely that the errno reflects the | |
2080 | // true cause of the error at this point, so I did not pass it. | |
2081 | if (calloutContext) { | |
2082 | Ip::Address noAddr; | |
2083 | noAddr.setNoAddr(); | |
2084 | ConnStateData * c = getConn(); | |
2085 | calloutContext->error = clientBuildError(error, Http::scInternalServerError, | |
2086 | NULL, | |
2087 | c != NULL ? c->clientConnection->remote : noAddr, | |
2088 | request | |
2089 | ); | |
2090 | #if USE_AUTH | |
2091 | calloutContext->error->auth_user_request = | |
2092 | c != NULL && c->getAuth() != NULL ? c->getAuth() : request->auth_user_request; | |
2093 | #endif | |
2094 | calloutContext->error->detailError(errDetail); | |
2095 | calloutContext->readNextRequest = true; | |
2096 | if (c != NULL) | |
2097 | c->expectNoForwarding(); | |
2098 | } | |
2099 | //else if(calloutContext == NULL) is it possible? | |
2100 | } | |
2101 |