]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ICAP/ICAPModXact.cc
Bootstrapped
[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());
251 debugs(93, 8, "ICAPModXact will write up to " << size << " bytes of " <<
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) {
262 debugs(93, 7, "ICAPModXact will write " << chunkSize <<
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()) {
275 debugs(93, 8, "ICAPModXact will write last-chunk of " << label);
276 addLastRequestChunk(writeBuf);
277 }
278
279 debugs(93, 7, "ICAPModXact will write " << writeBuf.contentSize()
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());
527
528 if (state.parsingHeaders())
529 parseHeaders();
530
531 if (state.parsing == State::psBody)
532 parseBody();
533}
534
535// note that allocation for echoing is done in handle204NoContent()
536void ICAPModXact::maybeAllocateHttpMsg()
537{
538 if (adapted->data->header) // already allocated
539 return;
540
541 if (gotEncapsulated("res-hdr")) {
542 adapted->data->header = new HttpReply;
543 } else if (gotEncapsulated("req-hdr")) {
544 adapted->data->header = new HttpRequest;
545 } else
546 throw TexcHere("Neither res-hdr nor req-hdr in maybeAllocateHttpMsg()");
547}
548
549void ICAPModXact::parseHeaders()
550{
551 Must(state.parsingHeaders());
552
553 if (state.parsing == State::psIcapHeader)
554 parseIcapHead();
555
556 if (state.parsing == State::psHttpHeader)
557 parseHttpHead();
558
559 if (state.parsingHeaders()) { // need more data
560 Must(mayReadMore());
561 return;
562 }
563
564 adapted->sendSourceStart();
565
566 if (state.sending == State::sendingVirgin)
567 echoMore();
568}
569
570void ICAPModXact::parseIcapHead()
571{
572 Must(state.sending == State::sendingUndecided);
573
574 if (!parseHead(icapReply))
575 return;
576
fc764d26 577 if (httpHeaderHasConnDir(&icapReply->header, "close")) {
578 debugs(93, 5, HERE << "found connection close");
579 reuseConnection = false;
580 }
581
774c051c 582 switch (icapReply->sline.status) {
583
584 case 100:
585 handle100Continue();
586 break;
587
588 case 200:
b559db5d 589
590 if (!validate200Ok()) {
591 throw TexcHere("Invalid ICAP Response");
592 } else {
593 handle200Ok();
594 }
595
774c051c 596 break;
597
598 case 204:
599 handle204NoContent();
600 break;
601
602 default:
b559db5d 603 debugs(93, 5, HERE << "ICAP status " << icapReply->sline.status);
774c051c 604 handleUnknownScode();
605 break;
606 }
607
608 // handle100Continue() manages state.writing on its own.
609 // Non-100 status means the server needs no postPreview data from us.
610 if (state.writing == State::writingPaused)
611 stopWriting();
612
613 // TODO: Consider applying a Squid 2.5 patch to recognize 201 responses
614}
615
b559db5d 616bool ICAPModXact::validate200Ok()
617{
618 if (ICAP::methodRespmod == service().method) {
619 if (!gotEncapsulated("res-hdr"))
620 return false;
621
622 return true;
623 }
624
625 if (ICAP::methodReqmod == service().method) {
626 if (!gotEncapsulated("res-hdr") && !gotEncapsulated("req-hdr"))
627 return false;
628
629 return true;
630 }
631
632 return false;
633}
634
774c051c 635void ICAPModXact::handle100Continue()
636{
637 Must(state.writing == State::writingPaused);
638 Must(preview.enabled() && preview.done() && !preview.ieof());
639 Must(virginSendClaim.active());
640
641 if (virginSendClaim.limited()) // preview only
642 stopBackup();
643
644 state.parsing = State::psHttpHeader; // eventually
645
646 state.writing = State::writingPrime;
647
648 writeMore();
649}
650
651void ICAPModXact::handle200Ok()
652{
653 state.parsing = State::psHttpHeader;
654 state.sending = State::sendingAdapted;
655 stopBackup();
656}
657
658void ICAPModXact::handle204NoContent()
659{
660 stopParsing();
661 Must(virginSendClaim.active());
662 virginSendClaim.protectAll(); // extends protection if needed
663 state.sending = State::sendingVirgin;
664
665 // We want to clone the HTTP message, but we do not want
666 // to copy non-HTTP state parts that HttpMsg kids carry in them.
667 // Thus, we cannot use a smart pointer, copy constructor, or equivalent.
668 // Instead, we simply write the HTTP message and "clone" it by parsing.
669
670 HttpMsg *oldHead = virgin->data->header;
671 debugs(93, 7, "ICAPModXact cloning virgin message " << oldHead);
672
673 MemBuf httpBuf;
674
675 // write the virgin message into a memory buffer
676 httpBuf.init();
677 packHead(httpBuf, oldHead);
678
679 // allocate the adapted message
680 HttpMsg *&newHead = adapted->data->header;
681 Must(!newHead);
682
683 if (dynamic_cast<const HttpRequest*>(oldHead))
684 newHead = new HttpRequest;
685 else
686 if (dynamic_cast<const HttpReply*>(oldHead))
687 newHead = new HttpReply;
688
689 Must(newHead);
690
691 // parse the buffer back
692 http_status error = HTTP_STATUS_NONE;
693
694 Must(newHead->parse(&httpBuf, true, &error));
695
696 Must(newHead->hdr_sz == httpBuf.contentSize()); // no leftovers
697
698 httpBuf.clean();
699
700 debugs(93, 7, "ICAPModXact cloned virgin message " << oldHead << " to " << newHead);
701}
702
703void ICAPModXact::handleUnknownScode()
704{
705 stopParsing();
706 stopBackup();
707 // TODO: mark connection as "bad"
708
709 // Terminate the transaction; we do not know how to handle this response.
710 throw TexcHere("Unsupported ICAP status code");
711}
712
713void ICAPModXact::parseHttpHead()
714{
715 if (gotEncapsulated("res-hdr") || gotEncapsulated("req-hdr")) {
716 maybeAllocateHttpMsg();
717
718 if (!parseHead(adapted->data->header))
200ac359 719 return; // need more header data
774c051c 720 }
721
722 state.parsing = State::psBody;
723}
724
fc764d26 725/*
726 * Common routine used to parse both HTTP and ICAP headers
727 */
774c051c 728bool ICAPModXact::parseHead(HttpMsg *head)
729{
730 assert(head);
def17b6a 731 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " head bytes to parse" <<
774c051c 732 "; state: " << state.parsing);
733
734 http_status error = HTTP_STATUS_NONE;
735 const bool parsed = head->parse(&readBuf, commEof, &error);
736 Must(parsed || !error); // success or need more data
737
738 if (!parsed) { // need more data
739 head->reset();
740 return false;
741 }
742
743 readBuf.consume(head->hdr_sz);
744 return true;
745}
746
747void ICAPModXact::parseBody()
748{
749 Must(state.parsing == State::psBody);
750
aa761e5f 751 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes to parse");
774c051c 752
200ac359 753 if (gotEncapsulated("res-body") || gotEncapsulated("req-body")) {
774c051c 754 if (!parsePresentBody()) // need more body data
755 return;
756 } else {
b559db5d 757 debugs(93, 5, HERE << "not expecting a body");
774c051c 758 }
759
760 stopParsing();
761 stopSending(true);
762}
763
764// returns true iff complete body was parsed
765bool ICAPModXact::parsePresentBody()
766{
767 if (!bodyParser)
768 bodyParser = new ChunkedCodingParser;
769
770 // the parser will throw on errors
771 const bool parsed = bodyParser->parse(&readBuf, adapted->data->body);
772
773 adapted->sendSourceProgress(); // TODO: do not send if parsed nothing
774
aa761e5f 775 debugs(93, 5, HERE << "have " << readBuf.contentSize() << " body bytes after " <<
774c051c 776 "parse; parsed all: " << parsed);
777
778 if (parsed)
779 return true;
780
781 if (bodyParser->needsMoreData())
782 Must(mayReadMore());
783
784 if (bodyParser->needsMoreSpace()) {
785 Must(!doneSending()); // can hope for more space
786 Must(adapted->data->body->hasContent()); // paranoid
787 // TODO: there should be a timeout in case the sink is broken.
788 }
789
790 return false;
791}
792
793void ICAPModXact::stopParsing()
794{
795 if (state.parsing == State::psDone)
796 return;
797
798 debugs(93, 7, "ICAPModXact will no longer parse " << status());
799
800 delete bodyParser;
801
802 bodyParser = NULL;
803
804 state.parsing = State::psDone;
805}
806
807// HTTP side added virgin body data
808void ICAPModXact::noteSourceProgress(MsgPipe *p)
809{
810 ICAPXaction_Enter(noteSourceProgress);
811
812 Must(!state.doneReceiving);
813 writeMore();
814
815 if (state.sending == State::sendingVirgin)
816 echoMore();
817
818 ICAPXaction_Exit();
819}
820
821// HTTP side sent us all virgin info
822void ICAPModXact::noteSourceFinish(MsgPipe *p)
823{
824 ICAPXaction_Enter(noteSourceFinish);
825
826 Must(!state.doneReceiving);
827 stopReceiving();
828
829 // push writer and sender in case we were waiting for the last-chunk
830 writeMore();
831
832 if (state.sending == State::sendingVirgin)
833 echoMore();
834
835 ICAPXaction_Exit();
836}
837
838// HTTP side is aborting
839void ICAPModXact::noteSourceAbort(MsgPipe *p)
840{
841 ICAPXaction_Enter(noteSourceAbort);
842
843 Must(!state.doneReceiving);
844 stopReceiving();
845 mustStop("HTTP source quit");
846
847 ICAPXaction_Exit();
848}
849
850// HTTP side wants more adapted data and possibly freed some buffer space
851void ICAPModXact::noteSinkNeed(MsgPipe *p)
852{
853 ICAPXaction_Enter(noteSinkNeed);
854
855 if (state.sending == State::sendingVirgin)
856 echoMore();
857 else
858 if (state.sending == State::sendingAdapted)
859 parseMore();
860 else
861 Must(state.sending == State::sendingUndecided);
862
863 ICAPXaction_Exit();
864}
865
866// HTTP side aborted
867void ICAPModXact::noteSinkAbort(MsgPipe *p)
868{
869 ICAPXaction_Enter(noteSinkAbort);
870
871 mustStop("HTTP sink quit");
872
873 ICAPXaction_Exit();
874}
875
876// internal cleanup
877void ICAPModXact::doStop()
878{
879 ICAPXaction::doStop();
880
881 stopWriting();
882 stopBackup();
883
884 if (icapReply) {
885 delete icapReply;
886 icapReply = NULL;
887 }
888
889 stopSending(false);
890
891 // see stopReceiving() for reasons it cannot NULLify virgin there
892
893 if (virgin != NULL) {
894 if (!state.doneReceiving)
895 virgin->sendSinkAbort();
896 else
897 virgin->sink = NULL;
898
899 virgin = NULL; // refcounted
900 }
901
902 if (self != NULL) {
903 Pointer s = self;
904 self = NULL;
905 ICAPNoteXactionDone(s);
906 /* this object may be destroyed when 's' is cleared */
907 }
908}
909
910void ICAPModXact::makeRequestHeaders(MemBuf &buf)
911{
12b91c99 912 /*
913 * XXX These should use HttpHdr interfaces instead of Printfs
914 */
774c051c 915 const ICAPServiceRep &s = service();
916 buf.Printf("%s %s ICAP/1.0\r\n", s.methodStr(), s.uri.buf());
917 buf.Printf("Host: %s:%d\r\n", s.host.buf(), s.port);
12b91c99 918 buf.Printf("Date: %s\r\n", mkrfc1123(squid_curtime));
919
920 if (!TheICAPConfig.reuse_connections)
921 buf.Printf("Connection: close\r\n");
922
774c051c 923 buf.Printf("Encapsulated: ");
924
925 MemBuf httpBuf;
12b91c99 926
774c051c 927 httpBuf.init();
928
929 // build HTTP request header, if any
930 ICAP::Method m = s.method;
931
932 if (ICAP::methodRespmod == m && virgin->data->cause)
933 encapsulateHead(buf, "req-hdr", httpBuf, virgin->data->cause);
934 else if (ICAP::methodReqmod == m)
935 encapsulateHead(buf, "req-hdr", httpBuf, virgin->data->header);
936
937 if (ICAP::methodRespmod == m)
938 if (const MsgPipeData::Header *prime = virgin->data->header)
939 encapsulateHead(buf, "res-hdr", httpBuf, prime);
940
941 if (!virginBody.expected())
1dd6edf2 942 buf.Printf("null-body=%d", (int) httpBuf.contentSize());
774c051c 943 else if (ICAP::methodReqmod == m)
1dd6edf2 944 buf.Printf("req-body=%d", (int) httpBuf.contentSize());
774c051c 945 else
1dd6edf2 946 buf.Printf("res-body=%d", (int) httpBuf.contentSize());
774c051c 947
948 buf.append(ICAP::crlf, 2); // terminate Encapsulated line
949
950 if (shouldPreview()) {
951 buf.Printf("Preview: %d\r\n", (int)preview.ad());
952 virginSendClaim.protectUpTo(preview.ad());
953 }
954
955 if (shouldAllow204()) {
956 buf.Printf("Allow: 204\r\n");
957 // be robust: do not rely on the expected body size
958 virginSendClaim.protectAll();
959 }
960
a97e82a8 961 const HttpRequest *request = virgin->data->cause ?
962 virgin->data->cause :
963 dynamic_cast<const HttpRequest*>(virgin->data->header);
964
12b91c99 965 if (TheICAPConfig.send_client_ip)
966 if (request->client_addr.s_addr != any_addr.s_addr)
967 buf.Printf("X-Client-IP: %s\r\n", inet_ntoa(request->client_addr));
a97e82a8 968
12b91c99 969 if (TheICAPConfig.send_client_username)
970 if (request->auth_user_request)
971 if (request->auth_user_request->username())
972 buf.Printf("X-Client-Username: %s\r\n", request->auth_user_request->username());
a97e82a8 973
2dfede9e 974 // fprintf(stderr, "%s\n", buf.content());
a97e82a8 975
774c051c 976 buf.append(ICAP::crlf, 2); // terminate ICAP header
977
978 // start ICAP request body with encapsulated HTTP headers
979 buf.append(httpBuf.content(), httpBuf.contentSize());
980
981 httpBuf.clean();
982}
983
984void ICAPModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
985{
986 // update ICAP header
7cab7e9f 987 icapBuf.Printf("%s=%d, ", section, (int) httpBuf.contentSize());
774c051c 988
989 // pack HTTP head
990 packHead(httpBuf, head);
991}
992
993void ICAPModXact::packHead(MemBuf &httpBuf, const HttpMsg *head)
994{
995 Packer p;
996 packerToMemInit(&p, &httpBuf);
997 head->packInto(&p, true);
998 packerClean(&p);
999}
1000
1001// decides whether to offer a preview and calculates its size
1002bool ICAPModXact::shouldPreview()
1003{
1004 size_t wantedSize;
1005
1006 if (!service().wantsPreview(wantedSize)) {
1007 debugs(93, 5, "ICAPModXact should not offer preview");
1008 return false;
1009 }
1010
1011 Must(wantedSize >= 0);
1012
1013 // cannot preview more than we can backup
1014 size_t ad = XMIN(wantedSize, TheBackupLimit);
1015
1016 if (virginBody.expected() && virginBody.knownSize())
1017 ad = XMIN(ad, virginBody.size()); // not more than we have
1018 else
1019 ad = 0; // questionable optimization?
1020
1021 debugs(93, 5, "ICAPModXact should offer " << ad << "-byte preview " <<
1022 "(service wanted " << wantedSize << ")");
1023
1024 preview.enable(ad);
1025
1026 return preview.enabled();
1027}
1028
1029// decides whether to allow 204 responses
1030bool ICAPModXact::shouldAllow204()
1031{
1032 if (!service().allows204())
1033 return false;
1034
1035 if (!virginBody.expected())
1036 return true; // no body means no problems with supporting 204s.
1037
1038 // if there is a body, make sure we can backup it all
1039
1040 if (!virginBody.knownSize())
1041 return false;
1042
1043 // or should we have a different backup limit?
1044 // note that '<' allows for 0-termination of the "full" backup buffer
1045 return virginBody.size() < TheBackupLimit;
1046}
1047
1048// returns a temporary string depicting transaction status, for debugging
1049void ICAPModXact::fillPendingStatus(MemBuf &buf) const
1050{
1051 if (state.serviceWaiting)
1052 buf.append("U", 1);
1053
1054 if (!state.doneWriting() && state.writing != State::writingInit)
1055 buf.Printf("w(%d)", state.writing);
1056
1057 if (preview.enabled()) {
1058 if (!preview.done())
1dd6edf2 1059 buf.Printf("P(%d)", (int) preview.debt());
774c051c 1060 }
1061
1062 if (virginSendClaim.active())
1063 buf.append("B", 1);
1064
1065 if (!state.doneParsing() && state.parsing != State::psIcapHeader)
1066 buf.Printf("p(%d)", state.parsing);
1067
1068 if (!doneSending() && state.sending != State::sendingUndecided)
1069 buf.Printf("S(%d)", state.sending);
1070}
1071
1072void ICAPModXact::fillDoneStatus(MemBuf &buf) const
1073{
1074 if (state.doneReceiving)
1075 buf.append("R", 1);
1076
1077 if (state.doneWriting())
1078 buf.append("w", 1);
1079
1080 if (preview.enabled()) {
1081 if (preview.done())
1082 buf.Printf("P%s", preview.ieof() ? "(ieof)" : "");
1083 }
1084
1085 if (doneReading())
1086 buf.append("r", 1);
1087
1088 if (state.doneParsing())
1089 buf.append("p", 1);
1090
1091 if (doneSending())
1092 buf.append("S", 1);
1093}
1094
1095bool ICAPModXact::gotEncapsulated(const char *section) const
1096{
1097 return httpHeaderGetByNameListMember(&icapReply->header, "Encapsulated",
1098 section, ',').size() > 0;
1099}
1100
1101// calculate whether there is a virgin HTTP body and
1102// whether its expected size is known
1103void ICAPModXact::estimateVirginBody()
1104{
1105 // note: defaults should be fine but will disable previews and 204s
1106
1107 Must(virgin != NULL && virgin->data->header);
1108
1109 method_t method;
1110
1111 if (virgin->data->cause)
1112 method = virgin->data->cause->method;
1113 else
a97e82a8 1114 if (HttpRequest *req = dynamic_cast<HttpRequest*>(virgin->data->
1115 header))
774c051c 1116 method = req->method;
1117 else
1118 return;
1119
1120 ssize_t size;
1121 if (virgin->data->header->expectingBody(method, size)) {
1122 virginBody.expect(size)
1123 ;
1124 debugs(93, 6, "ICAPModXact expects virgin body; size: " << size);
1125 } else {
1126 debugs(93, 6, "ICAPModXact does not expect virgin body");
1127 }
1128}
1129
1130
1131// TODO: Move SizedEstimate, MemBufBackup, and ICAPPreview elsewhere
1132
1133SizedEstimate::SizedEstimate()
1134 : theData(dtUnexpected)
1135{}
1136
1137void SizedEstimate::expect(ssize_t aSize)
1138{
1139 theData = (aSize >= 0) ? aSize : (ssize_t)dtUnknown;
1140}
1141
1142bool SizedEstimate::expected() const
1143{
1144 return theData != dtUnexpected;
1145}
1146
1147bool SizedEstimate::knownSize() const
1148{
1149 Must(expected());
1150 return theData != dtUnknown;
1151}
1152
1153size_t SizedEstimate::size() const
1154{
1155 Must(knownSize());
1156 return static_cast<size_t>(theData);
1157}
1158
1159
1160
1161MemBufClaim::MemBufClaim(): theStart(-1), theGoal(-1)
1162{}
1163
1164void MemBufClaim::protectAll()
1165{
1166 if (theStart < 0)
1167 theStart = 0;
1168
1169 theGoal = -1; // no specific goal
1170}
1171
1172void MemBufClaim::protectUpTo(size_t aGoal)
1173{
1174 if (theStart < 0)
1175 theStart = 0;
1176
1177 Must(aGoal >= 0);
1178
1179 theGoal = (theGoal < 0) ? static_cast<ssize_t>(aGoal) :
1180 XMIN(static_cast<ssize_t>(aGoal), theGoal);
1181}
1182
1183void MemBufClaim::disable()
1184{
1185 theStart = -1;
1186}
1187
1188void MemBufClaim::release(size_t size)
1189{
1190 Must(active());
1191 Must(size >= 0);
1192 theStart += static_cast<ssize_t>(size);
1193
1194 if (limited() && theStart >= theGoal)
1195 disable();
1196}
1197
1198size_t MemBufClaim::offset() const
1199{
1200 Must(active());
1201 return static_cast<size_t>(theStart);
1202}
1203
1204bool MemBufClaim::limited() const
1205{
1206 Must(active());
1207 return theGoal >= 0;
1208}
1209
1210
1211ICAPPreview::ICAPPreview(): theWritten(0), theAd(0), theState(stDisabled)
1212{}
1213
1214void ICAPPreview::enable(size_t anAd)
1215{
1216 // TODO: check for anAd not exceeding preview size limit
1217 Must(anAd >= 0);
1218 Must(!enabled());
1219 theAd = anAd;
1220 theState = stWriting;
1221}
1222
1223bool ICAPPreview::enabled() const
1224{
1225 return theState != stDisabled;
1226}
1227
1228size_t ICAPPreview::ad() const
1229{
1230 Must(enabled());
1231 return theAd;
1232}
1233
1234bool ICAPPreview::done() const
1235{
1236 Must(enabled());
1237 return theState >= stIeof;
1238}
1239
1240bool ICAPPreview::ieof() const
1241{
1242 Must(enabled());
1243 return theState == stIeof;
1244}
1245
1246size_t ICAPPreview::debt() const
1247{
1248 Must(enabled());
1249 return done() ? 0 : (theAd - theWritten);
1250}
1251
1252void ICAPPreview::wrote(size_t size, bool sawEof)
1253{
1254 Must(enabled());
1255 theWritten += size;
1256
1257 if (theWritten >= theAd)
1258 theState = stDone; // sawEof is irrelevant
1259 else
1260 if (sawEof)
1261 theState = stIeof;
1262}
1263