https://issues.shibboleth.net/jira/browse/SSPCPP-349
[shibboleth/cpp-sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLServiceProvider.cpp
23  *
24  * XML-based SP configuration and mgmt.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "version.h"
30 #include "AccessControl.h"
31 #include "Application.h"
32 #include "RequestMapper.h"
33 #include "ServiceProvider.h"
34 #include "SessionCache.h"
35 #include "SPConfig.h"
36 #include "SPRequest.h"
37 #include "binding/ProtocolProvider.h"
38 #include "handler/LogoutInitiator.h"
39 #include "handler/SessionInitiator.h"
40 #include "remoting/ListenerService.h"
41 #include "util/DOMPropertySet.h"
42 #include "util/SPConstants.h"
43
44 #if defined(XMLTOOLING_LOG4SHIB)
45 # include <log4shib/PropertyConfigurator.hh>
46 #elif defined(XMLTOOLING_LOG4CPP)
47 # include <log4cpp/PropertyConfigurator.hh>
48 #else
49 # error "Supported logging library not available."
50 #endif
51 #include <algorithm>
52 #include <xercesc/util/XMLUniDefs.hpp>
53 #include <xercesc/util/XMLStringTokenizer.hpp>
54 #include <xmltooling/XMLToolingConfig.h>
55 #include <xmltooling/version.h>
56 #include <xmltooling/util/NDC.h>
57 #include <xmltooling/util/ReloadableXMLFile.h>
58 #include <xmltooling/util/TemplateEngine.h>
59 #include <xmltooling/util/Threads.h>
60 #include <xmltooling/util/XMLHelper.h>
61
62 #ifndef SHIBSP_LITE
63 # include "attribute/filtering/AttributeFilter.h"
64 # include "attribute/resolver/AttributeExtractor.h"
65 # include "attribute/resolver/AttributeResolver.h"
66 # include "security/PKIXTrustEngine.h"
67 # include "security/SecurityPolicyProvider.h"
68 # include <saml/SAMLConfig.h>
69 # include <saml/version.h>
70 # include <saml/binding/ArtifactMap.h>
71 # include <saml/binding/SAMLArtifact.h>
72 # include <saml/saml1/core/Assertions.h>
73 # include <saml/saml2/core/Assertions.h>
74 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
75 # include <saml/saml2/metadata/Metadata.h>
76 # include <saml/saml2/metadata/MetadataProvider.h>
77 # include <saml/util/SAMLConstants.h>
78 # include <xmltooling/security/ChainingTrustEngine.h>
79 # include <xmltooling/security/CredentialResolver.h>
80 # include <xmltooling/security/SecurityHelper.h>
81 # include <xmltooling/util/ReplayCache.h>
82 # include <xmltooling/util/StorageService.h>
83 # include <xsec/utils/XSECPlatformUtils.hpp>
84 using namespace opensaml::saml2;
85 using namespace opensaml::saml2p;
86 using namespace opensaml::saml2md;
87 using namespace opensaml;
88 #else
89 # include "lite/SAMLConstants.h"
90 #endif
91
92 using namespace shibsp;
93 using namespace xmltooling;
94 using namespace std;
95
96 #ifndef min
97 # define min(a,b)            (((a) < (b)) ? (a) : (b))
98 #endif
99
100 namespace {
101
102 #if defined (_MSC_VER)
103     #pragma warning( push )
104     #pragma warning( disable : 4250 )
105 #endif
106
107     static vector<const Handler*> g_noHandlers;
108
109     // Application configuration wrapper
110     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
111     {
112     public:
113         XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
114         ~XMLApplication() { cleanup(); }
115
116         const char* getHash() const {return m_hash.c_str();}
117
118 #ifndef SHIBSP_LITE
119         SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
120             throw ConfigurationException("No support for SAML 1.x artifact generation.");
121         }
122         SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
123             pair<bool,int> index = make_pair(false,0);
124             const PropertySet* props = getRelyingParty(relyingParty);
125             index = props->getInt("artifactEndpointIndex");
126             if (!index.first)
127                 index = getArtifactEndpointIndex();
128             pair<bool,const char*> entityID = props->getString("entityID");
129             return new SAML2ArtifactType0004(
130                 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
131                 index.first ? index.second : 1
132                 );
133         }
134
135         MetadataProvider* getMetadataProvider(bool required=true) const {
136             if (required && !m_base && !m_metadata)
137                 throw ConfigurationException("No MetadataProvider available.");
138             return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata;
139         }
140         TrustEngine* getTrustEngine(bool required=true) const {
141             if (required && !m_base && !m_trust)
142                 throw ConfigurationException("No TrustEngine available.");
143             return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust;
144         }
145         AttributeExtractor* getAttributeExtractor() const {
146             return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
147         }
148         AttributeFilter* getAttributeFilter() const {
149             return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
150         }
151         AttributeResolver* getAttributeResolver() const {
152             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
153         }
154         CredentialResolver* getCredentialResolver() const {
155             return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
156         }
157         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
158         const PropertySet* getRelyingParty(const XMLCh* entityID) const;
159         const vector<const XMLCh*>* getAudiences() const {
160             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
161         }
162 #endif
163         string getNotificationURL(const char* resource, bool front, unsigned int index) const;
164
165         const vector<string>& getRemoteUserAttributeIds() const {
166             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
167         }
168
169         void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
170         void setHeader(SPRequest& request, const char* name, const char* value) const;
171         string getSecureHeader(const SPRequest& request, const char* name) const;
172
173         const SessionInitiator* getDefaultSessionInitiator() const;
174         const SessionInitiator* getSessionInitiatorById(const char* id) const;
175         const Handler* getDefaultAssertionConsumerService() const;
176         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
177         const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
178         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
179         const Handler* getHandler(const char* path) const;
180         void getHandlers(vector<const Handler*>& handlers) const;
181
182         void receive(DDF& in, ostream& out) {
183             // Only current function is to return the headers to clear.
184             DDF header;
185             DDF ret=DDF(nullptr).list();
186             DDFJanitor jret(ret);
187             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
188                 header = DDF(i->first.c_str()).string(i->second.c_str());
189                 ret.add(header);
190             }
191             out << ret;
192         }
193
194         // Provides filter to exclude special config elements.
195 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
196         short
197 #else
198         FilterAction
199 #endif
200         acceptNode(const DOMNode* node) const;
201
202     private:
203         template <class T> T* doChainedPlugins(
204             PluginManager<T,string,const DOMElement*>& pluginMgr,
205             const char* pluginType,
206             const char* chainingType,
207             const XMLCh* localName,
208             DOMElement* e,
209             Category& log,
210             const char* dummyType=nullptr
211             );
212         void doAttributeInfo();
213         void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
214         void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
215         void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
216         void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
217         void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
218         void cleanup();
219         const XMLApplication* m_base;
220         string m_hash;
221         std::pair<std::string,std::string> m_attributePrefix;
222 #ifndef SHIBSP_LITE
223         void doAttributePlugins(DOMElement* e, Category& log);
224         MetadataProvider* m_metadata;
225         TrustEngine* m_trust;
226         AttributeExtractor* m_attrExtractor;
227         AttributeFilter* m_attrFilter;
228         AttributeResolver* m_attrResolver;
229         CredentialResolver* m_credResolver;
230         vector<const XMLCh*> m_audiences;
231
232         // RelyingParty properties
233         map<xstring,PropertySet*> m_partyMap;
234 #endif
235         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
236
237         // manage handler objects
238         vector<Handler*> m_handlers;
239
240         // maps location (path info) to applicable handlers
241         map<string,const Handler*> m_handlerMap;
242
243         // maps unique indexes to consumer services
244         map<unsigned int,const Handler*> m_acsIndexMap;
245
246         // pointer to default consumer service
247         const Handler* m_acsDefault;
248
249         // maps binding strings to supporting consumer service(s)
250         typedef map< xstring,vector<const Handler*> > ACSBindingMap;
251         ACSBindingMap m_acsBindingMap;
252
253         // maps protocol strings to supporting consumer service(s)
254         typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
255         ACSProtocolMap m_acsProtocolMap;
256
257         // pointer to default session initiator
258         const SessionInitiator* m_sessionInitDefault;
259
260         // maps unique ID strings to session initiators
261         map<string,const SessionInitiator*> m_sessionInitMap;
262
263         // pointer to default artifact resolution service
264         const Handler* m_artifactResolutionDefault;
265
266         pair<bool,int> getArtifactEndpointIndex() const {
267             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
268             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
269         }
270     };
271
272     // Top-level configuration implementation
273     class SHIBSP_DLLLOCAL XMLConfig;
274     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
275     {
276     public:
277         XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
278         ~XMLConfigImpl();
279
280         RequestMapper* m_requestMapper;
281         map<string,Application*> m_appmap;
282 #ifndef SHIBSP_LITE
283         TransactionLog* m_tranLog;
284         SecurityPolicyProvider* m_policy;
285         vector< pair< string, pair<string,string> > > m_transportOptions;
286 #endif
287
288         // Provides filter to exclude special config elements.
289 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
290         short
291 #else
292         FilterAction
293 #endif
294         acceptNode(const DOMNode* node) const;
295
296         void setDocument(DOMDocument* doc) {
297             m_document = doc;
298         }
299
300     private:
301         void doExtensions(const DOMElement*, const char*, Category&);
302         void doListener(const DOMElement*, XMLConfig*, Category&);
303         void doCaching(const DOMElement*, XMLConfig*, Category&);
304         void cleanup();
305
306         DOMDocument* m_document;
307     };
308
309     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
310 #ifndef SHIBSP_LITE
311         ,public Remoted
312 #endif
313     {
314     public:
315         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
316             m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr) {
317         }
318
319         void init() {
320             background_load();
321         }
322
323         ~XMLConfig() {
324             shutdown();
325             delete m_impl;
326             delete m_sessionCache;
327             delete m_listener;
328 #ifndef SHIBSP_LITE
329             SAMLConfig::getConfig().setArtifactMap(nullptr);
330             XMLToolingConfig::getConfig().setReplayCache(nullptr);
331             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
332 #endif
333         }
334
335 #ifndef SHIBSP_LITE
336         // Lockable
337         Lockable* lock() {
338             ReloadableXMLFile::lock();
339             if (m_impl->m_policy)
340                 m_impl->m_policy->lock();
341             return this;
342         }
343         void unlock() {
344             if (m_impl->m_policy)
345                 m_impl->m_policy->unlock();
346             ReloadableXMLFile::unlock();
347         }
348 #endif
349
350         // PropertySet
351         const PropertySet* getParent() const { return m_impl->getParent(); }
352         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
353         pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
354         pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
355         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
356         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
357         pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
358         void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
359         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
360         const DOMElement* getElement() const {return m_impl->getElement();}
361
362         // ServiceProvider
363 #ifndef SHIBSP_LITE
364         // Remoted
365         void receive(DDF& in, ostream& out);
366
367         TransactionLog* getTransactionLog() const {
368             if (m_impl->m_tranLog)
369                 return m_impl->m_tranLog;
370             throw ConfigurationException("No TransactionLog available.");
371         }
372
373         StorageService* getStorageService(const char* id) const {
374             if (id) {
375                 map<string,StorageService*>::const_iterator i=m_storage.find(id);
376                 if (i!=m_storage.end())
377                     return i->second;
378             }
379             else if (!m_storage.empty())
380                 return m_storage.begin()->second;
381             return nullptr;
382         }
383 #endif
384
385         ListenerService* getListenerService(bool required=true) const {
386             if (required && !m_listener)
387                 throw ConfigurationException("No ListenerService available.");
388             return m_listener;
389         }
390
391         SessionCache* getSessionCache(bool required=true) const {
392             if (required && !m_sessionCache)
393                 throw ConfigurationException("No SessionCache available.");
394             return m_sessionCache;
395         }
396
397         RequestMapper* getRequestMapper(bool required=true) const {
398             if (required && !m_impl->m_requestMapper)
399                 throw ConfigurationException("No RequestMapper available.");
400             return m_impl->m_requestMapper;
401         }
402
403         const Application* getApplication(const char* applicationId) const {
404             map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId ? applicationId : "default");
405             return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
406         }
407
408 #ifndef SHIBSP_LITE
409         SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
410             if (required && !m_impl->m_policy)
411                 throw ConfigurationException("No SecurityPolicyProvider available.");
412             return m_impl->m_policy;
413         }
414
415         const PropertySet* getPolicySettings(const char* id) const {
416             return getSecurityPolicyProvider()->getPolicySettings(id);
417         }
418
419         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
420             return getSecurityPolicyProvider()->getPolicyRules(id);
421         }
422
423         bool setTransportOptions(SOAPTransport& transport) const {
424             bool ret = true;
425             vector< pair< string, pair<string,string> > >::const_iterator opt;
426             for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
427                 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
428                     m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
429                     ret = false;
430                 }
431             }
432             return ret;
433         }
434 #endif
435
436     protected:
437         pair<bool,DOMElement*> background_load();
438
439     private:
440         friend class XMLConfigImpl;
441         XMLConfigImpl* m_impl;
442         ListenerService* m_listener;
443         SessionCache* m_sessionCache;
444 #ifndef SHIBSP_LITE
445         map<string,StorageService*> m_storage;
446 #endif
447     };
448
449 #if defined (_MSC_VER)
450     #pragma warning( pop )
451 #endif
452
453     static const XMLCh applicationId[] =        UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
454     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);
455     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);
456     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
457     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);
458     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
459     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
460     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);
461     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);
462     static const XMLCh _Audience[] =            UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
463     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
464     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
465     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);
466     static const XMLCh _default[] =             UNICODE_LITERAL_7(d,e,f,a,u,l,t);
467     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
468     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
469     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
470     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
471     static const XMLCh _index[] =               UNICODE_LITERAL_5(i,n,d,e,x);
472     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
473     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);
474     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
475     static const XMLCh Location[] =             UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
476     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);
477     static const XMLCh Logout[] =               UNICODE_LITERAL_6(L,o,g,o,u,t);
478     static const XMLCh _LogoutInitiator[] =     UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
479     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);
480     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
481     static const XMLCh NameIDMgmt[] =           UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
482     static const XMLCh Notify[] =               UNICODE_LITERAL_6(N,o,t,i,f,y);
483     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
484     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
485     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
486     static const XMLCh _ProtocolProvider[] =    UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
487     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
488     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
489     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
490     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
491     static const XMLCh RequestMap[] =           UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
492     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
493     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);
494     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
495     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
496     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);
497     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
498     static const XMLCh SSO[] =                  UNICODE_LITERAL_3(S,S,O);
499     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
500     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
501     static const XMLCh tranLogFiller[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
502     static const XMLCh tranLogFormat[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
503     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
504     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
505     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
506     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
507 };
508
509 namespace shibsp {
510     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
511     {
512         return new XMLConfig(e);
513     }
514 };
515
516 XMLApplication::XMLApplication(
517     const ServiceProvider* sp,
518     const ProtocolProvider* pp,
519     DOMElement* e,
520     const XMLApplication* base
521     ) : Application(sp), m_base(base),
522 #ifndef SHIBSP_LITE
523         m_metadata(nullptr), m_trust(nullptr),
524         m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
525         m_credResolver(nullptr),
526 #endif
527         m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
528 {
529 #ifdef _DEBUG
530     xmltooling::NDC ndc("XMLApplication");
531 #endif
532     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
533
534     try {
535         // First load any property sets.
536         load(e,nullptr,this);
537         if (base)
538             setParent(base);
539
540         SPConfig& conf=SPConfig::getConfig();
541 #ifndef SHIBSP_LITE
542         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
543 #endif
544
545         // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
546         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
547         string tohash=getId();
548         tohash+=getString("entityID").second;
549         for (const char* ch = tohash.c_str(); *ch; ++ch) {
550             m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
551             m_hash += (DIGITS[0x0F & *ch]);
552         }
553
554         doAttributeInfo();
555
556         if (conf.isEnabled(SPConfig::Handlers))
557             doHandlers(pp, e, log);
558
559         // Notification.
560         DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
561         for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
562             if (nlist->item(i)->getParentNode()->isSameNode(e)) {
563                 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
564                 string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
565                 if (!loc.empty()) {
566                     if (channel && *channel == chLatin_f)
567                         m_frontLogout.push_back(loc);
568                     else
569                         m_backLogout.push_back(loc);
570                 }
571             }
572         }
573
574 #ifndef SHIBSP_LITE
575         nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
576         if (nlist && nlist->getLength()) {
577             log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
578             for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
579                 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
580                     m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
581         }
582
583         if (conf.isEnabled(SPConfig::Metadata)) {
584             auto_ptr<MetadataProvider> mp(
585                 doChainedPlugins(
586                     SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
587                     )
588                 );
589             try {
590                 if (mp.get()) {
591                     mp->init();
592                     m_metadata = mp.release();
593                 }
594                 else if (!m_base) {
595                     log.crit("no MetadataProvider available, configuration is probably unusable");
596                 }
597             }
598             catch (exception& ex) {
599                 log.crit("error initializing MetadataProvider: %s", ex.what());
600             }
601         }
602
603         if (conf.isEnabled(SPConfig::Trust)) {
604             m_trust = doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log);
605             if (!m_trust && !m_base) {
606                 log.info(
607                     "no TrustEngine specified or installed, using default chain {%s, %s}",
608                     EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
609                     );
610                 m_trust = xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr);
611                 ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust);
612                 if (trustchain) {
613                     trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
614                     trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
615                 }
616             }
617         }
618
619         if (conf.isEnabled(SPConfig::AttributeResolution))
620             doAttributePlugins(e, log);
621
622         if (conf.isEnabled(SPConfig::Credentials)) {
623             m_credResolver = doChainedPlugins(
624                 xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log
625                 );
626         }
627
628         // Finally, load relying parties.
629         const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
630         while (child) {
631             if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
632                 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
633                 rp->load(child, nullptr, this);
634                 rp->setParent(this);
635                 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
636             }
637             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
638         }
639         if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
640             // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
641             child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
642             while (child) {
643                 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
644                     DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
645                     auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
646                     rp->load(rpclone, nullptr, this);
647                     rp->setParent(this);
648                     m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
649                 }
650                 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
651             }
652         }
653 #endif
654
655         // Out of process only, we register a listener endpoint.
656         if (!conf.isEnabled(SPConfig::InProcess)) {
657             ListenerService* listener = sp->getListenerService(false);
658             if (listener) {
659                 string addr=string(getId()) + "::getHeaders::Application";
660                 listener->regListener(addr.c_str(),this);
661             }
662             else {
663                 log.info("no ListenerService available, Application remoting disabled");
664             }
665         }
666     }
667     catch (exception&) {
668         cleanup();
669         throw;
670     }
671 #ifndef _DEBUG
672     catch (...) {
673         cleanup();
674         throw;
675     }
676 #endif
677 }
678
679 template <class T> T* XMLApplication::doChainedPlugins(
680     PluginManager<T,string,const DOMElement*>& pluginMgr,
681     const char* pluginType,
682     const char* chainingType,
683     const XMLCh* localName,
684     DOMElement* e,
685     Category& log,
686     const char* dummyType
687     )
688 {
689     string t;
690     DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
691     if (child) {
692         // Check for multiple.
693         if (XMLHelper::getNextSiblingElement(child, localName)) {
694             log.info("multiple %s plugins, wrapping in a chain", pluginType);
695             DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
696             while (child) {
697                 chain->appendChild(child);
698                 child = XMLHelper::getFirstChildElement(e, localName);
699             }
700             t = chainingType;
701             child = chain;
702             e->appendChild(chain);
703         }
704         else {
705             // Only a single one.
706             t = XMLHelper::getAttrString(child, nullptr, _type);
707         }
708
709         try {
710             if (!t.empty()) {
711                 log.info("building %s of type %s...", pluginType, t.c_str());
712                 return pluginMgr.newPlugin(t.c_str(), child);
713             }
714             else {
715                 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
716             }
717         }
718         catch (exception& ex) {
719             log.crit("error building %s: %s", pluginType, ex.what());
720             if (dummyType) {
721                 // Install a dummy version as a safety valve.
722                 log.crit("installing safe %s in place of failed version", pluginType);
723                 return pluginMgr.newPlugin(dummyType, nullptr);
724             }
725         }
726     }
727
728     return nullptr;
729 }
730
731 void XMLApplication::doAttributeInfo()
732 {
733     // Populate prefix pair.
734     m_attributePrefix.second = "HTTP_";
735     pair<bool,const char*> prefix = getString("attributePrefix");
736     if (prefix.first) {
737         m_attributePrefix.first = prefix.second;
738         const char* pch = prefix.second;
739         while (*pch) {
740             m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
741             pch++;
742         }
743     }
744
745     pair<bool,const char*> attributes = getString("REMOTE_USER");
746     if (attributes.first) {
747         char* dup = strdup(attributes.second);
748         char* pos;
749         char* start = dup;
750         while (start && *start) {
751             while (*start && isspace(*start))
752                 start++;
753             if (!*start)
754                 break;
755             pos = strchr(start,' ');
756             if (pos)
757                 *pos=0;
758             m_remoteUsers.push_back(start);
759             start = pos ? pos+1 : nullptr;
760         }
761         free(dup);
762     }
763
764     // Load attribute ID lists for REMOTE_USER and header clearing.
765     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
766         attributes = getString("unsetHeaders");
767         if (attributes.first) {
768             string transformedprefix(m_attributePrefix.second);
769             const char* pch;
770             prefix = getString("metadataAttributePrefix");
771             if (prefix.first) {
772                 pch = prefix.second;
773                 while (*pch) {
774                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
775                     pch++;
776                 }
777             }
778             char* dup = strdup(attributes.second);
779             char* pos;
780             char* start = dup;
781             while (start && *start) {
782                 while (*start && isspace(*start))
783                     start++;
784                 if (!*start)
785                     break;
786                 pos = strchr(start,' ');
787                 if (pos)
788                     *pos=0;
789
790                 string transformed;
791                 pch = start;
792                 while (*pch) {
793                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
794                     pch++;
795                 }
796
797                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
798                 if (prefix.first)
799                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
800                 start = pos ? pos+1 : nullptr;
801             }
802             free(dup);
803             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
804         }
805     }
806 }
807
808 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
809 {
810     SPConfig& conf = SPConfig::getConfig();
811
812     Handler* handler = nullptr;
813     const PropertySet* sessions = getPropertySet("Sessions");
814
815     // Process assertion export handler.
816     pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
817     if (location.first) {
818         try {
819             DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
820             exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
821             pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
822             if (exportACL.first) {
823                 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
824                 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
825             }
826             handler = conf.HandlerManager.newPlugin(
827                 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
828                 );
829             m_handlers.push_back(handler);
830
831             // Insert into location map. If it contains the handlerURL, we skip past that part.
832             const char* hurl = sessions->getString("handlerURL").second;
833             if (!hurl)
834                 hurl = "/Shibboleth.sso";
835             const char* pch = strstr(location.second, hurl);
836             if (pch)
837                 location.second = pch + strlen(hurl);
838             if (*location.second == '/')
839                 m_handlerMap[location.second]=handler;
840             else
841                 m_handlerMap[string("/") + location.second]=handler;
842         }
843         catch (exception& ex) {
844             log.error("caught exception installing assertion lookup handler: %s", ex.what());
845         }
846     }
847
848     // Look for "shorthand" elements first.
849     set<string> protocols;
850     DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
851     while (child) {
852         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
853             if (pp)
854                 doSSO(*pp, protocols, child, log);
855             else
856                 log.error("no ProtocolProvider, SSO auto-configure unsupported");
857         }
858         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
859             if (pp)
860                 doLogout(*pp, protocols, child, log);
861             else
862                 log.error("no ProtocolProvider, Logout auto-configure unsupported");
863         }
864         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
865             if (pp)
866                 doNameIDMgmt(*pp, protocols, child, log);
867             else
868                 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
869         }
870         else {
871             break;  // drop into next while loop
872         }
873         child = XMLHelper::getNextSiblingElement(child);
874     }
875
876     // Process other handlers.
877     bool hardACS=false, hardSessionInit=false, hardArt=false;
878     while (child) {
879         if (!child->hasAttributeNS(nullptr, Location)) {
880             auto_ptr_char hclass(child->getLocalName());
881             log.error("%s handler with no Location property cannot be processed", hclass.get());
882             child = XMLHelper::getNextSiblingElement(child);
883             continue;
884         }
885         try {
886             if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
887                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
888                 if (bindprop.empty()) {
889                     log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
890                     child = XMLHelper::getNextSiblingElement(child);
891                     continue;
892                 }
893                 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
894                 // Map by binding and protocol (may be > 1 per protocol and binding)
895                 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
896                 const XMLCh* protfamily = handler->getProtocolFamily();
897                 if (protfamily)
898                     m_acsProtocolMap[protfamily].push_back(handler);
899                 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
900
901                 if (!hardACS) {
902                     pair<bool,bool> defprop = handler->getBool("isDefault");
903                     if (defprop.first) {
904                         if (defprop.second) {
905                             hardACS = true;
906                             m_acsDefault = handler;
907                         }
908                     }
909                     else if (!m_acsDefault)
910                         m_acsDefault = handler;
911                 }
912             }
913             else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
914                 string t(XMLHelper::getAttrString(child, nullptr, _type));
915                 if (t.empty()) {
916                     log.error("SessionInitiator element has no type attribute, skipping it...");
917                     child = XMLHelper::getNextSiblingElement(child);
918                     continue;
919                 }
920                 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
921                 handler = sihandler;
922                 pair<bool,const char*> si_id = handler->getString("id");
923                 if (si_id.first && si_id.second)
924                     m_sessionInitMap[si_id.second] = sihandler;
925                 if (!hardSessionInit) {
926                     pair<bool,bool> defprop = handler->getBool("isDefault");
927                     if (defprop.first) {
928                         if (defprop.second) {
929                             hardSessionInit = true;
930                             m_sessionInitDefault = sihandler;
931                         }
932                     }
933                     else if (!m_sessionInitDefault) {
934                         m_sessionInitDefault = sihandler;
935                     }
936                 }
937             }
938             else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
939                 string t(XMLHelper::getAttrString(child, nullptr, _type));
940                 if (t.empty()) {
941                     log.error("LogoutInitiator element has no type attribute, skipping it...");
942                     child = XMLHelper::getNextSiblingElement(child);
943                     continue;
944                 }
945                 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
946             }
947             else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
948                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
949                 if (bindprop.empty()) {
950                     log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
951                     child = XMLHelper::getNextSiblingElement(child);
952                     continue;
953                 }
954                 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
955
956                 if (!hardArt) {
957                     pair<bool,bool> defprop = handler->getBool("isDefault");
958                     if (defprop.first) {
959                         if (defprop.second) {
960                             hardArt = true;
961                             m_artifactResolutionDefault = handler;
962                         }
963                     }
964                     else if (!m_artifactResolutionDefault)
965                         m_artifactResolutionDefault = handler;
966                 }
967             }
968             else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
969                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
970                 if (bindprop.empty()) {
971                     log.error("SingleLogoutService element has no Binding attribute, skipping it...");
972                     child = XMLHelper::getNextSiblingElement(child);
973                     continue;
974                 }
975                 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
976             }
977             else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
978                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
979                 if (bindprop.empty()) {
980                     log.error("ManageNameIDService element has no Binding attribute, skipping it...");
981                     child = XMLHelper::getNextSiblingElement(child);
982                     continue;
983                 }
984                 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId()));
985             }
986             else {
987                 string t(XMLHelper::getAttrString(child, nullptr, _type));
988                 if (t.empty()) {
989                     log.error("Handler element has no type attribute, skipping it...");
990                     child = XMLHelper::getNextSiblingElement(child);
991                     continue;
992                 }
993                 handler = conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()));
994             }
995
996             m_handlers.push_back(handler);
997
998             // Insert into location map.
999             location = handler->getString("Location");
1000             if (location.first && *location.second == '/')
1001                 m_handlerMap[location.second] = handler;
1002             else if (location.first)
1003                 m_handlerMap[string("/") + location.second] = handler;
1004         }
1005         catch (exception& ex) {
1006             log.error("caught exception processing handler element: %s", ex.what());
1007         }
1008
1009         child = XMLHelper::getNextSiblingElement(child);
1010     }
1011 }
1012
1013 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1014 {
1015     if (!e->hasChildNodes())
1016         return;
1017
1018     SPConfig& conf = SPConfig::getConfig();
1019
1020     // Tokenize the protocol list inside the element.
1021     XMLStringTokenizer prottokens(e->getTextContent());
1022     while (prottokens.hasMoreTokens()) {
1023         auto_ptr_char prot(prottokens.nextToken());
1024
1025         // Look for initiator.
1026         const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1027         if (initiator) {
1028             log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1029             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1030             if (inittype.first) {
1031                 // Append a session initiator element of the designated type to the root element.
1032                 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1033                 sidom->setAttributeNS(nullptr, _type, inittype.second);
1034                 e->appendChild(sidom);
1035                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1036
1037                 doArtifactResolution(pp, prot.get(), e, log);
1038                 protocols.insert(prot.get());
1039             }
1040             else {
1041                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1042             }
1043         }
1044
1045         // Look for incoming bindings.
1046         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1047         if (!bindings.empty()) {
1048             log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1049             int index = 0;
1050             pair<bool,const XMLCh*> idprop,pathprop;
1051             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1052                 idprop = (*b)->getXMLString("id");
1053                 pathprop = (*b)->getXMLString("path");
1054                 if (idprop.first && pathprop.first) {
1055                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1056                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1057                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1058                     xstring indexbuf(chDigit_1 + (index % 10), 1);
1059                     if (index / 10)
1060                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1061                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1062
1063                     log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1064                     Handler* handler = conf.AssertionConsumerServiceManager.newPlugin(
1065                         (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1066                         );
1067                     m_handlers.push_back(handler);
1068
1069                     // Setup maps and defaults.
1070                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1071                     const XMLCh* protfamily = handler->getProtocolFamily();
1072                     if (protfamily)
1073                         m_acsProtocolMap[protfamily].push_back(handler);
1074                     m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1075                     if (!m_acsDefault)
1076                         m_acsDefault = handler;
1077
1078                     // Insert into location map.
1079                     pair<bool,const char*> location = handler->getString("Location");
1080                     if (location.first && *location.second == '/')
1081                         m_handlerMap[location.second] = handler;
1082                     else if (location.first)
1083                         m_handlerMap[string("/") + location.second] = handler;
1084                 }
1085                 else {
1086                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1087                 }
1088             }
1089         }
1090
1091         if (!initiator && bindings.empty()) {
1092             log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1093         }
1094     }
1095
1096     // Handle discovery.
1097     static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1098     static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1099     static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1100     const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1101     if (discop && *discop) {
1102         const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1103         if (discou && *discou) {
1104             // Append a session initiator element of the designated type to the root element.
1105             DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1106             sidom->setAttributeNS(nullptr, _type, discop);
1107             sidom->setAttributeNS(nullptr, _URL, discou);
1108             e->appendChild(sidom);
1109             if (log.isInfoEnabled()) {
1110                 auto_ptr_char dp(discop);
1111                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1112             }
1113         }
1114         else {
1115             log.error("SSO discoveryProtocol specified without discoveryURL");
1116         }
1117     }
1118
1119     // Attach default Location to SSO element.
1120     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1121     e->setAttributeNS(nullptr, Location, _loc);
1122
1123     // Instantiate Chaining initiator around the SSO element.
1124     SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(
1125         CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1126         );
1127     m_handlers.push_back(chain);
1128     m_sessionInitDefault = chain;
1129     m_handlerMap["/Login"] = chain;
1130 }
1131
1132 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1133 {
1134     if (!e->hasChildNodes())
1135         return;
1136
1137     SPConfig& conf = SPConfig::getConfig();
1138
1139     // Tokenize the protocol list inside the element.
1140     XMLStringTokenizer prottokens(e->getTextContent());
1141     while (prottokens.hasMoreTokens()) {
1142         auto_ptr_char prot(prottokens.nextToken());
1143
1144         // Look for initiator.
1145         const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1146         if (initiator) {
1147             log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1148             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1149             if (inittype.first) {
1150                 // Append a logout initiator element of the designated type to the root element.
1151                 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1152                 lidom->setAttributeNS(nullptr, _type, inittype.second);
1153                 e->appendChild(lidom);
1154                 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1155
1156                 if (protocols.count(prot.get()) == 0) {
1157                     doArtifactResolution(pp, prot.get(), e, log);
1158                     protocols.insert(prot.get());
1159                 }
1160             }
1161             else {
1162                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1163             }
1164         }
1165
1166         // Look for incoming bindings.
1167         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1168         if (!bindings.empty()) {
1169             log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1170             pair<bool,const XMLCh*> idprop,pathprop;
1171             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1172                 idprop = (*b)->getXMLString("id");
1173                 pathprop = (*b)->getXMLString("path");
1174                 if (idprop.first && pathprop.first) {
1175                     DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1176                     slodom->setAttributeNS(nullptr, Binding, idprop.second);
1177                     slodom->setAttributeNS(nullptr, Location, pathprop.second);
1178
1179                     log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1180                     Handler* handler = conf.SingleLogoutServiceManager.newPlugin(
1181                         (*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId())
1182                         );
1183                     m_handlers.push_back(handler);
1184
1185                     // Insert into location map.
1186                     pair<bool,const char*> location = handler->getString("Location");
1187                     if (location.first && *location.second == '/')
1188                         m_handlerMap[location.second] = handler;
1189                     else if (location.first)
1190                         m_handlerMap[string("/") + location.second] = handler;
1191                 }
1192                 else {
1193                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1194                 }
1195             }
1196
1197             if (protocols.count(prot.get()) == 0) {
1198                 doArtifactResolution(pp, prot.get(), e, log);
1199                 protocols.insert(prot.get());
1200             }
1201         }
1202
1203         if (!initiator && bindings.empty()) {
1204             log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1205         }
1206     }
1207
1208     // Attach default Location to Logout element.
1209     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1210     e->setAttributeNS(nullptr, Location, _loc);
1211
1212     // Instantiate Chaining initiator around the SSO element.
1213     Handler* chain = conf.LogoutInitiatorManager.newPlugin(
1214         CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId())
1215         );
1216     m_handlers.push_back(chain);
1217     m_handlerMap["/Logout"] = chain;
1218 }
1219
1220 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1221 {
1222     if (!e->hasChildNodes())
1223         return;
1224
1225     SPConfig& conf = SPConfig::getConfig();
1226
1227     // Tokenize the protocol list inside the element.
1228     XMLStringTokenizer prottokens(e->getTextContent());
1229     while (prottokens.hasMoreTokens()) {
1230         auto_ptr_char prot(prottokens.nextToken());
1231
1232         // Look for incoming bindings.
1233         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1234         if (!bindings.empty()) {
1235             log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1236             pair<bool,const XMLCh*> idprop,pathprop;
1237             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1238                 idprop = (*b)->getXMLString("id");
1239                 pathprop = (*b)->getXMLString("path");
1240                 if (idprop.first && pathprop.first) {
1241                     DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1242                     nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1243                     nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1244
1245                     log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1246                     Handler* handler = conf.ManageNameIDServiceManager.newPlugin(
1247                         (*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId())
1248                         );
1249                     m_handlers.push_back(handler);
1250
1251                     // Insert into location map.
1252                     pair<bool,const char*> location = handler->getString("Location");
1253                     if (location.first && *location.second == '/')
1254                         m_handlerMap[location.second] = handler;
1255                     else if (location.first)
1256                         m_handlerMap[string("/") + location.second] = handler;
1257                 }
1258                 else {
1259                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1260                 }
1261             }
1262
1263             if (protocols.count(prot.get()) == 0) {
1264                 doArtifactResolution(pp, prot.get(), e, log);
1265                 protocols.insert(prot.get());
1266             }
1267         }
1268         else {
1269             log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1270         }
1271     }
1272 }
1273
1274 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1275 {
1276     SPConfig& conf = SPConfig::getConfig();
1277
1278     // Look for incoming bindings.
1279     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1280     if (!bindings.empty()) {
1281         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1282         int index = 0;
1283         pair<bool,const XMLCh*> idprop,pathprop;
1284         for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1285             idprop = (*b)->getXMLString("id");
1286             pathprop = (*b)->getXMLString("path");
1287             if (idprop.first && pathprop.first) {
1288                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1289                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1290                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1291                 xstring indexbuf(chDigit_1 + (index % 10), 1);
1292                 if (index / 10)
1293                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1294                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1295
1296                 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1297                 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin(
1298                     (*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId())
1299                     );
1300                 m_handlers.push_back(handler);
1301
1302                 if (!m_artifactResolutionDefault)
1303                     m_artifactResolutionDefault = handler;
1304
1305                 // Insert into location map.
1306                 pair<bool,const char*> location = handler->getString("Location");
1307                 if (location.first && *location.second == '/')
1308                     m_handlerMap[location.second] = handler;
1309                 else if (location.first)
1310                     m_handlerMap[string("/") + location.second] = handler;
1311             }
1312             else {
1313                 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1314             }
1315         }
1316     }
1317 }
1318
1319 #ifndef SHIBSP_LITE
1320 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1321 {
1322     SPConfig& conf = SPConfig::getConfig();
1323
1324     m_attrExtractor =
1325         doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log);
1326
1327     m_attrFilter =
1328         doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER);
1329
1330     m_attrResolver =
1331         doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log);
1332
1333     if (m_unsetHeaders.empty()) {
1334         vector<string> unsetHeaders;
1335         if (m_attrExtractor) {
1336             Locker extlock(m_attrExtractor);
1337             m_attrExtractor->getAttributeIds(unsetHeaders);
1338         }
1339         else if (m_base && m_base->m_attrExtractor) {
1340             Locker extlock(m_base->m_attrExtractor);
1341             m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1342         }
1343         if (m_attrResolver) {
1344             Locker reslock(m_attrResolver);
1345             m_attrResolver->getAttributeIds(unsetHeaders);
1346         }
1347         else if (m_base && m_base->m_attrResolver) {
1348             Locker extlock(m_base->m_attrResolver);
1349             m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1350         }
1351         if (!unsetHeaders.empty()) {
1352             string transformedprefix(m_attributePrefix.second);
1353             const char* pch;
1354             pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1355             if (prefix.first) {
1356                 pch = prefix.second;
1357                 while (*pch) {
1358                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1359                     pch++;
1360                 }
1361             }
1362             for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1363                 string transformed;
1364                 pch = hdr->c_str();
1365                 while (*pch) {
1366                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1367                     pch++;
1368                 }
1369                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1370                 if (prefix.first)
1371                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1372             }
1373         }
1374         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1375     }
1376 }
1377 #endif
1378
1379 void XMLApplication::cleanup()
1380 {
1381     ListenerService* listener=getServiceProvider().getListenerService(false);
1382     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1383         string addr=string(getId()) + "::getHeaders::Application";
1384         listener->unregListener(addr.c_str(),this);
1385     }
1386     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1387     m_handlers.clear();
1388 #ifndef SHIBSP_LITE
1389     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1390     m_partyMap.clear();
1391     delete m_credResolver;
1392     m_credResolver = nullptr;
1393     delete m_attrResolver;
1394     m_attrResolver = nullptr;
1395     delete m_attrFilter;
1396     m_attrFilter = nullptr;
1397     delete m_attrExtractor;
1398     m_attrExtractor = nullptr;
1399     delete m_trust;
1400     m_trust = nullptr;
1401     delete m_metadata;
1402     m_metadata = nullptr;
1403 #endif
1404 }
1405
1406 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1407 short
1408 #else
1409 DOMNodeFilter::FilterAction
1410 #endif
1411 XMLApplication::acceptNode(const DOMNode* node) const
1412 {
1413     const XMLCh* name=node->getLocalName();
1414     if (XMLString::equals(name,ApplicationOverride) ||
1415         XMLString::equals(name,_Audience) ||
1416         XMLString::equals(name,Notify) ||
1417         XMLString::equals(name,_Handler) ||
1418         XMLString::equals(name,_AssertionConsumerService) ||
1419         XMLString::equals(name,_ArtifactResolutionService) ||
1420         XMLString::equals(name,Logout) ||
1421         XMLString::equals(name,_LogoutInitiator) ||
1422         XMLString::equals(name,_ManageNameIDService) ||
1423         XMLString::equals(name,NameIDMgmt) ||
1424         XMLString::equals(name,_SessionInitiator) ||
1425         XMLString::equals(name,_SingleLogoutService) ||
1426         XMLString::equals(name,SSO) ||
1427         XMLString::equals(name,RelyingParty) ||
1428         XMLString::equals(name,_MetadataProvider) ||
1429         XMLString::equals(name,_TrustEngine) ||
1430         XMLString::equals(name,_CredentialResolver) ||
1431         XMLString::equals(name,_AttributeFilter) ||
1432         XMLString::equals(name,_AttributeExtractor) ||
1433         XMLString::equals(name,_AttributeResolver))
1434         return FILTER_REJECT;
1435
1436     return FILTER_ACCEPT;
1437 }
1438
1439 #ifndef SHIBSP_LITE
1440
1441 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1442 {
1443     if (!provider)
1444         return this;
1445
1446     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1447     if (i!=m_partyMap.end())
1448         return i->second;
1449     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1450     while (group) {
1451         if (group->getName()) {
1452             i=m_partyMap.find(group->getName());
1453             if (i!=m_partyMap.end())
1454                 return i->second;
1455         }
1456         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1457     }
1458     return this;
1459 }
1460
1461 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1462 {
1463     if (!entityID)
1464         return this;
1465
1466     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1467     if (i!=m_partyMap.end())
1468         return i->second;
1469     return this;
1470 }
1471
1472 #endif
1473
1474 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1475 {
1476     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1477     if (locs.empty())
1478         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1479     else if (index >= locs.size())
1480         return string();
1481
1482 #ifdef HAVE_STRCASECMP
1483     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1484 #else
1485     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1486 #endif
1487         throw ConfigurationException("Request URL was not absolute.");
1488
1489     const char* handler=locs[index].c_str();
1490
1491     // Should never happen...
1492     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1493         throw ConfigurationException(
1494             "Invalid Location property ($1) in Notify element for Application ($2)",
1495             params(2, handler ? handler : "null", getId())
1496             );
1497
1498     // The "Location" property can be in one of three formats:
1499     //
1500     // 1) a full URI:       http://host/foo/bar
1501     // 2) a hostless URI:   http:///foo/bar
1502     // 3) a relative path:  /foo/bar
1503     //
1504     // #  Protocol  Host        Path
1505     // 1  handler   handler     handler
1506     // 2  handler   resource    handler
1507     // 3  resource  resource    handler
1508
1509     const char* path = nullptr;
1510
1511     // Decide whether to use the handler or the resource for the "protocol"
1512     const char* prot;
1513     if (*handler != '/') {
1514         prot = handler;
1515     }
1516     else {
1517         prot = resource;
1518         path = handler;
1519     }
1520
1521     // break apart the "protocol" string into protocol, host, and "the rest"
1522     const char* colon=strchr(prot,':');
1523     colon += 3;
1524     const char* slash=strchr(colon,'/');
1525     if (!path)
1526         path = slash;
1527
1528     // Compute the actual protocol and store.
1529     string notifyURL(prot, colon-prot);
1530
1531     // create the "host" from either the colon/slash or from the target string
1532     // If prot == handler then we're in either #1 or #2, else #3.
1533     // If slash == colon then we're in #2.
1534     if (prot != handler || slash == colon) {
1535         colon = strchr(resource, ':');
1536         colon += 3;      // Get past the ://
1537         slash = strchr(colon, '/');
1538     }
1539     string host(colon, (slash ? slash-colon : strlen(colon)));
1540
1541     // Build the URL
1542     notifyURL += host + path;
1543     return notifyURL;
1544 }
1545
1546 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1547 {
1548     if (!m_attributePrefix.first.empty()) {
1549         string temp = m_attributePrefix.first + rawname;
1550         string temp2 = m_attributePrefix.second + (cginame + 5);
1551         request.clearHeader(temp.c_str(), temp2.c_str());
1552     }
1553     else if (m_base) {
1554         m_base->clearHeader(request, rawname, cginame);
1555     }
1556     else {
1557         request.clearHeader(rawname, cginame);
1558     }
1559 }
1560
1561 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1562 {
1563     if (!m_attributePrefix.first.empty()) {
1564         string temp = m_attributePrefix.first + name;
1565         request.setHeader(temp.c_str(), value);
1566     }
1567     else if (m_base) {
1568         m_base->setHeader(request, name, value);
1569     }
1570     else {
1571         request.setHeader(name, value);
1572     }
1573 }
1574
1575 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1576 {
1577     if (!m_attributePrefix.first.empty()) {
1578         string temp = m_attributePrefix.first + name;
1579         return request.getSecureHeader(temp.c_str());
1580     }
1581     else if (m_base) {
1582         return m_base->getSecureHeader(request,name);
1583     }
1584     else {
1585         return request.getSecureHeader(name);
1586     }
1587 }
1588
1589 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1590 {
1591     if (m_sessionInitDefault) return m_sessionInitDefault;
1592     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1593 }
1594
1595 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1596 {
1597     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1598     if (i!=m_sessionInitMap.end()) return i->second;
1599     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1600 }
1601
1602 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1603 {
1604     if (m_acsDefault) return m_acsDefault;
1605     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1606 }
1607
1608 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1609 {
1610     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1611     if (i != m_acsIndexMap.end()) return i->second;
1612     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1613 }
1614
1615 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1616 {
1617     ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1618     if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1619         if (!binding || !*binding)
1620             return i->second.front();
1621         for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1622             if (!strcmp(binding, (*j)->getString("Binding").second))
1623                 return *j;
1624         }
1625     }
1626     return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1627 }
1628
1629 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1630 {
1631     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1632     if (i != m_acsBindingMap.end())
1633         return i->second;
1634     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1635 }
1636
1637 const Handler* XMLApplication::getHandler(const char* path) const
1638 {
1639     string wrap(path);
1640     wrap = wrap.substr(0,wrap.find(';'));
1641     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1642     if (i!=m_handlerMap.end())
1643         return i->second;
1644     return m_base ? m_base->getHandler(path) : nullptr;
1645 }
1646
1647 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1648 {
1649     handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1650     if (m_base) {
1651         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1652             if (m_handlerMap.count(h->first) == 0)
1653                 handlers.push_back(h->second);
1654         }
1655     }
1656 }
1657
1658 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1659 short
1660 #else
1661 DOMNodeFilter::FilterAction
1662 #endif
1663 XMLConfigImpl::acceptNode(const DOMNode* node) const
1664 {
1665     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1666         return FILTER_ACCEPT;
1667     const XMLCh* name=node->getLocalName();
1668     if (XMLString::equals(name,ApplicationDefaults) ||
1669         XMLString::equals(name,_ArtifactMap) ||
1670         XMLString::equals(name,_Extensions) ||
1671         XMLString::equals(name,Listener) ||
1672         XMLString::equals(name,_ProtocolProvider) ||
1673         XMLString::equals(name,_RequestMapper) ||
1674         XMLString::equals(name,_ReplayCache) ||
1675         XMLString::equals(name,SecurityPolicies) ||
1676         XMLString::equals(name,_SecurityPolicyProvider) ||
1677         XMLString::equals(name,_SessionCache) ||
1678         XMLString::equals(name,Site) ||
1679         XMLString::equals(name,_StorageService) ||
1680         XMLString::equals(name,TCPListener) ||
1681         XMLString::equals(name,TransportOption) ||
1682         XMLString::equals(name,UnixListener))
1683         return FILTER_REJECT;
1684
1685     return FILTER_ACCEPT;
1686 }
1687
1688 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1689 {
1690     const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1691     if (exts) {
1692         exts = XMLHelper::getFirstChildElement(exts, Library);
1693         while (exts) {
1694             string path(XMLHelper::getAttrString(exts, nullptr, _path));
1695             try {
1696                 if (!path.empty()) {
1697                     if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1698                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1699                     log.debug("loaded %s extension library (%s)", label, path.c_str());
1700                 }
1701             }
1702             catch (exception& e) {
1703                 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1704                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1705                     throw;
1706                 }
1707                 else {
1708                     log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1709                 }
1710             }
1711             exts = XMLHelper::getNextSiblingElement(exts, Library);
1712         }
1713     }
1714 }
1715
1716 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1717 {
1718 #ifdef WIN32
1719     string plugtype(TCP_LISTENER_SERVICE);
1720 #else
1721     string plugtype(UNIX_LISTENER_SERVICE);
1722 #endif
1723     DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1724     if (child)
1725         plugtype = UNIX_LISTENER_SERVICE;
1726     else {
1727         child = XMLHelper::getFirstChildElement(e, TCPListener);
1728         if (child)
1729             plugtype = TCP_LISTENER_SERVICE;
1730         else {
1731             child = XMLHelper::getFirstChildElement(e, Listener);
1732             if (child) {
1733                 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1734                 if (type.get() && *type.get())
1735                     plugtype = type.get();
1736             }
1737         }
1738     }
1739
1740     log.info("building ListenerService of type %s...", plugtype.c_str());
1741     conf->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1742 }
1743
1744 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1745 {
1746     SPConfig& spConf = SPConfig::getConfig();
1747 #ifndef SHIBSP_LITE
1748     SAMLConfig& samlConf = SAMLConfig::getConfig();
1749 #endif
1750
1751     DOMElement* child;
1752 #ifndef SHIBSP_LITE
1753     if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1754         XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1755         // First build any StorageServices.
1756         child = XMLHelper::getFirstChildElement(e, _StorageService);
1757         while (child) {
1758             string id(XMLHelper::getAttrString(child, nullptr, _id));
1759             string t(XMLHelper::getAttrString(child, nullptr, _type));
1760             if (!t.empty()) {
1761                 try {
1762                     log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1763                     conf->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1764                 }
1765                 catch (exception& ex) {
1766                     log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1767                 }
1768             }
1769             child = XMLHelper::getNextSiblingElement(child, _StorageService);
1770         }
1771
1772         if (conf->m_storage.empty()) {
1773             log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1774             conf->m_storage["mem"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1775         }
1776
1777         // Replay cache.
1778         StorageService* replaySS = nullptr;
1779         child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1780         if (child) {
1781             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1782             if (!ssid.empty()) {
1783                 if (conf->m_storage.count(ssid)) {
1784                     log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1785                     replaySS = conf->m_storage[ssid];
1786                 }
1787                 else {
1788                     log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1789                     replaySS = conf->m_storage.begin()->second;
1790                 }
1791             }
1792             else {
1793                 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1794                 replaySS = conf->m_storage.begin()->second;
1795             }
1796         }
1797         else {
1798             log.info("no ReplayCache specified, using arbitrary StorageService instance");
1799             replaySS = conf->m_storage.begin()->second;
1800         }
1801         xmlConf.setReplayCache(new ReplayCache(replaySS));
1802
1803         // ArtifactMap
1804         child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1805         if (child) {
1806             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1807             if (!ssid.empty()) {
1808                 if (conf->m_storage.count(ssid)) {
1809                     log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1810                     samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid]));
1811                 }
1812                 else {
1813                     log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1814                     samlConf.setArtifactMap(new ArtifactMap(child));
1815                 }
1816             }
1817             else {
1818                 log.info("no StorageService specified, using in-memory ArtifactMap");
1819                 samlConf.setArtifactMap(new ArtifactMap(child));
1820             }
1821         }
1822         else {
1823             log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1824             samlConf.setArtifactMap(new ArtifactMap(child));
1825         }
1826     }   // end of out of process caching components
1827 #endif
1828
1829     child = XMLHelper::getFirstChildElement(e, _SessionCache);
1830     if (child) {
1831         string t(XMLHelper::getAttrString(child, nullptr, _type));
1832         if (!t.empty()) {
1833             log.info("building SessionCache of type %s...", t.c_str());
1834             conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(t.c_str(), child);
1835         }
1836     }
1837     if (!conf->m_sessionCache) {
1838         log.info("no SessionCache specified, using StorageService-backed instance");
1839         conf->m_sessionCache = spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1840     }
1841 }
1842
1843 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log)
1844     : m_requestMapper(nullptr),
1845 #ifndef SHIBSP_LITE
1846         m_tranLog(nullptr),
1847         m_policy(nullptr),
1848 #endif
1849         m_document(nullptr)
1850 {
1851 #ifdef _DEBUG
1852     xmltooling::NDC ndc("XMLConfigImpl");
1853 #endif
1854
1855     try {
1856         SPConfig& conf=SPConfig::getConfig();
1857         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1858         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1859         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1860
1861         // Initialize logging manually in order to redirect log messages as soon as possible.
1862         if (conf.isEnabled(SPConfig::Logging)) {
1863             string logconf;
1864             if (conf.isEnabled(SPConfig::OutOfProcess))
1865                 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1866             else if (conf.isEnabled(SPConfig::InProcess))
1867                 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1868             if (logconf.empty())
1869                 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1870             if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1871                 // No properties found, so default them.
1872                 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1873                     logconf = "shibd.logger";
1874                 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1875                     logconf = "native.logger";
1876                 else
1877                     logconf = "shibboleth.logger";
1878             }
1879             if (!logconf.empty()) {
1880                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1881                 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1882                     log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1883             }
1884
1885 #ifndef SHIBSP_LITE
1886             m_tranLog = new TransactionLog(
1887                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1888                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1889                 );
1890 #endif
1891         }
1892
1893         // Re-log library versions now that logging is set up.
1894         log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1895 #ifndef SHIBSP_LITE
1896         log.info(
1897             "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1898 # if defined(LOG4SHIB_VERSION)
1899         "log4shib", LOG4SHIB_VERSION,
1900 # elif defined(LOG4CPP_VERSION)
1901         "log4cpp", LOG4CPP_VERSION,
1902 # else
1903         "", "",
1904 # endif
1905             XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1906             );
1907 #else
1908         log.info(
1909             "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1910 # if defined(LOG4SHIB_VERSION)
1911         "log4shib", LOG4SHIB_VERSION,
1912 # elif defined(LOG4CPP_VERSION)
1913         "log4cpp", LOG4CPP_VERSION,
1914 # else
1915         "", "",
1916 # endif
1917             XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1918             );
1919 #endif
1920
1921         // First load any property sets.
1922         load(e,nullptr,this);
1923
1924         DOMElement* child;
1925
1926         // Much of the processing can only occur on the first instantiation.
1927         if (first) {
1928             // Set clock skew.
1929             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1930             if (skew.first)
1931                 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1932
1933             pair<bool,const char*> unsafe = getString("unsafeChars");
1934             if (unsafe.first)
1935                 TemplateEngine::unsafe_chars = unsafe.second;
1936
1937             unsafe = getString("allowedSchemes");
1938             if (unsafe.first) {
1939                 HTTPResponse::getAllowedSchemes().clear();
1940                 string schemes=unsafe.second;
1941                 unsigned int j_sch=0;
1942                 for (unsigned int i_sch=0;  i_sch < schemes.length();  i_sch++) {
1943                     if (schemes.at(i_sch)==' ') {
1944                         HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1945                         j_sch = i_sch + 1;
1946                     }
1947                 }
1948                 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1949             }
1950
1951             // Extensions
1952             doExtensions(e, "global", log);
1953             if (conf.isEnabled(SPConfig::OutOfProcess))
1954                 doExtensions(SHAR, "out of process", log);
1955
1956             if (conf.isEnabled(SPConfig::InProcess))
1957                 doExtensions(SHIRE, "in process", log);
1958
1959             // Instantiate the ListenerService and SessionCache objects.
1960             if (conf.isEnabled(SPConfig::Listener))
1961                 doListener(e, outer, log);
1962
1963 #ifndef SHIBSP_LITE
1964             if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1965                 outer->m_listener->regListener("set::RelayState", outer);
1966                 outer->m_listener->regListener("get::RelayState", outer);
1967                 outer->m_listener->regListener("set::PostData", outer);
1968                 outer->m_listener->regListener("get::PostData", outer);
1969             }
1970 #endif
1971             if (conf.isEnabled(SPConfig::Caching))
1972                 doCaching(e, outer, log);
1973         } // end of first-time-only stuff
1974
1975         // Back to the fully dynamic stuff...next up is the RequestMapper.
1976         if (conf.isEnabled(SPConfig::RequestMapping)) {
1977             if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1978                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1979                 if (!t.empty()) {
1980                     log.info("building RequestMapper of type %s...", t.c_str());
1981                     m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1982                 }
1983             }
1984             if (!m_requestMapper) {
1985                 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1986                 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1987                 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1988                 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1989                 child->appendChild(mapperDummy);
1990                 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1991             }
1992         }
1993
1994 #ifndef SHIBSP_LITE
1995         // Load security policies.
1996         if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1997             string t(XMLHelper::getAttrString(child, nullptr, _type));
1998             if (!t.empty()) {
1999                 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2000                 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
2001             }
2002             else {
2003                 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2004             }
2005         }
2006         else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2007             // For backward compatibility, wrap in a plugin element.
2008             DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2009             polwrapper->appendChild(child);
2010             log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2011             m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
2012         }
2013         else {
2014             log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2015             throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2016         }
2017
2018         if (first) {
2019             if (!m_policy->getAlgorithmBlacklist().empty()) {
2020 #ifdef SHIBSP_XMLSEC_WHITELISTING
2021                 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2022                     XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2023 #else
2024                 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2025 #endif
2026             }
2027             else if (!m_policy->getAlgorithmWhitelist().empty()) {
2028 #ifdef SHIBSP_XMLSEC_WHITELISTING
2029                 for (vector<xstring>::const_iterator alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2030                     XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2031 #else
2032                 log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2033 #endif
2034             }
2035         }
2036
2037         // Process TransportOption elements.
2038         child = XMLHelper::getLastChildElement(e, TransportOption);
2039         while (child) {
2040             if (child->hasChildNodes()) {
2041                 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2042                 string option(XMLHelper::getAttrString(child, nullptr, _option));
2043                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2044                 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2045                     m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2046                 }
2047             }
2048             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2049         }
2050 #endif
2051
2052         ProtocolProvider* pp = nullptr;
2053         if (conf.isEnabled(SPConfig::Handlers)) {
2054             if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2055                 string t(XMLHelper::getAttrString(child, nullptr, _type));
2056                 if (!t.empty()) {
2057                     log.info("building ProtocolProvider of type %s...", t.c_str());
2058                     pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2059                 }
2060             }
2061         }
2062         auto_ptr<ProtocolProvider> ppwrapper(pp);
2063         Locker pplocker(pp);
2064
2065         // Load the default application.
2066         child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2067         if (!child) {
2068             log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2069             throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2070         }
2071         XMLApplication* defapp = new XMLApplication(outer, pp, child);
2072         m_appmap[defapp->getId()] = defapp;
2073
2074         // Load any overrides.
2075         child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2076         while (child) {
2077             auto_ptr<XMLApplication> iapp(new XMLApplication(outer, pp, child, defapp));
2078             if (m_appmap.count(iapp->getId()))
2079                 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2080             else {
2081                 const char* iappid=iapp->getId();
2082                 m_appmap[iappid] = iapp.release();
2083             }
2084
2085             child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2086         }
2087
2088         // Check for extra AuthTypes to recognize.
2089         if (conf.isEnabled(SPConfig::InProcess)) {
2090             const PropertySet* inprocs = getPropertySet("InProcess");
2091             if (inprocs) {
2092                 pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2093                 if (extraAuthTypes.first) {
2094                     string types=extraAuthTypes.second;
2095                     unsigned int j_types=0;
2096                     for (unsigned int i_types=0;  i_types < types.length();  i_types++) {
2097                         if (types.at(i_types) == ' ') {
2098                             outer->m_authTypes.insert(types.substr(j_types, i_types - j_types));
2099                             j_types = i_types + 1;
2100                         }
2101                     }
2102                     outer->m_authTypes.insert(types.substr(j_types, types.length() - j_types));
2103                 }
2104             }
2105         }
2106     }
2107     catch (exception&) {
2108         cleanup();
2109         throw;
2110     }
2111 }
2112
2113 XMLConfigImpl::~XMLConfigImpl()
2114 {
2115     cleanup();
2116 }
2117
2118 void XMLConfigImpl::cleanup()
2119 {
2120     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2121     m_appmap.clear();
2122 #ifndef SHIBSP_LITE
2123     delete m_policy;
2124     m_policy = nullptr;
2125     delete m_tranLog;
2126     m_tranLog = nullptr;
2127 #endif
2128     delete m_requestMapper;
2129     m_requestMapper = nullptr;
2130     if (m_document)
2131         m_document->release();
2132     m_document = nullptr;
2133 }
2134
2135 #ifndef SHIBSP_LITE
2136 void XMLConfig::receive(DDF& in, ostream& out)
2137 {
2138     if (!strcmp(in.name(), "get::RelayState")) {
2139         const char* id = in["id"].string();
2140         const char* key = in["key"].string();
2141         if (!id || !key)
2142             throw ListenerException("Required parameters missing for RelayState recovery.");
2143
2144         string relayState;
2145         StorageService* storage = getStorageService(id);
2146         if (storage) {
2147             if (storage->readString("RelayState",key,&relayState)>0) {
2148                 if (in["clear"].integer())
2149                     storage->deleteString("RelayState",key);
2150             }
2151             else if (storage->readText("RelayState",key,&relayState)>0) {
2152                 if (in["clear"].integer())
2153                     storage->deleteText("RelayState",key);
2154             }
2155         }
2156         else {
2157             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2158                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2159                 );
2160         }
2161
2162         // Repack for return to caller.
2163         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2164         DDFJanitor jret(ret);
2165         out << ret;
2166     }
2167     else if (!strcmp(in.name(), "set::RelayState")) {
2168         const char* id = in["id"].string();
2169         const char* value = in["value"].string();
2170         if (!id || !value)
2171             throw ListenerException("Required parameters missing for RelayState creation.");
2172
2173         string rsKey;
2174         StorageService* storage = getStorageService(id);
2175         if (storage) {
2176             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2177             rsKey = SAMLArtifact::toHex(rsKey);
2178             if (strlen(value) <= storage->getCapabilities().getStringSize())
2179                 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2180             else
2181                 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2182         }
2183         else {
2184             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2185                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2186                 );
2187         }
2188
2189         // Repack for return to caller.
2190         DDF ret=DDF(nullptr).string(rsKey.c_str());
2191         DDFJanitor jret(ret);
2192         out << ret;
2193     }
2194     else if (!strcmp(in.name(), "get::PostData")) {
2195         const char* id = in["id"].string();
2196         const char* key = in["key"].string();
2197         if (!id || !key)
2198             throw ListenerException("Required parameters missing for PostData recovery.");
2199
2200         string postData;
2201         StorageService* storage = getStorageService(id);
2202         if (storage) {
2203             if (storage->readText("PostData",key,&postData) > 0) {
2204                 storage->deleteText("PostData",key);
2205             }
2206         }
2207         else {
2208             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2209                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2210                 );
2211         }
2212         // If the data's empty, we'll send nothing back.
2213         // If not, we don't need to round trip it, just send back the serialized DDF list.
2214         if (postData.empty()) {
2215             DDF ret(nullptr);
2216             DDFJanitor jret(ret);
2217             out << ret;
2218         }
2219         else {
2220             out << postData;
2221         }
2222     }
2223     else if (!strcmp(in.name(), "set::PostData")) {
2224         const char* id = in["id"].string();
2225         if (!id || !in["parameters"].islist())
2226             throw ListenerException("Required parameters missing for PostData creation.");
2227
2228         string rsKey;
2229         StorageService* storage = getStorageService(id);
2230         if (storage) {
2231             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2232             rsKey = SAMLArtifact::toHex(rsKey);
2233             ostringstream params;
2234             params << in["parameters"];
2235             storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2236         }
2237         else {
2238             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2239                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2240                 );
2241         }
2242
2243         // Repack for return to caller.
2244         DDF ret=DDF(nullptr).string(rsKey.c_str());
2245         DDFJanitor jret(ret);
2246         out << ret;
2247     }
2248 }
2249 #endif
2250
2251 pair<bool,DOMElement*> XMLConfig::background_load()
2252 {
2253     // Load from source using base class.
2254     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2255
2256     // If we own it, wrap it.
2257     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2258
2259     XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2260
2261     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2262     impl->setDocument(docjanitor.release());
2263
2264     // Perform the swap inside a lock.
2265     if (m_lock)
2266         m_lock->wrlock();
2267     SharedLock locker(m_lock, false);
2268     delete m_impl;
2269     m_impl = impl;
2270
2271     return make_pair(false,(DOMElement*)nullptr);
2272 }