]>
Commit | Line | Data |
---|---|---|
30a4f2a8 | 1 | /* |
4ac4a490 | 2 | * Copyright (C) 1996-2017 The Squid Software Foundation and contributors |
30a4f2a8 | 3 | * |
bbc27441 AJ |
4 | * Squid software is distributed under GPLv2+ license and includes |
5 | * contributions from numerous individuals and organizations. | |
6 | * Please see the COPYING and CONTRIBUTORS files for details. | |
30a4f2a8 | 7 | */ |
019dd986 | 8 | |
bbc27441 AJ |
9 | /* DEBUG: section 11 Hypertext Transfer Protocol (HTTP) */ |
10 | ||
4a83b852 | 11 | /* |
12 | * Anonymizing patch by lutz@as-node.jena.thur.de | |
de3bdb4c | 13 | * have a look into http-anon.c to get more informations. |
4a83b852 | 14 | */ |
15 | ||
582c2af2 | 16 | #include "squid.h" |
9ca29d23 | 17 | #include "acl/FilledChecklist.h" |
655daa06 | 18 | #include "base/AsyncJobCalls.h" |
3d93a84d | 19 | #include "base/TextException.h" |
602d9612 | 20 | #include "base64.h" |
a011edee | 21 | #include "CachePeer.h" |
582c2af2 | 22 | #include "client_side.h" |
8d71285d | 23 | #include "comm/Connection.h" |
395a814a | 24 | #include "comm/Read.h" |
ec41b64c | 25 | #include "comm/Write.h" |
d4a083cc | 26 | #include "CommRead.h" |
8b997339 | 27 | #include "err_detail_type.h" |
aa839030 | 28 | #include "errorpage.h" |
fc54b8d2 | 29 | #include "fd.h" |
85bef0a7 | 30 | #include "fde.h" |
67679543 | 31 | #include "globals.h" |
582c2af2 | 32 | #include "http.h" |
f542211b | 33 | #include "http/one/ResponseParser.h" |
db1720f8 | 34 | #include "http/one/TeChunkedParser.h" |
d3dddfb5 | 35 | #include "http/Stream.h" |
602d9612 | 36 | #include "HttpControlMsg.h" |
7ebe76de | 37 | #include "HttpHdrCc.h" |
582c2af2 | 38 | #include "HttpHdrContRange.h" |
b19dd748 | 39 | #include "HttpHdrSc.h" |
40 | #include "HttpHdrScTarget.h" | |
fc54b8d2 | 41 | #include "HttpHeaderTools.h" |
9ca29d23 AJ |
42 | #include "HttpReply.h" |
43 | #include "HttpRequest.h" | |
fc54b8d2 | 44 | #include "log/access_log.h" |
9ca29d23 AJ |
45 | #include "MemBuf.h" |
46 | #include "MemObject.h" | |
fc54b8d2 | 47 | #include "neighbors.h" |
6ff204fc | 48 | #include "peer_proxy_negotiate_auth.h" |
582c2af2 | 49 | #include "profiler/Profiler.h" |
fc54b8d2 | 50 | #include "refresh.h" |
8d9a8184 | 51 | #include "RefreshPattern.h" |
1fa9b1a7 | 52 | #include "rfc1738.h" |
4d5904f7 | 53 | #include "SquidConfig.h" |
985c86bc | 54 | #include "SquidTime.h" |
e4f1fdae | 55 | #include "StatCounters.h" |
9ca29d23 | 56 | #include "Store.h" |
28204b3b | 57 | #include "StrList.h" |
fc54b8d2 FC |
58 | #include "tools.h" |
59 | #include "URL.h" | |
ed6e9fb9 | 60 | #include "util.h" |
af0bb8e5 | 61 | |
582c2af2 FC |
62 | #if USE_AUTH |
63 | #include "auth/UserRequest.h" | |
64 | #endif | |
65 | #if USE_DELAY_POOLS | |
66 | #include "DelayPools.h" | |
67 | #endif | |
9ca29d23 | 68 | |
af0bb8e5 | 69 | #define SQUID_ENTER_THROWING_CODE() try { |
70 | #define SQUID_EXIT_THROWING_CODE(status) \ | |
f53969cc | 71 | status = true; \ |
af0bb8e5 | 72 | } \ |
0a8bbeeb | 73 | catch (const std::exception &e) { \ |
f53969cc SM |
74 | debugs (11, 1, "Exception error:" << e.what()); \ |
75 | status = false; \ | |
9e008dda | 76 | } |
e6ccf245 | 77 | |
2afaba07 | 78 | CBDATA_CLASS_INIT(HttpStateData); |
090089c4 | 79 | |
6bf8443a | 80 | static const char *const crlf = "\r\n"; |
4db43fab | 81 | |
955394ce | 82 | static void httpMaybeRemovePublic(StoreEntry *, Http::StatusCode); |
e24f13cd | 83 | static void copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, |
bad9c5e4 | 84 | HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &); |
528b2c61 | 85 | |
8e100780 | 86 | HttpStateData::HttpStateData(FwdState *theFwdState) : |
1810a0cb SM |
87 | AsyncJob("HttpStateData"), |
88 | Client(theFwdState), | |
89 | lastChunk(0), | |
90 | httpChunkDecoder(NULL), | |
91 | payloadSeen(0), | |
eace013e EB |
92 | payloadTruncated(0), |
93 | sawDateGoBack(false) | |
2bb867b5 | 94 | { |
95 | debugs(11,5,HERE << "HttpStateData " << this << " created"); | |
a3d50c30 | 96 | ignoreCacheControl = false; |
97 | surrogateNoStore = false; | |
8d71285d | 98 | serverConnection = fwd->serverConnection(); |
a3d50c30 | 99 | |
3ff65596 | 100 | // reset peer response time stats for %<pt |
e24f13cd CT |
101 | request->hier.peer_http_request_sent.tv_sec = 0; |
102 | request->hier.peer_http_request_sent.tv_usec = 0; | |
3ff65596 | 103 | |
5229395c AJ |
104 | if (fwd->serverConnection() != NULL) |
105 | _peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */ | |
a3d50c30 | 106 | |
107 | if (_peer) { | |
e857372a | 108 | request->flags.proxying = true; |
a3d50c30 | 109 | /* |
110 | * This NEIGHBOR_PROXY_ONLY check probably shouldn't be here. | |
111 | * We might end up getting the object from somewhere else if, | |
112 | * for example, the request to this neighbor fails. | |
113 | */ | |
114 | if (_peer->options.proxy_only) | |
d88e3c49 | 115 | entry->releaseRequest(); |
a3d50c30 | 116 | |
9a0a18de | 117 | #if USE_DELAY_POOLS |
a3d50c30 | 118 | entry->setNoDelay(_peer->options.no_delay); |
a3d50c30 | 119 | #endif |
a3d50c30 | 120 | } |
121 | ||
122 | /* | |
123 | * register the handler to free HTTP state data when the FD closes | |
124 | */ | |
dc56a9b1 | 125 | typedef CommCbMemFunT<HttpStateData, CommCloseCbParams> Dialer; |
d1c7f781 | 126 | closeHandler = JobCallback(9, 5, Dialer, this, HttpStateData::httpStateConnClosed); |
8d71285d | 127 | comm_add_close_handler(serverConnection->fd, closeHandler); |
2bb867b5 | 128 | } |
b8d8561b | 129 | |
2afaba07 | 130 | HttpStateData::~HttpStateData() |
f5558c95 | 131 | { |
253caccb | 132 | /* |
fccd4a86 | 133 | * don't forget that ~Client() gets called automatically |
253caccb | 134 | */ |
135 | ||
9e008dda AJ |
136 | if (httpChunkDecoder) |
137 | delete httpChunkDecoder; | |
af0bb8e5 | 138 | |
5229395c AJ |
139 | cbdataReferenceDone(_peer); |
140 | ||
9cf7de1b | 141 | debugs(11,5, HERE << "HttpStateData " << this << " destroyed; " << serverConnection); |
5f8252d2 | 142 | } |
143 | ||
6b679a01 | 144 | const Comm::ConnectionPointer & |
e83cc785 | 145 | HttpStateData::dataConnection() const |
fc68f6b1 | 146 | { |
6b679a01 | 147 | return serverConnection; |
2afaba07 | 148 | } |
8d71285d | 149 | |
9e008dda | 150 | void |
dc56a9b1 | 151 | HttpStateData::httpStateConnClosed(const CommCloseCbParams ¶ms) |
152 | { | |
153 | debugs(11, 5, "httpStateFree: FD " << params.fd << ", httpState=" << params.data); | |
70df76e3 | 154 | doneWithFwd = "httpStateConnClosed()"; // assume FwdState is monitoring too |
79628299 | 155 | mustStop("HttpStateData::httpStateConnClosed"); |
f5558c95 | 156 | } |
157 | ||
dc56a9b1 | 158 | void |
ced8def3 | 159 | HttpStateData::httpTimeout(const CommTimeoutCbParams &) |
090089c4 | 160 | { |
ced8def3 | 161 | debugs(11, 4, serverConnection << ": '" << entry->url() << "'"); |
62e76326 | 162 | |
12158bdc | 163 | if (entry->store_status == STORE_PENDING) { |
f11c8e2f | 164 | fwd->fail(new ErrorState(ERR_READ_TIMEOUT, Http::scGatewayTimeout, fwd->request)); |
9b312a19 | 165 | } |
62e76326 | 166 | |
398bc066 CT |
167 | closeServer(); |
168 | mustStop("HttpStateData::httpTimeout"); | |
090089c4 | 169 | } |
170 | ||
eace013e EB |
171 | static StoreEntry * |
172 | findPreviouslyCachedEntry(StoreEntry *newEntry) { | |
173 | assert(newEntry->mem_obj); | |
174 | return newEntry->mem_obj->request ? | |
c43405e7 | 175 | storeGetPublicByRequest(newEntry->mem_obj->request.getRaw()) : |
eace013e EB |
176 | storeGetPublic(newEntry->mem_obj->storeId(), newEntry->mem_obj->method); |
177 | } | |
178 | ||
09f0985d AR |
179 | /// Remove an existing public store entry if the incoming response (to be |
180 | /// stored in a currently private entry) is going to invalidate it. | |
f9cece6e | 181 | static void |
955394ce | 182 | httpMaybeRemovePublic(StoreEntry * e, Http::StatusCode status) |
f9cece6e | 183 | { |
914b89a2 | 184 | int remove = 0; |
7e3ce7b9 | 185 | int forbidden = 0; |
62e76326 | 186 | |
09f0985d AR |
187 | // If the incoming response already goes into a public entry, then there is |
188 | // nothing to remove. This protects ready-for-collapsing entries as well. | |
d46a87a8 | 189 | if (!EBIT_TEST(e->flags, KEY_PRIVATE)) |
62e76326 | 190 | return; |
3140dc6a GD |
191 | |
192 | // If the new/incoming response cannot be stored, then it does not | |
193 | // compete with the old stored response for the public key, and the | |
194 | // old stored response should be left as is. | |
195 | if (e->mem_obj->request && !e->mem_obj->request->flags.cachable) | |
196 | return; | |
62e76326 | 197 | |
f9cece6e | 198 | switch (status) { |
62e76326 | 199 | |
955394ce | 200 | case Http::scOkay: |
62e76326 | 201 | |
955394ce | 202 | case Http::scNonAuthoritativeInformation: |
62e76326 | 203 | |
955394ce | 204 | case Http::scMultipleChoices: |
62e76326 | 205 | |
955394ce | 206 | case Http::scMovedPermanently: |
62e76326 | 207 | |
f11c8e2f | 208 | case Http::scFound: |
62e76326 | 209 | |
5613c60d GD |
210 | case Http::scSeeOther: |
211 | ||
955394ce | 212 | case Http::scGone: |
62e76326 | 213 | |
955394ce | 214 | case Http::scNotFound: |
914b89a2 | 215 | remove = 1; |
62e76326 | 216 | |
217 | break; | |
218 | ||
955394ce | 219 | case Http::scForbidden: |
62e76326 | 220 | |
955394ce | 221 | case Http::scMethodNotAllowed: |
62e76326 | 222 | forbidden = 1; |
223 | ||
224 | break; | |
225 | ||
f9cece6e | 226 | #if WORK_IN_PROGRESS |
62e76326 | 227 | |
955394ce | 228 | case Http::scUnauthorized: |
62e76326 | 229 | forbidden = 1; |
230 | ||
231 | break; | |
232 | ||
f9cece6e | 233 | #endif |
62e76326 | 234 | |
f9cece6e | 235 | default: |
7e3ce7b9 | 236 | #if QUESTIONABLE |
62e76326 | 237 | /* |
238 | * Any 2xx response should eject previously cached entities... | |
239 | */ | |
abb929f0 | 240 | |
62e76326 | 241 | if (status >= 200 && status < 300) |
914b89a2 | 242 | remove = 1; |
62e76326 | 243 | |
7e3ce7b9 | 244 | #endif |
62e76326 | 245 | |
246 | break; | |
f9cece6e | 247 | } |
62e76326 | 248 | |
914b89a2 | 249 | if (!remove && !forbidden) |
62e76326 | 250 | return; |
251 | ||
eace013e | 252 | StoreEntry *pe = findPreviouslyCachedEntry(e); |
62e76326 | 253 | |
f66a9ef4 | 254 | if (pe != NULL) { |
62e76326 | 255 | assert(e != pe); |
d9129474 | 256 | #if USE_HTCP |
c43405e7 | 257 | neighborsHtcpClear(e, nullptr, e->mem_obj->request.getRaw(), e->mem_obj->method, HTCP_CLR_INVALIDATION); |
d9129474 | 258 | #endif |
5f33b71d | 259 | pe->release(); |
0856d155 | 260 | } |
62e76326 | 261 | |
914b89a2 | 262 | /** \par |
7e3ce7b9 | 263 | * Also remove any cached HEAD response in case the object has |
264 | * changed. | |
265 | */ | |
f66a9ef4 | 266 | if (e->mem_obj->request) |
c43405e7 | 267 | pe = storeGetPublicByRequestMethod(e->mem_obj->request.getRaw(), Http::METHOD_HEAD); |
f66a9ef4 | 268 | else |
c877c0bc | 269 | pe = storeGetPublic(e->mem_obj->storeId(), Http::METHOD_HEAD); |
62e76326 | 270 | |
f66a9ef4 | 271 | if (pe != NULL) { |
62e76326 | 272 | assert(e != pe); |
d9129474 | 273 | #if USE_HTCP |
c43405e7 | 274 | neighborsHtcpClear(e, nullptr, e->mem_obj->request.getRaw(), HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION); |
d9129474 | 275 | #endif |
5f33b71d | 276 | pe->release(); |
7e3ce7b9 | 277 | } |
f9cece6e | 278 | } |
279 | ||
43ae1d95 | 280 | void |
281 | HttpStateData::processSurrogateControl(HttpReply *reply) | |
282 | { | |
45e5102d | 283 | if (request->flags.accelerated && reply->surrogate_control) { |
45a58345 | 284 | HttpHdrScTarget *sctusable = reply->surrogate_control->getMergedTarget(Config.Accel.surrogate_id); |
43ae1d95 | 285 | |
286 | if (sctusable) { | |
810d879f | 287 | if (sctusable->hasNoStore() || |
43ae1d95 | 288 | (Config.onoff.surrogate_is_remote |
45a58345 | 289 | && sctusable->noStoreRemote())) { |
43ae1d95 | 290 | surrogateNoStore = true; |
39fe14b2 EB |
291 | // Be conservative for now and make it non-shareable because |
292 | // there is no enough information here to make the decision. | |
293 | entry->makePrivate(false); | |
43ae1d95 | 294 | } |
295 | ||
296 | /* The HttpHeader logic cannot tell if the header it's parsing is a reply to an | |
297 | * accelerated request or not... | |
45cca89d | 298 | * Still, this is an abstraction breach. - RC |
43ae1d95 | 299 | */ |
45a58345 FC |
300 | if (sctusable->hasMaxAge()) { |
301 | if (sctusable->maxAge() < sctusable->maxStale()) | |
302 | reply->expires = reply->date + sctusable->maxAge(); | |
43ae1d95 | 303 | else |
45a58345 | 304 | reply->expires = reply->date + sctusable->maxStale(); |
43ae1d95 | 305 | |
306 | /* And update the timestamps */ | |
3900307b | 307 | entry->timestampsSet(); |
43ae1d95 | 308 | } |
309 | ||
310 | /* We ignore cache-control directives as per the Surrogate specification */ | |
311 | ignoreCacheControl = true; | |
312 | ||
45a58345 | 313 | delete sctusable; |
43ae1d95 | 314 | } |
315 | } | |
43ae1d95 | 316 | } |
317 | ||
39fe14b2 EB |
318 | HttpStateData::ReuseDecision::Answers |
319 | HttpStateData::reusableReply(HttpStateData::ReuseDecision &decision) | |
c54e9052 | 320 | { |
585ab260 | 321 | HttpReply const *rep = finalReply(); |
528b2c61 | 322 | HttpHeader const *hdr = &rep->header; |
c68e9c6b | 323 | const char *v; |
626096be | 324 | #if USE_HTTP_VIOLATIONS |
62e76326 | 325 | |
8d9a8184 | 326 | const RefreshPattern *R = NULL; |
b6445726 | 327 | |
346be6ad | 328 | /* This strange looking define first looks up the refresh pattern |
b6445726 | 329 | * and then checks if the specified flag is set. The main purpose |
626096be | 330 | * of this is to simplify the refresh pattern lookup and USE_HTTP_VIOLATIONS |
b6445726 | 331 | * condition |
332 | */ | |
333 | #define REFRESH_OVERRIDE(flag) \ | |
c877c0bc | 334 | ((R = (R ? R : refreshLimits(entry->mem_obj->storeId()))) , \ |
5f8252d2 | 335 | (R && R->flags.flag)) |
b445957e | 336 | #else |
337 | #define REFRESH_OVERRIDE(flag) 0 | |
38f9c547 | 338 | #endif |
43ae1d95 | 339 | |
39fe14b2 EB |
340 | if (EBIT_TEST(entry->flags, RELEASE_REQUEST)) |
341 | return decision.make(ReuseDecision::reuseNot, "the entry has been released"); | |
6919be24 | 342 | |
eace013e EB |
343 | // RFC 7234 section 4: a cache MUST use the most recent response |
344 | // (as determined by the Date header field) | |
39fe14b2 EB |
345 | // TODO: whether such responses could be shareable? |
346 | if (sawDateGoBack) | |
347 | return decision.make(ReuseDecision::reuseNot, "the response has an older date header"); | |
eace013e | 348 | |
2b59002c AJ |
349 | // Check for Surrogate/1.0 protocol conditions |
350 | // NP: reverse-proxy traffic our parent server has instructed us never to cache | |
39fe14b2 EB |
351 | if (surrogateNoStore) |
352 | return decision.make(ReuseDecision::reuseNot, "Surrogate-Control:no-store"); | |
62e76326 | 353 | |
2b59002c AJ |
354 | // RFC 2616: HTTP/1.1 Cache-Control conditions |
355 | if (!ignoreCacheControl) { | |
356 | // XXX: check to see if the request headers alone were enough to prevent caching earlier | |
357 | // (ie no-store request header) no need to check those all again here if so. | |
358 | // for now we are not reliably doing that so we waste CPU re-checking request CC | |
8466a4af | 359 | |
2b59002c | 360 | // RFC 2616 section 14.9.2 - MUST NOT cache any response with request CC:no-store |
810d879f | 361 | if (request && request->cache_control && request->cache_control->hasNoStore() && |
39fe14b2 EB |
362 | !REFRESH_OVERRIDE(ignore_no_store)) |
363 | return decision.make(ReuseDecision::reuseNot, | |
364 | "client request Cache-Control:no-store"); | |
38f9c547 | 365 | |
2b59002c | 366 | // NP: request CC:no-cache only means cache READ is forbidden. STORE is permitted. |
810d879f | 367 | if (rep->cache_control && rep->cache_control->hasNoCacheWithParameters()) { |
1259f9cf AJ |
368 | /* TODO: we are allowed to cache when no-cache= has parameters. |
369 | * Provided we strip away any of the listed headers unless they are revalidated | |
370 | * successfully (ie, must revalidate AND these headers are prohibited on stale replies). | |
371 | * That is a bit tricky for squid right now so we avoid caching entirely. | |
372 | */ | |
39fe14b2 EB |
373 | return decision.make(ReuseDecision::reuseNot, |
374 | "server reply Cache-Control:no-cache has parameters"); | |
1259f9cf AJ |
375 | } |
376 | ||
2b59002c AJ |
377 | // NP: request CC:private is undefined. We ignore. |
378 | // NP: other request CC flags are limiters on HIT/MISS. We don't care about here. | |
379 | ||
380 | // RFC 2616 section 14.9.2 - MUST NOT cache any response with CC:no-store | |
810d879f | 381 | if (rep->cache_control && rep->cache_control->hasNoStore() && |
39fe14b2 EB |
382 | !REFRESH_OVERRIDE(ignore_no_store)) |
383 | return decision.make(ReuseDecision::reuseNot, | |
384 | "server reply Cache-Control:no-store"); | |
38f9c547 | 385 | |
2b59002c | 386 | // RFC 2616 section 14.9.1 - MUST NOT cache any response with CC:private in a shared cache like Squid. |
1259f9cf | 387 | // CC:private overrides CC:public when both are present in a response. |
2b59002c AJ |
388 | // TODO: add a shared/private cache configuration possibility. |
389 | if (rep->cache_control && | |
1259f9cf | 390 | rep->cache_control->hasPrivate() && |
2b59002c | 391 | !REFRESH_OVERRIDE(ignore_private)) { |
1259f9cf AJ |
392 | /* TODO: we are allowed to cache when private= has parameters. |
393 | * Provided we strip away any of the listed headers unless they are revalidated | |
394 | * successfully (ie, must revalidate AND these headers are prohibited on stale replies). | |
395 | * That is a bit tricky for squid right now so we avoid caching entirely. | |
396 | */ | |
39fe14b2 EB |
397 | return decision.make(ReuseDecision::reuseNot, |
398 | "server reply Cache-Control:private"); | |
38f9c547 | 399 | } |
2b59002c | 400 | } |
1259f9cf | 401 | |
2b59002c AJ |
402 | // RFC 2068, sec 14.9.4 - MUST NOT cache any response with Authentication UNLESS certain CC controls are present |
403 | // allow HTTP violations to IGNORE those controls (ie re-block caching Auth) | |
d94cbaa8 | 404 | if (request && (request->flags.auth || request->flags.authSent)) { |
39fe14b2 EB |
405 | if (!rep->cache_control) |
406 | return decision.make(ReuseDecision::reuseNot, | |
407 | "authenticated and server reply missing Cache-Control"); | |
62e76326 | 408 | |
39fe14b2 EB |
409 | if (ignoreCacheControl) |
410 | return decision.make(ReuseDecision::reuseNot, | |
411 | "authenticated and ignoring Cache-Control"); | |
62e76326 | 412 | |
2b59002c | 413 | bool mayStore = false; |
8f9343d0 | 414 | // HTTPbis pt6 section 3.2: a response CC:public is present |
810d879f | 415 | if (rep->cache_control->hasPublic()) { |
2b59002c AJ |
416 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:public"); |
417 | mayStore = true; | |
418 | ||
8f9343d0 | 419 | // HTTPbis pt6 section 3.2: a response CC:must-revalidate is present |
810d879f | 420 | } else if (rep->cache_control->hasMustRevalidate()) { |
d94cbaa8 | 421 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:must-revalidate"); |
2b59002c AJ |
422 | mayStore = true; |
423 | ||
8f9343d0 | 424 | #if USE_HTTP_VIOLATIONS |
2b59002c | 425 | // NP: given the must-revalidate exception we should also be able to exempt no-cache. |
8f9343d0 AJ |
426 | // HTTPbis WG verdict on this is that it is omitted from the spec due to being 'unexpected' by |
427 | // some. The caching+revalidate is not exactly unsafe though with Squids interpretation of no-cache | |
1259f9cf | 428 | // (without parameters) as equivalent to must-revalidate in the reply. |
810d879f | 429 | } else if (rep->cache_control->hasNoCacheWithoutParameters()) { |
8f9343d0 | 430 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:no-cache (equivalent to must-revalidate)"); |
2b59002c AJ |
431 | mayStore = true; |
432 | #endif | |
433 | ||
8f9343d0 | 434 | // HTTPbis pt6 section 3.2: a response CC:s-maxage is present |
810d879f | 435 | } else if (rep->cache_control->hasSMaxAge()) { |
908ac81e | 436 | debugs(22, 3, HERE << "Authenticated but server reply Cache-Control:s-maxage"); |
2b59002c AJ |
437 | mayStore = true; |
438 | } | |
62e76326 | 439 | |
39fe14b2 EB |
440 | if (!mayStore) |
441 | return decision.make(ReuseDecision::reuseNot, "authenticated transaction"); | |
2b59002c AJ |
442 | |
443 | // NP: response CC:no-cache is equivalent to CC:must-revalidate,max-age=0. We MAY cache, and do so. | |
444 | // NP: other request CC flags are limiters on HIT/MISS/REFRESH. We don't care about here. | |
c68e9c6b | 445 | } |
62e76326 | 446 | |
2b59002c | 447 | /* HACK: The "multipart/x-mixed-replace" content type is used for |
c68e9c6b | 448 | * continuous push replies. These are generally dynamic and |
449 | * probably should not be cachable | |
450 | */ | |
789217a2 | 451 | if ((v = hdr->getStr(Http::HdrType::CONTENT_TYPE))) |
39fe14b2 EB |
452 | if (!strncasecmp(v, "multipart/x-mixed-replace", 25)) |
453 | return decision.make(ReuseDecision::reuseNot, "Content-Type:multipart/x-mixed-replace"); | |
454 | ||
455 | // TODO: if possible, provide more specific message for each status code | |
456 | static const char *shareableError = "shareable error status code"; | |
457 | static const char *nonShareableError = "non-shareable error status code"; | |
458 | ReuseDecision::Answers statusAnswer = ReuseDecision::reuseNot; | |
459 | const char *statusReason = nonShareableError; | |
62e76326 | 460 | |
9b769c67 | 461 | switch (rep->sline.status()) { |
39fe14b2 EB |
462 | |
463 | /* There are several situations when a non-cacheable response may be | |
464 | * still shareable (e.g., among collapsed clients). We assume that these | |
465 | * are 3xx and 5xx responses, indicating server problems and some of | |
466 | * 4xx responses, common for all clients with a given cache key (e.g., | |
467 | * 404 Not Found or 414 URI Too Long). On the other hand, we should not | |
468 | * share non-cacheable client-specific errors, such as 400 Bad Request | |
469 | * or 406 Not Acceptable. | |
470 | */ | |
471 | ||
f53969cc | 472 | /* Responses that are cacheable */ |
62e76326 | 473 | |
955394ce | 474 | case Http::scOkay: |
62e76326 | 475 | |
955394ce | 476 | case Http::scNonAuthoritativeInformation: |
62e76326 | 477 | |
955394ce | 478 | case Http::scMultipleChoices: |
62e76326 | 479 | |
955394ce AJ |
480 | case Http::scMovedPermanently: |
481 | case Http::scPermanentRedirect: | |
62e76326 | 482 | |
955394ce | 483 | case Http::scGone: |
62e76326 | 484 | /* |
485 | * Don't cache objects that need to be refreshed on next request, | |
486 | * unless we know how to refresh it. | |
487 | */ | |
488 | ||
39fe14b2 EB |
489 | if (refreshIsCachable(entry) || REFRESH_OVERRIDE(store_stale)) |
490 | decision.make(ReuseDecision::cachePositively, "refresh check returned cacheable"); | |
491 | else | |
492 | decision.make(ReuseDecision::doNotCacheButShare, "refresh check returned non-cacheable"); | |
62e76326 | 493 | break; |
494 | ||
f53969cc | 495 | /* Responses that only are cacheable if the server says so */ |
62e76326 | 496 | |
f11c8e2f | 497 | case Http::scFound: |
955394ce | 498 | case Http::scTemporaryRedirect: |
39fe14b2 EB |
499 | if (rep->date <= 0) |
500 | decision.make(ReuseDecision::doNotCacheButShare, "Date is missing/invalid"); | |
501 | if (rep->expires > rep->date) | |
502 | decision.make(ReuseDecision::cachePositively, "Expires > Date"); | |
503 | else | |
504 | decision.make(ReuseDecision::doNotCacheButShare, "Expires <= Date"); | |
62e76326 | 505 | break; |
506 | ||
39fe14b2 | 507 | /* Some responses can be negatively cached */ |
955394ce | 508 | case Http::scNoContent: |
955394ce | 509 | case Http::scUseProxy: |
955394ce | 510 | case Http::scForbidden: |
955394ce | 511 | case Http::scNotFound: |
955394ce | 512 | case Http::scMethodNotAllowed: |
f11c8e2f | 513 | case Http::scUriTooLong: |
955394ce | 514 | case Http::scInternalServerError: |
955394ce | 515 | case Http::scNotImplemented: |
955394ce | 516 | case Http::scBadGateway: |
955394ce | 517 | case Http::scServiceUnavailable: |
f11c8e2f | 518 | case Http::scGatewayTimeout: |
fe3f8977 AJ |
519 | case Http::scMisdirectedRequest: |
520 | ||
39fe14b2 EB |
521 | statusAnswer = ReuseDecision::doNotCacheButShare; |
522 | statusReason = shareableError; | |
523 | case Http::scBadRequest: | |
62e76326 | 524 | |
39fe14b2 EB |
525 | #if USE_HTTP_VIOLATIONS |
526 | if (Config.negativeTtl > 0) | |
527 | decision.make(ReuseDecision::cacheNegatively, "Config.negativeTtl > 0"); | |
528 | else | |
529 | #endif | |
530 | decision.make(statusAnswer, statusReason); | |
62e76326 | 531 | break; |
532 | ||
39fe14b2 EB |
533 | /* these responses can never be cached, some |
534 | of them can be shared though */ | |
955394ce | 535 | case Http::scSeeOther: |
955394ce | 536 | case Http::scNotModified: |
955394ce | 537 | case Http::scUnauthorized: |
955394ce | 538 | case Http::scProxyAuthenticationRequired: |
955394ce | 539 | case Http::scPaymentRequired: |
39fe14b2 EB |
540 | case Http::scInsufficientStorage: |
541 | // TODO: use more specific reason for non-error status codes | |
542 | decision.make(ReuseDecision::doNotCacheButShare, shareableError); | |
543 | break; | |
544 | ||
545 | case Http::scPartialContent: /* Not yet supported. TODO: make shareable for suitable ranges */ | |
955394ce | 546 | case Http::scNotAcceptable: |
39fe14b2 EB |
547 | case Http::scRequestTimeout: // TODO: is this shareable? |
548 | case Http::scConflict: // TODO: is this shareable? | |
955394ce AJ |
549 | case Http::scLengthRequired: |
550 | case Http::scPreconditionFailed: | |
f11c8e2f | 551 | case Http::scPayloadTooLarge: |
955394ce AJ |
552 | case Http::scUnsupportedMediaType: |
553 | case Http::scUnprocessableEntity: | |
39fe14b2 | 554 | case Http::scLocked: // TODO: is this shareable? |
955394ce | 555 | case Http::scFailedDependency: |
955394ce AJ |
556 | case Http::scRequestedRangeNotSatisfied: |
557 | case Http::scExpectationFailed: | |
39fe14b2 EB |
558 | case Http::scInvalidHeader: /* Squid header parsing error */ |
559 | case Http::scHeaderTooLarge: | |
560 | decision.make(ReuseDecision::reuseNot, nonShareableError); | |
561 | break; | |
62e76326 | 562 | |
41217979 AJ |
563 | default: |
564 | /* RFC 2616 section 6.1.1: an unrecognized response MUST NOT be cached. */ | |
39fe14b2 | 565 | decision.make(ReuseDecision::reuseNot, "unknown status code"); |
62e76326 | 566 | break; |
c54e9052 | 567 | } |
62e76326 | 568 | |
39fe14b2 | 569 | return decision.answer; |
c54e9052 | 570 | } |
090089c4 | 571 | |
f5df2040 AJ |
572 | /// assemble a variant key (vary-mark) from the given Vary header and HTTP request |
573 | static void | |
574 | assembleVaryKey(String &vary, SBuf &vstr, const HttpRequest &request) | |
f66a9ef4 | 575 | { |
90ab8f20 | 576 | static const SBuf asterisk("*"); |
f5df2040 AJ |
577 | const char *pos = nullptr; |
578 | const char *item = nullptr; | |
579 | int ilen = 0; | |
62e76326 | 580 | |
f66a9ef4 | 581 | while (strListGetItem(&vary, ',', &item, &ilen, &pos)) { |
81ab22b6 FC |
582 | SBuf name(item, ilen); |
583 | if (name == asterisk) { | |
ee2e0b31 | 584 | vstr = asterisk; |
9776e3cc | 585 | break; |
586 | } | |
81ab22b6 | 587 | name.toLower(); |
90ab8f20 AJ |
588 | if (!vstr.isEmpty()) |
589 | vstr.append(", ", 2); | |
590 | vstr.append(name); | |
f5df2040 AJ |
591 | String hdr(request.header.getByName(name)); |
592 | const char *value = hdr.termedBuf(); | |
62e76326 | 593 | if (value) { |
594 | value = rfc1738_escape_part(value); | |
595 | vstr.append("=\"", 2); | |
596 | vstr.append(value); | |
597 | vstr.append("\"", 1); | |
598 | } | |
599 | ||
30abd221 | 600 | hdr.clean(); |
f66a9ef4 | 601 | } |
f5df2040 | 602 | } |
62e76326 | 603 | |
f5df2040 AJ |
604 | /* |
605 | * For Vary, store the relevant request headers as | |
606 | * virtual headers in the reply | |
607 | * Returns an empty SBuf if the variance cannot be stored | |
608 | */ | |
609 | SBuf | |
610 | httpMakeVaryMark(HttpRequest * request, HttpReply const * reply) | |
611 | { | |
612 | SBuf vstr; | |
613 | String vary; | |
62e76326 | 614 | |
f5df2040 AJ |
615 | vary = reply->header.getList(Http::HdrType::VARY); |
616 | assembleVaryKey(vary, vstr, *request); | |
62e76326 | 617 | |
f5df2040 | 618 | #if X_ACCELERATOR_VARY |
30abd221 | 619 | vary.clean(); |
f5df2040 AJ |
620 | vary = reply->header.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY); |
621 | assembleVaryKey(vary, vstr, *request); | |
f66a9ef4 | 622 | #endif |
62e76326 | 623 | |
90ab8f20 AJ |
624 | debugs(11, 3, vstr); |
625 | return vstr; | |
f66a9ef4 | 626 | } |
627 | ||
2afaba07 | 628 | void |
629 | HttpStateData::keepaliveAccounting(HttpReply *reply) | |
630 | { | |
631 | if (flags.keepalive) | |
632 | if (_peer) | |
95dc7ff4 | 633 | ++ _peer->stats.n_keepalives_sent; |
2afaba07 | 634 | |
635 | if (reply->keep_alive) { | |
636 | if (_peer) | |
95dc7ff4 | 637 | ++ _peer->stats.n_keepalives_recv; |
2afaba07 | 638 | |
af6a12ee AJ |
639 | if (Config.onoff.detect_broken_server_pconns |
640 | && reply->bodySize(request->method) == -1 && !flags.chunked) { | |
e0236918 | 641 | debugs(11, DBG_IMPORTANT, "keepaliveAccounting: Impossible keep-alive header from '" << entry->url() << "'" ); |
bf8fe701 | 642 | // debugs(11, 2, "GOT HTTP REPLY HDR:\n---------\n" << readBuf->content() << "\n----------" ); |
46f4b111 | 643 | flags.keepalive_broken = true; |
2afaba07 | 644 | } |
645 | } | |
646 | } | |
647 | ||
648 | void | |
649 | HttpStateData::checkDateSkew(HttpReply *reply) | |
650 | { | |
651 | if (reply->date > -1 && !_peer) { | |
652 | int skew = abs((int)(reply->date - squid_curtime)); | |
653 | ||
654 | if (skew > 86400) | |
5c51bffb | 655 | debugs(11, 3, "" << request->url.host() << "'s clock is skewed by " << skew << " seconds!"); |
2afaba07 | 656 | } |
657 | } | |
658 | ||
073ba374 | 659 | /** |
4eb368f9 | 660 | * This creates the error page itself.. its likely |
661 | * that the forward ported reply header max size patch | |
662 | * generates non http conformant error pages - in which | |
663 | * case the errors where should be 'BAD_GATEWAY' etc | |
664 | */ | |
b8d8561b | 665 | void |
2afaba07 | 666 | HttpStateData::processReplyHeader() |
f5558c95 | 667 | { |
073ba374 | 668 | /** Creates a blank header. If this routine is made incremental, this will not do */ |
859f1666 AJ |
669 | |
670 | /* NP: all exit points to this function MUST call ctx_exit(ctx) */ | |
c877c0bc | 671 | Ctx ctx = ctx_enter(entry->mem_obj->urlXXX()); |
859f1666 | 672 | |
bf8fe701 | 673 | debugs(11, 3, "processReplyHeader: key '" << entry->getMD5Text() << "'"); |
62e76326 | 674 | |
1a98175f | 675 | assert(!flags.headers_parsed); |
62e76326 | 676 | |
395a814a | 677 | if (!inBuf.length()) { |
859f1666 | 678 | ctx_exit(ctx); |
b73a07d6 | 679 | return; |
859f1666 | 680 | } |
b73a07d6 | 681 | |
f542211b AJ |
682 | /* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */ |
683 | { | |
684 | if (hp == NULL) | |
685 | hp = new Http1::ResponseParser; | |
686 | ||
687 | bool parsedOk = hp->parse(inBuf); | |
688 | ||
689 | // sync the buffers after parsing. | |
690 | inBuf = hp->remaining(); | |
691 | ||
692 | if (hp->needsMoreData()) { | |
693 | if (eof) { // no more data coming | |
694 | /* Bug 2879: Replies may terminate with \r\n then EOF instead of \r\n\r\n. | |
695 | * We also may receive truncated responses. | |
696 | * Ensure here that we have at minimum two \r\n when EOF is seen. | |
697 | */ | |
698 | inBuf.append("\r\n\r\n", 4); | |
699 | // retry the parse | |
700 | parsedOk = hp->parse(inBuf); | |
701 | // sync the buffers after parsing. | |
702 | inBuf = hp->remaining(); | |
703 | } else { | |
704 | debugs(33, 5, "Incomplete response, waiting for end of response headers"); | |
705 | ctx_exit(ctx); | |
706 | return; | |
707 | } | |
708 | } | |
62e76326 | 709 | |
f542211b AJ |
710 | if (!parsedOk) { |
711 | // unrecoverable parsing error | |
3d67f7e6 | 712 | // TODO: Use Raw! XXX: inBuf no longer has the [beginning of the] malformed header. |
f542211b | 713 | debugs(11, 3, "Non-HTTP-compliant header:\n---------\n" << inBuf << "\n----------"); |
18b4c80d | 714 | flags.headers_parsed = true; |
f542211b | 715 | HttpReply *newrep = new HttpReply; |
3d67f7e6 AR |
716 | newrep->sline.set(Http::ProtocolVersion(), hp->parseStatusCode); |
717 | setVirginReply(newrep); | |
9e008dda AJ |
718 | ctx_exit(ctx); |
719 | return; | |
720 | } | |
f542211b | 721 | } |
9e008dda | 722 | |
f542211b AJ |
723 | /* We know the whole response is in parser now */ |
724 | debugs(11, 2, "HTTP Server " << serverConnection); | |
725 | debugs(11, 2, "HTTP Server RESPONSE:\n---------\n" << | |
726 | hp->messageProtocol() << " " << hp->messageStatus() << " " << hp->reasonPhrase() << "\n" << | |
727 | hp->mimeHeader() << | |
8e100780 | 728 | "----------"); |
9e008dda | 729 | |
8e100780 AJ |
730 | // reset payload tracking to begin after message headers |
731 | payloadSeen = inBuf.length(); | |
9e008dda | 732 | |
f542211b | 733 | HttpReply *newrep = new HttpReply; |
62f9b110 AJ |
734 | // XXX: RFC 7230 indicates we MAY ignore the reason phrase, |
735 | // and use an empty string on unknown status. | |
736 | // We do that now to avoid performance regression from using SBuf::c_str() | |
737 | newrep->sline.set(Http::ProtocolVersion(1,1), hp->messageStatus() /* , hp->reasonPhrase() */); | |
f542211b AJ |
738 | newrep->sline.protocol = newrep->sline.version.protocol = hp->messageProtocol().protocol; |
739 | newrep->sline.version.major = hp->messageProtocol().major; | |
740 | newrep->sline.version.minor = hp->messageProtocol().minor; | |
741 | ||
742 | // parse headers | |
af2980f3 | 743 | if (!newrep->parseHeader(*hp)) { |
f542211b AJ |
744 | // XXX: when Http::ProtocolVersion is a function, remove this hack. just set with messageProtocol() |
745 | newrep->sline.set(Http::ProtocolVersion(), Http::scInvalidHeader); | |
746 | newrep->sline.version.protocol = hp->messageProtocol().protocol; | |
747 | newrep->sline.version.major = hp->messageProtocol().major; | |
748 | newrep->sline.version.minor = hp->messageProtocol().minor; | |
749 | debugs(11, 2, "error parsing response headers mime block"); | |
f5558c95 | 750 | } |
62e76326 | 751 | |
f542211b AJ |
752 | // done with Parser, now process using the HttpReply |
753 | hp = NULL; | |
754 | ||
63df1d28 | 755 | newrep->sources |= request->url.getScheme() == AnyP::PROTO_HTTPS ? Http::Message::srcHttps : Http::Message::srcHttp; |
88df846b | 756 | |
c679653d | 757 | newrep->removeStaleWarnings(); |
3d9e71e6 | 758 | |
9b769c67 | 759 | if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->sline.status() >= 100 && newrep->sline.status() < 200) { |
655daa06 | 760 | handle1xx(newrep); |
3d9e71e6 | 761 | ctx_exit(ctx); |
3d9e71e6 AJ |
762 | return; |
763 | } | |
764 | ||
46f4b111 | 765 | flags.chunked = false; |
0c3d3f65 | 766 | if (newrep->sline.protocol == AnyP::PROTO_HTTP && newrep->header.chunked()) { |
46f4b111 | 767 | flags.chunked = true; |
db1720f8 | 768 | httpChunkDecoder = new Http1::TeChunkedParser; |
af0bb8e5 | 769 | } |
770 | ||
9e008dda | 771 | if (!peerSupportsConnectionPinning()) |
e857372a | 772 | request->flags.connectionAuthDisabled = true; |
d67acb4e | 773 | |
585ab260 | 774 | HttpReply *vrep = setVirginReply(newrep); |
46f4b111 | 775 | flags.headers_parsed = true; |
6965ab28 | 776 | |
585ab260 | 777 | keepaliveAccounting(vrep); |
47ac2ebe | 778 | |
585ab260 | 779 | checkDateSkew(vrep); |
47ac2ebe | 780 | |
585ab260 | 781 | processSurrogateControl (vrep); |
528b2c61 | 782 | |
9b769c67 | 783 | request->hier.peer_reply_status = newrep->sline.status(); |
3ff65596 | 784 | |
2afaba07 | 785 | ctx_exit(ctx); |
786 | } | |
787 | ||
655daa06 AR |
788 | /// ignore or start forwarding the 1xx response (a.k.a., control message) |
789 | void | |
790 | HttpStateData::handle1xx(HttpReply *reply) | |
791 | { | |
b248c2a3 | 792 | HttpReply::Pointer msg(reply); // will destroy reply if unused |
655daa06 AR |
793 | |
794 | // one 1xx at a time: we must not be called while waiting for previous 1xx | |
795 | Must(!flags.handling1xx); | |
796 | flags.handling1xx = true; | |
797 | ||
ec69bdb2 CT |
798 | if (!request->canHandle1xx() || request->forcedBodyContinuation) { |
799 | debugs(11, 2, "ignoring 1xx because it is " << (request->forcedBodyContinuation ? "already sent" : "not supported by client")); | |
655daa06 AR |
800 | proceedAfter1xx(); |
801 | return; | |
802 | } | |
803 | ||
804 | #if USE_HTTP_VIOLATIONS | |
805 | // check whether the 1xx response forwarding is allowed by squid.conf | |
806 | if (Config.accessList.reply) { | |
d603e3c2 | 807 | ACLFilledChecklist ch(Config.accessList.reply, originalRequest().getRaw()); |
b248c2a3 AJ |
808 | ch.reply = reply; |
809 | HTTPMSGLOCK(ch.reply); | |
e0f7153c | 810 | if (ch.fastCheck() != ACCESS_ALLOWED) { // TODO: support slow lookups? |
655daa06 AR |
811 | debugs(11, 3, HERE << "ignoring denied 1xx"); |
812 | proceedAfter1xx(); | |
813 | return; | |
de48b288 | 814 | } |
655daa06 AR |
815 | } |
816 | #endif // USE_HTTP_VIOLATIONS | |
817 | ||
818 | debugs(11, 2, HERE << "forwarding 1xx to client"); | |
819 | ||
820 | // the Sink will use this to call us back after writing 1xx to the client | |
821 | typedef NullaryMemFunT<HttpStateData> CbDialer; | |
822 | const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this, | |
de48b288 | 823 | HttpStateData::proceedAfter1xx); |
e24f13cd | 824 | CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData, |
655daa06 AR |
825 | ConnStateData::sendControlMsg, HttpControlMsg(msg, cb)); |
826 | // If the call is not fired, then the Sink is gone, and HttpStateData | |
827 | // will terminate due to an aborted store entry or another similar error. | |
828 | // If we get stuck, it is not handle1xx fault if we could get stuck | |
829 | // for similar reasons without a 1xx response. | |
830 | } | |
831 | ||
832 | /// restores state and resumes processing after 1xx is ignored or forwarded | |
833 | void | |
834 | HttpStateData::proceedAfter1xx() | |
835 | { | |
836 | Must(flags.handling1xx); | |
8e100780 | 837 | debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx"); |
655daa06 AR |
838 | CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply); |
839 | } | |
840 | ||
d67acb4e AJ |
841 | /** |
842 | * returns true if the peer can support connection pinning | |
843 | */ | |
f891baff AJ |
844 | bool |
845 | HttpStateData::peerSupportsConnectionPinning() const | |
d67acb4e | 846 | { |
d67acb4e | 847 | if (!_peer) |
9e008dda AJ |
848 | return true; |
849 | ||
850 | /*If this peer does not support connection pinning (authenticated | |
d67acb4e AJ |
851 | connections) return false |
852 | */ | |
853 | if (!_peer->connection_auth) | |
9e008dda | 854 | return false; |
d67acb4e | 855 | |
a0c227a9 | 856 | const HttpReplyPointer rep(entry->mem_obj->getReply()); |
f891baff | 857 | |
9e008dda | 858 | /*The peer supports connection pinning and the http reply status |
d67acb4e AJ |
859 | is not unauthorized, so the related connection can be pinned |
860 | */ | |
9b769c67 | 861 | if (rep->sline.status() != Http::scUnauthorized) |
9e008dda AJ |
862 | return true; |
863 | ||
955394ce | 864 | /*The server respond with Http::scUnauthorized and the peer configured |
9e008dda | 865 | with "connection-auth=on" we know that the peer supports pinned |
d67acb4e AJ |
866 | connections |
867 | */ | |
868 | if (_peer->connection_auth == 1) | |
9e008dda | 869 | return true; |
d67acb4e | 870 | |
9e008dda AJ |
871 | /*At this point peer has configured with "connection-auth=auto" |
872 | parameter so we need some extra checks to decide if we are going | |
d67acb4e AJ |
873 | to allow pinned connections or not |
874 | */ | |
875 | ||
9e008dda | 876 | /*if the peer configured with originserver just allow connection |
d67acb4e AJ |
877 | pinning (squid 2.6 behaviour) |
878 | */ | |
879 | if (_peer->options.originserver) | |
9e008dda | 880 | return true; |
d67acb4e AJ |
881 | |
882 | /*if the connections it is already pinned it is OK*/ | |
45e5102d | 883 | if (request->flags.pinned) |
9e008dda AJ |
884 | return true; |
885 | ||
886 | /*Allow pinned connections only if the Proxy-support header exists in | |
887 | reply and has in its list the "Session-Based-Authentication" | |
d67acb4e AJ |
888 | which means that the peer supports connection pinning. |
889 | */ | |
f891baff AJ |
890 | if (rep->header.hasListMember(Http::HdrType::PROXY_SUPPORT, "Session-Based-Authentication", ',')) |
891 | return true; | |
d67acb4e | 892 | |
f891baff | 893 | return false; |
d67acb4e AJ |
894 | } |
895 | ||
5f8252d2 | 896 | // Called when we parsed (and possibly adapted) the headers but |
897 | // had not starting storing (a.k.a., sending) the body yet. | |
2afaba07 | 898 | void |
899 | HttpStateData::haveParsedReplyHeaders() | |
900 | { | |
fccd4a86 | 901 | Client::haveParsedReplyHeaders(); |
c1520b67 | 902 | |
c877c0bc | 903 | Ctx ctx = ctx_enter(entry->mem_obj->urlXXX()); |
585ab260 | 904 | HttpReply *rep = finalReply(); |
39fe14b2 | 905 | const Http::StatusCode statusCode = rep->sline.status(); |
2afaba07 | 906 | |
3900307b | 907 | entry->timestampsSet(); |
62e76326 | 908 | |
9bc73deb | 909 | /* Check if object is cacheable or not based on reply code */ |
39fe14b2 | 910 | debugs(11, 3, "HTTP CODE: " << statusCode); |
62e76326 | 911 | |
eace013e EB |
912 | if (const StoreEntry *oldEntry = findPreviouslyCachedEntry(entry)) |
913 | sawDateGoBack = rep->olderThan(oldEntry->getReply()); | |
914 | ||
915 | if (neighbors_do_private_keys && !sawDateGoBack) | |
9b769c67 | 916 | httpMaybeRemovePublic(entry, rep->sline.status()); |
e6ccf245 | 917 | |
7c476309 | 918 | bool varyFailure = false; |
789217a2 | 919 | if (rep->header.has(Http::HdrType::VARY) |
f66a9ef4 | 920 | #if X_ACCELERATOR_VARY |
789217a2 | 921 | || rep->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY) |
f66a9ef4 | 922 | #endif |
4b44c907 | 923 | ) { |
d603e3c2 | 924 | const SBuf vary(httpMakeVaryMark(request.getRaw(), rep)); |
4b44c907 | 925 | |
90ab8f20 | 926 | if (vary.isEmpty()) { |
39fe14b2 EB |
927 | // TODO: check whether such responses are shareable. |
928 | // Do not share for now. | |
929 | entry->makePrivate(false); | |
9b769c67 | 930 | if (!fwd->reforwardableStatus(rep->sline.status())) |
d7d3253b | 931 | EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT); |
7c476309 AJ |
932 | varyFailure = true; |
933 | } else { | |
90ab8f20 | 934 | entry->mem_obj->vary_headers = vary; |
ee2e0b31 AJ |
935 | |
936 | // RFC 7231 section 7.1.4 | |
937 | // Vary:* can be cached, but has mandatory revalidation | |
938 | static const SBuf asterisk("*"); | |
939 | if (vary == asterisk) | |
940 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); | |
62e76326 | 941 | } |
4b44c907 | 942 | } |
943 | ||
7c476309 AJ |
944 | if (!varyFailure) { |
945 | /* | |
946 | * If its not a reply that we will re-forward, then | |
947 | * allow the client to get it. | |
948 | */ | |
949 | if (!fwd->reforwardableStatus(rep->sline.status())) | |
950 | EBIT_CLR(entry->flags, ENTRY_FWD_HDR_WAIT); | |
2afaba07 | 951 | |
39fe14b2 | 952 | ReuseDecision decision(entry, statusCode); |
4b44c907 | 953 | |
39fe14b2 EB |
954 | switch (reusableReply(decision)) { |
955 | ||
956 | case ReuseDecision::reuseNot: | |
957 | entry->makePrivate(false); | |
7c476309 | 958 | break; |
62e76326 | 959 | |
39fe14b2 EB |
960 | case ReuseDecision::cachePositively: |
961 | entry->makePublic(); | |
7c476309 | 962 | break; |
62e76326 | 963 | |
39fe14b2 EB |
964 | case ReuseDecision::cacheNegatively: |
965 | entry->cacheNegatively(); | |
966 | break; | |
4b44c907 | 967 | |
39fe14b2 EB |
968 | case ReuseDecision::doNotCacheButShare: |
969 | entry->makePrivate(true); | |
7c476309 | 970 | break; |
4b44c907 | 971 | |
7c476309 AJ |
972 | default: |
973 | assert(0); | |
974 | break; | |
975 | } | |
39fe14b2 | 976 | debugs(11, 3, "decided: " << decision); |
9bc73deb | 977 | } |
62e76326 | 978 | |
2b59002c AJ |
979 | if (!ignoreCacheControl) { |
980 | if (rep->cache_control) { | |
1259f9cf AJ |
981 | // We are required to revalidate on many conditions. |
982 | // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option | |
983 | ||
984 | // CC:must-revalidate or CC:proxy-revalidate | |
810d879f | 985 | const bool ccMustRevalidate = (rep->cache_control->hasProxyRevalidate() || rep->cache_control->hasMustRevalidate()); |
1259f9cf AJ |
986 | |
987 | // CC:no-cache (only if there are no parameters) | |
810d879f | 988 | const bool ccNoCacheNoParams = rep->cache_control->hasNoCacheWithoutParameters(); |
1259f9cf AJ |
989 | |
990 | // CC:s-maxage=N | |
991 | const bool ccSMaxAge = rep->cache_control->hasSMaxAge(); | |
992 | ||
993 | // CC:private (yes, these can sometimes be stored) | |
994 | const bool ccPrivate = rep->cache_control->hasPrivate(); | |
995 | ||
fa83b766 EB |
996 | if (ccNoCacheNoParams || ccPrivate) |
997 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); | |
998 | else if (ccMustRevalidate || ccSMaxAge) | |
999 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_STALE); | |
2b59002c AJ |
1000 | } |
1001 | #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP | |
1002 | else { | |
1003 | // Expensive calculation. So only do it IF the CC: header is not present. | |
1004 | ||
1005 | /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP, | |
1006 | * but servers like "Active Imaging Webcast/2.0" sure do use it */ | |
789217a2 FC |
1007 | if (rep->header.has(Http::HdrType::PRAGMA) && |
1008 | rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",',')) | |
fa83b766 | 1009 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); |
2b59002c AJ |
1010 | } |
1011 | #endif | |
9bc73deb | 1012 | } |
62e76326 | 1013 | |
c3609322 | 1014 | #if HEADERS_LOG |
585ab260 | 1015 | headersLog(1, 0, request->method, rep); |
fc68f6b1 | 1016 | |
c3609322 | 1017 | #endif |
5f8252d2 | 1018 | |
1019 | ctx_exit(ctx); | |
f5558c95 | 1020 | } |
1021 | ||
528b2c61 | 1022 | HttpStateData::ConnectionStatus |
1023 | HttpStateData::statusIfComplete() const | |
603a02fd | 1024 | { |
585ab260 | 1025 | const HttpReply *rep = virginReply(); |
073ba374 AJ |
1026 | /** \par |
1027 | * If the reply wants to close the connection, it takes precedence */ | |
62e76326 | 1028 | |
d5f18517 AJ |
1029 | static SBuf close("close", 5); |
1030 | if (httpHeaderHasConnDir(&rep->header, close)) | |
62e76326 | 1031 | return COMPLETE_NONPERSISTENT_MSG; |
1032 | ||
073ba374 AJ |
1033 | /** \par |
1034 | * If we didn't send a keep-alive request header, then this | |
978e455f | 1035 | * can not be a persistent connection. |
1036 | */ | |
528b2c61 | 1037 | if (!flags.keepalive) |
62e76326 | 1038 | return COMPLETE_NONPERSISTENT_MSG; |
1039 | ||
073ba374 | 1040 | /** \par |
72b63f06 | 1041 | * If we haven't sent the whole request then this can not be a persistent |
1042 | * connection. | |
1043 | */ | |
1044 | if (!flags.request_sent) { | |
7f06a3d8 | 1045 | debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url()); |
72b63f06 | 1046 | return COMPLETE_NONPERSISTENT_MSG; |
1047 | } | |
1048 | ||
073ba374 | 1049 | /** \par |
9f5a2895 | 1050 | * What does the reply have to say about keep-alive? |
1051 | */ | |
073ba374 AJ |
1052 | /** |
1053 | \bug XXX BUG? | |
b6a2f15e | 1054 | * If the origin server (HTTP/1.0) does not send a keep-alive |
1055 | * header, but keeps the connection open anyway, what happens? | |
1056 | * We'll return here and http.c waits for an EOF before changing | |
1057 | * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT | |
1058 | * and an error status code, and we might have to wait until | |
1059 | * the server times out the socket. | |
1060 | */ | |
2afaba07 | 1061 | if (!rep->keep_alive) |
528b2c61 | 1062 | return COMPLETE_NONPERSISTENT_MSG; |
62e76326 | 1063 | |
528b2c61 | 1064 | return COMPLETE_PERSISTENT_MSG; |
1065 | } | |
1066 | ||
1067 | HttpStateData::ConnectionStatus | |
1068 | HttpStateData::persistentConnStatus() const | |
1069 | { | |
9cf7de1b | 1070 | debugs(11, 3, HERE << serverConnection << " eof=" << eof); |
839291ac AJ |
1071 | if (eof) // already reached EOF |
1072 | return COMPLETE_NONPERSISTENT_MSG; | |
1073 | ||
505c2f28 AR |
1074 | /* If server fd is closing (but we have not been notified yet), stop Comm |
1075 | I/O to avoid assertions. TODO: Change Comm API to handle callers that | |
1076 | want more I/O after async closing (usually initiated by others). */ | |
1077 | // XXX: add canReceive or s/canSend/canTalkToServer/ | |
e7cea0ed | 1078 | if (!Comm::IsConnOpen(serverConnection)) |
505c2f28 AR |
1079 | return COMPLETE_NONPERSISTENT_MSG; |
1080 | ||
9035d1d5 AJ |
1081 | /** \par |
1082 | * In chunked response we do not know the content length but we are absolutely | |
af0bb8e5 | 1083 | * sure about the end of response, so we are calling the statusIfComplete to |
9e008dda | 1084 | * decide if we can be persistant |
af0bb8e5 | 1085 | */ |
839291ac | 1086 | if (lastChunk && flags.chunked) |
9e008dda | 1087 | return statusIfComplete(); |
af0bb8e5 | 1088 | |
718d84bf AR |
1089 | const HttpReply *vrep = virginReply(); |
1090 | debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length); | |
1091 | ||
47f6e231 | 1092 | const int64_t clen = vrep->bodySize(request->method); |
fc68f6b1 | 1093 | |
bf8fe701 | 1094 | debugs(11, 5, "persistentConnStatus: clen=" << clen); |
2afaba07 | 1095 | |
35282fbf | 1096 | /* If the body size is unknown we must wait for EOF */ |
1097 | if (clen < 0) | |
62e76326 | 1098 | return INCOMPLETE_MSG; |
1099 | ||
9035d1d5 AJ |
1100 | /** \par |
1101 | * If the body size is known, we must wait until we've gotten all of it. */ | |
5f8252d2 | 1102 | if (clen > 0) { |
8e100780 | 1103 | debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length); |
2afaba07 | 1104 | |
8e100780 | 1105 | if (payloadSeen < vrep->content_length) |
5f8252d2 | 1106 | return INCOMPLETE_MSG; |
821beb5e | 1107 | |
8e100780 | 1108 | if (payloadTruncated > 0) // already read more than needed |
821beb5e | 1109 | return COMPLETE_NONPERSISTENT_MSG; // disable pconns |
5f8252d2 | 1110 | } |
62e76326 | 1111 | |
9035d1d5 AJ |
1112 | /** \par |
1113 | * If there is no message body or we got it all, we can be persistent */ | |
5f8252d2 | 1114 | return statusIfComplete(); |
603a02fd | 1115 | } |
090089c4 | 1116 | |
d4a083cc AJ |
1117 | static void |
1118 | readDelayed(void *context, CommRead const &) | |
1119 | { | |
1120 | HttpStateData *state = static_cast<HttpStateData*>(context); | |
57912702 | 1121 | state->flags.do_next_read = true; |
d4a083cc AJ |
1122 | state->maybeReadVirginBody(); |
1123 | } | |
d4a083cc | 1124 | |
c4b7a5a9 | 1125 | void |
e6edd8df | 1126 | HttpStateData::readReply(const CommIoCbParams &io) |
090089c4 | 1127 | { |
5867ac79 | 1128 | Must(!flags.do_next_read); // XXX: should have been set false by mayReadVirginBody() |
46f4b111 | 1129 | flags.do_next_read = false; |
9e008dda | 1130 | |
395a814a | 1131 | debugs(11, 5, io.conn); |
62e76326 | 1132 | |
c8407295 AJ |
1133 | // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us |
1134 | if (io.flag == Comm::ERR_CLOSING) { | |
bf8fe701 | 1135 | debugs(11, 3, "http socket closing"); |
c4b7a5a9 | 1136 | return; |
1137 | } | |
1138 | ||
e92e4e44 | 1139 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { |
6dd9a2e4 | 1140 | abortTransaction("store entry aborted while reading reply"); |
62e76326 | 1141 | return; |
e92e4e44 | 1142 | } |
c4b7a5a9 | 1143 | |
5867ac79 AJ |
1144 | Must(Comm::IsConnOpen(serverConnection)); |
1145 | Must(io.conn->fd == serverConnection->fd); | |
fdf55365 | 1146 | |
395a814a AJ |
1147 | /* |
1148 | * Don't reset the timeout value here. The value should be | |
1149 | * counting Config.Timeout.request and applies to the request | |
1150 | * as a whole, not individual read() calls. | |
1151 | * Plus, it breaks our lame *HalfClosed() detection | |
1152 | */ | |
1153 | ||
1ad68518 | 1154 | Must(maybeMakeSpaceAvailable(true)); |
395a814a AJ |
1155 | CommIoCbParams rd(this); // will be expanded with ReadNow results |
1156 | rd.conn = io.conn; | |
1157 | rd.size = entry->bytesWanted(Range<size_t>(0, inBuf.spaceSize())); | |
395a814a | 1158 | |
f1ba1fba EB |
1159 | if (rd.size <= 0) { |
1160 | assert(entry->mem_obj); | |
d4a083cc | 1161 | AsyncCall::Pointer nilCall; |
f1ba1fba | 1162 | entry->mem_obj->delayRead(DeferredRead(readDelayed, this, CommRead(io.conn, NULL, 0, nilCall))); |
fdf55365 | 1163 | return; |
1164 | } | |
1165 | ||
395a814a AJ |
1166 | switch (Comm::ReadNow(rd, inBuf)) { |
1167 | case Comm::INPROGRESS: | |
1168 | if (inBuf.isEmpty()) | |
1169 | debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno)); | |
da958e50 | 1170 | flags.do_next_read = true; |
395a814a AJ |
1171 | maybeReadVirginBody(); |
1172 | return; | |
1173 | ||
1174 | case Comm::OK: | |
1175 | { | |
8e100780 | 1176 | payloadSeen += rd.size; |
9a0a18de | 1177 | #if USE_DELAY_POOLS |
2afaba07 | 1178 | DelayId delayId = entry->mem_obj->mostBytesAllowed(); |
395a814a | 1179 | delayId.bytesIn(rd.size); |
447e176b | 1180 | #endif |
62e76326 | 1181 | |
a0864754 AJ |
1182 | statCounter.server.all.kbytes_in += rd.size; |
1183 | statCounter.server.http.kbytes_in += rd.size; | |
95dc7ff4 | 1184 | ++ IOStats.Http.reads; |
62e76326 | 1185 | |
395a814a AJ |
1186 | int bin = 0; |
1187 | for (int clen = rd.size - 1; clen; ++bin) | |
62e76326 | 1188 | clen >>= 1; |
1189 | ||
95dc7ff4 | 1190 | ++ IOStats.Http.read_hist[bin]; |
3ff65596 AR |
1191 | |
1192 | // update peer response time stats (%<pt) | |
e24f13cd | 1193 | const timeval &sent = request->hier.peer_http_request_sent; |
01bd87d8 CT |
1194 | if (sent.tv_sec) |
1195 | tvSub(request->hier.peer_response_time, sent, current_time); | |
1196 | else | |
1197 | request->hier.peer_response_time.tv_sec = -1; | |
30a4f2a8 | 1198 | } |
62e76326 | 1199 | |
395a814a | 1200 | /* Continue to process previously read data */ |
1810a0cb | 1201 | break; |
5fa061b8 | 1202 | |
395a814a | 1203 | case Comm::ENDFILE: // close detected by 0-byte read |
62e76326 | 1204 | eof = 1; |
46f4b111 | 1205 | flags.do_next_read = false; |
da6c8415 | 1206 | |
395a814a AJ |
1207 | /* Continue to process previously read data */ |
1208 | break; | |
1209 | ||
1810a0cb | 1210 | // case Comm::COMM_ERROR: |
395a814a AJ |
1211 | default: // no other flags should ever occur |
1212 | debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno)); | |
da958e50 CT |
1213 | ErrorState *err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request); |
1214 | err->xerrno = rd.xerrno; | |
1215 | fwd->fail(err); | |
1216 | flags.do_next_read = false; | |
398bc066 CT |
1217 | closeServer(); |
1218 | mustStop("HttpStateData::readReply"); | |
395a814a | 1219 | return; |
ba82c452 | 1220 | } |
62e76326 | 1221 | |
395a814a | 1222 | /* Process next response from buffer */ |
655daa06 AR |
1223 | processReply(); |
1224 | } | |
1225 | ||
1226 | /// processes the already read and buffered response data, possibly after | |
1227 | /// waiting for asynchronous 1xx control message processing | |
1228 | void | |
de48b288 A |
1229 | HttpStateData::processReply() |
1230 | { | |
655daa06 AR |
1231 | |
1232 | if (flags.handling1xx) { // we came back after handling a 1xx response | |
1233 | debugs(11, 5, HERE << "done with 1xx handling"); | |
1234 | flags.handling1xx = false; | |
1235 | Must(!flags.headers_parsed); | |
1236 | } | |
1237 | ||
ba82c452 | 1238 | if (!flags.headers_parsed) { // have not parsed headers yet? |
1239 | PROF_start(HttpStateData_processReplyHeader); | |
1240 | processReplyHeader(); | |
1241 | PROF_stop(HttpStateData_processReplyHeader); | |
1242 | ||
1243 | if (!continueAfterParsingHeader()) // parsing error or need more data | |
1244 | return; // TODO: send errors to ICAP | |
1245 | ||
ab593f19 | 1246 | adaptOrFinalizeReply(); // may write to, abort, or "close" the entry |
ba82c452 | 1247 | } |
1248 | ||
1249 | // kick more reads if needed and/or process the response body, if any | |
1250 | PROF_start(HttpStateData_processReplyBody); | |
1251 | processReplyBody(); // may call serverComplete() | |
1252 | PROF_stop(HttpStateData_processReplyBody); | |
1253 | } | |
1254 | ||
073ba374 AJ |
1255 | /** |
1256 | \retval true if we can continue with processing the body or doing ICAP. | |
1257 | */ | |
ba82c452 | 1258 | bool |
1259 | HttpStateData::continueAfterParsingHeader() | |
1260 | { | |
655daa06 AR |
1261 | if (flags.handling1xx) { |
1262 | debugs(11, 5, HERE << "wait for 1xx handling"); | |
1263 | Must(!flags.headers_parsed); | |
1264 | return false; | |
1265 | } | |
1266 | ||
073ba374 | 1267 | if (!flags.headers_parsed && !eof) { |
395a814a | 1268 | debugs(11, 9, "needs more at " << inBuf.length()); |
46f4b111 | 1269 | flags.do_next_read = true; |
073ba374 AJ |
1270 | /** \retval false If we have not finished parsing the headers and may get more data. |
1271 | * Schedules more reads to retrieve the missing data. | |
1272 | */ | |
ba82c452 | 1273 | maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename |
073ba374 | 1274 | return false; |
ba82c452 | 1275 | } |
1276 | ||
073ba374 | 1277 | /** If we are done with parsing, check for errors */ |
ba82c452 | 1278 | |
1279 | err_type error = ERR_NONE; | |
1280 | ||
1281 | if (flags.headers_parsed) { // parsed headers, possibly with errors | |
1282 | // check for header parsing errors | |
585ab260 | 1283 | if (HttpReply *vrep = virginReply()) { |
9b769c67 | 1284 | const Http::StatusCode s = vrep->sline.status(); |
2592bc70 | 1285 | const AnyP::ProtocolVersion &v = vrep->sline.version; |
526ed14e | 1286 | if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) { |
51b5dcf5 | 1287 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url); |
ba82c452 | 1288 | error = ERR_INVALID_RESP; |
955394ce | 1289 | } else if (s == Http::scHeaderTooLarge) { |
e1381638 AJ |
1290 | fwd->dontRetry(true); |
1291 | error = ERR_TOO_BIG; | |
3e42b356 AR |
1292 | } else if (vrep->header.conflictingContentLength()) { |
1293 | fwd->dontRetry(true); | |
1294 | error = ERR_INVALID_RESP; | |
e1381638 AJ |
1295 | } else { |
1296 | return true; // done parsing, got reply, and no error | |
1297 | } | |
ba82c452 | 1298 | } else { |
1299 | // parsed headers but got no reply | |
51b5dcf5 | 1300 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url); |
ba82c452 | 1301 | error = ERR_INVALID_RESP; |
62e76326 | 1302 | } |
090089c4 | 1303 | } else { |
ba82c452 | 1304 | assert(eof); |
395a814a | 1305 | if (inBuf.length()) { |
9121eba6 | 1306 | error = ERR_INVALID_RESP; |
51b5dcf5 | 1307 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url); |
9121eba6 AJ |
1308 | } else { |
1309 | error = ERR_ZERO_SIZE_OBJECT; | |
51b5dcf5 | 1310 | debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url); |
9121eba6 | 1311 | } |
2afaba07 | 1312 | } |
ba82c452 | 1313 | |
1314 | assert(error != ERR_NONE); | |
1315 | entry->reset(); | |
955394ce | 1316 | fwd->fail(new ErrorState(error, Http::scBadGateway, fwd->request)); |
46f4b111 | 1317 | flags.do_next_read = false; |
398bc066 CT |
1318 | closeServer(); |
1319 | mustStop("HttpStateData::continueAfterParsingHeader"); | |
ba82c452 | 1320 | return false; // quit on error |
2afaba07 | 1321 | } |
1322 | ||
821beb5e AR |
1323 | /** truncate what we read if we read too much so that writeReplyBody() |
1324 | writes no more than what we should have read */ | |
1325 | void | |
1326 | HttpStateData::truncateVirginBody() | |
1327 | { | |
1328 | assert(flags.headers_parsed); | |
1329 | ||
1330 | HttpReply *vrep = virginReply(); | |
1331 | int64_t clen = -1; | |
1332 | if (!vrep->expectingBody(request->method, clen) || clen < 0) | |
1333 | return; // no body or a body of unknown size, including chunked | |
1334 | ||
8e100780 | 1335 | if (payloadSeen - payloadTruncated <= clen) |
821beb5e AR |
1336 | return; // we did not read too much or already took care of the extras |
1337 | ||
8e100780 | 1338 | if (const int64_t extras = payloadSeen - payloadTruncated - clen) { |
821beb5e | 1339 | // server sent more that the advertised content length |
8e100780 | 1340 | debugs(11, 5, "payloadSeen=" << payloadSeen << |
e1381638 | 1341 | " clen=" << clen << '/' << vrep->content_length << |
8e100780 | 1342 | " trucated=" << payloadTruncated << '+' << extras); |
821beb5e | 1343 | |
395a814a | 1344 | inBuf.chop(0, inBuf.length() - extras); |
8e100780 | 1345 | payloadTruncated += extras; |
821beb5e AR |
1346 | } |
1347 | } | |
1348 | ||
073ba374 | 1349 | /** |
2afaba07 | 1350 | * Call this when there is data from the origin server |
1351 | * which should be sent to either StoreEntry, or to ICAP... | |
1352 | */ | |
1353 | void | |
5f8252d2 | 1354 | HttpStateData::writeReplyBody() |
2afaba07 | 1355 | { |
821beb5e | 1356 | truncateVirginBody(); // if needed |
395a814a AJ |
1357 | const char *data = inBuf.rawContent(); |
1358 | int len = inBuf.length(); | |
bc81cb2b | 1359 | addVirginReplyBody(data, len); |
395a814a | 1360 | inBuf.consume(len); |
af0bb8e5 | 1361 | } |
fc68f6b1 | 1362 | |
af0bb8e5 | 1363 | bool |
1364 | HttpStateData::decodeAndWriteReplyBody() | |
1365 | { | |
1366 | const char *data = NULL; | |
1367 | int len; | |
e053c141 | 1368 | bool wasThereAnException = false; |
af0bb8e5 | 1369 | assert(flags.chunked); |
1370 | assert(httpChunkDecoder); | |
1371 | SQUID_ENTER_THROWING_CODE(); | |
1372 | MemBuf decodedData; | |
1373 | decodedData.init(); | |
be29ee33 AJ |
1374 | httpChunkDecoder->setPayloadBuffer(&decodedData); |
1375 | const bool doneParsing = httpChunkDecoder->parse(inBuf); | |
1376 | inBuf = httpChunkDecoder->remaining(); // sync buffers after parse | |
af0bb8e5 | 1377 | len = decodedData.contentSize(); |
1378 | data=decodedData.content(); | |
1379 | addVirginReplyBody(data, len); | |
e053c141 | 1380 | if (doneParsing) { |
839291ac | 1381 | lastChunk = 1; |
46f4b111 | 1382 | flags.do_next_read = false; |
af0bb8e5 | 1383 | } |
e053c141 FC |
1384 | SQUID_EXIT_THROWING_CODE(wasThereAnException); |
1385 | return wasThereAnException; | |
e6ccf245 | 1386 | } |
1387 | ||
073ba374 | 1388 | /** |
2afaba07 | 1389 | * processReplyBody has two purposes: |
1390 | * 1 - take the reply body data, if any, and put it into either | |
1391 | * the StoreEntry, or give it over to ICAP. | |
1392 | * 2 - see if we made it to the end of the response (persistent | |
1393 | * connections and such) | |
1394 | */ | |
e6ccf245 | 1395 | void |
2afaba07 | 1396 | HttpStateData::processReplyBody() |
e6ccf245 | 1397 | { |
b7ac5457 | 1398 | Ip::Address client_addr; |
d67acb4e | 1399 | bool ispinned = false; |
fc68f6b1 | 1400 | |
1a98175f | 1401 | if (!flags.headers_parsed) { |
46f4b111 | 1402 | flags.do_next_read = true; |
5f8252d2 | 1403 | maybeReadVirginBody(); |
62e76326 | 1404 | return; |
528b2c61 | 1405 | } |
62e76326 | 1406 | |
a83c6ed6 | 1407 | #if USE_ADAPTATION |
c30ac6ea | 1408 | debugs(11,5, HERE << "adaptationAccessCheckPending=" << adaptationAccessCheckPending); |
a83c6ed6 | 1409 | if (adaptationAccessCheckPending) |
2afaba07 | 1410 | return; |
fc68f6b1 | 1411 | |
2afaba07 | 1412 | #endif |
62e76326 | 1413 | |
2afaba07 | 1414 | /* |
1415 | * At this point the reply headers have been parsed and consumed. | |
1416 | * That means header content has been removed from readBuf and | |
1417 | * it contains only body data. | |
1418 | */ | |
ef85ab2f DK |
1419 | if (entry->isAccepting()) { |
1420 | if (flags.chunked) { | |
1421 | if (!decodeAndWriteReplyBody()) { | |
46f4b111 | 1422 | flags.do_next_read = false; |
ef85ab2f DK |
1423 | serverComplete(); |
1424 | return; | |
1425 | } | |
1426 | } else | |
1427 | writeReplyBody(); | |
1428 | } | |
528b2c61 | 1429 | |
abf396ec AR |
1430 | // storing/sending methods like earlier adaptOrFinalizeReply() or |
1431 | // above writeReplyBody() may release/abort the store entry. | |
e6ccf245 | 1432 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { |
abf396ec AR |
1433 | // TODO: In some cases (e.g., 304), we should keep persistent conn open. |
1434 | // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP). | |
6dd9a2e4 AJ |
1435 | abortTransaction("store entry aborted while storing reply"); |
1436 | return; | |
62e76326 | 1437 | } else |
1438 | switch (persistentConnStatus()) { | |
dc49061a | 1439 | case INCOMPLETE_MSG: { |
3e4bebf8 | 1440 | debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection); |
21b92762 | 1441 | /* Wait for more data or EOF condition */ |
8d77a37c | 1442 | AsyncCall::Pointer nil; |
21b92762 | 1443 | if (flags.keepalive_broken) { |
8d77a37c | 1444 | commSetConnTimeout(serverConnection, 10, nil); |
21b92762 | 1445 | } else { |
8d77a37c | 1446 | commSetConnTimeout(serverConnection, Config.Timeout.read, nil); |
21b92762 | 1447 | } |
1448 | ||
46f4b111 | 1449 | flags.do_next_read = true; |
dc49061a A |
1450 | } |
1451 | break; | |
62e76326 | 1452 | |
1453 | case COMPLETE_PERSISTENT_MSG: | |
3e4bebf8 | 1454 | debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection); |
62e76326 | 1455 | /* yes we have to clear all these! */ |
8d77a37c | 1456 | commUnsetConnTimeout(serverConnection); |
46f4b111 | 1457 | flags.do_next_read = false; |
62e76326 | 1458 | |
8d71285d | 1459 | comm_remove_close_handler(serverConnection->fd, closeHandler); |
dc56a9b1 | 1460 | closeHandler = NULL; |
8d71285d | 1461 | fwd->unregister(serverConnection); |
fc68f6b1 | 1462 | |
450fe1cb | 1463 | if (request->flags.spoofClientIp) |
e24f13cd | 1464 | client_addr = request->client_addr; |
fc68f6b1 | 1465 | |
45e5102d | 1466 | if (request->flags.pinned) { |
9e008dda | 1467 | ispinned = true; |
450fe1cb | 1468 | } else if (request->flags.connectionAuth && request->flags.authSent) { |
9e008dda AJ |
1469 | ispinned = true; |
1470 | } | |
1471 | ||
abbd1c5d | 1472 | if (ispinned && request->clientConnectionManager.valid()) { |
d603e3c2 | 1473 | request->clientConnectionManager->pinConnection(serverConnection, request.getRaw(), _peer, |
e857372a | 1474 | (request->flags.connectionAuth)); |
bd0723ad | 1475 | } else { |
5c51bffb | 1476 | fwd->pconnPush(serverConnection, request->url.host()); |
bd0723ad | 1477 | } |
1478 | ||
8d71285d | 1479 | serverConnection = NULL; |
5f8252d2 | 1480 | serverComplete(); |
62e76326 | 1481 | return; |
1482 | ||
1483 | case COMPLETE_NONPERSISTENT_MSG: | |
3e4bebf8 | 1484 | debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection); |
5f8252d2 | 1485 | serverComplete(); |
62e76326 | 1486 | return; |
1487 | } | |
1488 | ||
5f8252d2 | 1489 | maybeReadVirginBody(); |
c4b7a5a9 | 1490 | } |
1491 | ||
aea65fec AR |
1492 | bool |
1493 | HttpStateData::mayReadVirginReplyBody() const | |
1494 | { | |
1495 | // TODO: Be more precise here. For example, if/when reading trailer, we may | |
1496 | // not be doneWithServer() yet, but we should return false. Similarly, we | |
1497 | // could still be writing the request body after receiving the whole reply. | |
1498 | return !doneWithServer(); | |
1499 | } | |
1500 | ||
c4b7a5a9 | 1501 | void |
5f8252d2 | 1502 | HttpStateData::maybeReadVirginBody() |
c4b7a5a9 | 1503 | { |
85bef0a7 AR |
1504 | // too late to read |
1505 | if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing()) | |
1506 | return; | |
1507 | ||
1ad68518 AJ |
1508 | if (!maybeMakeSpaceAvailable(false)) |
1509 | return; | |
1510 | ||
1511 | // XXX: get rid of the do_next_read flag | |
1512 | // check for the proper reasons preventing read(2) | |
1513 | if (!flags.do_next_read) | |
1514 | return; | |
1515 | ||
1516 | flags.do_next_read = false; | |
1517 | ||
1518 | // must not already be waiting for read(2) ... | |
1519 | assert(!Comm::MonitorsRead(serverConnection->fd)); | |
1520 | ||
1521 | // wait for read(2) to be possible. | |
1522 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
1523 | AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply); | |
1524 | Comm::Read(serverConnection, call); | |
1525 | } | |
1526 | ||
1527 | bool | |
1528 | HttpStateData::maybeMakeSpaceAvailable(bool doGrow) | |
1529 | { | |
57912702 AJ |
1530 | // how much we are allowed to buffer |
1531 | const int limitBuffer = (flags.headers_parsed ? Config.readAheadGap : Config.maxReplyHeaderSize); | |
2afaba07 | 1532 | |
57912702 AJ |
1533 | if (limitBuffer < 0 || inBuf.length() >= (SBuf::size_type)limitBuffer) { |
1534 | // when buffer is at or over limit already | |
1535 | debugs(11, 7, "wont read up to " << limitBuffer << ". buffer has (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection); | |
1536 | debugs(11, DBG_DATA, "buffer has {" << inBuf << "}"); | |
1537 | // Process next response from buffer | |
1538 | processReply(); | |
1ad68518 | 1539 | return false; |
57912702 AJ |
1540 | } |
1541 | ||
1542 | // how much we want to read | |
5867ac79 | 1543 | const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), (limitBuffer - inBuf.length())); |
57912702 | 1544 | |
5867ac79 | 1545 | if (!read_size) { |
57912702 | 1546 | debugs(11, 7, "wont read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection); |
1ad68518 | 1547 | return false; |
57912702 AJ |
1548 | } |
1549 | ||
1ad68518 AJ |
1550 | // just report whether we could grow or not, dont actually do it |
1551 | if (doGrow) | |
1552 | return (read_size >= 2); | |
1553 | ||
57912702 AJ |
1554 | // we may need to grow the buffer |
1555 | inBuf.reserveSpace(read_size); | |
1556 | debugs(11, 8, (!flags.do_next_read ? "wont" : "may") << | |
1557 | " read up to " << read_size << " bytes info buf(" << inBuf.length() << "/" << inBuf.spaceSize() << | |
1558 | ") from " << serverConnection); | |
2afaba07 | 1559 | |
1ad68518 | 1560 | return (inBuf.spaceSize() >= 2); // only read if there is 1+ bytes of space available |
090089c4 | 1561 | } |
1562 | ||
39cb8c41 | 1563 | /// called after writing the very last request byte (body, last-chunk, etc) |
d576a6a6 | 1564 | void |
39cb8c41 | 1565 | HttpStateData::wroteLast(const CommIoCbParams &io) |
090089c4 | 1566 | { |
9cf7de1b | 1567 | debugs(11, 5, HERE << serverConnection << ": size " << io.size << ": errflag " << io.flag << "."); |
bc87dc25 | 1568 | #if URL_CHECKSUM_DEBUG |
62e76326 | 1569 | |
528b2c61 | 1570 | entry->mem_obj->checkUrlChecksum(); |
bc87dc25 | 1571 | #endif |
62e76326 | 1572 | |
dc56a9b1 | 1573 | if (io.size > 0) { |
49ae8b95 | 1574 | fd_bytes(io.fd, io.size, FD_WRITE); |
a0864754 AJ |
1575 | statCounter.server.all.kbytes_out += io.size; |
1576 | statCounter.server.http.kbytes_out += io.size; | |
ee1679df | 1577 | } |
62e76326 | 1578 | |
c8407295 | 1579 | if (io.flag == Comm::ERR_CLOSING) |
62e76326 | 1580 | return; |
1581 | ||
dc56a9b1 | 1582 | if (io.flag) { |
955394ce | 1583 | ErrorState *err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request); |
dc56a9b1 | 1584 | err->xerrno = io.xerrno; |
1585 | fwd->fail(err); | |
398bc066 CT |
1586 | closeServer(); |
1587 | mustStop("HttpStateData::wroteLast"); | |
62e76326 | 1588 | return; |
090089c4 | 1589 | } |
72b63f06 | 1590 | |
39cb8c41 AR |
1591 | sendComplete(); |
1592 | } | |
1593 | ||
1594 | /// successfully wrote the entire request (including body, last-chunk, etc.) | |
1595 | void | |
1596 | HttpStateData::sendComplete() | |
1597 | { | |
2afaba07 | 1598 | /* |
1599 | * Set the read timeout here because it hasn't been set yet. | |
1600 | * We only set the read timeout after the request has been | |
d5430dc8 | 1601 | * fully written to the peer. If we start the timeout |
2afaba07 | 1602 | * after connection establishment, then we are likely to hit |
1603 | * the timeout for POST/PUT requests that have very large | |
1604 | * request bodies. | |
1605 | */ | |
dc56a9b1 | 1606 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 1607 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, |
4cb2536f | 1608 | TimeoutDialer, this, HttpStateData::httpTimeout); |
2afaba07 | 1609 | |
8d77a37c | 1610 | commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall); |
46f4b111 | 1611 | flags.request_sent = true; |
e24f13cd | 1612 | request->hier.peer_http_request_sent = current_time; |
090089c4 | 1613 | } |
1614 | ||
2afaba07 | 1615 | void |
5f8252d2 | 1616 | HttpStateData::closeServer() |
2afaba07 | 1617 | { |
9cf7de1b | 1618 | debugs(11,5, HERE << "closing HTTP server " << serverConnection << " this " << this); |
fc68f6b1 | 1619 | |
9cf7de1b | 1620 | if (Comm::IsConnOpen(serverConnection)) { |
8d71285d AJ |
1621 | fwd->unregister(serverConnection); |
1622 | comm_remove_close_handler(serverConnection->fd, closeHandler); | |
dc56a9b1 | 1623 | closeHandler = NULL; |
8d71285d | 1624 | serverConnection->close(); |
2afaba07 | 1625 | } |
5f8252d2 | 1626 | } |
2afaba07 | 1627 | |
5f8252d2 | 1628 | bool |
1629 | HttpStateData::doneWithServer() const | |
1630 | { | |
9cf7de1b | 1631 | return !Comm::IsConnOpen(serverConnection); |
2afaba07 | 1632 | } |
1633 | ||
ee0b94f4 HN |
1634 | /* |
1635 | * Fixup authentication request headers for special cases | |
1636 | */ | |
1637 | static void | |
bad9c5e4 | 1638 | httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const Http::StateFlags &flags) |
ee0b94f4 | 1639 | { |
789217a2 | 1640 | Http::HdrType header = flags.originpeer ? Http::HdrType::AUTHORIZATION : Http::HdrType::PROXY_AUTHORIZATION; |
ee0b94f4 HN |
1641 | |
1642 | /* Nothing to do unless we are forwarding to a peer */ | |
45e5102d | 1643 | if (!request->flags.proxying) |
f54f527e | 1644 | return; |
ee0b94f4 HN |
1645 | |
1646 | /* Needs to be explicitly enabled */ | |
e24f13cd | 1647 | if (!request->peer_login) |
f54f527e | 1648 | return; |
ee0b94f4 HN |
1649 | |
1650 | /* Maybe already dealt with? */ | |
1651 | if (hdr_out->has(header)) | |
f54f527e | 1652 | return; |
ee0b94f4 HN |
1653 | |
1654 | /* Nothing to do here for PASSTHRU */ | |
e24f13cd | 1655 | if (strcmp(request->peer_login, "PASSTHRU") == 0) |
f54f527e | 1656 | return; |
ee0b94f4 HN |
1657 | |
1658 | /* PROXYPASS is a special case, single-signon to servers with the proxy password (basic only) */ | |
789217a2 FC |
1659 | if (flags.originpeer && strcmp(request->peer_login, "PROXYPASS") == 0 && hdr_in->has(Http::HdrType::PROXY_AUTHORIZATION)) { |
1660 | const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION); | |
ee0b94f4 | 1661 | |
f54f527e AJ |
1662 | if (auth && strncasecmp(auth, "basic ", 6) == 0) { |
1663 | hdr_out->putStr(header, auth); | |
1664 | return; | |
1665 | } | |
ee0b94f4 HN |
1666 | } |
1667 | ||
aadbbd7d AJ |
1668 | uint8_t loginbuf[base64_encode_len(MAX_LOGIN_SZ)]; |
1669 | size_t blen; | |
1670 | struct base64_encode_ctx ctx; | |
1671 | base64_encode_init(&ctx); | |
1672 | ||
ee0b94f4 | 1673 | /* Special mode to pass the username to the upstream cache */ |
e24f13cd | 1674 | if (*request->peer_login == '*') { |
f54f527e | 1675 | const char *username = "-"; |
ee0b94f4 | 1676 | |
e24f13cd CT |
1677 | if (request->extacl_user.size()) |
1678 | username = request->extacl_user.termedBuf(); | |
2f1431ea | 1679 | #if USE_AUTH |
e24f13cd CT |
1680 | else if (request->auth_user_request != NULL) |
1681 | username = request->auth_user_request->username(); | |
2f1431ea | 1682 | #endif |
ee0b94f4 | 1683 | |
aadbbd7d AJ |
1684 | blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username)); |
1685 | blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1)); | |
1686 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1687 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
f54f527e | 1688 | return; |
ee0b94f4 HN |
1689 | } |
1690 | ||
1691 | /* external_acl provided credentials */ | |
e24f13cd CT |
1692 | if (request->extacl_user.size() && request->extacl_passwd.size() && |
1693 | (strcmp(request->peer_login, "PASS") == 0 || | |
1694 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
aadbbd7d AJ |
1695 | |
1696 | blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf())); | |
1697 | blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":")); | |
1698 | blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf())); | |
1699 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1700 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
f54f527e | 1701 | return; |
ee0b94f4 | 1702 | } |
8fdaa8af AJ |
1703 | // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU |
1704 | if (strcmp(request->peer_login, "PASS") == 0) | |
28204b3b | 1705 | return; |
ee0b94f4 | 1706 | |
9ca29d23 | 1707 | /* Kerberos login to peer */ |
2f1431ea | 1708 | #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI |
e24f13cd | 1709 | if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) { |
9ca29d23 AJ |
1710 | char *Token=NULL; |
1711 | char *PrincipalName=NULL,*p; | |
9825b398 AJ |
1712 | int negotiate_flags = 0; |
1713 | ||
e24f13cd | 1714 | if ((p=strchr(request->peer_login,':')) != NULL ) { |
9ca29d23 AJ |
1715 | PrincipalName=++p; |
1716 | } | |
9825b398 AJ |
1717 | if (request->flags.auth_no_keytab) { |
1718 | negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB; | |
1719 | } | |
1720 | Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags); | |
9ca29d23 | 1721 | if (Token) { |
63f03f79 | 1722 | httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token); |
9ca29d23 AJ |
1723 | } |
1724 | return; | |
1725 | } | |
1726 | #endif /* HAVE_KRB5 && HAVE_GSSAPI */ | |
1727 | ||
aadbbd7d AJ |
1728 | blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login)); |
1729 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1730 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
ee0b94f4 HN |
1731 | return; |
1732 | } | |
1733 | ||
99edd1c3 | 1734 | /* |
9e008dda | 1735 | * build request headers and append them to a given MemBuf |
e5ee81f0 | 1736 | * used by buildRequestPrefix() |
818c6c9e | 1737 | * note: initialised the HttpHeader, the caller is responsible for Clean()-ing |
99edd1c3 | 1738 | */ |
e1e72f06 | 1739 | void |
e5ee81f0 | 1740 | HttpStateData::httpBuildRequestHeader(HttpRequest * request, |
e5ee81f0 | 1741 | StoreEntry * entry, |
4bf68cfa | 1742 | const AccessLogEntryPointer &al, |
e5ee81f0 | 1743 | HttpHeader * hdr_out, |
bad9c5e4 | 1744 | const Http::StateFlags &flags) |
6bf8443a | 1745 | { |
99edd1c3 | 1746 | /* building buffer for complex strings */ |
5999b776 | 1747 | #define BBUF_SZ (MAX_URL+32) |
99edd1c3 | 1748 | LOCAL_ARRAY(char, bbuf, BBUF_SZ); |
67c06f0d | 1749 | LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN); |
e24f13cd | 1750 | const HttpHeader *hdr_in = &request->header; |
67c06f0d | 1751 | const HttpHeaderEntry *e = NULL; |
99edd1c3 | 1752 | HttpHeaderPos pos = HttpHeaderInitPos; |
75faaa7a | 1753 | assert (hdr_out->owner == hoRequest); |
62e76326 | 1754 | |
46017fdd | 1755 | /* use our IMS header if the cached entry has Last-Modified time */ |
fa3e249f | 1756 | if (request->lastmod > -1) |
789217a2 | 1757 | hdr_out->putTime(Http::HdrType::IF_MODIFIED_SINCE, request->lastmod); |
99edd1c3 | 1758 | |
46017fdd CT |
1759 | // Add our own If-None-Match field if the cached entry has a strong ETag. |
1760 | // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones. | |
b38b26cb | 1761 | if (request->etag.size() > 0) { |
d5f18517 | 1762 | hdr_out->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH, SBuf(), |
7f754be8 | 1763 | request->etag.termedBuf())); |
46017fdd CT |
1764 | } |
1765 | ||
e24f13cd | 1766 | bool we_do_ranges = decideIfWeDoRanges (request); |
528b2c61 | 1767 | |
789217a2 | 1768 | String strConnection (hdr_in->getList(Http::HdrType::CONNECTION)); |
62e76326 | 1769 | |
a9925b40 | 1770 | while ((e = hdr_in->getEntry(&pos))) |
e24f13cd | 1771 | copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags); |
528b2c61 | 1772 | |
43ae1d95 | 1773 | /* Abstraction break: We should interpret multipart/byterange responses |
528b2c61 | 1774 | * into offset-length data, and this works around our inability to do so. |
1775 | */ | |
e24f13cd | 1776 | if (!we_do_ranges && request->multipartRangeRequest()) { |
62e76326 | 1777 | /* don't cache the result */ |
e857372a | 1778 | request->flags.cachable = false; |
62e76326 | 1779 | /* pretend it's not a range request */ |
f0baf149 | 1780 | request->ignoreRange("want to request the whole object"); |
e857372a | 1781 | request->flags.isRanged = false; |
62e76326 | 1782 | } |
528b2c61 | 1783 | |
90be6ff5 | 1784 | hdr_out->addVia(request->http_ver, hdr_in); |
62e76326 | 1785 | |
45e5102d | 1786 | if (request->flags.accelerated) { |
43ae1d95 | 1787 | /* Append Surrogate-Capabilities */ |
789217a2 | 1788 | String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY)); |
45cca89d AJ |
1789 | #if USE_SQUID_ESI |
1790 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id); | |
1791 | #else | |
1792 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id); | |
1793 | #endif | |
43ae1d95 | 1794 | strListAdd(&strSurrogate, bbuf, ','); |
789217a2 | 1795 | hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf()); |
43ae1d95 | 1796 | } |
43ae1d95 | 1797 | |
67c06f0d | 1798 | /** \pre Handle X-Forwarded-For */ |
9e008dda | 1799 | if (strcmp(opt_forwarded_for, "delete") != 0) { |
c4f30223 | 1800 | |
789217a2 | 1801 | String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR); |
c4f30223 | 1802 | |
70df76e3 AR |
1803 | // if we cannot double strFwd size, then it grew past 50% of the limit |
1804 | if (!strFwd.canGrowBy(strFwd.size())) { | |
c4f30223 AR |
1805 | // There is probably a forwarding loop with Via detection disabled. |
1806 | // If we do nothing, String will assert on overflow soon. | |
1807 | // TODO: Terminate all transactions with huge XFF? | |
1808 | strFwd = "error"; | |
1809 | ||
1810 | static int warnedCount = 0; | |
1811 | if (warnedCount++ < 100) { | |
851feda6 | 1812 | const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri()); |
e0236918 | 1813 | debugs(11, DBG_IMPORTANT, "Warning: likely forwarding loop with " << url); |
c4f30223 AR |
1814 | } |
1815 | } | |
1816 | ||
9e008dda | 1817 | if (strcmp(opt_forwarded_for, "on") == 0) { |
67c06f0d | 1818 | /** If set to ON - append client IP or 'unknown'. */ |
4dd643d5 | 1819 | if ( request->client_addr.isNoAddr() ) |
67c06f0d AJ |
1820 | strListAdd(&strFwd, "unknown", ','); |
1821 | else | |
4dd643d5 | 1822 | strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ','); |
9e008dda | 1823 | } else if (strcmp(opt_forwarded_for, "off") == 0) { |
67c06f0d | 1824 | /** If set to OFF - append 'unknown'. */ |
67c06f0d | 1825 | strListAdd(&strFwd, "unknown", ','); |
9e008dda | 1826 | } else if (strcmp(opt_forwarded_for, "transparent") == 0) { |
67c06f0d | 1827 | /** If set to TRANSPARENT - pass through unchanged. */ |
9e008dda | 1828 | } else if (strcmp(opt_forwarded_for, "truncate") == 0) { |
67c06f0d | 1829 | /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */ |
4dd643d5 | 1830 | if ( request->client_addr.isNoAddr() ) |
67c06f0d AJ |
1831 | strFwd = "unknown"; |
1832 | else | |
4dd643d5 | 1833 | strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN); |
67c06f0d | 1834 | } |
9e008dda | 1835 | if (strFwd.size() > 0) |
789217a2 | 1836 | hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf()); |
cc192b50 | 1837 | } |
67c06f0d | 1838 | /** If set to DELETE - do not copy through. */ |
6bccf575 | 1839 | |
99edd1c3 | 1840 | /* append Host if not there already */ |
789217a2 | 1841 | if (!hdr_out->has(Http::HdrType::HOST)) { |
e24f13cd | 1842 | if (request->peer_domain) { |
789217a2 | 1843 | hdr_out->putStr(Http::HdrType::HOST, request->peer_domain); |
62e76326 | 1844 | } else { |
5c51bffb | 1845 | SBuf authority = request->url.authority(); |
789217a2 | 1846 | hdr_out->putStr(Http::HdrType::HOST, authority.c_str()); |
62e76326 | 1847 | } |
6bf8443a | 1848 | } |
62e76326 | 1849 | |
c68e9c6b | 1850 | /* append Authorization if known in URL, not in header and going direct */ |
789217a2 | 1851 | if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) { |
92d6986d | 1852 | if (!request->flags.proxying && !request->url.userInfo().isEmpty()) { |
aadbbd7d AJ |
1853 | static uint8_t result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment |
1854 | struct base64_encode_ctx ctx; | |
1855 | base64_encode_init(&ctx); | |
1856 | size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent())); | |
1857 | blen += base64_encode_final(&ctx, result+blen); | |
1858 | result[blen] = '\0'; | |
1859 | if (blen) | |
789217a2 | 1860 | httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result); |
62e76326 | 1861 | } |
c68e9c6b | 1862 | } |
62e76326 | 1863 | |
ee0b94f4 | 1864 | /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */ |
e24f13cd | 1865 | httpFixupAuthentication(request, hdr_in, hdr_out, flags); |
62e76326 | 1866 | |
ee0b94f4 HN |
1867 | /* append Cache-Control, add max-age if not there already */ |
1868 | { | |
a9925b40 | 1869 | HttpHdrCc *cc = hdr_in->getCc(); |
62e76326 | 1870 | |
1871 | if (!cc) | |
a4a03b37 | 1872 | cc = new HttpHdrCc(); |
62e76326 | 1873 | |
7dc5c309 AJ |
1874 | #if 0 /* see bug 2330 */ |
1875 | /* Set no-cache if determined needed but not found */ | |
e24f13cd | 1876 | if (request->flags.nocache) |
1da82544 | 1877 | EBIT_SET(cc->mask, HttpHdrCcType::CC_NO_CACHE); |
7dc5c309 AJ |
1878 | #endif |
1879 | ||
af6a12ee | 1880 | /* Add max-age only without no-cache */ |
1259f9cf | 1881 | if (!cc->hasMaxAge() && !cc->hasNoCache()) { |
851feda6 AJ |
1882 | // XXX: performance regression. c_str() reallocates |
1883 | SBuf tmp(request->effectiveRequestUri()); | |
1884 | cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str())); | |
62e76326 | 1885 | } |
1886 | ||
ce2d6441 | 1887 | /* Enforce sibling relations */ |
62e76326 | 1888 | if (flags.only_if_cached) |
4ce6e3b5 | 1889 | cc->onlyIfCached(true); |
62e76326 | 1890 | |
a9925b40 | 1891 | hdr_out->putCc(cc); |
62e76326 | 1892 | |
3d7782c1 | 1893 | delete cc; |
6bf8443a | 1894 | } |
62e76326 | 1895 | |
99edd1c3 | 1896 | /* maybe append Connection: keep-alive */ |
b515fc11 | 1897 | if (flags.keepalive) { |
789217a2 | 1898 | hdr_out->putStr(Http::HdrType::CONNECTION, "keep-alive"); |
603a02fd | 1899 | } |
62e76326 | 1900 | |
a7ad6e4e | 1901 | /* append Front-End-Https */ |
1902 | if (flags.front_end_https) { | |
4e3f4dc7 | 1903 | if (flags.front_end_https == 1 || request->url.getScheme() == AnyP::PROTO_HTTPS) |
789217a2 | 1904 | hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On"); |
a7ad6e4e | 1905 | } |
1906 | ||
e31a1e67 AR |
1907 | if (flags.chunked_request) { |
1908 | // Do not just copy the original value so that if the client-side | |
1909 | // starts decode other encodings, this code may remain valid. | |
789217a2 | 1910 | hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked"); |
39cb8c41 AR |
1911 | } |
1912 | ||
6bccf575 | 1913 | /* Now mangle the headers. */ |
cde8f31b | 1914 | httpHdrMangleList(hdr_out, request, al, ROR_REQUEST); |
f4698e0b | 1915 | |
30abd221 | 1916 | strConnection.clean(); |
99edd1c3 | 1917 | } |
1918 | ||
9e498bfb AJ |
1919 | /** |
1920 | * Decides whether a particular header may be cloned from the received Clients request | |
1921 | * to our outgoing fetch request. | |
1922 | */ | |
528b2c61 | 1923 | void |
bad9c5e4 | 1924 | copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &flags) |
528b2c61 | 1925 | { |
e8466ea9 | 1926 | debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value ); |
62e76326 | 1927 | |
528b2c61 | 1928 | switch (e->id) { |
62e76326 | 1929 | |
f53969cc | 1930 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */ |
9e498bfb | 1931 | |
789217a2 | 1932 | case Http::HdrType::PROXY_AUTHORIZATION: |
9e498bfb AJ |
1933 | /** \par Proxy-Authorization: |
1934 | * Only pass on proxy authentication to peers for which | |
62e76326 | 1935 | * authentication forwarding is explicitly enabled |
1936 | */ | |
e24f13cd CT |
1937 | if (!flags.originpeer && flags.proxying && request->peer_login && |
1938 | (strcmp(request->peer_login, "PASS") == 0 || | |
1939 | strcmp(request->peer_login, "PROXYPASS") == 0 || | |
1940 | strcmp(request->peer_login, "PASSTHRU") == 0)) { | |
eede25e7 | 1941 | hdr_out->addEntry(e->clone()); |
62e76326 | 1942 | } |
62e76326 | 1943 | break; |
1944 | ||
f53969cc | 1945 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */ |
9e498bfb | 1946 | |
789217a2 FC |
1947 | case Http::HdrType::CONNECTION: /** \par Connection: */ |
1948 | case Http::HdrType::TE: /** \par TE: */ | |
1949 | case Http::HdrType::KEEP_ALIVE: /** \par Keep-Alive: */ | |
1950 | case Http::HdrType::PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */ | |
1951 | case Http::HdrType::TRAILER: /** \par Trailer: */ | |
1952 | case Http::HdrType::UPGRADE: /** \par Upgrade: */ | |
1953 | case Http::HdrType::TRANSFER_ENCODING: /** \par Transfer-Encoding: */ | |
9e498bfb AJ |
1954 | break; |
1955 | ||
f53969cc | 1956 | /** \par OTHER headers I haven't bothered to track down yet. */ |
9e498bfb | 1957 | |
789217a2 | 1958 | case Http::HdrType::AUTHORIZATION: |
9e498bfb AJ |
1959 | /** \par WWW-Authorization: |
1960 | * Pass on WWW authentication */ | |
62e76326 | 1961 | |
1962 | if (!flags.originpeer) { | |
eede25e7 | 1963 | hdr_out->addEntry(e->clone()); |
62e76326 | 1964 | } else { |
9e498bfb | 1965 | /** \note In accelerators, only forward authentication if enabled |
ee0b94f4 | 1966 | * (see also httpFixupAuthentication for special cases) |
62e76326 | 1967 | */ |
e24f13cd CT |
1968 | if (request->peer_login && |
1969 | (strcmp(request->peer_login, "PASS") == 0 || | |
1970 | strcmp(request->peer_login, "PASSTHRU") == 0 || | |
1971 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
eede25e7 | 1972 | hdr_out->addEntry(e->clone()); |
62e76326 | 1973 | } |
1974 | } | |
1975 | ||
1976 | break; | |
1977 | ||
789217a2 | 1978 | case Http::HdrType::HOST: |
9e498bfb | 1979 | /** \par Host: |
b883b594 | 1980 | * Normally Squid rewrites the Host: header. |
1981 | * However, there is one case when we don't: If the URL | |
62e76326 | 1982 | * went through our redirector and the admin configured |
1983 | * 'redir_rewrites_host' to be off. | |
1984 | */ | |
e24f13cd | 1985 | if (request->peer_domain) |
789217a2 | 1986 | hdr_out->putStr(Http::HdrType::HOST, request->peer_domain); |
45e5102d | 1987 | else if (request->flags.redirected && !Config.onoff.redir_rewrites_host) |
eede25e7 | 1988 | hdr_out->addEntry(e->clone()); |
b883b594 | 1989 | else { |
5c51bffb | 1990 | SBuf authority = request->url.authority(); |
789217a2 | 1991 | hdr_out->putStr(Http::HdrType::HOST, authority.c_str()); |
b883b594 | 1992 | } |
62e76326 | 1993 | |
1994 | break; | |
1995 | ||
789217a2 | 1996 | case Http::HdrType::IF_MODIFIED_SINCE: |
9e498bfb | 1997 | /** \par If-Modified-Since: |
96598f93 AJ |
1998 | * append unless we added our own, |
1999 | * but only if cache_miss_revalidate is enabled, or | |
2000 | * the request is not cacheable, or | |
2001 | * the request contains authentication credentials. | |
2002 | * \note at most one client's If-Modified-Since header can pass through | |
2003 | */ | |
2004 | // XXX: need to check and cleanup the auth case so cacheable auth requests get cached. | |
789217a2 | 2005 | if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE)) |
96598f93 AJ |
2006 | break; |
2007 | else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth) | |
eede25e7 | 2008 | hdr_out->addEntry(e->clone()); |
96598f93 | 2009 | break; |
62e76326 | 2010 | |
789217a2 | 2011 | case Http::HdrType::IF_NONE_MATCH: |
96598f93 AJ |
2012 | /** \par If-None-Match: |
2013 | * append if the wildcard '*' special case value is present, or | |
2014 | * cache_miss_revalidate is disabled, or | |
2015 | * the request is not cacheable in this proxy, or | |
2016 | * the request contains authentication credentials. | |
2017 | * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set. | |
2018 | */ | |
2019 | // XXX: need to check and cleanup the auth case so cacheable auth requests get cached. | |
789217a2 | 2020 | if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth) |
eede25e7 | 2021 | hdr_out->addEntry(e->clone()); |
62e76326 | 2022 | break; |
2023 | ||
789217a2 | 2024 | case Http::HdrType::MAX_FORWARDS: |
9e498bfb | 2025 | /** \par Max-Forwards: |
fc90edc3 | 2026 | * pass only on TRACE or OPTIONS requests */ |
c2a7cefd | 2027 | if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) { |
fc90edc3 | 2028 | const int64_t hops = e->getInt64(); |
62e76326 | 2029 | |
2030 | if (hops > 0) | |
789217a2 | 2031 | hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1); |
62e76326 | 2032 | } |
2033 | ||
2034 | break; | |
2035 | ||
789217a2 | 2036 | case Http::HdrType::VIA: |
9e498bfb AJ |
2037 | /** \par Via: |
2038 | * If Via is disabled then forward any received header as-is. | |
2039 | * Otherwise leave for explicit updated addition later. */ | |
62e76326 | 2040 | |
2041 | if (!Config.onoff.via) | |
eede25e7 | 2042 | hdr_out->addEntry(e->clone()); |
62e76326 | 2043 | |
2044 | break; | |
2045 | ||
789217a2 | 2046 | case Http::HdrType::RANGE: |
62e76326 | 2047 | |
789217a2 | 2048 | case Http::HdrType::IF_RANGE: |
62e76326 | 2049 | |
789217a2 | 2050 | case Http::HdrType::REQUEST_RANGE: |
9e498bfb AJ |
2051 | /** \par Range:, If-Range:, Request-Range: |
2052 | * Only pass if we accept ranges */ | |
62e76326 | 2053 | if (!we_do_ranges) |
eede25e7 | 2054 | hdr_out->addEntry(e->clone()); |
62e76326 | 2055 | |
2056 | break; | |
2057 | ||
789217a2 | 2058 | case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things. |
95e78500 | 2059 | break; |
62e76326 | 2060 | |
789217a2 | 2061 | case Http::HdrType::CONTENT_LENGTH: |
f228d6f6 AR |
2062 | // pass through unless we chunk; also, keeping this away from default |
2063 | // prevents request smuggling via Connection: Content-Length tricks | |
2064 | if (!flags.chunked_request) | |
2065 | hdr_out->addEntry(e->clone()); | |
2066 | break; | |
2067 | ||
789217a2 | 2068 | case Http::HdrType::X_FORWARDED_FOR: |
62e76326 | 2069 | |
789217a2 | 2070 | case Http::HdrType::CACHE_CONTROL: |
95e78500 | 2071 | /** \par X-Forwarded-For:, Cache-Control: |
9e498bfb AJ |
2072 | * handled specially by Squid, so leave off for now. |
2073 | * append these after the loop if needed */ | |
62e76326 | 2074 | break; |
2075 | ||
789217a2 | 2076 | case Http::HdrType::FRONT_END_HTTPS: |
9e498bfb AJ |
2077 | /** \par Front-End-Https: |
2078 | * Pass thru only if peer is configured with front-end-https */ | |
62e76326 | 2079 | if (!flags.front_end_https) |
eede25e7 | 2080 | hdr_out->addEntry(e->clone()); |
62e76326 | 2081 | |
2082 | break; | |
2083 | ||
be753325 | 2084 | default: |
9e498bfb AJ |
2085 | /** \par default. |
2086 | * pass on all other header fields | |
2087 | * which are NOT listed by the special Connection: header. */ | |
d5f18517 | 2088 | if (strConnection.size()>0 && strListIsMember(&strConnection, e->name, ',')) { |
e1ea7456 | 2089 | debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition"); |
9e498bfb AJ |
2090 | return; |
2091 | } | |
2092 | ||
eede25e7 | 2093 | hdr_out->addEntry(e->clone()); |
528b2c61 | 2094 | } |
2095 | } | |
2096 | ||
e5ee81f0 | 2097 | bool |
e24f13cd | 2098 | HttpStateData::decideIfWeDoRanges (HttpRequest * request) |
528b2c61 | 2099 | { |
e5ee81f0 | 2100 | bool result = true; |
62e76326 | 2101 | /* decide if we want to do Ranges ourselves |
2102 | * and fetch the whole object now) | |
2103 | * We want to handle Ranges ourselves iff | |
2104 | * - we can actually parse client Range specs | |
2105 | * - the specs are expected to be simple enough (e.g. no out-of-order ranges) | |
2106 | * - reply will be cachable | |
2107 | * (If the reply will be uncachable we have to throw it away after | |
2108 | * serving this request, so it is better to forward ranges to | |
2109 | * the server and fetch only the requested content) | |
2110 | */ | |
2111 | ||
e24f13cd | 2112 | int64_t roffLimit = request->getRangeOffsetLimit(); |
11e3fa1c | 2113 | |
45e5102d | 2114 | if (NULL == request->range || !request->flags.cachable |
450fe1cb | 2115 | || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth) |
e5ee81f0 | 2116 | result = false; |
62e76326 | 2117 | |
9e008dda | 2118 | debugs(11, 8, "decideIfWeDoRanges: range specs: " << |
e24f13cd | 2119 | request->range << ", cachable: " << |
45e5102d | 2120 | request->flags.cachable << "; we_do_ranges: " << result); |
62e76326 | 2121 | |
2122 | return result; | |
528b2c61 | 2123 | } |
2124 | ||
62e76326 | 2125 | /* build request prefix and append it to a given MemBuf; |
99edd1c3 | 2126 | * return the length of the prefix */ |
9bc73deb | 2127 | mb_size_t |
e24f13cd | 2128 | HttpStateData::buildRequestPrefix(MemBuf * mb) |
99edd1c3 | 2129 | { |
2130 | const int offset = mb->size; | |
2592bc70 | 2131 | /* Uses a local httpver variable to print the HTTP label |
526ed14e AJ |
2132 | * since the HttpRequest may have an older version label. |
2133 | * XXX: This could create protocol bugs as the headers sent and | |
2134 | * flow control should all be based on the HttpRequest version | |
2135 | * not the one we are sending. Needs checking. | |
2136 | */ | |
2592bc70 | 2137 | const AnyP::ProtocolVersion httpver = Http::ProtocolVersion(); |
851feda6 | 2138 | const SBuf url(_peer && !_peer->options.originserver ? request->effectiveRequestUri() : request->url.path()); |
51b5dcf5 | 2139 | mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n", |
4391cd15 | 2140 | SQUIDSBUFPRINT(request->method.image()), |
51b5dcf5 | 2141 | SQUIDSBUFPRINT(url), |
4391cd15 AJ |
2142 | AnyP::ProtocolType_str[httpver.protocol], |
2143 | httpver.major,httpver.minor); | |
99edd1c3 | 2144 | /* build and pack headers */ |
2145 | { | |
75faaa7a | 2146 | HttpHeader hdr(hoRequest); |
d603e3c2 | 2147 | httpBuildRequestHeader(request.getRaw(), entry, fwd->al, &hdr, flags); |
9e008dda | 2148 | |
450fe1cb | 2149 | if (request->flags.pinned && request->flags.connectionAuth) |
e857372a | 2150 | request->flags.authSent = true; |
789217a2 | 2151 | else if (hdr.has(Http::HdrType::AUTHORIZATION)) |
e857372a | 2152 | request->flags.authSent = true; |
d67acb4e | 2153 | |
10201568 | 2154 | hdr.packInto(mb); |
519e0948 | 2155 | hdr.clean(); |
9d9d144b | 2156 | } |
99edd1c3 | 2157 | /* append header terminator */ |
2fe7eff9 | 2158 | mb->append(crlf, 2); |
99edd1c3 | 2159 | return mb->size - offset; |
6bf8443a | 2160 | } |
62e76326 | 2161 | |
090089c4 | 2162 | /* This will be called when connect completes. Write request. */ |
5f8252d2 | 2163 | bool |
2bb867b5 | 2164 | HttpStateData::sendRequest() |
090089c4 | 2165 | { |
99edd1c3 | 2166 | MemBuf mb; |
090089c4 | 2167 | |
9cf7de1b | 2168 | debugs(11, 5, HERE << serverConnection << ", request " << request << ", this " << this << "."); |
a0297974 | 2169 | |
6b679a01 | 2170 | if (!Comm::IsConnOpen(serverConnection)) { |
9cf7de1b | 2171 | debugs(11,3, HERE << "cannot send request to closing " << serverConnection); |
a0297974 AR |
2172 | assert(closeHandler != NULL); |
2173 | return false; | |
2174 | } | |
2175 | ||
dc56a9b1 | 2176 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 2177 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, |
4cb2536f | 2178 | TimeoutDialer, this, HttpStateData::httpTimeout); |
8d77a37c | 2179 | commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall); |
46f4b111 | 2180 | flags.do_next_read = true; |
5f8252d2 | 2181 | maybeReadVirginBody(); |
2182 | ||
e24f13cd | 2183 | if (request->body_pipe != NULL) { |
123ec4de | 2184 | if (!startRequestBodyFlow()) // register to receive body data |
5f8252d2 | 2185 | return false; |
9e008dda | 2186 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
4299f876 | 2187 | requestSender = JobCallback(11,5, |
4cb2536f | 2188 | Dialer, this, HttpStateData::sentRequestBody); |
e31a1e67 AR |
2189 | |
2190 | Must(!flags.chunked_request); | |
f228d6f6 | 2191 | // use chunked encoding if we do not know the length |
e24f13cd | 2192 | if (request->content_length < 0) |
46f4b111 | 2193 | flags.chunked_request = true; |
5f8252d2 | 2194 | } else { |
2195 | assert(!requestBodySource); | |
9e008dda | 2196 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
4299f876 | 2197 | requestSender = JobCallback(11,5, |
39cb8c41 | 2198 | Dialer, this, HttpStateData::wroteLast); |
5f8252d2 | 2199 | } |
54220df8 | 2200 | |
e5656c29 AJ |
2201 | flags.originpeer = (_peer != NULL && _peer->options.originserver); |
2202 | flags.proxying = (_peer != NULL && !flags.originpeer); | |
62e76326 | 2203 | |
efb9218c | 2204 | /* |
99edd1c3 | 2205 | * Is keep-alive okay for all request methods? |
efb9218c | 2206 | */ |
450fe1cb | 2207 | if (request->flags.mustKeepalive) |
46f4b111 | 2208 | flags.keepalive = true; |
693cb033 CT |
2209 | else if (request->flags.pinned) |
2210 | flags.keepalive = request->persistent(); | |
d67acb4e | 2211 | else if (!Config.onoff.server_pconns) |
46f4b111 | 2212 | flags.keepalive = false; |
2bb867b5 | 2213 | else if (_peer == NULL) |
46f4b111 | 2214 | flags.keepalive = true; |
2bb867b5 | 2215 | else if (_peer->stats.n_keepalives_sent < 10) |
46f4b111 | 2216 | flags.keepalive = true; |
2bb867b5 | 2217 | else if ((double) _peer->stats.n_keepalives_recv / |
2218 | (double) _peer->stats.n_keepalives_sent > 0.50) | |
46f4b111 | 2219 | flags.keepalive = true; |
2bb867b5 | 2220 | |
2221 | if (_peer) { | |
2ecba5b6 | 2222 | /*The old code here was |
5c51bffb | 2223 | if (neighborType(_peer, request->url) == PEER_SIBLING && ... |
e24f13cd | 2224 | which is equivalent to: |
5c51bffb | 2225 | if (neighborType(_peer, URL()) == PEER_SIBLING && ... |
e24f13cd CT |
2226 | or better: |
2227 | if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) || | |
2228 | _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss) | |
2229 | flags.only_if_cached = 1; | |
2230 | ||
2231 | But I suppose it was a bug | |
2232 | */ | |
5c51bffb | 2233 | if (neighborType(_peer, request->url) == PEER_SIBLING && !_peer->options.allow_miss) |
46f4b111 | 2234 | flags.only_if_cached = true; |
2bb867b5 | 2235 | |
2236 | flags.front_end_https = _peer->front_end_https; | |
a7ad6e4e | 2237 | } |
62e76326 | 2238 | |
2fe7eff9 | 2239 | mb.init(); |
9ca29d23 | 2240 | request->peer_host=_peer?_peer->host:NULL; |
e24f13cd | 2241 | buildRequestPrefix(&mb); |
5f8252d2 | 2242 | |
1ce34ddd AJ |
2243 | debugs(11, 2, "HTTP Server " << serverConnection); |
2244 | debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------"); | |
2245 | ||
2246 | Comm::Write(serverConnection, &mb, requestSender); | |
5f8252d2 | 2247 | return true; |
090089c4 | 2248 | } |
b6a2f15e | 2249 | |
39cb8c41 AR |
2250 | bool |
2251 | HttpStateData::getMoreRequestBody(MemBuf &buf) | |
2252 | { | |
2253 | // parent's implementation can handle the no-encoding case | |
e31a1e67 | 2254 | if (!flags.chunked_request) |
fccd4a86 | 2255 | return Client::getMoreRequestBody(buf); |
39cb8c41 AR |
2256 | |
2257 | MemBuf raw; | |
2258 | ||
2259 | Must(requestBodySource != NULL); | |
2260 | if (!requestBodySource->getMoreData(raw)) | |
2261 | return false; // no request body bytes to chunk yet | |
2262 | ||
2263 | // optimization: pre-allocate buffer size that should be enough | |
2264 | const mb_size_t rawDataSize = raw.contentSize(); | |
2265 | // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk | |
2266 | buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity); | |
2267 | ||
4391cd15 | 2268 | buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize)); |
39cb8c41 | 2269 | buf.append(raw.content(), rawDataSize); |
4391cd15 | 2270 | buf.append("\r\n", 2); |
39cb8c41 AR |
2271 | |
2272 | Must(rawDataSize > 0); // we did not accidently created last-chunk above | |
2273 | ||
2274 | // Do not send last-chunk unless we successfully received everything | |
2275 | if (receivedWholeRequestBody) { | |
2276 | Must(!flags.sentLastChunk); | |
2277 | flags.sentLastChunk = true; | |
de48b288 | 2278 | buf.append("0\r\n\r\n", 5); |
39cb8c41 AR |
2279 | } |
2280 | ||
2281 | return true; | |
2282 | } | |
2283 | ||
910169e5 | 2284 | void |
b6b6f466 | 2285 | httpStart(FwdState *fwd) |
603a02fd | 2286 | { |
7f06a3d8 | 2287 | debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url()); |
79628299 CT |
2288 | AsyncJob::Start(new HttpStateData(fwd)); |
2289 | } | |
62e76326 | 2290 | |
79628299 CT |
2291 | void |
2292 | HttpStateData::start() | |
2293 | { | |
2294 | if (!sendRequest()) { | |
bf8fe701 | 2295 | debugs(11, 3, "httpStart: aborted"); |
79628299 | 2296 | mustStop("HttpStateData::start failed"); |
5f8252d2 | 2297 | return; |
2298 | } | |
62e76326 | 2299 | |
95dc7ff4 FC |
2300 | ++ statCounter.server.all.requests; |
2301 | ++ statCounter.server.http.requests; | |
62e76326 | 2302 | |
b6a2f15e | 2303 | /* |
2304 | * We used to set the read timeout here, but not any more. | |
2305 | * Now its set in httpSendComplete() after the full request, | |
2306 | * including request body, has been written to the server. | |
2307 | */ | |
090089c4 | 2308 | } |
2309 | ||
39cb8c41 AR |
2310 | /// if broken posts are enabled for the request, try to fix and return true |
2311 | bool | |
2312 | HttpStateData::finishingBrokenPost() | |
2bb867b5 | 2313 | { |
626096be | 2314 | #if USE_HTTP_VIOLATIONS |
39cb8c41 AR |
2315 | if (!Config.accessList.brokenPosts) { |
2316 | debugs(11, 5, HERE << "No brokenPosts list"); | |
2317 | return false; | |
2318 | } | |
a0297974 | 2319 | |
d603e3c2 | 2320 | ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest().getRaw()); |
e0f7153c | 2321 | if (ch.fastCheck() != ACCESS_ALLOWED) { |
39cb8c41 AR |
2322 | debugs(11, 5, HERE << "didn't match brokenPosts"); |
2323 | return false; | |
2324 | } | |
a0297974 | 2325 | |
9cf7de1b | 2326 | if (!Comm::IsConnOpen(serverConnection)) { |
30c48b1a | 2327 | debugs(11, 3, HERE << "ignoring broken POST for closed " << serverConnection); |
39cb8c41 AR |
2328 | assert(closeHandler != NULL); |
2329 | return true; // prevent caller from proceeding as if nothing happened | |
54220df8 | 2330 | } |
39cb8c41 | 2331 | |
30c48b1a | 2332 | debugs(11, 3, "finishingBrokenPost: fixing broken POST"); |
39cb8c41 AR |
2333 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
2334 | requestSender = JobCallback(11,5, | |
2335 | Dialer, this, HttpStateData::wroteLast); | |
b0388924 | 2336 | Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL); |
39cb8c41 AR |
2337 | return true; |
2338 | #else | |
2339 | return false; | |
626096be | 2340 | #endif /* USE_HTTP_VIOLATIONS */ |
39cb8c41 AR |
2341 | } |
2342 | ||
2343 | /// if needed, write last-chunk to end the request body and return true | |
2344 | bool | |
2345 | HttpStateData::finishingChunkedRequest() | |
2346 | { | |
2347 | if (flags.sentLastChunk) { | |
2348 | debugs(11, 5, HERE << "already sent last-chunk"); | |
2349 | return false; | |
2350 | } | |
2351 | ||
2352 | Must(receivedWholeRequestBody); // or we should not be sending last-chunk | |
2353 | flags.sentLastChunk = true; | |
2354 | ||
2355 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
e0d28505 | 2356 | requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast); |
b0388924 | 2357 | Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL); |
39cb8c41 AR |
2358 | return true; |
2359 | } | |
2360 | ||
2361 | void | |
2362 | HttpStateData::doneSendingRequestBody() | |
2363 | { | |
fccd4a86 | 2364 | Client::doneSendingRequestBody(); |
9cf7de1b | 2365 | debugs(11,5, HERE << serverConnection); |
39cb8c41 AR |
2366 | |
2367 | // do we need to write something after the last body byte? | |
e31a1e67 | 2368 | if (flags.chunked_request && finishingChunkedRequest()) |
39cb8c41 | 2369 | return; |
e31a1e67 | 2370 | if (!flags.chunked_request && finishingBrokenPost()) |
39cb8c41 | 2371 | return; |
aa49962c | 2372 | |
39cb8c41 | 2373 | sendComplete(); |
94439e4e | 2374 | } |
2375 | ||
5f8252d2 | 2376 | // more origin request body data is available |
2bb867b5 | 2377 | void |
5f8252d2 | 2378 | HttpStateData::handleMoreRequestBodyAvailable() |
2bb867b5 | 2379 | { |
6b679a01 | 2380 | if (eof || !Comm::IsConnOpen(serverConnection)) { |
5f8252d2 | 2381 | // XXX: we should check this condition in other callbacks then! |
2382 | // TODO: Check whether this can actually happen: We should unsubscribe | |
2383 | // as a body consumer when the above condition(s) are detected. | |
e0236918 | 2384 | debugs(11, DBG_IMPORTANT, HERE << "Transaction aborted while reading HTTP body"); |
2bb867b5 | 2385 | return; |
2386 | } | |
62e76326 | 2387 | |
5f8252d2 | 2388 | assert(requestBodySource != NULL); |
fc68f6b1 | 2389 | |
5f8252d2 | 2390 | if (requestBodySource->buf().hasContent()) { |
2391 | // XXX: why does not this trigger a debug message on every request? | |
fc68f6b1 | 2392 | |
2bb867b5 | 2393 | if (flags.headers_parsed && !flags.abuse_detected) { |
46f4b111 | 2394 | flags.abuse_detected = true; |
e0236918 | 2395 | debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" ); |
21b92762 | 2396 | |
9b769c67 | 2397 | if (virginReply()->sline.status() == Http::scInvalidHeader) { |
398bc066 CT |
2398 | closeServer(); |
2399 | mustStop("HttpStateData::handleMoreRequestBodyAvailable"); | |
21b92762 | 2400 | return; |
2401 | } | |
2402 | } | |
b6a2f15e | 2403 | } |
5f8252d2 | 2404 | |
2405 | HttpStateData::handleMoreRequestBodyAvailable(); | |
376bb137 | 2406 | } |
2407 | ||
5f8252d2 | 2408 | // premature end of the request body |
2bb867b5 | 2409 | void |
5f8252d2 | 2410 | HttpStateData::handleRequestBodyProducerAborted() |
376bb137 | 2411 | { |
fccd4a86 | 2412 | Client::handleRequestBodyProducerAborted(); |
64b66b76 | 2413 | if (entry->isEmpty()) { |
25b481e6 | 2414 | debugs(11, 3, "request body aborted: " << serverConnection); |
8b997339 AR |
2415 | // We usually get here when ICAP REQMOD aborts during body processing. |
2416 | // We might also get here if client-side aborts, but then our response | |
2417 | // should not matter because either client-side will provide its own or | |
2418 | // there will be no response at all (e.g., if the the client has left). | |
955394ce | 2419 | ErrorState *err = new ErrorState(ERR_ICAP_FAILURE, Http::scInternalServerError, fwd->request); |
129fe2a1 | 2420 | err->detailError(ERR_DETAIL_SRV_REQMOD_REQ_BODY); |
64b66b76 CT |
2421 | fwd->fail(err); |
2422 | } | |
2423 | ||
39cb8c41 | 2424 | abortTransaction("request body producer aborted"); |
2bb867b5 | 2425 | } |
2426 | ||
5f8252d2 | 2427 | // called when we wrote request headers(!) or a part of the body |
2bb867b5 | 2428 | void |
dc56a9b1 | 2429 | HttpStateData::sentRequestBody(const CommIoCbParams &io) |
2bb867b5 | 2430 | { |
dc56a9b1 | 2431 | if (io.size > 0) |
a0864754 | 2432 | statCounter.server.http.kbytes_out += io.size; |
fc68f6b1 | 2433 | |
fccd4a86 | 2434 | Client::sentRequestBody(io); |
5f8252d2 | 2435 | } |
3b299123 | 2436 | |
5f8252d2 | 2437 | void |
92cfc72f | 2438 | HttpStateData::abortAll(const char *reason) |
5f8252d2 | 2439 | { |
2440 | debugs(11,5, HERE << "aborting transaction for " << reason << | |
9cf7de1b | 2441 | "; " << serverConnection << ", this " << this); |
70df76e3 | 2442 | mustStop(reason); |
54220df8 | 2443 | } |
f53969cc | 2444 | |
39fe14b2 EB |
2445 | HttpStateData::ReuseDecision::ReuseDecision(const StoreEntry *e, const Http::StatusCode code) |
2446 | : answer(HttpStateData::ReuseDecision::reuseNot), reason(nullptr), entry(e), statusCode(code) {} | |
2447 | ||
2448 | HttpStateData::ReuseDecision::Answers | |
2449 | HttpStateData::ReuseDecision::make(const HttpStateData::ReuseDecision::Answers ans, const char *why) | |
2450 | { | |
2451 | answer = ans; | |
2452 | reason = why; | |
2453 | return answer; | |
2454 | } | |
2455 | ||
2456 | std::ostream &operator <<(std::ostream &os, const HttpStateData::ReuseDecision &d) | |
2457 | { | |
2458 | static const char *ReuseMessages[] = { | |
2459 | "do not cache and do not share", // reuseNot | |
2460 | "cache positively and share", // cachePositively | |
2461 | "cache negatively and share", // cacheNegatively | |
2462 | "do not cache but share" // doNotCacheButShare | |
2463 | }; | |
2464 | ||
2465 | assert(d.answer >= HttpStateData::ReuseDecision::reuseNot && | |
4a71b1fc | 2466 | d.answer <= HttpStateData::ReuseDecision::doNotCacheButShare); |
39fe14b2 | 2467 | return os << ReuseMessages[d.answer] << " because " << d.reason << |
4a71b1fc | 2468 | "; HTTP status " << d.statusCode << " " << *(d.entry); |
39fe14b2 EB |
2469 | } |
2470 |