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