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