]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * DEBUG: section 11 Hypertext Transfer Protocol (HTTP) | |
3 | * AUTHOR: Harvest Derived | |
4 | * | |
5 | * SQUID Web Proxy Cache http://www.squid-cache.org/ | |
6 | * ---------------------------------------------------------- | |
7 | * | |
8 | * Squid is the result of efforts by numerous individuals from | |
9 | * the Internet community; see the CONTRIBUTORS file for full | |
10 | * details. Many organizations have provided support for Squid's | |
11 | * development; see the SPONSORS file for full details. Squid is | |
12 | * Copyrighted (C) 2001 by the Regents of the University of | |
13 | * California; see the COPYRIGHT file for full details. Squid | |
14 | * incorporates software developed and/or copyrighted by other | |
15 | * sources; see the CREDITS file for full details. | |
16 | * | |
17 | * This program is free software; you can redistribute it and/or modify | |
18 | * it under the terms of the GNU General Public License as published by | |
19 | * the Free Software Foundation; either version 2 of the License, or | |
20 | * (at your option) any later version. | |
21 | * | |
22 | * This program is distributed in the hope that it will be useful, | |
23 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
24 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
25 | * GNU General Public License for more details. | |
26 | * | |
27 | * You should have received a copy of the GNU General Public License | |
28 | * along with this program; if not, write to the Free Software | |
29 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. | |
30 | */ | |
31 | ||
32 | /* | |
33 | * Anonymizing patch by lutz@as-node.jena.thur.de | |
34 | * have a look into http-anon.c to get more informations. | |
35 | */ | |
36 | ||
37 | #include "squid.h" | |
38 | #include "acl/FilledChecklist.h" | |
39 | #include "base64.h" | |
40 | #include "base/AsyncJobCalls.h" | |
41 | #include "base/TextException.h" | |
42 | #include "CachePeer.h" | |
43 | #include "ChunkedCodingParser.h" | |
44 | #include "client_side.h" | |
45 | #include "comm/Connection.h" | |
46 | #include "comm/Write.h" | |
47 | #include "err_detail_type.h" | |
48 | #include "errorpage.h" | |
49 | #include "fd.h" | |
50 | #include "fde.h" | |
51 | #include "globals.h" | |
52 | #include "HttpControlMsg.h" | |
53 | #include "http.h" | |
54 | #include "HttpHdrCc.h" | |
55 | #include "HttpHdrContRange.h" | |
56 | #include "HttpHdrSc.h" | |
57 | #include "HttpHdrScTarget.h" | |
58 | #include "HttpHeaderTools.h" | |
59 | #include "HttpReply.h" | |
60 | #include "HttpRequest.h" | |
61 | #include "HttpStateFlags.h" | |
62 | #include "log/access_log.h" | |
63 | #include "MemBuf.h" | |
64 | #include "MemObject.h" | |
65 | #include "mime_header.h" | |
66 | #include "neighbors.h" | |
67 | #include "peer_proxy_negotiate_auth.h" | |
68 | #include "profiler/Profiler.h" | |
69 | #include "refresh.h" | |
70 | #include "RefreshPattern.h" | |
71 | #include "rfc1738.h" | |
72 | #include "SquidConfig.h" | |
73 | #include "SquidTime.h" | |
74 | #include "StatCounters.h" | |
75 | #include "Store.h" | |
76 | #include "StrList.h" | |
77 | #include "tools.h" | |
78 | #include "URL.h" | |
79 | ||
80 | #if USE_AUTH | |
81 | #include "auth/UserRequest.h" | |
82 | #endif | |
83 | #if USE_DELAY_POOLS | |
84 | #include "DelayPools.h" | |
85 | #endif | |
86 | ||
87 | #define SQUID_ENTER_THROWING_CODE() try { | |
88 | #define SQUID_EXIT_THROWING_CODE(status) \ | |
89 | status = true; \ | |
90 | } \ | |
91 | catch (const std::exception &e) { \ | |
92 | debugs (11, 1, "Exception error:" << e.what()); \ | |
93 | status = false; \ | |
94 | } | |
95 | ||
96 | CBDATA_CLASS_INIT(HttpStateData); | |
97 | ||
98 | static const char *const crlf = "\r\n"; | |
99 | ||
100 | static void httpMaybeRemovePublic(StoreEntry *, http_status); | |
101 | static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, | |
102 | HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &); | |
103 | //Declared in HttpHeaderTools.cc | |
104 | void httpHdrAdd(HttpHeader *heads, HttpRequest *request, const AccessLogEntryPointer &al, HeaderWithAclList &headers_add); | |
105 | ||
106 | HttpStateData::HttpStateData(FwdState *theFwdState) : AsyncJob("HttpStateData"), ServerStateData(theFwdState), | |
107 | lastChunk(0), header_bytes_read(0), reply_bytes_read(0), | |
108 | body_bytes_truncated(0), httpChunkDecoder(NULL) | |
109 | { | |
110 | debugs(11,5,HERE << "HttpStateData " << this << " created"); | |
111 | ignoreCacheControl = false; | |
112 | surrogateNoStore = false; | |
113 | serverConnection = fwd->serverConnection(); | |
114 | readBuf = new MemBuf; | |
115 | readBuf->init(16*1024, 256*1024); | |
116 | ||
117 | // reset peer response time stats for %<pt | |
118 | request->hier.peer_http_request_sent.tv_sec = 0; | |
119 | request->hier.peer_http_request_sent.tv_usec = 0; | |
120 | ||
121 | if (fwd->serverConnection() != NULL) | |
122 | _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */ | |
123 | ||
124 | if (_peer) { | |
125 | request->flags.proxying = 1; | |
126 | /* | |
127 | * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here. | |
128 | * We might end up getting the object from somewhere else if, | |
129 | * for example, the request to this neighbor fails. | |
130 | */ | |
131 | if (_peer->options.proxy_only) | |
132 | entry->releaseRequest(); | |
133 | ||
134 | #if USE_DELAY_POOLS | |
135 | entry->setNoDelay(_peer->options.no_delay); | |
136 | #endif | |
137 | } | |
138 | ||
139 | /* | |
140 | * register the handler to free HTTP state data when the FD closes | |
141 | */ | |
142 | typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer; | |
143 | closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed); | |
144 | comm_add_close_handler(serverConnection->fd, closeHandler); | |
145 | } | |
146 | ||
147 | HttpStateData::~HttpStateData() | |
148 | { | |
149 | /* | |
150 | * don't forget that ~ServerStateData() gets called automatically | |
151 | */ | |
152 | ||
153 | if (!readBuf->isNull()) | |
154 | readBuf->clean(); | |
155 | ||
156 | delete readBuf; | |
157 | ||
158 | if (httpChunkDecoder) | |
159 | delete httpChunkDecoder; | |
160 | ||
161 | cbdataReferenceDone(_peer); | |
162 | ||
163 | debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection); | |
164 | } | |
165 | ||
166 | const Comm::ConnectionPointer & | |
167 | HttpStateData::dataConnection() const | |
168 | { | |
169 | return serverConnection; | |
170 | } | |
171 | ||
172 | void | |
173 | HttpStateData::httpStateConnClosed(const CommCloseCbParams ¶ms) | |
174 | { | |
175 | debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data); | |
176 | mustStop("HttpStateData::httpStateConnClosed"); | |
177 | } | |
178 | ||
179 | void | |
180 | HttpStateData::httpTimeout(const CommTimeoutCbParams ¶ms) | |
181 | { | |
182 | debugs(11, 4, HERE << serverConnection << ": '" << entry->url() << "'" ); | |
183 | ||
184 | if (entry->store_status == STORE_PENDING) { | |
185 | fwd->fail(new ErrorState(ERR_READ_TIMEOUT, HTTP_GATEWAY_TIMEOUT, fwd->request)); | |
186 | } | |
187 | ||
188 | serverConnection->close(); | |
189 | } | |
190 | ||
191 | static void | |
192 | httpMaybeRemovePublic(StoreEntry * e, http_status status) | |
193 | { | |
194 | int remove = 0; | |
195 | int forbidden = 0; | |
196 | StoreEntry *pe; | |
197 | ||
198 | if (!EBIT_TEST(e->flags, KEY_PRIVATE)) | |
199 | return; | |
200 | ||
201 | switch (status) { | |
202 | ||
203 | case HTTP_OK: | |
204 | ||
205 | case HTTP_NON_AUTHORITATIVE_INFORMATION: | |
206 | ||
207 | case HTTP_MULTIPLE_CHOICES: | |
208 | ||
209 | case HTTP_MOVED_PERMANENTLY: | |
210 | ||
211 | case HTTP_MOVED_TEMPORARILY: | |
212 | ||
213 | case HTTP_GONE: | |
214 | ||
215 | case HTTP_NOT_FOUND: | |
216 | remove = 1; | |
217 | ||
218 | break; | |
219 | ||
220 | case HTTP_FORBIDDEN: | |
221 | ||
222 | case HTTP_METHOD_NOT_ALLOWED: | |
223 | forbidden = 1; | |
224 | ||
225 | break; | |
226 | ||
227 | #if WORK_IN_PROGRESS | |
228 | ||
229 | case HTTP_UNAUTHORIZED: | |
230 | forbidden = 1; | |
231 | ||
232 | break; | |
233 | ||
234 | #endif | |
235 | ||
236 | default: | |
237 | #if QUESTIONABLE | |
238 | /* | |
239 | * Any 2xx response should eject previously cached entities... | |
240 | */ | |
241 | ||
242 | if (status >= 200 && status < 300) | |
243 | remove = 1; | |
244 | ||
245 | #endif | |
246 | ||
247 | break; | |
248 | } | |
249 | ||
250 | if (!remove && !forbidden) | |
251 | return; | |
252 | ||
253 | assert(e->mem_obj); | |
254 | ||
255 | if (e->mem_obj->request) | |
256 | pe = storeGetPublicByRequest(e->mem_obj->request); | |
257 | else | |
258 | pe = storeGetPublic(e->mem_obj->url, e->mem_obj->method); | |
259 | ||
260 | if (pe != NULL) { | |
261 | assert(e != pe); | |
262 | #if USE_HTCP | |
263 | neighborsHtcpClear(e, NULL, e->mem_obj->request, e->mem_obj->method, HTCP_CLR_INVALIDATION); | |
264 | #endif | |
265 | pe->release(); | |
266 | } | |
267 | ||
268 | /** \par | |
269 | * Also remove any cached HEAD response in case the object has | |
270 | * changed. | |
271 | */ | |
272 | if (e->mem_obj->request) | |
273 | pe = storeGetPublicByRequestMethod(e->mem_obj->request, Http::METHOD_HEAD); | |
274 | else | |
275 | pe = storeGetPublic(e->mem_obj->url, Http::METHOD_HEAD); | |
276 | ||
277 | if (pe != NULL) { | |
278 | assert(e != pe); | |
279 | #if USE_HTCP | |
280 | neighborsHtcpClear(e, NULL, e->mem_obj->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION); | |
281 | #endif | |
282 | pe->release(); | |
283 | } | |
284 | } | |
285 | ||
286 | void | |
287 | HttpStateData::processSurrogateControl(HttpReply *reply) | |
288 | { | |
289 | if (request->flags.accelerated && reply->surrogate_control) { | |
290 | HttpHdrScTarget *sctusable = reply->surrogate_control->getMergedTarget(Config.Accel.surrogate_id); | |
291 | ||
292 | if (sctusable) { | |
293 | if (sctusable->noStore() || | |
294 | (Config.onoff.surrogate_is_remote | |
295 | && sctusable->noStoreRemote())) { | |
296 | surrogateNoStore = true; | |
297 | entry->makePrivate(); | |
298 | } | |
299 | ||
300 | /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an | |
301 | * accelerated request or not... | |
302 | * Still, this is an abstraction breach. - RC | |
303 | */ | |
304 | if (sctusable->hasMaxAge()) { | |
305 | if (sctusable->maxAge() < sctusable->maxStale()) | |
306 | reply->expires = reply->date + sctusable->maxAge(); | |
307 | else | |
308 | reply->expires = reply->date + sctusable->maxStale(); | |
309 | ||
310 | /* And update the timestamps */ | |
311 | entry->timestampsSet(); | |
312 | } | |
313 | ||
314 | /* We ignore cache-control directives as per the Surrogate specification */ | |
315 | ignoreCacheControl = true; | |
316 | ||
317 | delete sctusable; | |
318 | } | |
319 | } | |
320 | } | |
321 | ||
322 | int | |
323 | HttpStateData::cacheableReply() | |
324 | { | |
325 | HttpReply const *rep = finalReply(); | |
326 | HttpHeader const *hdr = &rep->header; | |
327 | const char *v; | |
328 | #if USE_HTTP_VIOLATIONS | |
329 | ||
330 | const RefreshPattern *R = NULL; | |
331 | ||
332 | /* This strange looking define first looks up the refresh pattern | |
333 | * and then checks if the specified flag is set. The main purpose | |
334 | * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS | |
335 | * condition | |
336 | */ | |
337 | #define REFRESH_OVERRIDE(flag) \ | |
338 | ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \ | |
339 | (R && R->flags.flag)) | |
340 | #else | |
341 | #define REFRESH_OVERRIDE(flag) 0 | |
342 | #endif | |
343 | ||
344 | // Check for Surrogate/1.0 protocol conditions | |
345 | // NP: reverse-proxy traffic our parent server has instructed us never to cache | |
346 | if (surrogateNoStore) { | |
347 | debugs(22, 3, HERE << "NO because Surrogate-Control:no-store"); | |
348 | return 0; | |
349 | } | |
350 | ||
351 | // RFC 2616: HTTP/1.1 Cache-Control conditions | |
352 | if (!ignoreCacheControl) { | |
353 | // XXX: check to see if the request headers alone were enough to prevent caching earlier | |
354 | // (ie no-store request header) no need to check those all again here if so. | |
355 | // for now we are not reliably doing that so we waste CPU re-checking request CC | |
356 | ||
357 | // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store | |
358 | if (request && request->cache_control && request->cache_control->noStore() && | |
359 | !REFRESH_OVERRIDE(ignore_no_store)) { | |
360 | debugs(22, 3, HERE << "NO because client request Cache-Control:no-store"); | |
361 | return 0; | |
362 | } | |
363 | ||
364 | // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted. | |
365 | // NP: request CC:private is undefined. We ignore. | |
366 | // NP: other request CC flags are limiters on HIT/MISS. We don't care about here. | |
367 | ||
368 | // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store | |
369 | if (rep->cache_control && rep->cache_control->noStore() && | |
370 | !REFRESH_OVERRIDE(ignore_no_store)) { | |
371 | debugs(22, 3, HERE << "NO because server reply Cache-Control:no-store"); | |
372 | return 0; | |
373 | } | |
374 | ||
375 | // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid. | |
376 | // TODO: add a shared/private cache configuration possibility. | |
377 | if (rep->cache_control && | |
378 | rep->cache_control->Private() && | |
379 | !REFRESH_OVERRIDE(ignore_private)) { | |
380 | debugs(22, 3, HERE << "NO because server reply Cache-Control:private"); | |
381 | return 0; | |
382 | } | |
383 | // NP: being conservative; CC:private overrides CC:public when both are present in a response. | |
384 | ||
385 | } | |
386 | // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present | |
387 | // allow HTTP violations to IGNORE those controls (ie re-block caching Auth) | |
388 | if (request && (request->flags.auth || request->flags.authSent) && !REFRESH_OVERRIDE(ignore_auth)) { | |
389 | if (!rep->cache_control) { | |
390 | debugs(22, 3, HERE << "NO because Authenticated and server reply missing Cache-Control"); | |
391 | return 0; | |
392 | } | |
393 | ||
394 | if (ignoreCacheControl) { | |
395 | debugs(22, 3, HERE << "NO because Authenticated and ignoring Cache-Control"); | |
396 | return 0; | |
397 | } | |
398 | ||
399 | bool mayStore = false; | |
400 | // HTTPbis pt6 section 3.2: a response CC:public is present | |
401 | if (rep->cache_control->Public()) { | |
402 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public"); | |
403 | mayStore = true; | |
404 | ||
405 | // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present | |
406 | } else if (rep->cache_control->mustRevalidate() && !REFRESH_OVERRIDE(ignore_must_revalidate)) { | |
407 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public"); | |
408 | mayStore = true; | |
409 | ||
410 | #if USE_HTTP_VIOLATIONS | |
411 | // NP: given the must-revalidate exception we should also be able to exempt no-cache. | |
412 | // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by | |
413 | // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache | |
414 | // as equivalent to must-revalidate in the reply. | |
415 | } else if (rep->cache_control->noCache() && !REFRESH_OVERRIDE(ignore_must_revalidate)) { | |
416 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)"); | |
417 | mayStore = true; | |
418 | #endif | |
419 | ||
420 | // HTTPbis pt6 section 3.2: a response CC:s-maxage is present | |
421 | } else if (rep->cache_control->sMaxAge()) { | |
422 | debugs(22, 3, HERE << " Authenticated but server reply Cache-Control:s-maxage"); | |
423 | mayStore = true; | |
424 | } | |
425 | ||
426 | if (!mayStore) { | |
427 | debugs(22, 3, HERE << "NO because Authenticated transaction"); | |
428 | return 0; | |
429 | } | |
430 | ||
431 | // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so. | |
432 | // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here. | |
433 | } | |
434 | ||
435 | /* HACK: The "multipart/x-mixed-replace" content type is used for | |
436 | * continuous push replies. These are generally dynamic and | |
437 | * probably should not be cachable | |
438 | */ | |
439 | if ((v = hdr->getStr(HDR_CONTENT_TYPE))) | |
440 | if (!strncasecmp(v, "multipart/x-mixed-replace", 25)) { | |
441 | debugs(22, 3, HERE << "NO because Content-Type:multipart/x-mixed-replace"); | |
442 | return 0; | |
443 | } | |
444 | ||
445 | switch (rep->sline.status) { | |
446 | /* Responses that are cacheable */ | |
447 | ||
448 | case HTTP_OK: | |
449 | ||
450 | case HTTP_NON_AUTHORITATIVE_INFORMATION: | |
451 | ||
452 | case HTTP_MULTIPLE_CHOICES: | |
453 | ||
454 | case HTTP_MOVED_PERMANENTLY: | |
455 | case HTTP_PERMANENT_REDIRECT: | |
456 | ||
457 | case HTTP_GONE: | |
458 | /* | |
459 | * Don't cache objects that need to be refreshed on next request, | |
460 | * unless we know how to refresh it. | |
461 | */ | |
462 | ||
463 | if (!refreshIsCachable(entry) && !REFRESH_OVERRIDE(store_stale)) { | |
464 | debugs(22, 3, "NO because refreshIsCachable() returned non-cacheable.."); | |
465 | return 0; | |
466 | } else { | |
467 | debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status); | |
468 | return 1; | |
469 | } | |
470 | /* NOTREACHED */ | |
471 | break; | |
472 | ||
473 | /* Responses that only are cacheable if the server says so */ | |
474 | ||
475 | case HTTP_MOVED_TEMPORARILY: | |
476 | case HTTP_TEMPORARY_REDIRECT: | |
477 | if (rep->date <= 0) { | |
478 | debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status << " and Date missing/invalid"); | |
479 | return 0; | |
480 | } | |
481 | if (rep->expires > rep->date) { | |
482 | debugs(22, 3, HERE << "YES because HTTP status " << rep->sline.status << " and Expires > Date"); | |
483 | return 1; | |
484 | } else { | |
485 | debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status << " and Expires <= Date"); | |
486 | return 0; | |
487 | } | |
488 | /* NOTREACHED */ | |
489 | break; | |
490 | ||
491 | /* Errors can be negatively cached */ | |
492 | ||
493 | case HTTP_NO_CONTENT: | |
494 | ||
495 | case HTTP_USE_PROXY: | |
496 | ||
497 | case HTTP_BAD_REQUEST: | |
498 | ||
499 | case HTTP_FORBIDDEN: | |
500 | ||
501 | case HTTP_NOT_FOUND: | |
502 | ||
503 | case HTTP_METHOD_NOT_ALLOWED: | |
504 | ||
505 | case HTTP_REQUEST_URI_TOO_LARGE: | |
506 | ||
507 | case HTTP_INTERNAL_SERVER_ERROR: | |
508 | ||
509 | case HTTP_NOT_IMPLEMENTED: | |
510 | ||
511 | case HTTP_BAD_GATEWAY: | |
512 | ||
513 | case HTTP_SERVICE_UNAVAILABLE: | |
514 | ||
515 | case HTTP_GATEWAY_TIMEOUT: | |
516 | debugs(22, 3, HERE << "MAYBE because HTTP status " << rep->sline.status); | |
517 | return -1; | |
518 | ||
519 | /* NOTREACHED */ | |
520 | break; | |
521 | ||
522 | /* Some responses can never be cached */ | |
523 | ||
524 | case HTTP_PARTIAL_CONTENT: /* Not yet supported */ | |
525 | ||
526 | case HTTP_SEE_OTHER: | |
527 | ||
528 | case HTTP_NOT_MODIFIED: | |
529 | ||
530 | case HTTP_UNAUTHORIZED: | |
531 | ||
532 | case HTTP_PROXY_AUTHENTICATION_REQUIRED: | |
533 | ||
534 | case HTTP_INVALID_HEADER: /* Squid header parsing error */ | |
535 | ||
536 | case HTTP_HEADER_TOO_LARGE: | |
537 | ||
538 | case HTTP_PAYMENT_REQUIRED: | |
539 | case HTTP_NOT_ACCEPTABLE: | |
540 | case HTTP_REQUEST_TIMEOUT: | |
541 | case HTTP_CONFLICT: | |
542 | case HTTP_LENGTH_REQUIRED: | |
543 | case HTTP_PRECONDITION_FAILED: | |
544 | case HTTP_REQUEST_ENTITY_TOO_LARGE: | |
545 | case HTTP_UNSUPPORTED_MEDIA_TYPE: | |
546 | case HTTP_UNPROCESSABLE_ENTITY: | |
547 | case HTTP_LOCKED: | |
548 | case HTTP_FAILED_DEPENDENCY: | |
549 | case HTTP_INSUFFICIENT_STORAGE: | |
550 | case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: | |
551 | case HTTP_EXPECTATION_FAILED: | |
552 | ||
553 | debugs(22, 3, HERE << "NO because HTTP status " << rep->sline.status); | |
554 | return 0; | |
555 | ||
556 | default: | |
557 | /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */ | |
558 | debugs (11, 3, HERE << "NO because unknown HTTP status code " << rep->sline.status); | |
559 | return 0; | |
560 | ||
561 | /* NOTREACHED */ | |
562 | break; | |
563 | } | |
564 | ||
565 | /* NOTREACHED */ | |
566 | } | |
567 | ||
568 | /* | |
569 | * For Vary, store the relevant request headers as | |
570 | * virtual headers in the reply | |
571 | * Returns false if the variance cannot be stored | |
572 | */ | |
573 | const char * | |
574 | httpMakeVaryMark(HttpRequest * request, HttpReply const * reply) | |
575 | { | |
576 | String vary, hdr; | |
577 | const char *pos = NULL; | |
578 | const char *item; | |
579 | const char *value; | |
580 | int ilen; | |
581 | static String vstr; | |
582 | ||
583 | vstr.clean(); | |
584 | vary = reply->header.getList(HDR_VARY); | |
585 | ||
586 | while (strListGetItem(&vary, ',', &item, &ilen, &pos)) { | |
587 | char *name = (char *)xmalloc(ilen + 1); | |
588 | xstrncpy(name, item, ilen + 1); | |
589 | Tolower(name); | |
590 | ||
591 | if (strcmp(name, "*") == 0) { | |
592 | /* Can not handle "Vary: *" withtout ETag support */ | |
593 | safe_free(name); | |
594 | vstr.clean(); | |
595 | break; | |
596 | } | |
597 | ||
598 | strListAdd(&vstr, name, ','); | |
599 | hdr = request->header.getByName(name); | |
600 | safe_free(name); | |
601 | value = hdr.termedBuf(); | |
602 | ||
603 | if (value) { | |
604 | value = rfc1738_escape_part(value); | |
605 | vstr.append("=\"", 2); | |
606 | vstr.append(value); | |
607 | vstr.append("\"", 1); | |
608 | } | |
609 | ||
610 | hdr.clean(); | |
611 | } | |
612 | ||
613 | vary.clean(); | |
614 | #if X_ACCELERATOR_VARY | |
615 | ||
616 | pos = NULL; | |
617 | vary = reply->header.getList(HDR_X_ACCELERATOR_VARY); | |
618 | ||
619 | while (strListGetItem(&vary, ',', &item, &ilen, &pos)) { | |
620 | char *name = (char *)xmalloc(ilen + 1); | |
621 | xstrncpy(name, item, ilen + 1); | |
622 | Tolower(name); | |
623 | strListAdd(&vstr, name, ','); | |
624 | hdr = request->header.getByName(name); | |
625 | safe_free(name); | |
626 | value = hdr.termedBuf(); | |
627 | ||
628 | if (value) { | |
629 | value = rfc1738_escape_part(value); | |
630 | vstr.append("=\"", 2); | |
631 | vstr.append(value); | |
632 | vstr.append("\"", 1); | |
633 | } | |
634 | ||
635 | hdr.clean(); | |
636 | } | |
637 | ||
638 | vary.clean(); | |
639 | #endif | |
640 | ||
641 | debugs(11, 3, "httpMakeVaryMark: " << vstr); | |
642 | return vstr.termedBuf(); | |
643 | } | |
644 | ||
645 | void | |
646 | HttpStateData::keepaliveAccounting(HttpReply *reply) | |
647 | { | |
648 | if (flags.keepalive) | |
649 | if (_peer) | |
650 | ++ _peer->stats.n_keepalives_sent; | |
651 | ||
652 | if (reply->keep_alive) { | |
653 | if (_peer) | |
654 | ++ _peer->stats.n_keepalives_recv; | |
655 | ||
656 | if (Config.onoff.detect_broken_server_pconns | |
657 | && reply->bodySize(request->method) == -1 && !flags.chunked) { | |
658 | debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" ); | |
659 | // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" ); | |
660 | flags.keepalive_broken = true; | |
661 | } | |
662 | } | |
663 | } | |
664 | ||
665 | void | |
666 | HttpStateData::checkDateSkew(HttpReply *reply) | |
667 | { | |
668 | if (reply->date > -1 && !_peer) { | |
669 | int skew = abs((int)(reply->date - squid_curtime)); | |
670 | ||
671 | if (skew > 86400) | |
672 | debugs(11, 3, "" << request->GetHost() << "'s clock is skewed by " << skew << " seconds!"); | |
673 | } | |
674 | } | |
675 | ||
676 | /** | |
677 | * This creates the error page itself.. its likely | |
678 | * that the forward ported reply header max size patch | |
679 | * generates non http conformant error pages - in which | |
680 | * case the errors where should be 'BAD_GATEWAY' etc | |
681 | */ | |
682 | void | |
683 | HttpStateData::processReplyHeader() | |
684 | { | |
685 | /** Creates a blank header. If this routine is made incremental, this will not do */ | |
686 | ||
687 | /* NP: all exit points to this function MUST call ctx_exit(ctx) */ | |
688 | Ctx ctx = ctx_enter(entry->mem_obj->url); | |
689 | ||
690 | debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'"); | |
691 | ||
692 | assert(!flags.headers_parsed); | |
693 | ||
694 | if (!readBuf->hasContent()) { | |
695 | ctx_exit(ctx); | |
696 | return; | |
697 | } | |
698 | ||
699 | http_status error = HTTP_STATUS_NONE; | |
700 | ||
701 | HttpReply *newrep = new HttpReply; | |
702 | const bool parsed = newrep->parse(readBuf, eof, &error); | |
703 | ||
704 | if (!parsed && readBuf->contentSize() > 5 && strncmp(readBuf->content(), "HTTP/", 5) != 0 && strncmp(readBuf->content(), "ICY", 3) != 0) { | |
705 | MemBuf *mb; | |
706 | HttpReply *tmprep = new HttpReply; | |
707 | tmprep->setHeaders(HTTP_OK, "Gatewaying", NULL, -1, -1, -1); | |
708 | tmprep->header.putExt("X-Transformed-From", "HTTP/0.9"); | |
709 | mb = tmprep->pack(); | |
710 | newrep->parse(mb, eof, &error); | |
711 | delete mb; | |
712 | delete tmprep; | |
713 | } else { | |
714 | if (!parsed && error > 0) { // unrecoverable parsing error | |
715 | debugs(11, 3, "processReplyHeader: Non-HTTP-compliant header: '" << readBuf->content() << "'"); | |
716 | flags.headers_parsed = true; | |
717 | newrep->sline.version = HttpVersion(1,1); | |
718 | newrep->sline.status = error; | |
719 | HttpReply *vrep = setVirginReply(newrep); | |
720 | entry->replaceHttpReply(vrep); | |
721 | ctx_exit(ctx); | |
722 | return; | |
723 | } | |
724 | ||
725 | if (!parsed) { // need more data | |
726 | assert(!error); | |
727 | assert(!eof); | |
728 | delete newrep; | |
729 | ctx_exit(ctx); | |
730 | return; | |
731 | } | |
732 | ||
733 | debugs(11, 2, "HTTP Server " << serverConnection); | |
734 | debugs(11, 2, "HTTP Server REPLY:\n---------\n" << readBuf->content() << "\n----------"); | |
735 | ||
736 | header_bytes_read = headersEnd(readBuf->content(), readBuf->contentSize()); | |
737 | readBuf->consume(header_bytes_read); | |
738 | } | |
739 | ||
740 | newrep->removeStaleWarnings(); | |
741 | ||
742 | if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->sline.status >= 100 && newrep->sline.status < 200) { | |
743 | handle1xx(newrep); | |
744 | ctx_exit(ctx); | |
745 | return; | |
746 | } | |
747 | ||
748 | flags.chunked = false; | |
749 | if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) { | |
750 | flags.chunked = true; | |
751 | httpChunkDecoder = new ChunkedCodingParser; | |
752 | } | |
753 | ||
754 | if (!peerSupportsConnectionPinning()) | |
755 | request->flags.connectionAuthDisabled = 1; | |
756 | ||
757 | HttpReply *vrep = setVirginReply(newrep); | |
758 | flags.headers_parsed = true; | |
759 | ||
760 | keepaliveAccounting(vrep); | |
761 | ||
762 | checkDateSkew(vrep); | |
763 | ||
764 | processSurrogateControl (vrep); | |
765 | ||
766 | request->hier.peer_reply_status = newrep->sline.status; | |
767 | ||
768 | ctx_exit(ctx); | |
769 | } | |
770 | ||
771 | /// ignore or start forwarding the 1xx response (a.k.a., control message) | |
772 | void | |
773 | HttpStateData::handle1xx(HttpReply *reply) | |
774 | { | |
775 | HttpMsgPointerT<HttpReply> msg(reply); // will destroy reply if unused | |
776 | ||
777 | // one 1xx at a time: we must not be called while waiting for previous 1xx | |
778 | Must(!flags.handling1xx); | |
779 | flags.handling1xx = true; | |
780 | ||
781 | if (!request->canHandle1xx()) { | |
782 | debugs(11, 2, HERE << "ignoring client-unsupported 1xx"); | |
783 | proceedAfter1xx(); | |
784 | return; | |
785 | } | |
786 | ||
787 | #if USE_HTTP_VIOLATIONS | |
788 | // check whether the 1xx response forwarding is allowed by squid.conf | |
789 | if (Config.accessList.reply) { | |
790 | ACLFilledChecklist ch(Config.accessList.reply, originalRequest(), NULL); | |
791 | ch.reply = HTTPMSGLOCK(reply); | |
792 | if (ch.fastCheck() != ACCESS_ALLOWED) { // TODO: support slow lookups? | |
793 | debugs(11, 3, HERE << "ignoring denied 1xx"); | |
794 | proceedAfter1xx(); | |
795 | return; | |
796 | } | |
797 | } | |
798 | #endif // USE_HTTP_VIOLATIONS | |
799 | ||
800 | debugs(11, 2, HERE << "forwarding 1xx to client"); | |
801 | ||
802 | // the Sink will use this to call us back after writing 1xx to the client | |
803 | typedef NullaryMemFunT<HttpStateData> CbDialer; | |
804 | const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this, | |
805 | HttpStateData::proceedAfter1xx); | |
806 | CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData, | |
807 | ConnStateData::sendControlMsg, HttpControlMsg(msg, cb)); | |
808 | // If the call is not fired, then the Sink is gone, and HttpStateData | |
809 | // will terminate due to an aborted store entry or another similar error. | |
810 | // If we get stuck, it is not handle1xx fault if we could get stuck | |
811 | // for similar reasons without a 1xx response. | |
812 | } | |
813 | ||
814 | /// restores state and resumes processing after 1xx is ignored or forwarded | |
815 | void | |
816 | HttpStateData::proceedAfter1xx() | |
817 | { | |
818 | Must(flags.handling1xx); | |
819 | ||
820 | debugs(11, 2, HERE << "consuming " << header_bytes_read << | |
821 | " header and " << reply_bytes_read << " body bytes read after 1xx"); | |
822 | header_bytes_read = 0; | |
823 | reply_bytes_read = 0; | |
824 | ||
825 | CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply); | |
826 | } | |
827 | ||
828 | /** | |
829 | * returns true if the peer can support connection pinning | |
830 | */ | |
831 | bool HttpStateData::peerSupportsConnectionPinning() const | |
832 | { | |
833 | const HttpReply *rep = entry->mem_obj->getReply(); | |
834 | const HttpHeader *hdr = &rep->header; | |
835 | bool rc; | |
836 | String header; | |
837 | ||
838 | if (!_peer) | |
839 | return true; | |
840 | ||
841 | /*If this peer does not support connection pinning (authenticated | |
842 | connections) return false | |
843 | */ | |
844 | if (!_peer->connection_auth) | |
845 | return false; | |
846 | ||
847 | /*The peer supports connection pinning and the http reply status | |
848 | is not unauthorized, so the related connection can be pinned | |
849 | */ | |
850 | if (rep->sline.status != HTTP_UNAUTHORIZED) | |
851 | return true; | |
852 | ||
853 | /*The server respond with HTTP_UNAUTHORIZED and the peer configured | |
854 | with "connection-auth=on" we know that the peer supports pinned | |
855 | connections | |
856 | */ | |
857 | if (_peer->connection_auth == 1) | |
858 | return true; | |
859 | ||
860 | /*At this point peer has configured with "connection-auth=auto" | |
861 | parameter so we need some extra checks to decide if we are going | |
862 | to allow pinned connections or not | |
863 | */ | |
864 | ||
865 | /*if the peer configured with originserver just allow connection | |
866 | pinning (squid 2.6 behaviour) | |
867 | */ | |
868 | if (_peer->options.originserver) | |
869 | return true; | |
870 | ||
871 | /*if the connections it is already pinned it is OK*/ | |
872 | if (request->flags.pinned) | |
873 | return true; | |
874 | ||
875 | /*Allow pinned connections only if the Proxy-support header exists in | |
876 | reply and has in its list the "Session-Based-Authentication" | |
877 | which means that the peer supports connection pinning. | |
878 | */ | |
879 | if (!hdr->has(HDR_PROXY_SUPPORT)) | |
880 | return false; | |
881 | ||
882 | header = hdr->getStrOrList(HDR_PROXY_SUPPORT); | |
883 | /* XXX This ought to be done in a case-insensitive manner */ | |
884 | rc = (strstr(header.termedBuf(), "Session-Based-Authentication") != NULL); | |
885 | ||
886 | return rc; | |
887 | } | |
888 | ||
889 | // Called when we parsed (and possibly adapted) the headers but | |
890 | // had not starting storing (a.k.a., sending) the body yet. | |
891 | void | |
892 | HttpStateData::haveParsedReplyHeaders() | |
893 | { | |
894 | ServerStateData::haveParsedReplyHeaders(); | |
895 | ||
896 | Ctx ctx = ctx_enter(entry->mem_obj->url); | |
897 | HttpReply *rep = finalReply(); | |
898 | ||
899 | if (rep->sline.status == HTTP_PARTIAL_CONTENT && | |
900 | rep->content_range) | |
901 | currentOffset = rep->content_range->spec.offset; | |
902 | ||
903 | entry->timestampsSet(); | |
904 | ||
905 | /* Check if object is cacheable or not based on reply code */ | |
906 | debugs(11, 3, "haveParsedReplyHeaders: HTTP CODE: " << rep->sline.status); | |
907 | ||
908 | if (neighbors_do_private_keys) | |
909 | httpMaybeRemovePublic(entry, rep->sline.status); | |
910 | ||
911 | if (rep->header.has(HDR_VARY) | |
912 | #if X_ACCELERATOR_VARY | |
913 | || rep->header.has(HDR_X_ACCELERATOR_VARY) | |
914 | #endif | |
915 | ) { | |
916 | const char *vary = httpMakeVaryMark(request, rep); | |
917 | ||
918 | if (!vary) { | |
919 | entry->makePrivate(); | |
920 | if (!fwd->reforwardableStatus(rep->sline.status)) | |
921 | EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT); | |
922 | goto no_cache; | |
923 | } | |
924 | ||
925 | entry->mem_obj->vary_headers = xstrdup(vary); | |
926 | } | |
927 | ||
928 | /* | |
929 | * If its not a reply that we will re-forward, then | |
930 | * allow the client to get it. | |
931 | */ | |
932 | if (!fwd->reforwardableStatus(rep->sline.status)) | |
933 | EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT); | |
934 | ||
935 | switch (cacheableReply()) { | |
936 | ||
937 | case 1: | |
938 | entry->makePublic(); | |
939 | break; | |
940 | ||
941 | case 0: | |
942 | entry->makePrivate(); | |
943 | break; | |
944 | ||
945 | case -1: | |
946 | ||
947 | #if USE_HTTP_VIOLATIONS | |
948 | if (Config.negativeTtl > 0) | |
949 | entry->cacheNegatively(); | |
950 | else | |
951 | #endif | |
952 | entry->makePrivate(); | |
953 | ||
954 | break; | |
955 | ||
956 | default: | |
957 | assert(0); | |
958 | ||
959 | break; | |
960 | } | |
961 | ||
962 | no_cache: | |
963 | ||
964 | if (!ignoreCacheControl) { | |
965 | if (rep->cache_control) { | |
966 | if (rep->cache_control->proxyRevalidate() || | |
967 | rep->cache_control->mustRevalidate() || | |
968 | rep->cache_control->noCache() || | |
969 | rep->cache_control->hasSMaxAge()) | |
970 | EBIT_SET(entry->flags, ENTRY_REVALIDATE); | |
971 | } | |
972 | #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP | |
973 | else { | |
974 | // Expensive calculation. So only do it IF the CC: header is not present. | |
975 | ||
976 | /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP, | |
977 | * but servers like "Active Imaging Webcast/2.0" sure do use it */ | |
978 | if (rep->header.has(HDR_PRAGMA) && | |
979 | rep->header.hasListMember(HDR_PRAGMA,"no-cache",',')) | |
980 | EBIT_SET(entry->flags, ENTRY_REVALIDATE); | |
981 | } | |
982 | #endif | |
983 | } | |
984 | ||
985 | #if HEADERS_LOG | |
986 | headersLog(1, 0, request->method, rep); | |
987 | ||
988 | #endif | |
989 | ||
990 | ctx_exit(ctx); | |
991 | } | |
992 | ||
993 | HttpStateData::ConnectionStatus | |
994 | HttpStateData::statusIfComplete() const | |
995 | { | |
996 | const HttpReply *rep = virginReply(); | |
997 | /** \par | |
998 | * If the reply wants to close the connection, it takes precedence */ | |
999 | ||
1000 | if (httpHeaderHasConnDir(&rep->header, "close")) | |
1001 | return COMPLETE_NONPERSISTENT_MSG; | |
1002 | ||
1003 | /** \par | |
1004 | * If we didn't send a keep-alive request header, then this | |
1005 | * can not be a persistent connection. | |
1006 | */ | |
1007 | if (!flags.keepalive) | |
1008 | return COMPLETE_NONPERSISTENT_MSG; | |
1009 | ||
1010 | /** \par | |
1011 | * If we haven't sent the whole request then this can not be a persistent | |
1012 | * connection. | |
1013 | */ | |
1014 | if (!flags.request_sent) { | |
1015 | debugs(11, 2, "statusIfComplete: Request not yet fully sent \"" << RequestMethodStr(request->method) << " " << entry->url() << "\"" ); | |
1016 | return COMPLETE_NONPERSISTENT_MSG; | |
1017 | } | |
1018 | ||
1019 | /** \par | |
1020 | * What does the reply have to say about keep-alive? | |
1021 | */ | |
1022 | /** | |
1023 | \bug XXX BUG? | |
1024 | * If the origin server (HTTP/1.0) does not send a keep-alive | |
1025 | * header, but keeps the connection open anyway, what happens? | |
1026 | * We'll return here and http.c waits for an EOF before changing | |
1027 | * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT | |
1028 | * and an error status code, and we might have to wait until | |
1029 | * the server times out the socket. | |
1030 | */ | |
1031 | if (!rep->keep_alive) | |
1032 | return COMPLETE_NONPERSISTENT_MSG; | |
1033 | ||
1034 | return COMPLETE_PERSISTENT_MSG; | |
1035 | } | |
1036 | ||
1037 | HttpStateData::ConnectionStatus | |
1038 | HttpStateData::persistentConnStatus() const | |
1039 | { | |
1040 | debugs(11, 3, HERE << serverConnection << " eof=" << eof); | |
1041 | if (eof) // already reached EOF | |
1042 | return COMPLETE_NONPERSISTENT_MSG; | |
1043 | ||
1044 | /* If server fd is closing (but we have not been notified yet), stop Comm | |
1045 | I/O to avoid assertions. TODO: Change Comm API to handle callers that | |
1046 | want more I/O after async closing (usually initiated by others). */ | |
1047 | // XXX: add canReceive or s/canSend/canTalkToServer/ | |
1048 | if (!Comm::IsConnOpen(serverConnection)) | |
1049 | return COMPLETE_NONPERSISTENT_MSG; | |
1050 | ||
1051 | /** \par | |
1052 | * In chunked response we do not know the content length but we are absolutely | |
1053 | * sure about the end of response, so we are calling the statusIfComplete to | |
1054 | * decide if we can be persistant | |
1055 | */ | |
1056 | if (lastChunk && flags.chunked) | |
1057 | return statusIfComplete(); | |
1058 | ||
1059 | const HttpReply *vrep = virginReply(); | |
1060 | debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length); | |
1061 | ||
1062 | const int64_t clen = vrep->bodySize(request->method); | |
1063 | ||
1064 | debugs(11, 5, "persistentConnStatus: clen=" << clen); | |
1065 | ||
1066 | /* If the body size is unknown we must wait for EOF */ | |
1067 | if (clen < 0) | |
1068 | return INCOMPLETE_MSG; | |
1069 | ||
1070 | /** \par | |
1071 | * If the body size is known, we must wait until we've gotten all of it. */ | |
1072 | if (clen > 0) { | |
1073 | // old technique: | |
1074 | // if (entry->mem_obj->endOffset() < vrep->content_length + vrep->hdr_sz) | |
1075 | const int64_t body_bytes_read = reply_bytes_read - header_bytes_read; | |
1076 | debugs(11,5, "persistentConnStatus: body_bytes_read=" << | |
1077 | body_bytes_read << " content_length=" << vrep->content_length); | |
1078 | ||
1079 | if (body_bytes_read < vrep->content_length) | |
1080 | return INCOMPLETE_MSG; | |
1081 | ||
1082 | if (body_bytes_truncated > 0) // already read more than needed | |
1083 | return COMPLETE_NONPERSISTENT_MSG; // disable pconns | |
1084 | } | |
1085 | ||
1086 | /** \par | |
1087 | * If there is no message body or we got it all, we can be persistent */ | |
1088 | return statusIfComplete(); | |
1089 | } | |
1090 | ||
1091 | /* | |
1092 | * This is the callback after some data has been read from the network | |
1093 | */ | |
1094 | /* | |
1095 | void | |
1096 | HttpStateData::ReadReplyWrapper(int fd, char *buf, size_t len, comm_err_t flag, int xerrno, void *data) | |
1097 | { | |
1098 | HttpStateData *httpState = static_cast<HttpStateData *>(data); | |
1099 | assert (fd == httpState->serverConnection->fd); | |
1100 | // assert(buf == readBuf->content()); | |
1101 | PROF_start(HttpStateData_readReply); | |
1102 | httpState->readReply(len, flag, xerrno); | |
1103 | PROF_stop(HttpStateData_readReply); | |
1104 | } | |
1105 | */ | |
1106 | ||
1107 | /* XXX this function is too long! */ | |
1108 | void | |
1109 | HttpStateData::readReply(const CommIoCbParams &io) | |
1110 | { | |
1111 | int bin; | |
1112 | int clen; | |
1113 | int len = io.size; | |
1114 | ||
1115 | flags.do_next_read = false; | |
1116 | ||
1117 | debugs(11, 5, HERE << io.conn << ": len " << len << "."); | |
1118 | ||
1119 | // Bail out early on COMM_ERR_CLOSING - close handlers will tidy up for us | |
1120 | if (io.flag == COMM_ERR_CLOSING) { | |
1121 | debugs(11, 3, "http socket closing"); | |
1122 | return; | |
1123 | } | |
1124 | ||
1125 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { | |
1126 | abortTransaction("store entry aborted while reading reply"); | |
1127 | return; | |
1128 | } | |
1129 | ||
1130 | // handle I/O errors | |
1131 | if (io.flag != COMM_OK || len < 0) { | |
1132 | debugs(11, 2, HERE << io.conn << ": read failure: " << xstrerror() << "."); | |
1133 | ||
1134 | if (ignoreErrno(io.xerrno)) { | |
1135 | flags.do_next_read = true; | |
1136 | } else { | |
1137 | ErrorState *err = new ErrorState(ERR_READ_ERROR, HTTP_BAD_GATEWAY, fwd->request); | |
1138 | err->xerrno = io.xerrno; | |
1139 | fwd->fail(err); | |
1140 | flags.do_next_read = false; | |
1141 | serverConnection->close(); | |
1142 | } | |
1143 | ||
1144 | return; | |
1145 | } | |
1146 | ||
1147 | // update I/O stats | |
1148 | if (len > 0) { | |
1149 | readBuf->appended(len); | |
1150 | reply_bytes_read += len; | |
1151 | #if USE_DELAY_POOLS | |
1152 | DelayId delayId = entry->mem_obj->mostBytesAllowed(); | |
1153 | delayId.bytesIn(len); | |
1154 | #endif | |
1155 | ||
1156 | kb_incr(&(statCounter.server.all.kbytes_in), len); | |
1157 | kb_incr(&(statCounter.server.http.kbytes_in), len); | |
1158 | ++ IOStats.Http.reads; | |
1159 | ||
1160 | for (clen = len - 1, bin = 0; clen; ++bin) | |
1161 | clen >>= 1; | |
1162 | ||
1163 | ++ IOStats.Http.read_hist[bin]; | |
1164 | ||
1165 | // update peer response time stats (%<pt) | |
1166 | const timeval &sent = request->hier.peer_http_request_sent; | |
1167 | request->hier.peer_response_time = | |
1168 | sent.tv_sec ? tvSubMsec(sent, current_time) : -1; | |
1169 | } | |
1170 | ||
1171 | /** \par | |
1172 | * Here the RFC says we should ignore whitespace between replies, but we can't as | |
1173 | * doing so breaks HTTP/0.9 replies beginning with witespace, and in addition | |
1174 | * the response splitting countermeasures is extremely likely to trigger on this, | |
1175 | * not allowing connection reuse in the first place. | |
1176 | * | |
1177 | * 2012-02-10: which RFC? not 2068 or 2616, | |
1178 | * tolerance there is all about whitespace between requests and header tokens. | |
1179 | */ | |
1180 | ||
1181 | if (len == 0) { // reached EOF? | |
1182 | eof = 1; | |
1183 | flags.do_next_read = false; | |
1184 | ||
1185 | /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n | |
1186 | * Ensure here that we have at minimum two \r\n when EOF is seen. | |
1187 | * TODO: Add eof parameter to headersEnd() and move this hack there. | |
1188 | */ | |
1189 | if (readBuf->contentSize() && !flags.headers_parsed) { | |
1190 | /* | |
1191 | * Yes Henrik, there is a point to doing this. When we | |
1192 | * called httpProcessReplyHeader() before, we didn't find | |
1193 | * the end of headers, but now we are definately at EOF, so | |
1194 | * we want to process the reply headers. | |
1195 | */ | |
1196 | /* Fake an "end-of-headers" to work around such broken servers */ | |
1197 | readBuf->append("\r\n", 2); | |
1198 | } | |
1199 | } | |
1200 | ||
1201 | processReply(); | |
1202 | } | |
1203 | ||
1204 | /// processes the already read and buffered response data, possibly after | |
1205 | /// waiting for asynchronous 1xx control message processing | |
1206 | void | |
1207 | HttpStateData::processReply() | |
1208 | { | |
1209 | ||
1210 | if (flags.handling1xx) { // we came back after handling a 1xx response | |
1211 | debugs(11, 5, HERE << "done with 1xx handling"); | |
1212 | flags.handling1xx = false; | |
1213 | Must(!flags.headers_parsed); | |
1214 | } | |
1215 | ||
1216 | if (!flags.headers_parsed) { // have not parsed headers yet? | |
1217 | PROF_start(HttpStateData_processReplyHeader); | |
1218 | processReplyHeader(); | |
1219 | PROF_stop(HttpStateData_processReplyHeader); | |
1220 | ||
1221 | if (!continueAfterParsingHeader()) // parsing error or need more data | |
1222 | return; // TODO: send errors to ICAP | |
1223 | ||
1224 | adaptOrFinalizeReply(); // may write to, abort, or "close" the entry | |
1225 | } | |
1226 | ||
1227 | // kick more reads if needed and/or process the response body, if any | |
1228 | PROF_start(HttpStateData_processReplyBody); | |
1229 | processReplyBody(); // may call serverComplete() | |
1230 | PROF_stop(HttpStateData_processReplyBody); | |
1231 | } | |
1232 | ||
1233 | /** | |
1234 | \retval true if we can continue with processing the body or doing ICAP. | |
1235 | */ | |
1236 | bool | |
1237 | HttpStateData::continueAfterParsingHeader() | |
1238 | { | |
1239 | if (flags.handling1xx) { | |
1240 | debugs(11, 5, HERE << "wait for 1xx handling"); | |
1241 | Must(!flags.headers_parsed); | |
1242 | return false; | |
1243 | } | |
1244 | ||
1245 | if (!flags.headers_parsed && !eof) { | |
1246 | debugs(11, 9, HERE << "needs more at " << readBuf->contentSize()); | |
1247 | flags.do_next_read = true; | |
1248 | /** \retval false If we have not finished parsing the headers and may get more data. | |
1249 | * Schedules more reads to retrieve the missing data. | |
1250 | */ | |
1251 | maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename | |
1252 | return false; | |
1253 | } | |
1254 | ||
1255 | /** If we are done with parsing, check for errors */ | |
1256 | ||
1257 | err_type error = ERR_NONE; | |
1258 | ||
1259 | if (flags.headers_parsed) { // parsed headers, possibly with errors | |
1260 | // check for header parsing errors | |
1261 | if (HttpReply *vrep = virginReply()) { | |
1262 | const http_status s = vrep->sline.status; | |
1263 | const HttpVersion &v = vrep->sline.version; | |
1264 | if (s == HTTP_INVALID_HEADER && v != HttpVersion(0,9)) { | |
1265 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() ); | |
1266 | error = ERR_INVALID_RESP; | |
1267 | } else if (s == HTTP_HEADER_TOO_LARGE) { | |
1268 | fwd->dontRetry(true); | |
1269 | error = ERR_TOO_BIG; | |
1270 | } else { | |
1271 | return true; // done parsing, got reply, and no error | |
1272 | } | |
1273 | } else { | |
1274 | // parsed headers but got no reply | |
1275 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() ); | |
1276 | error = ERR_INVALID_RESP; | |
1277 | } | |
1278 | } else { | |
1279 | assert(eof); | |
1280 | if (readBuf->hasContent()) { | |
1281 | error = ERR_INVALID_RESP; | |
1282 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() ); | |
1283 | } else { | |
1284 | error = ERR_ZERO_SIZE_OBJECT; | |
1285 | debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << | |
1286 | entry->url() << " AKA " << request->GetHost() << request->urlpath.termedBuf() ); | |
1287 | } | |
1288 | } | |
1289 | ||
1290 | assert(error != ERR_NONE); | |
1291 | entry->reset(); | |
1292 | fwd->fail(new ErrorState(error, HTTP_BAD_GATEWAY, fwd->request)); | |
1293 | flags.do_next_read = false; | |
1294 | serverConnection->close(); | |
1295 | return false; // quit on error | |
1296 | } | |
1297 | ||
1298 | /** truncate what we read if we read too much so that writeReplyBody() | |
1299 | writes no more than what we should have read */ | |
1300 | void | |
1301 | HttpStateData::truncateVirginBody() | |
1302 | { | |
1303 | assert(flags.headers_parsed); | |
1304 | ||
1305 | HttpReply *vrep = virginReply(); | |
1306 | int64_t clen = -1; | |
1307 | if (!vrep->expectingBody(request->method, clen) || clen < 0) | |
1308 | return; // no body or a body of unknown size, including chunked | |
1309 | ||
1310 | const int64_t body_bytes_read = reply_bytes_read - header_bytes_read; | |
1311 | if (body_bytes_read - body_bytes_truncated <= clen) | |
1312 | return; // we did not read too much or already took care of the extras | |
1313 | ||
1314 | if (const int64_t extras = body_bytes_read - body_bytes_truncated - clen) { | |
1315 | // server sent more that the advertised content length | |
1316 | debugs(11,5, HERE << "body_bytes_read=" << body_bytes_read << | |
1317 | " clen=" << clen << '/' << vrep->content_length << | |
1318 | " body_bytes_truncated=" << body_bytes_truncated << '+' << extras); | |
1319 | ||
1320 | readBuf->truncate(extras); | |
1321 | body_bytes_truncated += extras; | |
1322 | } | |
1323 | } | |
1324 | ||
1325 | /** | |
1326 | * Call this when there is data from the origin server | |
1327 | * which should be sent to either StoreEntry, or to ICAP... | |
1328 | */ | |
1329 | void | |
1330 | HttpStateData::writeReplyBody() | |
1331 | { | |
1332 | truncateVirginBody(); // if needed | |
1333 | const char *data = readBuf->content(); | |
1334 | int len = readBuf->contentSize(); | |
1335 | addVirginReplyBody(data, len); | |
1336 | readBuf->consume(len); | |
1337 | } | |
1338 | ||
1339 | bool | |
1340 | HttpStateData::decodeAndWriteReplyBody() | |
1341 | { | |
1342 | const char *data = NULL; | |
1343 | int len; | |
1344 | bool wasThereAnException = false; | |
1345 | assert(flags.chunked); | |
1346 | assert(httpChunkDecoder); | |
1347 | SQUID_ENTER_THROWING_CODE(); | |
1348 | MemBuf decodedData; | |
1349 | decodedData.init(); | |
1350 | const bool doneParsing = httpChunkDecoder->parse(readBuf,&decodedData); | |
1351 | len = decodedData.contentSize(); | |
1352 | data=decodedData.content(); | |
1353 | addVirginReplyBody(data, len); | |
1354 | if (doneParsing) { | |
1355 | lastChunk = 1; | |
1356 | flags.do_next_read = false; | |
1357 | } | |
1358 | SQUID_EXIT_THROWING_CODE(wasThereAnException); | |
1359 | return wasThereAnException; | |
1360 | } | |
1361 | ||
1362 | /** | |
1363 | * processReplyBody has two purposes: | |
1364 | * 1 - take the reply body data, if any, and put it into either | |
1365 | * the StoreEntry, or give it over to ICAP. | |
1366 | * 2 - see if we made it to the end of the response (persistent | |
1367 | * connections and such) | |
1368 | */ | |
1369 | void | |
1370 | HttpStateData::processReplyBody() | |
1371 | { | |
1372 | Ip::Address client_addr; | |
1373 | bool ispinned = false; | |
1374 | ||
1375 | if (!flags.headers_parsed) { | |
1376 | flags.do_next_read = true; | |
1377 | maybeReadVirginBody(); | |
1378 | return; | |
1379 | } | |
1380 | ||
1381 | #if USE_ADAPTATION | |
1382 | debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending); | |
1383 | if (adaptationAccessCheckPending) | |
1384 | return; | |
1385 | ||
1386 | #endif | |
1387 | ||
1388 | /* | |
1389 | * At this point the reply headers have been parsed and consumed. | |
1390 | * That means header content has been removed from readBuf and | |
1391 | * it contains only body data. | |
1392 | */ | |
1393 | if (entry->isAccepting()) { | |
1394 | if (flags.chunked) { | |
1395 | if (!decodeAndWriteReplyBody()) { | |
1396 | flags.do_next_read = false; | |
1397 | serverComplete(); | |
1398 | return; | |
1399 | } | |
1400 | } else | |
1401 | writeReplyBody(); | |
1402 | } | |
1403 | ||
1404 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { | |
1405 | // The above writeReplyBody() call may have aborted the store entry. | |
1406 | abortTransaction("store entry aborted while storing reply"); | |
1407 | return; | |
1408 | } else | |
1409 | switch (persistentConnStatus()) { | |
1410 | case INCOMPLETE_MSG: { | |
1411 | debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection); | |
1412 | /* Wait for more data or EOF condition */ | |
1413 | AsyncCall::Pointer nil; | |
1414 | if (flags.keepalive_broken) { | |
1415 | commSetConnTimeout(serverConnection, 10, nil); | |
1416 | } else { | |
1417 | commSetConnTimeout(serverConnection, Config.Timeout.read, nil); | |
1418 | } | |
1419 | ||
1420 | flags.do_next_read = true; | |
1421 | } | |
1422 | break; | |
1423 | ||
1424 | case COMPLETE_PERSISTENT_MSG: | |
1425 | debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection); | |
1426 | /* yes we have to clear all these! */ | |
1427 | commUnsetConnTimeout(serverConnection); | |
1428 | flags.do_next_read = false; | |
1429 | ||
1430 | comm_remove_close_handler(serverConnection->fd, closeHandler); | |
1431 | closeHandler = NULL; | |
1432 | fwd->unregister(serverConnection); | |
1433 | ||
1434 | if (request->flags.spoofClientIp) | |
1435 | client_addr = request->client_addr; | |
1436 | ||
1437 | if (request->flags.pinned) { | |
1438 | ispinned = true; | |
1439 | } else if (request->flags.connectionAuth && request->flags.authSent) { | |
1440 | ispinned = true; | |
1441 | } | |
1442 | ||
1443 | if (ispinned && request->clientConnectionManager.valid()) { | |
1444 | request->clientConnectionManager->pinConnection(serverConnection, request, _peer, | |
1445 | (request->flags.connectionAuth != 0)); | |
1446 | } else { | |
1447 | fwd->pconnPush(serverConnection, request->peer_host ? request->peer_host : request->GetHost()); | |
1448 | } | |
1449 | ||
1450 | serverConnection = NULL; | |
1451 | serverComplete(); | |
1452 | return; | |
1453 | ||
1454 | case COMPLETE_NONPERSISTENT_MSG: | |
1455 | debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection); | |
1456 | serverComplete(); | |
1457 | return; | |
1458 | } | |
1459 | ||
1460 | maybeReadVirginBody(); | |
1461 | } | |
1462 | ||
1463 | void | |
1464 | HttpStateData::maybeReadVirginBody() | |
1465 | { | |
1466 | // too late to read | |
1467 | if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing()) | |
1468 | return; | |
1469 | ||
1470 | // we may need to grow the buffer if headers do not fit | |
1471 | const int minRead = flags.headers_parsed ? 0 :1024; | |
1472 | const int read_size = replyBodySpace(*readBuf, minRead); | |
1473 | ||
1474 | debugs(11,9, HERE << (flags.do_next_read ? "may" : "wont") << | |
1475 | " read up to " << read_size << " bytes from " << serverConnection); | |
1476 | ||
1477 | /* | |
1478 | * why <2? Because delayAwareRead() won't actually read if | |
1479 | * you ask it to read 1 byte. The delayed read request | |
1480 | * just gets re-queued until the client side drains, then | |
1481 | * the I/O thread hangs. Better to not register any read | |
1482 | * handler until we get a notification from someone that | |
1483 | * its okay to read again. | |
1484 | */ | |
1485 | if (read_size < 2) | |
1486 | return; | |
1487 | ||
1488 | if (flags.do_next_read) { | |
1489 | flags.do_next_read = false; | |
1490 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
1491 | entry->delayAwareRead(serverConnection, readBuf->space(read_size), read_size, | |
1492 | JobCallback(11, 5, Dialer, this, HttpStateData::readReply)); | |
1493 | } | |
1494 | } | |
1495 | ||
1496 | /// called after writing the very last request byte (body, last-chunk, etc) | |
1497 | void | |
1498 | HttpStateData::wroteLast(const CommIoCbParams &io) | |
1499 | { | |
1500 | debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << "."); | |
1501 | #if URL_CHECKSUM_DEBUG | |
1502 | ||
1503 | entry->mem_obj->checkUrlChecksum(); | |
1504 | #endif | |
1505 | ||
1506 | if (io.size > 0) { | |
1507 | fd_bytes(io.fd, io.size, FD_WRITE); | |
1508 | kb_incr(&(statCounter.server.all.kbytes_out), io.size); | |
1509 | kb_incr(&(statCounter.server.http.kbytes_out), io.size); | |
1510 | } | |
1511 | ||
1512 | if (io.flag == COMM_ERR_CLOSING) | |
1513 | return; | |
1514 | ||
1515 | if (io.flag) { | |
1516 | ErrorState *err = new ErrorState(ERR_WRITE_ERROR, HTTP_BAD_GATEWAY, fwd->request); | |
1517 | err->xerrno = io.xerrno; | |
1518 | fwd->fail(err); | |
1519 | serverConnection->close(); | |
1520 | return; | |
1521 | } | |
1522 | ||
1523 | sendComplete(); | |
1524 | } | |
1525 | ||
1526 | /// successfully wrote the entire request (including body, last-chunk, etc.) | |
1527 | void | |
1528 | HttpStateData::sendComplete() | |
1529 | { | |
1530 | /* | |
1531 | * Set the read timeout here because it hasn't been set yet. | |
1532 | * We only set the read timeout after the request has been | |
1533 | * fully written to the server-side. If we start the timeout | |
1534 | * after connection establishment, then we are likely to hit | |
1535 | * the timeout for POST/PUT requests that have very large | |
1536 | * request bodies. | |
1537 | */ | |
1538 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; | |
1539 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, | |
1540 | TimeoutDialer, this, HttpStateData::httpTimeout); | |
1541 | ||
1542 | commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall); | |
1543 | flags.request_sent = true; | |
1544 | request->hier.peer_http_request_sent = current_time; | |
1545 | } | |
1546 | ||
1547 | // Close the HTTP server connection. Used by serverComplete(). | |
1548 | void | |
1549 | HttpStateData::closeServer() | |
1550 | { | |
1551 | debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this); | |
1552 | ||
1553 | if (Comm::IsConnOpen(serverConnection)) { | |
1554 | fwd->unregister(serverConnection); | |
1555 | comm_remove_close_handler(serverConnection->fd, closeHandler); | |
1556 | closeHandler = NULL; | |
1557 | serverConnection->close(); | |
1558 | } | |
1559 | } | |
1560 | ||
1561 | bool | |
1562 | HttpStateData::doneWithServer() const | |
1563 | { | |
1564 | return !Comm::IsConnOpen(serverConnection); | |
1565 | } | |
1566 | ||
1567 | /* | |
1568 | * Fixup authentication request headers for special cases | |
1569 | */ | |
1570 | static void | |
1571 | httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const HttpStateFlags &flags) | |
1572 | { | |
1573 | http_hdr_type header = flags.originpeer ? HDR_AUTHORIZATION : HDR_PROXY_AUTHORIZATION; | |
1574 | ||
1575 | /* Nothing to do unless we are forwarding to a peer */ | |
1576 | if (!request->flags.proxying) | |
1577 | return; | |
1578 | ||
1579 | /* Needs to be explicitly enabled */ | |
1580 | if (!request->peer_login) | |
1581 | return; | |
1582 | ||
1583 | /* Maybe already dealt with? */ | |
1584 | if (hdr_out->has(header)) | |
1585 | return; | |
1586 | ||
1587 | /* Nothing to do here for PASSTHRU */ | |
1588 | if (strcmp(request->peer_login, "PASSTHRU") == 0) | |
1589 | return; | |
1590 | ||
1591 | /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */ | |
1592 | if (flags.originpeer && strcmp(request->peer_login, "PROXYPASS") == 0 && hdr_in->has(HDR_PROXY_AUTHORIZATION)) { | |
1593 | const char *auth = hdr_in->getStr(HDR_PROXY_AUTHORIZATION); | |
1594 | ||
1595 | if (auth && strncasecmp(auth, "basic ", 6) == 0) { | |
1596 | hdr_out->putStr(header, auth); | |
1597 | return; | |
1598 | } | |
1599 | } | |
1600 | ||
1601 | /* Special mode to pass the username to the upstream cache */ | |
1602 | if (*request->peer_login == '*') { | |
1603 | char loginbuf[256]; | |
1604 | const char *username = "-"; | |
1605 | ||
1606 | if (request->extacl_user.size()) | |
1607 | username = request->extacl_user.termedBuf(); | |
1608 | #if USE_AUTH | |
1609 | else if (request->auth_user_request != NULL) | |
1610 | username = request->auth_user_request->username(); | |
1611 | #endif | |
1612 | ||
1613 | snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, request->peer_login + 1); | |
1614 | ||
1615 | httpHeaderPutStrf(hdr_out, header, "Basic %s", | |
1616 | old_base64_encode(loginbuf)); | |
1617 | return; | |
1618 | } | |
1619 | ||
1620 | /* external_acl provided credentials */ | |
1621 | if (request->extacl_user.size() && request->extacl_passwd.size() && | |
1622 | (strcmp(request->peer_login, "PASS") == 0 || | |
1623 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
1624 | char loginbuf[256]; | |
1625 | snprintf(loginbuf, sizeof(loginbuf), SQUIDSTRINGPH ":" SQUIDSTRINGPH, | |
1626 | SQUIDSTRINGPRINT(request->extacl_user), | |
1627 | SQUIDSTRINGPRINT(request->extacl_passwd)); | |
1628 | httpHeaderPutStrf(hdr_out, header, "Basic %s", | |
1629 | old_base64_encode(loginbuf)); | |
1630 | return; | |
1631 | } | |
1632 | // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU | |
1633 | if (strcmp(request->peer_login, "PASS") == 0) | |
1634 | return; | |
1635 | ||
1636 | /* Kerberos login to peer */ | |
1637 | #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI | |
1638 | if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) { | |
1639 | char *Token=NULL; | |
1640 | char *PrincipalName=NULL,*p; | |
1641 | if ((p=strchr(request->peer_login,':')) != NULL ) { | |
1642 | PrincipalName=++p; | |
1643 | } | |
1644 | Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host); | |
1645 | if (Token) { | |
1646 | httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token); | |
1647 | } | |
1648 | return; | |
1649 | } | |
1650 | #endif /* HAVE_KRB5 && HAVE_GSSAPI */ | |
1651 | ||
1652 | httpHeaderPutStrf(hdr_out, header, "Basic %s", | |
1653 | old_base64_encode(request->peer_login)); | |
1654 | return; | |
1655 | } | |
1656 | ||
1657 | /* | |
1658 | * build request headers and append them to a given MemBuf | |
1659 | * used by buildRequestPrefix() | |
1660 | * note: initialised the HttpHeader, the caller is responsible for Clean()-ing | |
1661 | */ | |
1662 | void | |
1663 | HttpStateData::httpBuildRequestHeader(HttpRequest * request, | |
1664 | StoreEntry * entry, | |
1665 | const AccessLogEntryPointer &al, | |
1666 | HttpHeader * hdr_out, | |
1667 | const HttpStateFlags &flags) | |
1668 | { | |
1669 | /* building buffer for complex strings */ | |
1670 | #define BBUF_SZ (MAX_URL+32) | |
1671 | LOCAL_ARRAY(char, bbuf, BBUF_SZ); | |
1672 | LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN); | |
1673 | const HttpHeader *hdr_in = &request->header; | |
1674 | const HttpHeaderEntry *e = NULL; | |
1675 | HttpHeaderPos pos = HttpHeaderInitPos; | |
1676 | assert (hdr_out->owner == hoRequest); | |
1677 | ||
1678 | /* append our IMS header */ | |
1679 | if (request->lastmod > -1) | |
1680 | hdr_out->putTime(HDR_IF_MODIFIED_SINCE, request->lastmod); | |
1681 | ||
1682 | bool we_do_ranges = decideIfWeDoRanges (request); | |
1683 | ||
1684 | String strConnection (hdr_in->getList(HDR_CONNECTION)); | |
1685 | ||
1686 | while ((e = hdr_in->getEntry(&pos))) | |
1687 | copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags); | |
1688 | ||
1689 | /* Abstraction break: We should interpret multipart/byterange responses | |
1690 | * into offset-length data, and this works around our inability to do so. | |
1691 | */ | |
1692 | if (!we_do_ranges && request->multipartRangeRequest()) { | |
1693 | /* don't cache the result */ | |
1694 | request->flags.cachable = 0; | |
1695 | /* pretend it's not a range request */ | |
1696 | delete request->range; | |
1697 | request->range = NULL; | |
1698 | request->flags.isRanged=false; | |
1699 | } | |
1700 | ||
1701 | /* append Via */ | |
1702 | if (Config.onoff.via) { | |
1703 | String strVia; | |
1704 | strVia = hdr_in->getList(HDR_VIA); | |
1705 | snprintf(bbuf, BBUF_SZ, "%d.%d %s", | |
1706 | request->http_ver.major, | |
1707 | request->http_ver.minor, ThisCache); | |
1708 | strListAdd(&strVia, bbuf, ','); | |
1709 | hdr_out->putStr(HDR_VIA, strVia.termedBuf()); | |
1710 | strVia.clean(); | |
1711 | } | |
1712 | ||
1713 | if (request->flags.accelerated) { | |
1714 | /* Append Surrogate-Capabilities */ | |
1715 | String strSurrogate(hdr_in->getList(HDR_SURROGATE_CAPABILITY)); | |
1716 | #if USE_SQUID_ESI | |
1717 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id); | |
1718 | #else | |
1719 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id); | |
1720 | #endif | |
1721 | strListAdd(&strSurrogate, bbuf, ','); | |
1722 | hdr_out->putStr(HDR_SURROGATE_CAPABILITY, strSurrogate.termedBuf()); | |
1723 | } | |
1724 | ||
1725 | /** \pre Handle X-Forwarded-For */ | |
1726 | if (strcmp(opt_forwarded_for, "delete") != 0) { | |
1727 | ||
1728 | String strFwd = hdr_in->getList(HDR_X_FORWARDED_FOR); | |
1729 | ||
1730 | if (strFwd.size() > 65536/2) { | |
1731 | // There is probably a forwarding loop with Via detection disabled. | |
1732 | // If we do nothing, String will assert on overflow soon. | |
1733 | // TODO: Terminate all transactions with huge XFF? | |
1734 | strFwd = "error"; | |
1735 | ||
1736 | static int warnedCount = 0; | |
1737 | if (warnedCount++ < 100) { | |
1738 | const char *url = entry ? entry->url() : urlCanonical(request); | |
1739 | debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url); | |
1740 | } | |
1741 | } | |
1742 | ||
1743 | if (strcmp(opt_forwarded_for, "on") == 0) { | |
1744 | /** If set to ON - append client IP or 'unknown'. */ | |
1745 | if ( request->client_addr.IsNoAddr() ) | |
1746 | strListAdd(&strFwd, "unknown", ','); | |
1747 | else | |
1748 | strListAdd(&strFwd, request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN), ','); | |
1749 | } else if (strcmp(opt_forwarded_for, "off") == 0) { | |
1750 | /** If set to OFF - append 'unknown'. */ | |
1751 | strListAdd(&strFwd, "unknown", ','); | |
1752 | } else if (strcmp(opt_forwarded_for, "transparent") == 0) { | |
1753 | /** If set to TRANSPARENT - pass through unchanged. */ | |
1754 | } else if (strcmp(opt_forwarded_for, "truncate") == 0) { | |
1755 | /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */ | |
1756 | if ( request->client_addr.IsNoAddr() ) | |
1757 | strFwd = "unknown"; | |
1758 | else | |
1759 | strFwd = request->client_addr.NtoA(ntoabuf, MAX_IPSTRLEN); | |
1760 | } | |
1761 | if (strFwd.size() > 0) | |
1762 | hdr_out->putStr(HDR_X_FORWARDED_FOR, strFwd.termedBuf()); | |
1763 | } | |
1764 | /** If set to DELETE - do not copy through. */ | |
1765 | ||
1766 | /* append Host if not there already */ | |
1767 | if (!hdr_out->has(HDR_HOST)) { | |
1768 | if (request->peer_domain) { | |
1769 | hdr_out->putStr(HDR_HOST, request->peer_domain); | |
1770 | } else if (request->port == urlDefaultPort(request->protocol)) { | |
1771 | /* use port# only if not default */ | |
1772 | hdr_out->putStr(HDR_HOST, request->GetHost()); | |
1773 | } else { | |
1774 | httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d", | |
1775 | request->GetHost(), | |
1776 | (int) request->port); | |
1777 | } | |
1778 | } | |
1779 | ||
1780 | /* append Authorization if known in URL, not in header and going direct */ | |
1781 | if (!hdr_out->has(HDR_AUTHORIZATION)) { | |
1782 | if (!request->flags.proxying && request->login[0] != '\0') { | |
1783 | httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s", | |
1784 | old_base64_encode(request->login)); | |
1785 | } | |
1786 | } | |
1787 | ||
1788 | /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */ | |
1789 | httpFixupAuthentication(request, hdr_in, hdr_out, flags); | |
1790 | ||
1791 | /* append Cache-Control, add max-age if not there already */ | |
1792 | { | |
1793 | HttpHdrCc *cc = hdr_in->getCc(); | |
1794 | ||
1795 | if (!cc) | |
1796 | cc = new HttpHdrCc(); | |
1797 | ||
1798 | #if 0 /* see bug 2330 */ | |
1799 | /* Set no-cache if determined needed but not found */ | |
1800 | if (request->flags.nocache) | |
1801 | EBIT_SET(cc->mask, CC_NO_CACHE); | |
1802 | #endif | |
1803 | ||
1804 | /* Add max-age only without no-cache */ | |
1805 | if (!cc->hasMaxAge() && !cc->noCache()) { | |
1806 | const char *url = | |
1807 | entry ? entry->url() : urlCanonical(request); | |
1808 | cc->maxAge(getMaxAge(url)); | |
1809 | ||
1810 | } | |
1811 | ||
1812 | /* Enforce sibling relations */ | |
1813 | if (flags.only_if_cached) | |
1814 | cc->onlyIfCached(true); | |
1815 | ||
1816 | hdr_out->putCc(cc); | |
1817 | ||
1818 | delete cc; | |
1819 | } | |
1820 | ||
1821 | /* maybe append Connection: keep-alive */ | |
1822 | if (flags.keepalive) { | |
1823 | hdr_out->putStr(HDR_CONNECTION, "keep-alive"); | |
1824 | } | |
1825 | ||
1826 | /* append Front-End-Https */ | |
1827 | if (flags.front_end_https) { | |
1828 | if (flags.front_end_https == 1 || request->protocol == AnyP::PROTO_HTTPS) | |
1829 | hdr_out->putStr(HDR_FRONT_END_HTTPS, "On"); | |
1830 | } | |
1831 | ||
1832 | if (flags.chunked_request) { | |
1833 | // Do not just copy the original value so that if the client-side | |
1834 | // starts decode other encodings, this code may remain valid. | |
1835 | hdr_out->putStr(HDR_TRANSFER_ENCODING, "chunked"); | |
1836 | } | |
1837 | ||
1838 | /* Now mangle the headers. */ | |
1839 | if (Config2.onoff.mangle_request_headers) | |
1840 | httpHdrMangleList(hdr_out, request, ROR_REQUEST); | |
1841 | ||
1842 | if (Config.request_header_add && !Config.request_header_add->empty()) | |
1843 | httpHdrAdd(hdr_out, request, al, *Config.request_header_add); | |
1844 | ||
1845 | strConnection.clean(); | |
1846 | } | |
1847 | ||
1848 | /** | |
1849 | * Decides whether a particular header may be cloned from the received Clients request | |
1850 | * to our outgoing fetch request. | |
1851 | */ | |
1852 | void | |
1853 | copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const HttpStateFlags &flags) | |
1854 | { | |
1855 | debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value ); | |
1856 | ||
1857 | switch (e->id) { | |
1858 | ||
1859 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */ | |
1860 | ||
1861 | case HDR_PROXY_AUTHORIZATION: | |
1862 | /** \par Proxy-Authorization: | |
1863 | * Only pass on proxy authentication to peers for which | |
1864 | * authentication forwarding is explicitly enabled | |
1865 | */ | |
1866 | if (!flags.originpeer && flags.proxying && request->peer_login && | |
1867 | (strcmp(request->peer_login, "PASS") == 0 || | |
1868 | strcmp(request->peer_login, "PROXYPASS") == 0 || | |
1869 | strcmp(request->peer_login, "PASSTHRU") == 0)) { | |
1870 | hdr_out->addEntry(e->clone()); | |
1871 | } | |
1872 | break; | |
1873 | ||
1874 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */ | |
1875 | ||
1876 | case HDR_CONNECTION: /** \par Connection: */ | |
1877 | case HDR_TE: /** \par TE: */ | |
1878 | case HDR_KEEP_ALIVE: /** \par Keep-Alive: */ | |
1879 | case HDR_PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */ | |
1880 | case HDR_TRAILER: /** \par Trailer: */ | |
1881 | case HDR_UPGRADE: /** \par Upgrade: */ | |
1882 | case HDR_TRANSFER_ENCODING: /** \par Transfer-Encoding: */ | |
1883 | break; | |
1884 | ||
1885 | /** \par OTHER headers I haven't bothered to track down yet. */ | |
1886 | ||
1887 | case HDR_AUTHORIZATION: | |
1888 | /** \par WWW-Authorization: | |
1889 | * Pass on WWW authentication */ | |
1890 | ||
1891 | if (!flags.originpeer) { | |
1892 | hdr_out->addEntry(e->clone()); | |
1893 | } else { | |
1894 | /** \note In accelerators, only forward authentication if enabled | |
1895 | * (see also httpFixupAuthentication for special cases) | |
1896 | */ | |
1897 | if (request->peer_login && | |
1898 | (strcmp(request->peer_login, "PASS") == 0 || | |
1899 | strcmp(request->peer_login, "PASSTHRU") == 0 || | |
1900 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
1901 | hdr_out->addEntry(e->clone()); | |
1902 | } | |
1903 | } | |
1904 | ||
1905 | break; | |
1906 | ||
1907 | case HDR_HOST: | |
1908 | /** \par Host: | |
1909 | * Normally Squid rewrites the Host: header. | |
1910 | * However, there is one case when we don't: If the URL | |
1911 | * went through our redirector and the admin configured | |
1912 | * 'redir_rewrites_host' to be off. | |
1913 | */ | |
1914 | if (request->peer_domain) | |
1915 | hdr_out->putStr(HDR_HOST, request->peer_domain); | |
1916 | else if (request->flags.redirected && !Config.onoff.redir_rewrites_host) | |
1917 | hdr_out->addEntry(e->clone()); | |
1918 | else { | |
1919 | /* use port# only if not default */ | |
1920 | ||
1921 | if (request->port == urlDefaultPort(request->protocol)) { | |
1922 | hdr_out->putStr(HDR_HOST, request->GetHost()); | |
1923 | } else { | |
1924 | httpHeaderPutStrf(hdr_out, HDR_HOST, "%s:%d", | |
1925 | request->GetHost(), | |
1926 | (int) request->port); | |
1927 | } | |
1928 | } | |
1929 | ||
1930 | break; | |
1931 | ||
1932 | case HDR_IF_MODIFIED_SINCE: | |
1933 | /** \par If-Modified-Since: | |
1934 | * append unless we added our own; | |
1935 | * \note at most one client's ims header can pass through */ | |
1936 | ||
1937 | if (!hdr_out->has(HDR_IF_MODIFIED_SINCE)) | |
1938 | hdr_out->addEntry(e->clone()); | |
1939 | ||
1940 | break; | |
1941 | ||
1942 | case HDR_MAX_FORWARDS: | |
1943 | /** \par Max-Forwards: | |
1944 | * pass only on TRACE or OPTIONS requests */ | |
1945 | if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) { | |
1946 | const int64_t hops = e->getInt64(); | |
1947 | ||
1948 | if (hops > 0) | |
1949 | hdr_out->putInt64(HDR_MAX_FORWARDS, hops - 1); | |
1950 | } | |
1951 | ||
1952 | break; | |
1953 | ||
1954 | case HDR_VIA: | |
1955 | /** \par Via: | |
1956 | * If Via is disabled then forward any received header as-is. | |
1957 | * Otherwise leave for explicit updated addition later. */ | |
1958 | ||
1959 | if (!Config.onoff.via) | |
1960 | hdr_out->addEntry(e->clone()); | |
1961 | ||
1962 | break; | |
1963 | ||
1964 | case HDR_RANGE: | |
1965 | ||
1966 | case HDR_IF_RANGE: | |
1967 | ||
1968 | case HDR_REQUEST_RANGE: | |
1969 | /** \par Range:, If-Range:, Request-Range: | |
1970 | * Only pass if we accept ranges */ | |
1971 | if (!we_do_ranges) | |
1972 | hdr_out->addEntry(e->clone()); | |
1973 | ||
1974 | break; | |
1975 | ||
1976 | case HDR_PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things. | |
1977 | break; | |
1978 | ||
1979 | case HDR_CONTENT_LENGTH: | |
1980 | // pass through unless we chunk; also, keeping this away from default | |
1981 | // prevents request smuggling via Connection: Content-Length tricks | |
1982 | if (!flags.chunked_request) | |
1983 | hdr_out->addEntry(e->clone()); | |
1984 | break; | |
1985 | ||
1986 | case HDR_X_FORWARDED_FOR: | |
1987 | ||
1988 | case HDR_CACHE_CONTROL: | |
1989 | /** \par X-Forwarded-For:, Cache-Control: | |
1990 | * handled specially by Squid, so leave off for now. | |
1991 | * append these after the loop if needed */ | |
1992 | break; | |
1993 | ||
1994 | case HDR_FRONT_END_HTTPS: | |
1995 | /** \par Front-End-Https: | |
1996 | * Pass thru only if peer is configured with front-end-https */ | |
1997 | if (!flags.front_end_https) | |
1998 | hdr_out->addEntry(e->clone()); | |
1999 | ||
2000 | break; | |
2001 | ||
2002 | default: | |
2003 | /** \par default. | |
2004 | * pass on all other header fields | |
2005 | * which are NOT listed by the special Connection: header. */ | |
2006 | ||
2007 | if (strConnection.size()>0 && strListIsMember(&strConnection, e->name.termedBuf(), ',')) { | |
2008 | debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition"); | |
2009 | return; | |
2010 | } | |
2011 | ||
2012 | hdr_out->addEntry(e->clone()); | |
2013 | } | |
2014 | } | |
2015 | ||
2016 | bool | |
2017 | HttpStateData::decideIfWeDoRanges (HttpRequest * request) | |
2018 | { | |
2019 | bool result = true; | |
2020 | /* decide if we want to do Ranges ourselves | |
2021 | * and fetch the whole object now) | |
2022 | * We want to handle Ranges ourselves iff | |
2023 | * - we can actually parse client Range specs | |
2024 | * - the specs are expected to be simple enough (e.g. no out-of-order ranges) | |
2025 | * - reply will be cachable | |
2026 | * (If the reply will be uncachable we have to throw it away after | |
2027 | * serving this request, so it is better to forward ranges to | |
2028 | * the server and fetch only the requested content) | |
2029 | */ | |
2030 | ||
2031 | int64_t roffLimit = request->getRangeOffsetLimit(); | |
2032 | ||
2033 | if (NULL == request->range || !request->flags.cachable | |
2034 | || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth) | |
2035 | result = false; | |
2036 | ||
2037 | debugs(11, 8, "decideIfWeDoRanges: range specs: " << | |
2038 | request->range << ", cachable: " << | |
2039 | request->flags.cachable << "; we_do_ranges: " << result); | |
2040 | ||
2041 | return result; | |
2042 | } | |
2043 | ||
2044 | /* build request prefix and append it to a given MemBuf; | |
2045 | * return the length of the prefix */ | |
2046 | mb_size_t | |
2047 | HttpStateData::buildRequestPrefix(MemBuf * mb) | |
2048 | { | |
2049 | const int offset = mb->size; | |
2050 | HttpVersion httpver(1,1); | |
2051 | const char * url; | |
2052 | if (_peer && !_peer->options.originserver) | |
2053 | url = entry->url(); | |
2054 | else | |
2055 | url = request->urlpath.termedBuf(); | |
2056 | mb->Printf("%s %s %s/%d.%d\r\n", | |
2057 | RequestMethodStr(request->method), | |
2058 | url && *url ? url : "/", | |
2059 | AnyP::ProtocolType_str[httpver.protocol], | |
2060 | httpver.major,httpver.minor); | |
2061 | /* build and pack headers */ | |
2062 | { | |
2063 | HttpHeader hdr(hoRequest); | |
2064 | Packer p; | |
2065 | httpBuildRequestHeader(request, entry, fwd->al, &hdr, flags); | |
2066 | ||
2067 | if (request->flags.pinned && request->flags.connectionAuth) | |
2068 | request->flags.authSent = 1; | |
2069 | else if (hdr.has(HDR_AUTHORIZATION)) | |
2070 | request->flags.authSent = 1; | |
2071 | ||
2072 | packerToMemInit(&p, mb); | |
2073 | hdr.packInto(&p); | |
2074 | hdr.clean(); | |
2075 | packerClean(&p); | |
2076 | } | |
2077 | /* append header terminator */ | |
2078 | mb->append(crlf, 2); | |
2079 | return mb->size - offset; | |
2080 | } | |
2081 | ||
2082 | /* This will be called when connect completes. Write request. */ | |
2083 | bool | |
2084 | HttpStateData::sendRequest() | |
2085 | { | |
2086 | MemBuf mb; | |
2087 | ||
2088 | debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << "."); | |
2089 | ||
2090 | if (!Comm::IsConnOpen(serverConnection)) { | |
2091 | debugs(11,3, HERE << "cannot send request to closing " << serverConnection); | |
2092 | assert(closeHandler != NULL); | |
2093 | return false; | |
2094 | } | |
2095 | ||
2096 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; | |
2097 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, | |
2098 | TimeoutDialer, this, HttpStateData::httpTimeout); | |
2099 | commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall); | |
2100 | flags.do_next_read = true; | |
2101 | maybeReadVirginBody(); | |
2102 | ||
2103 | if (request->body_pipe != NULL) { | |
2104 | if (!startRequestBodyFlow()) // register to receive body data | |
2105 | return false; | |
2106 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
2107 | requestSender = JobCallback(11,5, | |
2108 | Dialer, this, HttpStateData::sentRequestBody); | |
2109 | ||
2110 | Must(!flags.chunked_request); | |
2111 | // use chunked encoding if we do not know the length | |
2112 | if (request->content_length < 0) | |
2113 | flags.chunked_request = true; | |
2114 | } else { | |
2115 | assert(!requestBodySource); | |
2116 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
2117 | requestSender = JobCallback(11,5, | |
2118 | Dialer, this, HttpStateData::wroteLast); | |
2119 | } | |
2120 | ||
2121 | if (_peer != NULL) { | |
2122 | if (_peer->options.originserver) { | |
2123 | flags.proxying = false; | |
2124 | flags.originpeer = true; | |
2125 | } else { | |
2126 | flags.proxying = false; | |
2127 | flags.originpeer = false; | |
2128 | } | |
2129 | } else { | |
2130 | flags.proxying = false; | |
2131 | flags.originpeer = false; | |
2132 | } | |
2133 | ||
2134 | /* | |
2135 | * Is keep-alive okay for all request methods? | |
2136 | */ | |
2137 | if (request->flags.mustKeepalive) | |
2138 | flags.keepalive = true; | |
2139 | else if (request->flags.pinned) | |
2140 | flags.keepalive = request->persistent(); | |
2141 | else if (!Config.onoff.server_pconns) | |
2142 | flags.keepalive = false; | |
2143 | else if (_peer == NULL) | |
2144 | flags.keepalive = true; | |
2145 | else if (_peer->stats.n_keepalives_sent < 10) | |
2146 | flags.keepalive = true; | |
2147 | else if ((double) _peer->stats.n_keepalives_recv / | |
2148 | (double) _peer->stats.n_keepalives_sent > 0.50) | |
2149 | flags.keepalive = true; | |
2150 | ||
2151 | if (_peer) { | |
2152 | /*The old code here was | |
2153 | if (neighborType(_peer, request) == PEER_SIBLING && ... | |
2154 | which is equivalent to: | |
2155 | if (neighborType(_peer, NULL) == PEER_SIBLING && ... | |
2156 | or better: | |
2157 | if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) || | |
2158 | _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss) | |
2159 | flags.only_if_cached = 1; | |
2160 | ||
2161 | But I suppose it was a bug | |
2162 | */ | |
2163 | if (neighborType(_peer, request) == PEER_SIBLING && | |
2164 | !_peer->options.allow_miss) | |
2165 | flags.only_if_cached = true; | |
2166 | ||
2167 | flags.front_end_https = _peer->front_end_https; | |
2168 | } | |
2169 | ||
2170 | mb.init(); | |
2171 | request->peer_host=_peer?_peer->host:NULL; | |
2172 | buildRequestPrefix(&mb); | |
2173 | ||
2174 | debugs(11, 2, "HTTP Server " << serverConnection); | |
2175 | debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------"); | |
2176 | ||
2177 | Comm::Write(serverConnection, &mb, requestSender); | |
2178 | return true; | |
2179 | } | |
2180 | ||
2181 | bool | |
2182 | HttpStateData::getMoreRequestBody(MemBuf &buf) | |
2183 | { | |
2184 | // parent's implementation can handle the no-encoding case | |
2185 | if (!flags.chunked_request) | |
2186 | return ServerStateData::getMoreRequestBody(buf); | |
2187 | ||
2188 | MemBuf raw; | |
2189 | ||
2190 | Must(requestBodySource != NULL); | |
2191 | if (!requestBodySource->getMoreData(raw)) | |
2192 | return false; // no request body bytes to chunk yet | |
2193 | ||
2194 | // optimization: pre-allocate buffer size that should be enough | |
2195 | const mb_size_t rawDataSize = raw.contentSize(); | |
2196 | // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk | |
2197 | buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity); | |
2198 | ||
2199 | buf.Printf("%x\r\n", static_cast<unsigned int>(rawDataSize)); | |
2200 | buf.append(raw.content(), rawDataSize); | |
2201 | buf.Printf("\r\n"); | |
2202 | ||
2203 | Must(rawDataSize > 0); // we did not accidently created last-chunk above | |
2204 | ||
2205 | // Do not send last-chunk unless we successfully received everything | |
2206 | if (receivedWholeRequestBody) { | |
2207 | Must(!flags.sentLastChunk); | |
2208 | flags.sentLastChunk = true; | |
2209 | buf.append("0\r\n\r\n", 5); | |
2210 | } | |
2211 | ||
2212 | return true; | |
2213 | } | |
2214 | ||
2215 | void | |
2216 | httpStart(FwdState *fwd) | |
2217 | { | |
2218 | debugs(11, 3, "httpStart: \"" << RequestMethodStr(fwd->request->method) << " " << fwd->entry->url() << "\"" ); | |
2219 | AsyncJob::Start(new HttpStateData(fwd)); | |
2220 | } | |
2221 | ||
2222 | void | |
2223 | HttpStateData::start() | |
2224 | { | |
2225 | if (!sendRequest()) { | |
2226 | debugs(11, 3, "httpStart: aborted"); | |
2227 | mustStop("HttpStateData::start failed"); | |
2228 | return; | |
2229 | } | |
2230 | ||
2231 | ++ statCounter.server.all.requests; | |
2232 | ++ statCounter.server.http.requests; | |
2233 | ||
2234 | /* | |
2235 | * We used to set the read timeout here, but not any more. | |
2236 | * Now its set in httpSendComplete() after the full request, | |
2237 | * including request body, has been written to the server. | |
2238 | */ | |
2239 | } | |
2240 | ||
2241 | /// if broken posts are enabled for the request, try to fix and return true | |
2242 | bool | |
2243 | HttpStateData::finishingBrokenPost() | |
2244 | { | |
2245 | #if USE_HTTP_VIOLATIONS | |
2246 | if (!Config.accessList.brokenPosts) { | |
2247 | debugs(11, 5, HERE << "No brokenPosts list"); | |
2248 | return false; | |
2249 | } | |
2250 | ||
2251 | ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest(), NULL); | |
2252 | if (ch.fastCheck() != ACCESS_ALLOWED) { | |
2253 | debugs(11, 5, HERE << "didn't match brokenPosts"); | |
2254 | return false; | |
2255 | } | |
2256 | ||
2257 | if (!Comm::IsConnOpen(serverConnection)) { | |
2258 | debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection); | |
2259 | assert(closeHandler != NULL); | |
2260 | return true; // prevent caller from proceeding as if nothing happened | |
2261 | } | |
2262 | ||
2263 | debugs(11, 3, "finishingBrokenPost: fixing broken POST"); | |
2264 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
2265 | requestSender = JobCallback(11,5, | |
2266 | Dialer, this, HttpStateData::wroteLast); | |
2267 | Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL); | |
2268 | return true; | |
2269 | #else | |
2270 | return false; | |
2271 | #endif /* USE_HTTP_VIOLATIONS */ | |
2272 | } | |
2273 | ||
2274 | /// if needed, write last-chunk to end the request body and return true | |
2275 | bool | |
2276 | HttpStateData::finishingChunkedRequest() | |
2277 | { | |
2278 | if (flags.sentLastChunk) { | |
2279 | debugs(11, 5, HERE << "already sent last-chunk"); | |
2280 | return false; | |
2281 | } | |
2282 | ||
2283 | Must(receivedWholeRequestBody); // or we should not be sending last-chunk | |
2284 | flags.sentLastChunk = true; | |
2285 | ||
2286 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
2287 | requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast); | |
2288 | Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL); | |
2289 | return true; | |
2290 | } | |
2291 | ||
2292 | void | |
2293 | HttpStateData::doneSendingRequestBody() | |
2294 | { | |
2295 | ServerStateData::doneSendingRequestBody(); | |
2296 | debugs(11,5, HERE << serverConnection); | |
2297 | ||
2298 | // do we need to write something after the last body byte? | |
2299 | if (flags.chunked_request && finishingChunkedRequest()) | |
2300 | return; | |
2301 | if (!flags.chunked_request && finishingBrokenPost()) | |
2302 | return; | |
2303 | ||
2304 | sendComplete(); | |
2305 | } | |
2306 | ||
2307 | // more origin request body data is available | |
2308 | void | |
2309 | HttpStateData::handleMoreRequestBodyAvailable() | |
2310 | { | |
2311 | if (eof || !Comm::IsConnOpen(serverConnection)) { | |
2312 | // XXX: we should check this condition in other callbacks then! | |
2313 | // TODO: Check whether this can actually happen: We should unsubscribe | |
2314 | // as a body consumer when the above condition(s) are detected. | |
2315 | debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body"); | |
2316 | return; | |
2317 | } | |
2318 | ||
2319 | assert(requestBodySource != NULL); | |
2320 | ||
2321 | if (requestBodySource->buf().hasContent()) { | |
2322 | // XXX: why does not this trigger a debug message on every request? | |
2323 | ||
2324 | if (flags.headers_parsed && !flags.abuse_detected) { | |
2325 | flags.abuse_detected = true; | |
2326 | debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" ); | |
2327 | ||
2328 | if (virginReply()->sline.status == HTTP_INVALID_HEADER) { | |
2329 | serverConnection->close(); | |
2330 | return; | |
2331 | } | |
2332 | } | |
2333 | } | |
2334 | ||
2335 | HttpStateData::handleMoreRequestBodyAvailable(); | |
2336 | } | |
2337 | ||
2338 | // premature end of the request body | |
2339 | void | |
2340 | HttpStateData::handleRequestBodyProducerAborted() | |
2341 | { | |
2342 | ServerStateData::handleRequestBodyProducerAborted(); | |
2343 | if (entry->isEmpty()) { | |
2344 | debugs(11, 3, "request body aborted: " << serverConnection); | |
2345 | // We usually get here when ICAP REQMOD aborts during body processing. | |
2346 | // We might also get here if client-side aborts, but then our response | |
2347 | // should not matter because either client-side will provide its own or | |
2348 | // there will be no response at all (e.g., if the the client has left). | |
2349 | ErrorState *err = new ErrorState(ERR_ICAP_FAILURE, HTTP_INTERNAL_SERVER_ERROR, fwd->request); | |
2350 | err->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY); | |
2351 | fwd->fail(err); | |
2352 | } | |
2353 | ||
2354 | abortTransaction("request body producer aborted"); | |
2355 | } | |
2356 | ||
2357 | // called when we wrote request headers(!) or a part of the body | |
2358 | void | |
2359 | HttpStateData::sentRequestBody(const CommIoCbParams &io) | |
2360 | { | |
2361 | if (io.size > 0) | |
2362 | kb_incr(&statCounter.server.http.kbytes_out, io.size); | |
2363 | ||
2364 | ServerStateData::sentRequestBody(io); | |
2365 | } | |
2366 | ||
2367 | // Quickly abort the transaction | |
2368 | // TODO: destruction should be sufficient as the destructor should cleanup, | |
2369 | // including canceling close handlers | |
2370 | void | |
2371 | HttpStateData::abortTransaction(const char *reason) | |
2372 | { | |
2373 | debugs(11,5, HERE << "aborting transaction for " << reason << | |
2374 | "; " << serverConnection << ", this " << this); | |
2375 | ||
2376 | if (Comm::IsConnOpen(serverConnection)) { | |
2377 | serverConnection->close(); | |
2378 | return; | |
2379 | } | |
2380 | ||
2381 | fwd->handleUnregisteredServerEnd(); | |
2382 | mustStop("HttpStateData::abortTransaction"); | |
2383 | } |