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