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