2 * DEBUG: section 86 ESI processing
3 * AUTHOR: Robert Collins
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 ; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
31 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
34 #include "squid-old.h"
36 /* MS Visual Studio Projects are monolithic, so we need the following
37 * #if to exclude the ESI code from compile process when not needed.
39 #if (USE_SQUID_ESI == 1)
42 #include "clientStream.h"
43 #include "client_side_request.h"
44 #include "comm/Connection.h"
45 #include "errorpage.h"
46 #include "esi/Segment.h"
47 #include "esi/Element.h"
48 #include "esi/Context.h"
49 #include "HttpHdrSc.h"
50 #include "HttpHdrScTarget.h"
51 #include "HttpReply.h"
52 #include "esi/Attempt.h"
53 #include "esi/Except.h"
54 #include "client_side.h"
55 #include "esi/VarState.h"
56 #include "esi/Assign.h"
57 #include "esi/Expression.h"
58 #include "HttpRequest.h"
60 #include "ip/Address.h"
62 /* quick reference on behaviour here.
63 * The ESI specification 1.0 requires the ESI processor to be able to
64 * return an error code at any point in the processing. To that end
65 * we buffer the incoming esi body until we know we will be able to
66 * satisfy the request. At that point we start streaming the queued
71 class ESIStreamContext
;
73 /* TODO: split this out into separate files ? */
74 /* Parsing: quick and dirty. ESI files are not valid XML, so a generic
75 * XML parser is not much use. Also we need a push parser not a pull
76 * parser, so LibXML is out.
78 * Interpreter methods:
79 * Render: May only ever be called after Process returns PROCESS_COMPLETE.
80 * Renders the resulting content into a ESISegment chain.
81 * Process: returns the status of the node.
82 * COMPLETE - processing is complete, rendering may staret
83 * PENDING_WONTFAIL - process is incomplete, but the element *will*
84 * be able to be rendered given time.
85 * PENDING_MAYFAIL - processing is incomplete, and the element *may*
86 * fail to be able to rendered.
87 * FAILED - processing failed, return an error to the client.
91 * NOT TODO: esi:inline - out of scope.
94 /* make comparisons with refcount pointers easy */
95 bool operator == (ESIElement
const *lhs
, ESIElement::Pointer
const &rhs
)
97 return lhs
== rhs
.getRaw();
100 typedef ESIContext::esiKick_t esiKick_t
;
103 /* some core operators */
107 struct esiComment
: public ESIElement
{
108 MEMPROXY_CLASS(esiComment
);
111 Pointer
makeCacheable() const;
112 Pointer
makeUsable(esiTreeParentPtr
, ESIVarState
&) const;
114 void render(ESISegment::Pointer
);
118 MEMPROXY_CLASS_INLINE(esiComment
);
120 #include "esi/Literal.h"
122 #include "esi/Sequence.h"
124 #include "esi/Include.h"
128 class esiRemove
: public ESIElement
132 void *operator new (size_t byteCount
);
133 void operator delete (void *address
);
136 void render(ESISegment::Pointer
);
137 bool addElement (ESIElement::Pointer
);
138 Pointer
makeCacheable() const;
139 Pointer
makeUsable(esiTreeParentPtr
, ESIVarState
&) const;
143 CBDATA_TYPE (esiRemove
);
144 static FREE esiRemoveFree
;
145 static ESIElement
* esiRemoveNew(void);
150 struct esiTry
: public ESIElement
{
151 MEMPROXY_CLASS(esiTry
);
153 esiTry(esiTreeParentPtr aParent
);
156 void render(ESISegment::Pointer
);
157 bool addElement (ESIElement::Pointer
);
158 void fail(ESIElement
*, char const * = NULL
);
159 esiProcessResult_t
process (int dovars
);
160 void provideData (ESISegment::Pointer data
, ESIElement
* source
);
161 Pointer
makeCacheable() const;
162 Pointer
makeUsable(esiTreeParentPtr
, ESIVarState
&) const;
164 ESIElement::Pointer attempt
;
165 ESIElement::Pointer except
;
168 int attemptok
:1; /* the attempt branch process correctly */
169 int exceptok
:1; /* likewise */
170 int attemptfailed
:1; /* The attempt branch failed */
171 int exceptfailed
:1; /* the except branch failed */
177 esiTreeParentPtr parent
;
178 ESISegment::Pointer exceptbuffer
;
179 esiTry (esiTry
const &);
180 esiProcessResult_t
bestAttemptRV() const;
183 MEMPROXY_CLASS_INLINE(esiTry
);
189 struct esiChoose
: public ESIElement
{
190 MEMPROXY_CLASS(esiChoose
);
192 esiChoose(esiTreeParentPtr
);
195 void render(ESISegment::Pointer
);
196 bool addElement (ESIElement::Pointer
);
197 void fail(ESIElement
*, char const * = NULL
);
198 esiProcessResult_t
process (int dovars
);
200 void provideData (ESISegment::Pointer data
, ESIElement
*source
);
201 void makeCachableElements(esiChoose
const &old
);
202 void makeUsableElements(esiChoose
const &old
, ESIVarState
&);
203 Pointer
makeCacheable() const;
204 Pointer
makeUsable(esiTreeParentPtr
, ESIVarState
&) const;
207 ElementList elements
;
209 ESIElement::Pointer otherwise
;
213 esiChoose(esiChoose
const &);
214 esiTreeParentPtr parent
;
215 void checkValidSource (ESIElement::Pointer source
) const;
216 void selectElement();
219 MEMPROXY_CLASS_INLINE(esiChoose
);
223 struct esiWhen
: public esiSequence
{
224 MEMPROXY_CLASS(esiWhen
);
225 esiWhen(esiTreeParentPtr aParent
, int attributes
, const char **attr
, ESIVarState
*);
227 Pointer
makeCacheable() const;
228 Pointer
makeUsable(esiTreeParentPtr
, ESIVarState
&) const;
230 bool testsTrue() const { return testValue
;}
232 void setTestResult(bool aBool
) {testValue
= aBool
;}
235 esiWhen (esiWhen
const &);
237 char const *unevaluatedExpression
;
238 ESIVarState
*varState
;
242 MEMPROXY_CLASS_INLINE(esiWhen
);
246 struct esiOtherwise
: public esiSequence
{
247 // void *operator new (size_t byteCount);
248 // void operator delete (void *address);
249 esiOtherwise(esiTreeParentPtr aParent
) : esiSequence (aParent
) {}
252 CBDATA_CLASS_INIT(ESIContext
);
254 void ESIContext::startRead()
260 void ESIContext::finishRead()
266 bool ESIContext::reading() const
272 ESIStreamContext::ESIStreamContext() : finished(false), include (NULL
), localbuffer (new ESISegment
), buffer (NULL
)
275 /* Local functions */
277 static ESIContext
*ESIContextNew(HttpReply
*, clientStreamNode
*, ClientHttpRequest
*);
281 ESIContext::operator new(size_t byteCount
)
283 assert (byteCount
== sizeof (ESIContext
));
284 CBDATA_INIT_TYPE(ESIContext
);
285 ESIContext
*result
= cbdataAlloc(ESIContext
);
290 ESIContext::operator delete (void *address
)
292 ESIContext
*t
= static_cast<ESIContext
*>(address
);
297 ESIContext::setError()
300 errorstatus
= HTTP_INTERNAL_SERVER_ERROR
;
305 ESIContext::appendOutboundData(ESISegment::Pointer theData
)
307 if (!outbound
.getRaw()) {
309 outboundtail
= outbound
;
311 assert (outboundtail
->next
.getRaw() == NULL
);
312 outboundtail
->next
= theData
;
316 debugs(86, 9, "ESIContext::appendOutboundData: outbound " << outbound
.getRaw());
320 ESIContext::provideData (ESISegment::Pointer theData
, ESIElement
* source
)
322 debugs(86, 5, "ESIContext::provideData: " << this << " " << theData
.getRaw() << " " << source
);
323 /* No callbacks permitted after finish() called on the tree */
324 assert (tree
.getRaw());
325 assert (source
== tree
);
326 appendOutboundData(theData
);
334 ESIContext::fail (ESIElement
* source
, char const *anError
)
337 setErrorMessage (anError
);
343 ESIContext::fixupOutboundTail()
345 /* TODO: fixup thisNode outboundtail dross a little */
347 if (outboundtail
.getRaw())
348 outboundtail
= outboundtail
->tail();
357 debugs(86, 5, "esiKick: Re-entered whilst in progress");
358 // return ESI_KICK_INPROGRESS;
363 /* we've been detached from - we can't do anything more */
364 return ESI_KICK_FAILED
;
366 /* Something has occured. Process any remaining nodes */
368 /* Process some of our data */
369 switch (process ()) {
371 case ESI_PROCESS_COMPLETE
:
372 debugs(86, 5, "esiKick: esiProcess OK");
375 case ESI_PROCESS_PENDING_WONTFAIL
:
376 debugs(86, 5, "esiKick: esiProcess PENDING OK");
379 case ESI_PROCESS_PENDING_MAYFAIL
:
380 debugs(86, 5, "esiKick: esiProcess PENDING UNKNOWN");
383 case ESI_PROCESS_FAILED
:
384 debugs(86, 2, "esiKick: esiProcess " << this << " FAILED");
385 /* this can not happen - processing can't fail until we have data,
386 * and when we come here we have sent data to the client
394 return ESI_KICK_FAILED
;
397 /* Render if we can to get maximal sent data */
398 assert (tree
.getRaw() || flags
.error
);
400 if (!flags
.finished
&& !outbound
.getRaw()) {
401 outboundtail
= new ESISegment
;
402 outbound
= outboundtail
;
405 if (!flags
.error
&& !flags
.finished
)
406 tree
->render(outboundtail
);
411 /* Is there data to send? */
413 /* some data was sent. we're finished until the next read */
415 return ESI_KICK_SENT
;
419 /* nothing to send */
420 return flags
.error
? ESI_KICK_FAILED
: ESI_KICK_PENDING
;
423 /* request from downstream for more data
426 esiStreamRead (clientStreamNode
*thisNode
, ClientHttpRequest
*http
)
428 clientStreamNode
*next
;
429 /* Test preconditions */
430 assert (thisNode
!= NULL
);
431 assert (cbdataReferenceValid (thisNode
));
432 /* we are not in the chain until ESI is detected on a data callback */
433 assert (thisNode
->node
.prev
!= NULL
);
434 assert (thisNode
->node
.next
!= NULL
);
436 ESIContext::Pointer context
= dynamic_cast<ESIContext
*>(thisNode
->data
.getRaw());
437 assert (context
.getRaw() != NULL
);
439 if (context
->flags
.passthrough
) {
440 /* passthru mode - read into supplied buffers */
441 next
= thisNode
->next();
442 clientStreamRead (thisNode
, http
, next
->readBuffer
);
446 context
->flags
.clientwantsdata
= 1;
447 debugs(86, 5, "esiStreamRead: Client now wants data");
449 /* Ok, not passing through */
451 switch (context
->kick ()) {
453 case ESIContext::ESI_KICK_FAILED
:
454 /* this can not happen - processing can't fail until we have data,
455 * and when we come here we have sent data to the client
458 case ESIContext::ESI_KICK_SENT
:
460 case ESIContext::ESI_KICK_INPROGRESS
:
463 case ESIContext::ESI_KICK_PENDING
:
467 /* Nothing to send */
469 if (context
->flags
.oktosend
&& (context
->flags
.finishedtemplate
470 || context
->cachedASTInUse
) &&
471 ! context
->flags
.finished
) {
472 /* we've started sending, finished reading, but not finished
473 * processing. stop here, a callback will resume the stream
476 debugs(86, 5, "esiStreamRead: Waiting for async resume of esi processing");
480 if (context
->flags
.oktosend
&& context
->flags
.finished
&& context
->outbound
.getRaw()) {
481 debugs(86, 5, "all processing complete, but outbound data still buffered");
482 assert (!context
->flags
.clientwantsdata
);
483 /* client MUST be processing the last reply */
488 if (context
->flags
.oktosend
&& context
->flags
.finished
) {
489 StoreIOBuffer tempBuffer
;
490 assert (!context
->outbound
.getRaw());
491 /* We've finished processing, and there is no more data buffered */
492 debugs(86, 5, "Telling recipient EOF on READ");
493 clientStreamCallback (thisNode
, http
, NULL
, tempBuffer
);
497 if (context
->reading())
500 /* no data that is ready to send, and still reading? well, lets get some */
501 /* secure a buffer */
502 if (!context
->incoming
.getRaw()) {
503 /* create a new buffer segment */
504 context
->buffered
= new ESISegment
;
505 context
->incoming
= context
->buffered
;
508 assert (context
->incoming
.getRaw() && context
->incoming
->len
!= HTTP_REQBUF_SZ
);
510 StoreIOBuffer tempBuffer
;
511 tempBuffer
.offset
= context
->readpos
;
512 tempBuffer
.length
= context
->incoming
->len
- HTTP_REQBUF_SZ
;
513 tempBuffer
.data
= &context
->incoming
->buf
[context
->incoming
->len
];
514 context
->startRead();
515 clientStreamRead (thisNode
, http
, tempBuffer
);
519 clientStream_status_t
520 esiStreamStatus (clientStreamNode
*thisNode
, ClientHttpRequest
*http
)
522 /* Test preconditions */
523 assert (thisNode
!= NULL
);
524 assert (cbdataReferenceValid (thisNode
));
525 /* we are not in the chain until ESI is detected on a data callback */
526 assert (thisNode
->node
.prev
!= NULL
);
527 assert (thisNode
->node
.next
!= NULL
);
529 ESIContext::Pointer context
= dynamic_cast<ESIContext
*>(thisNode
->data
.getRaw());
530 assert (context
.getRaw() != NULL
);
532 if (context
->flags
.passthrough
)
533 return clientStreamStatus (thisNode
, http
);
535 if (context
->flags
.oktosend
&& context
->flags
.finished
&&
536 !(context
->outbound
.getRaw() && context
->outbound_offset
< context
->outbound
->len
)) {
537 debugs(86, 5, "Telling recipient EOF on STATUS");
538 return STREAM_UNPLANNED_COMPLETE
; /* we don't know lengths in advance */
541 /* ?? RC: we can't be aborted / fail ? */
546 esiAlwaysPassthrough(http_status sline
)
552 case HTTP_CONTINUE
: /* Should never reach us... but squid needs to alter to accomodate this */
554 case HTTP_SWITCHING_PROTOCOLS
: /* Ditto */
556 case HTTP_PROCESSING
: /* Unknown - some extension */
558 case HTTP_NO_CONTENT
: /* no body, no esi */
560 case HTTP_NOT_MODIFIED
: /* ESI does not affect assembled page headers, so 304s are valid */
573 ESIContext::trimBlanks()
575 /* trim leading empty buffers ? */
577 while (outbound
.getRaw() && outbound
->next
.getRaw() && !outbound
->len
) {
578 debugs(86, 5, "ESIContext::trimBlanks: " << this <<
579 " skipping segment " << outbound
.getRaw());
580 outbound
= outbound
->next
;
583 if (outboundtail
.getRaw())
584 assert (outbound
.getRaw());
587 /* Send data downstream
588 * Returns 0 if nothing was sent. Non-zero if data was sent.
593 debugs(86, 5, "ESIContext::send: this=" << this);
594 /* send any processed data */
598 if (!flags
.clientwantsdata
) {
599 debugs(86, 5, "ESIContext::send: Client does not want data - not sending anything");
603 if (tree
.getRaw() && tree
->mayFail()) {
604 debugs(86, 5, "ESIContext::send: Tree may fail. Not sending.");
611 if (!flags
.oktosend
) {
613 fatal("ESIContext::send: Not OK to send.\n");
619 if (!(rep
|| (outbound
.getRaw() &&
620 outbound
->len
&& (outbound_offset
<= outbound
->len
)))) {
621 debugs(86, 5, "ESIContext::send: Nothing to send.");
625 debugs(86, 5, "ESIContext::send: Sending something...");
626 /* Yes! Send it without asking for more upstream */
627 /* memcopying because the client provided the buffer */
628 /* TODO: skip data until pos == next->readoff; */
629 assert (thisNode
->data
== this);
630 clientStreamNode
*next
= thisNode
->next();
631 ESIContext
*templock
= cbdataReference (this);
634 if (outbound
.getRaw())
635 len
= min (next
->readBuffer
.length
, outbound
->len
- outbound_offset
);
637 /* prevent corruption on range requests, even though we don't support them yet */
638 assert (pos
== next
->readBuffer
.offset
);
640 /* We must send data or a reply */
641 assert (len
!= 0 || rep
!= NULL
);
644 memcpy(next
->readBuffer
.data
, &outbound
->buf
[outbound_offset
], len
);
646 if (len
+ outbound_offset
== outbound
->len
) {
647 ESISegment::Pointer temp
= outbound
->next
;
648 /* remove the used buffer */
655 if (!outbound
.getRaw())
661 flags
.clientwantsdata
= 0;
662 debugs(86, 5, "ESIContext::send: this=" << this << " Client no longer wants data ");
663 /* Deal with re-entrancy */
664 HttpReply
*temprep
= rep
;
665 rep
= NULL
; /* freed downstream */
667 if (temprep
&& varState
)
668 varState
->buildVary (temprep
);
671 StoreIOBuffer tempBuffer
;
672 tempBuffer
.length
= len
;
673 tempBuffer
.offset
= pos
- len
;
674 tempBuffer
.data
= next
->readBuffer
.data
;
675 clientStreamCallback (thisNode
, http
, temprep
, tempBuffer
);
679 len
= 1; /* tell the caller we sent something (because we sent headers */
682 cbdataReferenceDone (templock
);
684 debugs (86,5,"ESIContext::send: this=" << this << " sent " << len
);
690 ESIContext::finishChildren()
698 /* Detach event from a client Stream */
700 esiStreamDetach (clientStreamNode
*thisNode
, ClientHttpRequest
*http
)
702 /* if we have pending callbacks, tell them we're done. */
703 /* test preconditions */
704 assert (thisNode
!= NULL
);
705 assert (cbdataReferenceValid (thisNode
));
706 ESIContext::Pointer context
= dynamic_cast<ESIContext
*>(thisNode
->data
.getRaw());
707 assert (context
.getRaw() != NULL
);
708 /* detach from the stream */
709 clientStreamDetach (thisNode
,http
);
710 /* if we have pending callbacks (from subincludes), tell them we're done. */
711 context
->thisNode
= NULL
;
712 context
->flags
.detached
= 1;
713 context
->finishChildren();
714 /* HACK for parser stack not being emptied */
715 context
->parserState
.stack
[0] = NULL
;
716 /* allow refcount logic to trigger */
717 context
->cbdataLocker
= NULL
;
720 /* Process incoming data for ESI tags */
721 /* ESI TODO: Long term: we should have a framework to parse html/xml and
722 * callback to a set of processors like thisNode, to prevent multiple parsing
723 * overhead. More thoughts on thisNode: We have to parse multiple times, because
724 * the output of one processor may create a very different tree. What we could
725 * do is something like DOM and pass that down to a final renderer. This is
726 * getting into web server territory though...
729 * This is not the last node in the stream.
730 * ESI processing has been enabled.
731 * There is context data or a reply structure
734 esiProcessStream (clientStreamNode
*thisNode
, ClientHttpRequest
*http
, HttpReply
*rep
, StoreIOBuffer receivedData
)
736 /* test preconditions */
737 assert (thisNode
!= NULL
);
738 /* ESI TODO: handle thisNode rather than asserting - it should only ever
739 * happen if we cause an abort and the callback chain
740 * loops back to here, so we can simply return. However, that itself
741 * shouldn't happen, so it stays as an assert for now. */
742 assert (cbdataReferenceValid (thisNode
));
744 * if data is NULL thisNode is the first entrance. If rep is also NULL,
745 * something is wrong.
747 assert (thisNode
->data
.getRaw() != NULL
|| rep
);
748 assert (thisNode
->node
.next
!= NULL
);
750 if (!thisNode
->data
.getRaw())
751 /* setup ESI context from reply headers */
752 thisNode
->data
= ESIContextNew(rep
, thisNode
, http
);
754 ESIContext::Pointer context
= dynamic_cast<ESIContext
*>(thisNode
->data
.getRaw());
756 assert (context
.getRaw() != NULL
);
758 context
->finishRead();
760 /* Skipping all ESI processing. All remaining data gets untouched.
761 * Mainly used when an error or other non-ESI processable entity
762 * has been detected to prevent ESI processing the error body
764 if (context
->flags
.passthrough
) {
765 clientStreamCallback (thisNode
, http
, rep
, receivedData
);
769 debugs(86, 3, "esiProcessStream: Processing thisNode " << thisNode
<<
770 " context " << context
.getRaw() << " offset " <<
771 (int) receivedData
.offset
<< " length " <<
772 (unsigned int)receivedData
.length
);
774 /* once we finish the template, we *cannot* return here */
775 assert (!context
->flags
.finishedtemplate
);
776 assert (!context
->cachedASTInUse
);
778 /* Can we generate any data ?*/
780 if (receivedData
.data
) {
781 /* Increase our buffer area with incoming data */
782 assert (receivedData
.length
<= HTTP_REQBUF_SZ
);
783 assert (thisNode
->readBuffer
.offset
== receivedData
.offset
);
784 debugs (86,5, "esiProcessStream found " << receivedData
.length
<< " bytes of body data at offset " << receivedData
.offset
);
785 /* secure the data for later use */
787 if (!context
->incoming
.getRaw()) {
788 /* create a new buffer segment */
789 debugs(86, 5, "esiProcessStream: Setting up incoming buffer");
790 context
->buffered
= new ESISegment
;
791 context
->incoming
= context
->buffered
;
794 if (receivedData
.data
!= &context
->incoming
->buf
[context
->incoming
->len
]) {
795 /* We have to copy the data out because we didn't supply thisNode buffer */
796 size_t space
= HTTP_REQBUF_SZ
- context
->incoming
->len
;
797 size_t len
= min (space
, receivedData
.length
);
798 debugs(86, 5, "Copying data from " << receivedData
.data
<< " to " <<
799 &context
->incoming
->buf
[context
->incoming
->len
] <<
800 " because our buffer was not used");
802 memcpy(&context
->incoming
->buf
[context
->incoming
->len
], receivedData
.data
, len
);
803 context
->incoming
->len
+= len
;
805 if (context
->incoming
->len
== HTTP_REQBUF_SZ
) {
806 /* append another buffer */
807 context
->incoming
->next
= new ESISegment
;
808 context
->incoming
= context
->incoming
->next
;
811 if (len
!= receivedData
.length
) {
812 /* capture the remnants */
813 memcpy(context
->incoming
->buf
, &receivedData
.data
[len
], receivedData
.length
- len
);
814 context
->incoming
->len
= receivedData
.length
- len
;
817 /* and note where we are up to */
818 context
->readpos
+= receivedData
.length
;
820 /* update our position counters, and if needed assign a new buffer */
821 context
->incoming
->len
+= receivedData
.length
;
822 assert (context
->incoming
->len
<= HTTP_REQBUF_SZ
);
824 if (context
->incoming
->len
> HTTP_REQBUF_SZ
* 3 / 4) {
825 /* allocate a new buffer - to stop us asking for ridiculously small amounts */
826 context
->incoming
->next
= new ESISegment
;
827 context
->incoming
= context
->incoming
->next
;
830 context
->readpos
+= receivedData
.length
;
834 /* EOF / Read error / aborted entry */
835 if (rep
== NULL
&& receivedData
.data
== NULL
&& receivedData
.length
== 0 && !context
->flags
.finishedtemplate
) {
836 /* TODO: get stream status to test the entry for aborts */
837 /* else flush the esi processor */
838 debugs(86, 5, "esiProcess: " << context
.getRaw() << " Finished reading upstream data");
839 /* This is correct */
840 context
->flags
.finishedtemplate
= 1;
843 switch (context
->kick()) {
845 case ESIContext::ESI_KICK_FAILED
:
846 /* thisNode can not happen - processing can't fail until we have data,
847 * and when we come here we have sent data to the client
851 case ESIContext::ESI_KICK_SENT
:
853 case ESIContext::ESI_KICK_INPROGRESS
:
856 case ESIContext::ESI_KICK_PENDING
:
860 /* ok.. no data sent, try to pull more data in from upstream.
861 * FIXME: Don't try thisNode if we have finished reading the template
863 if (!context
->flags
.finishedtemplate
&& !context
->reading()
864 && !context
->cachedASTInUse
) {
865 StoreIOBuffer tempBuffer
;
866 assert (context
->incoming
.getRaw() && context
->incoming
->len
< HTTP_REQBUF_SZ
);
867 tempBuffer
.offset
= context
->readpos
;
868 tempBuffer
.length
= HTTP_REQBUF_SZ
- context
->incoming
->len
;
869 tempBuffer
.data
= &context
->incoming
->buf
[context
->incoming
->len
];
870 context
->startRead();
871 clientStreamRead (thisNode
, http
, tempBuffer
);
875 debugs(86, 3, "esiProcessStream: no data to send, no data to read, awaiting a callback");
878 ESIContext::~ESIContext()
881 /* Not freed by freeresources because esi::fail needs it */
882 safe_free (errormessage
);
883 debugs(86, 3, "ESIContext::~ESIContext: Freed " << this);
887 ESIContextNew (HttpReply
*rep
, clientStreamNode
*thisNode
, ClientHttpRequest
*http
)
890 ESIContext
*rv
= new ESIContext
;
892 rv
->cbdataLocker
= rv
;
894 if (esiAlwaysPassthrough(rep
->sline
.status
)) {
895 rv
->flags
.passthrough
= 1;
897 /* remove specific headers for ESI to prevent
898 * downstream cache confusion */
899 HttpHeader
*hdr
= &rep
->header
;
900 hdr
->delById(HDR_ACCEPT_RANGES
);
901 hdr
->delById(HDR_ETAG
);
902 hdr
->delById(HDR_CONTENT_LENGTH
);
903 hdr
->delById(HDR_CONTENT_MD5
);
904 rv
->tree
= new esiSequence (rv
, true);
905 rv
->thisNode
= thisNode
;
907 rv
->flags
.clientwantsdata
= 1;
908 rv
->varState
= new ESIVarState (&http
->request
->header
, http
->uri
);
909 debugs(86, 5, "ESIContextNew: Client wants data (always created during reply cycle");
912 debugs(86, 5, "ESIContextNew: Create context " << rv
);
916 ESIElement::ESIElementType_t
917 ESIElement::IdentifyElement (const char *el
)
923 return ESI_ELEMENT_NONE
;
925 if (!strncmp (el
, "esi:", 4))
927 else if (!strncmp (el
, "http://www.edge-delivery.org/esi/1.0|", 37))
930 return ESI_ELEMENT_NONE
;
932 if (!strncmp (el
+ offset
, "otherwise", 9))
933 return ESI_ELEMENT_OTHERWISE
;
935 if (!strncmp (el
+ offset
, "comment", 7))
936 return ESI_ELEMENT_COMMENT
;
938 if (!strncmp (el
+ offset
, "include", 7))
939 return ESI_ELEMENT_INCLUDE
;
941 if (!strncmp (el
+ offset
, "attempt", 7))
942 return ESI_ELEMENT_ATTEMPT
;
944 if (!strncmp (el
+ offset
, "assign", 6))
945 return ESI_ELEMENT_ASSIGN
;
947 if (!strncmp (el
+ offset
, "remove", 6))
948 return ESI_ELEMENT_REMOVE
;
950 if (!strncmp (el
+ offset
, "except", 6))
951 return ESI_ELEMENT_EXCEPT
;
953 if (!strncmp (el
+ offset
, "choose", 6))
954 return ESI_ELEMENT_CHOOSE
;
956 if (!strncmp (el
+ offset
, "vars", 4))
957 return ESI_ELEMENT_VARS
;
959 if (!strncmp (el
+ offset
, "when", 4))
960 return ESI_ELEMENT_WHEN
;
962 if (!strncmp (el
+ offset
, "try", 3))
963 return ESI_ELEMENT_TRY
;
965 return ESI_ELEMENT_NONE
;
969 ESIContext::ParserState::top()
971 return stack
[stackdepth
-1];
974 ESIContext::ParserState::ParserState() : inited_ (false)
978 ESIContext::ParserState::inited() const
984 ESIContext::addStackElement (ESIElement::Pointer element
)
986 /* Put on the stack to allow skipping of 'invalid' markup */
987 assert (parserState
.stackdepth
<11);
989 debugs(86, 5, "ESIContext::addStackElement: About to add ESI Node " << element
.getRaw());
991 if (!parserState
.top()->addElement(element
)) {
992 debugs(86, 1, "ESIContext::addStackElement: failed to add esi node, probable error in ESI template");
995 /* added ok, push onto the stack */
996 parserState
.stack
[parserState
.stackdepth
++] = element
;
1001 ESIContext::start(const char *el
, const char **attr
, size_t attrCount
)
1004 unsigned int ellen
= strlen (el
);
1005 char localbuf
[HTTP_REQBUF_SZ
];
1006 ESIElement::Pointer element
;
1007 int specifiedattcount
= attrCount
* 2;
1009 assert (ellen
< sizeof (localbuf
)); /* prevent unexpected overruns. */
1011 debugs(86, 5, "ESIContext::Start: element '" << el
<< "' with " << specifiedattcount
<< " tags");
1014 /* waiting for expat to finish the buffer we gave it */
1017 switch (ESIElement::IdentifyElement (el
)) {
1019 case ESIElement::ESI_ELEMENT_NONE
:
1020 /* Spit out elements we aren't interested in */
1023 assert (xstrncpy (&localbuf
[1], el
, sizeof(localbuf
) - 2));
1024 position
= localbuf
+ strlen (localbuf
);
1026 for (i
= 0; i
< specifiedattcount
&& attr
[i
]; i
+= 2) {
1028 /* TODO: handle thisNode gracefully */
1029 assert (xstrncpy (position
, attr
[i
], sizeof(localbuf
) + (position
- localbuf
)));
1030 position
+= strlen (position
);
1033 const char *chPtr
= attr
[i
+ 1];
1035 while ((ch
= *chPtr
++) != '\0') {
1037 assert( xstrncpy(position
, """, sizeof(localbuf
) + (position
-localbuf
)) );
1044 position
+= strlen (position
);
1052 addLiteral (localbuf
, position
- localbuf
);
1053 debugs(86, 5, "esi stack depth " << parserState
.stackdepth
);
1057 case ESIElement::ESI_ELEMENT_COMMENT
:
1058 /* Put on the stack to allow skipping of 'invalid' markup */
1059 element
= new esiComment ();
1062 case ESIElement::ESI_ELEMENT_INCLUDE
:
1063 /* Put on the stack to allow skipping of 'invalid' markup */
1064 element
= new ESIInclude (parserState
.top().getRaw(), specifiedattcount
, attr
, this);
1067 case ESIElement::ESI_ELEMENT_REMOVE
:
1068 /* Put on the stack to allow skipping of 'invalid' markup */
1069 element
= esiRemoveNew ();
1072 case ESIElement::ESI_ELEMENT_TRY
:
1073 /* Put on the stack to allow skipping of 'invalid' markup */
1074 element
= new esiTry (parserState
.top().getRaw());
1077 case ESIElement::ESI_ELEMENT_ATTEMPT
:
1078 /* Put on the stack to allow skipping of 'invalid' markup */
1079 element
= new esiAttempt (parserState
.top().getRaw());
1082 case ESIElement::ESI_ELEMENT_EXCEPT
:
1083 /* Put on the stack to allow skipping of 'invalid' markup */
1084 element
= new esiExcept (parserState
.top().getRaw());
1087 case ESIElement::ESI_ELEMENT_VARS
:
1088 /* Put on the stack to allow skipping of 'invalid' markup */
1089 element
= new ESIVar (parserState
.top().getRaw());
1092 case ESIElement::ESI_ELEMENT_CHOOSE
:
1093 /* Put on the stack to allow skipping of 'invalid' markup */
1094 element
= new esiChoose (parserState
.top().getRaw());
1097 case ESIElement::ESI_ELEMENT_WHEN
:
1098 /* Put on the stack to allow skipping of 'invalid' markup */
1099 element
= new esiWhen (parserState
.top().getRaw(), specifiedattcount
, attr
, varState
);
1102 case ESIElement::ESI_ELEMENT_OTHERWISE
:
1103 /* Put on the stack to allow skipping of 'invalid' markup */
1104 element
= new esiOtherwise (parserState
.top().getRaw());
1107 case ESIElement::ESI_ELEMENT_ASSIGN
:
1108 /* Put on the stack to allow skipping of 'invalid' markup */
1109 element
= new ESIAssign (parserState
.top().getRaw(), specifiedattcount
, attr
, this);
1113 addStackElement(element
);
1115 debugs(86, 5, "esi stack depth " << parserState
.stackdepth
);
1117 } /* End of start handler */
1120 ESIContext::end(const char *el
)
1122 unsigned int ellen
= strlen (el
);
1123 char localbuf
[HTTP_REQBUF_SZ
];
1127 /* waiting for expat to finish the buffer we gave it */
1130 switch (ESIElement::IdentifyElement (el
)) {
1132 case ESIElement::ESI_ELEMENT_NONE
:
1133 assert (ellen
< sizeof (localbuf
)); /* prevent unexpected overruns. */
1134 /* Add elements we aren't interested in */
1137 assert (xstrncpy (&localbuf
[2], el
, sizeof(localbuf
) - 3));
1138 position
= localbuf
+ strlen (localbuf
);
1141 addLiteral (localbuf
, position
- localbuf
);
1144 case ESIElement::ESI_ELEMENT_COMMENT
:
1146 case ESIElement::ESI_ELEMENT_INCLUDE
:
1148 case ESIElement::ESI_ELEMENT_REMOVE
:
1150 case ESIElement::ESI_ELEMENT_TRY
:
1152 case ESIElement::ESI_ELEMENT_ATTEMPT
:
1154 case ESIElement::ESI_ELEMENT_EXCEPT
:
1156 case ESIElement::ESI_ELEMENT_VARS
:
1158 case ESIElement::ESI_ELEMENT_CHOOSE
:
1160 case ESIElement::ESI_ELEMENT_WHEN
:
1162 case ESIElement::ESI_ELEMENT_OTHERWISE
:
1164 case ESIElement::ESI_ELEMENT_ASSIGN
:
1165 /* pop of the stack */
1166 parserState
.stack
[--parserState
.stackdepth
] = NULL
;
1169 } /* End of end handler */
1172 ESIContext::parserDefault (const char *s
, int len
)
1177 /* handle any skipped data */
1178 addLiteral (s
, len
);
1182 ESIContext::parserComment (const char *s
)
1187 if (!strncmp(s
, "esi",3)) {
1188 debugs(86, 5, "ESIContext::parserComment: ESI <!-- block encountered");
1189 ESIParser::Pointer tempParser
= ESIParser::NewParser (this);
1191 /* wrap the comment in some tags */
1193 if (!tempParser
->parse("<div>", 5,0) ||
1194 !tempParser
->parse(s
+ 3, strlen(s
) - 3, 0) ||
1195 !tempParser
->parse("</div>",6,1)) {
1196 debugs(86, 0, "ESIContext::parserComment: Parsing fragment '" << s
+ 3 << "' failed.");
1199 snprintf(tempstr
, 1023, "ESIContext::parserComment: Parse error at line %ld:\n%s\n",
1200 tempParser
->lineNumber(),
1201 tempParser
->errorString());
1202 debugs(86, 0, "" << tempstr
<< "");
1204 setErrorMessage(tempstr
);
1207 debugs(86, 5, "ESIContext::parserComment: ESI <!-- block parsed");
1210 char localbuf
[HTTP_REQBUF_SZ
];
1212 debugs(86, 5, "ESIContext::parserComment: Regenerating comment block");
1215 if (len
> sizeof (localbuf
) - 9) {
1216 debugs(86, 0, "ESIContext::parserComment: Truncating long comment");
1217 len
= sizeof (localbuf
) - 9;
1220 xstrncpy(localbuf
, "<!--", 5);
1221 xstrncpy(localbuf
+ 4, s
, len
+ 1);
1222 xstrncpy(localbuf
+ 4 + len
, "-->", 4);
1223 addLiteral (localbuf
,len
+ 7);
1228 ESIContext::addLiteral (const char *s
, int len
)
1230 /* handle any skipped data */
1232 debugs(86, 5, "literal length is " << len
);
1233 /* give a literal to the current element */
1234 assert (parserState
.stackdepth
<11);
1235 ESIElement::Pointer
element (new esiLiteral (this, s
, len
));
1237 if (!parserState
.top()->addElement(element
)) {
1238 debugs(86, 1, "ESIContext::addLiteral: failed to add esi node, probable error in ESI template");
1244 ESIContext::ParserState::init(ESIParserClient
*userData
)
1246 theParser
= ESIParser::NewParser (userData
);
1251 ESIContext::parseOneBuffer()
1253 assert (buffered
.getRaw());
1255 debugs (86,9,"ESIContext::parseOneBuffer: " << buffered
->len
<< " bytes");
1256 bool lastBlock
= buffered
->next
.getRaw() == NULL
&& flags
.finishedtemplate
? true : false;
1258 if (! parserState
.theParser
->parse(buffered
->buf
, buffered
->len
, lastBlock
)) {
1261 snprintf (tempstr
, 1023, "esiProcess: Parse error at line %ld:\n%s\n",
1262 parserState
.theParser
->lineNumber(),
1263 parserState
.theParser
->errorString());
1264 debugs(86, 0, "" << tempstr
<< "");
1266 setErrorMessage(tempstr
);
1268 assert (flags
.error
);
1278 ESISegment::Pointer temp
= buffered
;
1279 buffered
= temp
->next
;
1285 if (!parserState
.stackdepth
) {
1286 debugs(86, 5, "empty parser stack, inserting the top level node");
1287 assert (tree
.getRaw());
1288 parserState
.stack
[parserState
.stackdepth
++] = tree
;
1291 if (rep
&& !parserState
.inited())
1292 parserState
.init(this);
1295 if (buffered
.getRaw()) {
1296 parserState
.parsing
= 1;
1297 /* we don't keep any data around */
1299 PROF_start(esiParsing
);
1301 while (buffered
.getRaw() && !flags
.error
)
1304 PROF_stop(esiParsing
);
1306 /* Tel the read code to allocate a new buffer */
1309 parserState
.parsing
= 0;
1314 ESIContext::process ()
1317 * read through buffered, skipping plain text, and skipping any
1318 * <...> entry that is not an <esi: entry.
1319 * when it's found, hand an esiLiteral of the preceeding data to our current
1323 if (parserState
.parsing
) {
1324 /* in middle of parsing - finish here */
1325 return ESI_PROCESS_PENDING_MAYFAIL
;
1328 assert (flags
.finished
== 0);
1330 assert (!flags
.error
);
1332 if (!hasCachedAST())
1334 else if (!flags
.finishedtemplate
)
1338 debugs(86, 5, "ESIContext::process: Parsing failed");
1340 parserState
.popAll();
1341 return ESI_PROCESS_FAILED
;
1344 if (!flags
.finishedtemplate
&& !incoming
.getRaw() && !cachedASTInUse
) {
1345 buffered
= new ESISegment
;
1346 incoming
= buffered
;
1349 if (!flags
.finishedtemplate
&& !cachedASTInUse
) {
1350 return ESI_PROCESS_PENDING_MAYFAIL
;
1353 assert (flags
.finishedtemplate
|| cachedASTInUse
);
1355 /* ok, we've done all we can with the data. What can we process now?
1358 esiProcessResult_t status
;
1359 PROF_start(esiProcessing
);
1361 status
= tree
->process(0);
1366 case ESI_PROCESS_COMPLETE
:
1367 debugs(86, 5, "esiProcess: tree Processed OK");
1370 case ESI_PROCESS_PENDING_WONTFAIL
:
1371 debugs(86, 5, "esiProcess: tree Processed PENDING OK");
1374 case ESI_PROCESS_PENDING_MAYFAIL
:
1375 debugs(86, 5, "esiProcess: tree Processed PENDING UNKNOWN");
1378 case ESI_PROCESS_FAILED
:
1379 debugs(86, 0, "esiProcess: tree Processed FAILED");
1382 setErrorMessage("esiProcess: ESI template Processing failed.");
1384 PROF_stop(esiProcessing
);
1386 return ESI_PROCESS_FAILED
;
1391 if (status
!= ESI_PROCESS_PENDING_MAYFAIL
&& (flags
.finishedtemplate
|| cachedASTInUse
)) {
1392 /* We've read the entire template, and no nodes will
1395 debugs(86, 5, "esiProcess, request will succeed");
1399 if (status
== ESI_PROCESS_COMPLETE
1400 && (flags
.finishedtemplate
|| cachedASTInUse
)) {
1401 /* we've finished all processing. Render and send. */
1402 debugs(86, 5, "esiProcess, processing complete");
1406 PROF_stop(esiProcessing
);
1407 return status
; /* because we have no callbacks */
1412 ESIContext::ParserState::freeResources()
1419 ESIContext::ParserState::popAll()
1422 stack
[--stackdepth
] = NULL
;
1426 ESIContext::freeResources ()
1428 debugs(86, 5, HERE
<< "Freeing for this=" << this);
1434 if (parserState
.inited()) {
1435 parserState
.freeResources();
1438 parserState
.popAll();
1439 ESISegmentFreeList (buffered
);
1440 ESISegmentFreeList (outbound
);
1441 ESISegmentFreeList (outboundtail
);
1444 /* don't touch incoming, it's a pointer into buffered anyway */
1447 extern ErrorState
*clientBuildError (err_type
, http_status
, char const *, Ip::Address
&, HttpRequest
*);
1450 /* This can ONLY be used before we have sent *any* data to the client */
1454 debugs(86, 5, "ESIContext::fail: this=" << this);
1455 /* check preconditions */
1457 /* cleanup current state */
1459 /* Stop altering thisNode request */
1462 /* don't honour range requests - for errors we send it all */
1464 /* create an error object */
1465 // XXX: with the in-direction on remote IP. does the http->getConn()->clientConnection exist?
1466 ErrorState
* err
= clientBuildError(errorpage
, errorstatus
, NULL
, http
->getConn()->clientConnection
->remote
, http
->request
);
1467 err
->err_msg
= errormessage
;
1468 errormessage
= NULL
;
1469 rep
= err
->BuildHttpReply();
1470 assert (rep
->body
.hasContent());
1471 size_t errorprogress
= rep
->body
.contentSize();
1472 /* Tell esiSend where to start sending from */
1473 outbound_offset
= 0;
1474 /* copy the membuf from the reply to outbound */
1476 while (errorprogress
< (size_t)rep
->body
.contentSize()) {
1477 appendOutboundData(new ESISegment
);
1478 errorprogress
+= outboundtail
->append(rep
->body
.content() + errorprogress
, rep
->body
.contentSize() - errorprogress
);
1481 /* the esiCode now thinks that the error is the outbound,
1482 * and all processing has finished. */
1483 /* Send as much as we can */
1486 /* don't cancel anything. The stream nodes will clean up after
1487 * themselves when the reply is freed - and we don't know what to
1492 /* Implementation of ESIElements */
1495 esiComment::~esiComment()
1497 debugs(86, 5, "esiComment::~esiComment " << this);
1500 esiComment::esiComment()
1504 esiComment::finish()
1508 esiComment::render(ESISegment::Pointer output
)
1510 /* Comments do nothing dude */
1511 debugs(86, 5, "esiCommentRender: Rendering comment " << this << " into " << output
.getRaw());
1515 esiComment::makeCacheable() const
1517 debugs(86, 5, "esiComment::makeCacheable: returning NULL");
1522 esiComment::makeUsable(esiTreeParentPtr
, ESIVarState
&) const
1524 fatal ("esiComment::Usable: unreachable code!\n");
1529 esiLiteral::~esiLiteral()
1531 debugs(86, 5, "esiLiteral::~esiLiteral: " << this);
1532 ESISegmentFreeList (buffer
);
1533 cbdataReferenceDone (varState
);
1536 esiLiteral::esiLiteral(ESISegment::Pointer aSegment
)
1539 /* we've been handed a complete, processed string */
1546 esiLiteral::finish()
1549 /* precondition: the buffer chain has at least start + length bytes of data
1551 esiLiteral::esiLiteral(ESIContext
*context
, const char *s
, int numberOfCharacters
)
1554 buffer
= new ESISegment
;
1555 ESISegment::Pointer local
= buffer
;
1557 int remainingCharacters
= numberOfCharacters
;
1559 while (remainingCharacters
> 0) {
1560 if (local
->len
== sizeof (local
->buf
)) {
1561 local
->next
= new ESISegment
;
1565 size_t len
= local
->append (&s
[start
], remainingCharacters
);
1567 remainingCharacters
-= len
;
1570 varState
= cbdataReference (context
->varState
);
1574 esiLiteral::render (ESISegment::Pointer output
)
1576 debugs(86, 9, "esiLiteral::render: Rendering " << this);
1577 /* append the entire chain */
1578 assert (output
->next
.getRaw() == NULL
);
1579 output
->next
= buffer
;
1584 esiLiteral::process (int dovars
)
1587 return ESI_PROCESS_COMPLETE
;
1590 ESISegment::Pointer temp
= buffer
;
1591 /* Ensure variable state is clean */
1593 while (temp
.getRaw()) {
1594 varState
->feedData(temp
->buf
,temp
->len
);
1598 /* free the pre-processed content */
1599 ESISegmentFreeList (buffer
);
1601 buffer
= varState
->extractList ();
1605 return ESI_PROCESS_COMPLETE
;
1608 esiLiteral::esiLiteral(esiLiteral
const &old
) : buffer (old
.buffer
->cloneList()),
1615 esiLiteral::makeCacheable() const
1617 return new esiLiteral (*this);
1621 esiLiteral::makeUsable(esiTreeParentPtr
, ESIVarState
&newVarState
) const
1623 debugs(86, 5, "esiLiteral::makeUsable: Creating usable literal");
1624 esiLiteral
* result
= new esiLiteral (*this);
1625 result
->varState
= cbdataReference (&newVarState
);
1631 esiRemoveFree (void *data
)
1633 esiRemove
*thisNode
= (esiRemove
*)data
;
1634 debugs(86, 5, "esiRemoveFree " << thisNode
);
1638 esiRemove::operator new(size_t byteCount
)
1640 assert (byteCount
== sizeof (esiRemove
));
1642 CBDATA_INIT_TYPE_FREECB(esiRemove
, esiRemoveFree
);
1643 rv
= (void *)cbdataAlloc (esiRemove
);
1648 esiRemove::operator delete (void *address
)
1650 cbdataFree (address
);
1656 return new esiRemove
;
1659 esiRemove::esiRemove()
1667 esiRemove::render(ESISegment::Pointer output
)
1669 /* Removes do nothing dude */
1670 debugs(86, 5, "esiRemoveRender: Rendering remove " << this);
1673 /* Accept non-ESI children */
1675 esiRemove::addElement (ESIElement::Pointer element
)
1677 if (!dynamic_cast<esiLiteral
*>(element
.getRaw())) {
1678 debugs(86, 5, "esiRemoveAdd: Failed for " << this);
1686 esiRemove::makeCacheable() const
1688 debugs(86, 5, "esiRemove::makeCacheable: Returning NULL");
1693 esiRemove::makeUsable(esiTreeParentPtr
, ESIVarState
&) const
1695 fatal ("esiRemove::Usable: unreachable code!\n");
1702 debugs(86, 5, "esiTry::~esiTry " << this);
1705 esiTry::esiTry(esiTreeParentPtr aParent
) : parent (aParent
) , exceptbuffer(NULL
)
1709 esiTry::render (ESISegment::Pointer output
)
1711 /* Try renders from it's children */
1713 assert (attempt
.getRaw());
1714 assert (except
.getRaw());
1715 debugs(86, 5, "esiTryRender: Rendering Try " << this);
1717 if (flags
.attemptok
) {
1718 attempt
->render(output
);
1719 } else if (flags
.exceptok
) {
1722 if (exceptbuffer
.getRaw())
1723 ESISegment::ListTransfer(exceptbuffer
, output
);
1725 except
->render(output
);
1727 debugs(86, 5, "esiTryRender: Neither except nor attempt succeeded?!?");
1730 /* Accept attempt and except only */
1732 esiTry::addElement(ESIElement::Pointer element
)
1734 debugs(86, 5, "esiTryAdd: Try " << this << " adding element " <<
1737 if (dynamic_cast<esiLiteral
*>(element
.getRaw())) {
1738 /* Swallow whitespace */
1739 debugs(86, 5, "esiTryAdd: Try " << this << " skipping whitespace " << element
.getRaw());
1743 if (dynamic_cast<esiAttempt
*>(element
.getRaw())) {
1744 if (attempt
.getRaw()) {
1745 debugs(86, 1, "esiTryAdd: Failed for " << this << " - try allready has an attempt node (section 3.4)");
1753 if (dynamic_cast<esiExcept
*>(element
.getRaw())) {
1754 if (except
.getRaw()) {
1755 debugs(86, 1, "esiTryAdd: Failed for " << this << " - try already has an except node (section 3.4)");
1763 debugs(86, 1, "esiTryAdd: Failed to add element " << element
.getRaw() << " to try " << this << ", incorrect element type (see section 3.4)");
1768 esiTry::bestAttemptRV() const
1770 if (flags
.attemptfailed
)
1771 return ESI_PROCESS_COMPLETE
;
1773 return ESI_PROCESS_PENDING_MAYFAIL
;
1777 esiTry::process (int dovars
)
1779 esiProcessResult_t rv
= ESI_PROCESS_PENDING_MAYFAIL
;
1782 if (!attempt
.getRaw()) {
1783 debugs(86, 0, "esiTryProcess: Try has no attempt element - ESI template is invalid (section 3.4)");
1784 return ESI_PROCESS_FAILED
;
1787 if (!except
.getRaw()) {
1788 debugs(86, 0, "esiTryProcess: Try has no except element - ESI template is invalid (section 3.4)");
1789 return ESI_PROCESS_FAILED
;
1792 if (!flags
.attemptfailed
)
1793 /* Try the attempt branch */
1794 switch ((rv
= attempt
->process(dovars
))) {
1796 case ESI_PROCESS_COMPLETE
:
1797 debugs(86, 5, "esiTryProcess: attempt Processed OK");
1798 flags
.attemptok
= 1;
1799 return ESI_PROCESS_COMPLETE
;
1801 case ESI_PROCESS_PENDING_WONTFAIL
:
1802 debugs(86, 5, "esiTryProcess: attempt Processed PENDING OK");
1803 /* We're not done yet, but don't need to test except */
1804 return ESI_PROCESS_PENDING_WONTFAIL
;
1806 case ESI_PROCESS_PENDING_MAYFAIL
:
1807 debugs(86, 5, "eseSequenceProcess: element Processed PENDING UNKNOWN");
1810 case ESI_PROCESS_FAILED
:
1811 debugs(86, 5, "esiSequenceProcess: element Processed FAILED");
1812 flags
.attemptfailed
= 1;
1816 /* attempt is either MAYFAIL or FAILED */
1818 return bestAttemptRV();
1820 /* query except to see if it has a definite result */
1821 if (!flags
.exceptfailed
)
1822 /* Try the except branch */
1823 switch (except
->process(dovars
)) {
1825 case ESI_PROCESS_COMPLETE
:
1826 debugs(86, 5, "esiTryProcess: except Processed OK");
1828 return bestAttemptRV();
1830 case ESI_PROCESS_PENDING_WONTFAIL
:
1831 debugs(86, 5, "esiTryProcess: attempt Processed PENDING OK");
1832 /* We're not done yet, but can't fail */
1833 return ESI_PROCESS_PENDING_WONTFAIL
;
1835 case ESI_PROCESS_PENDING_MAYFAIL
:
1836 debugs(86, 5, "eseSequenceProcess: element Processed PENDING UNKNOWN");
1837 /* The except branch fail fail */
1838 return ESI_PROCESS_PENDING_MAYFAIL
;
1840 case ESI_PROCESS_FAILED
:
1841 debugs(86, 5, "esiSequenceProcess: element Processed FAILED");
1842 flags
.exceptfailed
= 1;
1846 if (flags
.exceptfailed
&& flags
.attemptfailed
)
1847 return ESI_PROCESS_FAILED
;
1849 /* one of attempt or except returned PENDING MAYFAIL */
1850 return ESI_PROCESS_PENDING_MAYFAIL
;
1854 esiTry::notifyParent()
1856 if (flags
.attemptfailed
) {
1857 if (flags
.exceptok
) {
1858 parent
->provideData (exceptbuffer
, this);
1859 exceptbuffer
= NULL
;
1860 } else if (flags
.exceptfailed
|| except
.getRaw() == NULL
) {
1861 parent
->fail (this, "esi:try - except claused failed, or no except clause found");
1865 /* nothing to do when except fails and attempt hasn't */
1869 esiTry::fail(ESIElement
*source
, char const *anError
)
1872 assert (source
== attempt
|| source
== except
);
1873 debugs(86, 5, "esiTry::fail: this=" << this << ", source=" << source
<< ", message=" << anError
);
1875 if (source
== except
) {
1876 flags
.exceptfailed
= 1;
1878 flags
.attemptfailed
= 1;
1885 esiTry::provideData (ESISegment::Pointer data
, ESIElement
* source
)
1887 if (source
== attempt
) {
1888 flags
.attemptok
= 1;
1889 parent
->provideData (data
, this);
1890 } else if (source
== except
) {
1892 assert (exceptbuffer
== NULL
);
1893 ESISegment::ListTransfer (data
, exceptbuffer
);
1898 esiTry::esiTry(esiTry
const &old
)
1902 flags
.attemptok
= 0;
1904 flags
.attemptfailed
= 0;
1905 flags
.exceptfailed
= 0;
1907 exceptbuffer
= NULL
;
1911 esiTry::makeCacheable() const
1913 debugs(86, 5, "esiTry::makeCacheable: making cachable Try from " << this);
1914 esiTry
*resultT
= new esiTry (*this);
1915 ESIElement::Pointer result
= resultT
;
1917 if (attempt
.getRaw())
1918 resultT
->attempt
= attempt
->makeCacheable();
1920 if (except
.getRaw())
1921 resultT
->except
= except
->makeCacheable();
1927 esiTry::makeUsable(esiTreeParentPtr newParent
, ESIVarState
&newVarState
) const
1929 debugs(86, 5, "esiTry::makeUsable: making usable Try from " << this);
1930 esiTry
*resultT
= new esiTry (*this);
1931 ESIElement::Pointer result
= resultT
;
1933 resultT
->parent
= newParent
;
1935 if (attempt
.getRaw())
1936 resultT
->attempt
= attempt
->makeUsable(resultT
, newVarState
);
1938 if (except
.getRaw())
1939 resultT
->except
= except
->makeUsable(resultT
, newVarState
);
1949 if (attempt
.getRaw())
1954 if (except
.getRaw())
1963 esiAttempt::operator new(size_t byteCount
)
1965 assert (byteCount
== sizeof (esiAttempt
));
1970 esiAttempt::operator delete (void *address
)
1972 cbdataFree (address
);
1980 esiExcept::operator new(size_t byteCount
)
1982 assert (byteCount
== sizeof (esiExcept
));
1984 CBDATA_INIT_TYPE_FREECB(esiExcept
, esiSequence::Free
);
1985 rv
= (void *)cbdataAlloc (esiExcept
);
1990 esiExcept::operator delete (void *address
)
1992 cbdataFree (address
);
2000 esiVar::operator new(size_t byteCount
)
2002 assert (byteCount
== sizeof (esiVar
));
2004 CBDATA_INIT_TYPE_FREECB(esiVar
, esiSequence::Free
);
2005 rv
= (void *)cbdataAlloc (esiVar
);
2010 esiVar::operator delete (void *address
)
2012 cbdataFree (address
);
2018 esiChoose::~esiChoose()
2020 debugs(86, 5, "esiChoose::~esiChoose " << this);
2023 esiChoose::esiChoose(esiTreeParentPtr aParent
) : elements (), chosenelement (-1),parent (aParent
)
2027 esiChoose::render(ESISegment::Pointer output
)
2029 /* append all processed elements, and trim processed and rendered elements */
2030 assert (output
->next
== NULL
);
2031 assert (elements
.size() || otherwise
.getRaw());
2032 debugs(86, 5, "esiChooseRender: rendering");
2034 if (chosenelement
>= 0)
2035 elements
[chosenelement
]->render(output
);
2036 else if (otherwise
.getRaw())
2037 otherwise
->render(output
);
2041 esiChoose::addElement(ESIElement::Pointer element
)
2043 /* add an element to the output list */
2045 if (dynamic_cast<esiLiteral
*>(element
.getRaw())) {
2046 /* Swallow whitespace */
2047 debugs(86, 5, "esiChooseAdd: Choose " << this << " skipping whitespace " << element
.getRaw());
2051 /* Some elements require specific parents */
2052 if (!(dynamic_cast<esiWhen
*>(element
.getRaw()) || dynamic_cast<esiOtherwise
*>(element
.getRaw()))) {
2053 debugs(86, 0, "esiChooseAdd: invalid child node for esi:choose (section 3.3)");
2057 if (dynamic_cast<esiOtherwise
*>(element
.getRaw())) {
2058 if (otherwise
.getRaw()) {
2059 debugs(86, 0, "esiChooseAdd: only one otherwise node allowed for esi:choose (section 3.3)");
2063 otherwise
= element
;
2065 elements
.push_back (element
);
2067 debugs (86,3, "esiChooseAdd: Added a new element, elements = " << elements
.size());
2069 if (chosenelement
== -1)
2070 if ((dynamic_cast<esiWhen
*>(element
.getRaw()))->
2072 chosenelement
= elements
.size() - 1;
2073 debugs (86,3, "esiChooseAdd: Chose element " << elements
.size());
2081 esiChoose::selectElement()
2083 if (chosenelement
> -1)
2086 for (size_t counter
= 0; counter
< elements
.size(); ++counter
) {
2087 if ((dynamic_cast<esiWhen
*>(elements
[counter
].getRaw()))->
2089 chosenelement
= counter
;
2090 debugs (86,3, "esiChooseAdd: Chose element " << counter
+ 1);
2099 elements
.setNULL(0, elements
.size());
2101 if (otherwise
.getRaw())
2102 otherwise
->finish();
2110 ElementList::setNULL (int start
, int end
)
2112 assert (start
>= 0 && start
<= elementcount
);
2113 assert (end
>= 0 && end
<= elementcount
);
2115 for (int loopPosition
= start
; loopPosition
< end
; ++loopPosition
) {
2116 if (elements
[loopPosition
].getRaw())
2117 elements
[loopPosition
]->finish();
2119 debugs(86, 5, "esiSequence::NULLElements: Setting index " <<
2120 loopPosition
<< ", pointer " <<
2121 elements
[loopPosition
].getRaw() << " to NULL");
2123 elements
[loopPosition
] = NULL
;
2128 esiChoose::NULLUnChosen()
2130 if (chosenelement
>= 0) {
2131 if (otherwise
.getRaw())
2132 otherwise
->finish();
2136 elements
.setNULL (0, chosenelement
);
2138 elements
.setNULL (chosenelement
+ 1, elements
.size());
2139 } else if (otherwise
.getRaw()) {
2140 elements
.setNULL (0, elements
.size());
2145 esiChoose::process (int dovars
)
2147 /* process as much of the list as we can, stopping only on
2150 /* We MUST have a when clause */
2153 if (!elements
.size()) {
2156 if (otherwise
.getRaw())
2157 otherwise
->finish();
2163 return ESI_PROCESS_FAILED
;
2166 if (chosenelement
>= 0) {
2167 return elements
[chosenelement
]->process(dovars
);
2168 } else if (otherwise
.getRaw())
2169 return otherwise
->process(dovars
);
2171 return ESI_PROCESS_COMPLETE
;
2175 esiChoose::checkValidSource (ESIElement::Pointer source
) const
2177 if (!elements
.size())
2178 fatal ("invalid callback = no when clause\n");
2180 if (chosenelement
>= 0)
2181 assert (source
== elements
[chosenelement
]);
2182 else if (otherwise
.getRaw())
2183 assert (source
== otherwise
);
2185 fatal ("esiChoose::checkValidSource: invalid callback - no elements chosen\n");
2189 esiChoose::fail(ESIElement
* source
, char const *anError
)
2191 checkValidSource (source
);
2192 elements
.setNULL (0, elements
.size());
2194 if (otherwise
.getRaw())
2195 otherwise
->finish();
2199 parent
->fail(this, anError
);
2205 esiChoose::provideData (ESISegment::Pointer data
, ESIElement
*source
)
2207 checkValidSource (source
);
2208 parent
->provideData (data
, this);
2212 esiChoose::esiChoose(esiChoose
const &old
) : chosenelement(-1), otherwise (NULL
), parent (NULL
)
2214 for (size_t counter
= 0; counter
< old
.elements
.size(); ++counter
) {
2215 ESIElement::Pointer newElement
= old
.elements
[counter
]->makeCacheable();
2217 if (newElement
.getRaw())
2218 assert (addElement(newElement
));
2223 esiChoose::makeCachableElements(esiChoose
const &old
)
2225 for (size_t counter
= 0; counter
< old
.elements
.size(); ++counter
) {
2226 ESIElement::Pointer newElement
= old
.elements
[counter
]->makeCacheable();
2228 if (newElement
.getRaw())
2229 assert (addElement(newElement
));
2234 esiChoose::makeUsableElements(esiChoose
const &old
, ESIVarState
&newVarState
)
2236 for (size_t counter
= 0; counter
< old
.elements
.size(); ++counter
) {
2237 ESIElement::Pointer newElement
= old
.elements
[counter
]->makeUsable (this, newVarState
);
2239 if (newElement
.getRaw())
2240 assert (addElement(newElement
));
2245 esiChoose::makeCacheable() const
2247 esiChoose
*resultC
= new esiChoose (*this);
2248 ESIElement::Pointer result
= resultC
;
2249 resultC
->makeCachableElements(*this);
2251 if (otherwise
.getRaw())
2252 resultC
->otherwise
= otherwise
->makeCacheable();
2258 esiChoose::makeUsable(esiTreeParentPtr newParent
, ESIVarState
&newVarState
) const
2260 esiChoose
*resultC
= new esiChoose (*this);
2261 ESIElement::Pointer result
= resultC
;
2262 resultC
->parent
= newParent
;
2263 resultC
->makeUsableElements(*this, newVarState
);
2264 resultC
->selectElement();
2266 if (otherwise
.getRaw())
2267 resultC
->otherwise
= otherwise
->makeUsable(resultC
, newVarState
);
2273 ElementList::ElementList () : elements(NULL
), allocedcount(0), allocedsize(0), elementcount (0)
2276 ElementList::~ElementList()
2278 debugs(86, 5, "ElementList::~ElementList " << this);
2279 setNULL(0, elementcount
);
2282 memFreeBuf (allocedsize
, elements
);
2285 ESIElement::Pointer
&
2286 ElementList::operator [] (int index
)
2288 return elements
[index
];
2291 ESIElement::Pointer
const &
2292 ElementList::operator [] (int index
) const
2294 return elements
[index
];
2298 ElementList::pop_front (size_t const count
)
2303 memmove(elements
, &elements
[count
], (elementcount
- count
) * sizeof (ESIElement::Pointer
));
2305 elementcount
-= count
;
2309 ElementList::push_back(ESIElement::Pointer
&newElement
)
2311 elements
= (ESIElement::Pointer
*)memReallocBuf (elements
, ++elementcount
* sizeof (ESIElement::Pointer
),
2314 allocedcount
= elementcount
;
2315 memset(&elements
[elementcount
- 1], '\0', sizeof (ESIElement::Pointer
));
2316 elements
[elementcount
- 1] = newElement
;
2320 ElementList::size() const
2322 return elementcount
;
2326 esiWhen::esiWhen (esiTreeParentPtr aParent
, int attrcount
, const char **attr
,ESIVarState
*aVar
) : esiSequence (aParent
)
2329 char const *expression
= NULL
;
2331 for (int loopCounter
= 0; loopCounter
< attrcount
&& attr
[loopCounter
]; loopCounter
+= 2) {
2332 if (!strcmp(attr
[loopCounter
],"test")) {
2334 debugs(86, 5, "esiWhen::esiWhen: Evaluating '" << attr
[loopCounter
+1] << "'");
2335 /* TODO: warn the user instead of asserting */
2336 assert (expression
== NULL
);
2337 expression
= attr
[loopCounter
+1];
2339 /* ignore mistyped attributes.
2340 * TODO:? error on these for user feedback - config parameter needed
2342 debugs(86, 1, "Found misttyped attribute on ESI When clause");
2346 /* No expression ? default is not matching */
2350 unevaluatedExpression
= xstrdup(expression
);
2352 varState
= cbdataReference (aVar
);
2359 safe_free (unevaluatedExpression
);
2362 cbdataReferenceDone (varState
);
2368 if (!unevaluatedExpression
)
2373 varState
->feedData(unevaluatedExpression
, strlen (unevaluatedExpression
));
2375 char const *expression
= varState
->extractChar ();
2377 setTestResult(ESIExpression::Evaluate (expression
));
2379 safe_free (expression
);
2382 esiWhen::esiWhen(esiWhen
const &old
) : esiSequence (old
)
2384 unevaluatedExpression
= NULL
;
2386 if (old
.unevaluatedExpression
)
2387 unevaluatedExpression
= xstrdup(old
.unevaluatedExpression
);
2393 esiWhen::makeCacheable() const
2395 return new esiWhen(*this);
2399 esiWhen::makeUsable(esiTreeParentPtr newParent
, ESIVarState
&newVarState
) const
2401 esiWhen
*resultW
= new esiWhen (*this);
2402 ESIElement::Pointer result
= resultW
;
2403 resultW
->parent
= newParent
;
2404 resultW
->makeUsableElements(*this, newVarState
);
2405 resultW
->varState
= cbdataReference (&newVarState
);
2406 resultW
->evaluate();
2413 esiOtherwise::operator new(size_t byteCount
)
2415 assert (byteCount
== sizeof (esiOtherwise
));
2417 CBDATA_INIT_TYPE_FREECB(esiOtherwise
, esiSequence::Free
);
2418 rv
= (void *)cbdataAlloc (esiOtherwise
);
2423 esiOtherwise::operator delete (void *address
)
2425 cbdataFree (address
);
2430 /* TODO: implement surrogate targeting and control processing */
2432 esiEnableProcessing (HttpReply
*rep
)
2436 if (rep
->surrogate_control
) {
2437 HttpHdrScTarget
*sctusable
=
2438 rep
->surrogate_control
->getMergedTarget(Config
.Accel
.surrogate_id
);
2440 if (!sctusable
|| !sctusable
->hasContent())
2441 /* Nothing generic or targeted at us, or no
2442 * content processing requested
2446 if (sctusable
->content().pos("ESI/1.0") != NULL
)
2455 #endif /* USE_SQUID_ESI == 1 */