]>
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 | |
80a6a08a | 705 | const auto newrep = HttpReply::Pointer::Make(); |
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())) { |
80a6a08a | 723 | handle1xx(newrep.getRaw()); |
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 | |
80a6a08a | 736 | const auto vrep = setVirginReply(newrep.getRaw()); |
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 | |
80a6a08a | 748 | HttpStateData::handle1xx(const HttpReply::Pointer &reply) |
655daa06 | 749 | { |
49f57088 EB |
750 | if (fwd->al) |
751 | fwd->al->reply = reply; | |
752 | ||
655daa06 AR |
753 | // one 1xx at a time: we must not be called while waiting for previous 1xx |
754 | Must(!flags.handling1xx); | |
755 | flags.handling1xx = true; | |
756 | ||
1c2b4465 CT |
757 | const auto statusCode = reply->sline.status(); |
758 | ||
759 | // drop1xx() needs to handle HTTP 101 (Switching Protocols) responses | |
760 | // specially because they indicate that the server has stopped speaking HTTP | |
761 | Must(!flags.serverSwitchedProtocols); | |
762 | flags.serverSwitchedProtocols = (statusCode == Http::scSwitchingProtocols); | |
763 | ||
764 | if (statusCode == Http::scContinue && request->forcedBodyContinuation) | |
765 | return drop1xx("we have sent it already"); | |
766 | ||
767 | if (!request->canHandle1xx()) | |
768 | return drop1xx("the client does not support it"); | |
655daa06 AR |
769 | |
770 | #if USE_HTTP_VIOLATIONS | |
771 | // check whether the 1xx response forwarding is allowed by squid.conf | |
772 | if (Config.accessList.reply) { | |
d603e3c2 | 773 | ACLFilledChecklist ch(Config.accessList.reply, originalRequest().getRaw()); |
b1c2ea7a AR |
774 | ch.updateAle(fwd->al); |
775 | ch.updateReply(reply); | |
cb365059 | 776 | ch.syncAle(originalRequest().getRaw(), nullptr); |
1c2b4465 CT |
777 | if (!ch.fastCheck().allowed()) // TODO: support slow lookups? |
778 | return drop1xx("http_reply_access blocked it"); | |
655daa06 AR |
779 | } |
780 | #endif // USE_HTTP_VIOLATIONS | |
781 | ||
1c2b4465 CT |
782 | if (flags.serverSwitchedProtocols) { |
783 | if (const auto reason = blockSwitchingProtocols(*reply)) | |
784 | return drop1xx(reason); | |
785 | } | |
786 | ||
bf95c10a | 787 | debugs(11, 2, "forwarding 1xx to client"); |
655daa06 AR |
788 | |
789 | // the Sink will use this to call us back after writing 1xx to the client | |
790 | typedef NullaryMemFunT<HttpStateData> CbDialer; | |
791 | const AsyncCall::Pointer cb = JobCallback(11, 3, CbDialer, this, | |
de48b288 | 792 | HttpStateData::proceedAfter1xx); |
e24f13cd | 793 | CallJobHere1(11, 4, request->clientConnectionManager, ConnStateData, |
80a6a08a | 794 | ConnStateData::sendControlMsg, HttpControlMsg(reply, cb)); |
655daa06 AR |
795 | // If the call is not fired, then the Sink is gone, and HttpStateData |
796 | // will terminate due to an aborted store entry or another similar error. | |
797 | // If we get stuck, it is not handle1xx fault if we could get stuck | |
798 | // for similar reasons without a 1xx response. | |
799 | } | |
800 | ||
1c2b4465 CT |
801 | /// if possible, safely ignores the received 1xx control message |
802 | /// otherwise, terminates the server connection | |
803 | void | |
804 | HttpStateData::drop1xx(const char *reason) | |
805 | { | |
806 | if (flags.serverSwitchedProtocols) { | |
807 | debugs(11, 2, "bad 101 because " << reason); | |
808 | const auto err = new ErrorState(ERR_INVALID_RESP, Http::scBadGateway, request.getRaw(), fwd->al); | |
809 | fwd->fail(err); | |
810 | closeServer(); | |
811 | mustStop("prohibited HTTP/101 response"); | |
812 | return; | |
813 | } | |
814 | ||
815 | debugs(11, 2, "ignoring 1xx because " << reason); | |
816 | proceedAfter1xx(); | |
817 | } | |
818 | ||
819 | /// \retval nil if the HTTP/101 (Switching Protocols) reply should be forwarded | |
820 | /// \retval reason why an attempt to switch protocols should be stopped | |
821 | const char * | |
822 | HttpStateData::blockSwitchingProtocols(const HttpReply &reply) const | |
823 | { | |
824 | if (!upgradeHeaderOut) | |
825 | return "Squid offered no Upgrade at all, but server switched to a tunnel"; | |
826 | ||
827 | // See RFC 7230 section 6.7 for the corresponding MUSTs | |
828 | ||
829 | if (!reply.header.has(Http::HdrType::UPGRADE)) | |
830 | return "server did not send an Upgrade header field"; | |
831 | ||
832 | if (!reply.header.hasListMember(Http::HdrType::CONNECTION, "upgrade", ',')) | |
833 | return "server did not send 'Connection: upgrade'"; | |
834 | ||
835 | const auto acceptedProtos = reply.header.getList(Http::HdrType::UPGRADE); | |
836 | const char *pos = nullptr; | |
837 | const char *accepted = nullptr; | |
838 | int acceptedLen = 0; | |
839 | while (strListGetItem(&acceptedProtos, ',', &accepted, &acceptedLen, &pos)) { | |
840 | debugs(11, 5, "server accepted at least" << Raw(nullptr, accepted, acceptedLen)); | |
841 | return nullptr; // OK: let the client validate server's selection | |
842 | } | |
843 | ||
844 | return "server sent an essentially empty Upgrade header field"; | |
845 | } | |
846 | ||
655daa06 AR |
847 | /// restores state and resumes processing after 1xx is ignored or forwarded |
848 | void | |
849 | HttpStateData::proceedAfter1xx() | |
850 | { | |
851 | Must(flags.handling1xx); | |
1c2b4465 CT |
852 | |
853 | if (flags.serverSwitchedProtocols) { | |
854 | // pass server connection ownership to request->clientConnectionManager | |
8b082ed9 | 855 | ConnStateData::ServerConnectionContext scc(serverConnection, inBuf); |
1c2b4465 CT |
856 | typedef UnaryMemFunT<ConnStateData, ConnStateData::ServerConnectionContext> MyDialer; |
857 | AsyncCall::Pointer call = asyncCall(11, 3, "ConnStateData::noteTakeServerConnectionControl", | |
858 | MyDialer(request->clientConnectionManager, | |
859 | &ConnStateData::noteTakeServerConnectionControl, scc)); | |
860 | ScheduleCallHere(call); | |
861 | fwd->unregister(serverConnection); | |
862 | comm_remove_close_handler(serverConnection->fd, closeHandler); | |
863 | closeHandler = nullptr; | |
864 | serverConnection = nullptr; | |
865 | doneWithFwd = "switched protocols"; | |
866 | mustStop(doneWithFwd); | |
867 | return; | |
868 | } | |
869 | ||
8e100780 | 870 | debugs(11, 2, "continuing with " << payloadSeen << " bytes in buffer after 1xx"); |
655daa06 AR |
871 | CallJobHere(11, 3, this, HttpStateData, HttpStateData::processReply); |
872 | } | |
873 | ||
d67acb4e AJ |
874 | /** |
875 | * returns true if the peer can support connection pinning | |
876 | */ | |
f891baff AJ |
877 | bool |
878 | HttpStateData::peerSupportsConnectionPinning() const | |
d67acb4e | 879 | { |
d67acb4e | 880 | if (!_peer) |
9e008dda AJ |
881 | return true; |
882 | ||
f5e17947 CT |
883 | // we are talking "through" rather than "to" our _peer |
884 | if (flags.tunneling) | |
885 | return true; | |
886 | ||
9e008dda | 887 | /*If this peer does not support connection pinning (authenticated |
d67acb4e AJ |
888 | connections) return false |
889 | */ | |
890 | if (!_peer->connection_auth) | |
9e008dda | 891 | return false; |
d67acb4e | 892 | |
66d51f4f | 893 | const auto &rep = entry->mem().freshestReply(); |
f891baff | 894 | |
9e008dda | 895 | /*The peer supports connection pinning and the http reply status |
d67acb4e AJ |
896 | is not unauthorized, so the related connection can be pinned |
897 | */ | |
66d51f4f | 898 | if (rep.sline.status() != Http::scUnauthorized) |
9e008dda AJ |
899 | return true; |
900 | ||
955394ce | 901 | /*The server respond with Http::scUnauthorized and the peer configured |
9e008dda | 902 | with "connection-auth=on" we know that the peer supports pinned |
d67acb4e AJ |
903 | connections |
904 | */ | |
905 | if (_peer->connection_auth == 1) | |
9e008dda | 906 | return true; |
d67acb4e | 907 | |
9e008dda AJ |
908 | /*At this point peer has configured with "connection-auth=auto" |
909 | parameter so we need some extra checks to decide if we are going | |
d67acb4e AJ |
910 | to allow pinned connections or not |
911 | */ | |
912 | ||
9e008dda | 913 | /*if the peer configured with originserver just allow connection |
d67acb4e AJ |
914 | pinning (squid 2.6 behaviour) |
915 | */ | |
916 | if (_peer->options.originserver) | |
9e008dda | 917 | return true; |
d67acb4e AJ |
918 | |
919 | /*if the connections it is already pinned it is OK*/ | |
45e5102d | 920 | if (request->flags.pinned) |
9e008dda AJ |
921 | return true; |
922 | ||
923 | /*Allow pinned connections only if the Proxy-support header exists in | |
924 | reply and has in its list the "Session-Based-Authentication" | |
d67acb4e AJ |
925 | which means that the peer supports connection pinning. |
926 | */ | |
66d51f4f | 927 | if (rep.header.hasListMember(Http::HdrType::PROXY_SUPPORT, "Session-Based-Authentication", ',')) |
f891baff | 928 | return true; |
d67acb4e | 929 | |
f891baff | 930 | return false; |
d67acb4e AJ |
931 | } |
932 | ||
5f8252d2 | 933 | // Called when we parsed (and possibly adapted) the headers but |
934 | // had not starting storing (a.k.a., sending) the body yet. | |
2afaba07 | 935 | void |
936 | HttpStateData::haveParsedReplyHeaders() | |
937 | { | |
fccd4a86 | 938 | Client::haveParsedReplyHeaders(); |
c1520b67 | 939 | |
585ab260 | 940 | HttpReply *rep = finalReply(); |
39fe14b2 | 941 | const Http::StatusCode statusCode = rep->sline.status(); |
2afaba07 | 942 | |
3900307b | 943 | entry->timestampsSet(); |
62e76326 | 944 | |
9bc73deb | 945 | /* Check if object is cacheable or not based on reply code */ |
39fe14b2 | 946 | debugs(11, 3, "HTTP CODE: " << statusCode); |
62e76326 | 947 | |
4310f8b0 EB |
948 | if (StoreEntry *oldEntry = findPreviouslyCachedEntry(entry)) { |
949 | oldEntry->lock("HttpStateData::haveParsedReplyHeaders"); | |
66d51f4f | 950 | sawDateGoBack = rep->olderThan(oldEntry->hasFreshestReply()); |
4310f8b0 EB |
951 | oldEntry->unlock("HttpStateData::haveParsedReplyHeaders"); |
952 | } | |
eace013e EB |
953 | |
954 | if (neighbors_do_private_keys && !sawDateGoBack) | |
9b769c67 | 955 | httpMaybeRemovePublic(entry, rep->sline.status()); |
e6ccf245 | 956 | |
7c476309 | 957 | bool varyFailure = false; |
789217a2 | 958 | if (rep->header.has(Http::HdrType::VARY) |
f66a9ef4 | 959 | #if X_ACCELERATOR_VARY |
789217a2 | 960 | || rep->header.has(Http::HdrType::HDR_X_ACCELERATOR_VARY) |
f66a9ef4 | 961 | #endif |
4b44c907 | 962 | ) { |
d603e3c2 | 963 | const SBuf vary(httpMakeVaryMark(request.getRaw(), rep)); |
4b44c907 | 964 | |
90ab8f20 | 965 | if (vary.isEmpty()) { |
39fe14b2 EB |
966 | // TODO: check whether such responses are shareable. |
967 | // Do not share for now. | |
968 | entry->makePrivate(false); | |
a98270b0 | 969 | if (Http::IsReforwardableStatus(rep->sline.status())) |
70eb3fde | 970 | EBIT_SET(entry->flags, ENTRY_FWD_HDR_WAIT); |
7c476309 AJ |
971 | varyFailure = true; |
972 | } else { | |
90ab8f20 | 973 | entry->mem_obj->vary_headers = vary; |
ee2e0b31 AJ |
974 | |
975 | // RFC 7231 section 7.1.4 | |
976 | // Vary:* can be cached, but has mandatory revalidation | |
977 | static const SBuf asterisk("*"); | |
978 | if (vary == asterisk) | |
979 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); | |
62e76326 | 980 | } |
4b44c907 | 981 | } |
982 | ||
7c476309 AJ |
983 | if (!varyFailure) { |
984 | /* | |
985 | * If its not a reply that we will re-forward, then | |
986 | * allow the client to get it. | |
987 | */ | |
a98270b0 | 988 | if (Http::IsReforwardableStatus(rep->sline.status())) |
70eb3fde | 989 | EBIT_SET(entry->flags, ENTRY_FWD_HDR_WAIT); |
2afaba07 | 990 | |
39fe14b2 | 991 | ReuseDecision decision(entry, statusCode); |
4b44c907 | 992 | |
39fe14b2 EB |
993 | switch (reusableReply(decision)) { |
994 | ||
995 | case ReuseDecision::reuseNot: | |
996 | entry->makePrivate(false); | |
7c476309 | 997 | break; |
62e76326 | 998 | |
39fe14b2 | 999 | case ReuseDecision::cachePositively: |
4310f8b0 EB |
1000 | if (!entry->makePublic()) { |
1001 | decision.make(ReuseDecision::doNotCacheButShare, "public key creation error"); | |
1002 | entry->makePrivate(true); | |
1003 | } | |
7c476309 | 1004 | break; |
62e76326 | 1005 | |
39fe14b2 | 1006 | case ReuseDecision::cacheNegatively: |
4310f8b0 EB |
1007 | if (!entry->cacheNegatively()) { |
1008 | decision.make(ReuseDecision::doNotCacheButShare, "public key creation error"); | |
1009 | entry->makePrivate(true); | |
1010 | } | |
39fe14b2 | 1011 | break; |
4b44c907 | 1012 | |
39fe14b2 EB |
1013 | case ReuseDecision::doNotCacheButShare: |
1014 | entry->makePrivate(true); | |
7c476309 | 1015 | break; |
4b44c907 | 1016 | |
7c476309 AJ |
1017 | default: |
1018 | assert(0); | |
1019 | break; | |
1020 | } | |
39fe14b2 | 1021 | debugs(11, 3, "decided: " << decision); |
9bc73deb | 1022 | } |
62e76326 | 1023 | |
2b59002c AJ |
1024 | if (!ignoreCacheControl) { |
1025 | if (rep->cache_control) { | |
1259f9cf AJ |
1026 | // We are required to revalidate on many conditions. |
1027 | // For security reasons we do so even if storage was caused by refresh_pattern ignore-* option | |
1028 | ||
1029 | // CC:must-revalidate or CC:proxy-revalidate | |
810d879f | 1030 | const bool ccMustRevalidate = (rep->cache_control->hasProxyRevalidate() || rep->cache_control->hasMustRevalidate()); |
1259f9cf AJ |
1031 | |
1032 | // CC:no-cache (only if there are no parameters) | |
810d879f | 1033 | const bool ccNoCacheNoParams = rep->cache_control->hasNoCacheWithoutParameters(); |
1259f9cf AJ |
1034 | |
1035 | // CC:s-maxage=N | |
1036 | const bool ccSMaxAge = rep->cache_control->hasSMaxAge(); | |
1037 | ||
1038 | // CC:private (yes, these can sometimes be stored) | |
1039 | const bool ccPrivate = rep->cache_control->hasPrivate(); | |
1040 | ||
fa83b766 EB |
1041 | if (ccNoCacheNoParams || ccPrivate) |
1042 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); | |
1043 | else if (ccMustRevalidate || ccSMaxAge) | |
1044 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_STALE); | |
2b59002c AJ |
1045 | } |
1046 | #if USE_HTTP_VIOLATIONS // response header Pragma::no-cache is undefined in HTTP | |
1047 | else { | |
1048 | // Expensive calculation. So only do it IF the CC: header is not present. | |
1049 | ||
1050 | /* HACK: Pragma: no-cache in _replies_ is not documented in HTTP, | |
1051 | * but servers like "Active Imaging Webcast/2.0" sure do use it */ | |
789217a2 FC |
1052 | if (rep->header.has(Http::HdrType::PRAGMA) && |
1053 | rep->header.hasListMember(Http::HdrType::PRAGMA,"no-cache",',')) | |
fa83b766 | 1054 | EBIT_SET(entry->flags, ENTRY_REVALIDATE_ALWAYS); |
2b59002c AJ |
1055 | } |
1056 | #endif | |
9bc73deb | 1057 | } |
f5558c95 | 1058 | } |
1059 | ||
528b2c61 | 1060 | HttpStateData::ConnectionStatus |
1061 | HttpStateData::statusIfComplete() const | |
603a02fd | 1062 | { |
585ab260 | 1063 | const HttpReply *rep = virginReply(); |
073ba374 AJ |
1064 | /** \par |
1065 | * If the reply wants to close the connection, it takes precedence */ | |
62e76326 | 1066 | |
d5f18517 AJ |
1067 | static SBuf close("close", 5); |
1068 | if (httpHeaderHasConnDir(&rep->header, close)) | |
62e76326 | 1069 | return COMPLETE_NONPERSISTENT_MSG; |
1070 | ||
073ba374 | 1071 | /** \par |
1f482f82 | 1072 | * If we sent a Connection:close request header, then this |
978e455f | 1073 | * can not be a persistent connection. |
1074 | */ | |
528b2c61 | 1075 | if (!flags.keepalive) |
62e76326 | 1076 | return COMPLETE_NONPERSISTENT_MSG; |
1077 | ||
1f482f82 AR |
1078 | /** \par |
1079 | * If we banned reuse, then this cannot be a persistent connection. | |
1080 | */ | |
1081 | if (flags.forceClose) | |
1082 | return COMPLETE_NONPERSISTENT_MSG; | |
1083 | ||
073ba374 | 1084 | /** \par |
72b63f06 | 1085 | * If we haven't sent the whole request then this can not be a persistent |
1086 | * connection. | |
1087 | */ | |
1088 | if (!flags.request_sent) { | |
7f06a3d8 | 1089 | debugs(11, 2, "Request not yet fully sent " << request->method << ' ' << entry->url()); |
72b63f06 | 1090 | return COMPLETE_NONPERSISTENT_MSG; |
1091 | } | |
1092 | ||
073ba374 | 1093 | /** \par |
9f5a2895 | 1094 | * What does the reply have to say about keep-alive? |
1095 | */ | |
e0d875fa | 1096 | /* XXX: BUG? |
b6a2f15e | 1097 | * If the origin server (HTTP/1.0) does not send a keep-alive |
1098 | * header, but keeps the connection open anyway, what happens? | |
e0d875fa | 1099 | * We'll return here and wait for an EOF before changing |
b6a2f15e | 1100 | * store_status to STORE_OK. Combine this with ENTRY_FWD_HDR_WAIT |
1101 | * and an error status code, and we might have to wait until | |
1102 | * the server times out the socket. | |
1103 | */ | |
2afaba07 | 1104 | if (!rep->keep_alive) |
528b2c61 | 1105 | return COMPLETE_NONPERSISTENT_MSG; |
62e76326 | 1106 | |
528b2c61 | 1107 | return COMPLETE_PERSISTENT_MSG; |
1108 | } | |
1109 | ||
1110 | HttpStateData::ConnectionStatus | |
1111 | HttpStateData::persistentConnStatus() const | |
1112 | { | |
bf95c10a | 1113 | debugs(11, 3, serverConnection << " eof=" << eof); |
839291ac AJ |
1114 | if (eof) // already reached EOF |
1115 | return COMPLETE_NONPERSISTENT_MSG; | |
1116 | ||
505c2f28 AR |
1117 | /* If server fd is closing (but we have not been notified yet), stop Comm |
1118 | I/O to avoid assertions. TODO: Change Comm API to handle callers that | |
1119 | want more I/O after async closing (usually initiated by others). */ | |
1120 | // XXX: add canReceive or s/canSend/canTalkToServer/ | |
e7cea0ed | 1121 | if (!Comm::IsConnOpen(serverConnection)) |
505c2f28 AR |
1122 | return COMPLETE_NONPERSISTENT_MSG; |
1123 | ||
9035d1d5 AJ |
1124 | /** \par |
1125 | * In chunked response we do not know the content length but we are absolutely | |
af0bb8e5 | 1126 | * sure about the end of response, so we are calling the statusIfComplete to |
2f8abb64 | 1127 | * decide if we can be persistent |
af0bb8e5 | 1128 | */ |
839291ac | 1129 | if (lastChunk && flags.chunked) |
9e008dda | 1130 | return statusIfComplete(); |
af0bb8e5 | 1131 | |
718d84bf AR |
1132 | const HttpReply *vrep = virginReply(); |
1133 | debugs(11, 5, "persistentConnStatus: content_length=" << vrep->content_length); | |
1134 | ||
47f6e231 | 1135 | const int64_t clen = vrep->bodySize(request->method); |
fc68f6b1 | 1136 | |
bf8fe701 | 1137 | debugs(11, 5, "persistentConnStatus: clen=" << clen); |
2afaba07 | 1138 | |
35282fbf | 1139 | /* If the body size is unknown we must wait for EOF */ |
1140 | if (clen < 0) | |
62e76326 | 1141 | return INCOMPLETE_MSG; |
1142 | ||
9035d1d5 AJ |
1143 | /** \par |
1144 | * If the body size is known, we must wait until we've gotten all of it. */ | |
5f8252d2 | 1145 | if (clen > 0) { |
8e100780 | 1146 | debugs(11,5, "payloadSeen=" << payloadSeen << " content_length=" << vrep->content_length); |
2afaba07 | 1147 | |
8e100780 | 1148 | if (payloadSeen < vrep->content_length) |
5f8252d2 | 1149 | return INCOMPLETE_MSG; |
821beb5e | 1150 | |
8e100780 | 1151 | if (payloadTruncated > 0) // already read more than needed |
821beb5e | 1152 | return COMPLETE_NONPERSISTENT_MSG; // disable pconns |
5f8252d2 | 1153 | } |
62e76326 | 1154 | |
9035d1d5 AJ |
1155 | /** \par |
1156 | * If there is no message body or we got it all, we can be persistent */ | |
5f8252d2 | 1157 | return statusIfComplete(); |
603a02fd | 1158 | } |
090089c4 | 1159 | |
a928fdfd EB |
1160 | void |
1161 | HttpStateData::noteDelayAwareReadChance() | |
d4a083cc | 1162 | { |
cc8b26f9 | 1163 | waitingForDelayAwareReadChance = false; |
a928fdfd | 1164 | maybeReadVirginBody(); |
d4a083cc | 1165 | } |
d4a083cc | 1166 | |
c4b7a5a9 | 1167 | void |
e6edd8df | 1168 | HttpStateData::readReply(const CommIoCbParams &io) |
090089c4 | 1169 | { |
395a814a | 1170 | debugs(11, 5, io.conn); |
cc8b26f9 | 1171 | waitingForCommRead = false; |
62e76326 | 1172 | |
c8407295 AJ |
1173 | // Bail out early on Comm::ERR_CLOSING - close handlers will tidy up for us |
1174 | if (io.flag == Comm::ERR_CLOSING) { | |
bf8fe701 | 1175 | debugs(11, 3, "http socket closing"); |
c4b7a5a9 | 1176 | return; |
1177 | } | |
1178 | ||
e92e4e44 | 1179 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { |
6dd9a2e4 | 1180 | abortTransaction("store entry aborted while reading reply"); |
62e76326 | 1181 | return; |
e92e4e44 | 1182 | } |
c4b7a5a9 | 1183 | |
5867ac79 AJ |
1184 | Must(Comm::IsConnOpen(serverConnection)); |
1185 | Must(io.conn->fd == serverConnection->fd); | |
fdf55365 | 1186 | |
395a814a AJ |
1187 | /* |
1188 | * Don't reset the timeout value here. The value should be | |
1189 | * counting Config.Timeout.request and applies to the request | |
1190 | * as a whole, not individual read() calls. | |
1191 | * Plus, it breaks our lame *HalfClosed() detection | |
1192 | */ | |
1193 | ||
50c5af88 AR |
1194 | const auto moreDataPermission = canBufferMoreReplyBytes(); |
1195 | if (!moreDataPermission) { | |
1196 | abortTransaction("ready to read required data, but the read buffer is full and cannot be drained"); | |
1197 | return; | |
1198 | } | |
1199 | ||
1200 | const auto readSizeMax = maybeMakeSpaceAvailable(moreDataPermission.value()); | |
1201 | // TODO: Move this logic inside maybeMakeSpaceAvailable(): | |
1202 | const auto readSizeWanted = readSizeMax ? entry->bytesWanted(Range<size_t>(0, readSizeMax)) : 0; | |
395a814a | 1203 | |
50c5af88 | 1204 | if (readSizeWanted <= 0) { |
cc8b26f9 AR |
1205 | // XXX: If we avoid Comm::ReadNow(), we should not Comm::Read() again |
1206 | // when the wait is over. We should go straight to readReply() instead. | |
1207 | ||
1208 | #if USE_ADAPTATION | |
1209 | // XXX: We are duplicating Client::calcBufferSpaceToReserve() logic. | |
1210 | // XXX: Some other delayRead() cases may lack kickReads() guarantees. | |
1211 | // TODO: Refactor maybeMakeSpaceAvailable() to properly treat each | |
1212 | // no-read case instead of calling delayRead() for the remaining cases. | |
1213 | ||
1214 | if (responseBodyBuffer) { | |
1215 | debugs(11, 5, "avoid delayRead() to give adaptation a chance to drain overflow buffer: " << responseBodyBuffer->contentSize()); | |
1216 | return; // wait for Client::noteMoreBodySpaceAvailable() | |
1217 | } | |
1218 | ||
1219 | if (virginBodyDestination && virginBodyDestination->buf().hasContent()) { | |
1220 | debugs(11, 5, "avoid delayRead() to give adaptation a chance to drain body pipe buffer: " << virginBodyDestination->buf().contentSize()); | |
1221 | return; // wait for Client::noteMoreBodySpaceAvailable() | |
1222 | } | |
1223 | #endif | |
1224 | ||
1225 | delayRead(); /// wait for Client::noteDelayAwareReadChance() | |
fdf55365 | 1226 | return; |
1227 | } | |
1228 | ||
50c5af88 AR |
1229 | CommIoCbParams rd(this); // will be expanded with ReadNow results |
1230 | rd.conn = io.conn; | |
1231 | rd.size = readSizeWanted; | |
395a814a AJ |
1232 | switch (Comm::ReadNow(rd, inBuf)) { |
1233 | case Comm::INPROGRESS: | |
1234 | if (inBuf.isEmpty()) | |
1235 | debugs(33, 2, io.conn << ": no data to process, " << xstrerr(rd.xerrno)); | |
1236 | maybeReadVirginBody(); | |
1237 | return; | |
1238 | ||
1239 | case Comm::OK: | |
1240 | { | |
8e100780 | 1241 | payloadSeen += rd.size; |
9a0a18de | 1242 | #if USE_DELAY_POOLS |
2afaba07 | 1243 | DelayId delayId = entry->mem_obj->mostBytesAllowed(); |
395a814a | 1244 | delayId.bytesIn(rd.size); |
447e176b | 1245 | #endif |
62e76326 | 1246 | |
a0864754 AJ |
1247 | statCounter.server.all.kbytes_in += rd.size; |
1248 | statCounter.server.http.kbytes_in += rd.size; | |
95dc7ff4 | 1249 | ++ IOStats.Http.reads; |
62e76326 | 1250 | |
395a814a AJ |
1251 | int bin = 0; |
1252 | for (int clen = rd.size - 1; clen; ++bin) | |
62e76326 | 1253 | clen >>= 1; |
1254 | ||
95dc7ff4 | 1255 | ++ IOStats.Http.read_hist[bin]; |
3ff65596 | 1256 | |
d8165775 | 1257 | request->hier.notePeerRead(); |
30a4f2a8 | 1258 | } |
62e76326 | 1259 | |
395a814a | 1260 | /* Continue to process previously read data */ |
1810a0cb | 1261 | break; |
5fa061b8 | 1262 | |
395a814a | 1263 | case Comm::ENDFILE: // close detected by 0-byte read |
62e76326 | 1264 | eof = 1; |
da6c8415 | 1265 | |
395a814a AJ |
1266 | /* Continue to process previously read data */ |
1267 | break; | |
1268 | ||
1810a0cb | 1269 | // case Comm::COMM_ERROR: |
395a814a AJ |
1270 | default: // no other flags should ever occur |
1271 | debugs(11, 2, io.conn << ": read failure: " << xstrerr(rd.xerrno)); | |
7e6eabbc | 1272 | const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al); |
da958e50 CT |
1273 | err->xerrno = rd.xerrno; |
1274 | fwd->fail(err); | |
398bc066 CT |
1275 | closeServer(); |
1276 | mustStop("HttpStateData::readReply"); | |
395a814a | 1277 | return; |
ba82c452 | 1278 | } |
62e76326 | 1279 | |
395a814a | 1280 | /* Process next response from buffer */ |
655daa06 AR |
1281 | processReply(); |
1282 | } | |
1283 | ||
1284 | /// processes the already read and buffered response data, possibly after | |
1285 | /// waiting for asynchronous 1xx control message processing | |
1286 | void | |
de48b288 A |
1287 | HttpStateData::processReply() |
1288 | { | |
655daa06 AR |
1289 | |
1290 | if (flags.handling1xx) { // we came back after handling a 1xx response | |
bf95c10a | 1291 | debugs(11, 5, "done with 1xx handling"); |
655daa06 AR |
1292 | flags.handling1xx = false; |
1293 | Must(!flags.headers_parsed); | |
1294 | } | |
1295 | ||
d2b604ec AR |
1296 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { |
1297 | abortTransaction("store entry aborted while we were waiting for processReply()"); | |
1298 | return; | |
1299 | } | |
1300 | ||
ba82c452 | 1301 | if (!flags.headers_parsed) { // have not parsed headers yet? |
ba82c452 | 1302 | processReplyHeader(); |
ba82c452 | 1303 | |
1304 | if (!continueAfterParsingHeader()) // parsing error or need more data | |
1305 | return; // TODO: send errors to ICAP | |
1306 | ||
ab593f19 | 1307 | adaptOrFinalizeReply(); // may write to, abort, or "close" the entry |
ba82c452 | 1308 | } |
1309 | ||
1310 | // kick more reads if needed and/or process the response body, if any | |
ba82c452 | 1311 | processReplyBody(); // may call serverComplete() |
ba82c452 | 1312 | } |
1313 | ||
073ba374 AJ |
1314 | /** |
1315 | \retval true if we can continue with processing the body or doing ICAP. | |
1316 | */ | |
ba82c452 | 1317 | bool |
1318 | HttpStateData::continueAfterParsingHeader() | |
1319 | { | |
655daa06 | 1320 | if (flags.handling1xx) { |
bf95c10a | 1321 | debugs(11, 5, "wait for 1xx handling"); |
655daa06 AR |
1322 | Must(!flags.headers_parsed); |
1323 | return false; | |
1324 | } | |
1325 | ||
073ba374 | 1326 | if (!flags.headers_parsed && !eof) { |
395a814a | 1327 | debugs(11, 9, "needs more at " << inBuf.length()); |
073ba374 AJ |
1328 | /** \retval false If we have not finished parsing the headers and may get more data. |
1329 | * Schedules more reads to retrieve the missing data. | |
1330 | */ | |
ba82c452 | 1331 | maybeReadVirginBody(); // schedules all kinds of reads; TODO: rename |
073ba374 | 1332 | return false; |
ba82c452 | 1333 | } |
1334 | ||
073ba374 | 1335 | /** If we are done with parsing, check for errors */ |
ba82c452 | 1336 | |
1337 | err_type error = ERR_NONE; | |
1338 | ||
1339 | if (flags.headers_parsed) { // parsed headers, possibly with errors | |
1340 | // check for header parsing errors | |
585ab260 | 1341 | if (HttpReply *vrep = virginReply()) { |
9b769c67 | 1342 | const Http::StatusCode s = vrep->sline.status(); |
2592bc70 | 1343 | const AnyP::ProtocolVersion &v = vrep->sline.version; |
526ed14e | 1344 | if (s == Http::scInvalidHeader && v != Http::ProtocolVersion(0,9)) { |
51b5dcf5 | 1345 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Bad header encountered from " << entry->url() << " AKA " << request->url); |
ba82c452 | 1346 | error = ERR_INVALID_RESP; |
955394ce | 1347 | } else if (s == Http::scHeaderTooLarge) { |
e1381638 AJ |
1348 | fwd->dontRetry(true); |
1349 | error = ERR_TOO_BIG; | |
3e42b356 AR |
1350 | } else if (vrep->header.conflictingContentLength()) { |
1351 | fwd->dontRetry(true); | |
1352 | error = ERR_INVALID_RESP; | |
f6dd87e9 AJ |
1353 | } else if (vrep->header.unsupportedTe()) { |
1354 | fwd->dontRetry(true); | |
1355 | error = ERR_INVALID_RESP; | |
e1381638 AJ |
1356 | } else { |
1357 | return true; // done parsing, got reply, and no error | |
1358 | } | |
ba82c452 | 1359 | } else { |
1360 | // parsed headers but got no reply | |
51b5dcf5 | 1361 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: No reply at all for " << entry->url() << " AKA " << request->url); |
ba82c452 | 1362 | error = ERR_INVALID_RESP; |
62e76326 | 1363 | } |
090089c4 | 1364 | } else { |
ba82c452 | 1365 | assert(eof); |
395a814a | 1366 | if (inBuf.length()) { |
9121eba6 | 1367 | error = ERR_INVALID_RESP; |
51b5dcf5 | 1368 | debugs(11, DBG_IMPORTANT, "WARNING: HTTP: Invalid Response: Headers did not parse at all for " << entry->url() << " AKA " << request->url); |
9121eba6 AJ |
1369 | } else { |
1370 | error = ERR_ZERO_SIZE_OBJECT; | |
51b5dcf5 | 1371 | debugs(11, (request->flags.accelerated?DBG_IMPORTANT:2), "WARNING: HTTP: Invalid Response: No object data received for " << entry->url() << " AKA " << request->url); |
9121eba6 | 1372 | } |
2afaba07 | 1373 | } |
ba82c452 | 1374 | |
1375 | assert(error != ERR_NONE); | |
1376 | entry->reset(); | |
7e6eabbc | 1377 | fwd->fail(new ErrorState(error, Http::scBadGateway, fwd->request, fwd->al)); |
398bc066 CT |
1378 | closeServer(); |
1379 | mustStop("HttpStateData::continueAfterParsingHeader"); | |
ba82c452 | 1380 | return false; // quit on error |
2afaba07 | 1381 | } |
1382 | ||
821beb5e AR |
1383 | /** truncate what we read if we read too much so that writeReplyBody() |
1384 | writes no more than what we should have read */ | |
1385 | void | |
1386 | HttpStateData::truncateVirginBody() | |
1387 | { | |
1388 | assert(flags.headers_parsed); | |
1389 | ||
1390 | HttpReply *vrep = virginReply(); | |
1391 | int64_t clen = -1; | |
1392 | if (!vrep->expectingBody(request->method, clen) || clen < 0) | |
1393 | return; // no body or a body of unknown size, including chunked | |
1394 | ||
8e100780 | 1395 | if (payloadSeen - payloadTruncated <= clen) |
821beb5e AR |
1396 | return; // we did not read too much or already took care of the extras |
1397 | ||
8e100780 | 1398 | if (const int64_t extras = payloadSeen - payloadTruncated - clen) { |
821beb5e | 1399 | // server sent more that the advertised content length |
8e100780 | 1400 | debugs(11, 5, "payloadSeen=" << payloadSeen << |
e1381638 | 1401 | " clen=" << clen << '/' << vrep->content_length << |
2f8abb64 | 1402 | " truncated=" << payloadTruncated << '+' << extras); |
821beb5e | 1403 | |
395a814a | 1404 | inBuf.chop(0, inBuf.length() - extras); |
8e100780 | 1405 | payloadTruncated += extras; |
821beb5e AR |
1406 | } |
1407 | } | |
1408 | ||
21f90159 EB |
1409 | /// called on a premature EOF discovered when reading response body |
1410 | void | |
1411 | HttpStateData::markPrematureReplyBodyEofFailure() | |
1412 | { | |
1413 | const auto err = new ErrorState(ERR_READ_ERROR, Http::scBadGateway, fwd->request, fwd->al); | |
1414 | static const auto d = MakeNamedErrorDetail("SRV_PREMATURE_EOF"); | |
1415 | err->detailError(d); | |
1416 | fwd->fail(err); | |
1417 | } | |
1418 | ||
073ba374 | 1419 | /** |
2afaba07 | 1420 | * Call this when there is data from the origin server |
1421 | * which should be sent to either StoreEntry, or to ICAP... | |
1422 | */ | |
1423 | void | |
5f8252d2 | 1424 | HttpStateData::writeReplyBody() |
2afaba07 | 1425 | { |
821beb5e | 1426 | truncateVirginBody(); // if needed |
395a814a AJ |
1427 | const char *data = inBuf.rawContent(); |
1428 | int len = inBuf.length(); | |
bc81cb2b | 1429 | addVirginReplyBody(data, len); |
395a814a | 1430 | inBuf.consume(len); |
ba3fe8d9 EB |
1431 | |
1432 | // after addVirginReplyBody() wrote (when not adapting) everything we have | |
1433 | // received to Store, check whether we have received/parsed the entire reply | |
1434 | int64_t clen = -1; | |
1435 | const char *parsedWhole = nullptr; | |
1436 | if (!virginReply()->expectingBody(request->method, clen)) | |
1437 | parsedWhole = "http parsed header-only reply"; | |
1438 | else if (clen >= 0 && clen == payloadSeen - payloadTruncated) | |
1439 | parsedWhole = "http parsed Content-Length body bytes"; | |
1440 | else if (clen < 0 && eof) | |
1441 | parsedWhole = "http parsed body ending with expected/required EOF"; | |
21f90159 | 1442 | |
ba3fe8d9 EB |
1443 | if (parsedWhole) |
1444 | markParsedVirginReplyAsWhole(parsedWhole); | |
21f90159 EB |
1445 | else if (eof) |
1446 | markPrematureReplyBodyEofFailure(); | |
af0bb8e5 | 1447 | } |
fc68f6b1 | 1448 | |
af0bb8e5 | 1449 | bool |
1450 | HttpStateData::decodeAndWriteReplyBody() | |
1451 | { | |
af0bb8e5 | 1452 | assert(flags.chunked); |
1453 | assert(httpChunkDecoder); | |
3a89d435 AR |
1454 | try { |
1455 | MemBuf decodedData; | |
1456 | decodedData.init(); | |
1457 | httpChunkDecoder->setPayloadBuffer(&decodedData); | |
1458 | const bool doneParsing = httpChunkDecoder->parse(inBuf); | |
1459 | inBuf = httpChunkDecoder->remaining(); // sync buffers after parse | |
1460 | addVirginReplyBody(decodedData.content(), decodedData.contentSize()); | |
1461 | if (doneParsing) { | |
1462 | lastChunk = 1; | |
ba3fe8d9 | 1463 | markParsedVirginReplyAsWhole("http parsed last-chunk"); |
21f90159 EB |
1464 | } else if (eof) { |
1465 | markPrematureReplyBodyEofFailure(); | |
3a89d435 AR |
1466 | } |
1467 | return true; | |
af0bb8e5 | 1468 | } |
3a89d435 AR |
1469 | catch (...) { |
1470 | debugs (11, 2, "de-chunking failure: " << CurrentException); | |
1471 | } | |
1472 | return false; | |
e6ccf245 | 1473 | } |
1474 | ||
073ba374 | 1475 | /** |
2afaba07 | 1476 | * processReplyBody has two purposes: |
1477 | * 1 - take the reply body data, if any, and put it into either | |
1478 | * the StoreEntry, or give it over to ICAP. | |
1479 | * 2 - see if we made it to the end of the response (persistent | |
1480 | * connections and such) | |
1481 | */ | |
e6ccf245 | 1482 | void |
2afaba07 | 1483 | HttpStateData::processReplyBody() |
e6ccf245 | 1484 | { |
1a98175f | 1485 | if (!flags.headers_parsed) { |
5f8252d2 | 1486 | maybeReadVirginBody(); |
62e76326 | 1487 | return; |
528b2c61 | 1488 | } |
62e76326 | 1489 | |
a83c6ed6 | 1490 | #if USE_ADAPTATION |
bf95c10a | 1491 | debugs(11,5, "adaptationAccessCheckPending=" << adaptationAccessCheckPending); |
a83c6ed6 | 1492 | if (adaptationAccessCheckPending) |
2afaba07 | 1493 | return; |
fc68f6b1 | 1494 | |
2afaba07 | 1495 | #endif |
62e76326 | 1496 | |
2afaba07 | 1497 | /* |
1498 | * At this point the reply headers have been parsed and consumed. | |
1499 | * That means header content has been removed from readBuf and | |
1500 | * it contains only body data. | |
1501 | */ | |
ef85ab2f DK |
1502 | if (entry->isAccepting()) { |
1503 | if (flags.chunked) { | |
1504 | if (!decodeAndWriteReplyBody()) { | |
ef85ab2f DK |
1505 | serverComplete(); |
1506 | return; | |
1507 | } | |
1508 | } else | |
1509 | writeReplyBody(); | |
1510 | } | |
528b2c61 | 1511 | |
abf396ec AR |
1512 | // storing/sending methods like earlier adaptOrFinalizeReply() or |
1513 | // above writeReplyBody() may release/abort the store entry. | |
e6ccf245 | 1514 | if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) { |
abf396ec AR |
1515 | // TODO: In some cases (e.g., 304), we should keep persistent conn open. |
1516 | // Detect end-of-reply (and, hence, pool our idle pconn) earlier (ASAP). | |
6dd9a2e4 AJ |
1517 | abortTransaction("store entry aborted while storing reply"); |
1518 | return; | |
62e76326 | 1519 | } else |
1520 | switch (persistentConnStatus()) { | |
dc49061a | 1521 | case INCOMPLETE_MSG: { |
3e4bebf8 | 1522 | debugs(11, 5, "processReplyBody: INCOMPLETE_MSG from " << serverConnection); |
21b92762 | 1523 | /* Wait for more data or EOF condition */ |
8d77a37c | 1524 | AsyncCall::Pointer nil; |
21b92762 | 1525 | if (flags.keepalive_broken) { |
8d77a37c | 1526 | commSetConnTimeout(serverConnection, 10, nil); |
21b92762 | 1527 | } else { |
8d77a37c | 1528 | commSetConnTimeout(serverConnection, Config.Timeout.read, nil); |
21b92762 | 1529 | } |
dc49061a A |
1530 | } |
1531 | break; | |
62e76326 | 1532 | |
801cfc26 | 1533 | case COMPLETE_PERSISTENT_MSG: { |
3e4bebf8 | 1534 | debugs(11, 5, "processReplyBody: COMPLETE_PERSISTENT_MSG from " << serverConnection); |
801cfc26 CT |
1535 | |
1536 | // TODO: Remove serverConnectionSaved but preserve exception safety. | |
1537 | ||
8d77a37c | 1538 | commUnsetConnTimeout(serverConnection); |
62e76326 | 1539 | |
8d71285d | 1540 | comm_remove_close_handler(serverConnection->fd, closeHandler); |
aee3523a | 1541 | closeHandler = nullptr; |
fc68f6b1 | 1542 | |
801cfc26 | 1543 | Ip::Address client_addr; // XXX: Remove as unused. Why was it added? |
450fe1cb | 1544 | if (request->flags.spoofClientIp) |
e24f13cd | 1545 | client_addr = request->client_addr; |
fc68f6b1 | 1546 | |
801cfc26 CT |
1547 | auto serverConnectionSaved = serverConnection; |
1548 | fwd->unregister(serverConnection); | |
1549 | serverConnection = nullptr; | |
1550 | ||
1551 | bool ispinned = false; // TODO: Rename to isOrShouldBePinned | |
45e5102d | 1552 | if (request->flags.pinned) { |
9e008dda | 1553 | ispinned = true; |
450fe1cb | 1554 | } else if (request->flags.connectionAuth && request->flags.authSent) { |
9e008dda AJ |
1555 | ispinned = true; |
1556 | } | |
1557 | ||
801cfc26 CT |
1558 | if (ispinned) { |
1559 | if (request->clientConnectionManager.valid()) { | |
1560 | CallJobHere1(11, 4, request->clientConnectionManager, | |
1561 | ConnStateData, | |
1562 | notePinnedConnectionBecameIdle, | |
1563 | ConnStateData::PinnedIdleContext(serverConnectionSaved, request)); | |
1564 | } else { | |
1565 | // must not pool/share ispinned connections, even orphaned ones | |
1566 | serverConnectionSaved->close(); | |
1567 | } | |
bd0723ad | 1568 | } else { |
55622953 | 1569 | fwdPconnPool->push(serverConnectionSaved, request->url.host()); |
bd0723ad | 1570 | } |
1571 | ||
5f8252d2 | 1572 | serverComplete(); |
62e76326 | 1573 | return; |
801cfc26 | 1574 | } |
62e76326 | 1575 | |
1576 | case COMPLETE_NONPERSISTENT_MSG: | |
3e4bebf8 | 1577 | debugs(11, 5, "processReplyBody: COMPLETE_NONPERSISTENT_MSG from " << serverConnection); |
6c36866e | 1578 | |
5f8252d2 | 1579 | serverComplete(); |
62e76326 | 1580 | return; |
1581 | } | |
1582 | ||
5f8252d2 | 1583 | maybeReadVirginBody(); |
c4b7a5a9 | 1584 | } |
1585 | ||
aea65fec AR |
1586 | bool |
1587 | HttpStateData::mayReadVirginReplyBody() const | |
1588 | { | |
1589 | // TODO: Be more precise here. For example, if/when reading trailer, we may | |
1590 | // not be doneWithServer() yet, but we should return false. Similarly, we | |
1591 | // could still be writing the request body after receiving the whole reply. | |
1592 | return !doneWithServer(); | |
1593 | } | |
1594 | ||
c4b7a5a9 | 1595 | void |
5f8252d2 | 1596 | HttpStateData::maybeReadVirginBody() |
c4b7a5a9 | 1597 | { |
cc8b26f9 AR |
1598 | if (!Comm::IsConnOpen(serverConnection) || fd_table[serverConnection->fd].closing()) { |
1599 | debugs(11, 3, "no, peer connection gone"); | |
85bef0a7 | 1600 | return; |
cc8b26f9 AR |
1601 | } |
1602 | ||
1603 | if (eof) { | |
1604 | // tolerate hypothetical calls between Comm::ENDFILE and closeServer() | |
1605 | debugs(11, 3, "no, saw EOF"); | |
1606 | return; | |
1607 | } | |
1608 | ||
1609 | if (lastChunk) { | |
1610 | // tolerate hypothetical calls between setting lastChunk and clearing serverConnection | |
1611 | debugs(11, 3, "no, saw last-chunk"); | |
1612 | return; | |
1613 | } | |
85bef0a7 | 1614 | |
50c5af88 AR |
1615 | if (!canBufferMoreReplyBytes()) { |
1616 | abortTransaction("more response bytes required, but the read buffer is full and cannot be drained"); | |
1ad68518 | 1617 | return; |
50c5af88 | 1618 | } |
1ad68518 | 1619 | |
cc8b26f9 AR |
1620 | if (waitingForDelayAwareReadChance) { |
1621 | debugs(11, 5, "no, still waiting for noteDelayAwareReadChance()"); | |
1ad68518 | 1622 | return; |
cc8b26f9 | 1623 | } |
1ad68518 | 1624 | |
cc8b26f9 AR |
1625 | if (waitingForCommRead) { |
1626 | debugs(11, 3, "no, already waiting for readReply()"); | |
1627 | return; | |
1628 | } | |
1ad68518 | 1629 | |
1ad68518 AJ |
1630 | assert(!Comm::MonitorsRead(serverConnection->fd)); |
1631 | ||
1632 | // wait for read(2) to be possible. | |
1633 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
1634 | AsyncCall::Pointer call = JobCallback(11, 5, Dialer, this, HttpStateData::readReply); | |
1635 | Comm::Read(serverConnection, call); | |
cc8b26f9 | 1636 | waitingForCommRead = true; |
1ad68518 AJ |
1637 | } |
1638 | ||
50c5af88 AR |
1639 | /// Desired inBuf capacity based on various capacity preferences/limits: |
1640 | /// * a smaller buffer may not hold enough for look-ahead header/body parsers; | |
1641 | /// * a smaller buffer may result in inefficient tiny network reads; | |
1642 | /// * a bigger buffer may waste memory; | |
1643 | /// * a bigger buffer may exceed SBuf storage capabilities (SBuf::maxSize); | |
1644 | size_t | |
1645 | HttpStateData::calcReadBufferCapacityLimit() const | |
1ad68518 | 1646 | { |
50c5af88 AR |
1647 | if (!flags.headers_parsed) |
1648 | return Config.maxReplyHeaderSize; | |
1649 | ||
1650 | // XXX: Our inBuf is not used to maintain the read-ahead gap, and using | |
1651 | // Config.readAheadGap like this creates huge read buffers for large | |
1652 | // read_ahead_gap values. TODO: Switch to using tcp_recv_bufsize as the | |
1653 | // primary read buffer capacity factor. | |
1654 | // | |
1655 | // TODO: Cannot reuse throwing NaturalCast() here. Consider removing | |
1656 | // .value() dereference in NaturalCast() or add/use NaturalCastOrMax(). | |
1657 | const auto configurationPreferences = NaturalSum<size_t>(Config.readAheadGap).value_or(SBuf::maxSize); | |
1658 | ||
1659 | // TODO: Honor TeChunkedParser look-ahead and trailer parsing requirements | |
1660 | // (when explicit configurationPreferences are set too low). | |
1661 | ||
1662 | return std::min<size_t>(configurationPreferences, SBuf::maxSize); | |
1663 | } | |
1664 | ||
1665 | /// The maximum number of virgin reply bytes we may buffer before we violate | |
1666 | /// the currently configured response buffering limits. | |
1667 | /// \retval std::nullopt means that no more virgin response bytes can be read | |
1668 | /// \retval 0 means that more virgin response bytes may be read later | |
1669 | /// \retval >0 is the number of bytes that can be read now (subject to other constraints) | |
1670 | std::optional<size_t> | |
1671 | HttpStateData::canBufferMoreReplyBytes() const | |
1672 | { | |
1673 | #if USE_ADAPTATION | |
1674 | // If we do not check this now, we may say the final "no" prematurely below | |
1675 | // because inBuf.length() will decrease as adaptation drains buffered bytes. | |
1676 | if (responseBodyBuffer) { | |
1677 | debugs(11, 3, "yes, but waiting for adaptation to drain read buffer"); | |
1678 | return 0; // yes, we may be able to buffer more (but later) | |
1679 | } | |
1680 | #endif | |
1681 | ||
1682 | const auto maxCapacity = calcReadBufferCapacityLimit(); | |
1683 | if (inBuf.length() >= maxCapacity) { | |
1684 | debugs(11, 3, "no, due to a full buffer: " << inBuf.length() << '/' << inBuf.spaceSize() << "; limit: " << maxCapacity); | |
1685 | return std::nullopt; // no, configuration prohibits buffering more | |
57912702 AJ |
1686 | } |
1687 | ||
50c5af88 AR |
1688 | const auto maxReadSize = maxCapacity - inBuf.length(); // positive |
1689 | debugs(11, 7, "yes, may read up to " << maxReadSize << " into " << inBuf.length() << '/' << inBuf.spaceSize()); | |
1690 | return maxReadSize; // yes, can read up to this many bytes (subject to other constraints) | |
1691 | } | |
1692 | ||
1693 | /// prepare read buffer for reading | |
1694 | /// \return the maximum number of bytes the caller should attempt to read | |
1695 | /// \retval 0 means that the caller should delay reading | |
1696 | size_t | |
1697 | HttpStateData::maybeMakeSpaceAvailable(const size_t maxReadSize) | |
1698 | { | |
57912702 | 1699 | // how much we want to read |
50c5af88 | 1700 | const size_t read_size = calcBufferSpaceToReserve(inBuf.spaceSize(), maxReadSize); |
57912702 | 1701 | |
50c5af88 | 1702 | if (read_size < 2) { |
61beade2 | 1703 | debugs(11, 7, "will not read up to " << read_size << " into buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection); |
50c5af88 | 1704 | return 0; |
57912702 AJ |
1705 | } |
1706 | ||
1707 | // we may need to grow the buffer | |
1708 | inBuf.reserveSpace(read_size); | |
50c5af88 AR |
1709 | debugs(11, 7, "may read up to " << read_size << " bytes info buffer (" << inBuf.length() << "/" << inBuf.spaceSize() << ") from " << serverConnection); |
1710 | return read_size; | |
090089c4 | 1711 | } |
1712 | ||
39cb8c41 | 1713 | /// called after writing the very last request byte (body, last-chunk, etc) |
d576a6a6 | 1714 | void |
39cb8c41 | 1715 | HttpStateData::wroteLast(const CommIoCbParams &io) |
090089c4 | 1716 | { |
bf95c10a | 1717 | debugs(11, 5, serverConnection << ": size " << io.size << ": errflag " << io.flag << "."); |
bc87dc25 | 1718 | #if URL_CHECKSUM_DEBUG |
62e76326 | 1719 | |
528b2c61 | 1720 | entry->mem_obj->checkUrlChecksum(); |
bc87dc25 | 1721 | #endif |
62e76326 | 1722 | |
d8165775 AR |
1723 | // XXX: Keep in sync with Client::sentRequestBody(). |
1724 | // TODO: Extract common parts. | |
1725 | ||
dc56a9b1 | 1726 | if (io.size > 0) { |
5baf2c78 | 1727 | fd_bytes(io.fd, io.size, IoDirection::Write); |
a0864754 AJ |
1728 | statCounter.server.all.kbytes_out += io.size; |
1729 | statCounter.server.http.kbytes_out += io.size; | |
ee1679df | 1730 | } |
62e76326 | 1731 | |
c8407295 | 1732 | if (io.flag == Comm::ERR_CLOSING) |
62e76326 | 1733 | return; |
1734 | ||
d8165775 AR |
1735 | // both successful and failed writes affect response times |
1736 | request->hier.notePeerWrite(); | |
1737 | ||
dc56a9b1 | 1738 | if (io.flag) { |
7e6eabbc | 1739 | const auto err = new ErrorState(ERR_WRITE_ERROR, Http::scBadGateway, fwd->request, fwd->al); |
dc56a9b1 | 1740 | err->xerrno = io.xerrno; |
1741 | fwd->fail(err); | |
398bc066 CT |
1742 | closeServer(); |
1743 | mustStop("HttpStateData::wroteLast"); | |
62e76326 | 1744 | return; |
090089c4 | 1745 | } |
72b63f06 | 1746 | |
39cb8c41 AR |
1747 | sendComplete(); |
1748 | } | |
1749 | ||
1750 | /// successfully wrote the entire request (including body, last-chunk, etc.) | |
1751 | void | |
1752 | HttpStateData::sendComplete() | |
1753 | { | |
2afaba07 | 1754 | /* |
1755 | * Set the read timeout here because it hasn't been set yet. | |
1756 | * We only set the read timeout after the request has been | |
d5430dc8 | 1757 | * fully written to the peer. If we start the timeout |
2afaba07 | 1758 | * after connection establishment, then we are likely to hit |
1759 | * the timeout for POST/PUT requests that have very large | |
1760 | * request bodies. | |
1761 | */ | |
dc56a9b1 | 1762 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 1763 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, |
4cb2536f | 1764 | TimeoutDialer, this, HttpStateData::httpTimeout); |
2afaba07 | 1765 | |
8d77a37c | 1766 | commSetConnTimeout(serverConnection, Config.Timeout.read, timeoutCall); |
46f4b111 | 1767 | flags.request_sent = true; |
090089c4 | 1768 | } |
1769 | ||
2afaba07 | 1770 | void |
5f8252d2 | 1771 | HttpStateData::closeServer() |
2afaba07 | 1772 | { |
bf95c10a | 1773 | debugs(11,5, "closing HTTP server " << serverConnection << " this " << this); |
fc68f6b1 | 1774 | |
9cf7de1b | 1775 | if (Comm::IsConnOpen(serverConnection)) { |
8d71285d AJ |
1776 | fwd->unregister(serverConnection); |
1777 | comm_remove_close_handler(serverConnection->fd, closeHandler); | |
aee3523a | 1778 | closeHandler = nullptr; |
8d71285d | 1779 | serverConnection->close(); |
2afaba07 | 1780 | } |
5f8252d2 | 1781 | } |
2afaba07 | 1782 | |
5f8252d2 | 1783 | bool |
1784 | HttpStateData::doneWithServer() const | |
1785 | { | |
9cf7de1b | 1786 | return !Comm::IsConnOpen(serverConnection); |
2afaba07 | 1787 | } |
1788 | ||
ee0b94f4 HN |
1789 | /* |
1790 | * Fixup authentication request headers for special cases | |
1791 | */ | |
1792 | static void | |
bad9c5e4 | 1793 | httpFixupAuthentication(HttpRequest * request, const HttpHeader * hdr_in, HttpHeader * hdr_out, const Http::StateFlags &flags) |
ee0b94f4 | 1794 | { |
ee0b94f4 | 1795 | /* Nothing to do unless we are forwarding to a peer */ |
f5e17947 CT |
1796 | if (!flags.peering) |
1797 | return; | |
1798 | ||
1799 | // This request is going "through" rather than "to" our _peer. | |
1800 | if (flags.tunneling) | |
f54f527e | 1801 | return; |
ee0b94f4 HN |
1802 | |
1803 | /* Needs to be explicitly enabled */ | |
e24f13cd | 1804 | if (!request->peer_login) |
f54f527e | 1805 | return; |
ee0b94f4 | 1806 | |
f5e17947 | 1807 | const auto header = flags.toOrigin ? Http::HdrType::AUTHORIZATION : Http::HdrType::PROXY_AUTHORIZATION; |
ee0b94f4 HN |
1808 | /* Maybe already dealt with? */ |
1809 | if (hdr_out->has(header)) | |
f54f527e | 1810 | return; |
ee0b94f4 HN |
1811 | |
1812 | /* Nothing to do here for PASSTHRU */ | |
e24f13cd | 1813 | if (strcmp(request->peer_login, "PASSTHRU") == 0) |
f54f527e | 1814 | return; |
ee0b94f4 | 1815 | |
f5e17947 CT |
1816 | // Dangerous and undocumented PROXYPASS is a single-signon to servers with |
1817 | // the proxy password. Only Basic Authentication can work this way. This | |
1818 | // statement forwards a "basic" Proxy-Authorization value from our client | |
1819 | // to an originserver peer. Other PROXYPASS cases are handled lower. | |
1820 | if (flags.toOrigin && | |
63ed43c5 | 1821 | strcmp(request->peer_login, "PROXYPASS") == 0 && |
1822 | hdr_in->has(Http::HdrType::PROXY_AUTHORIZATION)) { | |
f5e17947 | 1823 | |
789217a2 | 1824 | const char *auth = hdr_in->getStr(Http::HdrType::PROXY_AUTHORIZATION); |
ee0b94f4 | 1825 | |
f54f527e AJ |
1826 | if (auth && strncasecmp(auth, "basic ", 6) == 0) { |
1827 | hdr_out->putStr(header, auth); | |
1828 | return; | |
1829 | } | |
ee0b94f4 HN |
1830 | } |
1831 | ||
1d11e9b3 | 1832 | char loginbuf[base64_encode_len(MAX_LOGIN_SZ)]; |
aadbbd7d AJ |
1833 | size_t blen; |
1834 | struct base64_encode_ctx ctx; | |
1835 | base64_encode_init(&ctx); | |
1836 | ||
ee0b94f4 | 1837 | /* Special mode to pass the username to the upstream cache */ |
e24f13cd | 1838 | if (*request->peer_login == '*') { |
f54f527e | 1839 | const char *username = "-"; |
ee0b94f4 | 1840 | |
e24f13cd CT |
1841 | if (request->extacl_user.size()) |
1842 | username = request->extacl_user.termedBuf(); | |
2f1431ea | 1843 | #if USE_AUTH |
aee3523a | 1844 | else if (request->auth_user_request != nullptr) |
e24f13cd | 1845 | username = request->auth_user_request->username(); |
2f1431ea | 1846 | #endif |
ee0b94f4 | 1847 | |
aadbbd7d AJ |
1848 | blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username)); |
1849 | blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1)); | |
1850 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1851 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
f54f527e | 1852 | return; |
ee0b94f4 HN |
1853 | } |
1854 | ||
1855 | /* external_acl provided credentials */ | |
e24f13cd CT |
1856 | if (request->extacl_user.size() && request->extacl_passwd.size() && |
1857 | (strcmp(request->peer_login, "PASS") == 0 || | |
1858 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
aadbbd7d AJ |
1859 | |
1860 | blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf())); | |
1861 | blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":")); | |
1862 | blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf())); | |
1863 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1864 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
f54f527e | 1865 | return; |
ee0b94f4 | 1866 | } |
8fdaa8af AJ |
1867 | // if no external user credentials are available to fake authentication with PASS acts like PASSTHRU |
1868 | if (strcmp(request->peer_login, "PASS") == 0) | |
28204b3b | 1869 | return; |
ee0b94f4 | 1870 | |
9ca29d23 | 1871 | /* Kerberos login to peer */ |
2f1431ea | 1872 | #if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI |
e24f13cd | 1873 | if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) { |
aee3523a AR |
1874 | char *Token=nullptr; |
1875 | char *PrincipalName=nullptr,*p; | |
9825b398 AJ |
1876 | int negotiate_flags = 0; |
1877 | ||
aee3523a | 1878 | if ((p=strchr(request->peer_login,':')) != nullptr ) { |
9ca29d23 AJ |
1879 | PrincipalName=++p; |
1880 | } | |
9825b398 AJ |
1881 | if (request->flags.auth_no_keytab) { |
1882 | negotiate_flags |= PEER_PROXY_NEGOTIATE_NOKEYTAB; | |
1883 | } | |
1884 | Token = peer_proxy_negotiate_auth(PrincipalName, request->peer_host, negotiate_flags); | |
9ca29d23 | 1885 | if (Token) { |
63f03f79 | 1886 | httpHeaderPutStrf(hdr_out, header, "Negotiate %s",Token); |
9ca29d23 AJ |
1887 | } |
1888 | return; | |
1889 | } | |
1890 | #endif /* HAVE_KRB5 && HAVE_GSSAPI */ | |
1891 | ||
aadbbd7d AJ |
1892 | blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login)); |
1893 | blen += base64_encode_final(&ctx, loginbuf+blen); | |
bb64d879 | 1894 | httpHeaderPutStrf(hdr_out, header, "Basic %.*s", (int)blen, loginbuf); |
ee0b94f4 HN |
1895 | return; |
1896 | } | |
1897 | ||
99edd1c3 | 1898 | /* |
9e008dda | 1899 | * build request headers and append them to a given MemBuf |
e5ee81f0 | 1900 | * used by buildRequestPrefix() |
818c6c9e | 1901 | * note: initialised the HttpHeader, the caller is responsible for Clean()-ing |
99edd1c3 | 1902 | */ |
e1e72f06 | 1903 | void |
e5ee81f0 | 1904 | HttpStateData::httpBuildRequestHeader(HttpRequest * request, |
e5ee81f0 | 1905 | StoreEntry * entry, |
4bf68cfa | 1906 | const AccessLogEntryPointer &al, |
e5ee81f0 | 1907 | HttpHeader * hdr_out, |
bad9c5e4 | 1908 | const Http::StateFlags &flags) |
6bf8443a | 1909 | { |
99edd1c3 | 1910 | /* building buffer for complex strings */ |
5999b776 | 1911 | #define BBUF_SZ (MAX_URL+32) |
99edd1c3 | 1912 | LOCAL_ARRAY(char, bbuf, BBUF_SZ); |
67c06f0d | 1913 | LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN); |
e24f13cd | 1914 | const HttpHeader *hdr_in = &request->header; |
aee3523a | 1915 | const HttpHeaderEntry *e = nullptr; |
99edd1c3 | 1916 | HttpHeaderPos pos = HttpHeaderInitPos; |
75faaa7a | 1917 | assert (hdr_out->owner == hoRequest); |
62e76326 | 1918 | |
46017fdd | 1919 | /* use our IMS header if the cached entry has Last-Modified time */ |
fa3e249f | 1920 | if (request->lastmod > -1) |
789217a2 | 1921 | hdr_out->putTime(Http::HdrType::IF_MODIFIED_SINCE, request->lastmod); |
99edd1c3 | 1922 | |
46017fdd CT |
1923 | // Add our own If-None-Match field if the cached entry has a strong ETag. |
1924 | // copyOneHeaderFromClientsideRequestToUpstreamRequest() adds client ones. | |
b38b26cb | 1925 | if (request->etag.size() > 0) { |
d5f18517 | 1926 | hdr_out->addEntry(new HttpHeaderEntry(Http::HdrType::IF_NONE_MATCH, SBuf(), |
7f754be8 | 1927 | request->etag.termedBuf())); |
46017fdd CT |
1928 | } |
1929 | ||
e24f13cd | 1930 | bool we_do_ranges = decideIfWeDoRanges (request); |
528b2c61 | 1931 | |
789217a2 | 1932 | String strConnection (hdr_in->getList(Http::HdrType::CONNECTION)); |
62e76326 | 1933 | |
a9925b40 | 1934 | while ((e = hdr_in->getEntry(&pos))) |
e24f13cd | 1935 | copyOneHeaderFromClientsideRequestToUpstreamRequest(e, strConnection, request, hdr_out, we_do_ranges, flags); |
528b2c61 | 1936 | |
43ae1d95 | 1937 | /* Abstraction break: We should interpret multipart/byterange responses |
528b2c61 | 1938 | * into offset-length data, and this works around our inability to do so. |
1939 | */ | |
e24f13cd | 1940 | if (!we_do_ranges && request->multipartRangeRequest()) { |
62e76326 | 1941 | /* don't cache the result */ |
aeeff7fd | 1942 | request->flags.cachable.veto(); |
62e76326 | 1943 | /* pretend it's not a range request */ |
f0baf149 | 1944 | request->ignoreRange("want to request the whole object"); |
e857372a | 1945 | request->flags.isRanged = false; |
62e76326 | 1946 | } |
528b2c61 | 1947 | |
90be6ff5 | 1948 | hdr_out->addVia(request->http_ver, hdr_in); |
62e76326 | 1949 | |
45e5102d | 1950 | if (request->flags.accelerated) { |
43ae1d95 | 1951 | /* Append Surrogate-Capabilities */ |
789217a2 | 1952 | String strSurrogate(hdr_in->getList(Http::HdrType::SURROGATE_CAPABILITY)); |
45cca89d AJ |
1953 | #if USE_SQUID_ESI |
1954 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0 ESI/1.0\"", Config.Accel.surrogate_id); | |
1955 | #else | |
1956 | snprintf(bbuf, BBUF_SZ, "%s=\"Surrogate/1.0\"", Config.Accel.surrogate_id); | |
1957 | #endif | |
43ae1d95 | 1958 | strListAdd(&strSurrogate, bbuf, ','); |
789217a2 | 1959 | hdr_out->putStr(Http::HdrType::SURROGATE_CAPABILITY, strSurrogate.termedBuf()); |
43ae1d95 | 1960 | } |
43ae1d95 | 1961 | |
67c06f0d | 1962 | /** \pre Handle X-Forwarded-For */ |
9e008dda | 1963 | if (strcmp(opt_forwarded_for, "delete") != 0) { |
c4f30223 | 1964 | |
789217a2 | 1965 | String strFwd = hdr_in->getList(Http::HdrType::X_FORWARDED_FOR); |
c4f30223 | 1966 | |
801593a9 AR |
1967 | // Detect unreasonably long header values. And paranoidly check String |
1968 | // limits: a String ought to accommodate two reasonable-length values. | |
1969 | if (strFwd.size() > 32*1024 || !strFwd.canGrowBy(strFwd.size())) { | |
c4f30223 AR |
1970 | // There is probably a forwarding loop with Via detection disabled. |
1971 | // If we do nothing, String will assert on overflow soon. | |
1972 | // TODO: Terminate all transactions with huge XFF? | |
1973 | strFwd = "error"; | |
1974 | ||
1975 | static int warnedCount = 0; | |
1976 | if (warnedCount++ < 100) { | |
851feda6 | 1977 | const SBuf url(entry ? SBuf(entry->url()) : request->effectiveRequestUri()); |
d816f28d | 1978 | debugs(11, DBG_IMPORTANT, "WARNING: likely forwarding loop with " << url); |
c4f30223 AR |
1979 | } |
1980 | } | |
1981 | ||
9e008dda | 1982 | if (strcmp(opt_forwarded_for, "on") == 0) { |
67c06f0d | 1983 | /** If set to ON - append client IP or 'unknown'. */ |
4dd643d5 | 1984 | if ( request->client_addr.isNoAddr() ) |
67c06f0d AJ |
1985 | strListAdd(&strFwd, "unknown", ','); |
1986 | else | |
4dd643d5 | 1987 | strListAdd(&strFwd, request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN), ','); |
9e008dda | 1988 | } else if (strcmp(opt_forwarded_for, "off") == 0) { |
67c06f0d | 1989 | /** If set to OFF - append 'unknown'. */ |
67c06f0d | 1990 | strListAdd(&strFwd, "unknown", ','); |
9e008dda | 1991 | } else if (strcmp(opt_forwarded_for, "transparent") == 0) { |
67c06f0d | 1992 | /** If set to TRANSPARENT - pass through unchanged. */ |
9e008dda | 1993 | } else if (strcmp(opt_forwarded_for, "truncate") == 0) { |
67c06f0d | 1994 | /** If set to TRUNCATE - drop existing list and replace with client IP or 'unknown'. */ |
4dd643d5 | 1995 | if ( request->client_addr.isNoAddr() ) |
67c06f0d AJ |
1996 | strFwd = "unknown"; |
1997 | else | |
4dd643d5 | 1998 | strFwd = request->client_addr.toStr(ntoabuf, MAX_IPSTRLEN); |
67c06f0d | 1999 | } |
9e008dda | 2000 | if (strFwd.size() > 0) |
789217a2 | 2001 | hdr_out->putStr(Http::HdrType::X_FORWARDED_FOR, strFwd.termedBuf()); |
cc192b50 | 2002 | } |
67c06f0d | 2003 | /** If set to DELETE - do not copy through. */ |
6bccf575 | 2004 | |
99edd1c3 | 2005 | /* append Host if not there already */ |
789217a2 | 2006 | if (!hdr_out->has(Http::HdrType::HOST)) { |
e24f13cd | 2007 | if (request->peer_domain) { |
789217a2 | 2008 | hdr_out->putStr(Http::HdrType::HOST, request->peer_domain); |
62e76326 | 2009 | } else { |
5c51bffb | 2010 | SBuf authority = request->url.authority(); |
789217a2 | 2011 | hdr_out->putStr(Http::HdrType::HOST, authority.c_str()); |
62e76326 | 2012 | } |
6bf8443a | 2013 | } |
62e76326 | 2014 | |
c68e9c6b | 2015 | /* append Authorization if known in URL, not in header and going direct */ |
789217a2 | 2016 | if (!hdr_out->has(Http::HdrType::AUTHORIZATION)) { |
f5e17947 | 2017 | if (flags.toOrigin && !request->url.userInfo().isEmpty()) { |
1d11e9b3 | 2018 | static char result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment |
aadbbd7d AJ |
2019 | struct base64_encode_ctx ctx; |
2020 | base64_encode_init(&ctx); | |
2021 | size_t blen = base64_encode_update(&ctx, result, request->url.userInfo().length(), reinterpret_cast<const uint8_t*>(request->url.userInfo().rawContent())); | |
2022 | blen += base64_encode_final(&ctx, result+blen); | |
2023 | result[blen] = '\0'; | |
2024 | if (blen) | |
789217a2 | 2025 | httpHeaderPutStrf(hdr_out, Http::HdrType::AUTHORIZATION, "Basic %.*s", (int)blen, result); |
62e76326 | 2026 | } |
c68e9c6b | 2027 | } |
62e76326 | 2028 | |
ee0b94f4 | 2029 | /* Fixup (Proxy-)Authorization special cases. Plain relaying dealt with above */ |
e24f13cd | 2030 | httpFixupAuthentication(request, hdr_in, hdr_out, flags); |
62e76326 | 2031 | |
ee0b94f4 HN |
2032 | /* append Cache-Control, add max-age if not there already */ |
2033 | { | |
a9925b40 | 2034 | HttpHdrCc *cc = hdr_in->getCc(); |
62e76326 | 2035 | |
2036 | if (!cc) | |
a4a03b37 | 2037 | cc = new HttpHdrCc(); |
62e76326 | 2038 | |
af6a12ee | 2039 | /* Add max-age only without no-cache */ |
1259f9cf | 2040 | if (!cc->hasMaxAge() && !cc->hasNoCache()) { |
851feda6 AJ |
2041 | // XXX: performance regression. c_str() reallocates |
2042 | SBuf tmp(request->effectiveRequestUri()); | |
2043 | cc->maxAge(getMaxAge(entry ? entry->url() : tmp.c_str())); | |
62e76326 | 2044 | } |
2045 | ||
ce2d6441 | 2046 | /* Enforce sibling relations */ |
62e76326 | 2047 | if (flags.only_if_cached) |
4ce6e3b5 | 2048 | cc->onlyIfCached(true); |
62e76326 | 2049 | |
182faab8 | 2050 | hdr_out->putCc(*cc); |
62e76326 | 2051 | |
3d7782c1 | 2052 | delete cc; |
6bf8443a | 2053 | } |
62e76326 | 2054 | |
1f482f82 AR |
2055 | // Always send Connection because HTTP/1.0 servers need explicit |
2056 | // "keep-alive", HTTP/1.1 servers need explicit "close", Upgrade recipients | |
2057 | // need bare "upgrade", and we do not always know the server expectations. | |
2058 | if (!hdr_out->has(Http::HdrType::CONNECTION)) // forwardUpgrade() may add it | |
2059 | hdr_out->putStr(Http::HdrType::CONNECTION, flags.keepalive ? "keep-alive" : "close"); | |
62e76326 | 2060 | |
a7ad6e4e | 2061 | /* append Front-End-Https */ |
2062 | if (flags.front_end_https) { | |
4e3f4dc7 | 2063 | if (flags.front_end_https == 1 || request->url.getScheme() == AnyP::PROTO_HTTPS) |
789217a2 | 2064 | hdr_out->putStr(Http::HdrType::FRONT_END_HTTPS, "On"); |
a7ad6e4e | 2065 | } |
2066 | ||
e31a1e67 AR |
2067 | if (flags.chunked_request) { |
2068 | // Do not just copy the original value so that if the client-side | |
2069 | // starts decode other encodings, this code may remain valid. | |
789217a2 | 2070 | hdr_out->putStr(Http::HdrType::TRANSFER_ENCODING, "chunked"); |
39cb8c41 AR |
2071 | } |
2072 | ||
6bccf575 | 2073 | /* Now mangle the headers. */ |
cde8f31b | 2074 | httpHdrMangleList(hdr_out, request, al, ROR_REQUEST); |
f4698e0b | 2075 | |
30abd221 | 2076 | strConnection.clean(); |
99edd1c3 | 2077 | } |
2078 | ||
1c2b4465 CT |
2079 | /// copies from-client Upgrade info into the given to-server header while |
2080 | /// honoring configuration filters and following HTTP requirements | |
2081 | void | |
2082 | HttpStateData::forwardUpgrade(HttpHeader &hdrOut) | |
2083 | { | |
2084 | if (!Config.http_upgrade_request_protocols) | |
2085 | return; // forward nothing by default | |
2086 | ||
2087 | /* RFC 7230 section 6.7 paragraph 10: | |
2088 | * A server MUST ignore an Upgrade header field that is received in | |
2089 | * an HTTP/1.0 request. | |
2090 | */ | |
2091 | if (request->http_ver == Http::ProtocolVersion(1,0)) | |
2092 | return; | |
2093 | ||
2094 | const auto &hdrIn = request->header; | |
2095 | if (!hdrIn.has(Http::HdrType::UPGRADE)) | |
2096 | return; | |
2097 | const auto upgradeIn = hdrIn.getList(Http::HdrType::UPGRADE); | |
2098 | ||
2099 | String upgradeOut; | |
2100 | ||
2101 | ACLFilledChecklist ch(nullptr, request.getRaw()); | |
2102 | ch.al = fwd->al; | |
2103 | const char *pos = nullptr; | |
2104 | const char *offeredStr = nullptr; | |
2105 | int offeredStrLen = 0; | |
2106 | while (strListGetItem(&upgradeIn, ',', &offeredStr, &offeredStrLen, &pos)) { | |
2107 | const ProtocolView offeredProto(offeredStr, offeredStrLen); | |
2108 | debugs(11, 5, "checks all rules applicable to " << offeredProto); | |
2109 | Config.http_upgrade_request_protocols->forApplicable(offeredProto, [&ch, offeredStr, offeredStrLen, &upgradeOut] (const SBuf &cfgProto, const acl_access *guard) { | |
2110 | debugs(11, 5, "checks " << cfgProto << " rule(s)"); | |
2111 | ch.changeAcl(guard); | |
2112 | const auto answer = ch.fastCheck(); | |
2113 | if (answer.implicit) | |
2114 | return false; // keep looking for an explicit rule match | |
2115 | if (answer.allowed()) | |
2116 | strListAdd(upgradeOut, offeredStr, offeredStrLen); | |
2117 | // else drop the offer (explicitly denied cases and ACL errors) | |
2118 | return true; // stop after an explicit rule match or an error | |
2119 | }); | |
2120 | } | |
2121 | ||
2122 | if (upgradeOut.size()) { | |
2123 | hdrOut.putStr(Http::HdrType::UPGRADE, upgradeOut.termedBuf()); | |
2124 | ||
2125 | /* RFC 7230 section 6.7 paragraph 10: | |
2126 | * When Upgrade is sent, the sender MUST also send a Connection header | |
2127 | * field that contains an "upgrade" connection option, in | |
2128 | * order to prevent Upgrade from being accidentally forwarded by | |
2129 | * intermediaries that might not implement the listed protocols. | |
2130 | * | |
2131 | * NP: Squid does not truly implement the protocol(s) in this Upgrade. | |
2132 | * For now we are treating an explicit blind tunnel as "implemented" | |
2133 | * regardless of the security implications. | |
2134 | */ | |
2135 | hdrOut.putStr(Http::HdrType::CONNECTION, "upgrade"); | |
1f482f82 AR |
2136 | |
2137 | // Connection:close and Connection:keepalive confuse some Upgrade | |
2138 | // recipients, so we do not send those headers. Our Upgrade request | |
2139 | // implicitly offers connection persistency per HTTP/1.1 defaults. | |
2140 | // Update the keepalive flag to reflect that offer. | |
2141 | // * If the server upgrades, then we would not be talking HTTP past the | |
2142 | // HTTP 101 control message, and HTTP persistence would be irrelevant. | |
2143 | // * Otherwise, our request will contradict onoff.server_pconns=off or | |
2144 | // other no-keepalive conditions (if any). We compensate by copying | |
2145 | // the original no-keepalive decision now and honoring it later. | |
2146 | flags.forceClose = !flags.keepalive; | |
2147 | flags.keepalive = true; // should already be true in most cases | |
1c2b4465 CT |
2148 | } |
2149 | } | |
2150 | ||
9e498bfb AJ |
2151 | /** |
2152 | * Decides whether a particular header may be cloned from the received Clients request | |
2153 | * to our outgoing fetch request. | |
2154 | */ | |
528b2c61 | 2155 | void |
bad9c5e4 | 2156 | copyOneHeaderFromClientsideRequestToUpstreamRequest(const HttpHeaderEntry *e, const String strConnection, const HttpRequest * request, HttpHeader * hdr_out, const int we_do_ranges, const Http::StateFlags &flags) |
528b2c61 | 2157 | { |
e8466ea9 | 2158 | debugs(11, 5, "httpBuildRequestHeader: " << e->name << ": " << e->value ); |
62e76326 | 2159 | |
528b2c61 | 2160 | switch (e->id) { |
62e76326 | 2161 | |
f53969cc | 2162 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid should not pass on. */ |
9e498bfb | 2163 | |
789217a2 | 2164 | case Http::HdrType::PROXY_AUTHORIZATION: |
9e498bfb AJ |
2165 | /** \par Proxy-Authorization: |
2166 | * Only pass on proxy authentication to peers for which | |
62e76326 | 2167 | * authentication forwarding is explicitly enabled |
2168 | */ | |
f5e17947 | 2169 | if (!flags.toOrigin && request->peer_login && |
e24f13cd CT |
2170 | (strcmp(request->peer_login, "PASS") == 0 || |
2171 | strcmp(request->peer_login, "PROXYPASS") == 0 || | |
2172 | strcmp(request->peer_login, "PASSTHRU") == 0)) { | |
eede25e7 | 2173 | hdr_out->addEntry(e->clone()); |
62e76326 | 2174 | } |
62e76326 | 2175 | break; |
2176 | ||
f53969cc | 2177 | /** \par RFC 2616 sect 13.5.1 - Hop-by-Hop headers which Squid does not pass on. */ |
9e498bfb | 2178 | |
789217a2 FC |
2179 | case Http::HdrType::CONNECTION: /** \par Connection: */ |
2180 | case Http::HdrType::TE: /** \par TE: */ | |
2181 | case Http::HdrType::KEEP_ALIVE: /** \par Keep-Alive: */ | |
2182 | case Http::HdrType::PROXY_AUTHENTICATE: /** \par Proxy-Authenticate: */ | |
2183 | case Http::HdrType::TRAILER: /** \par Trailer: */ | |
789217a2 | 2184 | case Http::HdrType::TRANSFER_ENCODING: /** \par Transfer-Encoding: */ |
9e498bfb AJ |
2185 | break; |
2186 | ||
1c2b4465 CT |
2187 | /// \par Upgrade is hop-by-hop but forwardUpgrade() may send a filtered one |
2188 | case Http::HdrType::UPGRADE: | |
2189 | break; | |
2190 | ||
f53969cc | 2191 | /** \par OTHER headers I haven't bothered to track down yet. */ |
9e498bfb | 2192 | |
789217a2 | 2193 | case Http::HdrType::AUTHORIZATION: |
9e498bfb AJ |
2194 | /** \par WWW-Authorization: |
2195 | * Pass on WWW authentication */ | |
62e76326 | 2196 | |
f5e17947 | 2197 | if (!flags.toOriginPeer()) { |
eede25e7 | 2198 | hdr_out->addEntry(e->clone()); |
62e76326 | 2199 | } else { |
f5e17947 CT |
2200 | /** \note Assume that talking to a cache_peer originserver makes |
2201 | * us a reverse proxy and only forward authentication if enabled | |
ee0b94f4 | 2202 | * (see also httpFixupAuthentication for special cases) |
62e76326 | 2203 | */ |
e24f13cd CT |
2204 | if (request->peer_login && |
2205 | (strcmp(request->peer_login, "PASS") == 0 || | |
2206 | strcmp(request->peer_login, "PASSTHRU") == 0 || | |
2207 | strcmp(request->peer_login, "PROXYPASS") == 0)) { | |
eede25e7 | 2208 | hdr_out->addEntry(e->clone()); |
62e76326 | 2209 | } |
2210 | } | |
2211 | ||
2212 | break; | |
2213 | ||
789217a2 | 2214 | case Http::HdrType::HOST: |
9e498bfb | 2215 | /** \par Host: |
b883b594 | 2216 | * Normally Squid rewrites the Host: header. |
2217 | * However, there is one case when we don't: If the URL | |
62e76326 | 2218 | * went through our redirector and the admin configured |
2219 | * 'redir_rewrites_host' to be off. | |
2220 | */ | |
e24f13cd | 2221 | if (request->peer_domain) |
789217a2 | 2222 | hdr_out->putStr(Http::HdrType::HOST, request->peer_domain); |
45e5102d | 2223 | else if (request->flags.redirected && !Config.onoff.redir_rewrites_host) |
eede25e7 | 2224 | hdr_out->addEntry(e->clone()); |
b883b594 | 2225 | else { |
5c51bffb | 2226 | SBuf authority = request->url.authority(); |
789217a2 | 2227 | hdr_out->putStr(Http::HdrType::HOST, authority.c_str()); |
b883b594 | 2228 | } |
62e76326 | 2229 | |
2230 | break; | |
2231 | ||
789217a2 | 2232 | case Http::HdrType::IF_MODIFIED_SINCE: |
9e498bfb | 2233 | /** \par If-Modified-Since: |
96598f93 AJ |
2234 | * append unless we added our own, |
2235 | * but only if cache_miss_revalidate is enabled, or | |
2236 | * the request is not cacheable, or | |
2237 | * the request contains authentication credentials. | |
2238 | * \note at most one client's If-Modified-Since header can pass through | |
2239 | */ | |
2240 | // XXX: need to check and cleanup the auth case so cacheable auth requests get cached. | |
789217a2 | 2241 | if (hdr_out->has(Http::HdrType::IF_MODIFIED_SINCE)) |
96598f93 AJ |
2242 | break; |
2243 | else if (Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth) | |
eede25e7 | 2244 | hdr_out->addEntry(e->clone()); |
96598f93 | 2245 | break; |
62e76326 | 2246 | |
789217a2 | 2247 | case Http::HdrType::IF_NONE_MATCH: |
96598f93 AJ |
2248 | /** \par If-None-Match: |
2249 | * append if the wildcard '*' special case value is present, or | |
2250 | * cache_miss_revalidate is disabled, or | |
2251 | * the request is not cacheable in this proxy, or | |
2252 | * the request contains authentication credentials. | |
2253 | * \note this header lists a set of responses for the server to elide sending. Squid added values are extending that set. | |
2254 | */ | |
2255 | // XXX: need to check and cleanup the auth case so cacheable auth requests get cached. | |
789217a2 | 2256 | if (hdr_out->hasListMember(Http::HdrType::IF_MATCH, "*", ',') || Config.onoff.cache_miss_revalidate || !request->flags.cachable || request->flags.auth) |
eede25e7 | 2257 | hdr_out->addEntry(e->clone()); |
62e76326 | 2258 | break; |
2259 | ||
789217a2 | 2260 | case Http::HdrType::MAX_FORWARDS: |
9e498bfb | 2261 | /** \par Max-Forwards: |
fc90edc3 | 2262 | * pass only on TRACE or OPTIONS requests */ |
c2a7cefd | 2263 | if (request->method == Http::METHOD_TRACE || request->method == Http::METHOD_OPTIONS) { |
fc90edc3 | 2264 | const int64_t hops = e->getInt64(); |
62e76326 | 2265 | |
2266 | if (hops > 0) | |
789217a2 | 2267 | hdr_out->putInt64(Http::HdrType::MAX_FORWARDS, hops - 1); |
62e76326 | 2268 | } |
2269 | ||
2270 | break; | |
2271 | ||
789217a2 | 2272 | case Http::HdrType::VIA: |
9e498bfb AJ |
2273 | /** \par Via: |
2274 | * If Via is disabled then forward any received header as-is. | |
2275 | * Otherwise leave for explicit updated addition later. */ | |
62e76326 | 2276 | |
2277 | if (!Config.onoff.via) | |
eede25e7 | 2278 | hdr_out->addEntry(e->clone()); |
62e76326 | 2279 | |
2280 | break; | |
2281 | ||
789217a2 | 2282 | case Http::HdrType::RANGE: |
62e76326 | 2283 | |
789217a2 | 2284 | case Http::HdrType::IF_RANGE: |
62e76326 | 2285 | |
789217a2 | 2286 | case Http::HdrType::REQUEST_RANGE: |
9e498bfb AJ |
2287 | /** \par Range:, If-Range:, Request-Range: |
2288 | * Only pass if we accept ranges */ | |
62e76326 | 2289 | if (!we_do_ranges) |
eede25e7 | 2290 | hdr_out->addEntry(e->clone()); |
62e76326 | 2291 | |
2292 | break; | |
2293 | ||
789217a2 | 2294 | case Http::HdrType::PROXY_CONNECTION: // SHOULD ignore. But doing so breaks things. |
95e78500 | 2295 | break; |
62e76326 | 2296 | |
789217a2 | 2297 | case Http::HdrType::CONTENT_LENGTH: |
f228d6f6 AR |
2298 | // pass through unless we chunk; also, keeping this away from default |
2299 | // prevents request smuggling via Connection: Content-Length tricks | |
2300 | if (!flags.chunked_request) | |
2301 | hdr_out->addEntry(e->clone()); | |
2302 | break; | |
2303 | ||
789217a2 | 2304 | case Http::HdrType::X_FORWARDED_FOR: |
62e76326 | 2305 | |
789217a2 | 2306 | case Http::HdrType::CACHE_CONTROL: |
95e78500 | 2307 | /** \par X-Forwarded-For:, Cache-Control: |
9e498bfb AJ |
2308 | * handled specially by Squid, so leave off for now. |
2309 | * append these after the loop if needed */ | |
62e76326 | 2310 | break; |
2311 | ||
789217a2 | 2312 | case Http::HdrType::FRONT_END_HTTPS: |
9e498bfb AJ |
2313 | /** \par Front-End-Https: |
2314 | * Pass thru only if peer is configured with front-end-https */ | |
62e76326 | 2315 | if (!flags.front_end_https) |
eede25e7 | 2316 | hdr_out->addEntry(e->clone()); |
62e76326 | 2317 | |
2318 | break; | |
2319 | ||
be753325 | 2320 | default: |
9e498bfb AJ |
2321 | /** \par default. |
2322 | * pass on all other header fields | |
2323 | * which are NOT listed by the special Connection: header. */ | |
d5f18517 | 2324 | if (strConnection.size()>0 && strListIsMember(&strConnection, e->name, ',')) { |
e1ea7456 | 2325 | debugs(11, 2, "'" << e->name << "' header cropped by Connection: definition"); |
9e498bfb AJ |
2326 | return; |
2327 | } | |
2328 | ||
eede25e7 | 2329 | hdr_out->addEntry(e->clone()); |
528b2c61 | 2330 | } |
2331 | } | |
2332 | ||
e5ee81f0 | 2333 | bool |
e24f13cd | 2334 | HttpStateData::decideIfWeDoRanges (HttpRequest * request) |
528b2c61 | 2335 | { |
e5ee81f0 | 2336 | bool result = true; |
62e76326 | 2337 | /* decide if we want to do Ranges ourselves |
2338 | * and fetch the whole object now) | |
2339 | * We want to handle Ranges ourselves iff | |
2340 | * - we can actually parse client Range specs | |
2341 | * - the specs are expected to be simple enough (e.g. no out-of-order ranges) | |
2342 | * - reply will be cachable | |
2343 | * (If the reply will be uncachable we have to throw it away after | |
2344 | * serving this request, so it is better to forward ranges to | |
2345 | * the server and fetch only the requested content) | |
2346 | */ | |
2347 | ||
e24f13cd | 2348 | int64_t roffLimit = request->getRangeOffsetLimit(); |
11e3fa1c | 2349 | |
aee3523a | 2350 | if (nullptr == request->range || !request->flags.cachable |
450fe1cb | 2351 | || request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth) |
e5ee81f0 | 2352 | result = false; |
62e76326 | 2353 | |
9e008dda | 2354 | debugs(11, 8, "decideIfWeDoRanges: range specs: " << |
e24f13cd | 2355 | request->range << ", cachable: " << |
45e5102d | 2356 | request->flags.cachable << "; we_do_ranges: " << result); |
62e76326 | 2357 | |
2358 | return result; | |
528b2c61 | 2359 | } |
2360 | ||
62e76326 | 2361 | /* build request prefix and append it to a given MemBuf; |
99edd1c3 | 2362 | * return the length of the prefix */ |
9bc73deb | 2363 | mb_size_t |
e24f13cd | 2364 | HttpStateData::buildRequestPrefix(MemBuf * mb) |
99edd1c3 | 2365 | { |
2366 | const int offset = mb->size; | |
2592bc70 | 2367 | /* Uses a local httpver variable to print the HTTP label |
526ed14e AJ |
2368 | * since the HttpRequest may have an older version label. |
2369 | * XXX: This could create protocol bugs as the headers sent and | |
2370 | * flow control should all be based on the HttpRequest version | |
2371 | * not the one we are sending. Needs checking. | |
2372 | */ | |
2592bc70 | 2373 | const AnyP::ProtocolVersion httpver = Http::ProtocolVersion(); |
f5e17947 | 2374 | const SBuf url(flags.toOrigin ? request->url.path() : request->effectiveRequestUri()); |
51b5dcf5 | 2375 | mb->appendf(SQUIDSBUFPH " " SQUIDSBUFPH " %s/%d.%d\r\n", |
4391cd15 | 2376 | SQUIDSBUFPRINT(request->method.image()), |
51b5dcf5 | 2377 | SQUIDSBUFPRINT(url), |
4391cd15 AJ |
2378 | AnyP::ProtocolType_str[httpver.protocol], |
2379 | httpver.major,httpver.minor); | |
99edd1c3 | 2380 | /* build and pack headers */ |
2381 | { | |
75faaa7a | 2382 | HttpHeader hdr(hoRequest); |
1f482f82 | 2383 | forwardUpgrade(hdr); // before httpBuildRequestHeader() for CONNECTION |
d603e3c2 | 2384 | httpBuildRequestHeader(request.getRaw(), entry, fwd->al, &hdr, flags); |
9e008dda | 2385 | |
450fe1cb | 2386 | if (request->flags.pinned && request->flags.connectionAuth) |
e857372a | 2387 | request->flags.authSent = true; |
789217a2 | 2388 | else if (hdr.has(Http::HdrType::AUTHORIZATION)) |
e857372a | 2389 | request->flags.authSent = true; |
d67acb4e | 2390 | |
1c2b4465 CT |
2391 | // The late placement of this check supports reply_header_add mangling, |
2392 | // but also complicates optimizing upgradeHeaderOut-like lookups. | |
2393 | if (hdr.has(Http::HdrType::UPGRADE)) { | |
2394 | assert(!upgradeHeaderOut); | |
2395 | upgradeHeaderOut = new String(hdr.getList(Http::HdrType::UPGRADE)); | |
2396 | } | |
2397 | ||
10201568 | 2398 | hdr.packInto(mb); |
519e0948 | 2399 | hdr.clean(); |
9d9d144b | 2400 | } |
99edd1c3 | 2401 | /* append header terminator */ |
2fe7eff9 | 2402 | mb->append(crlf, 2); |
99edd1c3 | 2403 | return mb->size - offset; |
6bf8443a | 2404 | } |
62e76326 | 2405 | |
090089c4 | 2406 | /* This will be called when connect completes. Write request. */ |
5f8252d2 | 2407 | bool |
2bb867b5 | 2408 | HttpStateData::sendRequest() |
090089c4 | 2409 | { |
99edd1c3 | 2410 | MemBuf mb; |
090089c4 | 2411 | |
bf95c10a | 2412 | debugs(11, 5, serverConnection << ", request " << request << ", this " << this << "."); |
a0297974 | 2413 | |
6b679a01 | 2414 | if (!Comm::IsConnOpen(serverConnection)) { |
bf95c10a | 2415 | debugs(11,3, "cannot send request to closing " << serverConnection); |
aee3523a | 2416 | assert(closeHandler != nullptr); |
a0297974 AR |
2417 | return false; |
2418 | } | |
2419 | ||
dc56a9b1 | 2420 | typedef CommCbMemFunT<HttpStateData, CommTimeoutCbParams> TimeoutDialer; |
4299f876 | 2421 | AsyncCall::Pointer timeoutCall = JobCallback(11, 5, |
4cb2536f | 2422 | TimeoutDialer, this, HttpStateData::httpTimeout); |
8d77a37c | 2423 | commSetConnTimeout(serverConnection, Config.Timeout.lifetime, timeoutCall); |
5f8252d2 | 2424 | maybeReadVirginBody(); |
2425 | ||
aee3523a | 2426 | if (request->body_pipe != nullptr) { |
123ec4de | 2427 | if (!startRequestBodyFlow()) // register to receive body data |
5f8252d2 | 2428 | return false; |
9e008dda | 2429 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
4299f876 | 2430 | requestSender = JobCallback(11,5, |
4cb2536f | 2431 | Dialer, this, HttpStateData::sentRequestBody); |
e31a1e67 AR |
2432 | |
2433 | Must(!flags.chunked_request); | |
f228d6f6 | 2434 | // use chunked encoding if we do not know the length |
e24f13cd | 2435 | if (request->content_length < 0) |
46f4b111 | 2436 | flags.chunked_request = true; |
5f8252d2 | 2437 | } else { |
2438 | assert(!requestBodySource); | |
9e008dda | 2439 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
4299f876 | 2440 | requestSender = JobCallback(11,5, |
39cb8c41 | 2441 | Dialer, this, HttpStateData::wroteLast); |
5f8252d2 | 2442 | } |
54220df8 | 2443 | |
efb9218c | 2444 | /* |
99edd1c3 | 2445 | * Is keep-alive okay for all request methods? |
efb9218c | 2446 | */ |
450fe1cb | 2447 | if (request->flags.mustKeepalive) |
46f4b111 | 2448 | flags.keepalive = true; |
693cb033 CT |
2449 | else if (request->flags.pinned) |
2450 | flags.keepalive = request->persistent(); | |
d67acb4e | 2451 | else if (!Config.onoff.server_pconns) |
46f4b111 | 2452 | flags.keepalive = false; |
f5e17947 CT |
2453 | else if (flags.tunneling) |
2454 | // tunneled non pinned bumped requests must not keepalive | |
2455 | flags.keepalive = !request->flags.sslBumped; | |
aee3523a | 2456 | else if (_peer == nullptr) |
46f4b111 | 2457 | flags.keepalive = true; |
2bb867b5 | 2458 | else if (_peer->stats.n_keepalives_sent < 10) |
46f4b111 | 2459 | flags.keepalive = true; |
2bb867b5 | 2460 | else if ((double) _peer->stats.n_keepalives_recv / |
2461 | (double) _peer->stats.n_keepalives_sent > 0.50) | |
46f4b111 | 2462 | flags.keepalive = true; |
2bb867b5 | 2463 | |
f5e17947 | 2464 | if (_peer && !flags.tunneling) { |
2ecba5b6 | 2465 | /*The old code here was |
5c51bffb | 2466 | if (neighborType(_peer, request->url) == PEER_SIBLING && ... |
e24f13cd | 2467 | which is equivalent to: |
5c51bffb | 2468 | if (neighborType(_peer, URL()) == PEER_SIBLING && ... |
e24f13cd CT |
2469 | or better: |
2470 | if (((_peer->type == PEER_MULTICAST && p->options.mcast_siblings) || | |
2471 | _peer->type == PEER_SIBLINGS ) && _peer->options.allow_miss) | |
2472 | flags.only_if_cached = 1; | |
2473 | ||
2474 | But I suppose it was a bug | |
2475 | */ | |
5c51bffb | 2476 | if (neighborType(_peer, request->url) == PEER_SIBLING && !_peer->options.allow_miss) |
46f4b111 | 2477 | flags.only_if_cached = true; |
2bb867b5 | 2478 | |
2479 | flags.front_end_https = _peer->front_end_https; | |
a7ad6e4e | 2480 | } |
62e76326 | 2481 | |
2fe7eff9 | 2482 | mb.init(); |
aee3523a | 2483 | request->peer_host=_peer?_peer->host:nullptr; |
e24f13cd | 2484 | buildRequestPrefix(&mb); |
5f8252d2 | 2485 | |
1ce34ddd AJ |
2486 | debugs(11, 2, "HTTP Server " << serverConnection); |
2487 | debugs(11, 2, "HTTP Server REQUEST:\n---------\n" << mb.buf << "\n----------"); | |
2488 | ||
2489 | Comm::Write(serverConnection, &mb, requestSender); | |
5f8252d2 | 2490 | return true; |
090089c4 | 2491 | } |
b6a2f15e | 2492 | |
39cb8c41 AR |
2493 | bool |
2494 | HttpStateData::getMoreRequestBody(MemBuf &buf) | |
2495 | { | |
2496 | // parent's implementation can handle the no-encoding case | |
e31a1e67 | 2497 | if (!flags.chunked_request) |
fccd4a86 | 2498 | return Client::getMoreRequestBody(buf); |
39cb8c41 AR |
2499 | |
2500 | MemBuf raw; | |
2501 | ||
aee3523a | 2502 | Must(requestBodySource != nullptr); |
39cb8c41 AR |
2503 | if (!requestBodySource->getMoreData(raw)) |
2504 | return false; // no request body bytes to chunk yet | |
2505 | ||
2506 | // optimization: pre-allocate buffer size that should be enough | |
2507 | const mb_size_t rawDataSize = raw.contentSize(); | |
2508 | // we may need to send: hex-chunk-size CRLF raw-data CRLF last-chunk | |
2509 | buf.init(16 + 2 + rawDataSize + 2 + 5, raw.max_capacity); | |
2510 | ||
4391cd15 | 2511 | buf.appendf("%x\r\n", static_cast<unsigned int>(rawDataSize)); |
39cb8c41 | 2512 | buf.append(raw.content(), rawDataSize); |
4391cd15 | 2513 | buf.append("\r\n", 2); |
39cb8c41 | 2514 | |
2f8abb64 | 2515 | Must(rawDataSize > 0); // we did not accidentally created last-chunk above |
39cb8c41 AR |
2516 | |
2517 | // Do not send last-chunk unless we successfully received everything | |
2518 | if (receivedWholeRequestBody) { | |
2519 | Must(!flags.sentLastChunk); | |
2520 | flags.sentLastChunk = true; | |
de48b288 | 2521 | buf.append("0\r\n\r\n", 5); |
39cb8c41 AR |
2522 | } |
2523 | ||
2524 | return true; | |
2525 | } | |
2526 | ||
910169e5 | 2527 | void |
b6b6f466 | 2528 | httpStart(FwdState *fwd) |
603a02fd | 2529 | { |
7f06a3d8 | 2530 | debugs(11, 3, fwd->request->method << ' ' << fwd->entry->url()); |
79628299 CT |
2531 | AsyncJob::Start(new HttpStateData(fwd)); |
2532 | } | |
62e76326 | 2533 | |
79628299 CT |
2534 | void |
2535 | HttpStateData::start() | |
2536 | { | |
2537 | if (!sendRequest()) { | |
bf8fe701 | 2538 | debugs(11, 3, "httpStart: aborted"); |
79628299 | 2539 | mustStop("HttpStateData::start failed"); |
5f8252d2 | 2540 | return; |
2541 | } | |
62e76326 | 2542 | |
95dc7ff4 FC |
2543 | ++ statCounter.server.all.requests; |
2544 | ++ statCounter.server.http.requests; | |
62e76326 | 2545 | |
b6a2f15e | 2546 | /* |
2547 | * We used to set the read timeout here, but not any more. | |
2548 | * Now its set in httpSendComplete() after the full request, | |
2549 | * including request body, has been written to the server. | |
2550 | */ | |
090089c4 | 2551 | } |
2552 | ||
39cb8c41 AR |
2553 | /// if broken posts are enabled for the request, try to fix and return true |
2554 | bool | |
2555 | HttpStateData::finishingBrokenPost() | |
2bb867b5 | 2556 | { |
626096be | 2557 | #if USE_HTTP_VIOLATIONS |
39cb8c41 | 2558 | if (!Config.accessList.brokenPosts) { |
bf95c10a | 2559 | debugs(11, 5, "No brokenPosts list"); |
39cb8c41 AR |
2560 | return false; |
2561 | } | |
a0297974 | 2562 | |
d603e3c2 | 2563 | ACLFilledChecklist ch(Config.accessList.brokenPosts, originalRequest().getRaw()); |
cb365059 EB |
2564 | ch.al = fwd->al; |
2565 | ch.syncAle(originalRequest().getRaw(), nullptr); | |
06bf5384 | 2566 | if (!ch.fastCheck().allowed()) { |
bf95c10a | 2567 | debugs(11, 5, "didn't match brokenPosts"); |
39cb8c41 AR |
2568 | return false; |
2569 | } | |
a0297974 | 2570 | |
9cf7de1b | 2571 | if (!Comm::IsConnOpen(serverConnection)) { |
bf95c10a | 2572 | debugs(11, 3, "ignoring broken POST for closed " << serverConnection); |
aee3523a | 2573 | assert(closeHandler != nullptr); |
39cb8c41 | 2574 | return true; // prevent caller from proceeding as if nothing happened |
54220df8 | 2575 | } |
39cb8c41 | 2576 | |
30c48b1a | 2577 | debugs(11, 3, "finishingBrokenPost: fixing broken POST"); |
39cb8c41 AR |
2578 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; |
2579 | requestSender = JobCallback(11,5, | |
2580 | Dialer, this, HttpStateData::wroteLast); | |
aee3523a | 2581 | Comm::Write(serverConnection, "\r\n", 2, requestSender, nullptr); |
39cb8c41 AR |
2582 | return true; |
2583 | #else | |
2584 | return false; | |
626096be | 2585 | #endif /* USE_HTTP_VIOLATIONS */ |
39cb8c41 AR |
2586 | } |
2587 | ||
2588 | /// if needed, write last-chunk to end the request body and return true | |
2589 | bool | |
2590 | HttpStateData::finishingChunkedRequest() | |
2591 | { | |
2592 | if (flags.sentLastChunk) { | |
bf95c10a | 2593 | debugs(11, 5, "already sent last-chunk"); |
39cb8c41 AR |
2594 | return false; |
2595 | } | |
2596 | ||
2597 | Must(receivedWholeRequestBody); // or we should not be sending last-chunk | |
2598 | flags.sentLastChunk = true; | |
2599 | ||
2600 | typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer; | |
e0d28505 | 2601 | requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast); |
aee3523a | 2602 | Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, nullptr); |
39cb8c41 AR |
2603 | return true; |
2604 | } | |
2605 | ||
2606 | void | |
2607 | HttpStateData::doneSendingRequestBody() | |
2608 | { | |
fccd4a86 | 2609 | Client::doneSendingRequestBody(); |
bf95c10a | 2610 | debugs(11,5, serverConnection); |
39cb8c41 AR |
2611 | |
2612 | // do we need to write something after the last body byte? | |
e31a1e67 | 2613 | if (flags.chunked_request && finishingChunkedRequest()) |
39cb8c41 | 2614 | return; |
e31a1e67 | 2615 | if (!flags.chunked_request && finishingBrokenPost()) |
39cb8c41 | 2616 | return; |
aa49962c | 2617 | |
39cb8c41 | 2618 | sendComplete(); |
94439e4e | 2619 | } |
2620 | ||
5f8252d2 | 2621 | // more origin request body data is available |
2bb867b5 | 2622 | void |
5f8252d2 | 2623 | HttpStateData::handleMoreRequestBodyAvailable() |
2bb867b5 | 2624 | { |
6b679a01 | 2625 | if (eof || !Comm::IsConnOpen(serverConnection)) { |
5f8252d2 | 2626 | // XXX: we should check this condition in other callbacks then! |
2627 | // TODO: Check whether this can actually happen: We should unsubscribe | |
2628 | // as a body consumer when the above condition(s) are detected. | |
bf95c10a | 2629 | debugs(11, DBG_IMPORTANT, "Transaction aborted while reading HTTP body"); |
2bb867b5 | 2630 | return; |
2631 | } | |
62e76326 | 2632 | |
aee3523a | 2633 | assert(requestBodySource != nullptr); |
fc68f6b1 | 2634 | |
5f8252d2 | 2635 | if (requestBodySource->buf().hasContent()) { |
2636 | // XXX: why does not this trigger a debug message on every request? | |
fc68f6b1 | 2637 | |
2bb867b5 | 2638 | if (flags.headers_parsed && !flags.abuse_detected) { |
46f4b111 | 2639 | flags.abuse_detected = true; |
e0236918 | 2640 | debugs(11, DBG_IMPORTANT, "http handleMoreRequestBodyAvailable: Likely proxy abuse detected '" << request->client_addr << "' -> '" << entry->url() << "'" ); |
21b92762 | 2641 | |
9b769c67 | 2642 | if (virginReply()->sline.status() == Http::scInvalidHeader) { |
398bc066 CT |
2643 | closeServer(); |
2644 | mustStop("HttpStateData::handleMoreRequestBodyAvailable"); | |
21b92762 | 2645 | return; |
2646 | } | |
2647 | } | |
b6a2f15e | 2648 | } |
5f8252d2 | 2649 | |
2650 | HttpStateData::handleMoreRequestBodyAvailable(); | |
376bb137 | 2651 | } |
2652 | ||
5f8252d2 | 2653 | // premature end of the request body |
2bb867b5 | 2654 | void |
5f8252d2 | 2655 | HttpStateData::handleRequestBodyProducerAborted() |
376bb137 | 2656 | { |
fccd4a86 | 2657 | Client::handleRequestBodyProducerAborted(); |
64b66b76 | 2658 | if (entry->isEmpty()) { |
25b481e6 | 2659 | debugs(11, 3, "request body aborted: " << serverConnection); |
8b997339 AR |
2660 | // We usually get here when ICAP REQMOD aborts during body processing. |
2661 | // We might also get here if client-side aborts, but then our response | |
2662 | // should not matter because either client-side will provide its own or | |
2663 | // there will be no response at all (e.g., if the the client has left). | |
7e6eabbc | 2664 | const auto err = new ErrorState(ERR_ICAP_FAILURE, Http::scInternalServerError, fwd->request, fwd->al); |
83b053a0 CT |
2665 | static const auto d = MakeNamedErrorDetail("SRV_REQMOD_REQ_BODY"); |
2666 | err->detailError(d); | |
64b66b76 CT |
2667 | fwd->fail(err); |
2668 | } | |
2669 | ||
39cb8c41 | 2670 | abortTransaction("request body producer aborted"); |
2bb867b5 | 2671 | } |
2672 | ||
5f8252d2 | 2673 | // called when we wrote request headers(!) or a part of the body |
2bb867b5 | 2674 | void |
dc56a9b1 | 2675 | HttpStateData::sentRequestBody(const CommIoCbParams &io) |
2bb867b5 | 2676 | { |
dc56a9b1 | 2677 | if (io.size > 0) |
a0864754 | 2678 | statCounter.server.http.kbytes_out += io.size; |
fc68f6b1 | 2679 | |
fccd4a86 | 2680 | Client::sentRequestBody(io); |
5f8252d2 | 2681 | } |
3b299123 | 2682 | |
5f8252d2 | 2683 | void |
92cfc72f | 2684 | HttpStateData::abortAll(const char *reason) |
5f8252d2 | 2685 | { |
bf95c10a | 2686 | debugs(11,5, "aborting transaction for " << reason << |
9cf7de1b | 2687 | "; " << serverConnection << ", this " << this); |
70df76e3 | 2688 | mustStop(reason); |
54220df8 | 2689 | } |
f53969cc | 2690 | |
39fe14b2 EB |
2691 | HttpStateData::ReuseDecision::ReuseDecision(const StoreEntry *e, const Http::StatusCode code) |
2692 | : answer(HttpStateData::ReuseDecision::reuseNot), reason(nullptr), entry(e), statusCode(code) {} | |
2693 | ||
2694 | HttpStateData::ReuseDecision::Answers | |
2695 | HttpStateData::ReuseDecision::make(const HttpStateData::ReuseDecision::Answers ans, const char *why) | |
2696 | { | |
2697 | answer = ans; | |
2698 | reason = why; | |
2699 | return answer; | |
2700 | } | |
2701 | ||
2702 | std::ostream &operator <<(std::ostream &os, const HttpStateData::ReuseDecision &d) | |
2703 | { | |
2704 | static const char *ReuseMessages[] = { | |
2705 | "do not cache and do not share", // reuseNot | |
2706 | "cache positively and share", // cachePositively | |
2707 | "cache negatively and share", // cacheNegatively | |
2708 | "do not cache but share" // doNotCacheButShare | |
2709 | }; | |
2710 | ||
2711 | assert(d.answer >= HttpStateData::ReuseDecision::reuseNot && | |
4a71b1fc | 2712 | d.answer <= HttpStateData::ReuseDecision::doNotCacheButShare); |
39fe14b2 | 2713 | return os << ReuseMessages[d.answer] << " because " << d.reason << |
4a71b1fc | 2714 | "; HTTP status " << d.statusCode << " " << *(d.entry); |
39fe14b2 EB |
2715 | } |
2716 |