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