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