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