2 * Copyright (C) 1996-2017 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 ICAP (RFC 3507) Client */
12 #include "adaptation/Answer.h"
13 #include "adaptation/icap/Config.h"
14 #include "adaptation/icap/ModXact.h"
15 #include "adaptation/icap/Options.h"
16 #include "adaptation/icap/OptXact.h"
17 #include "adaptation/icap/ServiceRep.h"
18 #include "base/TextException.h"
19 #include "comm/Connection.h"
20 #include "ConfigParser.h"
24 #include "HttpReply.h"
26 #include "SquidConfig.h"
27 #include "SquidTime.h"
29 #define DEFAULT_ICAP_PORT 1344
30 #define DEFAULT_ICAPS_PORT 11344
32 CBDATA_NAMESPACED_CLASS_INIT(Adaptation::Icap
, ServiceRep
);
34 Adaptation::Icap::ServiceRep::ServiceRep(const ServiceConfigPointer
&svcCfg
):
35 AsyncJob("Adaptation::Icap::ServiceRep"), Adaptation::Service(svcCfg
),
36 theOptions(NULL
), theOptionsFetcher(0), theLastUpdate(0),
39 connOverloadReported(false),
41 isSuspended(0), notifying(false),
42 updateScheduled(false),
43 wasAnnouncedUp(true), // do not announce an "up" service at startup
47 theIdleConns
= new IdleConnList("ICAP Service", NULL
);
50 Adaptation::Icap::ServiceRep::~ServiceRep()
53 Must(!theOptionsFetcher
);
58 Adaptation::Icap::ServiceRep::finalize()
60 Adaptation::Service::finalize();
62 // use /etc/services or default port if needed
63 const bool have_port
= cfg().port
>= 0;
66 if (cfg().protocol
.caseCmp("icaps") == 0)
67 serv
= getservbyname("icaps", "tcp");
69 serv
= getservbyname("icap", "tcp");
72 writeableCfg().port
= htons(serv
->s_port
);
74 writeableCfg().port
= cfg().protocol
.caseCmp("icaps") == 0 ? DEFAULT_ICAPS_PORT
: DEFAULT_ICAP_PORT
;
78 if (cfg().protocol
.caseCmp("icaps") == 0)
79 writeableCfg().secure
.encryptTransport
= true;
81 if (cfg().secure
.encryptTransport
) {
82 debugs(3, DBG_IMPORTANT
, "Initializing service " << cfg().resource
<< " SSL context");
83 sslContext
= writeableCfg().secure
.createClientContext(true);
86 if (!cfg().connectionEncryption
.configured())
87 writeableCfg().connectionEncryption
.defaultTo(cfg().secure
.encryptTransport
);
89 theSessionFailures
.configure(TheConfig
.oldest_service_failure
> 0 ?
90 TheConfig
.oldest_service_failure
: -1);
93 void Adaptation::Icap::ServiceRep::noteFailure()
95 const int failures
= theSessionFailures
.count(1);
96 debugs(93,4, HERE
<< " failure " << failures
<< " out of " <<
97 TheConfig
.service_failure_limit
<< " allowed in " <<
98 TheConfig
.oldest_service_failure
<< "sec " << status());
103 if (TheConfig
.service_failure_limit
>= 0 &&
104 failures
> TheConfig
.service_failure_limit
)
105 suspend("too many failures");
107 // TODO: Should bypass setting affect how much Squid tries to talk to
108 // the ICAP service that is currently unusable and is likely to remain
109 // so for some time? The current code says "no". Perhaps the answer
110 // should be configurable.
113 // returns a persistent or brand new connection; negative int on failures
114 Comm::ConnectionPointer
115 Adaptation::Icap::ServiceRep::getConnection(bool retriableXact
, bool &reused
)
117 Comm::ConnectionPointer connection
;
119 /* 2011-06-17: rousskov:
120 * There are two things that happen at the same time in pop(). Both are important.
121 * 1) Ensure that we can use a pconn for this transaction.
122 * 2) Ensure that the number of idle pconns does not grow without bounds.
124 * Both happen in the beginning of the transaction. Both are dictated by real-world problems.
125 * retriable means you can repeat the request if you suspect the first try failed due to a pconn race.
126 * HTTP and ICAP rules prohibit the use of pconns for non-retriable requests.
128 * If there are zero idle connections, (2) is irrelevant. (2) is only relevant when there are many
129 * idle connections and we should not open more connections without closing some idle ones,
130 * or instead of just opening a new connection and leaving idle connections as is.
131 * In other words, (2) tells us to close one FD for each new one we open due to retriable.
134 connection
= theIdleConns
->pop();
136 theIdleConns
->closeN(1);
138 reused
= Comm::IsConnOpen(connection
);
140 debugs(93,3, HERE
<< "got connection: " << connection
);
144 // pools connection if it is reusable or closes it
145 void Adaptation::Icap::ServiceRep::putConnection(const Comm::ConnectionPointer
&conn
, bool isReusable
, bool sendReset
, const char *comment
)
147 Must(Comm::IsConnOpen(conn
));
148 // do not pool an idle connection if we owe connections
149 if (isReusable
&& excessConnections() == 0) {
150 debugs(93, 3, HERE
<< "pushing pconn" << comment
);
151 commUnsetConnTimeout(conn
);
152 theIdleConns
->push(conn
);
154 debugs(93, 3, HERE
<< (sendReset
? "RST" : "FIN") << "-closing " <<
156 // comm_close called from Connection::close will clear timeout
157 // TODO: add "bool sendReset = false" to Connection::close()?
159 comm_reset_close(conn
);
164 Must(theBusyConns
> 0);
166 // a connection slot released. Check if there are waiters....
170 // a wrapper to avoid exposing theIdleConns
171 void Adaptation::Icap::ServiceRep::noteConnectionUse(const Comm::ConnectionPointer
&conn
)
173 Must(Comm::IsConnOpen(conn
));
174 fd_table
[conn
->fd
].noteUse(); // pconn re-use, albeit not via PconnPool API
177 void Adaptation::Icap::ServiceRep::noteConnectionFailed(const char *comment
)
179 debugs(93, 3, HERE
<< "Connection failed: " << comment
);
183 void Adaptation::Icap::ServiceRep::setMaxConnections()
185 if (cfg().maxConn
>= 0)
186 theMaxConnections
= cfg().maxConn
;
187 else if (theOptions
&& theOptions
->max_connections
>= 0)
188 theMaxConnections
= theOptions
->max_connections
;
190 theMaxConnections
= -1;
194 if (::Config
.workers
> 1 )
195 theMaxConnections
/= ::Config
.workers
;
198 int Adaptation::Icap::ServiceRep::availableConnections() const
200 if (theMaxConnections
< 0)
203 // we are available if we can open or reuse connections
204 // in other words, if we will not create debt
205 int available
= max(0, theMaxConnections
- theBusyConns
);
207 if (!available
&& !connOverloadReported
) {
208 debugs(93, DBG_IMPORTANT
, "WARNING: ICAP Max-Connections limit " <<
209 "exceeded for service " << cfg().uri
<< ". Open connections now: " <<
210 theBusyConns
+ theIdleConns
->count() << ", including " <<
211 theIdleConns
->count() << " idle persistent connections.");
212 connOverloadReported
= true;
215 if (cfg().onOverload
== srvForce
)
221 // The number of connections which excess the Max-Connections limit
222 int Adaptation::Icap::ServiceRep::excessConnections() const
224 if (theMaxConnections
< 0)
227 // Waiters affect the number of needed connections but a needed
228 // connection may still be excessive from Max-Connections p.o.v.
229 // so we should not account for waiting transaction needs here.
230 const int debt
= theBusyConns
+ theIdleConns
->count() - theMaxConnections
;
237 void Adaptation::Icap::ServiceRep::noteGoneWaiter()
241 // in case the notified transaction did not take the connection slot
245 // called when a connection slot may become available
246 void Adaptation::Icap::ServiceRep::busyCheckpoint()
248 if (theNotificationWaiters
.empty()) // nobody is waiting for a slot
252 int available
= availableConnections();
255 // It is possible to have waiters when no limit on connections exist in
256 // case of reconfigure or because new Options received.
257 // In this case, notify all waiting transactions.
258 freed
= theNotificationWaiters
.size();
260 // avoid notifying more waiters than there will be available slots
261 const int notifiedWaiters
= theAllWaiters
- theNotificationWaiters
.size();
262 freed
= available
- notifiedWaiters
;
265 debugs(93,7, HERE
<< "Available connections: " << available
<<
266 " freed slots: " << freed
<<
267 " waiting in queue: " << theNotificationWaiters
.size());
269 while (freed
> 0 && !theNotificationWaiters
.empty()) {
270 Client i
= theNotificationWaiters
.front();
271 theNotificationWaiters
.pop_front();
272 ScheduleCallHere(i
.callback
);
278 void Adaptation::Icap::ServiceRep::suspend(const char *reason
)
281 debugs(93,4, HERE
<< "keeping suspended, also for " << reason
);
283 isSuspended
= reason
;
284 debugs(93, DBG_IMPORTANT
, "suspending ICAP service for " << reason
);
285 scheduleUpdate(squid_curtime
+ TheConfig
.service_revival_delay
);
286 announceStatusChange("suspended", true);
290 bool Adaptation::Icap::ServiceRep::probed() const
292 return theLastUpdate
!= 0;
295 bool Adaptation::Icap::ServiceRep::hasOptions() const
297 return theOptions
&& theOptions
->valid() && theOptions
->fresh();
300 bool Adaptation::Icap::ServiceRep::up() const
302 return !isSuspended
&& hasOptions();
305 bool Adaptation::Icap::ServiceRep::availableForNew() const
308 int available
= availableConnections();
312 return (available
- theAllWaiters
> 0);
315 bool Adaptation::Icap::ServiceRep::availableForOld() const
319 int available
= availableConnections();
320 return (available
!= 0); // it is -1 (no limit) or has available slots
323 bool Adaptation::Icap::ServiceRep::wantsUrl(const SBuf
&urlPath
) const
326 return theOptions
->transferKind(urlPath
) != Adaptation::Icap::Options::xferIgnore
;
329 bool Adaptation::Icap::ServiceRep::wantsPreview(const SBuf
&urlPath
, size_t &wantedSize
) const
333 if (theOptions
->preview
< 0)
336 if (theOptions
->transferKind(urlPath
) != Adaptation::Icap::Options::xferPreview
)
339 wantedSize
= theOptions
->preview
;
344 bool Adaptation::Icap::ServiceRep::allows204() const
347 return true; // in the future, we may have ACLs to prevent 204s
350 bool Adaptation::Icap::ServiceRep::allows206() const
353 if (theOptions
->allow206
)
354 return true; // in the future, we may have ACLs to prevent 206s
359 void ServiceRep_noteTimeToUpdate(void *data
)
361 Adaptation::Icap::ServiceRep
*service
= static_cast<Adaptation::Icap::ServiceRep
*>(data
);
363 service
->noteTimeToUpdate();
366 void Adaptation::Icap::ServiceRep::noteTimeToUpdate()
369 updateScheduled
= false;
371 if (detached() || theOptionsFetcher
.set()) {
372 debugs(93,5, HERE
<< "ignores options update " << status());
376 debugs(93,5, HERE
<< "performs a regular options update " << status());
377 startGettingOptions();
382 void Adaptation::Icap::ServiceRep_noteTimeToNotify(void *data
)
384 Adaptation::Icap::ServiceRep
*service
= static_cast<Adaptation::Icap::ServiceRep
*>(data
);
386 service
->noteTimeToNotify();
390 void Adaptation::Icap::ServiceRep::noteTimeToNotify()
394 debugs(93,7, HERE
<< "notifies " << theClients
.size() << " clients " <<
397 // note: we must notify even if we are invalidated
401 while (!theClients
.empty()) {
402 Client i
= theClients
.back();
403 theClients
.pop_back();
404 ScheduleCallHere(i
.callback
);
411 void Adaptation::Icap::ServiceRep::callWhenAvailable(AsyncCall::Pointer
&cb
, bool priority
)
413 debugs(93,8, "ICAPServiceRep::callWhenAvailable");
416 Must(!theIdleConns
->count()); // or we should not be waiting
419 i
.service
= Pointer(this);
422 theNotificationWaiters
.push_front(i
);
424 theNotificationWaiters
.push_back(i
);
429 void Adaptation::Icap::ServiceRep::callWhenReady(AsyncCall::Pointer
&cb
)
433 debugs(93,5, HERE
<< "Adaptation::Icap::Service is asked to call " << *cb
<<
434 " when ready " << status());
436 Must(!broken()); // we do not wait for a broken service
439 i
.service
= Pointer(this); // TODO: is this really needed?
441 theClients
.push_back(i
);
443 if (theOptionsFetcher
.set() || notifying
)
444 return; // do nothing, we will be picked up in noteTimeToNotify()
446 if (needNewOptions())
447 startGettingOptions();
449 scheduleNotification();
452 void Adaptation::Icap::ServiceRep::scheduleNotification()
454 debugs(93,7, HERE
<< "will notify " << theClients
.size() << " clients");
455 CallJobHere(93, 5, this, Adaptation::Icap::ServiceRep
, noteTimeToNotify
);
458 bool Adaptation::Icap::ServiceRep::needNewOptions() const
460 return !detached() && !up();
463 void Adaptation::Icap::ServiceRep::changeOptions(Adaptation::Icap::Options
*newOptions
)
465 debugs(93,8, HERE
<< "changes options from " << theOptions
<< " to " <<
466 newOptions
<< ' ' << status());
469 theOptions
= newOptions
;
470 theSessionFailures
.clear();
472 theLastUpdate
= squid_curtime
;
475 announceStatusChange("down after an options fetch failure", true);
478 void Adaptation::Icap::ServiceRep::checkOptions()
480 if (theOptions
== NULL
)
483 if (!theOptions
->valid()) {
484 debugs(93, DBG_IMPORTANT
, "WARNING: Squid got an invalid ICAP OPTIONS response " <<
485 "from service " << cfg().uri
<< "; error: " << theOptions
->error
);
490 * Issue a warning if the ICAP server returned methods in the
491 * options response that don't match the method from squid.conf.
494 if (!theOptions
->methods
.empty()) {
495 bool method_found
= false;
497 std::vector
<ICAP::Method
>::iterator iter
= theOptions
->methods
.begin();
499 while (iter
!= theOptions
->methods
.end()) {
501 if (*iter
== cfg().method
) {
506 method_list
.append(ICAP::methodStr(*iter
));
507 method_list
.append(" ", 1);
512 debugs(93, DBG_IMPORTANT
, "WARNING: Squid is configured to use ICAP method " <<
514 " for service " << cfg().uri
<<
515 " but OPTIONS response declares the methods are " << method_list
);
520 * Check the ICAP server's date header for clock skew
522 const int skew
= (int)(theOptions
->timestamp() - squid_curtime
);
523 if (abs(skew
) > theOptions
->ttl()) {
524 // TODO: If skew is negative, the option will be considered down
525 // because of stale options. We should probably change this.
526 debugs(93, DBG_IMPORTANT
, "ICAP service's clock is skewed by " << skew
<<
527 " seconds: " << cfg().uri
);
531 void Adaptation::Icap::ServiceRep::announceStatusChange(const char *downPhrase
, bool important
) const
533 if (wasAnnouncedUp
== up()) // no significant changes to announce
536 const char *what
= cfg().bypass
? "optional" : "essential";
537 const char *state
= wasAnnouncedUp
? downPhrase
: "up";
538 const int level
= important
? 1 :2;
539 debugs(93,level
, what
<< " ICAP service is " << state
<< ": " <<
540 cfg().uri
<< ' ' << status());
542 wasAnnouncedUp
= !wasAnnouncedUp
;
545 // we are receiving ICAP OPTIONS response headers here or NULL on failures
546 void Adaptation::Icap::ServiceRep::noteAdaptationAnswer(const Answer
&answer
)
548 Must(initiated(theOptionsFetcher
));
549 clearAdaptation(theOptionsFetcher
);
551 if (answer
.kind
== Answer::akError
) {
552 debugs(93,3, HERE
<< "failed to fetch options " << status());
557 Must(answer
.kind
== Answer::akForward
); // no akBlock for OPTIONS requests
558 const HttpMsg
*msg
= answer
.message
.getRaw();
561 debugs(93,5, HERE
<< "is interpreting new options " << status());
563 Adaptation::Icap::Options
*newOptions
= NULL
;
564 if (const HttpReply
*r
= dynamic_cast<const HttpReply
*>(msg
)) {
565 newOptions
= new Adaptation::Icap::Options
;
566 newOptions
->configure(r
);
568 debugs(93, DBG_IMPORTANT
, "ICAP service got wrong options message " << status());
571 handleNewOptions(newOptions
);
574 // we (a) must keep trying to get OPTIONS and (b) are RefCounted so we
575 // must keep our job alive (XXX: until nobody needs us)
576 void Adaptation::Icap::ServiceRep::callException(const std::exception
&e
)
578 clearAdaptation(theOptionsFetcher
);
579 debugs(93,2, "ICAP probably failed to fetch options (" << e
.what() <<
584 void Adaptation::Icap::ServiceRep::handleNewOptions(Adaptation::Icap::Options
*newOptions
)
586 // new options may be NULL
587 changeOptions(newOptions
);
589 debugs(93,3, HERE
<< "got new options and is now " << status());
591 scheduleUpdate(optionsFetchTime());
593 // XXX: this whole feature bases on the false assumption a service only has one IP
595 const int excess
= excessConnections();
596 // if we owe connections and have idle pconns, close the latter
597 if (excess
&& theIdleConns
->count() > 0) {
598 const int n
= min(excess
, theIdleConns
->count());
599 debugs(93,5, HERE
<< "closing " << n
<< " pconns to relief debt");
600 theIdleConns
->closeN(n
);
603 scheduleNotification();
606 void Adaptation::Icap::ServiceRep::startGettingOptions()
608 Must(!theOptionsFetcher
);
609 debugs(93,6, HERE
<< "will get new options " << status());
611 // XXX: "this" here is "self"; works until refcounting API changes
612 theOptionsFetcher
= initiateAdaptation(
613 new Adaptation::Icap::OptXactLauncher(this));
614 // TODO: timeout in case Adaptation::Icap::OptXact never calls us back?
615 // Such a timeout should probably be a generic AsyncStart feature.
618 void Adaptation::Icap::ServiceRep::scheduleUpdate(time_t when
)
620 if (updateScheduled
) {
621 debugs(93,7, HERE
<< "reschedules update");
622 // XXX: check whether the event is there because AR saw
623 // an unreproducible eventDelete assertion on 2007/06/18
624 if (eventFind(&ServiceRep_noteTimeToUpdate
, this))
625 eventDelete(&ServiceRep_noteTimeToUpdate
, this);
627 debugs(93, DBG_IMPORTANT
, "XXX: ICAP service lost an update event.");
628 updateScheduled
= false;
631 debugs(93,7, HERE
<< "raw OPTIONS fetch at " << when
<< " or in " <<
632 (when
- squid_curtime
) << " sec");
633 debugs(93,9, HERE
<< "last fetched at " << theLastUpdate
<< " or " <<
634 (squid_curtime
- theLastUpdate
) << " sec ago");
636 /* adjust update time to prevent too-frequent updates */
638 if (when
< squid_curtime
)
639 when
= squid_curtime
;
641 // XXX: move hard-coded constants from here to Adaptation::Icap::TheConfig
642 const int minUpdateGap
= 30; // seconds
643 if (when
< theLastUpdate
+ minUpdateGap
)
644 when
= theLastUpdate
+ minUpdateGap
;
646 const int delay
= when
- squid_curtime
;
647 debugs(93,5, HERE
<< "will fetch OPTIONS in " << delay
<< " sec");
649 eventAdd("Adaptation::Icap::ServiceRep::noteTimeToUpdate",
650 &ServiceRep_noteTimeToUpdate
, this, delay
, 0, true);
651 updateScheduled
= true;
654 // returns absolute time when OPTIONS should be fetched
656 Adaptation::Icap::ServiceRep::optionsFetchTime() const
658 if (theOptions
&& theOptions
->valid()) {
659 const time_t expire
= theOptions
->expire();
660 debugs(93,7, HERE
<< "options expire on " << expire
<< " >= " << squid_curtime
);
662 // conservative estimate of how long the OPTIONS transaction will take
663 // XXX: move hard-coded constants from here to Adaptation::Icap::TheConfig
664 const int expectedWait
= 20; // seconds
666 // Unknown or invalid (too small) expiration times should not happen.
667 // Adaptation::Icap::Options should use the default TTL, and ICAP servers should not
668 // send invalid TTLs, but bugs and attacks happen.
669 if (expire
< expectedWait
)
670 return squid_curtime
;
672 return expire
- expectedWait
; // before the current options expire
675 // use revival delay as "expiration" time for a service w/o valid options
676 return squid_curtime
+ TheConfig
.service_revival_delay
;
679 Adaptation::Initiate
*
680 Adaptation::Icap::ServiceRep::makeXactLauncher(HttpMsg
*virgin
,
681 HttpRequest
*cause
, AccessLogEntry::Pointer
&alp
)
683 return new Adaptation::Icap::ModXactLauncher(virgin
, cause
, alp
, this);
686 // returns a temporary string depicting service status, for debugging
687 const char *Adaptation::Icap::ServiceRep::status() const
697 buf
.append("down", 4);
699 buf
.append(",susp", 5);
702 buf
.append(",!opt", 5);
703 else if (!theOptions
->valid())
704 buf
.append(",!valid", 7);
705 else if (!theOptions
->fresh())
706 buf
.append(",stale", 6);
710 buf
.append(",detached", 9);
712 if (theOptionsFetcher
.set())
713 buf
.append(",fetch", 6);
716 buf
.append(",notif", 6);
718 if (const int failures
= theSessionFailures
.remembered())
719 buf
.appendf(",fail%d", failures
);
724 return buf
.content();
727 void Adaptation::Icap::ServiceRep::detach()
729 debugs(93,3, HERE
<< "detaching ICAP service: " << cfg().uri
<<
734 bool Adaptation::Icap::ServiceRep::detached() const
739 Adaptation::Icap::ConnWaiterDialer::ConnWaiterDialer(const CbcPointer
<Adaptation::Icap::ModXact
> &xact
,
740 Adaptation::Icap::ConnWaiterDialer::Parent::Method aHandler
):
741 Parent(xact
, aHandler
)
743 theService
= &xact
->service();
744 theService
->noteNewWaiter();
747 Adaptation::Icap::ConnWaiterDialer::ConnWaiterDialer(const Adaptation::Icap::ConnWaiterDialer
&aConnWaiter
): Parent(aConnWaiter
)
749 theService
= aConnWaiter
.theService
;
750 theService
->noteNewWaiter();
753 Adaptation::Icap::ConnWaiterDialer::~ConnWaiterDialer()
755 theService
->noteGoneWaiter();