eb01515f6acfe182b2ed806b6bfb37b12bb4550a
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * XMLServiceProvider.cpp
19  *
20  * XML-based SP configuration and mgmt
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "AccessControl.h"
26 #include "Application.h"
27 #include "RequestMapper.h"
28 #include "ServiceProvider.h"
29 #include "SessionCache.h"
30 #include "SPConfig.h"
31 #include "SPRequest.h"
32 #include "handler/SessionInitiator.h"
33 #include "remoting/ListenerService.h"
34 #include "util/DOMPropertySet.h"
35 #include "util/SPConstants.h"
36
37 #if defined(XMLTOOLING_LOG4SHIB)
38 # include <log4shib/PropertyConfigurator.hh>
39 #elif defined(XMLTOOLING_LOG4CPP)
40 # include <log4cpp/PropertyConfigurator.hh>
41 #else
42 # error "Supported logging library not available."
43 #endif
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/ReloadableXMLFile.h>
48 #include <xmltooling/util/XMLHelper.h>
49
50 #ifndef SHIBSP_LITE
51 # include "TransactionLog.h"
52 # include "attribute/filtering/AttributeFilter.h"
53 # include "attribute/resolver/AttributeExtractor.h"
54 # include "attribute/resolver/AttributeResolver.h"
55 # include "security/PKIXTrustEngine.h"
56 # include <saml/SAMLConfig.h>
57 # include <saml/binding/ArtifactMap.h>
58 # include <saml/binding/SAMLArtifact.h>
59 # include <saml/saml1/core/Assertions.h>
60 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
61 # include <saml/saml2/metadata/ChainingMetadataProvider.h>
62 # include <xmltooling/security/ChainingTrustEngine.h>
63 # include <xmltooling/util/ReplayCache.h>
64 using namespace opensaml::saml2;
65 using namespace opensaml::saml2p;
66 using namespace opensaml::saml2md;
67 using namespace opensaml;
68 #endif
69
70 using namespace shibsp;
71 using namespace xmltooling;
72 using namespace std;
73
74 namespace {
75
76 #if defined (_MSC_VER)
77     #pragma warning( push )
78     #pragma warning( disable : 4250 )
79 #endif
80
81     static vector<const Handler*> g_noHandlers;
82
83     // Application configuration wrapper
84     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
85     {
86     public:
87         XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
88         ~XMLApplication() { cleanup(); }
89     
90         // Application
91         const ServiceProvider& getServiceProvider() const {return *m_sp;}
92         const char* getId() const {return getString("id").second;}
93         const char* getHash() const {return m_hash.c_str();}
94
95 #ifndef SHIBSP_LITE
96         SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
97             throw ConfigurationException("No support for SAML 1.x artifact generation.");
98         }
99         SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
100             pair<bool,int> index = make_pair(false,0);
101             const PropertySet* props = getRelyingParty(relyingParty);
102             if (props)
103                 index = getInt("artifactEndpointIndex");
104             if (!index.first)
105                 index = getArtifactEndpointIndex();
106             return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(getString("entityID").second),index.first ? index.second : 1);
107         }
108
109         MetadataProvider* getMetadataProvider(bool required=true) const {
110             if (required && !m_base && !m_metadata)
111                 throw ConfigurationException("No MetadataProvider available.");
112             return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
113         }
114         TrustEngine* getTrustEngine(bool required=true) const {
115             if (required && !m_base && !m_trust)
116                 throw ConfigurationException("No TrustEngine available.");
117             return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
118         }
119         AttributeExtractor* getAttributeExtractor() const {
120             return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
121         }
122         AttributeFilter* getAttributeFilter() const {
123             return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
124         }
125         AttributeResolver* getAttributeResolver() const {
126             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
127         }
128         CredentialResolver* getCredentialResolver() const {
129             return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
130         }
131         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
132         const vector<const XMLCh*>& getAudiences() const {
133             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
134         }
135 #endif
136         string getNotificationURL(const char* resource, bool front, unsigned int index) const;
137
138         const set<string>& getRemoteUserAttributeIds() const {
139             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
140         }
141
142         void clearAttributeHeaders(SPRequest& request) const;
143         const SessionInitiator* getDefaultSessionInitiator() const;
144         const SessionInitiator* getSessionInitiatorById(const char* id) const;
145         const Handler* getDefaultAssertionConsumerService() const;
146         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
147         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
148         const Handler* getHandler(const char* path) const;
149
150         void receive(DDF& in, ostream& out) {
151             // Only current function is to return the headers to clear.
152             DDF header;
153             DDF ret=DDF(NULL).list();
154             DDFJanitor jret(ret);
155             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
156                 header = DDF(i->first.c_str()).string(i->second.c_str());
157                 ret.add(header);
158             }
159             out << ret;
160         }
161
162         // Provides filter to exclude special config elements.
163         short acceptNode(const DOMNode* node) const;
164     
165     private:
166         void cleanup();
167         const ServiceProvider* m_sp;   // this is ok because its locking scope includes us
168         const XMLApplication* m_base;
169         string m_hash;
170 #ifndef SHIBSP_LITE
171         MetadataProvider* m_metadata;
172         TrustEngine* m_trust;
173         AttributeExtractor* m_attrExtractor;
174         AttributeFilter* m_attrFilter;
175         AttributeResolver* m_attrResolver;
176         CredentialResolver* m_credResolver;
177         vector<const XMLCh*> m_audiences;
178
179         // RelyingParty properties
180         DOMPropertySet* m_partyDefault;
181 #ifdef HAVE_GOOD_STL
182         map<xstring,PropertySet*> m_partyMap;
183 #else
184         map<const XMLCh*,PropertySet*> m_partyMap;
185 #endif
186 #endif
187         vector<string> m_frontLogout,m_backLogout;
188         set<string> m_remoteUsers;
189         mutable vector< pair<string,string> > m_unsetHeaders;
190         RWLock* m_unsetLock;
191
192         // manage handler objects
193         vector<Handler*> m_handlers;
194
195         // maps location (path info) to applicable handlers
196         map<string,const Handler*> m_handlerMap;
197
198         // maps unique indexes to consumer services
199         map<unsigned int,const Handler*> m_acsIndexMap;
200         
201         // pointer to default consumer service
202         const Handler* m_acsDefault;
203
204         // maps binding strings to supporting consumer service(s)
205 #ifdef HAVE_GOOD_STL
206         typedef map<xstring,vector<const Handler*> > ACSBindingMap;
207 #else
208         typedef map<string,vector<const Handler*> > ACSBindingMap;
209 #endif
210         ACSBindingMap m_acsBindingMap;
211
212         // pointer to default session initiator
213         const SessionInitiator* m_sessionInitDefault;
214
215         // maps unique ID strings to session initiators
216         map<string,const SessionInitiator*> m_sessionInitMap;
217
218         // pointer to default artifact resolution service
219         const Handler* m_artifactResolutionDefault;
220
221         pair<bool,int> getArtifactEndpointIndex() const {
222             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
223             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
224         }
225     };
226
227     // Top-level configuration implementation
228     class SHIBSP_DLLLOCAL XMLConfig;
229     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
230     {
231     public:
232         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
233         ~XMLConfigImpl();
234         
235         RequestMapper* m_requestMapper;
236         map<string,Application*> m_appmap;
237 #ifndef SHIBSP_LITE
238         map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
239         map< string, vector< pair< string, pair<string,string> > > > m_transportOptionMap;
240 #endif
241         
242         // Provides filter to exclude special config elements.
243         short acceptNode(const DOMNode* node) const;
244
245         void setDocument(DOMDocument* doc) {
246             m_document = doc;
247         }
248
249     private:
250         void doExtensions(const DOMElement* e, const char* label, Category& log);
251         void cleanup();
252
253         const XMLConfig* m_outer;
254         DOMDocument* m_document;
255     };
256
257     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile, public Remoted
258     {
259     public:
260         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
261             m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
262 #ifndef SHIBSP_LITE
263             , m_tranLog(NULL)
264 #endif
265         {
266         }
267         
268         void init() {
269             load();
270         }
271
272         ~XMLConfig() {
273             delete m_impl;
274             delete m_sessionCache;
275             delete m_listener;
276 #ifndef SHIBSP_LITE
277             delete m_tranLog;
278             SAMLConfig::getConfig().setArtifactMap(NULL);
279             XMLToolingConfig::getConfig().setReplayCache(NULL);
280             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
281 #endif
282         }
283
284         // PropertySet
285         const PropertySet* getParent() const { return m_impl->getParent(); }
286         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
287         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
288         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
289         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
290         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
291         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
292         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
293         const DOMElement* getElement() const {return m_impl->getElement();}
294
295         // Remoted
296         void receive(DDF& in, ostream& out);
297
298         // ServiceProvider
299 #ifndef SHIBSP_LITE
300         TransactionLog* getTransactionLog() const {
301             if (m_tranLog)
302                 return m_tranLog;
303             throw ConfigurationException("No TransactionLog available.");
304         }
305
306         StorageService* getStorageService(const char* id) const {
307             if (id) {
308                 map<string,StorageService*>::const_iterator i=m_storage.find(id);
309                 if (i!=m_storage.end())
310                     return i->second;
311             }
312             return NULL;
313         }
314 #endif
315
316         ListenerService* getListenerService(bool required=true) const {
317             if (required && !m_listener)
318                 throw ConfigurationException("No ListenerService available.");
319             return m_listener;
320         }
321
322         SessionCache* getSessionCache(bool required=true) const {
323             if (required && !m_sessionCache)
324                 throw ConfigurationException("No SessionCache available.");
325             return m_sessionCache;
326         }
327
328         RequestMapper* getRequestMapper(bool required=true) const {
329             if (required && !m_impl->m_requestMapper)
330                 throw ConfigurationException("No RequestMapper available.");
331             return m_impl->m_requestMapper;
332         }
333
334         const Application* getApplication(const char* applicationId) const {
335             map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
336             return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
337         }
338
339 #ifndef SHIBSP_LITE
340         const PropertySet* getPolicySettings(const char* id) const {
341             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
342             if (i!=m_impl->m_policyMap.end())
343                 return i->second.first;
344             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
345         }
346
347         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
348             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
349             if (i!=m_impl->m_policyMap.end())
350                 return i->second.second;
351             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
352         }
353
354         bool setTransportOptions(const char* id, SOAPTransport& transport) const {
355             bool ret = true;
356             map< string, vector< pair< string, pair<string,string> > > >::const_iterator p =
357                 m_impl->m_transportOptionMap.find(id);
358             if (p == m_impl->m_transportOptionMap.end())
359                 return ret;
360             vector< pair< string, pair<string,string> > >::const_iterator opt;
361             for (opt = p->second.begin(); opt != p->second.end(); ++opt) {
362                 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
363                     m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
364                     ret = false;
365                 }
366             }
367             return ret;
368         }
369 #endif
370
371     protected:
372         pair<bool,DOMElement*> load();
373
374     private:
375         friend class XMLConfigImpl;
376         XMLConfigImpl* m_impl;
377         mutable ListenerService* m_listener;
378         mutable SessionCache* m_sessionCache;
379 #ifndef SHIBSP_LITE
380         mutable TransactionLog* m_tranLog;
381         mutable map<string,StorageService*> m_storage;
382 #endif
383     };
384
385 #if defined (_MSC_VER)
386     #pragma warning( pop )
387 #endif
388
389     static const XMLCh _Application[] =         UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
390     static const XMLCh Applications[] =         UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
391     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
392     static const XMLCh _AttributeExtractor[] =  UNICODE_LITERAL_18(A,t,t,r,i,b,u,t,e,E,x,t,r,a,c,t,o,r);
393     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
394     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
395     static const XMLCh _AssertionConsumerService[] = UNICODE_LITERAL_24(A,s,s,e,r,t,i,o,n,C,o,n,s,u,m,e,r,S,e,r,v,i,c,e);
396     static const XMLCh _ArtifactResolutionService[] =UNICODE_LITERAL_25(A,r,t,i,f,a,c,t,R,e,s,o,l,u,t,i,o,n,S,e,r,v,i,c,e);
397     static const XMLCh _Audience[] =            UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
398     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
399     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
400     static const XMLCh _CredentialResolver[] =  UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
401     static const XMLCh DefaultRelyingParty[] =  UNICODE_LITERAL_19(D,e,f,a,u,l,t,R,e,l,y,i,n,g,P,a,r,t,y);
402     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
403     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
404     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
405     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
406     static const XMLCh Implementation[] =       UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
407     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
408     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);
409     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
410     static const XMLCh Location[] =             UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
411     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);
412     static const XMLCh _LogoutInitiator[] =     UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
413     static const XMLCh _ManageNameIDService[] = UNICODE_LITERAL_19(M,a,n,a,g,e,N,a,m,e,I,D,S,e,r,v,i,c,e);
414     static const XMLCh MemoryListener[] =       UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
415     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
416     static const XMLCh Notify[] =               UNICODE_LITERAL_6(N,o,t,i,f,y);
417     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
418     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
419     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
420     static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);
421     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
422     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
423     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
424     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
425     static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);
426     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
427     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
428     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
429     static const XMLCh _SingleLogoutService[] = UNICODE_LITERAL_19(S,i,n,g,l,e,L,o,g,o,u,t,S,e,r,v,i,c,e);
430     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
431     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
432     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
433     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
434     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
435     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
436
437 #ifndef SHIBSP_LITE
438     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
439     {
440     public:
441         short acceptNode(const DOMNode* node) const {
442             return FILTER_REJECT;
443         }
444     };
445 #endif
446 };
447
448 namespace shibsp {
449     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
450     {
451         return new XMLConfig(e);
452     }
453 };
454
455 XMLApplication::XMLApplication(
456     const ServiceProvider* sp,
457     const DOMElement* e,
458     const XMLApplication* base
459     ) : m_sp(sp), m_base(base),
460 #ifndef SHIBSP_LITE
461         m_metadata(NULL), m_trust(NULL),
462         m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
463         m_credResolver(NULL), m_partyDefault(NULL),
464 #endif
465         m_unsetLock(NULL), m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
466 {
467 #ifdef _DEBUG
468     xmltooling::NDC ndc("XMLApplication");
469 #endif
470     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
471
472     try {
473         // First load any property sets.
474         load(e,log,this);
475         if (base)
476             setParent(base);
477
478         SPConfig& conf=SPConfig::getConfig();
479 #ifndef SHIBSP_LITE
480         SAMLConfig& samlConf=SAMLConfig::getConfig();
481         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
482 #endif
483
484         // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
485         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
486         string tohash=getId();
487         tohash+=getString("entityID").second;
488         for (const char* ch = tohash.c_str(); *ch; ++ch) {
489             m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
490             m_hash += (DIGITS[0x0F & *ch]);
491         }
492
493         // Load attribute ID lists for REMOTE_USER and header clearing.
494         if (conf.isEnabled(SPConfig::InProcess)) {
495             pair<bool,const char*> attributes = getString("REMOTE_USER");
496             if (attributes.first) {
497                 char* dup = strdup(attributes.second);
498                 char* pos;
499                 char* start = dup;
500                 while (start && *start) {
501                     while (*start && isspace(*start))
502                         start++;
503                     if (!*start)
504                         break;
505                     pos = strchr(start,' ');
506                     if (pos)
507                         *pos=0;
508                     m_remoteUsers.insert(start);
509                     start = pos ? pos+1 : NULL;
510                 }
511                 free(dup);
512             }
513
514             attributes = getString("unsetHeaders");
515             if (attributes.first) {
516                 char* dup = strdup(attributes.second);
517                 char* pos;
518                 char* start = dup;
519                 while (start && *start) {
520                     while (*start && isspace(*start))
521                         start++;
522                     if (!*start)
523                         break;
524                     pos = strchr(start,' ');
525                     if (pos)
526                         *pos=0;
527
528                     string transformed("HTTP_");
529                     const char* pch = start;
530                     while (*pch) {
531                         transformed += (isalnum(*pch) ? toupper(*pch) : '_');
532                         pch++;
533                     }
534                     m_unsetHeaders.push_back(pair<string,string>(start,transformed));
535                     start = pos ? pos+1 : NULL;
536                 }
537                 free(dup);
538                 m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
539             }
540         }
541
542         Handler* handler=NULL;
543         const PropertySet* sessions = getPropertySet("Sessions");
544
545         // Process assertion export handler.
546         pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
547         if (location.first) {
548             try {
549                 handler = conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, make_pair(sessions->getElement(), getId()));
550                 m_handlers.push_back(handler);
551
552                 // Insert into location map. If it contains the handlerURL, we skip past that part.
553                 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
554                 if (pch)
555                     location.second = pch + strlen(sessions->getString("handlerURL").second);
556                 if (*location.second == '/')
557                     m_handlerMap[location.second]=handler;
558                 else
559                     m_handlerMap[string("/") + location.second]=handler;
560             }
561             catch (exception& ex) {
562                 log.error("caught exception installing assertion lookup handler: %s", ex.what());
563             }
564         }
565
566         // Process other handlers.
567         bool hardACS=false, hardSessionInit=false, hardArt=false;
568         const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
569         while (child) {
570             try {
571                 // A handler is based on the Binding property in conjunction with the element name.
572                 // If it's an ACS or SI, also handle index/id mappings and defaulting.
573                 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
574                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
575                     if (!bindprop.get() || !*(bindprop.get())) {
576                         log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
577                         child = XMLHelper::getNextSiblingElement(child);
578                         continue;
579                     }
580                     handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
581                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
582 #ifdef HAVE_GOOD_STL
583                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
584 #else
585                     m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
586 #endif
587                     m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
588                     
589                     if (!hardACS) {
590                         pair<bool,bool> defprop=handler->getBool("isDefault");
591                         if (defprop.first) {
592                             if (defprop.second) {
593                                 hardACS=true;
594                                 m_acsDefault=handler;
595                             }
596                         }
597                         else if (!m_acsDefault)
598                             m_acsDefault=handler;
599                     }
600                 }
601                 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
602                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
603                     if (!type.get() || !*(type.get())) {
604                         log.warn("SessionInitiator element has no type attribute, skipping it...");
605                         child = XMLHelper::getNextSiblingElement(child);
606                         continue;
607                     }
608                     SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
609                     handler=sihandler;
610                     pair<bool,const char*> si_id=handler->getString("id");
611                     if (si_id.first && si_id.second)
612                         m_sessionInitMap[si_id.second]=sihandler;
613                     if (!hardSessionInit) {
614                         pair<bool,bool> defprop=handler->getBool("isDefault");
615                         if (defprop.first) {
616                             if (defprop.second) {
617                                 hardSessionInit=true;
618                                 m_sessionInitDefault=sihandler;
619                             }
620                         }
621                         else if (!m_sessionInitDefault)
622                             m_sessionInitDefault=sihandler;
623                     }
624                 }
625                 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
626                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
627                     if (!type.get() || !*(type.get())) {
628                         log.warn("LogoutInitiator element has no type attribute, skipping it...");
629                         child = XMLHelper::getNextSiblingElement(child);
630                         continue;
631                     }
632                     handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
633                 }
634                 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
635                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
636                     if (!bindprop.get() || !*(bindprop.get())) {
637                         log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
638                         child = XMLHelper::getNextSiblingElement(child);
639                         continue;
640                     }
641                     handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
642                     
643                     if (!hardArt) {
644                         pair<bool,bool> defprop=handler->getBool("isDefault");
645                         if (defprop.first) {
646                             if (defprop.second) {
647                                 hardArt=true;
648                                 m_artifactResolutionDefault=handler;
649                             }
650                         }
651                         else if (!m_artifactResolutionDefault)
652                             m_artifactResolutionDefault=handler;
653                     }
654                 }
655                 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
656                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
657                     if (!bindprop.get() || !*(bindprop.get())) {
658                         log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
659                         child = XMLHelper::getNextSiblingElement(child);
660                         continue;
661                     }
662                     handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
663                 }
664                 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
665                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
666                     if (!bindprop.get() || !*(bindprop.get())) {
667                         log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
668                         child = XMLHelper::getNextSiblingElement(child);
669                         continue;
670                     }
671                     handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
672                 }
673                 else {
674                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
675                     if (!type.get() || !*(type.get())) {
676                         log.warn("Handler element has no type attribute, skipping it...");
677                         child = XMLHelper::getNextSiblingElement(child);
678                         continue;
679                     }
680                     handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
681                 }
682
683                 m_handlers.push_back(handler);
684
685                 // Insert into location map.
686                 location=handler->getString("Location");
687                 if (location.first && *location.second == '/')
688                     m_handlerMap[location.second]=handler;
689                 else if (location.first)
690                     m_handlerMap[string("/") + location.second]=handler;
691
692             }
693             catch (exception& ex) {
694                 log.error("caught exception processing handler element: %s", ex.what());
695             }
696             
697             child = XMLHelper::getNextSiblingElement(child);
698         }
699
700         // Notification.
701         DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
702         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
703             if (nlist->item(i)->getParentNode()->isSameNode(e)) {
704                 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
705                 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
706                 if (loc.get() && *loc.get()) {
707                     if (channel && *channel == chLatin_f)
708                         m_frontLogout.push_back(loc.get());
709                     else
710                         m_backLogout.push_back(loc.get());
711                 }
712             }
713         }
714
715 #ifndef SHIBSP_LITE
716         nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
717         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
718             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
719                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
720
721         // Always include our own entityID as an audience.
722         m_audiences.push_back(getXMLString("entityID").second);
723
724         if (conf.isEnabled(SPConfig::Metadata)) {
725             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
726             if (child) {
727                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
728                 log.info("building MetadataProvider of type %s...",type.get());
729                 try {
730                     auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
731                     mp->init();
732                     m_metadata = mp.release();
733                 }
734                 catch (exception& ex) {
735                     log.crit("error building/initializing MetadataProvider: %s", ex.what());
736                 }
737             }
738         }
739
740         if (conf.isEnabled(SPConfig::Trust)) {
741             child = XMLHelper::getFirstChildElement(e,_TrustEngine);
742             if (child) {
743                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
744                 log.info("building TrustEngine of type %s...",type.get());
745                 try {
746                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
747                 }
748                 catch (exception& ex) {
749                     log.crit("error building TrustEngine: %s", ex.what());
750                 }
751             }
752         }
753
754         if (conf.isEnabled(SPConfig::AttributeResolution)) {
755             child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
756             if (child) {
757                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
758                 log.info("building AttributeExtractor of type %s...",type.get());
759                 try {
760                     m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
761                 }
762                 catch (exception& ex) {
763                     log.crit("error building AttributeExtractor: %s", ex.what());
764                 }
765             }
766
767             child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
768             if (child) {
769                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
770                 log.info("building AttributeFilter of type %s...",type.get());
771                 try {
772                     m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
773                 }
774                 catch (exception& ex) {
775                     log.crit("error building AttributeFilter: %s", ex.what());
776                 }
777             }
778
779             child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
780             if (child) {
781                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
782                 log.info("building AttributeResolver of type %s...",type.get());
783                 try {
784                     m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
785                 }
786                 catch (exception& ex) {
787                     log.crit("error building AttributeResolver: %s", ex.what());
788                 }
789             }
790
791             if (m_unsetHeaders.empty()) {
792                 vector<string> unsetHeaders;
793                 if (m_attrExtractor) {
794                     Locker extlock(m_attrExtractor);
795                     m_attrExtractor->getAttributeIds(unsetHeaders);
796                 }
797                 if (m_attrResolver) {
798                     Locker reslock(m_attrResolver);
799                     m_attrResolver->getAttributeIds(unsetHeaders);
800                 }
801                 if (unsetHeaders.empty()) {
802                     if (m_base)
803                         m_unsetHeaders.insert(m_unsetHeaders.end(), m_base->m_unsetHeaders.begin(), m_base->m_unsetHeaders.end());
804                     else
805                         m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
806                 }
807                 else {
808                     for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
809                         string transformed("HTTP_");
810                         const char* pch = hdr->c_str();
811                         while (*pch) {
812                             transformed += (isalnum(*pch) ? toupper(*pch) : '_');
813                             pch++;
814                         }
815                         m_unsetHeaders.push_back(pair<string,string>(*hdr,transformed));
816                     }
817                     m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
818                 }
819             }
820         }
821
822         if (conf.isEnabled(SPConfig::Credentials)) {
823             child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
824             if (child) {
825                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
826                 log.info("building CredentialResolver of type %s...",type.get());
827                 try {
828                     m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
829                 }
830                 catch (exception& ex) {
831                     log.crit("error building CredentialResolver: %s", ex.what());
832                 }
833             }
834         }
835
836         // Finally, load relying parties.
837         child = XMLHelper::getFirstChildElement(e,DefaultRelyingParty);
838         if (child) {
839             m_partyDefault=new DOMPropertySet();
840             m_partyDefault->load(child,log,this);
841             child = XMLHelper::getFirstChildElement(child,RelyingParty);
842             while (child) {
843                 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
844                 rp->load(child,log,this);
845                 rp->setParent(m_partyDefault);
846                 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
847                 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
848             }
849         }
850 #endif
851
852         // In process only, we need a shared lock around accessing the header clearing list.
853         if (!conf.isEnabled(SPConfig::OutOfProcess)) {
854             m_unsetLock = RWLock::create();
855         }
856         else if (!conf.isEnabled(SPConfig::InProcess)) {
857             ListenerService* listener = sp->getListenerService(false);
858             if (listener) {
859                 string addr=string(getId()) + "::getHeaders::Application";
860                 listener->regListener(addr.c_str(),this);
861             }
862             else
863                 log.info("no ListenerService available, Application remoting disabled");
864         }
865     }
866     catch (exception&) {
867         cleanup();
868         throw;
869     }
870 #ifndef _DEBUG
871     catch (...) {
872         cleanup();
873         throw;
874     }
875 #endif
876 }
877
878 void XMLApplication::cleanup()
879 {
880     ListenerService* listener=getServiceProvider().getListenerService(false);
881     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
882         string addr=string(getId()) + "::getHeaders::Application";
883         listener->unregListener(addr.c_str(),this);
884     }
885     delete m_unsetLock;
886     m_unsetLock = NULL;
887     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
888     m_handlers.clear();
889 #ifndef SHIBSP_LITE
890     delete m_partyDefault;
891     m_partyDefault = NULL;
892 #ifdef HAVE_GOOD_STL
893     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
894 #else
895     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
896 #endif
897     m_partyMap.clear();
898     delete m_credResolver;
899     m_credResolver = NULL;
900     delete m_attrResolver;
901     m_attrResolver = NULL;
902     delete m_attrFilter;
903     m_attrFilter = NULL;
904     delete m_attrExtractor;
905     m_attrExtractor = NULL;
906     delete m_trust;
907     m_trust = NULL;
908     delete m_metadata;
909     m_metadata = NULL;
910 #endif
911 }
912
913 short XMLApplication::acceptNode(const DOMNode* node) const
914 {
915     const XMLCh* name=node->getLocalName();
916     if (XMLString::equals(name,_Application) ||
917         XMLString::equals(name,_Audience) ||
918         XMLString::equals(name,Notify) ||
919         XMLString::equals(name,_AssertionConsumerService) ||
920         XMLString::equals(name,_ArtifactResolutionService) ||
921         XMLString::equals(name,_LogoutInitiator) ||
922         XMLString::equals(name,_ManageNameIDService) ||
923         XMLString::equals(name,_SessionInitiator) ||
924         XMLString::equals(name,_SingleLogoutService) ||
925         XMLString::equals(name,DefaultRelyingParty) ||
926         XMLString::equals(name,RelyingParty) ||
927         XMLString::equals(name,_MetadataProvider) ||
928         XMLString::equals(name,_TrustEngine) ||
929         XMLString::equals(name,_CredentialResolver) ||
930         XMLString::equals(name,_AttributeFilter) ||
931         XMLString::equals(name,_AttributeExtractor) ||
932         XMLString::equals(name,_AttributeResolver))
933         return FILTER_REJECT;
934
935     return FILTER_ACCEPT;
936 }
937
938 #ifndef SHIBSP_LITE
939
940 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
941 {
942     if (!m_partyDefault && m_base)
943         return m_base->getRelyingParty(provider);
944     else if (!provider)
945         return m_partyDefault;
946         
947 #ifdef HAVE_GOOD_STL
948     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
949     if (i!=m_partyMap.end())
950         return i->second;
951     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
952     while (group) {
953         if (group->getName()) {
954             i=m_partyMap.find(group->getName());
955             if (i!=m_partyMap.end())
956                 return i->second;
957         }
958         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
959     }
960 #else
961     map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
962     for (; i!=m_partyMap.end(); i++) {
963         if (XMLString::equals(i->first,provider->getEntityID()))
964             return i->second;
965         const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
966         while (group) {
967             if (XMLString::equals(i->first,group->getName()))
968                 return i->second;
969             group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
970         }
971     }
972 #endif
973     return m_partyDefault;
974 }
975
976 #endif
977
978 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
979 {
980     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
981     if (locs.empty())
982         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
983     else if (index >= locs.size())
984         return string();
985
986 #ifdef HAVE_STRCASECMP
987     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
988 #else
989     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
990 #endif
991         throw ConfigurationException("Request URL was not absolute.");
992
993     const char* handler=locs[index].c_str();
994     
995     // Should never happen...
996     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
997         throw ConfigurationException(
998             "Invalid Location property ($1) in Notify element for Application ($2)",
999             params(2, handler ? handler : "null", getId())
1000             );
1001
1002     // The "Location" property can be in one of three formats:
1003     //
1004     // 1) a full URI:       http://host/foo/bar
1005     // 2) a hostless URI:   http:///foo/bar
1006     // 3) a relative path:  /foo/bar
1007     //
1008     // #  Protocol  Host        Path
1009     // 1  handler   handler     handler
1010     // 2  handler   resource    handler
1011     // 3  resource  resource    handler
1012
1013     const char* path = NULL;
1014
1015     // Decide whether to use the handler or the resource for the "protocol"
1016     const char* prot;
1017     if (*handler != '/') {
1018         prot = handler;
1019     }
1020     else {
1021         prot = resource;
1022         path = handler;
1023     }
1024
1025     // break apart the "protocol" string into protocol, host, and "the rest"
1026     const char* colon=strchr(prot,':');
1027     colon += 3;
1028     const char* slash=strchr(colon,'/');
1029     if (!path)
1030         path = slash;
1031
1032     // Compute the actual protocol and store.
1033     string notifyURL(prot, colon-prot);
1034
1035     // create the "host" from either the colon/slash or from the target string
1036     // If prot == handler then we're in either #1 or #2, else #3.
1037     // If slash == colon then we're in #2.
1038     if (prot != handler || slash == colon) {
1039         colon = strchr(resource, ':');
1040         colon += 3;      // Get past the ://
1041         slash = strchr(colon, '/');
1042     }
1043     string host(colon, (slash ? slash-colon : strlen(colon)));
1044
1045     // Build the URL
1046     notifyURL += host + path;
1047     return notifyURL;
1048 }
1049
1050 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1051 {
1052     if (m_sessionInitDefault) return m_sessionInitDefault;
1053     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1054 }
1055
1056 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1057 {
1058     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1059     if (i!=m_sessionInitMap.end()) return i->second;
1060     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1061 }
1062
1063 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1064 {
1065     if (m_acsDefault) return m_acsDefault;
1066     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1067 }
1068
1069 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1070 {
1071     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1072     if (i!=m_acsIndexMap.end()) return i->second;
1073     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1074 }
1075
1076 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1077 {
1078 #ifdef HAVE_GOOD_STL
1079     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1080 #else
1081     auto_ptr_char temp(binding);
1082     ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
1083 #endif
1084     if (i!=m_acsBindingMap.end())
1085         return i->second;
1086     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1087 }
1088
1089 const Handler* XMLApplication::getHandler(const char* path) const
1090 {
1091     string wrap(path);
1092     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1093     if (i!=m_handlerMap.end())
1094         return i->second;
1095     return m_base ? m_base->getHandler(path) : NULL;
1096 }
1097
1098 void XMLApplication::clearAttributeHeaders(SPRequest& request) const
1099 {
1100     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1101         for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
1102             request.clearHeader(i->first.c_str(), i->second.c_str());
1103         return;
1104     }
1105
1106     m_unsetLock->rdlock();
1107     if (m_unsetHeaders.empty()) {
1108         // No headers yet, so we have to request them from the remote half.
1109         m_unsetLock->unlock();
1110         m_unsetLock->wrlock();
1111         if (m_unsetHeaders.empty()) {
1112             SharedLock wrlock(m_unsetLock, false);
1113             string addr=string(getId()) + "::getHeaders::Application";
1114             DDF out,in = DDF(addr.c_str());
1115             DDFJanitor jin(in),jout(out);
1116             out = getServiceProvider().getListenerService()->send(in);
1117             if (out.islist()) {
1118                 DDF header = out.first();
1119                 while (header.isstring()) {
1120                     m_unsetHeaders.push_back(pair<string,string>(header.name(),header.string()));
1121                     header = out.next();
1122                 }
1123             }
1124         }
1125         else {
1126             m_unsetLock->unlock();
1127         }
1128         m_unsetLock->rdlock();
1129     }
1130
1131     // Now holding read lock.
1132     SharedLock unsetLock(m_unsetLock, false);
1133     for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
1134         request.clearHeader(i->first.c_str(), i->second.c_str());
1135 }
1136
1137 short XMLConfigImpl::acceptNode(const DOMNode* node) const
1138 {
1139     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1140         return FILTER_ACCEPT;
1141     const XMLCh* name=node->getLocalName();
1142     if (XMLString::equals(name,Applications) ||
1143         XMLString::equals(name,_ArtifactMap) ||
1144         XMLString::equals(name,_Extensions) ||
1145         XMLString::equals(name,Implementation) ||
1146         XMLString::equals(name,Listener) ||
1147         XMLString::equals(name,MemoryListener) ||
1148         XMLString::equals(name,Policy) ||
1149         XMLString::equals(name,_RequestMapper) ||
1150         XMLString::equals(name,_ReplayCache) ||
1151         XMLString::equals(name,_SessionCache) ||
1152         XMLString::equals(name,_StorageService) ||
1153         XMLString::equals(name,TCPListener) ||
1154         XMLString::equals(name,UnixListener))
1155         return FILTER_REJECT;
1156
1157     return FILTER_ACCEPT;
1158 }
1159
1160 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1161 {
1162     const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1163     if (exts) {
1164         exts=XMLHelper::getFirstChildElement(exts,Library);
1165         while (exts) {
1166             auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1167             try {
1168                 if (path.get()) {
1169                     XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts);
1170                     log.debug("loaded %s extension library (%s)", label, path.get());
1171                 }
1172             }
1173             catch (exception& e) {
1174                 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1175                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1176                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1177                     throw;
1178                 }
1179                 else {
1180                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1181                 }
1182             }
1183             exts=XMLHelper::getNextSiblingElement(exts,Library);
1184         }
1185     }
1186 }
1187
1188 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1189     : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1190 {
1191 #ifdef _DEBUG
1192     xmltooling::NDC ndc("XMLConfigImpl");
1193 #endif
1194
1195     try {
1196         SPConfig& conf=SPConfig::getConfig();
1197 #ifndef SHIBSP_LITE
1198         SAMLConfig& samlConf=SAMLConfig::getConfig();
1199 #endif
1200         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1201         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1202         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1203
1204         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1205         if (conf.isEnabled(SPConfig::Logging)) {
1206             const XMLCh* logconf=NULL;
1207             if (conf.isEnabled(SPConfig::OutOfProcess))
1208                 logconf=SHAR->getAttributeNS(NULL,logger);
1209             else if (conf.isEnabled(SPConfig::InProcess))
1210                 logconf=SHIRE->getAttributeNS(NULL,logger);
1211             if (!logconf || !*logconf)
1212                 logconf=e->getAttributeNS(NULL,logger);
1213             if (logconf && *logconf) {
1214                 auto_ptr_char logpath(logconf);
1215                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1216                 XMLToolingConfig::getConfig().log_config(logpath.get());
1217             }
1218             
1219 #ifndef SHIBSP_LITE
1220             if (first)
1221                 m_outer->m_tranLog = new TransactionLog();
1222 #endif
1223         }
1224         
1225         // First load any property sets.
1226         load(e,log,this);
1227
1228         const DOMElement* child;
1229         string plugtype;
1230
1231         // Much of the processing can only occur on the first instantiation.
1232         if (first) {
1233             // Set clock skew.
1234             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1235             if (skew.first)
1236                 xmlConf.clock_skew_secs=skew.second;
1237
1238             // Extensions
1239             doExtensions(e, "global", log);
1240             if (conf.isEnabled(SPConfig::OutOfProcess))
1241                 doExtensions(SHAR, "out of process", log);
1242
1243             if (conf.isEnabled(SPConfig::InProcess))
1244                 doExtensions(SHIRE, "in process", log);
1245             
1246             // Instantiate the ListenerService and SessionCache objects.
1247             if (conf.isEnabled(SPConfig::Listener)) {
1248                 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
1249                 if (child)
1250                     plugtype=UNIX_LISTENER_SERVICE;
1251                 else {
1252                     child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
1253                     if (child)
1254                         plugtype=TCP_LISTENER_SERVICE;
1255                     else {
1256                         child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
1257                         if (child)
1258                             plugtype=MEMORY_LISTENER_SERVICE;
1259                         else {
1260                             child=XMLHelper::getFirstChildElement(SHAR,Listener);
1261                             if (child) {
1262                                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1263                                 if (type.get())
1264                                     plugtype=type.get();
1265                             }
1266                         }
1267                     }
1268                 }
1269                 if (child) {
1270                     log.info("building ListenerService of type %s...", plugtype.c_str());
1271                     m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
1272                 }
1273                 else {
1274                     log.fatal("can't build ListenerService, missing conf:Listener element?");
1275                     throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1276                 }
1277             }
1278
1279             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1280                 m_outer->m_listener->regListener("set::RelayState",m_outer->m_listener);
1281                 m_outer->m_listener->regListener("get::RelayState",m_outer->m_listener);
1282             }
1283
1284             if (conf.isEnabled(SPConfig::Caching)) {
1285                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1286 #ifndef SHIBSP_LITE
1287                     // First build any StorageServices.
1288                     string inmemID;
1289                     child=XMLHelper::getFirstChildElement(SHAR,_StorageService);
1290                     while (child) {
1291                         auto_ptr_char id(child->getAttributeNS(NULL,_id));
1292                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1293                         try {
1294                             log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1295                             m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1296                             if (!strcmp(type.get(),MEMORY_STORAGE_SERVICE))
1297                                 inmemID = id.get();
1298                         }
1299                         catch (exception& ex) {
1300                             log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1301                         }
1302                         child=XMLHelper::getNextSiblingElement(child,_StorageService);
1303                     }
1304                 
1305                     child=XMLHelper::getFirstChildElement(SHAR,_SessionCache);
1306                     if (child) {
1307                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1308                         log.info("building SessionCache of type %s...",type.get());
1309                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1310                     }
1311                     else {
1312                         log.warn("SessionCache unspecified, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);
1313                         if (inmemID.empty()) {
1314                             inmemID = "memory";
1315                             log.info("no StorageServices configured, providing in-memory version for session cache");
1316                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1317                         }
1318                         child = e->getOwnerDocument()->createElementNS(NULL,_SessionCache);
1319                         auto_ptr_XMLCh ssid(inmemID.c_str());
1320                         const_cast<DOMElement*>(child)->setAttributeNS(NULL,_StorageService,ssid.get());
1321                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
1322                     }
1323
1324                     // Replay cache.
1325                     StorageService* replaySS=NULL;
1326                     child=XMLHelper::getFirstChildElement(SHAR,_ReplayCache);
1327                     if (child) {
1328                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1329                         if (ssid.get() && *ssid.get()) {
1330                             if (m_outer->m_storage.count(ssid.get()))
1331                                 replaySS = m_outer->m_storage[ssid.get()];
1332                             if (replaySS)
1333                                 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1334                             else
1335                                 log.crit("unable to locate StorageService (%s) in configuration", ssid.get());
1336                         }
1337                     }
1338                     if (!replaySS) {
1339                         log.info("building ReplayCache using in-memory StorageService...");
1340                         if (inmemID.empty()) {
1341                             inmemID = "memory";
1342                             log.info("no StorageServices configured, providing in-memory version for legacy config");
1343                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1344                         }
1345                         replaySS = m_outer->m_storage[inmemID];
1346                     }
1347                     xmlConf.setReplayCache(new ReplayCache(replaySS));
1348                     
1349                     // ArtifactMap
1350                     child=XMLHelper::getFirstChildElement(SHAR,_ArtifactMap);
1351                     if (child) {
1352                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1353                         if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1354                             log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1355                             samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1356                         }
1357                     }
1358                     if (samlConf.getArtifactMap()==NULL) {
1359                         log.info("building in-memory ArtifactMap...");
1360                         samlConf.setArtifactMap(new ArtifactMap(child));
1361                     }
1362 #endif
1363                 }
1364                 else {
1365                     child=XMLHelper::getFirstChildElement(SHIRE,_SessionCache);
1366                     if (child) {
1367                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1368                         log.info("building SessionCache of type %s...",type.get());
1369                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1370                     }
1371                     else {
1372                         log.warn("SessionCache unspecified, building SessionCache of type %s...",REMOTED_SESSION_CACHE);
1373                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(REMOTED_SESSION_CACHE,child);
1374                     }
1375                 }
1376             }
1377         } // end of first-time-only stuff
1378         
1379         // Back to the fully dynamic stuff...next up is the RequestMapper.
1380         if (conf.isEnabled(SPConfig::RequestMapping)) {
1381             child=XMLHelper::getFirstChildElement(SHIRE,_RequestMapper);
1382             if (child) {
1383                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1384                 log.info("building RequestMapper of type %s...",type.get());
1385                 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1386             }
1387         }
1388         
1389 #ifndef SHIBSP_LITE
1390         // Load security policies.
1391         child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1392         if (child) {
1393             PolicyNodeFilter filter;
1394             child = XMLHelper::getFirstChildElement(child,Policy);
1395             while (child) {
1396                 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1397                 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1398                 rules.first = NULL;
1399                 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1400                 settings->load(child, log, &filter);
1401                 rules.first = settings.release();
1402                 
1403                 // Process Rule elements.
1404                 const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);
1405                 while (rule) {
1406                     auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1407                     try {
1408                         rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1409                     }
1410                     catch (exception& ex) {
1411                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1412                     }
1413                     rule = XMLHelper::getNextSiblingElement(rule,Rule);
1414                 }
1415                 
1416                 // Process TransportOption elements.
1417                 rule = XMLHelper::getFirstChildElement(child,TransportOption);
1418                 while (rule) {
1419                     if (rule->hasChildNodes()) {
1420                         auto_ptr_char provider(rule->getAttributeNS(NULL,_provider));
1421                         auto_ptr_char option(rule->getAttributeNS(NULL,_option));
1422                         auto_ptr_char value(rule->getFirstChild()->getNodeValue());
1423                         if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1424                             m_transportOptionMap[id.get()].push_back(
1425                                 make_pair(provider.get(), make_pair(option.get(), value.get()))
1426                                 );
1427                         }
1428                     }
1429                     rule = XMLHelper::getNextSiblingElement(rule,TransportOption);
1430                 }
1431                 
1432                 child = XMLHelper::getNextSiblingElement(child,Policy);
1433             }
1434         }
1435 #endif
1436
1437         // Load the default application. This actually has a fixed ID of "default". ;-)
1438         child=XMLHelper::getLastChildElement(e,Applications);
1439         if (!child) {
1440             log.fatal("can't build default Application object, missing conf:Applications element?");
1441             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1442         }
1443         XMLApplication* defapp=new XMLApplication(m_outer,child);
1444         m_appmap[defapp->getId()]=defapp;
1445         
1446         // Load any overrides.
1447         child = XMLHelper::getFirstChildElement(child,_Application);
1448         while (child) {
1449             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1450             if (m_appmap.count(iapp->getId()))
1451                 log.crit("found conf:Application element with duplicate id attribute (%s), skipping it", iapp->getId());
1452             else
1453                 m_appmap[iapp->getId()]=iapp.release();
1454
1455             child = XMLHelper::getNextSiblingElement(child,_Application);
1456         }
1457     }
1458     catch (exception&) {
1459         cleanup();
1460         throw;
1461     }
1462 #ifndef _DEBUG
1463     catch (...) {
1464         cleanup();
1465         throw;
1466     }
1467 #endif
1468 }
1469
1470 XMLConfigImpl::~XMLConfigImpl()
1471 {
1472     cleanup();
1473 }
1474
1475 void XMLConfigImpl::cleanup()
1476 {
1477     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1478     m_appmap.clear();
1479 #ifndef SHIBSP_LITE
1480     for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1481         delete i->second.first;
1482         for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1483     }
1484     m_policyMap.clear();
1485 #endif
1486     delete m_requestMapper;
1487     m_requestMapper = NULL;
1488     if (m_document)
1489         m_document->release();
1490     m_document = NULL;
1491 }
1492
1493 void XMLConfig::receive(DDF& in, ostream& out)
1494 {
1495 #ifndef SHIBSP_LITE
1496     if (!strcmp(in.name(), "get::RelayState")) {
1497         const char* id = in["id"].string();
1498         const char* key = in["key"].string();
1499         if (!id || !key)
1500             throw ListenerException("Required parameters missing for RelayState recovery.");
1501
1502         string relayState;
1503         StorageService* storage = getStorageService(id);
1504         if (storage) {
1505             if (storage->readString("RelayState",key,&relayState)>0) {
1506                 if (in["clear"].integer())
1507                     storage->deleteString("RelayState",key);
1508             }
1509         }
1510         else {
1511             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1512                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1513                 );
1514         }
1515
1516         // Repack for return to caller.
1517         DDF ret=DDF(NULL).string(relayState.c_str());
1518         DDFJanitor jret(ret);
1519         out << ret;
1520     }
1521     else if (!strcmp(in.name(), "set::RelayState")) {
1522         const char* id = in["id"].string();
1523         const char* value = in["value"].string();
1524         if (!id || !value)
1525             throw ListenerException("Required parameters missing for RelayState creation.");
1526
1527         string rsKey;
1528         StorageService* storage = getStorageService(id);
1529         if (storage) {
1530             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1531             rsKey = SAMLArtifact::toHex(rsKey);
1532             storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1533         }
1534         else {
1535             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1536                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1537                 );
1538         }
1539
1540         // Repack for return to caller.
1541         DDF ret=DDF(NULL).string(rsKey.c_str());
1542         DDFJanitor jret(ret);
1543         out << ret;
1544     }
1545 #endif
1546 }
1547
1548 pair<bool,DOMElement*> XMLConfig::load()
1549 {
1550     // Load from source using base class.
1551     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1552     
1553     // If we own it, wrap it.
1554     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1555
1556     XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1557     
1558     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1559     impl->setDocument(docjanitor.release());
1560
1561     delete m_impl;
1562     m_impl = impl;
1563
1564     return make_pair(false,(DOMElement*)NULL);
1565 }