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