]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * Copyright (C) 1996-2017 The Squid Software Foundation and contributors | |
3 | * | |
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. | |
7 | */ | |
8 | ||
9 | /* DEBUG: section 93 ICAP (RFC 3507) Client */ | |
10 | ||
11 | #include "squid.h" | |
12 | #include "AccessLogEntry.h" | |
13 | #include "adaptation/Answer.h" | |
14 | #include "adaptation/History.h" | |
15 | #include "adaptation/icap/Client.h" | |
16 | #include "adaptation/icap/Config.h" | |
17 | #include "adaptation/icap/History.h" | |
18 | #include "adaptation/icap/Launcher.h" | |
19 | #include "adaptation/icap/ModXact.h" | |
20 | #include "adaptation/icap/ServiceRep.h" | |
21 | #include "adaptation/Initiator.h" | |
22 | #include "auth/UserRequest.h" | |
23 | #include "base/TextException.h" | |
24 | #include "base64.h" | |
25 | #include "comm.h" | |
26 | #include "comm/Connection.h" | |
27 | #include "err_detail_type.h" | |
28 | #include "http/one/TeChunkedParser.h" | |
29 | #include "HttpHeaderTools.h" | |
30 | #include "HttpReply.h" | |
31 | #include "SquidTime.h" | |
32 | #include "URL.h" | |
33 | ||
34 | // flow and terminology: | |
35 | // HTTP| --> receive --> encode --> write --> |network | |
36 | // end | <-- send <-- parse <-- read <-- |end | |
37 | ||
38 | // TODO: replace gotEncapsulated() with something faster; we call it often | |
39 | ||
40 | CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXact); | |
41 | CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap, ModXactLauncher); | |
42 | ||
43 | static const size_t TheBackupLimit = BodyPipe::MaxCapacity; | |
44 | ||
45 | Adaptation::Icap::ModXact::State::State() | |
46 | { | |
47 | memset(this, 0, sizeof(*this)); | |
48 | } | |
49 | ||
50 | Adaptation::Icap::ModXact::ModXact(Http::Message *virginHeader, | |
51 | HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::Icap::ServiceRep::Pointer &aService): | |
52 | AsyncJob("Adaptation::Icap::ModXact"), | |
53 | Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService), | |
54 | virginConsumed(0), | |
55 | bodyParser(NULL), | |
56 | canStartBypass(false), // too early | |
57 | protectGroupBypass(true), | |
58 | replyHttpHeaderSize(-1), | |
59 | replyHttpBodySize(-1), | |
60 | adaptHistoryId(-1), | |
61 | trailerParser(nullptr), | |
62 | alMaster(alp) | |
63 | { | |
64 | assert(virginHeader); | |
65 | ||
66 | virgin.setHeader(virginHeader); // sets virgin.body_pipe if needed | |
67 | virgin.setCause(virginCause); // may be NULL | |
68 | ||
69 | // adapted header and body are initialized when we parse them | |
70 | ||
71 | // writing and reading ends are handled by Adaptation::Icap::Xaction | |
72 | ||
73 | // encoding | |
74 | // nothing to do because we are using temporary buffers | |
75 | ||
76 | // parsing; TODO: do not set until we parse, see ICAPOptXact | |
77 | icapReply = new HttpReply; | |
78 | icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class? | |
79 | ||
80 | debugs(93,7, HERE << "initialized." << status()); | |
81 | } | |
82 | ||
83 | // initiator wants us to start | |
84 | void Adaptation::Icap::ModXact::start() | |
85 | { | |
86 | Adaptation::Icap::Xaction::start(); | |
87 | ||
88 | // reserve an adaptation history slot (attempts are known at this time) | |
89 | Adaptation::History::Pointer ah = virginRequest().adaptLogHistory(); | |
90 | if (ah != NULL) | |
91 | adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1); | |
92 | ||
93 | estimateVirginBody(); // before virgin disappears! | |
94 | ||
95 | canStartBypass = service().cfg().bypass; | |
96 | ||
97 | // it is an ICAP violation to send request to a service w/o known OPTIONS | |
98 | // and the service may is too busy for us: honor Max-Connections and such | |
99 | if (service().up() && service().availableForNew()) | |
100 | startWriting(); | |
101 | else | |
102 | waitForService(); | |
103 | } | |
104 | ||
105 | void Adaptation::Icap::ModXact::waitForService() | |
106 | { | |
107 | const char *comment; | |
108 | Must(!state.serviceWaiting); | |
109 | ||
110 | if (!service().up()) { | |
111 | AsyncCall::Pointer call = JobCallback(93,5, | |
112 | ConnWaiterDialer, this, Adaptation::Icap::ModXact::noteServiceReady); | |
113 | ||
114 | service().callWhenReady(call); | |
115 | comment = "to be up"; | |
116 | } else { | |
117 | //The service is unavailable because of max-connection or other reason | |
118 | ||
119 | if (service().cfg().onOverload != srvWait) { | |
120 | // The service is overloaded, but waiting to be available prohibited by | |
121 | // user configuration (onOverload is set to "block" or "bypass") | |
122 | if (service().cfg().onOverload == srvBlock) | |
123 | disableBypass("not available", true); | |
124 | else //if (service().cfg().onOverload == srvBypass) | |
125 | canStartBypass = true; | |
126 | ||
127 | disableRetries(); | |
128 | disableRepeats("ICAP service is not available"); | |
129 | ||
130 | debugs(93, 7, HERE << "will not wait for the service to be available" << | |
131 | status()); | |
132 | ||
133 | throw TexcHere("ICAP service is not available"); | |
134 | } | |
135 | ||
136 | AsyncCall::Pointer call = JobCallback(93,5, | |
137 | ConnWaiterDialer, this, Adaptation::Icap::ModXact::noteServiceAvailable); | |
138 | service().callWhenAvailable(call, state.waitedForService); | |
139 | comment = "to be available"; | |
140 | } | |
141 | ||
142 | debugs(93, 7, HERE << "will wait for the service " << comment << status()); | |
143 | state.serviceWaiting = true; // after callWhenReady() which may throw | |
144 | state.waitedForService = true; | |
145 | } | |
146 | ||
147 | void Adaptation::Icap::ModXact::noteServiceReady() | |
148 | { | |
149 | Must(state.serviceWaiting); | |
150 | state.serviceWaiting = false; | |
151 | ||
152 | if (!service().up()) { | |
153 | disableRetries(); | |
154 | disableRepeats("ICAP service is unusable"); | |
155 | throw TexcHere("ICAP service is unusable"); | |
156 | } | |
157 | ||
158 | if (service().availableForOld()) | |
159 | startWriting(); | |
160 | else | |
161 | waitForService(); | |
162 | } | |
163 | ||
164 | void Adaptation::Icap::ModXact::noteServiceAvailable() | |
165 | { | |
166 | Must(state.serviceWaiting); | |
167 | state.serviceWaiting = false; | |
168 | ||
169 | if (service().up() && service().availableForOld()) | |
170 | startWriting(); | |
171 | else | |
172 | waitForService(); | |
173 | } | |
174 | ||
175 | void Adaptation::Icap::ModXact::startWriting() | |
176 | { | |
177 | state.writing = State::writingConnect; | |
178 | ||
179 | decideOnPreview(); // must be decided before we decideOnRetries | |
180 | decideOnRetries(); | |
181 | ||
182 | openConnection(); | |
183 | } | |
184 | ||
185 | // connection with the ICAP service established | |
186 | void Adaptation::Icap::ModXact::handleCommConnected() | |
187 | { | |
188 | Must(state.writing == State::writingConnect); | |
189 | ||
190 | startReading(); // wait for early errors from the ICAP server | |
191 | ||
192 | MemBuf requestBuf; | |
193 | requestBuf.init(); | |
194 | ||
195 | makeRequestHeaders(requestBuf); | |
196 | debugs(93, 9, HERE << "will write" << status() << ":\n" << | |
197 | (requestBuf.terminate(), requestBuf.content())); | |
198 | ||
199 | // write headers | |
200 | state.writing = State::writingHeaders; | |
201 | icap_tio_start = current_time; | |
202 | scheduleWrite(requestBuf); | |
203 | } | |
204 | ||
205 | void Adaptation::Icap::ModXact::handleCommWrote(size_t sz) | |
206 | { | |
207 | debugs(93, 5, HERE << "Wrote " << sz << " bytes"); | |
208 | ||
209 | if (state.writing == State::writingHeaders) | |
210 | handleCommWroteHeaders(); | |
211 | else | |
212 | handleCommWroteBody(); | |
213 | } | |
214 | ||
215 | void Adaptation::Icap::ModXact::handleCommWroteHeaders() | |
216 | { | |
217 | Must(state.writing == State::writingHeaders); | |
218 | ||
219 | // determine next step | |
220 | if (preview.enabled()) { | |
221 | if (preview.done()) | |
222 | decideWritingAfterPreview("zero-size"); | |
223 | else | |
224 | state.writing = State::writingPreview; | |
225 | } else if (virginBody.expected()) { | |
226 | state.writing = State::writingPrime; | |
227 | } else { | |
228 | stopWriting(true); | |
229 | return; | |
230 | } | |
231 | ||
232 | writeMore(); | |
233 | } | |
234 | ||
235 | void Adaptation::Icap::ModXact::writeMore() | |
236 | { | |
237 | debugs(93, 5, HERE << "checking whether to write more" << status()); | |
238 | ||
239 | if (writer != NULL) // already writing something | |
240 | return; | |
241 | ||
242 | switch (state.writing) { | |
243 | ||
244 | case State::writingInit: // waiting for service OPTIONS | |
245 | Must(state.serviceWaiting); | |
246 | ||
247 | case State::writingConnect: // waiting for the connection to establish | |
248 | ||
249 | case State::writingHeaders: // waiting for the headers to be written | |
250 | ||
251 | case State::writingPaused: // waiting for the ICAP server response | |
252 | ||
253 | case State::writingReallyDone: // nothing more to write | |
254 | return; | |
255 | ||
256 | case State::writingAlmostDone: // was waiting for the last write | |
257 | stopWriting(false); | |
258 | return; | |
259 | ||
260 | case State::writingPreview: | |
261 | writePreviewBody(); | |
262 | return; | |
263 | ||
264 | case State::writingPrime: | |
265 | writePrimeBody(); | |
266 | return; | |
267 | ||
268 | default: | |
269 | throw TexcHere("Adaptation::Icap::ModXact in bad writing state"); | |
270 | } | |
271 | } | |
272 | ||
273 | void Adaptation::Icap::ModXact::writePreviewBody() | |
274 | { | |
275 | debugs(93, 8, HERE << "will write Preview body from " << | |
276 | virgin.body_pipe << status()); | |
277 | Must(state.writing == State::writingPreview); | |
278 | Must(virgin.body_pipe != NULL); | |
279 | ||
280 | const size_t sizeMax = (size_t)virgin.body_pipe->buf().contentSize(); | |
281 | const size_t size = min(preview.debt(), sizeMax); | |
282 | writeSomeBody("preview body", size); | |
283 | ||
284 | // change state once preview is written | |
285 | ||
286 | if (preview.done()) | |
287 | decideWritingAfterPreview("body"); | |
288 | } | |
289 | ||
290 | /// determine state.writing after we wrote the entire preview | |
291 | void Adaptation::Icap::ModXact::decideWritingAfterPreview(const char *kind) | |
292 | { | |
293 | if (preview.ieof()) // nothing more to write | |
294 | stopWriting(true); | |
295 | else if (state.parsing == State::psIcapHeader) // did not get a reply yet | |
296 | state.writing = State::writingPaused; // wait for the ICAP server reply | |
297 | else | |
298 | stopWriting(true); // ICAP server reply implies no post-preview writing | |
299 | ||
300 | debugs(93, 6, HERE << "decided on writing after " << kind << " preview" << | |
301 | status()); | |
302 | } | |
303 | ||
304 | void Adaptation::Icap::ModXact::writePrimeBody() | |
305 | { | |
306 | Must(state.writing == State::writingPrime); | |
307 | Must(virginBodyWriting.active()); | |
308 | ||
309 | const size_t size = (size_t)virgin.body_pipe->buf().contentSize(); | |
310 | writeSomeBody("prime virgin body", size); | |
311 | ||
312 | if (virginBodyEndReached(virginBodyWriting)) { | |
313 | debugs(93, 5, HERE << "wrote entire body"); | |
314 | stopWriting(true); | |
315 | } | |
316 | } | |
317 | ||
318 | void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size) | |
319 | { | |
320 | Must(!writer && state.writing < state.writingAlmostDone); | |
321 | Must(virgin.body_pipe != NULL); | |
322 | debugs(93, 8, HERE << "will write up to " << size << " bytes of " << | |
323 | label); | |
324 | ||
325 | MemBuf writeBuf; // TODO: suggest a min size based on size and lastChunk | |
326 | ||
327 | writeBuf.init(); // note: we assume that last-chunk will fit | |
328 | ||
329 | const size_t writableSize = virginContentSize(virginBodyWriting); | |
330 | const size_t chunkSize = min(writableSize, size); | |
331 | ||
332 | if (chunkSize) { | |
333 | debugs(93, 7, HERE << "will write " << chunkSize << | |
334 | "-byte chunk of " << label); | |
335 | ||
336 | openChunk(writeBuf, chunkSize, false); | |
337 | writeBuf.append(virginContentData(virginBodyWriting), chunkSize); | |
338 | closeChunk(writeBuf); | |
339 | ||
340 | virginBodyWriting.progress(chunkSize); | |
341 | virginConsume(); | |
342 | } else { | |
343 | debugs(93, 7, HERE << "has no writable " << label << " content"); | |
344 | } | |
345 | ||
346 | const bool wroteEof = virginBodyEndReached(virginBodyWriting); | |
347 | bool lastChunk = wroteEof; | |
348 | if (state.writing == State::writingPreview) { | |
349 | preview.wrote(chunkSize, wroteEof); // even if wrote nothing | |
350 | lastChunk = lastChunk || preview.done(); | |
351 | } | |
352 | ||
353 | if (lastChunk) { | |
354 | debugs(93, 8, HERE << "will write last-chunk of " << label); | |
355 | addLastRequestChunk(writeBuf); | |
356 | } | |
357 | ||
358 | debugs(93, 7, HERE << "will write " << writeBuf.contentSize() | |
359 | << " raw bytes of " << label); | |
360 | ||
361 | if (writeBuf.hasContent()) { | |
362 | scheduleWrite(writeBuf); // comm will free the chunk | |
363 | } else { | |
364 | writeBuf.clean(); | |
365 | } | |
366 | } | |
367 | ||
368 | void Adaptation::Icap::ModXact::addLastRequestChunk(MemBuf &buf) | |
369 | { | |
370 | const bool ieof = state.writing == State::writingPreview && preview.ieof(); | |
371 | openChunk(buf, 0, ieof); | |
372 | closeChunk(buf); | |
373 | } | |
374 | ||
375 | void Adaptation::Icap::ModXact::openChunk(MemBuf &buf, size_t chunkSize, bool ieof) | |
376 | { | |
377 | buf.appendf((ieof ? "%x; ieof\r\n" : "%x\r\n"), (int) chunkSize); | |
378 | } | |
379 | ||
380 | void Adaptation::Icap::ModXact::closeChunk(MemBuf &buf) | |
381 | { | |
382 | buf.append(ICAP::crlf, 2); // chunk-terminating CRLF | |
383 | } | |
384 | ||
385 | const HttpRequest &Adaptation::Icap::ModXact::virginRequest() const | |
386 | { | |
387 | const HttpRequest *request = virgin.cause ? | |
388 | virgin.cause : dynamic_cast<const HttpRequest*>(virgin.header); | |
389 | Must(request); | |
390 | return *request; | |
391 | } | |
392 | ||
393 | // did the activity reached the end of the virgin body? | |
394 | bool Adaptation::Icap::ModXact::virginBodyEndReached(const Adaptation::Icap::VirginBodyAct &act) const | |
395 | { | |
396 | return | |
397 | !act.active() || // did all (assuming it was originally planned) | |
398 | !virgin.body_pipe->expectMoreAfter(act.offset()); // wont have more | |
399 | } | |
400 | ||
401 | // the size of buffered virgin body data available for the specified activity | |
402 | // if this size is zero, we may be done or may be waiting for more data | |
403 | size_t Adaptation::Icap::ModXact::virginContentSize(const Adaptation::Icap::VirginBodyAct &act) const | |
404 | { | |
405 | Must(act.active()); | |
406 | // asbolute start of unprocessed data | |
407 | const uint64_t dataStart = act.offset(); | |
408 | // absolute end of buffered data | |
409 | const uint64_t dataEnd = virginConsumed + virgin.body_pipe->buf().contentSize(); | |
410 | Must(virginConsumed <= dataStart && dataStart <= dataEnd); | |
411 | return static_cast<size_t>(dataEnd - dataStart); | |
412 | } | |
413 | ||
414 | // pointer to buffered virgin body data available for the specified activity | |
415 | const char *Adaptation::Icap::ModXact::virginContentData(const Adaptation::Icap::VirginBodyAct &act) const | |
416 | { | |
417 | Must(act.active()); | |
418 | const uint64_t dataStart = act.offset(); | |
419 | Must(virginConsumed <= dataStart); | |
420 | return virgin.body_pipe->buf().content() + static_cast<size_t>(dataStart-virginConsumed); | |
421 | } | |
422 | ||
423 | void Adaptation::Icap::ModXact::virginConsume() | |
424 | { | |
425 | debugs(93, 9, HERE << "consumption guards: " << !virgin.body_pipe << isRetriable << | |
426 | isRepeatable << canStartBypass << protectGroupBypass); | |
427 | ||
428 | if (!virgin.body_pipe) | |
429 | return; // nothing to consume | |
430 | ||
431 | if (isRetriable) | |
432 | return; // do not consume if we may have to retry later | |
433 | ||
434 | BodyPipe &bp = *virgin.body_pipe; | |
435 | const bool wantToPostpone = isRepeatable || canStartBypass || protectGroupBypass; | |
436 | ||
437 | // Why > 2? HttpState does not use the last bytes in the buffer | |
438 | // because delayAwareRead() is arguably broken. See | |
439 | // HttpStateData::maybeReadVirginBody for more details. | |
440 | if (wantToPostpone && bp.buf().spaceSize() > 2) { | |
441 | // Postponing may increase memory footprint and slow the HTTP side | |
442 | // down. Not postponing may increase the number of ICAP errors | |
443 | // if the ICAP service fails. We may also use "potential" space to | |
444 | // postpone more aggressively. Should the trade-off be configurable? | |
445 | debugs(93, 8, HERE << "postponing consumption from " << bp.status()); | |
446 | return; | |
447 | } | |
448 | ||
449 | const size_t have = static_cast<size_t>(bp.buf().contentSize()); | |
450 | const uint64_t end = virginConsumed + have; | |
451 | uint64_t offset = end; | |
452 | ||
453 | debugs(93, 9, HERE << "max virgin consumption offset=" << offset << | |
454 | " acts " << virginBodyWriting.active() << virginBodySending.active() << | |
455 | " consumed=" << virginConsumed << | |
456 | " from " << virgin.body_pipe->status()); | |
457 | ||
458 | if (virginBodyWriting.active()) | |
459 | offset = min(virginBodyWriting.offset(), offset); | |
460 | ||
461 | if (virginBodySending.active()) | |
462 | offset = min(virginBodySending.offset(), offset); | |
463 | ||
464 | Must(virginConsumed <= offset && offset <= end); | |
465 | ||
466 | if (const size_t size = static_cast<size_t>(offset - virginConsumed)) { | |
467 | debugs(93, 8, HERE << "consuming " << size << " out of " << have << | |
468 | " virgin body bytes"); | |
469 | bp.consume(size); | |
470 | virginConsumed += size; | |
471 | Must(!isRetriable); // or we should not be consuming | |
472 | disableRepeats("consumed content"); | |
473 | disableBypass("consumed content", true); | |
474 | } | |
475 | } | |
476 | ||
477 | void Adaptation::Icap::ModXact::handleCommWroteBody() | |
478 | { | |
479 | writeMore(); | |
480 | } | |
481 | ||
482 | // Called when we do not expect to call comm_write anymore. | |
483 | // We may have a pending write though. | |
484 | // If stopping nicely, we will just wait for that pending write, if any. | |
485 | void Adaptation::Icap::ModXact::stopWriting(bool nicely) | |
486 | { | |
487 | if (state.writing == State::writingReallyDone) | |
488 | return; | |
489 | ||
490 | if (writer != NULL) { | |
491 | if (nicely) { | |
492 | debugs(93, 7, HERE << "will wait for the last write" << status()); | |
493 | state.writing = State::writingAlmostDone; // may already be set | |
494 | checkConsuming(); | |
495 | return; | |
496 | } | |
497 | debugs(93, 3, HERE << "will NOT wait for the last write" << status()); | |
498 | ||
499 | // Comm does not have an interface to clear the writer callback nicely, | |
500 | // but without clearing the writer we cannot recycle the connection. | |
501 | // We prevent connection reuse and hope that we can handle a callback | |
502 | // call at any time, usually in the middle of the destruction sequence! | |
503 | // Somebody should add comm_remove_write_handler() to comm API. | |
504 | reuseConnection = false; | |
505 | ignoreLastWrite = true; | |
506 | } | |
507 | ||
508 | debugs(93, 7, HERE << "will no longer write" << status()); | |
509 | if (virginBodyWriting.active()) { | |
510 | virginBodyWriting.disable(); | |
511 | virginConsume(); | |
512 | } | |
513 | state.writing = State::writingReallyDone; | |
514 | checkConsuming(); | |
515 | } | |
516 | ||
517 | void Adaptation::Icap::ModXact::stopBackup() | |
518 | { | |
519 | if (!virginBodySending.active()) | |
520 | return; | |
521 | ||
522 | debugs(93, 7, HERE << "will no longer backup" << status()); | |
523 | virginBodySending.disable(); | |
524 | virginConsume(); | |
525 | } | |
526 | ||
527 | bool Adaptation::Icap::ModXact::doneAll() const | |
528 | { | |
529 | return Adaptation::Icap::Xaction::doneAll() && !state.serviceWaiting && | |
530 | doneSending() && | |
531 | doneReading() && state.doneWriting(); | |
532 | } | |
533 | ||
534 | void Adaptation::Icap::ModXact::startReading() | |
535 | { | |
536 | Must(haveConnection()); | |
537 | Must(!reader); | |
538 | Must(!adapted.header); | |
539 | Must(!adapted.body_pipe); | |
540 | ||
541 | // we use the same buffer for headers and body and then consume headers | |
542 | readMore(); | |
543 | } | |
544 | ||
545 | void Adaptation::Icap::ModXact::readMore() | |
546 | { | |
547 | if (reader != NULL || doneReading()) { | |
548 | debugs(93,3,HERE << "returning from readMore because reader or doneReading()"); | |
549 | return; | |
550 | } | |
551 | ||
552 | // do not fill readBuf if we have no space to store the result | |
553 | if (adapted.body_pipe != NULL && | |
554 | !adapted.body_pipe->buf().hasPotentialSpace()) { | |
555 | debugs(93,3,HERE << "not reading because ICAP reply pipe is full"); | |
556 | return; | |
557 | } | |
558 | ||
559 | if (readBuf.length() < SQUID_TCP_SO_RCVBUF) | |
560 | scheduleRead(); | |
561 | else | |
562 | debugs(93,3,HERE << "cannot read with a full buffer"); | |
563 | } | |
564 | ||
565 | // comm module read a portion of the ICAP response for us | |
566 | void Adaptation::Icap::ModXact::handleCommRead(size_t) | |
567 | { | |
568 | Must(!state.doneParsing()); | |
569 | icap_tio_finish = current_time; | |
570 | parseMore(); | |
571 | readMore(); | |
572 | } | |
573 | ||
574 | void Adaptation::Icap::ModXact::echoMore() | |
575 | { | |
576 | Must(state.sending == State::sendingVirgin); | |
577 | Must(adapted.body_pipe != NULL); | |
578 | Must(virginBodySending.active()); | |
579 | ||
580 | const size_t sizeMax = virginContentSize(virginBodySending); | |
581 | debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes from " << | |
582 | virgin.body_pipe->status()); | |
583 | debugs(93,5, HERE << "will echo up to " << sizeMax << " bytes to " << | |
584 | adapted.body_pipe->status()); | |
585 | ||
586 | if (sizeMax > 0) { | |
587 | const size_t size = adapted.body_pipe->putMoreData(virginContentData(virginBodySending), sizeMax); | |
588 | debugs(93,5, HERE << "echoed " << size << " out of " << sizeMax << | |
589 | " bytes"); | |
590 | virginBodySending.progress(size); | |
591 | disableRepeats("echoed content"); | |
592 | disableBypass("echoed content", true); | |
593 | virginConsume(); | |
594 | } | |
595 | ||
596 | if (virginBodyEndReached(virginBodySending)) { | |
597 | debugs(93, 5, HERE << "echoed all" << status()); | |
598 | stopSending(true); | |
599 | } else { | |
600 | debugs(93, 5, HERE << "has " << | |
601 | virgin.body_pipe->buf().contentSize() << " bytes " << | |
602 | "and expects more to echo" << status()); | |
603 | // TODO: timeout if virgin or adapted pipes are broken | |
604 | } | |
605 | } | |
606 | ||
607 | bool Adaptation::Icap::ModXact::doneSending() const | |
608 | { | |
609 | return state.sending == State::sendingDone; | |
610 | } | |
611 | ||
612 | // stop (or do not start) sending adapted message body | |
613 | void Adaptation::Icap::ModXact::stopSending(bool nicely) | |
614 | { | |
615 | debugs(93, 7, HERE << "Enter stop sending "); | |
616 | if (doneSending()) | |
617 | return; | |
618 | debugs(93, 7, HERE << "Proceed with stop sending "); | |
619 | ||
620 | if (state.sending != State::sendingUndecided) { | |
621 | debugs(93, 7, HERE << "will no longer send" << status()); | |
622 | if (adapted.body_pipe != NULL) { | |
623 | virginBodySending.disable(); | |
624 | // we may leave debts if we were echoing and the virgin | |
625 | // body_pipe got exhausted before we echoed all planned bytes | |
626 | const bool leftDebts = adapted.body_pipe->needsMoreData(); | |
627 | stopProducingFor(adapted.body_pipe, nicely && !leftDebts); | |
628 | } | |
629 | } else { | |
630 | debugs(93, 7, HERE << "will not start sending" << status()); | |
631 | Must(!adapted.body_pipe); | |
632 | } | |
633 | ||
634 | state.sending = State::sendingDone; | |
635 | checkConsuming(); | |
636 | } | |
637 | ||
638 | // should be called after certain state.writing or state.sending changes | |
639 | void Adaptation::Icap::ModXact::checkConsuming() | |
640 | { | |
641 | // quit if we already stopped or are still using the pipe | |
642 | if (!virgin.body_pipe || !state.doneConsumingVirgin()) | |
643 | return; | |
644 | ||
645 | debugs(93, 7, HERE << "will stop consuming" << status()); | |
646 | stopConsumingFrom(virgin.body_pipe); | |
647 | } | |
648 | ||
649 | void Adaptation::Icap::ModXact::parseMore() | |
650 | { | |
651 | debugs(93, 5, "have " << readBuf.length() << " bytes to parse" << status()); | |
652 | debugs(93, 5, "\n" << readBuf); | |
653 | ||
654 | if (state.parsingHeaders()) | |
655 | parseHeaders(); | |
656 | ||
657 | if (state.parsing == State::psBody) | |
658 | parseBody(); | |
659 | ||
660 | if (state.parsing == State::psIcapTrailer) | |
661 | parseIcapTrailer(); | |
662 | } | |
663 | ||
664 | void Adaptation::Icap::ModXact::callException(const std::exception &e) | |
665 | { | |
666 | if (!canStartBypass || isRetriable) { | |
667 | if (!isRetriable) { | |
668 | if (const TextException *te = dynamic_cast<const TextException *>(&e)) | |
669 | detailError(ERR_DETAIL_EXCEPTION_START + te->id()); | |
670 | else | |
671 | detailError(ERR_DETAIL_EXCEPTION_OTHER); | |
672 | } | |
673 | Adaptation::Icap::Xaction::callException(e); | |
674 | return; | |
675 | } | |
676 | ||
677 | try { | |
678 | debugs(93, 3, HERE << "bypassing " << inCall << " exception: " << | |
679 | e.what() << ' ' << status()); | |
680 | bypassFailure(); | |
681 | } catch (const TextException &bypassTe) { | |
682 | detailError(ERR_DETAIL_EXCEPTION_START + bypassTe.id()); | |
683 | Adaptation::Icap::Xaction::callException(bypassTe); | |
684 | } catch (const std::exception &bypassE) { | |
685 | detailError(ERR_DETAIL_EXCEPTION_OTHER); | |
686 | Adaptation::Icap::Xaction::callException(bypassE); | |
687 | } | |
688 | } | |
689 | ||
690 | void Adaptation::Icap::ModXact::bypassFailure() | |
691 | { | |
692 | disableBypass("already started to bypass", false); | |
693 | ||
694 | Must(!isRetriable); // or we should not be bypassing | |
695 | // TODO: should the same be enforced for isRepeatable? Check icap_repeat?? | |
696 | ||
697 | prepEchoing(); | |
698 | ||
699 | startSending(); | |
700 | ||
701 | // end all activities associated with the ICAP server | |
702 | ||
703 | stopParsing(false); | |
704 | ||
705 | stopWriting(true); // or should we force it? | |
706 | if (haveConnection()) { | |
707 | reuseConnection = false; // be conservative | |
708 | cancelRead(); // may not work; and we cannot stop connecting either | |
709 | if (!doneWithIo()) | |
710 | debugs(93, 7, HERE << "Warning: bypass failed to stop I/O" << status()); | |
711 | } | |
712 | ||
713 | service().noteFailure(); // we are bypassing, but this is still a failure | |
714 | } | |
715 | ||
716 | void Adaptation::Icap::ModXact::disableBypass(const char *reason, bool includingGroupBypass) | |
717 | { | |
718 | if (canStartBypass) { | |
719 | debugs(93,7, HERE << "will never start bypass because " << reason); | |
720 | canStartBypass = false; | |
721 | } | |
722 | if (protectGroupBypass && includingGroupBypass) { | |
723 | debugs(93,7, HERE << "not protecting group bypass because " << reason); | |
724 | protectGroupBypass = false; | |
725 | } | |
726 | } | |
727 | ||
728 | // note that allocation for echoing is done in handle204NoContent() | |
729 | void Adaptation::Icap::ModXact::maybeAllocateHttpMsg() | |
730 | { | |
731 | if (adapted.header) // already allocated | |
732 | return; | |
733 | ||
734 | if (gotEncapsulated("res-hdr")) { | |
735 | adapted.setHeader(new HttpReply); | |
736 | setOutcome(service().cfg().method == ICAP::methodReqmod ? | |
737 | xoSatisfied : xoModified); | |
738 | } else if (gotEncapsulated("req-hdr")) { | |
739 | adapted.setHeader(new HttpRequest); | |
740 | setOutcome(xoModified); | |
741 | } else | |
742 | throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()"); | |
743 | } | |
744 | ||
745 | void Adaptation::Icap::ModXact::parseHeaders() | |
746 | { | |
747 | Must(state.parsingHeaders()); | |
748 | ||
749 | if (state.parsing == State::psIcapHeader) { | |
750 | debugs(93, 5, HERE << "parse ICAP headers"); | |
751 | parseIcapHead(); | |
752 | } | |
753 | ||
754 | if (state.parsing == State::psHttpHeader) { | |
755 | debugs(93, 5, HERE << "parse HTTP headers"); | |
756 | parseHttpHead(); | |
757 | } | |
758 | ||
759 | if (state.parsingHeaders()) { // need more data | |
760 | Must(mayReadMore()); | |
761 | return; | |
762 | } | |
763 | ||
764 | startSending(); | |
765 | } | |
766 | ||
767 | // called after parsing all headers or when bypassing an exception | |
768 | void Adaptation::Icap::ModXact::startSending() | |
769 | { | |
770 | disableRepeats("sent headers"); | |
771 | disableBypass("sent headers", true); | |
772 | sendAnswer(Answer::Forward(adapted.header)); | |
773 | ||
774 | if (state.sending == State::sendingVirgin) | |
775 | echoMore(); | |
776 | else { | |
777 | // If we are not using the virgin HTTP object update the | |
778 | // Http::Message::sources flag. | |
779 | // The state.sending may set to State::sendingVirgin in the case | |
780 | // of 206 responses too, where we do not want to update Http::Message::sources | |
781 | // flag. However even for 206 responses the state.sending is | |
782 | // not set yet to sendingVirgin. This is done in later step | |
783 | // after the parseBody method called. | |
784 | updateSources(); | |
785 | } | |
786 | } | |
787 | ||
788 | void Adaptation::Icap::ModXact::parseIcapHead() | |
789 | { | |
790 | Must(state.sending == State::sendingUndecided); | |
791 | ||
792 | if (!parseHead(icapReply.getRaw())) | |
793 | return; | |
794 | ||
795 | if (expectIcapTrailers()) { | |
796 | Must(!trailerParser); | |
797 | trailerParser = new TrailerParser; | |
798 | } | |
799 | ||
800 | static SBuf close("close", 5); | |
801 | if (httpHeaderHasConnDir(&icapReply->header, close)) { | |
802 | debugs(93, 5, HERE << "found connection close"); | |
803 | reuseConnection = false; | |
804 | } | |
805 | ||
806 | switch (icapReply->sline.status()) { | |
807 | ||
808 | case Http::scContinue: | |
809 | handle100Continue(); | |
810 | break; | |
811 | ||
812 | case Http::scOkay: | |
813 | case Http::scCreated: // Symantec Scan Engine 5.0 and later when modifying HTTP msg | |
814 | ||
815 | if (!validate200Ok()) { | |
816 | throw TexcHere("Invalid ICAP Response"); | |
817 | } else { | |
818 | handle200Ok(); | |
819 | } | |
820 | ||
821 | break; | |
822 | ||
823 | case Http::scNoContent: | |
824 | handle204NoContent(); | |
825 | break; | |
826 | ||
827 | case Http::scPartialContent: | |
828 | handle206PartialContent(); | |
829 | break; | |
830 | ||
831 | default: | |
832 | debugs(93, 5, "ICAP status " << icapReply->sline.status()); | |
833 | handleUnknownScode(); | |
834 | break; | |
835 | } | |
836 | ||
837 | const HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header); | |
838 | if (!request) | |
839 | request = &virginRequest(); | |
840 | ||
841 | // update the cross-transactional database if needed (all status codes!) | |
842 | if (const char *xxName = Adaptation::Config::masterx_shared_name) { | |
843 | Adaptation::History::Pointer ah = request->adaptHistory(true); | |
844 | if (ah != NULL) { // TODO: reorder checks to avoid creating history | |
845 | const String val = icapReply->header.getByName(xxName); | |
846 | if (val.size() > 0) // XXX: HttpHeader lacks empty value detection | |
847 | ah->updateXxRecord(xxName, val); | |
848 | } | |
849 | } | |
850 | ||
851 | // update the adaptation plan if needed (all status codes!) | |
852 | if (service().cfg().routing) { | |
853 | String services; | |
854 | if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) { | |
855 | Adaptation::History::Pointer ah = request->adaptHistory(true); | |
856 | if (ah != NULL) | |
857 | ah->updateNextServices(services); | |
858 | } | |
859 | } // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES | |
860 | ||
861 | // We need to store received ICAP headers for <icapLastHeader logformat option. | |
862 | // If we already have stored headers from previous ICAP transaction related to this | |
863 | // request, old headers will be replaced with the new one. | |
864 | ||
865 | Adaptation::History::Pointer ah = request->adaptLogHistory(); | |
866 | if (ah != NULL) | |
867 | ah->recordMeta(&icapReply->header); | |
868 | ||
869 | // handle100Continue() manages state.writing on its own. | |
870 | // Non-100 status means the server needs no postPreview data from us. | |
871 | if (state.writing == State::writingPaused) | |
872 | stopWriting(true); | |
873 | } | |
874 | ||
875 | /// Parses ICAP trailers and stops parsing, if all trailer data | |
876 | /// have been received. | |
877 | void Adaptation::Icap::ModXact::parseIcapTrailer() { | |
878 | ||
879 | if (parsePart(trailerParser, "trailer")) { | |
880 | for (const auto &e: trailerParser->trailer.entries) | |
881 | debugs(93, 5, "ICAP trailer: " << e->name << ": " << e->value); | |
882 | stopParsing(); | |
883 | } | |
884 | } | |
885 | ||
886 | bool Adaptation::Icap::ModXact::validate200Ok() | |
887 | { | |
888 | if (service().cfg().method == ICAP::methodRespmod) | |
889 | return gotEncapsulated("res-hdr"); | |
890 | ||
891 | return service().cfg().method == ICAP::methodReqmod && | |
892 | expectHttpHeader(); | |
893 | } | |
894 | ||
895 | void Adaptation::Icap::ModXact::handle100Continue() | |
896 | { | |
897 | Must(state.writing == State::writingPaused); | |
898 | // server must not respond before the end of preview: we may send ieof | |
899 | Must(preview.enabled() && preview.done() && !preview.ieof()); | |
900 | ||
901 | // 100 "Continue" cancels our Preview commitment, | |
902 | // but not commitment to handle 204 or 206 outside Preview | |
903 | if (!state.allowedPostview204 && !state.allowedPostview206) | |
904 | stopBackup(); | |
905 | ||
906 | state.parsing = State::psIcapHeader; // eventually | |
907 | icapReply->reset(); | |
908 | ||
909 | state.writing = State::writingPrime; | |
910 | ||
911 | writeMore(); | |
912 | } | |
913 | ||
914 | void Adaptation::Icap::ModXact::handle200Ok() | |
915 | { | |
916 | state.parsing = State::psHttpHeader; | |
917 | state.sending = State::sendingAdapted; | |
918 | stopBackup(); | |
919 | checkConsuming(); | |
920 | } | |
921 | ||
922 | void Adaptation::Icap::ModXact::handle204NoContent() | |
923 | { | |
924 | stopParsing(); | |
925 | prepEchoing(); | |
926 | } | |
927 | ||
928 | void Adaptation::Icap::ModXact::handle206PartialContent() | |
929 | { | |
930 | if (state.writing == State::writingPaused) { | |
931 | Must(preview.enabled()); | |
932 | Must(state.allowedPreview206); | |
933 | debugs(93, 7, HERE << "206 inside preview"); | |
934 | } else { | |
935 | Must(state.writing > State::writingPaused); | |
936 | Must(state.allowedPostview206); | |
937 | debugs(93, 7, HERE << "206 outside preview"); | |
938 | } | |
939 | state.parsing = State::psHttpHeader; | |
940 | state.sending = State::sendingAdapted; | |
941 | state.readyForUob = true; | |
942 | checkConsuming(); | |
943 | } | |
944 | ||
945 | // Called when we receive a 204 No Content response and | |
946 | // when we are trying to bypass a service failure. | |
947 | // We actually start sending (echoig or not) in startSending. | |
948 | void Adaptation::Icap::ModXact::prepEchoing() | |
949 | { | |
950 | disableRepeats("preparing to echo content"); | |
951 | disableBypass("preparing to echo content", true); | |
952 | setOutcome(xoEcho); | |
953 | ||
954 | // We want to clone the HTTP message, but we do not want | |
955 | // to copy some non-HTTP state parts that Http::Message kids carry in them. | |
956 | // Thus, we cannot use a smart pointer, copy constructor, or equivalent. | |
957 | // Instead, we simply write the HTTP message and "clone" it by parsing. | |
958 | // TODO: use Http::Message::clone()! | |
959 | ||
960 | Http::Message *oldHead = virgin.header; | |
961 | debugs(93, 7, HERE << "cloning virgin message " << oldHead); | |
962 | ||
963 | MemBuf httpBuf; | |
964 | ||
965 | // write the virgin message into a memory buffer | |
966 | httpBuf.init(); | |
967 | packHead(httpBuf, oldHead); | |
968 | ||
969 | // allocate the adapted message and copy metainfo | |
970 | Must(!adapted.header); | |
971 | { | |
972 | Http::MessagePointer newHead; | |
973 | if (dynamic_cast<const HttpRequest*>(oldHead)) { | |
974 | newHead = new HttpRequest; | |
975 | } else if (dynamic_cast<const HttpReply*>(oldHead)) { | |
976 | newHead = new HttpReply; | |
977 | } | |
978 | Must(newHead); | |
979 | ||
980 | newHead->inheritProperties(oldHead); | |
981 | ||
982 | adapted.setHeader(newHead.getRaw()); | |
983 | } | |
984 | ||
985 | // parse the buffer back | |
986 | Http::StatusCode error = Http::scNone; | |
987 | ||
988 | httpBuf.terminate(); // Http::Message::parse requires nil-terminated buffer | |
989 | Must(adapted.header->parse(httpBuf.content(), httpBuf.contentSize(), true, &error)); | |
990 | Must(adapted.header->hdr_sz == httpBuf.contentSize()); // no leftovers | |
991 | ||
992 | httpBuf.clean(); | |
993 | ||
994 | debugs(93, 7, HERE << "cloned virgin message " << oldHead << " to " << | |
995 | adapted.header); | |
996 | ||
997 | // setup adapted body pipe if needed | |
998 | if (oldHead->body_pipe != NULL) { | |
999 | debugs(93, 7, HERE << "will echo virgin body from " << | |
1000 | oldHead->body_pipe); | |
1001 | if (!virginBodySending.active()) | |
1002 | virginBodySending.plan(); // will throw if not possible | |
1003 | state.sending = State::sendingVirgin; | |
1004 | checkConsuming(); | |
1005 | ||
1006 | // TODO: optimize: is it possible to just use the oldHead pipe and | |
1007 | // remove ICAP from the loop? This echoing is probably a common case! | |
1008 | makeAdaptedBodyPipe("echoed virgin response"); | |
1009 | if (oldHead->body_pipe->bodySizeKnown()) | |
1010 | adapted.body_pipe->setBodySize(oldHead->body_pipe->bodySize()); | |
1011 | debugs(93, 7, HERE << "will echo virgin body to " << | |
1012 | adapted.body_pipe); | |
1013 | } else { | |
1014 | debugs(93, 7, HERE << "no virgin body to echo"); | |
1015 | stopSending(true); | |
1016 | } | |
1017 | } | |
1018 | ||
1019 | /// Called when we received use-original-body chunk extension in 206 response. | |
1020 | /// We actually start sending (echoing or not) in startSending(). | |
1021 | void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos) | |
1022 | { | |
1023 | Must(virginBodySending.active()); | |
1024 | Must(virgin.header->body_pipe != NULL); | |
1025 | ||
1026 | setOutcome(xoPartEcho); | |
1027 | ||
1028 | debugs(93, 7, HERE << "will echo virgin body suffix from " << | |
1029 | virgin.header->body_pipe << " offset " << pos ); | |
1030 | ||
1031 | // check that use-original-body=N does not point beyond buffered data | |
1032 | const uint64_t virginDataEnd = virginConsumed + | |
1033 | virgin.body_pipe->buf().contentSize(); | |
1034 | Must(pos <= virginDataEnd); | |
1035 | virginBodySending.progress(static_cast<size_t>(pos)); | |
1036 | ||
1037 | state.sending = State::sendingVirgin; | |
1038 | checkConsuming(); | |
1039 | ||
1040 | if (virgin.header->body_pipe->bodySizeKnown()) | |
1041 | adapted.body_pipe->expectProductionEndAfter(virgin.header->body_pipe->bodySize() - pos); | |
1042 | ||
1043 | debugs(93, 7, HERE << "will echo virgin body suffix to " << | |
1044 | adapted.body_pipe); | |
1045 | ||
1046 | // Start echoing data | |
1047 | echoMore(); | |
1048 | } | |
1049 | ||
1050 | void Adaptation::Icap::ModXact::handleUnknownScode() | |
1051 | { | |
1052 | stopParsing(false); | |
1053 | stopBackup(); | |
1054 | // TODO: mark connection as "bad" | |
1055 | ||
1056 | // Terminate the transaction; we do not know how to handle this response. | |
1057 | throw TexcHere("Unsupported ICAP status code"); | |
1058 | } | |
1059 | ||
1060 | void Adaptation::Icap::ModXact::parseHttpHead() | |
1061 | { | |
1062 | if (expectHttpHeader()) { | |
1063 | replyHttpHeaderSize = 0; | |
1064 | maybeAllocateHttpMsg(); | |
1065 | ||
1066 | if (!parseHead(adapted.header)) | |
1067 | return; // need more header data | |
1068 | ||
1069 | if (adapted.header) | |
1070 | replyHttpHeaderSize = adapted.header->hdr_sz; | |
1071 | ||
1072 | if (dynamic_cast<HttpRequest*>(adapted.header)) { | |
1073 | const HttpRequest *oldR = dynamic_cast<const HttpRequest*>(virgin.header); | |
1074 | Must(oldR); | |
1075 | // TODO: the adapted request did not really originate from the | |
1076 | // client; give proxy admin an option to prevent copying of | |
1077 | // sensitive client information here. See the following thread: | |
1078 | // http://www.squid-cache.org/mail-archive/squid-dev/200703/0040.html | |
1079 | } | |
1080 | ||
1081 | // Maybe adapted.header==NULL if HttpReply and have Http 0.9 .... | |
1082 | if (adapted.header) | |
1083 | adapted.header->inheritProperties(virgin.header); | |
1084 | } | |
1085 | ||
1086 | decideOnParsingBody(); | |
1087 | } | |
1088 | ||
1089 | template<class Part> | |
1090 | bool Adaptation::Icap::ModXact::parsePart(Part *part, const char *description) | |
1091 | { | |
1092 | Must(part); | |
1093 | debugs(93, 5, "have " << readBuf.length() << ' ' << description << " bytes to parse; state: " << state.parsing); | |
1094 | Http::StatusCode error = Http::scNone; | |
1095 | // XXX: performance regression. c_str() data copies | |
1096 | // XXX: Http::Message::parse requires a terminated string buffer | |
1097 | const char *tmpBuf = readBuf.c_str(); | |
1098 | const bool parsed = part->parse(tmpBuf, readBuf.length(), commEof, &error); | |
1099 | debugs(93, (!parsed && error) ? 2 : 5, description << " parsing result: " << parsed << " detail: " << error); | |
1100 | Must(parsed || !error); | |
1101 | if (parsed) | |
1102 | readBuf.consume(part->hdr_sz); | |
1103 | return parsed; | |
1104 | } | |
1105 | ||
1106 | // parses both HTTP and ICAP headers | |
1107 | bool | |
1108 | Adaptation::Icap::ModXact::parseHead(Http::Message *head) | |
1109 | { | |
1110 | if (!parsePart(head, "head")) { | |
1111 | head->reset(); | |
1112 | return false; | |
1113 | } | |
1114 | return true; | |
1115 | } | |
1116 | ||
1117 | bool Adaptation::Icap::ModXact::expectHttpHeader() const | |
1118 | { | |
1119 | return gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr"); | |
1120 | } | |
1121 | ||
1122 | bool Adaptation::Icap::ModXact::expectHttpBody() const | |
1123 | { | |
1124 | return gotEncapsulated("res-body") || gotEncapsulated("req-body"); | |
1125 | } | |
1126 | ||
1127 | bool Adaptation::Icap::ModXact::expectIcapTrailers() const | |
1128 | { | |
1129 | String trailers; | |
1130 | const bool promisesToSendTrailer = icapReply->header.getByIdIfPresent(Http::HdrType::TRAILER, &trailers); | |
1131 | const bool supportsTrailers = icapReply->header.hasListMember(Http::HdrType::ALLOW, "trailers", ','); | |
1132 | // ICAP Trailer specs require us to reject transactions having either Trailer | |
1133 | // header or Allow:trailers | |
1134 | Must((promisesToSendTrailer == supportsTrailers) || (!promisesToSendTrailer && supportsTrailers)); | |
1135 | if (promisesToSendTrailer && !trailers.size()) | |
1136 | debugs(93, DBG_IMPORTANT, "ERROR: ICAP Trailer response header field must not be empty (salvaged)"); | |
1137 | return promisesToSendTrailer; | |
1138 | } | |
1139 | ||
1140 | void Adaptation::Icap::ModXact::decideOnParsingBody() | |
1141 | { | |
1142 | if (expectHttpBody()) { | |
1143 | debugs(93, 5, HERE << "expecting a body"); | |
1144 | state.parsing = State::psBody; | |
1145 | replyHttpBodySize = 0; | |
1146 | bodyParser = new Http1::TeChunkedParser; | |
1147 | makeAdaptedBodyPipe("adapted response from the ICAP server"); | |
1148 | Must(state.sending == State::sendingAdapted); | |
1149 | } else { | |
1150 | debugs(93, 5, HERE << "not expecting a body"); | |
1151 | if (trailerParser) | |
1152 | state.parsing = State::psIcapTrailer; | |
1153 | else | |
1154 | stopParsing(); | |
1155 | stopSending(true); | |
1156 | } | |
1157 | } | |
1158 | ||
1159 | void Adaptation::Icap::ModXact::parseBody() | |
1160 | { | |
1161 | Must(state.parsing == State::psBody); | |
1162 | Must(bodyParser); | |
1163 | ||
1164 | debugs(93, 5, "have " << readBuf.length() << " body bytes to parse"); | |
1165 | ||
1166 | // the parser will throw on errors | |
1167 | BodyPipeCheckout bpc(*adapted.body_pipe); | |
1168 | bodyParser->setPayloadBuffer(&bpc.buf); | |
1169 | const bool parsed = bodyParser->parse(readBuf); | |
1170 | readBuf = bodyParser->remaining(); // sync buffers after parse | |
1171 | bpc.checkIn(); | |
1172 | ||
1173 | debugs(93, 5, "have " << readBuf.length() << " body bytes after parsed all: " << parsed); | |
1174 | replyHttpBodySize += adapted.body_pipe->buf().contentSize(); | |
1175 | ||
1176 | // TODO: expose BodyPipe::putSize() to make this check simpler and clearer | |
1177 | // TODO: do we really need this if we disable when sending headers? | |
1178 | if (adapted.body_pipe->buf().contentSize() > 0) { // parsed something sometime | |
1179 | disableRepeats("sent adapted content"); | |
1180 | disableBypass("sent adapted content", true); | |
1181 | } | |
1182 | ||
1183 | if (parsed) { | |
1184 | if (state.readyForUob && bodyParser->useOriginBody >= 0) | |
1185 | prepPartialBodyEchoing(static_cast<uint64_t>(bodyParser->useOriginBody)); | |
1186 | else | |
1187 | stopSending(true); // the parser succeeds only if all parsed data fits | |
1188 | if (trailerParser) | |
1189 | state.parsing = State::psIcapTrailer; | |
1190 | else | |
1191 | stopParsing(); | |
1192 | return; | |
1193 | } | |
1194 | ||
1195 | debugs(93,3,HERE << this << " needsMoreData = " << bodyParser->needsMoreData()); | |
1196 | ||
1197 | if (bodyParser->needsMoreData()) { | |
1198 | debugs(93,3,HERE << this); | |
1199 | Must(mayReadMore()); | |
1200 | readMore(); | |
1201 | } | |
1202 | ||
1203 | if (bodyParser->needsMoreSpace()) { | |
1204 | Must(!doneSending()); // can hope for more space | |
1205 | Must(adapted.body_pipe->buf().contentSize() > 0); // paranoid | |
1206 | // TODO: there should be a timeout in case the sink is broken | |
1207 | // or cannot consume partial content (while we need more space) | |
1208 | } | |
1209 | } | |
1210 | ||
1211 | void Adaptation::Icap::ModXact::stopParsing(const bool checkUnparsedData) | |
1212 | { | |
1213 | if (state.parsing == State::psDone) | |
1214 | return; | |
1215 | ||
1216 | if (checkUnparsedData) | |
1217 | Must(readBuf.isEmpty()); | |
1218 | ||
1219 | debugs(93, 7, "will no longer parse" << status()); | |
1220 | ||
1221 | delete bodyParser; | |
1222 | bodyParser = nullptr; | |
1223 | ||
1224 | delete trailerParser; | |
1225 | trailerParser = nullptr; | |
1226 | ||
1227 | state.parsing = State::psDone; | |
1228 | } | |
1229 | ||
1230 | // HTTP side added virgin body data | |
1231 | void Adaptation::Icap::ModXact::noteMoreBodyDataAvailable(BodyPipe::Pointer) | |
1232 | { | |
1233 | writeMore(); | |
1234 | ||
1235 | if (state.sending == State::sendingVirgin) | |
1236 | echoMore(); | |
1237 | } | |
1238 | ||
1239 | // HTTP side sent us all virgin info | |
1240 | void Adaptation::Icap::ModXact::noteBodyProductionEnded(BodyPipe::Pointer) | |
1241 | { | |
1242 | Must(virgin.body_pipe->productionEnded()); | |
1243 | ||
1244 | // push writer and sender in case we were waiting for the last-chunk | |
1245 | writeMore(); | |
1246 | ||
1247 | if (state.sending == State::sendingVirgin) | |
1248 | echoMore(); | |
1249 | } | |
1250 | ||
1251 | // body producer aborted, but the initiator may still want to know | |
1252 | // the answer, even though the HTTP message has been truncated | |
1253 | void Adaptation::Icap::ModXact::noteBodyProducerAborted(BodyPipe::Pointer) | |
1254 | { | |
1255 | Must(virgin.body_pipe->productionEnded()); | |
1256 | ||
1257 | // push writer and sender in case we were waiting for the last-chunk | |
1258 | writeMore(); | |
1259 | ||
1260 | if (state.sending == State::sendingVirgin) | |
1261 | echoMore(); | |
1262 | } | |
1263 | ||
1264 | // adapted body consumer wants more adapted data and | |
1265 | // possibly freed some buffer space | |
1266 | void Adaptation::Icap::ModXact::noteMoreBodySpaceAvailable(BodyPipe::Pointer) | |
1267 | { | |
1268 | if (state.sending == State::sendingVirgin) | |
1269 | echoMore(); | |
1270 | else if (state.sending == State::sendingAdapted) | |
1271 | parseMore(); | |
1272 | else | |
1273 | Must(state.sending == State::sendingUndecided); | |
1274 | } | |
1275 | ||
1276 | // adapted body consumer aborted | |
1277 | void Adaptation::Icap::ModXact::noteBodyConsumerAborted(BodyPipe::Pointer) | |
1278 | { | |
1279 | detailError(ERR_DETAIL_ICAP_XACT_BODY_CONSUMER_ABORT); | |
1280 | mustStop("adapted body consumer aborted"); | |
1281 | } | |
1282 | ||
1283 | Adaptation::Icap::ModXact::~ModXact() | |
1284 | { | |
1285 | delete bodyParser; | |
1286 | delete trailerParser; | |
1287 | } | |
1288 | ||
1289 | // internal cleanup | |
1290 | void Adaptation::Icap::ModXact::swanSong() | |
1291 | { | |
1292 | debugs(93, 5, HERE << "swan sings" << status()); | |
1293 | ||
1294 | stopWriting(false); | |
1295 | stopSending(false); | |
1296 | ||
1297 | if (theInitiator.set()) // we have not sent the answer to the initiator | |
1298 | detailError(ERR_DETAIL_ICAP_XACT_OTHER); | |
1299 | ||
1300 | // update adaptation history if start was called and we reserved a slot | |
1301 | Adaptation::History::Pointer ah = virginRequest().adaptLogHistory(); | |
1302 | if (ah != NULL && adaptHistoryId >= 0) | |
1303 | ah->recordXactFinish(adaptHistoryId); | |
1304 | ||
1305 | Adaptation::Icap::Xaction::swanSong(); | |
1306 | } | |
1307 | ||
1308 | void prepareLogWithRequestDetails(HttpRequest *, AccessLogEntry::Pointer &); | |
1309 | ||
1310 | void Adaptation::Icap::ModXact::finalizeLogInfo() | |
1311 | { | |
1312 | HttpRequest *adapted_request_ = nullptr; | |
1313 | HttpReply *adapted_reply_ = nullptr; | |
1314 | HttpRequest *virgin_request_ = const_cast<HttpRequest*>(&virginRequest()); | |
1315 | if (!(adapted_request_ = dynamic_cast<HttpRequest*>(adapted.header))) { | |
1316 | // if the request was not adapted, use virgin request to simplify | |
1317 | // the code further below | |
1318 | adapted_request_ = virgin_request_; | |
1319 | adapted_reply_ = dynamic_cast<HttpReply*>(adapted.header); | |
1320 | } | |
1321 | ||
1322 | Adaptation::Icap::History::Pointer h = virgin_request_->icapHistory(); | |
1323 | Must(h != NULL); // ICAPXaction::maybeLog calls only if there is a log | |
1324 | al.icp.opcode = ICP_INVALID; | |
1325 | al.url = h->log_uri.termedBuf(); | |
1326 | const Adaptation::Icap::ServiceRep &s = service(); | |
1327 | al.icap.reqMethod = s.cfg().method; | |
1328 | ||
1329 | al.cache.caddr = virgin_request_->client_addr; | |
1330 | ||
1331 | al.request = virgin_request_; | |
1332 | HTTPMSGLOCK(al.request); | |
1333 | al.adapted_request = adapted_request_; | |
1334 | HTTPMSGLOCK(al.adapted_request); | |
1335 | ||
1336 | if (adapted_reply_) { | |
1337 | al.reply = adapted_reply_; | |
1338 | HTTPMSGLOCK(al.reply); | |
1339 | } else | |
1340 | al.reply = NULL; | |
1341 | ||
1342 | if (h->rfc931.size()) | |
1343 | al.cache.rfc931 = h->rfc931.termedBuf(); | |
1344 | ||
1345 | #if USE_OPENSSL | |
1346 | if (h->ssluser.size()) | |
1347 | al.cache.ssluser = h->ssluser.termedBuf(); | |
1348 | #endif | |
1349 | al.cache.code = h->logType; | |
1350 | ||
1351 | const Http::Message *virgin_msg = dynamic_cast<HttpReply*>(virgin.header); | |
1352 | if (!virgin_msg) | |
1353 | virgin_msg = virgin_request_; | |
1354 | assert(virgin_msg != virgin.cause); | |
1355 | al.http.clientRequestSz.header = virgin_msg->hdr_sz; | |
1356 | if (virgin_msg->body_pipe != NULL) | |
1357 | al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize(); | |
1358 | ||
1359 | // leave al.icap.bodyBytesRead negative if no body | |
1360 | if (replyHttpHeaderSize >= 0 || replyHttpBodySize >= 0) { | |
1361 | const int64_t zero = 0; // to make max() argument types the same | |
1362 | const uint64_t headerSize = max(zero, replyHttpHeaderSize); | |
1363 | const uint64_t bodySize = max(zero, replyHttpBodySize); | |
1364 | al.icap.bodyBytesRead = headerSize + bodySize; | |
1365 | al.http.clientReplySz.header = headerSize; | |
1366 | al.http.clientReplySz.payloadData = bodySize; | |
1367 | } | |
1368 | ||
1369 | if (adapted_reply_) { | |
1370 | al.http.code = adapted_reply_->sline.status(); | |
1371 | al.http.content_type = adapted_reply_->content_type.termedBuf(); | |
1372 | if (replyHttpBodySize >= 0) | |
1373 | al.cache.highOffset = replyHttpBodySize; | |
1374 | //don't set al.cache.objectSize because it hasn't exist yet | |
1375 | ||
1376 | MemBuf mb; | |
1377 | mb.init(); | |
1378 | adapted_reply_->header.packInto(&mb); | |
1379 | al.headers.reply = xstrdup(mb.buf); | |
1380 | mb.clean(); | |
1381 | } | |
1382 | prepareLogWithRequestDetails(adapted_request_, alep); | |
1383 | Xaction::finalizeLogInfo(); | |
1384 | } | |
1385 | ||
1386 | void Adaptation::Icap::ModXact::makeRequestHeaders(MemBuf &buf) | |
1387 | { | |
1388 | char ntoabuf[MAX_IPSTRLEN]; | |
1389 | /* | |
1390 | * XXX These should use HttpHdr interfaces instead of Printfs | |
1391 | */ | |
1392 | const Adaptation::ServiceConfig &s = service().cfg(); | |
1393 | buf.appendf("%s " SQUIDSTRINGPH " ICAP/1.0\r\n", s.methodStr(), SQUIDSTRINGPRINT(s.uri)); | |
1394 | buf.appendf("Host: " SQUIDSTRINGPH ":%d\r\n", SQUIDSTRINGPRINT(s.host), s.port); | |
1395 | buf.appendf("Date: %s\r\n", mkrfc1123(squid_curtime)); | |
1396 | ||
1397 | if (!TheConfig.reuse_connections) | |
1398 | buf.appendf("Connection: close\r\n"); | |
1399 | ||
1400 | const HttpRequest *request = &virginRequest(); | |
1401 | ||
1402 | // we must forward "Proxy-Authenticate" and "Proxy-Authorization" | |
1403 | // as ICAP headers. | |
1404 | if (virgin.header->header.has(Http::HdrType::PROXY_AUTHENTICATE)) { | |
1405 | String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHENTICATE); | |
1406 | buf.appendf("Proxy-Authenticate: " SQUIDSTRINGPH "\r\n",SQUIDSTRINGPRINT(vh)); | |
1407 | } | |
1408 | ||
1409 | if (virgin.header->header.has(Http::HdrType::PROXY_AUTHORIZATION)) { | |
1410 | String vh=virgin.header->header.getById(Http::HdrType::PROXY_AUTHORIZATION); | |
1411 | buf.appendf("Proxy-Authorization: " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(vh)); | |
1412 | } else if (request->extacl_user.size() > 0 && request->extacl_passwd.size() > 0) { | |
1413 | struct base64_encode_ctx ctx; | |
1414 | base64_encode_init(&ctx); | |
1415 | uint8_t base64buf[base64_encode_len(MAX_LOGIN_SZ)]; | |
1416 | size_t resultLen = base64_encode_update(&ctx, base64buf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf())); | |
1417 | resultLen += base64_encode_update(&ctx, base64buf+resultLen, 1, reinterpret_cast<const uint8_t*>(":")); | |
1418 | resultLen += base64_encode_update(&ctx, base64buf+resultLen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf())); | |
1419 | resultLen += base64_encode_final(&ctx, base64buf+resultLen); | |
1420 | buf.appendf("Proxy-Authorization: Basic %.*s\r\n", (int)resultLen, base64buf); | |
1421 | } | |
1422 | ||
1423 | // share the cross-transactional database records if needed | |
1424 | if (Adaptation::Config::masterx_shared_name) { | |
1425 | Adaptation::History::Pointer ah = request->adaptHistory(false); | |
1426 | if (ah != NULL) { | |
1427 | String name, value; | |
1428 | if (ah->getXxRecord(name, value)) { | |
1429 | buf.appendf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value)); | |
1430 | } | |
1431 | } | |
1432 | } | |
1433 | ||
1434 | buf.append("Encapsulated: ", 14); | |
1435 | ||
1436 | MemBuf httpBuf; | |
1437 | ||
1438 | httpBuf.init(); | |
1439 | ||
1440 | // build HTTP request header, if any | |
1441 | ICAP::Method m = s.method; | |
1442 | ||
1443 | // to simplify, we could assume that request is always available | |
1444 | ||
1445 | if (request) { | |
1446 | if (ICAP::methodRespmod == m) | |
1447 | encapsulateHead(buf, "req-hdr", httpBuf, request); | |
1448 | else if (ICAP::methodReqmod == m) | |
1449 | encapsulateHead(buf, "req-hdr", httpBuf, virgin.header); | |
1450 | } | |
1451 | ||
1452 | if (ICAP::methodRespmod == m) | |
1453 | if (const Http::Message *prime = virgin.header) | |
1454 | encapsulateHead(buf, "res-hdr", httpBuf, prime); | |
1455 | ||
1456 | if (!virginBody.expected()) | |
1457 | buf.appendf("null-body=%d", (int) httpBuf.contentSize()); | |
1458 | else if (ICAP::methodReqmod == m) | |
1459 | buf.appendf("req-body=%d", (int) httpBuf.contentSize()); | |
1460 | else | |
1461 | buf.appendf("res-body=%d", (int) httpBuf.contentSize()); | |
1462 | ||
1463 | buf.append(ICAP::crlf, 2); // terminate Encapsulated line | |
1464 | ||
1465 | if (preview.enabled()) { | |
1466 | buf.appendf("Preview: %d\r\n", (int)preview.ad()); | |
1467 | if (!virginBody.expected()) // there is no body to preview | |
1468 | finishNullOrEmptyBodyPreview(httpBuf); | |
1469 | } | |
1470 | ||
1471 | makeAllowHeader(buf); | |
1472 | ||
1473 | if (TheConfig.send_client_ip && request) { | |
1474 | Ip::Address client_addr; | |
1475 | #if FOLLOW_X_FORWARDED_FOR | |
1476 | if (TheConfig.use_indirect_client) { | |
1477 | client_addr = request->indirect_client_addr; | |
1478 | } else | |
1479 | #endif | |
1480 | client_addr = request->client_addr; | |
1481 | if (!client_addr.isAnyAddr() && !client_addr.isNoAddr()) | |
1482 | buf.appendf("X-Client-IP: %s\r\n", client_addr.toStr(ntoabuf,MAX_IPSTRLEN)); | |
1483 | } | |
1484 | ||
1485 | if (TheConfig.send_username && request) | |
1486 | makeUsernameHeader(request, buf); | |
1487 | ||
1488 | // Adaptation::Config::metaHeaders | |
1489 | for (auto h: Adaptation::Config::metaHeaders) { | |
1490 | HttpRequest *r = virgin.cause ? | |
1491 | virgin.cause : dynamic_cast<HttpRequest*>(virgin.header); | |
1492 | Must(r); | |
1493 | ||
1494 | HttpReply *reply = dynamic_cast<HttpReply*>(virgin.header); | |
1495 | ||
1496 | SBuf matched; | |
1497 | if (h->match(r, reply, alMaster, matched)) { | |
1498 | buf.append(h->key().rawContent(), h->key().length()); | |
1499 | buf.append(": ", 2); | |
1500 | buf.append(matched.rawContent(), matched.length()); | |
1501 | buf.append("\r\n", 2); | |
1502 | Adaptation::History::Pointer ah = request->adaptHistory(false); | |
1503 | if (ah != NULL) { | |
1504 | if (ah->metaHeaders == NULL) | |
1505 | ah->metaHeaders = new NotePairs; | |
1506 | if (!ah->metaHeaders->hasPair(h->key(), matched)) | |
1507 | ah->metaHeaders->add(h->key(), matched); | |
1508 | } | |
1509 | } | |
1510 | } | |
1511 | ||
1512 | // fprintf(stderr, "%s\n", buf.content()); | |
1513 | ||
1514 | buf.append(ICAP::crlf, 2); // terminate ICAP header | |
1515 | ||
1516 | // fill icapRequest for logging | |
1517 | Must(icapRequest->parseCharBuf(buf.content(), buf.contentSize())); | |
1518 | ||
1519 | // start ICAP request body with encapsulated HTTP headers | |
1520 | buf.append(httpBuf.content(), httpBuf.contentSize()); | |
1521 | ||
1522 | httpBuf.clean(); | |
1523 | } | |
1524 | ||
1525 | // decides which Allow values to write and updates the request buffer | |
1526 | void Adaptation::Icap::ModXact::makeAllowHeader(MemBuf &buf) | |
1527 | { | |
1528 | const bool allow204in = preview.enabled(); // TODO: add shouldAllow204in() | |
1529 | const bool allow204out = state.allowedPostview204 = shouldAllow204(); | |
1530 | const bool allow206in = state.allowedPreview206 = shouldAllow206in(); | |
1531 | const bool allow206out = state.allowedPostview206 = shouldAllow206out(); | |
1532 | const bool allowTrailers = true; // TODO: make configurable | |
1533 | ||
1534 | debugs(93, 9, "Allows: " << allow204in << allow204out << | |
1535 | allow206in << allow206out << allowTrailers); | |
1536 | ||
1537 | const bool allow204 = allow204in || allow204out; | |
1538 | const bool allow206 = allow206in || allow206out; | |
1539 | ||
1540 | if (!allow204 && !allow206 && !allowTrailers) | |
1541 | return; // nothing to do | |
1542 | ||
1543 | if (virginBody.expected()) // if there is a virgin body, plan to send it | |
1544 | virginBodySending.plan(); | |
1545 | ||
1546 | // writing Preview:... means we will honor 204 inside preview | |
1547 | // writing Allow/204 means we will honor 204 outside preview | |
1548 | // writing Allow:206 means we will honor 206 inside preview | |
1549 | // writing Allow:204,206 means we will honor 206 outside preview | |
1550 | if (allow204 || allow206 || allowTrailers) { | |
1551 | buf.appendf("Allow: "); | |
1552 | if (allow204out) | |
1553 | buf.appendf("204, "); | |
1554 | if (allow206) | |
1555 | buf.appendf("206, "); | |
1556 | if (allowTrailers) | |
1557 | buf.appendf("trailers"); | |
1558 | buf.appendf("\r\n"); | |
1559 | } | |
1560 | } | |
1561 | ||
1562 | void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf) | |
1563 | { | |
1564 | #if USE_AUTH | |
1565 | struct base64_encode_ctx ctx; | |
1566 | base64_encode_init(&ctx); | |
1567 | ||
1568 | const char *value = NULL; | |
1569 | if (request->auth_user_request != NULL) { | |
1570 | value = request->auth_user_request->username(); | |
1571 | } else if (request->extacl_user.size() > 0) { | |
1572 | value = request->extacl_user.termedBuf(); | |
1573 | } | |
1574 | ||
1575 | if (value) { | |
1576 | if (TheConfig.client_username_encode) { | |
1577 | uint8_t base64buf[base64_encode_len(MAX_LOGIN_SZ)]; | |
1578 | size_t resultLen = base64_encode_update(&ctx, base64buf, strlen(value), reinterpret_cast<const uint8_t*>(value)); | |
1579 | resultLen += base64_encode_final(&ctx, base64buf+resultLen); | |
1580 | buf.appendf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf); | |
1581 | } else | |
1582 | buf.appendf("%s: %s\r\n", TheConfig.client_username_header, value); | |
1583 | } | |
1584 | #endif | |
1585 | } | |
1586 | ||
1587 | void | |
1588 | Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const Http::Message *head) | |
1589 | { | |
1590 | // update ICAP header | |
1591 | icapBuf.appendf("%s=%d, ", section, (int) httpBuf.contentSize()); | |
1592 | ||
1593 | // begin cloning | |
1594 | Http::MessagePointer headClone; | |
1595 | ||
1596 | if (const HttpRequest* old_request = dynamic_cast<const HttpRequest*>(head)) { | |
1597 | HttpRequest::Pointer new_request(new HttpRequest); | |
1598 | // copy the request-line details | |
1599 | new_request->method = old_request->method; | |
1600 | new_request->url = old_request->url; | |
1601 | new_request->http_ver = old_request->http_ver; | |
1602 | headClone = new_request.getRaw(); | |
1603 | } else if (const HttpReply *old_reply = dynamic_cast<const HttpReply*>(head)) { | |
1604 | HttpReply::Pointer new_reply(new HttpReply); | |
1605 | new_reply->sline = old_reply->sline; | |
1606 | headClone = new_reply.getRaw(); | |
1607 | } | |
1608 | Must(headClone); | |
1609 | headClone->inheritProperties(head); | |
1610 | ||
1611 | HttpHeaderPos pos = HttpHeaderInitPos; | |
1612 | while (HttpHeaderEntry* p_head_entry = head->header.getEntry(&pos)) | |
1613 | headClone->header.addEntry(p_head_entry->clone()); | |
1614 | ||
1615 | // end cloning | |
1616 | ||
1617 | // remove all hop-by-hop headers from the clone | |
1618 | headClone->header.delById(Http::HdrType::PROXY_AUTHENTICATE); | |
1619 | headClone->header.removeHopByHopEntries(); | |
1620 | ||
1621 | // pack polished HTTP header | |
1622 | packHead(httpBuf, headClone.getRaw()); | |
1623 | ||
1624 | // headClone unlocks and, hence, deletes the message we packed | |
1625 | } | |
1626 | ||
1627 | void | |
1628 | Adaptation::Icap::ModXact::packHead(MemBuf &httpBuf, const Http::Message *head) | |
1629 | { | |
1630 | head->packInto(&httpBuf, true); | |
1631 | } | |
1632 | ||
1633 | // decides whether to offer a preview and calculates its size | |
1634 | void Adaptation::Icap::ModXact::decideOnPreview() | |
1635 | { | |
1636 | if (!TheConfig.preview_enable) { | |
1637 | debugs(93, 5, HERE << "preview disabled by squid.conf"); | |
1638 | return; | |
1639 | } | |
1640 | ||
1641 | const SBuf urlPath(virginRequest().url.path()); | |
1642 | size_t wantedSize; | |
1643 | if (!service().wantsPreview(urlPath, wantedSize)) { | |
1644 | debugs(93, 5, "should not offer preview for " << urlPath); | |
1645 | return; | |
1646 | } | |
1647 | ||
1648 | // we decided to do preview, now compute its size | |
1649 | ||
1650 | // cannot preview more than we can backup | |
1651 | size_t ad = min(wantedSize, TheBackupLimit); | |
1652 | ||
1653 | if (!virginBody.expected()) | |
1654 | ad = 0; | |
1655 | else if (virginBody.knownSize()) | |
1656 | ad = min(static_cast<uint64_t>(ad), virginBody.size()); // not more than we have | |
1657 | ||
1658 | debugs(93, 5, HERE << "should offer " << ad << "-byte preview " << | |
1659 | "(service wanted " << wantedSize << ")"); | |
1660 | ||
1661 | preview.enable(ad); | |
1662 | Must(preview.enabled()); | |
1663 | } | |
1664 | ||
1665 | // decides whether to allow 204 responses | |
1666 | bool Adaptation::Icap::ModXact::shouldAllow204() | |
1667 | { | |
1668 | if (!service().allows204()) | |
1669 | return false; | |
1670 | ||
1671 | return canBackupEverything(); | |
1672 | } | |
1673 | ||
1674 | // decides whether to allow 206 responses in some mode | |
1675 | bool Adaptation::Icap::ModXact::shouldAllow206any() | |
1676 | { | |
1677 | return TheConfig.allow206_enable && service().allows206() && | |
1678 | virginBody.expected(); // no need for 206 without a body | |
1679 | } | |
1680 | ||
1681 | // decides whether to allow 206 responses in preview mode | |
1682 | bool Adaptation::Icap::ModXact::shouldAllow206in() | |
1683 | { | |
1684 | return shouldAllow206any() && preview.enabled(); | |
1685 | } | |
1686 | ||
1687 | // decides whether to allow 206 responses outside of preview | |
1688 | bool Adaptation::Icap::ModXact::shouldAllow206out() | |
1689 | { | |
1690 | return shouldAllow206any() && canBackupEverything(); | |
1691 | } | |
1692 | ||
1693 | // used by shouldAllow204 and decideOnRetries | |
1694 | bool Adaptation::Icap::ModXact::canBackupEverything() const | |
1695 | { | |
1696 | if (!virginBody.expected()) | |
1697 | return true; // no body means no problems with backup | |
1698 | ||
1699 | // if there is a body, check whether we can backup it all | |
1700 | ||
1701 | if (!virginBody.knownSize()) | |
1702 | return false; | |
1703 | ||
1704 | // or should we have a different backup limit? | |
1705 | // note that '<' allows for 0-termination of the "full" backup buffer | |
1706 | return virginBody.size() < TheBackupLimit; | |
1707 | } | |
1708 | ||
1709 | // Decide whether this transaction can be retried if pconn fails | |
1710 | // Must be called after decideOnPreview and before openConnection() | |
1711 | void Adaptation::Icap::ModXact::decideOnRetries() | |
1712 | { | |
1713 | if (!isRetriable) | |
1714 | return; // no, already decided | |
1715 | ||
1716 | if (preview.enabled()) | |
1717 | return; // yes, because preview provides enough guarantees | |
1718 | ||
1719 | if (canBackupEverything()) | |
1720 | return; // yes, because we can back everything up | |
1721 | ||
1722 | disableRetries(); // no, because we cannot back everything up | |
1723 | } | |
1724 | ||
1725 | // Normally, the body-writing code handles preview body. It can deal with | |
1726 | // bodies of unexpected size, including those that turn out to be empty. | |
1727 | // However, that code assumes that the body was expected and body control | |
1728 | // structures were initialized. This is not the case when there is no body | |
1729 | // or the body is known to be empty, because the virgin message will lack a | |
1730 | // body_pipe. So we handle preview of null-body and zero-size bodies here. | |
1731 | void Adaptation::Icap::ModXact::finishNullOrEmptyBodyPreview(MemBuf &) | |
1732 | { | |
1733 | Must(!virginBodyWriting.active()); // one reason we handle it here | |
1734 | Must(!virgin.body_pipe); // another reason we handle it here | |
1735 | Must(!preview.ad()); | |
1736 | ||
1737 | // do not add last-chunk because our Encapsulated header says null-body | |
1738 | // addLastRequestChunk(buf); | |
1739 | preview.wrote(0, true); | |
1740 | ||
1741 | Must(preview.done()); | |
1742 | Must(preview.ieof()); | |
1743 | } | |
1744 | ||
1745 | void Adaptation::Icap::ModXact::fillPendingStatus(MemBuf &buf) const | |
1746 | { | |
1747 | Adaptation::Icap::Xaction::fillPendingStatus(buf); | |
1748 | ||
1749 | if (state.serviceWaiting) | |
1750 | buf.append("U", 1); | |
1751 | ||
1752 | if (virgin.body_pipe != NULL) | |
1753 | buf.append("R", 1); | |
1754 | ||
1755 | if (haveConnection() && !doneReading()) | |
1756 | buf.append("r", 1); | |
1757 | ||
1758 | if (!state.doneWriting() && state.writing != State::writingInit) | |
1759 | buf.appendf("w(%d)", state.writing); | |
1760 | ||
1761 | if (preview.enabled()) { | |
1762 | if (!preview.done()) | |
1763 | buf.appendf("P(%d)", (int) preview.debt()); | |
1764 | } | |
1765 | ||
1766 | if (virginBodySending.active()) | |
1767 | buf.append("B", 1); | |
1768 | ||
1769 | if (!state.doneParsing() && state.parsing != State::psIcapHeader) | |
1770 | buf.appendf("p(%d)", state.parsing); | |
1771 | ||
1772 | if (!doneSending() && state.sending != State::sendingUndecided) | |
1773 | buf.appendf("S(%d)", state.sending); | |
1774 | ||
1775 | if (state.readyForUob) | |
1776 | buf.append("6", 1); | |
1777 | ||
1778 | if (canStartBypass) | |
1779 | buf.append("Y", 1); | |
1780 | ||
1781 | if (protectGroupBypass) | |
1782 | buf.append("G", 1); | |
1783 | } | |
1784 | ||
1785 | void Adaptation::Icap::ModXact::fillDoneStatus(MemBuf &buf) const | |
1786 | { | |
1787 | Adaptation::Icap::Xaction::fillDoneStatus(buf); | |
1788 | ||
1789 | if (!virgin.body_pipe) | |
1790 | buf.append("R", 1); | |
1791 | ||
1792 | if (state.doneWriting()) | |
1793 | buf.append("w", 1); | |
1794 | ||
1795 | if (preview.enabled()) { | |
1796 | if (preview.done()) | |
1797 | buf.appendf("P%s", preview.ieof() ? "(ieof)" : ""); | |
1798 | } | |
1799 | ||
1800 | if (doneReading()) | |
1801 | buf.append("r", 1); | |
1802 | ||
1803 | if (state.doneParsing()) | |
1804 | buf.append("p", 1); | |
1805 | ||
1806 | if (doneSending()) | |
1807 | buf.append("S", 1); | |
1808 | } | |
1809 | ||
1810 | bool Adaptation::Icap::ModXact::gotEncapsulated(const char *section) const | |
1811 | { | |
1812 | return icapReply->header.getByNameListMember("Encapsulated", | |
1813 | section, ',').size() > 0; | |
1814 | } | |
1815 | ||
1816 | // calculate whether there is a virgin HTTP body and | |
1817 | // whether its expected size is known | |
1818 | // TODO: rename because we do not just estimate | |
1819 | void Adaptation::Icap::ModXact::estimateVirginBody() | |
1820 | { | |
1821 | // note: lack of size info may disable previews and 204s | |
1822 | ||
1823 | Http::Message *msg = virgin.header; | |
1824 | Must(msg); | |
1825 | ||
1826 | HttpRequestMethod method; | |
1827 | ||
1828 | if (virgin.cause) | |
1829 | method = virgin.cause->method; | |
1830 | else if (HttpRequest *req = dynamic_cast<HttpRequest*>(msg)) | |
1831 | method = req->method; | |
1832 | else | |
1833 | method = Http::METHOD_NONE; | |
1834 | ||
1835 | int64_t size; | |
1836 | // expectingBody returns true for zero-sized bodies, but we will not | |
1837 | // get a pipe for that body, so we treat the message as bodyless | |
1838 | if (method != Http::METHOD_NONE && msg->expectingBody(method, size) && size) { | |
1839 | debugs(93, 6, HERE << "expects virgin body from " << | |
1840 | virgin.body_pipe << "; size: " << size); | |
1841 | ||
1842 | virginBody.expect(size); | |
1843 | virginBodyWriting.plan(); | |
1844 | ||
1845 | // sign up as a body consumer | |
1846 | Must(msg->body_pipe != NULL); | |
1847 | Must(msg->body_pipe == virgin.body_pipe); | |
1848 | Must(virgin.body_pipe->setConsumerIfNotLate(this)); | |
1849 | ||
1850 | // make sure TheBackupLimit is in-sync with the buffer size | |
1851 | Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity)); | |
1852 | } else { | |
1853 | debugs(93, 6, HERE << "does not expect virgin body"); | |
1854 | Must(msg->body_pipe == NULL); | |
1855 | checkConsuming(); | |
1856 | } | |
1857 | } | |
1858 | ||
1859 | void Adaptation::Icap::ModXact::makeAdaptedBodyPipe(const char *what) | |
1860 | { | |
1861 | Must(!adapted.body_pipe); | |
1862 | Must(!adapted.header->body_pipe); | |
1863 | adapted.header->body_pipe = new BodyPipe(this); | |
1864 | adapted.body_pipe = adapted.header->body_pipe; | |
1865 | debugs(93, 7, HERE << "will supply " << what << " via " << | |
1866 | adapted.body_pipe << " pipe"); | |
1867 | } | |
1868 | ||
1869 | // TODO: Move SizedEstimate and Preview elsewhere | |
1870 | ||
1871 | Adaptation::Icap::SizedEstimate::SizedEstimate() | |
1872 | : theData(dtUnexpected) | |
1873 | {} | |
1874 | ||
1875 | void Adaptation::Icap::SizedEstimate::expect(int64_t aSize) | |
1876 | { | |
1877 | theData = (aSize >= 0) ? aSize : (int64_t)dtUnknown; | |
1878 | } | |
1879 | ||
1880 | bool Adaptation::Icap::SizedEstimate::expected() const | |
1881 | { | |
1882 | return theData != dtUnexpected; | |
1883 | } | |
1884 | ||
1885 | bool Adaptation::Icap::SizedEstimate::knownSize() const | |
1886 | { | |
1887 | Must(expected()); | |
1888 | return theData != dtUnknown; | |
1889 | } | |
1890 | ||
1891 | uint64_t Adaptation::Icap::SizedEstimate::size() const | |
1892 | { | |
1893 | Must(knownSize()); | |
1894 | return static_cast<uint64_t>(theData); | |
1895 | } | |
1896 | ||
1897 | Adaptation::Icap::VirginBodyAct::VirginBodyAct(): theStart(0), theState(stUndecided) | |
1898 | {} | |
1899 | ||
1900 | void Adaptation::Icap::VirginBodyAct::plan() | |
1901 | { | |
1902 | Must(!disabled()); | |
1903 | Must(!theStart); // not started | |
1904 | theState = stActive; | |
1905 | } | |
1906 | ||
1907 | void Adaptation::Icap::VirginBodyAct::disable() | |
1908 | { | |
1909 | theState = stDisabled; | |
1910 | } | |
1911 | ||
1912 | void Adaptation::Icap::VirginBodyAct::progress(size_t size) | |
1913 | { | |
1914 | Must(active()); | |
1915 | #if SIZEOF_SIZE_T > 4 | |
1916 | /* always true for smaller size_t's */ | |
1917 | Must(static_cast<int64_t>(size) >= 0); | |
1918 | #endif | |
1919 | theStart += static_cast<int64_t>(size); | |
1920 | } | |
1921 | ||
1922 | uint64_t Adaptation::Icap::VirginBodyAct::offset() const | |
1923 | { | |
1924 | Must(active()); | |
1925 | return static_cast<uint64_t>(theStart); | |
1926 | } | |
1927 | ||
1928 | Adaptation::Icap::Preview::Preview(): theWritten(0), theAd(0), theState(stDisabled) | |
1929 | {} | |
1930 | ||
1931 | void Adaptation::Icap::Preview::enable(size_t anAd) | |
1932 | { | |
1933 | // TODO: check for anAd not exceeding preview size limit | |
1934 | Must(!enabled()); | |
1935 | theAd = anAd; | |
1936 | theState = stWriting; | |
1937 | } | |
1938 | ||
1939 | bool Adaptation::Icap::Preview::enabled() const | |
1940 | { | |
1941 | return theState != stDisabled; | |
1942 | } | |
1943 | ||
1944 | size_t Adaptation::Icap::Preview::ad() const | |
1945 | { | |
1946 | Must(enabled()); | |
1947 | return theAd; | |
1948 | } | |
1949 | ||
1950 | bool Adaptation::Icap::Preview::done() const | |
1951 | { | |
1952 | Must(enabled()); | |
1953 | return theState >= stIeof; | |
1954 | } | |
1955 | ||
1956 | bool Adaptation::Icap::Preview::ieof() const | |
1957 | { | |
1958 | Must(enabled()); | |
1959 | return theState == stIeof; | |
1960 | } | |
1961 | ||
1962 | size_t Adaptation::Icap::Preview::debt() const | |
1963 | { | |
1964 | Must(enabled()); | |
1965 | return done() ? 0 : (theAd - theWritten); | |
1966 | } | |
1967 | ||
1968 | void Adaptation::Icap::Preview::wrote(size_t size, bool wroteEof) | |
1969 | { | |
1970 | Must(enabled()); | |
1971 | ||
1972 | theWritten += size; | |
1973 | ||
1974 | Must(theWritten <= theAd); | |
1975 | ||
1976 | if (wroteEof) | |
1977 | theState = stIeof; // written size is irrelevant | |
1978 | else if (theWritten >= theAd) | |
1979 | theState = stDone; | |
1980 | } | |
1981 | ||
1982 | bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf &mb) const | |
1983 | { | |
1984 | if (virgin.header == NULL) | |
1985 | return false; | |
1986 | ||
1987 | virgin.header->firstLineBuf(mb); | |
1988 | ||
1989 | return true; | |
1990 | } | |
1991 | ||
1992 | void Adaptation::Icap::ModXact::detailError(int errDetail) | |
1993 | { | |
1994 | HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header); | |
1995 | // if no adapted request, update virgin (and inherit its properties later) | |
1996 | // TODO: make this and HttpRequest::detailError constant, like adaptHistory | |
1997 | if (!request) | |
1998 | request = const_cast<HttpRequest*>(&virginRequest()); | |
1999 | ||
2000 | if (request) | |
2001 | request->detailError(ERR_ICAP_FAILURE, errDetail); | |
2002 | } | |
2003 | ||
2004 | void Adaptation::Icap::ModXact::clearError() | |
2005 | { | |
2006 | HttpRequest *request = dynamic_cast<HttpRequest*>(adapted.header); | |
2007 | // if no adapted request, update virgin (and inherit its properties later) | |
2008 | if (!request) | |
2009 | request = const_cast<HttpRequest*>(&virginRequest()); | |
2010 | ||
2011 | if (request) | |
2012 | request->clearError(); | |
2013 | } | |
2014 | ||
2015 | void Adaptation::Icap::ModXact::updateSources() | |
2016 | { | |
2017 | Must(adapted.header); | |
2018 | adapted.header->sources |= (service().cfg().connectionEncryption ? Http::Message::srcIcaps : Http::Message::srcIcap); | |
2019 | } | |
2020 | ||
2021 | /* Adaptation::Icap::ModXactLauncher */ | |
2022 | ||
2023 | Adaptation::Icap::ModXactLauncher::ModXactLauncher(Http::Message *virginHeader, HttpRequest *virginCause, AccessLogEntry::Pointer &alp, Adaptation::ServicePointer aService): | |
2024 | AsyncJob("Adaptation::Icap::ModXactLauncher"), | |
2025 | Adaptation::Icap::Launcher("Adaptation::Icap::ModXactLauncher", aService), | |
2026 | al(alp) | |
2027 | { | |
2028 | virgin.setHeader(virginHeader); | |
2029 | virgin.setCause(virginCause); | |
2030 | updateHistory(true); | |
2031 | } | |
2032 | ||
2033 | Adaptation::Icap::Xaction *Adaptation::Icap::ModXactLauncher::createXaction() | |
2034 | { | |
2035 | Adaptation::Icap::ServiceRep::Pointer s = | |
2036 | dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw()); | |
2037 | Must(s != NULL); | |
2038 | return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, al, s); | |
2039 | } | |
2040 | ||
2041 | void Adaptation::Icap::ModXactLauncher::swanSong() | |
2042 | { | |
2043 | debugs(93, 5, HERE << "swan sings"); | |
2044 | updateHistory(false); | |
2045 | Adaptation::Icap::Launcher::swanSong(); | |
2046 | } | |
2047 | ||
2048 | void Adaptation::Icap::ModXactLauncher::updateHistory(bool doStart) | |
2049 | { | |
2050 | HttpRequest *r = virgin.cause ? | |
2051 | virgin.cause : dynamic_cast<HttpRequest*>(virgin.header); | |
2052 | ||
2053 | // r should never be NULL but we play safe; TODO: add Should() | |
2054 | if (r) { | |
2055 | Adaptation::Icap::History::Pointer h = r->icapHistory(); | |
2056 | if (h != NULL) { | |
2057 | if (doStart) | |
2058 | h->start("ICAPModXactLauncher"); | |
2059 | else | |
2060 | h->stop("ICAPModXactLauncher"); | |
2061 | } | |
2062 | } | |
2063 | } | |
2064 | ||
2065 | bool Adaptation::Icap::TrailerParser::parse(const char *buf, int len, int atEnd, Http::StatusCode *error) { | |
2066 | const int parsed = trailer.parse(buf, len, atEnd, hdr_sz); | |
2067 | if (parsed < 0) | |
2068 | *error = Http::scInvalidHeader; // TODO: should we add a new Http::scInvalidTrailer? | |
2069 | return parsed > 0; | |
2070 | } | |
2071 |