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