]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/adaptation/ecap/XactionRep.cc
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 93 eCAP Interface */
12 #include <libecap/common/area.h>
13 #include <libecap/common/delay.h>
14 #include <libecap/common/named_values.h>
15 #include <libecap/common/names.h>
16 #include <libecap/adapter/xaction.h>
17 #include "adaptation/Answer.h"
18 #include "adaptation/ecap/Config.h"
19 #include "adaptation/ecap/XactionRep.h"
20 #include "adaptation/Initiator.h"
21 #include "base/AsyncJobCalls.h"
22 #include "base/TextException.h"
23 #include "format/Format.h"
24 #include "HttpReply.h"
25 #include "HttpRequest.h"
26 #include "SquidTime.h"
28 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Ecap::XactionRep
, XactionRep
);
30 /// a libecap Visitor for converting adapter transaction options to HttpHeader
31 class OptionsExtractor
: public libecap::NamedValueVisitor
34 typedef libecap::Name Name
;
35 typedef libecap::Area Area
;
37 OptionsExtractor(HttpHeader
&aMeta
): meta(aMeta
) {}
39 // libecap::NamedValueVisitor API
40 virtual void visit(const Name
&name
, const Area
&value
) {
41 meta
.putExt(name
.image().c_str(), value
.toString().c_str());
44 HttpHeader
&meta
; ///< where to put extracted options
47 Adaptation::Ecap::XactionRep::XactionRep(
48 HttpMsg
*virginHeader
, HttpRequest
*virginCause
, AccessLogEntry::Pointer
&alp
,
49 const Adaptation::ServicePointer
&aService
):
50 AsyncJob("Adaptation::Ecap::XactionRep"),
51 Adaptation::Initiate("Adaptation::Ecap::XactionRep"),
53 theVirginRep(virginHeader
), theCauseRep(NULL
),
54 makingVb(opUndecided
), proxyingAb(opUndecided
),
56 vbProductionFinished(false),
57 abProductionFinished(false), abProductionAtEnd(false),
61 theCauseRep
= new MessageRep(virginCause
);
64 Adaptation::Ecap::XactionRep::~XactionRep()
72 Adaptation::Ecap::XactionRep::master(const AdapterXaction
&x
)
80 Adaptation::Ecap::XactionRep::service()
82 Must(theService
!= NULL
);
87 Adaptation::Ecap::XactionRep::option(const libecap::Name
&name
) const
89 if (name
== libecap::metaClientIp
)
90 return clientIpValue();
91 if (name
== libecap::metaUserName
)
92 return usernameValue();
93 if (Adaptation::Config::masterx_shared_name
&& name
== Adaptation::Config::masterx_shared_name
)
94 return masterxSharedValue(name
);
96 // TODO: metaServerIp, metaAuthenticatedUser, and metaAuthenticatedGroups
98 // If the name is unknown, metaValue returns an emtpy area
99 return metaValue(name
);
103 Adaptation::Ecap::XactionRep::visitEachOption(libecap::NamedValueVisitor
&visitor
) const
105 if (const libecap::Area value
= clientIpValue())
106 visitor
.visit(libecap::metaClientIp
, value
);
107 if (const libecap::Area value
= usernameValue())
108 visitor
.visit(libecap::metaUserName
, value
);
110 if (Adaptation::Config::masterx_shared_name
) {
111 const libecap::Name
name(Adaptation::Config::masterx_shared_name
);
112 if (const libecap::Area value
= masterxSharedValue(name
))
113 visitor
.visit(name
, value
);
116 visitEachMetaHeader(visitor
);
118 // TODO: metaServerIp, metaAuthenticatedUser, and metaAuthenticatedGroups
122 Adaptation::Ecap::XactionRep::clientIpValue() const
124 const HttpRequest
*request
= dynamic_cast<const HttpRequest
*>(theCauseRep
?
125 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
127 // TODO: move this logic into HttpRequest::clientIp(bool) and
128 // HttpRequest::clientIpString(bool) and reuse everywhere
129 if (TheConfig
.send_client_ip
&& request
) {
130 Ip::Address client_addr
;
131 #if FOLLOW_X_FORWARDED_FOR
132 if (TheConfig
.use_indirect_client
) {
133 client_addr
= request
->indirect_client_addr
;
136 client_addr
= request
->client_addr
;
137 if (!client_addr
.isAnyAddr() && !client_addr
.isNoAddr()) {
138 char ntoabuf
[MAX_IPSTRLEN
] = "";
139 client_addr
.toStr(ntoabuf
,MAX_IPSTRLEN
);
140 return libecap::Area::FromTempBuffer(ntoabuf
, strlen(ntoabuf
));
143 return libecap::Area();
147 Adaptation::Ecap::XactionRep::usernameValue() const
150 const HttpRequest
*request
= dynamic_cast<const HttpRequest
*>(theCauseRep
?
151 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
153 if (request
->auth_user_request
!= NULL
) {
154 if (char const *name
= request
->auth_user_request
->username())
155 return libecap::Area::FromTempBuffer(name
, strlen(name
));
156 else if (request
->extacl_user
.size() > 0)
157 return libecap::Area::FromTempBuffer(request
->extacl_user
.rawBuf(),
158 request
->extacl_user
.size());
161 return libecap::Area();
165 Adaptation::Ecap::XactionRep::masterxSharedValue(const libecap::Name
&name
) const
167 const HttpRequest
*request
= dynamic_cast<const HttpRequest
*>(theCauseRep
?
168 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
170 if (name
.known()) { // must check to avoid empty names matching unset cfg
171 Adaptation::History::Pointer ah
= request
->adaptHistory(false);
174 if (ah
->getXxRecord(name
, value
))
175 return libecap::Area::FromTempBuffer(value
.rawBuf(), value
.size());
178 return libecap::Area();
182 Adaptation::Ecap::XactionRep::metaValue(const libecap::Name
&name
) const
184 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(theCauseRep
?
185 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
187 HttpReply
*reply
= dynamic_cast<HttpReply
*>(theVirginRep
.raw().header
);
189 if (name
.known()) { // must check to avoid empty names matching unset cfg
190 typedef Notes::iterator ACAMLI
;
191 for (ACAMLI i
= Adaptation::Config::metaHeaders
.begin(); i
!= Adaptation::Config::metaHeaders
.end(); ++i
) {
192 if (name
== (*i
)->key
.termedBuf()) {
193 if (const char *value
= (*i
)->match(request
, reply
, al
))
194 return libecap::Area::FromTempString(value
);
196 return libecap::Area();
201 return libecap::Area();
205 Adaptation::Ecap::XactionRep::visitEachMetaHeader(libecap::NamedValueVisitor
&visitor
) const
207 HttpRequest
*request
= dynamic_cast<HttpRequest
*>(theCauseRep
?
208 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
210 HttpReply
*reply
= dynamic_cast<HttpReply
*>(theVirginRep
.raw().header
);
212 typedef Notes::iterator ACAMLI
;
213 for (ACAMLI i
= Adaptation::Config::metaHeaders
.begin(); i
!= Adaptation::Config::metaHeaders
.end(); ++i
) {
214 const char *v
= (*i
)->match(request
, reply
, al
);
216 const libecap::Name
name((*i
)->key
.termedBuf());
217 const libecap::Area value
= libecap::Area::FromTempString(v
);
218 visitor
.visit(name
, value
);
224 Adaptation::Ecap::XactionRep::start()
228 if (!theVirginRep
.raw().body_pipe
)
229 makingVb
= opNever
; // there is nothing to deliver
231 HttpRequest
*request
= dynamic_cast<HttpRequest
*> (theCauseRep
?
232 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
235 HttpReply
*reply
= dynamic_cast<HttpReply
*>(theVirginRep
.raw().header
);
237 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
239 // retrying=false because ecap never retries transactions
240 adaptHistoryId
= ah
->recordXactStart(service().cfg().key
, current_time
, false);
241 typedef Notes::iterator ACAMLI
;
242 for (ACAMLI i
= Adaptation::Config::metaHeaders
.begin(); i
!= Adaptation::Config::metaHeaders
.end(); ++i
) {
243 const char *v
= (*i
)->match(request
, reply
, al
);
245 if (ah
->metaHeaders
== NULL
)
246 ah
->metaHeaders
= new NotePairs();
247 if (!ah
->metaHeaders
->hasPair((*i
)->key
.termedBuf(), v
))
248 ah
->metaHeaders
->add((*i
)->key
.termedBuf(), v
);
257 Adaptation::Ecap::XactionRep::swanSong()
259 // clear body_pipes, if any
260 // this code does not maintain proxying* and canAccessVb states; should it?
262 if (theAnswerRep
!= NULL
) {
263 BodyPipe::Pointer body_pipe
= answer().body_pipe
;
264 if (body_pipe
!= NULL
) {
265 Must(body_pipe
->stillProducing(this));
266 stopProducingFor(body_pipe
, false);
270 BodyPipe::Pointer
&body_pipe
= theVirginRep
.raw().body_pipe
;
271 if (body_pipe
!= NULL
&& body_pipe
->stillConsuming(this))
272 stopConsumingFrom(body_pipe
);
276 const HttpRequest
*request
= dynamic_cast<const HttpRequest
*>(theCauseRep
?
277 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
279 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
280 if (ah
!= NULL
&& adaptHistoryId
>= 0)
281 ah
->recordXactFinish(adaptHistoryId
);
283 Adaptation::Initiate::swanSong();
287 Adaptation::Ecap::XactionRep::resume()
289 // go async to gain exception protection and done()-based job destruction
290 typedef NullaryMemFunT
<Adaptation::Ecap::XactionRep
> Dialer
;
291 AsyncCall::Pointer call
= asyncCall(93, 5, "Adaptation::Ecap::XactionRep::doResume",
292 Dialer(this, &Adaptation::Ecap::XactionRep::doResume
));
293 ScheduleCallHere(call
);
296 /// the guts of libecap::host::Xaction::resume() API implementation
297 /// which just goes async in Adaptation::Ecap::XactionRep::resume().
299 Adaptation::Ecap::XactionRep::doResume()
306 Adaptation::Ecap::XactionRep::virgin()
311 const libecap::Message
&
312 Adaptation::Ecap::XactionRep::cause()
314 Must(theCauseRep
!= NULL
);
319 Adaptation::Ecap::XactionRep::adapted()
321 Must(theAnswerRep
!= NULL
);
322 return *theAnswerRep
;
325 Adaptation::Message
&
326 Adaptation::Ecap::XactionRep::answer()
328 MessageRep
*rep
= dynamic_cast<MessageRep
*>(theAnswerRep
.get());
334 Adaptation::Ecap::XactionRep::terminateMaster()
337 AdapterXaction x
= theMaster
;
344 Adaptation::Ecap::XactionRep::doneAll() const
346 return makingVb
>= opComplete
&& proxyingAb
>= opComplete
&&
347 Adaptation::Initiate::doneAll();
350 // stops receiving virgin and enables auto-consumption, dropping any vb bytes
352 Adaptation::Ecap::XactionRep::sinkVb(const char *reason
)
354 debugs(93,4, HERE
<< "sink for " << reason
<< "; status:" << status());
356 // we reset raw().body_pipe when we are done, so use this one for checking
357 const BodyPipePointer
&permPipe
= theVirginRep
.raw().header
->body_pipe
;
358 if (permPipe
!= NULL
)
359 permPipe
->enableAutoConsumption();
364 // stops receiving virgin but preserves it for others to use
366 Adaptation::Ecap::XactionRep::preserveVb(const char *reason
)
368 debugs(93,4, HERE
<< "preserve for " << reason
<< "; status:" << status());
370 // we reset raw().body_pipe when we are done, so use this one for checking
371 const BodyPipePointer
&permPipe
= theVirginRep
.raw().header
->body_pipe
;
372 if (permPipe
!= NULL
) {
373 // if libecap consumed, we cannot preserve
374 Must(!permPipe
->consumedSize());
380 // disassociates us from vb; the last step of sinking or preserving vb
382 Adaptation::Ecap::XactionRep::forgetVb(const char *reason
)
384 debugs(93,9, HERE
<< "forget vb " << reason
<< "; status:" << status());
386 BodyPipePointer
&p
= theVirginRep
.raw().body_pipe
;
387 if (p
!= NULL
&& p
->stillConsuming(this))
388 stopConsumingFrom(p
);
390 if (makingVb
== opUndecided
)
392 else if (makingVb
== opOn
)
393 makingVb
= opComplete
;
397 Adaptation::Ecap::XactionRep::useVirgin()
399 debugs(93,3, HERE
<< status());
400 Must(proxyingAb
== opUndecided
);
401 proxyingAb
= opNever
;
403 preserveVb("useVirgin");
405 HttpMsg
*clone
= theVirginRep
.raw().header
->clone();
406 // check that clone() copies the pipe so that we do not have to
407 Must(!theVirginRep
.raw().header
->body_pipe
== !clone
->body_pipe
);
409 updateHistory(clone
);
410 sendAnswer(Answer::Forward(clone
));
415 Adaptation::Ecap::XactionRep::useAdapted(const libecap::shared_ptr
<libecap::Message
> &m
)
417 debugs(93,3, HERE
<< status());
420 Must(proxyingAb
== opUndecided
);
422 HttpMsg
*msg
= answer().header
;
423 if (!theAnswerRep
->body()) { // final, bodyless answer
424 proxyingAb
= opNever
;
426 sendAnswer(Answer::Forward(msg
));
427 } else { // got answer headers but need to handle body
429 Must(!msg
->body_pipe
); // only host can set body pipes
430 MessageRep
*rep
= dynamic_cast<MessageRep
*>(theAnswerRep
.get());
432 rep
->tieBody(this); // sets us as a producer
433 Must(msg
->body_pipe
!= NULL
); // check tieBody
436 sendAnswer(Answer::Forward(msg
));
438 debugs(93,4, HERE
<< "adapter will produce body" << status());
439 theMaster
->abMake(); // libecap will produce
444 Adaptation::Ecap::XactionRep::blockVirgin()
446 debugs(93,3, HERE
<< status());
447 Must(proxyingAb
== opUndecided
);
448 proxyingAb
= opNever
;
450 sinkVb("blockVirgin");
453 sendAnswer(Answer::Block(service().cfg().key
));
457 /// Called just before sendAnswer() to record adapter meta-information
458 /// which may affect answer processing and may be needed for logging.
460 Adaptation::Ecap::XactionRep::updateHistory(HttpMsg
*adapted
)
462 if (!theMaster
) // all updates rely on being able to query the adapter
465 const HttpRequest
*request
= dynamic_cast<const HttpRequest
*>(theCauseRep
?
466 theCauseRep
->raw().header
: theVirginRep
.raw().header
);
469 // TODO: move common ICAP/eCAP logic to Adaptation::Xaction or similar
470 // TODO: optimize Area-to-String conversion
472 // update the cross-transactional database if needed
473 if (const char *xxNameStr
= Adaptation::Config::masterx_shared_name
) {
474 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
476 libecap::Name
xxName(xxNameStr
); // TODO: optimize?
477 if (const libecap::Area val
= theMaster
->option(xxName
))
478 ah
->updateXxRecord(xxNameStr
, val
.toString().c_str());
482 // update the adaptation plan if needed
483 if (service().cfg().routing
) {
485 if (const libecap::Area services
= theMaster
->option(libecap::metaNextServices
)) {
486 Adaptation::History::Pointer ah
= request
->adaptHistory(true);
488 ah
->updateNextServices(services
.toString().c_str());
490 } // TODO: else warn (occasionally!) if we got libecap::metaNextServices
492 // Store received meta headers for adapt::<last_h logformat code use.
493 // If we already have stored headers from a previous adaptation transaction
494 // related to the same master transction, they will be replaced.
495 Adaptation::History::Pointer ah
= request
->adaptLogHistory();
497 HttpHeader
meta(hoReply
);
498 OptionsExtractor
extractor(meta
);
499 theMaster
->visitEachOption(extractor
);
500 ah
->recordMeta(&meta
);
503 // Add just-created history to the adapted/cloned request that lacks it.
504 if (HttpRequest
*adaptedReq
= dynamic_cast<HttpRequest
*>(adapted
))
505 adaptedReq
->adaptHistoryImport(*request
);
509 Adaptation::Ecap::XactionRep::vbDiscard()
511 Must(makingVb
== opUndecided
);
512 // if adapter does not need vb, we do not need to send it
514 Must(makingVb
== opNever
);
518 Adaptation::Ecap::XactionRep::vbMake()
520 Must(makingVb
== opUndecided
);
521 BodyPipePointer
&p
= theVirginRep
.raw().body_pipe
;
523 Must(p
->setConsumerIfNotLate(this)); // to deliver vb, we must receive vb
528 Adaptation::Ecap::XactionRep::vbStopMaking()
530 Must(makingVb
== opOn
);
531 // if adapter does not need vb, we do not need to receive it
532 sinkVb("vbStopMaking");
533 Must(makingVb
== opComplete
);
537 Adaptation::Ecap::XactionRep::vbMakeMore()
539 Must(makingVb
== opOn
); // cannot make more if done proxying
540 // we cannot guarantee more vb, but we can check that there is a chance
541 const BodyPipePointer
&p
= theVirginRep
.raw().body_pipe
;
542 Must(p
!= NULL
&& p
->stillConsuming(this)); // we are plugged in
543 Must(!p
->productionEnded() && p
->mayNeedMoreData()); // and may get more
547 Adaptation::Ecap::XactionRep::vbContent(libecap::size_type o
, libecap::size_type s
)
549 // We may not be makingVb yet. It should be OK, but see vbContentShift().
551 const BodyPipePointer
&p
= theVirginRep
.raw().body_pipe
;
554 // TODO: make MemBuf use size_t?
555 const size_t haveSize
= static_cast<size_t>(p
->buf().contentSize());
557 // convert to Squid types; XXX: check for overflow
558 const uint64_t offset
= static_cast<uint64_t>(o
);
559 Must(offset
<= haveSize
); // equal iff at the end of content
561 // nsize means no size limit: all content starting from offset
562 const size_t size
= s
== libecap::nsize
?
563 haveSize
- offset
: static_cast<size_t>(s
);
565 // XXX: optimize by making theBody a shared_ptr (see Area::FromTemp*() src)
566 return libecap::Area::FromTempBuffer(p
->buf().content() + offset
,
567 min(static_cast<size_t>(haveSize
- offset
), size
));
571 Adaptation::Ecap::XactionRep::vbContentShift(libecap::size_type n
)
573 // We may not be makingVb yet. It should be OK now, but if BodyPipe
574 // consume() requirements change, we would have to return empty vbContent
575 // until the adapter registers as a consumer
577 BodyPipePointer
&p
= theVirginRep
.raw().body_pipe
;
579 const size_t size
= static_cast<size_t>(n
); // XXX: check for overflow
580 const size_t haveSize
= static_cast<size_t>(p
->buf().contentSize()); // TODO: make MemBuf use size_t?
581 p
->consume(min(size
, haveSize
));
585 Adaptation::Ecap::XactionRep::noteAbContentDone(bool atEnd
)
587 Must(proxyingAb
== opOn
&& !abProductionFinished
);
588 abProductionFinished
= true;
589 abProductionAtEnd
= atEnd
; // store until ready to stop producing ourselves
590 debugs(93,5, HERE
<< "adapted body production ended");
595 Adaptation::Ecap::XactionRep::noteAbContentAvailable()
597 Must(proxyingAb
== opOn
&& !abProductionFinished
);
601 #if 0 /* XXX: implement */
603 Adaptation::Ecap::XactionRep::setAdaptedBodySize(const libecap::BodySize
&size
)
605 Must(answer().body_pipe
!= NULL
);
607 answer().body_pipe
->setBodySize(size
.value());
608 // else the piped body size is unknown by default
613 Adaptation::Ecap::XactionRep::adaptationDelayed(const libecap::Delay
&d
)
615 debugs(93,3, HERE
<< "adapter needs time: " <<
616 d
.state
<< '/' << d
.progress
);
621 Adaptation::Ecap::XactionRep::adaptationAborted()
623 tellQueryAborted(true); // should eCAP support retries?
624 mustStop("adaptationAborted");
628 Adaptation::Ecap::XactionRep::noteMoreBodySpaceAvailable(RefCount
<BodyPipe
> bp
)
630 Must(proxyingAb
== opOn
);
635 Adaptation::Ecap::XactionRep::noteBodyConsumerAborted(RefCount
<BodyPipe
> bp
)
637 Must(proxyingAb
== opOn
);
638 stopProducingFor(answer().body_pipe
, false);
640 theMaster
->abStopMaking();
641 proxyingAb
= opComplete
;
645 Adaptation::Ecap::XactionRep::noteMoreBodyDataAvailable(RefCount
<BodyPipe
> bp
)
647 Must(makingVb
== opOn
); // or we would not be registered as a consumer
649 theMaster
->noteVbContentAvailable();
653 Adaptation::Ecap::XactionRep::noteBodyProductionEnded(RefCount
<BodyPipe
> bp
)
655 Must(makingVb
== opOn
); // or we would not be registered as a consumer
657 theMaster
->noteVbContentDone(true);
658 vbProductionFinished
= true;
662 Adaptation::Ecap::XactionRep::noteBodyProducerAborted(RefCount
<BodyPipe
> bp
)
664 Must(makingVb
== opOn
); // or we would not be registered as a consumer
666 theMaster
->noteVbContentDone(false);
667 vbProductionFinished
= true;
671 Adaptation::Ecap::XactionRep::noteInitiatorAborted()
673 mustStop("initiator aborted");
676 // get content from the adapter and put it into the adapted pipe
678 Adaptation::Ecap::XactionRep::moveAbContent()
680 Must(proxyingAb
== opOn
);
681 const libecap::Area c
= theMaster
->abContent(0, libecap::nsize
);
682 debugs(93,5, HERE
<< "up to " << c
.size
<< " bytes");
683 if (c
.size
== 0 && abProductionFinished
) { // no ab now and in the future
684 stopProducingFor(answer().body_pipe
, abProductionAtEnd
);
685 proxyingAb
= opComplete
;
686 debugs(93,5, HERE
<< "last adapted body data retrieved");
687 } else if (c
.size
> 0) {
688 if (const size_t used
= answer().body_pipe
->putMoreData(c
.start
, c
.size
))
689 theMaster
->abContentShift(used
);
694 Adaptation::Ecap::XactionRep::status() const
702 buf
.Printf("M%d", static_cast<int>(makingVb
));
704 const BodyPipePointer
&vp
= theVirginRep
.raw().body_pipe
;
706 buf
.append(" !V", 3);
707 else if (vp
->stillConsuming(const_cast<XactionRep
*>(this)))
708 buf
.append(" Vc", 3);
710 buf
.append(" V?", 3);
712 if (vbProductionFinished
)
715 buf
.Printf(" A%d", static_cast<int>(proxyingAb
));
717 if (proxyingAb
== opOn
) {
718 MessageRep
*rep
= dynamic_cast<MessageRep
*>(theAnswerRep
.get());
720 const BodyPipePointer
&ap
= rep
->raw().body_pipe
;
722 buf
.append(" !A", 3);
723 else if (ap
->stillProducing(const_cast<XactionRep
*>(this)))
724 buf
.append(" Ap", 3);
726 buf
.append(" A?", 3);
729 buf
.Printf(" %s%u]", id
.Prefix
, id
.value
);
733 return buf
.content();