https://issues.shibboleth.net/jira/browse/SSPCPP-210
[shibboleth/cpp-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             if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
651                 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
652                 rp->load(child, nullptr, this);
653                 rp->setParent(this);
654                 m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
655             }
656             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
657         }
658         if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
659             // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
660             child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
661             while (child) {
662                 if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
663                     DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
664                     auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
665                     rp->load(rpclone, nullptr, this);
666                     rp->setParent(this);
667                     m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp.release();
668                 }
669                 child = XMLHelper::getNextSiblingElement(child, RelyingParty);
670             }
671         }
672 #endif
673
674         // Out of process only, we register a listener endpoint.
675         if (!conf.isEnabled(SPConfig::InProcess)) {
676             ListenerService* listener = sp->getListenerService(false);
677             if (listener) {
678                 string addr=string(getId()) + "::getHeaders::Application";
679                 listener->regListener(addr.c_str(),this);
680             }
681             else {
682                 log.info("no ListenerService available, Application remoting disabled");
683             }
684         }
685     }
686     catch (exception&) {
687         cleanup();
688         throw;
689     }
690 #ifndef _DEBUG
691     catch (...) {
692         cleanup();
693         throw;
694     }
695 #endif
696 }
697
698 void XMLApplication::doAttributeInfo()
699 {
700     // Populate prefix pair.
701     m_attributePrefix.second = "HTTP_";
702     pair<bool,const char*> prefix = getString("attributePrefix");
703     if (prefix.first) {
704         m_attributePrefix.first = prefix.second;
705         const char* pch = prefix.second;
706         while (*pch) {
707             m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
708             pch++;
709         }
710     }
711
712     // Load attribute ID lists for REMOTE_USER and header clearing.
713     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
714         pair<bool,const char*> attributes = getString("REMOTE_USER");
715         if (attributes.first) {
716             char* dup = strdup(attributes.second);
717             char* pos;
718             char* start = dup;
719             while (start && *start) {
720                 while (*start && isspace(*start))
721                     start++;
722                 if (!*start)
723                     break;
724                 pos = strchr(start,' ');
725                 if (pos)
726                     *pos=0;
727                 m_remoteUsers.push_back(start);
728                 start = pos ? pos+1 : nullptr;
729             }
730             free(dup);
731         }
732
733         attributes = getString("unsetHeaders");
734         if (attributes.first) {
735             string transformedprefix(m_attributePrefix.second);
736             const char* pch;
737             prefix = getString("metadataAttributePrefix");
738             if (prefix.first) {
739                 pch = prefix.second;
740                 while (*pch) {
741                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
742                     pch++;
743                 }
744             }
745             char* dup = strdup(attributes.second);
746             char* pos;
747             char* start = dup;
748             while (start && *start) {
749                 while (*start && isspace(*start))
750                     start++;
751                 if (!*start)
752                     break;
753                 pos = strchr(start,' ');
754                 if (pos)
755                     *pos=0;
756
757                 string transformed;
758                 pch = start;
759                 while (*pch) {
760                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
761                     pch++;
762                 }
763
764                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
765                 if (prefix.first)
766                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
767                 start = pos ? pos+1 : nullptr;
768             }
769             free(dup);
770             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
771         }
772     }
773 }
774
775 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
776 {
777     SPConfig& conf = SPConfig::getConfig();
778
779     Handler* handler = nullptr;
780     const PropertySet* sessions = getPropertySet("Sessions");
781
782     // Process assertion export handler.
783     pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
784     if (location.first) {
785         try {
786             DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
787             exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
788             pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
789             if (exportACL.first) {
790                 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
791                 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
792             }
793             handler = conf.HandlerManager.newPlugin(
794                 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
795                 );
796             m_handlers.push_back(handler);
797
798             // Insert into location map. If it contains the handlerURL, we skip past that part.
799             const char* hurl = sessions->getString("handlerURL").second;
800             if (!hurl)
801                 hurl = "/Shibboleth.sso";
802             const char* pch = strstr(location.second, hurl);
803             if (pch)
804                 location.second = pch + strlen(hurl);
805             if (*location.second == '/')
806                 m_handlerMap[location.second]=handler;
807             else
808                 m_handlerMap[string("/") + location.second]=handler;
809         }
810         catch (exception& ex) {
811             log.error("caught exception installing assertion lookup handler: %s", ex.what());
812         }
813     }
814
815     // Look for "shorthand" elements first.
816     set<string> protocols;
817     DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
818     while (child) {
819         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
820             if (pp)
821                 doSSO(*pp, protocols, child, log);
822             else
823                 log.error("no ProtocolProvider, SSO auto-configure unsupported");
824         }
825         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
826             if (pp)
827                 doLogout(*pp, protocols, child, log);
828             else
829                 log.error("no ProtocolProvider, Logout auto-configure unsupported");
830         }
831         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
832             if (pp)
833                 doNameIDMgmt(*pp, protocols, child, log);
834             else
835                 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
836         }
837         else {
838             break;  // drop into next while loop
839         }
840         child = XMLHelper::getNextSiblingElement(child);
841     }
842
843     // Process other handlers.
844     bool hardACS=false, hardSessionInit=false, hardArt=false;
845     while (child) {
846         if (!child->hasAttributeNS(nullptr, Location)) {
847             auto_ptr_char hclass(child->getLocalName());
848             log.error("%s handler with no Location property cannot be processed", hclass.get());
849             child = XMLHelper::getNextSiblingElement(child);
850             continue;
851         }
852         try {
853             if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
854                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
855                 if (bindprop.empty()) {
856                     log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
857                     child = XMLHelper::getNextSiblingElement(child);
858                     continue;
859                 }
860                 handler = conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
861                 // Map by binding and protocol (may be > 1 per protocol and binding)
862                 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
863                 const XMLCh* protfamily = handler->getProtocolFamily();
864                 if (protfamily)
865                     m_acsProtocolMap[protfamily].push_back(handler);
866                 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
867
868                 if (!hardACS) {
869                     pair<bool,bool> defprop = handler->getBool("isDefault");
870                     if (defprop.first) {
871                         if (defprop.second) {
872                             hardACS = true;
873                             m_acsDefault = handler;
874                         }
875                     }
876                     else if (!m_acsDefault)
877                         m_acsDefault = handler;
878                 }
879             }
880             else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
881                 string t(XMLHelper::getAttrString(child, nullptr, _type));
882                 if (t.empty()) {
883                     log.error("SessionInitiator element has no type attribute, skipping it...");
884                     child = XMLHelper::getNextSiblingElement(child);
885                     continue;
886                 }
887                 SessionInitiator* sihandler = conf.SessionInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
888                 handler = sihandler;
889                 pair<bool,const char*> si_id = handler->getString("id");
890                 if (si_id.first && si_id.second)
891                     m_sessionInitMap[si_id.second] = sihandler;
892                 if (!hardSessionInit) {
893                     pair<bool,bool> defprop = handler->getBool("isDefault");
894                     if (defprop.first) {
895                         if (defprop.second) {
896                             hardSessionInit = true;
897                             m_sessionInitDefault = sihandler;
898                         }
899                     }
900                     else if (!m_sessionInitDefault) {
901                         m_sessionInitDefault = sihandler;
902                     }
903                 }
904             }
905             else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
906                 string t(XMLHelper::getAttrString(child, nullptr, _type));
907                 if (t.empty()) {
908                     log.error("LogoutInitiator element has no type attribute, skipping it...");
909                     child = XMLHelper::getNextSiblingElement(child);
910                     continue;
911                 }
912                 handler = conf.LogoutInitiatorManager.newPlugin(t.c_str(), make_pair(child, getId()));
913             }
914             else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
915                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
916                 if (bindprop.empty()) {
917                     log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
918                     child = XMLHelper::getNextSiblingElement(child);
919                     continue;
920                 }
921                 handler = conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
922
923                 if (!hardArt) {
924                     pair<bool,bool> defprop = handler->getBool("isDefault");
925                     if (defprop.first) {
926                         if (defprop.second) {
927                             hardArt = true;
928                             m_artifactResolutionDefault = handler;
929                         }
930                     }
931                     else if (!m_artifactResolutionDefault)
932                         m_artifactResolutionDefault = handler;
933                 }
934             }
935             else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
936                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
937                 if (bindprop.empty()) {
938                     log.error("SingleLogoutService element has no Binding attribute, skipping it...");
939                     child = XMLHelper::getNextSiblingElement(child);
940                     continue;
941                 }
942                 handler = conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
943             }
944             else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
945                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
946                 if (bindprop.empty()) {
947                     log.error("ManageNameIDService element has no Binding attribute, skipping it...");
948                     child = XMLHelper::getNextSiblingElement(child);
949                     continue;
950                 }
951                 handler = conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), make_pair(child, getId()));
952             }
953             else {
954                 string t(XMLHelper::getAttrString(child, nullptr, _type));
955                 if (t.empty()) {
956                     log.error("Handler element has no type attribute, skipping it...");
957                     child = XMLHelper::getNextSiblingElement(child);
958                     continue;
959                 }
960                 handler = conf.HandlerManager.newPlugin(t.c_str(), make_pair(child, getId()));
961             }
962
963             m_handlers.push_back(handler);
964
965             // Insert into location map.
966             location = handler->getString("Location");
967             if (location.first && *location.second == '/')
968                 m_handlerMap[location.second] = handler;
969             else if (location.first)
970                 m_handlerMap[string("/") + location.second] = handler;
971         }
972         catch (exception& ex) {
973             log.error("caught exception processing handler element: %s", ex.what());
974         }
975
976         child = XMLHelper::getNextSiblingElement(child);
977     }
978 }
979
980 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
981 {
982     if (!e->hasChildNodes())
983         return;
984
985     SPConfig& conf = SPConfig::getConfig();
986
987     // Tokenize the protocol list inside the element.
988     const XMLCh* protlist = e->getFirstChild()->getNodeValue();
989     XMLStringTokenizer prottokens(protlist);
990     while (prottokens.hasMoreTokens()) {
991         auto_ptr_char prot(prottokens.nextToken());
992
993         // Look for initiator.
994         const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
995         if (initiator) {
996             log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
997             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
998             if (inittype.first) {
999                 // Append a session initiator element of the designated type to the root element.
1000                 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1001                 sidom->setAttributeNS(nullptr, _type, inittype.second);
1002                 e->appendChild(sidom);
1003                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1004
1005                 doArtifactResolution(pp, prot.get(), e, log);
1006                 protocols.insert(prot.get());
1007             }
1008             else {
1009                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1010             }
1011         }
1012
1013         // Look for incoming bindings.
1014         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1015         if (!bindings.empty()) {
1016             log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1017             int index = 0;
1018             pair<bool,const XMLCh*> idprop,pathprop;
1019             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1020                 idprop = (*b)->getXMLString("id");
1021                 pathprop = (*b)->getXMLString("path");
1022                 if (idprop.first && pathprop.first) {
1023                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1024                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1025                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1026                     xstring indexbuf(chDigit_1 + (index % 10), 1);
1027                     if (index / 10)
1028                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1029                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1030
1031                     log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1032                     Handler* handler = conf.AssertionConsumerServiceManager.newPlugin((*b)->getString("id").second, make_pair(acsdom, getId()));
1033                     m_handlers.push_back(handler);
1034
1035                     // Setup maps and defaults.
1036                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
1037                     const XMLCh* protfamily = handler->getProtocolFamily();
1038                     if (protfamily)
1039                         m_acsProtocolMap[protfamily].push_back(handler);
1040                     m_acsIndexMap[handler->getUnsignedInt("index").second] = handler;
1041                     if (!m_acsDefault)
1042                         m_acsDefault = handler;
1043
1044                     // Insert into location map.
1045                     pair<bool,const char*> location = handler->getString("Location");
1046                     if (location.first && *location.second == '/')
1047                         m_handlerMap[location.second] = handler;
1048                     else if (location.first)
1049                         m_handlerMap[string("/") + location.second] = handler;
1050                 }
1051                 else {
1052                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1053                 }
1054             }
1055         }
1056
1057         if (!initiator && bindings.empty()) {
1058             log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1059         }
1060     }
1061
1062     // Handle discovery.
1063     static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1064     static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1065     static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1066     const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1067     if (discop && *discop) {
1068         const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1069         if (discou && *discou) {
1070             // Append a session initiator element of the designated type to the root element.
1071             DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1072             sidom->setAttributeNS(nullptr, _type, discop);
1073             sidom->setAttributeNS(nullptr, _URL, discou);
1074             e->appendChild(sidom);
1075             if (log.isInfoEnabled()) {
1076                 auto_ptr_char dp(discop);
1077                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1078             }
1079         }
1080         else {
1081             log.error("SSO discoveryProtocol specified without discoveryURL");
1082         }
1083     }
1084
1085     // Attach default Location to SSO element.
1086     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1087     e->setAttributeNS(nullptr, Location, _loc);
1088
1089     // Instantiate Chaining initiator around the SSO element.
1090     SessionInitiator* chain = conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, make_pair(e, getId()));
1091     m_handlers.push_back(chain);
1092     m_sessionInitDefault = chain;
1093     m_handlerMap["/Login"] = chain;
1094 }
1095
1096 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1097 {
1098     if (!e->hasChildNodes())
1099         return;
1100
1101     SPConfig& conf = SPConfig::getConfig();
1102
1103     // Tokenize the protocol list inside the element.
1104     const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1105     XMLStringTokenizer prottokens(protlist);
1106     while (prottokens.hasMoreTokens()) {
1107         auto_ptr_char prot(prottokens.nextToken());
1108
1109         // Look for initiator.
1110         const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1111         if (initiator) {
1112             log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1113             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1114             if (inittype.first) {
1115                 // Append a logout initiator element of the designated type to the root element.
1116                 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1117                 lidom->setAttributeNS(nullptr, _type, inittype.second);
1118                 e->appendChild(lidom);
1119                 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1120
1121                 if (protocols.count(prot.get()) == 0) {
1122                     doArtifactResolution(pp, prot.get(), e, log);
1123                     protocols.insert(prot.get());
1124                 }
1125             }
1126             else {
1127                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1128             }
1129         }
1130
1131         // Look for incoming bindings.
1132         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1133         if (!bindings.empty()) {
1134             log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1135             pair<bool,const XMLCh*> idprop,pathprop;
1136             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1137                 idprop = (*b)->getXMLString("id");
1138                 pathprop = (*b)->getXMLString("path");
1139                 if (idprop.first && pathprop.first) {
1140                     DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1141                     slodom->setAttributeNS(nullptr, Binding, idprop.second);
1142                     slodom->setAttributeNS(nullptr, Location, pathprop.second);
1143
1144                     log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1145                     Handler* handler = conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, make_pair(slodom, getId()));
1146                     m_handlers.push_back(handler);
1147
1148                     // Insert into location map.
1149                     pair<bool,const char*> location = handler->getString("Location");
1150                     if (location.first && *location.second == '/')
1151                         m_handlerMap[location.second] = handler;
1152                     else if (location.first)
1153                         m_handlerMap[string("/") + location.second] = handler;
1154                 }
1155                 else {
1156                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1157                 }
1158             }
1159
1160             if (protocols.count(prot.get()) == 0) {
1161                 doArtifactResolution(pp, prot.get(), e, log);
1162                 protocols.insert(prot.get());
1163             }
1164         }
1165
1166         if (!initiator && bindings.empty()) {
1167             log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1168         }
1169     }
1170
1171     // Attach default Location to Logout element.
1172     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1173     e->setAttributeNS(nullptr, Location, _loc);
1174
1175     // Instantiate Chaining initiator around the SSO element.
1176     Handler* chain = conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, make_pair(e, getId()));
1177     m_handlers.push_back(chain);
1178     m_handlerMap["/Logout"] = chain;
1179 }
1180
1181 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1182 {
1183     if (!e->hasChildNodes())
1184         return;
1185
1186     SPConfig& conf = SPConfig::getConfig();
1187
1188     // Tokenize the protocol list inside the element.
1189     const XMLCh* protlist = e->getFirstChild()->getNodeValue();
1190     XMLStringTokenizer prottokens(protlist);
1191     while (prottokens.hasMoreTokens()) {
1192         auto_ptr_char prot(prottokens.nextToken());
1193
1194         // Look for incoming bindings.
1195         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1196         if (!bindings.empty()) {
1197             log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1198             pair<bool,const XMLCh*> idprop,pathprop;
1199             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1200                 idprop = (*b)->getXMLString("id");
1201                 pathprop = (*b)->getXMLString("path");
1202                 if (idprop.first && pathprop.first) {
1203                     DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1204                     nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1205                     nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1206
1207                     log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1208                     Handler* handler = conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, make_pair(nimdom, getId()));
1209                     m_handlers.push_back(handler);
1210
1211                     // Insert into location map.
1212                     pair<bool,const char*> location = handler->getString("Location");
1213                     if (location.first && *location.second == '/')
1214                         m_handlerMap[location.second] = handler;
1215                     else if (location.first)
1216                         m_handlerMap[string("/") + location.second] = handler;
1217                 }
1218                 else {
1219                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1220                 }
1221             }
1222
1223             if (protocols.count(prot.get()) == 0) {
1224                 doArtifactResolution(pp, prot.get(), e, log);
1225                 protocols.insert(prot.get());
1226             }
1227         }
1228         else {
1229             log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1230         }
1231     }
1232 }
1233
1234 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1235 {
1236     SPConfig& conf = SPConfig::getConfig();
1237
1238     // Look for incoming bindings.
1239     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1240     if (!bindings.empty()) {
1241         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1242         int index = 0;
1243         pair<bool,const XMLCh*> idprop,pathprop;
1244         for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1245             idprop = (*b)->getXMLString("id");
1246             pathprop = (*b)->getXMLString("path");
1247             if (idprop.first && pathprop.first) {
1248                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1249                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1250                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1251                 xstring indexbuf(chDigit_1 + (index % 10), 1);
1252                 if (index / 10)
1253                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1254                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1255
1256                 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1257                 Handler* handler = conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, make_pair(artdom, getId()));
1258                 m_handlers.push_back(handler);
1259
1260                 if (!m_artifactResolutionDefault)
1261                     m_artifactResolutionDefault = handler;
1262
1263                 // Insert into location map.
1264                 pair<bool,const char*> location = handler->getString("Location");
1265                 if (location.first && *location.second == '/')
1266                     m_handlerMap[location.second] = handler;
1267                 else if (location.first)
1268                     m_handlerMap[string("/") + location.second] = handler;
1269             }
1270             else {
1271                 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1272             }
1273         }
1274     }
1275 }
1276
1277 #ifndef SHIBSP_LITE
1278 void XMLApplication::doAttributePlugins(const DOMElement* e, Category& log)
1279 {
1280     SPConfig& conf = SPConfig::getConfig();
1281
1282     DOMElement* child = XMLHelper::getFirstChildElement(e, _AttributeExtractor);
1283     if (child) {
1284         string t(XMLHelper::getAttrString(child, nullptr, _type));
1285         try {
1286             if (!t.empty()) {
1287                 log.info("building AttributeExtractor of type %s...", t.c_str());
1288                 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(t.c_str(), child);
1289             }
1290             else {
1291                 throw ConfigurationException("AttributeExtractor element had no type attribute.");
1292             }
1293         }
1294         catch (exception& ex) {
1295             log.crit("error building AttributeExtractor: %s", ex.what());
1296         }
1297     }
1298
1299     child = XMLHelper::getFirstChildElement(e, _AttributeFilter);
1300     if (child) {
1301         string t(XMLHelper::getAttrString(child, nullptr, _type));
1302         try {
1303             if (!t.empty()) {
1304                 log.info("building AttributeFilter of type %s...", t.c_str());
1305                 m_attrFilter = conf.AttributeFilterManager.newPlugin(t.c_str(), child);
1306             }
1307             else {
1308                 throw ConfigurationException("AttributeFilter element had no type attribute.");
1309             }
1310         }
1311         catch (exception& ex) {
1312             log.crit("error building AttributeFilter: %s", ex.what());
1313         }
1314     }
1315
1316     child = XMLHelper::getFirstChildElement(e, _AttributeResolver);
1317     if (child) {
1318         string t(XMLHelper::getAttrString(child, nullptr, _type));
1319         try {
1320             if (!t.empty()) {
1321                 log.info("building AttributeResolver of type %s...", t.c_str());
1322                 m_attrResolver = conf.AttributeResolverManager.newPlugin(t.c_str(), child);
1323             }
1324             else {
1325                 throw ConfigurationException("AttributeResolver element had no type attribute.");
1326             }
1327         }
1328         catch (exception& ex) {
1329             log.crit("error building AttributeResolver: %s", ex.what());
1330         }
1331     }
1332
1333     if (m_unsetHeaders.empty()) {
1334         vector<string> unsetHeaders;
1335         if (m_attrExtractor) {
1336             Locker extlock(m_attrExtractor);
1337             m_attrExtractor->getAttributeIds(unsetHeaders);
1338         }
1339         else if (m_base && m_base->m_attrExtractor) {
1340             Locker extlock(m_base->m_attrExtractor);
1341             m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1342         }
1343         if (m_attrResolver) {
1344             Locker reslock(m_attrResolver);
1345             m_attrResolver->getAttributeIds(unsetHeaders);
1346         }
1347         else if (m_base && m_base->m_attrResolver) {
1348             Locker extlock(m_base->m_attrResolver);
1349             m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1350         }
1351         if (!unsetHeaders.empty()) {
1352             string transformedprefix(m_attributePrefix.second);
1353             const char* pch;
1354             pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1355             if (prefix.first) {
1356                 pch = prefix.second;
1357                 while (*pch) {
1358                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1359                     pch++;
1360                 }
1361             }
1362             for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1363                 string transformed;
1364                 pch = hdr->c_str();
1365                 while (*pch) {
1366                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1367                     pch++;
1368                 }
1369                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1370                 if (prefix.first)
1371                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1372             }
1373         }
1374         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1375     }
1376 }
1377 #endif
1378
1379 void XMLApplication::cleanup()
1380 {
1381     ListenerService* listener=getServiceProvider().getListenerService(false);
1382     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
1383         string addr=string(getId()) + "::getHeaders::Application";
1384         listener->unregListener(addr.c_str(),this);
1385     }
1386     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
1387     m_handlers.clear();
1388 #ifndef SHIBSP_LITE
1389     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
1390     m_partyMap.clear();
1391     delete m_credResolver;
1392     m_credResolver = nullptr;
1393     delete m_attrResolver;
1394     m_attrResolver = nullptr;
1395     delete m_attrFilter;
1396     m_attrFilter = nullptr;
1397     delete m_attrExtractor;
1398     m_attrExtractor = nullptr;
1399     delete m_trust;
1400     m_trust = nullptr;
1401     delete m_metadata;
1402     m_metadata = nullptr;
1403 #endif
1404 }
1405
1406 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1407 short
1408 #else
1409 DOMNodeFilter::FilterAction
1410 #endif
1411 XMLApplication::acceptNode(const DOMNode* node) const
1412 {
1413     const XMLCh* name=node->getLocalName();
1414     if (XMLString::equals(name,ApplicationOverride) ||
1415         XMLString::equals(name,_Audience) ||
1416         XMLString::equals(name,Notify) ||
1417         XMLString::equals(name,_Handler) ||
1418         XMLString::equals(name,_AssertionConsumerService) ||
1419         XMLString::equals(name,_ArtifactResolutionService) ||
1420         XMLString::equals(name,Logout) ||
1421         XMLString::equals(name,_LogoutInitiator) ||
1422         XMLString::equals(name,_ManageNameIDService) ||
1423         XMLString::equals(name,NameIDMgmt) ||
1424         XMLString::equals(name,_SessionInitiator) ||
1425         XMLString::equals(name,_SingleLogoutService) ||
1426         XMLString::equals(name,SSO) ||
1427         XMLString::equals(name,RelyingParty) ||
1428         XMLString::equals(name,_MetadataProvider) ||
1429         XMLString::equals(name,_TrustEngine) ||
1430         XMLString::equals(name,_CredentialResolver) ||
1431         XMLString::equals(name,_AttributeFilter) ||
1432         XMLString::equals(name,_AttributeExtractor) ||
1433         XMLString::equals(name,_AttributeResolver))
1434         return FILTER_REJECT;
1435
1436     return FILTER_ACCEPT;
1437 }
1438
1439 #ifndef SHIBSP_LITE
1440
1441 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1442 {
1443     if (!provider)
1444         return this;
1445
1446     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1447     if (i!=m_partyMap.end())
1448         return i->second;
1449     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1450     while (group) {
1451         if (group->getName()) {
1452             i=m_partyMap.find(group->getName());
1453             if (i!=m_partyMap.end())
1454                 return i->second;
1455         }
1456         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1457     }
1458     return this;
1459 }
1460
1461 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1462 {
1463     if (!entityID)
1464         return this;
1465
1466     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1467     if (i!=m_partyMap.end())
1468         return i->second;
1469     return this;
1470 }
1471
1472 #endif
1473
1474 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1475 {
1476     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1477     if (locs.empty())
1478         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1479     else if (index >= locs.size())
1480         return string();
1481
1482 #ifdef HAVE_STRCASECMP
1483     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1484 #else
1485     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1486 #endif
1487         throw ConfigurationException("Request URL was not absolute.");
1488
1489     const char* handler=locs[index].c_str();
1490
1491     // Should never happen...
1492     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1493         throw ConfigurationException(
1494             "Invalid Location property ($1) in Notify element for Application ($2)",
1495             params(2, handler ? handler : "null", getId())
1496             );
1497
1498     // The "Location" property can be in one of three formats:
1499     //
1500     // 1) a full URI:       http://host/foo/bar
1501     // 2) a hostless URI:   http:///foo/bar
1502     // 3) a relative path:  /foo/bar
1503     //
1504     // #  Protocol  Host        Path
1505     // 1  handler   handler     handler
1506     // 2  handler   resource    handler
1507     // 3  resource  resource    handler
1508
1509     const char* path = nullptr;
1510
1511     // Decide whether to use the handler or the resource for the "protocol"
1512     const char* prot;
1513     if (*handler != '/') {
1514         prot = handler;
1515     }
1516     else {
1517         prot = resource;
1518         path = handler;
1519     }
1520
1521     // break apart the "protocol" string into protocol, host, and "the rest"
1522     const char* colon=strchr(prot,':');
1523     colon += 3;
1524     const char* slash=strchr(colon,'/');
1525     if (!path)
1526         path = slash;
1527
1528     // Compute the actual protocol and store.
1529     string notifyURL(prot, colon-prot);
1530
1531     // create the "host" from either the colon/slash or from the target string
1532     // If prot == handler then we're in either #1 or #2, else #3.
1533     // If slash == colon then we're in #2.
1534     if (prot != handler || slash == colon) {
1535         colon = strchr(resource, ':');
1536         colon += 3;      // Get past the ://
1537         slash = strchr(colon, '/');
1538     }
1539     string host(colon, (slash ? slash-colon : strlen(colon)));
1540
1541     // Build the URL
1542     notifyURL += host + path;
1543     return notifyURL;
1544 }
1545
1546 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1547 {
1548     if (!m_attributePrefix.first.empty()) {
1549         string temp = m_attributePrefix.first + rawname;
1550         string temp2 = m_attributePrefix.second + (cginame + 5);
1551         request.clearHeader(temp.c_str(), temp2.c_str());
1552     }
1553     else if (m_base) {
1554         m_base->clearHeader(request, rawname, cginame);
1555     }
1556     else {
1557         request.clearHeader(rawname, cginame);
1558     }
1559 }
1560
1561 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1562 {
1563     if (!m_attributePrefix.first.empty()) {
1564         string temp = m_attributePrefix.first + name;
1565         request.setHeader(temp.c_str(), value);
1566     }
1567     else if (m_base) {
1568         m_base->setHeader(request, name, value);
1569     }
1570     else {
1571         request.setHeader(name, value);
1572     }
1573 }
1574
1575 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1576 {
1577     if (!m_attributePrefix.first.empty()) {
1578         string temp = m_attributePrefix.first + name;
1579         return request.getSecureHeader(temp.c_str());
1580     }
1581     else if (m_base) {
1582         return m_base->getSecureHeader(request,name);
1583     }
1584     else {
1585         return request.getSecureHeader(name);
1586     }
1587 }
1588
1589 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1590 {
1591     if (m_sessionInitDefault) return m_sessionInitDefault;
1592     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1593 }
1594
1595 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1596 {
1597     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1598     if (i!=m_sessionInitMap.end()) return i->second;
1599     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1600 }
1601
1602 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1603 {
1604     if (m_acsDefault) return m_acsDefault;
1605     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1606 }
1607
1608 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1609 {
1610     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1611     if (i != m_acsIndexMap.end()) return i->second;
1612     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1613 }
1614
1615 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1616 {
1617     ACSProtocolMap::const_iterator i=m_acsProtocolMap.find(protocol);
1618     if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1619         if (!binding || !*binding)
1620             return i->second.front();
1621         for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1622             if (!strcmp(binding, (*j)->getString("Binding").second))
1623                 return *j;
1624         }
1625     }
1626     return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol) : nullptr;
1627 }
1628
1629 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1630 {
1631     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1632     if (i != m_acsBindingMap.end())
1633         return i->second;
1634     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1635 }
1636
1637 const Handler* XMLApplication::getHandler(const char* path) const
1638 {
1639     string wrap(path);
1640     wrap = wrap.substr(0,wrap.find(';'));
1641     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1642     if (i!=m_handlerMap.end())
1643         return i->second;
1644     return m_base ? m_base->getHandler(path) : nullptr;
1645 }
1646
1647 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1648 {
1649     handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1650     if (m_base) {
1651         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1652             if (m_handlerMap.count(h->first) == 0)
1653                 handlers.push_back(h->second);
1654         }
1655     }
1656 }
1657
1658 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1659 short
1660 #else
1661 DOMNodeFilter::FilterAction
1662 #endif
1663 XMLConfigImpl::acceptNode(const DOMNode* node) const
1664 {
1665     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1666         return FILTER_ACCEPT;
1667     const XMLCh* name=node->getLocalName();
1668     if (XMLString::equals(name,ApplicationDefaults) ||
1669         XMLString::equals(name,_ArtifactMap) ||
1670         XMLString::equals(name,_Extensions) ||
1671         XMLString::equals(name,Listener) ||
1672         XMLString::equals(name,_ProtocolProvider) ||
1673         XMLString::equals(name,_RequestMapper) ||
1674         XMLString::equals(name,_ReplayCache) ||
1675         XMLString::equals(name,SecurityPolicies) ||
1676         XMLString::equals(name,_SecurityPolicyProvider) ||
1677         XMLString::equals(name,_SessionCache) ||
1678         XMLString::equals(name,Site) ||
1679         XMLString::equals(name,_StorageService) ||
1680         XMLString::equals(name,TCPListener) ||
1681         XMLString::equals(name,TransportOption) ||
1682         XMLString::equals(name,UnixListener))
1683         return FILTER_REJECT;
1684
1685     return FILTER_ACCEPT;
1686 }
1687
1688 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1689 {
1690     const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1691     if (exts) {
1692         exts = XMLHelper::getFirstChildElement(exts, Library);
1693         while (exts) {
1694             string path(XMLHelper::getAttrString(exts, nullptr, _path));
1695             try {
1696                 if (!path.empty()) {
1697                     if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1698                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1699                     log.debug("loaded %s extension library (%s)", label, path.c_str());
1700                 }
1701             }
1702             catch (exception& e) {
1703                 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1704                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1705                     throw;
1706                 }
1707                 else {
1708                     log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1709                 }
1710             }
1711             exts = XMLHelper::getNextSiblingElement(exts, Library);
1712         }
1713     }
1714 }
1715
1716 void XMLConfigImpl::doListener(const DOMElement* e, Category& log)
1717 {
1718 #ifdef WIN32
1719     string plugtype(TCP_LISTENER_SERVICE);
1720 #else
1721     string plugtype(UNIX_LISTENER_SERVICE);
1722 #endif
1723     DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1724     if (child)
1725         plugtype = UNIX_LISTENER_SERVICE;
1726     else {
1727         child = XMLHelper::getFirstChildElement(e, TCPListener);
1728         if (child)
1729             plugtype = TCP_LISTENER_SERVICE;
1730         else {
1731             child = XMLHelper::getFirstChildElement(e, Listener);
1732             if (child) {
1733                 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1734                 if (type.get() && *type.get())
1735                     plugtype = type.get();
1736             }
1737         }
1738     }
1739
1740     log.info("building ListenerService of type %s...", plugtype.c_str());
1741     m_outer->m_listener = SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1742 }
1743
1744 void XMLConfigImpl::doCaching(const DOMElement* e, Category& log)
1745 {
1746     SPConfig& conf = SPConfig::getConfig();
1747 #ifndef SHIBSP_LITE
1748     SAMLConfig& samlConf = SAMLConfig::getConfig();
1749 #endif
1750     XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1751
1752     DOMElement* child;
1753 #ifndef SHIBSP_LITE
1754     if (conf.isEnabled(SPConfig::OutOfProcess)) {
1755         // First build any StorageServices.
1756         child = XMLHelper::getFirstChildElement(e, _StorageService);
1757         while (child) {
1758             string id(XMLHelper::getAttrString(child, nullptr, _id));
1759             string t(XMLHelper::getAttrString(child, nullptr, _type));
1760             if (!t.empty()) {
1761                 try {
1762                     log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1763                     m_outer->m_storage[id] = xmlConf.StorageServiceManager.newPlugin(t.c_str(), child);
1764                 }
1765                 catch (exception& ex) {
1766                     log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1767                 }
1768             }
1769             child = XMLHelper::getNextSiblingElement(child, _StorageService);
1770         }
1771
1772         if (m_outer->m_storage.empty()) {
1773             log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1774             m_outer->m_storage["id"] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr);
1775         }
1776
1777         // Replay cache.
1778         StorageService* replaySS = nullptr;
1779         child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1780         if (child) {
1781             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1782             if (!ssid.empty()) {
1783                 if (m_outer->m_storage.count(ssid)) {
1784                     log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1785                     replaySS = m_outer->m_storage[ssid];
1786                 }
1787                 else {
1788                     log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1789                     replaySS = m_outer->m_storage.begin()->second;
1790                 }
1791             }
1792             else {
1793                 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1794                 replaySS = m_outer->m_storage.begin()->second;
1795             }
1796         }
1797         else {
1798             log.info("no ReplayCache specified, using arbitrary StorageService instance");
1799             replaySS = m_outer->m_storage.begin()->second;
1800         }
1801         xmlConf.setReplayCache(new ReplayCache(replaySS));
1802
1803         // ArtifactMap
1804         child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1805         if (child) {
1806             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1807             if (!ssid.empty()) {
1808                 if (m_outer->m_storage.count(ssid)) {
1809                     log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1810                     samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid]));
1811                 }
1812                 else {
1813                     log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1814                     samlConf.setArtifactMap(new ArtifactMap(child));
1815                 }
1816             }
1817             else {
1818                 log.info("no StorageService specified, using in-memory ArtifactMap");
1819                 samlConf.setArtifactMap(new ArtifactMap(child));
1820             }
1821         }
1822         else {
1823             log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1824             samlConf.setArtifactMap(new ArtifactMap(child));
1825         }
1826     }   // end of out of process caching components
1827 #endif
1828
1829     child = XMLHelper::getFirstChildElement(e, _SessionCache);
1830     if (child) {
1831         string t(XMLHelper::getAttrString(child, nullptr, _type));
1832         if (!t.empty()) {
1833             log.info("building SessionCache of type %s...", t.c_str());
1834             m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(t.c_str(), child);
1835         }
1836     }
1837     if (!m_outer->m_sessionCache) {
1838         log.info("no SessionCache specified, using StorageService-backed instance");
1839         m_outer->m_sessionCache = conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr);
1840     }
1841 }
1842
1843 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1844     : m_requestMapper(nullptr),
1845 #ifndef SHIBSP_LITE
1846         m_policy(nullptr),
1847 #endif
1848         m_outer(outer), m_document(nullptr)
1849 {
1850 #ifdef _DEBUG
1851     xmltooling::NDC ndc("XMLConfigImpl");
1852 #endif
1853
1854     try {
1855         SPConfig& conf=SPConfig::getConfig();
1856 #ifndef SHIBSP_LITE
1857         SAMLConfig& samlConf=SAMLConfig::getConfig();
1858 #endif
1859         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1860         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1861         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1862
1863         // Initialize logging manually in order to redirect log messages as soon as possible.
1864         if (conf.isEnabled(SPConfig::Logging)) {
1865             string logconf;
1866             if (conf.isEnabled(SPConfig::OutOfProcess))
1867                 logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1868             else if (conf.isEnabled(SPConfig::InProcess))
1869                 logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1870             if (logconf.empty())
1871                 logconf = XMLHelper::getAttrString(e, nullptr, logger);
1872             if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1873                 // No properties found, so default them.
1874                 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1875                     logconf = "shibd.logger";
1876                 else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1877                     logconf = "native.logger";
1878                 else
1879                     logconf = "shibboleth.logger";
1880             }
1881             if (!logconf.empty()) {
1882                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1883                 if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1884                     log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1885             }
1886
1887 #ifndef SHIBSP_LITE
1888             if (first)
1889                 m_outer->m_tranLog = new TransactionLog();
1890 #endif
1891         }
1892
1893         // Re-log library versions now that logging is set up.
1894         log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1895 #ifndef SHIBSP_LITE
1896         log.info(
1897             "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1898             XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1899             );
1900 #else
1901         log.info(
1902             "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1903             XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1904             );
1905 #endif
1906
1907         // First load any property sets.
1908         load(e,nullptr,this);
1909
1910         DOMElement* child;
1911
1912         // Much of the processing can only occur on the first instantiation.
1913         if (first) {
1914             // Set clock skew.
1915             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1916             if (skew.first)
1917                 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1918
1919             pair<bool,const char*> unsafe = getString("unsafeChars");
1920             if (unsafe.first)
1921                 TemplateEngine::unsafe_chars = unsafe.second;
1922
1923             unsafe = getString("allowedSchemes");
1924             if (unsafe.first) {
1925                 HTTPResponse::getAllowedSchemes().clear();
1926                 string schemes=unsafe.second;
1927                 unsigned int j_sch=0;
1928                 for (unsigned int i_sch=0;  i_sch < schemes.length();  i_sch++) {
1929                     if (schemes.at(i_sch)==' ') {
1930                         HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1931                         j_sch = i_sch + 1;
1932                     }
1933                 }
1934                 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1935             }
1936
1937             // Extensions
1938             doExtensions(e, "global", log);
1939             if (conf.isEnabled(SPConfig::OutOfProcess))
1940                 doExtensions(SHAR, "out of process", log);
1941
1942             if (conf.isEnabled(SPConfig::InProcess))
1943                 doExtensions(SHIRE, "in process", log);
1944
1945             // Instantiate the ListenerService and SessionCache objects.
1946             if (conf.isEnabled(SPConfig::Listener))
1947                 doListener(e, log);
1948
1949 #ifndef SHIBSP_LITE
1950             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1951                 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1952                 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1953                 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1954                 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1955             }
1956 #endif
1957             if (conf.isEnabled(SPConfig::Caching))
1958                 doCaching(e, log);
1959         } // end of first-time-only stuff
1960
1961         // Back to the fully dynamic stuff...next up is the RequestMapper.
1962         if (conf.isEnabled(SPConfig::RequestMapping)) {
1963             if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
1964                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1965                 if (!t.empty()) {
1966                     log.info("building RequestMapper of type %s...", t.c_str());
1967                     m_requestMapper = conf.RequestMapperManager.newPlugin(t.c_str(), child);
1968                 }
1969             }
1970             if (!m_requestMapper) {
1971                 log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
1972                 child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
1973                 DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
1974                 mapperDummy->setAttributeNS(nullptr, applicationId, _default);
1975                 child->appendChild(mapperDummy);
1976                 m_requestMapper = conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child);
1977             }
1978         }
1979
1980 #ifndef SHIBSP_LITE
1981         // Load security policies.
1982         if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
1983             string t(XMLHelper::getAttrString(child, nullptr, _type));
1984             if (!t.empty()) {
1985                 log.info("building SecurityPolicyProvider of type %s...", t.c_str());
1986                 m_policy = conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child);
1987             }
1988             else {
1989                 throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
1990             }
1991         }
1992         else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
1993             // For backward compatibility, wrap in a plugin element.
1994             DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
1995             polwrapper->appendChild(child);
1996             log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
1997             m_policy = conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper);
1998         }
1999         else {
2000             log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2001             throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2002         }
2003
2004         if (first) {
2005 #ifdef SHIBSP_XMLSEC_WHITELISTING
2006             vector<xstring>::const_iterator alg;
2007             if (!m_policy->getAlgorithmBlacklist().empty()) {
2008                 for (alg = m_policy->getAlgorithmBlacklist().begin(); alg != m_policy->getAlgorithmBlacklist().end(); ++alg)
2009                     XSECPlatformUtils::blacklistAlgorithm(alg->c_str());
2010             }
2011             else if (!m_policy->getAlgorithmWhitelist().empty()) {
2012                 for (alg = m_policy->getAlgorithmWhitelist().begin(); alg != m_policy->getAlgorithmWhitelist().end(); ++alg)
2013                     XSECPlatformUtils::whitelistAlgorithm(alg->c_str());
2014             }
2015 #else
2016             log.fatal("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2017             throw ConfigurationException("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists.");
2018 #endif
2019         }
2020
2021         // Process TransportOption elements.
2022         child = XMLHelper::getLastChildElement(e, TransportOption);
2023         while (child) {
2024             if (child->hasChildNodes()) {
2025                 string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2026                 string option(XMLHelper::getAttrString(child, nullptr, _option));
2027                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
2028                 if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2029                     m_transportOptions.push_back(make_pair(provider, make_pair(option, string(value.get()))));
2030                 }
2031             }
2032             child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2033         }
2034 #endif
2035
2036         ProtocolProvider* pp = nullptr;
2037         if (conf.isEnabled(SPConfig::Handlers)) {
2038             if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2039                 string t(XMLHelper::getAttrString(child, nullptr, _type));
2040                 if (!t.empty()) {
2041                     log.info("building ProtocolProvider of type %s...", t.c_str());
2042                     pp = conf.ProtocolProviderManager.newPlugin(t.c_str(), child);
2043                 }
2044             }
2045         }
2046         auto_ptr<ProtocolProvider> ppwrapper(pp);
2047         Locker pplocker(pp);
2048
2049         // Load the default application.
2050         child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2051         if (!child) {
2052             log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2053             throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2054         }
2055         XMLApplication* defapp = new XMLApplication(m_outer, pp, child);
2056         m_appmap[defapp->getId()] = defapp;
2057
2058         // Load any overrides.
2059         child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2060         while (child) {
2061             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer, pp, child, defapp));
2062             if (m_appmap.count(iapp->getId()))
2063                 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2064             else {
2065                 const char* iappid=iapp->getId();
2066                 m_appmap[iappid] = iapp.release();
2067             }
2068
2069             child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2070         }
2071     }
2072     catch (exception&) {
2073         cleanup();
2074         throw;
2075     }
2076 }
2077
2078 XMLConfigImpl::~XMLConfigImpl()
2079 {
2080     cleanup();
2081 }
2082
2083 void XMLConfigImpl::cleanup()
2084 {
2085     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
2086     m_appmap.clear();
2087 #ifndef SHIBSP_LITE
2088     delete m_policy;
2089     m_policy = nullptr;
2090 #endif
2091     delete m_requestMapper;
2092     m_requestMapper = nullptr;
2093     if (m_document)
2094         m_document->release();
2095     m_document = nullptr;
2096 }
2097
2098 #ifndef SHIBSP_LITE
2099 void XMLConfig::receive(DDF& in, ostream& out)
2100 {
2101     if (!strcmp(in.name(), "get::RelayState")) {
2102         const char* id = in["id"].string();
2103         const char* key = in["key"].string();
2104         if (!id || !key)
2105             throw ListenerException("Required parameters missing for RelayState recovery.");
2106
2107         string relayState;
2108         StorageService* storage = getStorageService(id);
2109         if (storage) {
2110             if (storage->readString("RelayState",key,&relayState)>0) {
2111                 if (in["clear"].integer())
2112                     storage->deleteString("RelayState",key);
2113             }
2114         }
2115         else {
2116             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2117                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2118                 );
2119         }
2120
2121         // Repack for return to caller.
2122         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2123         DDFJanitor jret(ret);
2124         out << ret;
2125     }
2126     else if (!strcmp(in.name(), "set::RelayState")) {
2127         const char* id = in["id"].string();
2128         const char* value = in["value"].string();
2129         if (!id || !value)
2130             throw ListenerException("Required parameters missing for RelayState creation.");
2131
2132         string rsKey;
2133         StorageService* storage = getStorageService(id);
2134         if (storage) {
2135             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2136             rsKey = SAMLArtifact::toHex(rsKey);
2137             storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2138         }
2139         else {
2140             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2141                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2142                 );
2143         }
2144
2145         // Repack for return to caller.
2146         DDF ret=DDF(nullptr).string(rsKey.c_str());
2147         DDFJanitor jret(ret);
2148         out << ret;
2149     }
2150     else if (!strcmp(in.name(), "get::PostData")) {
2151         const char* id = in["id"].string();
2152         const char* key = in["key"].string();
2153         if (!id || !key)
2154             throw ListenerException("Required parameters missing for PostData recovery.");
2155
2156         string postData;
2157         StorageService* storage = getStorageService(id);
2158         if (storage) {
2159             if (storage->readString("PostData",key,&postData) > 0) {
2160                 storage->deleteString("PostData",key);
2161             }
2162         }
2163         else {
2164             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2165                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2166                 );
2167         }
2168         // If the data's empty, we'll send nothing back.
2169         // If not, we don't need to round trip it, just send back the serialized DDF list.
2170         if (postData.empty()) {
2171             DDF ret(nullptr);
2172             DDFJanitor jret(ret);
2173             out << ret;
2174         }
2175         else {
2176             out << postData;
2177         }
2178     }
2179     else if (!strcmp(in.name(), "set::PostData")) {
2180         const char* id = in["id"].string();
2181         if (!id || !in["parameters"].islist())
2182             throw ListenerException("Required parameters missing for PostData creation.");
2183
2184         string rsKey;
2185         StorageService* storage = getStorageService(id);
2186         if (storage) {
2187             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
2188             rsKey = SAMLArtifact::toHex(rsKey);
2189             ostringstream params;
2190             params << in["parameters"];
2191             storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2192         }
2193         else {
2194             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2195                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2196                 );
2197         }
2198
2199         // Repack for return to caller.
2200         DDF ret=DDF(nullptr).string(rsKey.c_str());
2201         DDFJanitor jret(ret);
2202         out << ret;
2203     }
2204 }
2205 #endif
2206
2207 pair<bool,DOMElement*> XMLConfig::background_load()
2208 {
2209     // Load from source using base class.
2210     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2211
2212     // If we own it, wrap it.
2213     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2214
2215     XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
2216
2217     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2218     impl->setDocument(docjanitor.release());
2219
2220     // Perform the swap inside a lock.
2221     if (m_lock)
2222         m_lock->wrlock();
2223     SharedLock locker(m_lock, false);
2224     delete m_impl;
2225     m_impl = impl;
2226
2227     return make_pair(false,(DOMElement*)nullptr);
2228 }