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