]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ICAP/ICAPModXact.cc
Found and fixed a case where HttpMsg::parse() returned false but
[thirdparty/squid.git] / src / ICAP / ICAPModXact.cc
CommitLineData
774c051c 1/*
2 * DEBUG: section 93 ICAP (RFC 3507) Client
3 */
4
5#include "squid.h"
6#include "comm.h"
7#include "MsgPipe.h"
8#include "MsgPipeData.h"
9#include "HttpRequest.h"
10#include "HttpReply.h"
11#include "ICAPServiceRep.h"
12#include "ICAPModXact.h"
13#include "ICAPClient.h"
14#include "ChunkedCodingParser.h"
15#include "TextException.h"
a97e82a8 16#include "AuthUserRequest.h"
12b91c99 17#include "ICAPConfig.h"
774c051c 18
19// flow and terminology:
20// HTTP| --> receive --> encode --> write --> |network
21// end | <-- send <-- parse <-- read <-- |end
22
23// TODO: doneSending()/doneReceving() data members should probably be in sync
24// with this->adapted/virgin pointers. Make adapted/virgin methods?
25
26// TODO: replace gotEncapsulated() with something faster; we call it often
27
28CBDATA_CLASS_INIT(ICAPModXact);
29
30static const size_t TheBackupLimit = ICAP::MsgPipeBufSizeMax;
31
12b91c99 32extern ICAPConfig TheICAPConfig;
33
774c051c 34
35ICAPModXact::State::State()
36{
37 memset(this, sizeof(*this), 0);
38}
39
40ICAPModXact::ICAPModXact(): ICAPXaction("ICAPModXact"),
41 self(NULL), virgin(NULL), adapted(NULL),
42 icapReply(NULL), virginConsumed(0),
43 bodyParser(NULL)
44{}
45
46void ICAPModXact::init(ICAPServiceRep::Pointer &aService, MsgPipe::Pointer &aVirgin, MsgPipe::Pointer &anAdapted, Pointer &aSelf)
47{
48 assert(!self.getRaw() && !virgin.getRaw() && !adapted.getRaw());
49 assert(aSelf.getRaw() && aVirgin.getRaw() && anAdapted.getRaw());
50
51 self = aSelf;
52 service(aService);
53
54 virgin = aVirgin;
55 adapted = anAdapted;
56
57 // receiving end
58 virgin->sink = this; // should be 'self' and refcounted
59 // virgin pipe data is initiated by the source
60
61 // sending end
62 adapted->source = this; // should be 'self' and refcounted
63 adapted->data = new MsgPipeData;
64
65 adapted->data->body = new MemBuf; // XXX: make body a non-pointer?
66 adapted->data->body->init(ICAP::MsgPipeBufSizeMin, ICAP::MsgPipeBufSizeMax);
67 // headers are initialized when we parse them
68
69 // writing and reading ends are handled by ICAPXaction
70
71 // encoding
72 // nothing to do because we are using temporary buffers
73
74 // parsing
75 icapReply = new HttpReply;
76 icapReply->protoPrefix = "ICAP/"; // TODO: make an IcapReply class?
77
78 // XXX: make sure stop() cleans all buffers
79}
80
81// HTTP side starts sending virgin data
82void ICAPModXact::noteSourceStart(MsgPipe *p)
83{
84 ICAPXaction_Enter(noteSourceStart);
85
86 // make sure TheBackupLimit is in-sync with the buffer size
87 Must(TheBackupLimit <= static_cast<size_t>(virgin->data->body->max_capacity));
88
89 estimateVirginBody(); // before virgin disappears!
90
91 // it is an ICAP violation to send request to a service w/o known OPTIONS
92
93 if (service().up())
94 startWriting();
95 else
96 waitForService();
97
98 // XXX: but this has to be here to catch other errors. Thus, if
99 // commConnectStart in startWriting fails, we may get here
100 //_after_ the object got destroyed. Somebody please fix commConnectStart!
101 ICAPXaction_Exit();
102}
103
104static
105void ICAPModXact_noteServiceReady(void *data, ICAPServiceRep::Pointer &)
106{
107 ICAPModXact *x = static_cast<ICAPModXact*>(data);
108 assert(x);
109 x->noteServiceReady();
110}
111
112void ICAPModXact::waitForService()
113{
114 Must(!state.serviceWaiting);
115 debugs(93, 7, "ICAPModXact will wait for the ICAP service " << status());
116 state.serviceWaiting = true;
117 service().callWhenReady(&ICAPModXact_noteServiceReady, this);
118}
119
120void ICAPModXact::noteServiceReady()
121{
122 ICAPXaction_Enter(noteServiceReady);
123
124 Must(state.serviceWaiting);
125 state.serviceWaiting = false;
126 startWriting(); // will throw if service is not up
127
128 ICAPXaction_Exit();
129}
130
131void ICAPModXact::startWriting()
132{
133 Must(service().up());
134
135 state.writing = State::writingConnect;
136 openConnection();
137 // put nothing here as openConnection calls commConnectStart
138 // and that may call us back without waiting for the next select loop
139}
140
141// connection with the ICAP service established
142void ICAPModXact::handleCommConnected()
143{
144 Must(state.writing == State::writingConnect);
145
146 startReading(); // wait for early errors from the ICAP server
147
148 MemBuf requestBuf;
149 requestBuf.init();
150
151 makeRequestHeaders(requestBuf);
152 debugs(93, 9, "ICAPModXact ICAP request prefix " << status() << ":\n" <<
153 (requestBuf.terminate(), requestBuf.content()));
154
155 // write headers
156 state.writing = State::writingHeaders;
157 scheduleWrite(requestBuf);
158}
159
160void ICAPModXact::handleCommWrote(size_t)
161{
162 if (state.writing == State::writingHeaders)
163 handleCommWroteHeaders();
164 else
165 handleCommWroteBody();
166}
167
168void ICAPModXact::handleCommWroteHeaders()
169{
170 Must(state.writing == State::writingHeaders);
171
172 if (virginBody.expected()) {
173 state.writing = preview.enabled() ?
174 State::writingPreview : State::writingPrime;
175 virginWriteClaim.protectAll();
176 writeMore();
177 } else {
178 stopWriting();
179 }
180}
181
182void ICAPModXact::writeMore()
183{
184 if (writer) // already writing something
185 return;
186
187 switch (state.writing) {
188
189 case State::writingInit: // waiting for service OPTIONS
190 Must(state.serviceWaiting);
191
192 case State::writingConnect: // waiting for the connection to establish
193
194 case State::writingHeaders: // waiting for the headers to be written
195
196 case State::writingPaused: // waiting for the ICAP server response
197
198 case State::writingDone: // nothing more to write
199 return;
200
201 case State::writingPreview:
202 writePriviewBody();
203 return;
204
205 case State::writingPrime:
206 writePrimeBody();
207 return;
208
209 default:
210 throw TexcHere("ICAPModXact in bad writing state");
211 }
212}
213
214void ICAPModXact::writePriviewBody()
215{
216 debugs(93, 8, "ICAPModXact will write Preview body " << status());
217 Must(state.writing == State::writingPreview);
218
219 MsgPipeData::Body *body = virgin->data->body;
220 const size_t size = XMIN(preview.debt(), (size_t)body->contentSize());
221 writeSomeBody("preview body", size);
222
223 // change state once preview is written
224
225 if (preview.done()) {
226 debugs(93, 7, "ICAPModXact wrote entire Preview body " << status());
227
228 if (preview.ieof())
229 stopWriting();
230 else
231 state.writing = State::writingPaused;
232 }
233}
234
235void ICAPModXact::writePrimeBody()
236{
237 Must(state.writing == State::writingPrime);
238 Must(virginWriteClaim.active());
239
240 MsgPipeData::Body *body = virgin->data->body;
241 const size_t size = body->contentSize();
242 writeSomeBody("prime virgin body", size);
243
244 if (state.doneReceiving)
245 stopWriting();
246}
247
248void ICAPModXact::writeSomeBody(const char *label, size_t size)
249{
250 Must(!writer && !state.doneWriting());
12f4b710 251 debugs(93, 8, HERE << "will write up to " << size << " bytes of " <<
774c051c 252 label);
253
254 MemBuf writeBuf; // TODO: suggest a min size based on size and lastChunk
255
256 writeBuf.init(); // note: we assume that last-chunk will fit
257
258 const size_t writeableSize = claimSize(virginWriteClaim);
259 const size_t chunkSize = XMIN(writeableSize, size);
260
261 if (chunkSize) {
12f4b710 262 debugs(93, 7, HERE << "will write " << chunkSize <<
774c051c 263 "-byte chunk of " << label);
264 } else {
265 debugs(93, 7, "ICAPModXact has no writeable " << label << " content");
266 }
267
268 moveRequestChunk(writeBuf, chunkSize);
269
270 const bool lastChunk =
271 (state.writing == State::writingPreview && preview.done()) ||
272 (state.doneReceiving && claimSize(virginWriteClaim) <= 0);
273
274 if (lastChunk && virginBody.expected()) {
12f4b710 275 debugs(93, 8, HERE << "will write last-chunk of " << label);
774c051c 276 addLastRequestChunk(writeBuf);
277 }
278
12f4b710 279 debugs(93, 7, HERE << "will write " << writeBuf.contentSize()
774c051c 280 << " raw bytes of " << label);
281
282 if (writeBuf.hasContent()) {
283 scheduleWrite(writeBuf); // comm will free the chunk
284 } else {
285 writeBuf.clean();
286 }
287}
288
289void ICAPModXact::moveRequestChunk(MemBuf &buf, size_t chunkSize)
290{
291 if (chunkSize > 0) {
292 openChunk(buf, chunkSize);
293 buf.append(claimContent(virginWriteClaim), chunkSize);
294 closeChunk(buf, false);
295
296 virginWriteClaim.release(chunkSize);
297 virginConsume();
298 }
299
300 if (state.writing == State::writingPreview)
301 preview.wrote(chunkSize, state.doneReceiving); // even if wrote nothing
302}
303
304void ICAPModXact::addLastRequestChunk(MemBuf &buf)
305{
306 openChunk(buf, 0);
307 closeChunk(buf, state.writing == State::writingPreview && preview.ieof());
308}
309
310void ICAPModXact::openChunk(MemBuf &buf, size_t chunkSize)
311{
1dd6edf2 312 buf.Printf("%x\r\n", (int) chunkSize);
774c051c 313}
314
315void ICAPModXact::closeChunk(MemBuf &buf, bool ieof)
316{
317 if (ieof)
318 buf.append("; ieof", 6);
319
320 buf.append(ICAP::crlf, 2); // chunk-terminating CRLF
321}
322
323size_t ICAPModXact::claimSize(const MemBufClaim &claim) const
324{
325 Must(claim.active());
326 const size_t start = claim.offset();
327 const size_t end = virginConsumed + virgin->data->body->contentSize();
328 Must(virginConsumed <= start && start <= end);
329 return end - start;
330}
331
332const char *ICAPModXact::claimContent(const MemBufClaim &claim) const
333{
334 Must(claim.active());
335 const size_t start = claim.offset();
336 Must(virginConsumed <= start);
337 return virgin->data->body->content() + (start - virginConsumed);
338}
339
340void ICAPModXact::virginConsume()
341{
342 MemBuf &buf = *virgin->data->body;
343 const size_t have = static_cast<size_t>(buf.contentSize());
344 const size_t end = virginConsumed + have;
345 size_t offset = end;
346
347 if (virginWriteClaim.active())
348 offset = XMIN(virginWriteClaim.offset(), offset);
349
350 if (virginSendClaim.active())
351 offset = XMIN(virginSendClaim.offset(), offset);
352
353 Must(virginConsumed <= offset && offset <= end);
354
355 if (const size_t size = offset - virginConsumed) {
356 debugs(93, 8, "ICAPModXact consumes " << size << " out of " << have <<
357 " virgin body bytes");
358 buf.consume(size);
359 virginConsumed += size;
360
361 if (!state.doneReceiving)
362 virgin->sendSinkNeed();
363 }
364}
365
366void ICAPModXact::handleCommWroteBody()
367{
368 writeMore();
369}
370
371void ICAPModXact::stopWriting()
372{
373 if (state.writing == State::writingDone)
374 return;
375
376 debugs(93, 7, "ICAPModXact will no longer write " << status());
377
378 state.writing = State::writingDone;
379
380 virginWriteClaim.disable();
381
382 virginConsume();
383
384 // Comm does not have an interface to clear the writer, but
385 // writeMore() will not write if our write callback is called
386 // when state.writing == State::writingDone;
387}
388
389void ICAPModXact::stopBackup()
390{
391 if (!virginSendClaim.active())
392 return;
393
394 debugs(93, 7, "ICAPModXact will no longer backup " << status());
395
396 virginSendClaim.disable();
397
398 virginConsume();
399}
400
401bool ICAPModXact::doneAll() const
402{
403 return ICAPXaction::doneAll() && !state.serviceWaiting &&
404 state.doneReceiving && doneSending() &&
405 doneReading() && state.doneWriting();
406}
407
408void ICAPModXact::startReading()
409{
410 Must(connection >= 0);
411 Must(!reader);
412 Must(adapted.getRaw());
413 Must(adapted->data);
414 Must(adapted->data->body);
415
416 // we use the same buffer for headers and body and then consume headers
417 readMore();
418}
419
420void ICAPModXact::readMore()
421{
422 if (reader || doneReading())
423 return;
424
425 // do not fill readBuf if we have no space to store the result
426 if (!adapted->data->body->hasPotentialSpace())
427 return;
428
429 if (readBuf.hasSpace())
430 scheduleRead();
431}
432
433// comm module read a portion of the ICAP response for us
434void ICAPModXact::handleCommRead(size_t)
435{
436 Must(!state.doneParsing());
437 parseMore();
438 readMore();
439}
440
441void ICAPModXact::echoMore()
442{
443 Must(state.sending == State::sendingVirgin);
444 Must(virginSendClaim.active());
445
446 MemBuf &from = *virgin->data->body;
447 MemBuf &to = *adapted->data->body;
448
449 const size_t sizeMax = claimSize(virginSendClaim);
450 const size_t size = XMIN(static_cast<size_t>(to.potentialSpaceSize()),
451 sizeMax);
452 debugs(93, 5, "ICAPModXact echos " << size << " out of " << sizeMax <<
453 " bytes");
454
455 if (size > 0) {
456 to.append(claimContent(virginSendClaim), size);
457 virginSendClaim.release(size);
458 virginConsume();
459 adapted->sendSourceProgress();
460 }
461
462 if (!from.hasContent() && state.doneReceiving) {
463 debugs(93, 5, "ICAPModXact echoed all " << status());
464 stopSending(true);
465 } else {
466 debugs(93, 5, "ICAPModXact has " << from.contentSize() << " bytes " <<
467 "and expects more to echo " << status());
468 virgin->sendSinkNeed(); // TODO: timeout if sink is broken
469 }
470}
471
472bool ICAPModXact::doneSending() const
473{
474 Must((state.sending == State::sendingDone) == (!adapted));
475 return state.sending == State::sendingDone;
476}
477
478void ICAPModXact::stopSending(bool nicely)
479{
480 if (doneSending())
481 return;
482
483 if (state.sending != State::sendingUndecided) {
484 debugs(93, 7, "ICAPModXact will no longer send " << status());
485
486 if (nicely)
487 adapted->sendSourceFinish();
488 else
489 adapted->sendSourceAbort();
490 } else {
491 debugs(93, 7, "ICAPModXact will not start sending " << status());
492 adapted->sendSourceAbort(); // or the sink may wait forever
493 }
494
495 state.sending = State::sendingDone;
496
497 /*
498 * Note on adapted->data->header: we created the header, but allow the
bab98cf3 499 * other side (ICAPClientRespmodPrecache) to take control of it. We won't touch it here
774c051c 500 * and instead rely on the Anchor-side to make sure it is properly freed.
501 */
502 adapted = NULL; // refcounted
503}
504
505void ICAPModXact::stopReceiving()
506{
507 // stopSending NULLifies adapted but we do not NULLify virgin.
508 // This is assymetric because we want to keep virgin->data even
509 // though we are not expecting any more virgin->data->body.
510 // TODO: can we cache just the needed headers info instead?
511
512 // If they closed first, there is not point (or means) to notify them.
513
514 if (state.doneReceiving)
515 return;
516
517 // There is no sendSinkFinished() to notify the other side.
518 debugs(93, 7, "ICAPModXact will not receive " << status());
519
520 state.doneReceiving = true;
521}
522
523void ICAPModXact::parseMore()
524{
aa761e5f 525 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " bytes to parse" <<
774c051c 526 status());
7cdbbd47 527 debugs(93, 5, HERE << readBuf.content());
774c051c 528
529 if (state.parsingHeaders())
530 parseHeaders();
531
532 if (state.parsing == State::psBody)
533 parseBody();
534}
535
536// note that allocation for echoing is done in handle204NoContent()
537void ICAPModXact::maybeAllocateHttpMsg()
538{
539 if (adapted->data->header) // already allocated
540 return;
541
542 if (gotEncapsulated("res-hdr")) {
543 adapted->data->header = new HttpReply;
544 } else if (gotEncapsulated("req-hdr")) {
545 adapted->data->header = new HttpRequest;
546 } else
547 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
548}
549
550void ICAPModXact::parseHeaders()
551{
552 Must(state.parsingHeaders());
553
554 if (state.parsing == State::psIcapHeader)
555 parseIcapHead();
556
557 if (state.parsing == State::psHttpHeader)
558 parseHttpHead();
559
560 if (state.parsingHeaders()) { // need more data
561 Must(mayReadMore());
562 return;
563 }
564
565 adapted->sendSourceStart();
566
567 if (state.sending == State::sendingVirgin)
568 echoMore();
569}
570
571void ICAPModXact::parseIcapHead()
572{
573 Must(state.sending == State::sendingUndecided);
574
575 if (!parseHead(icapReply))
576 return;
577
fc764d26 578 if (httpHeaderHasConnDir(&icapReply->header, "close")) {
579 debugs(93, 5, HERE << "found connection close");
580 reuseConnection = false;
581 }
582
774c051c 583 switch (icapReply->sline.status) {
584
585 case 100:
586 handle100Continue();
587 break;
588
589 case 200:
b559db5d 590
591 if (!validate200Ok()) {
592 throw TexcHere("Invalid ICAP Response");
593 } else {
594 handle200Ok();
595 }
596
774c051c 597 break;
598
599 case 204:
600 handle204NoContent();
601 break;
602
603 default:
b559db5d 604 debugs(93, 5, HERE << "ICAP status " << icapReply->sline.status);
774c051c 605 handleUnknownScode();
606 break;
607 }
608
609 // handle100Continue() manages state.writing on its own.
610 // Non-100 status means the server needs no postPreview data from us.
611 if (state.writing == State::writingPaused)
612 stopWriting();
613
614 // TODO: Consider applying a Squid 2.5 patch to recognize 201 responses
615}
616
b559db5d 617bool ICAPModXact::validate200Ok()
618{
619 if (ICAP::methodRespmod == service().method) {
620 if (!gotEncapsulated("res-hdr"))
621 return false;
622
623 return true;
624 }
625
626 if (ICAP::methodReqmod == service().method) {
627 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
628 return false;
629
630 return true;
631 }
632
633 return false;
634}
635
774c051c 636void ICAPModXact::handle100Continue()
637{
638 Must(state.writing == State::writingPaused);
639 Must(preview.enabled() && preview.done() && !preview.ieof());
640 Must(virginSendClaim.active());
641
642 if (virginSendClaim.limited()) // preview only
643 stopBackup();
644
645 state.parsing = State::psHttpHeader; // eventually
646
647 state.writing = State::writingPrime;
648
649 writeMore();
650}
651
652void ICAPModXact::handle200Ok()
653{
654 state.parsing = State::psHttpHeader;
655 state.sending = State::sendingAdapted;
656 stopBackup();
657}
658
659void ICAPModXact::handle204NoContent()
660{
661 stopParsing();
662 Must(virginSendClaim.active());
663 virginSendClaim.protectAll(); // extends protection if needed
664 state.sending = State::sendingVirgin;
665
666 // We want to clone the HTTP message, but we do not want
667 // to copy non-HTTP state parts that HttpMsg kids carry in them.
668 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
669 // Instead, we simply write the HTTP message and "clone" it by parsing.
670
671 HttpMsg *oldHead = virgin->data->header;
672 debugs(93, 7, "ICAPModXact cloning virgin message " << oldHead);
673
674 MemBuf httpBuf;
675
676 // write the virgin message into a memory buffer
677 httpBuf.init();
678 packHead(httpBuf, oldHead);
679
680 // allocate the adapted message
681 HttpMsg *&newHead = adapted->data->header;
682 Must(!newHead);
683
684 if (dynamic_cast<const HttpRequest*>(oldHead))
685 newHead = new HttpRequest;
686 else
687 if (dynamic_cast<const HttpReply*>(oldHead))
688 newHead = new HttpReply;
689
690 Must(newHead);
691
692 // parse the buffer back
693 http_status error = HTTP_STATUS_NONE;
694
695 Must(newHead->parse(&httpBuf, true, &error));
696
697 Must(newHead->hdr_sz == httpBuf.contentSize()); // no leftovers
698
699 httpBuf.clean();
700
701 debugs(93, 7, "ICAPModXact cloned virgin message " << oldHead << " to " << newHead);
702}
703
704void ICAPModXact::handleUnknownScode()
705{
706 stopParsing();
707 stopBackup();
708 // TODO: mark connection as "bad"
709
710 // Terminate the transaction; we do not know how to handle this response.
711 throw TexcHere("Unsupported ICAP status code");
712}
713
714void ICAPModXact::parseHttpHead()
715{
716 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
717 maybeAllocateHttpMsg();
718
719 if (!parseHead(adapted->data->header))
200ac359 720 return; // need more header data
774c051c 721 }
722
723 state.parsing = State::psBody;
724}
725
fc764d26 726/*
727 * Common routine used to parse both HTTP and ICAP headers
728 */
774c051c 729bool ICAPModXact::parseHead(HttpMsg *head)
730{
731 assert(head);
def17b6a 732 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
774c051c 733 "; state: " << state.parsing);
734
735 http_status error = HTTP_STATUS_NONE;
736 const bool parsed = head->parse(&readBuf, commEof, &error);
737 Must(parsed || !error); // success or need more data
738
739 if (!parsed) { // need more data
740 head->reset();
741 return false;
742 }
743
744 readBuf.consume(head->hdr_sz);
745 return true;
746}
747
748void ICAPModXact::parseBody()
749{
750 Must(state.parsing == State::psBody);
751
aa761e5f 752 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
774c051c 753
200ac359 754 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
774c051c 755 if (!parsePresentBody()) // need more body data
756 return;
757 } else {
b559db5d 758 debugs(93, 5, HERE << "not expecting a body");
774c051c 759 }
760
761 stopParsing();
762 stopSending(true);
763}
764
765// returns true iff complete body was parsed
766bool ICAPModXact::parsePresentBody()
767{
768 if (!bodyParser)
769 bodyParser = new ChunkedCodingParser;
770
771 // the parser will throw on errors
772 const bool parsed = bodyParser->parse(&readBuf, adapted->data->body);
773
774 adapted->sendSourceProgress(); // TODO: do not send if parsed nothing
775
aa761e5f 776 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
774c051c 777 "parse; parsed all: " << parsed);
778
779 if (parsed)
780 return true;
781
782 if (bodyParser->needsMoreData())
783 Must(mayReadMore());
784
785 if (bodyParser->needsMoreSpace()) {
786 Must(!doneSending()); // can hope for more space
787 Must(adapted->data->body->hasContent()); // paranoid
788 // TODO: there should be a timeout in case the sink is broken.
789 }
790
791 return false;
792}
793
794void ICAPModXact::stopParsing()
795{
796 if (state.parsing == State::psDone)
797 return;
798
799 debugs(93, 7, "ICAPModXact will no longer parse " << status());
800
801 delete bodyParser;
802
803 bodyParser = NULL;
804
805 state.parsing = State::psDone;
806}
807
808// HTTP side added virgin body data
809void ICAPModXact::noteSourceProgress(MsgPipe *p)
810{
811 ICAPXaction_Enter(noteSourceProgress);
812
813 Must(!state.doneReceiving);
814 writeMore();
815
816 if (state.sending == State::sendingVirgin)
817 echoMore();
818
819 ICAPXaction_Exit();
820}
821
822// HTTP side sent us all virgin info
823void ICAPModXact::noteSourceFinish(MsgPipe *p)
824{
825 ICAPXaction_Enter(noteSourceFinish);
826
827 Must(!state.doneReceiving);
828 stopReceiving();
829
830 // push writer and sender in case we were waiting for the last-chunk
831 writeMore();
832
833 if (state.sending == State::sendingVirgin)
834 echoMore();
835
836 ICAPXaction_Exit();
837}
838
839// HTTP side is aborting
840void ICAPModXact::noteSourceAbort(MsgPipe *p)
841{
842 ICAPXaction_Enter(noteSourceAbort);
843
844 Must(!state.doneReceiving);
845 stopReceiving();
846 mustStop("HTTP source quit");
847
848 ICAPXaction_Exit();
849}
850
851// HTTP side wants more adapted data and possibly freed some buffer space
852void ICAPModXact::noteSinkNeed(MsgPipe *p)
853{
854 ICAPXaction_Enter(noteSinkNeed);
855
856 if (state.sending == State::sendingVirgin)
857 echoMore();
858 else
859 if (state.sending == State::sendingAdapted)
860 parseMore();
861 else
862 Must(state.sending == State::sendingUndecided);
863
864 ICAPXaction_Exit();
865}
866
867// HTTP side aborted
868void ICAPModXact::noteSinkAbort(MsgPipe *p)
869{
870 ICAPXaction_Enter(noteSinkAbort);
871
872 mustStop("HTTP sink quit");
873
874 ICAPXaction_Exit();
875}
876
877// internal cleanup
878void ICAPModXact::doStop()
879{
880 ICAPXaction::doStop();
881
882 stopWriting();
883 stopBackup();
884
885 if (icapReply) {
886 delete icapReply;
887 icapReply = NULL;
888 }
889
890 stopSending(false);
891
892 // see stopReceiving() for reasons it cannot NULLify virgin there
893
894 if (virgin != NULL) {
895 if (!state.doneReceiving)
896 virgin->sendSinkAbort();
897 else
898 virgin->sink = NULL;
899
900 virgin = NULL; // refcounted
901 }
902
903 if (self != NULL) {
904 Pointer s = self;
905 self = NULL;
906 ICAPNoteXactionDone(s);
907 /* this object may be destroyed when 's' is cleared */
908 }
909}
910
911void ICAPModXact::makeRequestHeaders(MemBuf &buf)
912{
12b91c99 913 /*
914 * XXX These should use HttpHdr interfaces instead of Printfs
915 */
774c051c 916 const ICAPServiceRep &s = service();
917 buf.Printf("%s %s ICAP/1.0\r\n", s.methodStr(), s.uri.buf());
918 buf.Printf("Host: %s:%d\r\n", s.host.buf(), s.port);
12b91c99 919 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
920
921 if (!TheICAPConfig.reuse_connections)
922 buf.Printf("Connection: close\r\n");
923
774c051c 924 buf.Printf("Encapsulated: ");
925
926 MemBuf httpBuf;
12b91c99 927
774c051c 928 httpBuf.init();
929
930 // build HTTP request header, if any
931 ICAP::Method m = s.method;
932
933 if (ICAP::methodRespmod == m && virgin->data->cause)
934 encapsulateHead(buf, "req-hdr", httpBuf, virgin->data->cause);
935 else if (ICAP::methodReqmod == m)
936 encapsulateHead(buf, "req-hdr", httpBuf, virgin->data->header);
937
938 if (ICAP::methodRespmod == m)
939 if (const MsgPipeData::Header *prime = virgin->data->header)
940 encapsulateHead(buf, "res-hdr", httpBuf, prime);
941
942 if (!virginBody.expected())
1dd6edf2 943 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
774c051c 944 else if (ICAP::methodReqmod == m)
1dd6edf2 945 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
774c051c 946 else
1dd6edf2 947 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
774c051c 948
949 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
950
951 if (shouldPreview()) {
952 buf.Printf("Preview: %d\r\n", (int)preview.ad());
953 virginSendClaim.protectUpTo(preview.ad());
954 }
955
956 if (shouldAllow204()) {
957 buf.Printf("Allow: 204\r\n");
958 // be robust: do not rely on the expected body size
959 virginSendClaim.protectAll();
960 }
961
a97e82a8 962 const HttpRequest *request = virgin->data->cause ?
963 virgin->data->cause :
964 dynamic_cast<const HttpRequest*>(virgin->data->header);
965
12b91c99 966 if (TheICAPConfig.send_client_ip)
967 if (request->client_addr.s_addr != any_addr.s_addr)
968 buf.Printf("X-Client-IP: %s\r\n", inet_ntoa(request->client_addr));
a97e82a8 969
12b91c99 970 if (TheICAPConfig.send_client_username)
971 if (request->auth_user_request)
972 if (request->auth_user_request->username())
973 buf.Printf("X-Client-Username: %s\r\n", request->auth_user_request->username());
a97e82a8 974
2dfede9e 975 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 976
774c051c 977 buf.append(ICAP::crlf, 2); // terminate ICAP header
978
979 // start ICAP request body with encapsulated HTTP headers
980 buf.append(httpBuf.content(), httpBuf.contentSize());
981
982 httpBuf.clean();
983}
984
985void ICAPModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
986{
987 // update ICAP header
7cab7e9f 988 icapBuf.Printf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 989
990 // pack HTTP head
991 packHead(httpBuf, head);
992}
993
994void ICAPModXact::packHead(MemBuf &httpBuf, const HttpMsg *head)
995{
996 Packer p;
997 packerToMemInit(&p, &httpBuf);
998 head->packInto(&p, true);
999 packerClean(&p);
1000}
1001
1002// decides whether to offer a preview and calculates its size
1003bool ICAPModXact::shouldPreview()
1004{
1005 size_t wantedSize;
1006
7cdbbd47 1007 if (!TheICAPConfig.preview_enable) {
1008 debugs(93, 5, HERE << "preview disabled by squid.conf");
1009 return false;
1010 }
1011
774c051c 1012 if (!service().wantsPreview(wantedSize)) {
1013 debugs(93, 5, "ICAPModXact should not offer preview");
1014 return false;
1015 }
1016
1017 Must(wantedSize >= 0);
1018
1019 // cannot preview more than we can backup
1020 size_t ad = XMIN(wantedSize, TheBackupLimit);
1021
1022 if (virginBody.expected() && virginBody.knownSize())
1023 ad = XMIN(ad, virginBody.size()); // not more than we have
1024 else
1025 ad = 0; // questionable optimization?
1026
1027 debugs(93, 5, "ICAPModXact should offer " << ad << "-byte preview " <<
1028 "(service wanted " << wantedSize << ")");
1029
1030 preview.enable(ad);
1031
1032 return preview.enabled();
1033}
1034
1035// decides whether to allow 204 responses
1036bool ICAPModXact::shouldAllow204()
1037{
1038 if (!service().allows204())
1039 return false;
1040
1041 if (!virginBody.expected())
1042 return true; // no body means no problems with supporting 204s.
1043
1044 // if there is a body, make sure we can backup it all
1045
1046 if (!virginBody.knownSize())
1047 return false;
1048
1049 // or should we have a different backup limit?
1050 // note that '<' allows for 0-termination of the "full" backup buffer
1051 return virginBody.size() < TheBackupLimit;
1052}
1053
1054// returns a temporary string depicting transaction status, for debugging
1055void ICAPModXact::fillPendingStatus(MemBuf &buf) const
1056{
1057 if (state.serviceWaiting)
1058 buf.append("U", 1);
1059
1060 if (!state.doneWriting() && state.writing != State::writingInit)
1061 buf.Printf("w(%d)", state.writing);
1062
1063 if (preview.enabled()) {
1064 if (!preview.done())
1dd6edf2 1065 buf.Printf("P(%d)", (int) preview.debt());
774c051c 1066 }
1067
1068 if (virginSendClaim.active())
1069 buf.append("B", 1);
1070
1071 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1072 buf.Printf("p(%d)", state.parsing);
1073
1074 if (!doneSending() && state.sending != State::sendingUndecided)
1075 buf.Printf("S(%d)", state.sending);
1076}
1077
1078void ICAPModXact::fillDoneStatus(MemBuf &buf) const
1079{
1080 if (state.doneReceiving)
1081 buf.append("R", 1);
1082
1083 if (state.doneWriting())
1084 buf.append("w", 1);
1085
1086 if (preview.enabled()) {
1087 if (preview.done())
1088 buf.Printf("P%s", preview.ieof() ? "(ieof)" : "");
1089 }
1090
1091 if (doneReading())
1092 buf.append("r", 1);
1093
1094 if (state.doneParsing())
1095 buf.append("p", 1);
1096
1097 if (doneSending())
1098 buf.append("S", 1);
1099}
1100
1101bool ICAPModXact::gotEncapsulated(const char *section) const
1102{
1103 return httpHeaderGetByNameListMember(&icapReply->header, "Encapsulated",
1104 section, ',').size() > 0;
1105}
1106
1107// calculate whether there is a virgin HTTP body and
1108// whether its expected size is known
1109void ICAPModXact::estimateVirginBody()
1110{
1111 // note: defaults should be fine but will disable previews and 204s
1112
1113 Must(virgin != NULL && virgin->data->header);
1114
1115 method_t method;
1116
1117 if (virgin->data->cause)
1118 method = virgin->data->cause->method;
1119 else
a97e82a8 1120 if (HttpRequest *req = dynamic_cast<HttpRequest*>(virgin->data->
1121 header))
774c051c 1122 method = req->method;
1123 else
1124 return;
1125
1126 ssize_t size;
1127 if (virgin->data->header->expectingBody(method, size)) {
1128 virginBody.expect(size)
1129 ;
1130 debugs(93, 6, "ICAPModXact expects virgin body; size: " << size);
1131 } else {
1132 debugs(93, 6, "ICAPModXact does not expect virgin body");
1133 }
1134}
1135
1136
1137// TODO: Move SizedEstimate, MemBufBackup, and ICAPPreview elsewhere
1138
1139SizedEstimate::SizedEstimate()
1140 : theData(dtUnexpected)
1141{}
1142
1143void SizedEstimate::expect(ssize_t aSize)
1144{
1145 theData = (aSize >= 0) ? aSize : (ssize_t)dtUnknown;
1146}
1147
1148bool SizedEstimate::expected() const
1149{
1150 return theData != dtUnexpected;
1151}
1152
1153bool SizedEstimate::knownSize() const
1154{
1155 Must(expected());
1156 return theData != dtUnknown;
1157}
1158
1159size_t SizedEstimate::size() const
1160{
1161 Must(knownSize());
1162 return static_cast<size_t>(theData);
1163}
1164
1165
1166
1167MemBufClaim::MemBufClaim(): theStart(-1), theGoal(-1)
1168{}
1169
1170void MemBufClaim::protectAll()
1171{
1172 if (theStart < 0)
1173 theStart = 0;
1174
1175 theGoal = -1; // no specific goal
1176}
1177
1178void MemBufClaim::protectUpTo(size_t aGoal)
1179{
1180 if (theStart < 0)
1181 theStart = 0;
1182
1183 Must(aGoal >= 0);
1184
1185 theGoal = (theGoal < 0) ? static_cast<ssize_t>(aGoal) :
1186 XMIN(static_cast<ssize_t>(aGoal), theGoal);
1187}
1188
1189void MemBufClaim::disable()
1190{
1191 theStart = -1;
1192}
1193
1194void MemBufClaim::release(size_t size)
1195{
1196 Must(active());
1197 Must(size >= 0);
1198 theStart += static_cast<ssize_t>(size);
1199
1200 if (limited() && theStart >= theGoal)
1201 disable();
1202}
1203
1204size_t MemBufClaim::offset() const
1205{
1206 Must(active());
1207 return static_cast<size_t>(theStart);
1208}
1209
1210bool MemBufClaim::limited() const
1211{
1212 Must(active());
1213 return theGoal >= 0;
1214}
1215
1216
1217ICAPPreview::ICAPPreview(): theWritten(0), theAd(0), theState(stDisabled)
1218{}
1219
1220void ICAPPreview::enable(size_t anAd)
1221{
1222 // TODO: check for anAd not exceeding preview size limit
1223 Must(anAd >= 0);
1224 Must(!enabled());
1225 theAd = anAd;
1226 theState = stWriting;
1227}
1228
1229bool ICAPPreview::enabled() const
1230{
1231 return theState != stDisabled;
1232}
1233
1234size_t ICAPPreview::ad() const
1235{
1236 Must(enabled());
1237 return theAd;
1238}
1239
1240bool ICAPPreview::done() const
1241{
1242 Must(enabled());
1243 return theState >= stIeof;
1244}
1245
1246bool ICAPPreview::ieof() const
1247{
1248 Must(enabled());
1249 return theState == stIeof;
1250}
1251
1252size_t ICAPPreview::debt() const
1253{
1254 Must(enabled());
1255 return done() ? 0 : (theAd - theWritten);
1256}
1257
1258void ICAPPreview::wrote(size_t size, bool sawEof)
1259{
1260 Must(enabled());
1261 theWritten += size;
1262
1263 if (theWritten >= theAd)
1264 theState = stDone; // sawEof is irrelevant
1265 else
1266 if (sawEof)
1267 theState = stIeof;
1268}
1269