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