VS10 solution files, convert from NULL macro to nullptr.
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * XMLServiceProvider.cpp
19  *
20  * XML-based SP configuration and mgmt.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "version.h"
26 #include "AccessControl.h"
27 #include "Application.h"
28 #include "RequestMapper.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
31 #include "SPConfig.h"
32 #include "SPRequest.h"
33 #include "handler/SessionInitiator.h"
34 #include "remoting/ListenerService.h"
35 #include "util/DOMPropertySet.h"
36 #include "util/SPConstants.h"
37
38 #if defined(XMLTOOLING_LOG4SHIB)
39 # include <log4shib/PropertyConfigurator.hh>
40 #elif defined(XMLTOOLING_LOG4CPP)
41 # include <log4cpp/PropertyConfigurator.hh>
42 #else
43 # error "Supported logging library not available."
44 #endif
45 #include <algorithm>
46 #include <xercesc/util/XMLUniDefs.hpp>
47 #include <xmltooling/XMLToolingConfig.h>
48 #include <xmltooling/version.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/ReloadableXMLFile.h>
51 #include <xmltooling/util/TemplateEngine.h>
52 #include <xmltooling/util/Threads.h>
53 #include <xmltooling/util/XMLHelper.h>
54
55 #ifndef SHIBSP_LITE
56 # include "TransactionLog.h"
57 # include "attribute/filtering/AttributeFilter.h"
58 # include "attribute/resolver/AttributeExtractor.h"
59 # include "attribute/resolver/AttributeResolver.h"
60 # include "security/PKIXTrustEngine.h"
61 # include <saml/SAMLConfig.h>
62 # include <saml/version.h>
63 # include <saml/binding/ArtifactMap.h>
64 # include <saml/binding/SAMLArtifact.h>
65 # include <saml/binding/SecurityPolicyRule.h>
66 # include <saml/saml1/core/Assertions.h>
67 # include <saml/saml2/core/Assertions.h>
68 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
69 # include <saml/saml2/metadata/Metadata.h>
70 # include <saml/saml2/metadata/MetadataProvider.h>
71 # include <saml/util/SAMLConstants.h>
72 # include <xmltooling/security/CredentialResolver.h>
73 # include <xmltooling/security/SecurityHelper.h>
74 # include <xmltooling/security/TrustEngine.h>
75 # include <xmltooling/util/ReplayCache.h>
76 # include <xmltooling/util/StorageService.h>
77 # include <xercesc/util/XMLStringTokenizer.hpp>
78 # include <xsec/utils/XSECPlatformUtils.hpp>
79 using namespace opensaml::saml2;
80 using namespace opensaml::saml2p;
81 using namespace opensaml::saml2md;
82 using namespace opensaml;
83 #else
84 # include "lite/SAMLConstants.h"
85 #endif
86
87 using namespace shibsp;
88 using namespace xmltooling;
89 using namespace std;
90
91 #ifndef min
92 # define min(a,b)            (((a) < (b)) ? (a) : (b))
93 #endif
94
95 namespace {
96
97 #if defined (_MSC_VER)
98     #pragma warning( push )
99     #pragma warning( disable : 4250 )
100 #endif
101
102     static vector<const Handler*> g_noHandlers;
103
104     // Application configuration wrapper
105     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
106     {
107     public:
108         XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=nullptr);
109         ~XMLApplication() { cleanup(); }
110
111         const char* getHash() const {return m_hash.c_str();}
112
113 #ifndef SHIBSP_LITE
114         SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
115             throw ConfigurationException("No support for SAML 1.x artifact generation.");
116         }
117         SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
118             pair<bool,int> index = make_pair(false,0);
119             const PropertySet* props = getRelyingParty(relyingParty);
120             index = props->getInt("artifactEndpointIndex");
121             if (!index.first)
122                 index = getArtifactEndpointIndex();
123             pair<bool,const char*> entityID = props->getString("entityID");
124             return new SAML2ArtifactType0004(
125                 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
126                 index.first ? index.second : 1
127                 );
128         }
129
130         MetadataProvider* getMetadataProvider(bool required=true) const {
131             if (required && !m_base && !m_metadata)
132                 throw ConfigurationException("No MetadataProvider available.");
133             return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
134         }
135         TrustEngine* getTrustEngine(bool required=true) const {
136             if (required && !m_base && !m_trust)
137                 throw ConfigurationException("No TrustEngine available.");
138             return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
139         }
140         AttributeExtractor* getAttributeExtractor() const {
141             return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
142         }
143         AttributeFilter* getAttributeFilter() const {
144             return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
145         }
146         AttributeResolver* getAttributeResolver() const {
147             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
148         }
149         CredentialResolver* getCredentialResolver() const {
150             return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
151         }
152         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
153         const PropertySet* getRelyingParty(const XMLCh* entityID) const;
154         const vector<const XMLCh*>* getAudiences() const {
155             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
156         }
157 #endif
158         string getNotificationURL(const char* resource, bool front, unsigned int index) const;
159
160         const vector<string>& getRemoteUserAttributeIds() const {
161             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
162         }
163
164         void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
165         void setHeader(SPRequest& request, const char* name, const char* value) const;
166         string getSecureHeader(const SPRequest& request, const char* name) const;
167
168         const SessionInitiator* getDefaultSessionInitiator() const;
169         const SessionInitiator* getSessionInitiatorById(const char* id) const;
170         const Handler* getDefaultAssertionConsumerService() const;
171         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
172         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
173         const Handler* getHandler(const char* path) const;
174         void getHandlers(vector<const Handler*>& handlers) const;
175
176         void receive(DDF& in, ostream& out) {
177             // Only current function is to return the headers to clear.
178             DDF header;
179             DDF ret=DDF(nullptr).list();
180             DDFJanitor jret(ret);
181             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
182                 header = DDF(i->first.c_str()).string(i->second.c_str());
183                 ret.add(header);
184             }
185             out << ret;
186         }
187
188         // Provides filter to exclude special config elements.
189 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
190         short
191 #else
192         FilterAction
193 #endif
194         acceptNode(const DOMNode* node) const;
195
196     private:
197         void cleanup();
198         const XMLApplication* m_base;
199         string m_hash;
200         std::pair<std::string,std::string> m_attributePrefix;
201 #ifndef SHIBSP_LITE
202         MetadataProvider* m_metadata;
203         TrustEngine* m_trust;
204         AttributeExtractor* m_attrExtractor;
205         AttributeFilter* m_attrFilter;
206         AttributeResolver* m_attrResolver;
207         CredentialResolver* m_credResolver;
208         vector<const XMLCh*> m_audiences;
209
210         // RelyingParty properties
211         map<xstring,PropertySet*> m_partyMap;
212 #endif
213         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
214
215         // manage handler objects
216         vector<Handler*> m_handlers;
217
218         // maps location (path info) to applicable handlers
219         map<string,const Handler*> m_handlerMap;
220
221         // maps unique indexes to consumer services
222         map<unsigned int,const Handler*> m_acsIndexMap;
223
224         // pointer to default consumer service
225         const Handler* m_acsDefault;
226
227         // maps binding strings to supporting consumer service(s)
228         typedef map<xstring,vector<const Handler*> > ACSBindingMap;
229         ACSBindingMap m_acsBindingMap;
230
231         // pointer to default session initiator
232         const SessionInitiator* m_sessionInitDefault;
233
234         // maps unique ID strings to session initiators
235         map<string,const SessionInitiator*> m_sessionInitMap;
236
237         // pointer to default artifact resolution service
238         const Handler* m_artifactResolutionDefault;
239
240         pair<bool,int> getArtifactEndpointIndex() const {
241             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
242             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
243         }
244     };
245
246     // Top-level configuration implementation
247     class SHIBSP_DLLLOCAL XMLConfig;
248     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
249     {
250     public:
251         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
252         ~XMLConfigImpl();
253
254         RequestMapper* m_requestMapper;
255         map<string,Application*> m_appmap;
256 #ifndef SHIBSP_LITE
257         map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
258         vector< pair< string, pair<string,string> > > m_transportOptions;
259 #endif
260
261         // Provides filter to exclude special config elements.
262 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
263         short
264 #else
265         FilterAction
266 #endif
267         acceptNode(const DOMNode* node) const;
268
269         void setDocument(DOMDocument* doc) {
270             m_document = doc;
271         }
272
273     private:
274         void doExtensions(const DOMElement* e, const char* label, Category& log);
275         void cleanup();
276
277         const XMLConfig* m_outer;
278         DOMDocument* m_document;
279     };
280
281     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
282 #ifndef SHIBSP_LITE
283         ,public Remoted
284 #endif
285     {
286     public:
287         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
288             m_impl(nullptr), m_listener(nullptr), m_sessionCache(nullptr)
289 #ifndef SHIBSP_LITE
290             , m_tranLog(nullptr)
291 #endif
292         {
293         }
294
295         void init() {
296             background_load();
297         }
298
299         ~XMLConfig() {
300             shutdown();
301             delete m_impl;
302             delete m_sessionCache;
303             delete m_listener;
304 #ifndef SHIBSP_LITE
305             delete m_tranLog;
306             SAMLConfig::getConfig().setArtifactMap(nullptr);
307             XMLToolingConfig::getConfig().setReplayCache(nullptr);
308             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
309 #endif
310         }
311
312         // PropertySet
313         const PropertySet* getParent() const { return m_impl->getParent(); }
314         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
315         pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
316         pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
317         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
318         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
319         pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
320         void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
321         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
322         const DOMElement* getElement() const {return m_impl->getElement();}
323
324         // ServiceProvider
325 #ifndef SHIBSP_LITE
326         // Remoted
327         void receive(DDF& in, ostream& out);
328
329         TransactionLog* getTransactionLog() const {
330             if (m_tranLog)
331                 return m_tranLog;
332             throw ConfigurationException("No TransactionLog available.");
333         }
334
335         StorageService* getStorageService(const char* id) const {
336             if (id) {
337                 map<string,StorageService*>::const_iterator i=m_storage.find(id);
338                 if (i!=m_storage.end())
339                     return i->second;
340             }
341             return nullptr;
342         }
343 #endif
344
345         ListenerService* getListenerService(bool required=true) const {
346             if (required && !m_listener)
347                 throw ConfigurationException("No ListenerService available.");
348             return m_listener;
349         }
350
351         SessionCache* getSessionCache(bool required=true) const {
352             if (required && !m_sessionCache)
353                 throw ConfigurationException("No SessionCache available.");
354             return m_sessionCache;
355         }
356
357         RequestMapper* getRequestMapper(bool required=true) const {
358             if (required && !m_impl->m_requestMapper)
359                 throw ConfigurationException("No RequestMapper available.");
360             return m_impl->m_requestMapper;
361         }
362
363         const Application* getApplication(const char* applicationId) const {
364             map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
365             return (i!=m_impl->m_appmap.end()) ? i->second : nullptr;
366         }
367
368 #ifndef SHIBSP_LITE
369         const PropertySet* getPolicySettings(const char* id) const {
370             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
371             if (i!=m_impl->m_policyMap.end())
372                 return i->second.first;
373             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
374         }
375
376         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
377             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
378             if (i!=m_impl->m_policyMap.end())
379                 return i->second.second;
380             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
381         }
382
383         bool setTransportOptions(SOAPTransport& transport) const {
384             bool ret = true;
385             vector< pair< string, pair<string,string> > >::const_iterator opt;
386             for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
387                 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
388                     m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
389                     ret = false;
390                 }
391             }
392             return ret;
393         }
394 #endif
395
396     protected:
397         pair<bool,DOMElement*> background_load();
398
399     private:
400         friend class XMLConfigImpl;
401         XMLConfigImpl* m_impl;
402         mutable ListenerService* m_listener;
403         mutable SessionCache* m_sessionCache;
404 #ifndef SHIBSP_LITE
405         mutable TransactionLog* m_tranLog;
406         mutable map<string,StorageService*> m_storage;
407 #endif
408     };
409
410 #if defined (_MSC_VER)
411     #pragma warning( pop )
412 #endif
413
414     static const XMLCh AlgorithmBlacklist[] =   UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,B,l,a,c,k,l,i,s,t);
415     static const XMLCh AlgorithmWhitelist[] =   UNICODE_LITERAL_18(A,l,g,o,r,i,t,h,m,W,h,i,t,e,l,i,s,t);
416     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);
417     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);
418     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
419     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);
420     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
421     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
422     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);
423     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);
424     static const XMLCh _Audience[] =            UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
425     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
426     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
427     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);
428     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
429     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
430     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
431     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
432     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
433     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);
434     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
435     static const XMLCh Location[] =             UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
436     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);
437     static const XMLCh _LogoutInitiator[] =     UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
438     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);
439     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
440     static const XMLCh Notify[] =               UNICODE_LITERAL_6(N,o,t,i,f,y);
441     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
442     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
443     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
444     static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);
445     static const XMLCh PolicyRule[] =           UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
446     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
447     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
448     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
449     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
450     static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);
451     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
452     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
453     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
454     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);
455     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
456     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
457     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
458     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
459     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
460     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
461     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
462
463 #ifndef SHIBSP_LITE
464     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
465     {
466     public:
467 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
468         short
469 #else
470         FilterAction
471 #endif
472         acceptNode(const DOMNode* node) const {
473             return FILTER_REJECT;
474         }
475     };
476 #endif
477 };
478
479 namespace shibsp {
480     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
481     {
482         return new XMLConfig(e);
483     }
484 };
485
486 XMLApplication::XMLApplication(
487     const ServiceProvider* sp,
488     const DOMElement* e,
489     const XMLApplication* base
490     ) : Application(sp), m_base(base),
491 #ifndef SHIBSP_LITE
492         m_metadata(nullptr), m_trust(nullptr),
493         m_attrExtractor(nullptr), m_attrFilter(nullptr), m_attrResolver(nullptr),
494         m_credResolver(nullptr),
495 #endif
496         m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
497 {
498 #ifdef _DEBUG
499     xmltooling::NDC ndc("XMLApplication");
500 #endif
501     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
502
503     try {
504         // First load any property sets.
505         load(e,nullptr,this);
506         if (base)
507             setParent(base);
508
509         SPConfig& conf=SPConfig::getConfig();
510 #ifndef SHIBSP_LITE
511         SAMLConfig& samlConf=SAMLConfig::getConfig();
512         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
513 #endif
514
515         // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
516         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
517         string tohash=getId();
518         tohash+=getString("entityID").second;
519         for (const char* ch = tohash.c_str(); *ch; ++ch) {
520             m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
521             m_hash += (DIGITS[0x0F & *ch]);
522         }
523
524         // Populate prefix pair.
525         m_attributePrefix.second = "HTTP_";
526         pair<bool,const char*> prefix = getString("attributePrefix");
527         if (prefix.first) {
528             m_attributePrefix.first = prefix.second;
529             const char* pch = prefix.second;
530             while (*pch) {
531                 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
532                 pch++;
533             }
534         }
535
536         // Load attribute ID lists for REMOTE_USER and header clearing.
537         if (conf.isEnabled(SPConfig::InProcess)) {
538             pair<bool,const char*> attributes = getString("REMOTE_USER");
539             if (attributes.first) {
540                 char* dup = strdup(attributes.second);
541                 char* pos;
542                 char* start = dup;
543                 while (start && *start) {
544                     while (*start && isspace(*start))
545                         start++;
546                     if (!*start)
547                         break;
548                     pos = strchr(start,' ');
549                     if (pos)
550                         *pos=0;
551                     m_remoteUsers.push_back(start);
552                     start = pos ? pos+1 : nullptr;
553                 }
554                 free(dup);
555             }
556
557             attributes = getString("unsetHeaders");
558             if (attributes.first) {
559                 string transformedprefix(m_attributePrefix.second);
560                 const char* pch;
561                 prefix = getString("metadataAttributePrefix");
562                 if (prefix.first) {
563                     pch = prefix.second;
564                     while (*pch) {
565                         transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
566                         pch++;
567                     }
568                 }
569                 char* dup = strdup(attributes.second);
570                 char* pos;
571                 char* start = dup;
572                 while (start && *start) {
573                     while (*start && isspace(*start))
574                         start++;
575                     if (!*start)
576                         break;
577                     pos = strchr(start,' ');
578                     if (pos)
579                         *pos=0;
580
581                     string transformed;
582                     pch = start;
583                     while (*pch) {
584                         transformed += (isalnum(*pch) ? toupper(*pch) : '_');
585                         pch++;
586                     }
587
588                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
589                     if (prefix.first)
590                         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
591                     start = pos ? pos+1 : nullptr;
592                 }
593                 free(dup);
594                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
595             }
596         }
597
598         Handler* handler=nullptr;
599         const PropertySet* sessions = getPropertySet("Sessions");
600
601         // Process assertion export handler.
602         pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
603         if (location.first) {
604             try {
605                 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
606                 exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
607                 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
608                 if (exportACL.first) {
609                     static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
610                     exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
611                 }
612                 handler = conf.HandlerManager.newPlugin(
613                     samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
614                     );
615                 m_handlers.push_back(handler);
616
617                 // Insert into location map. If it contains the handlerURL, we skip past that part.
618                 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
619                 if (pch)
620                     location.second = pch + strlen(sessions->getString("handlerURL").second);
621                 if (*location.second == '/')
622                     m_handlerMap[location.second]=handler;
623                 else
624                     m_handlerMap[string("/") + location.second]=handler;
625             }
626             catch (exception& ex) {
627                 log.error("caught exception installing assertion lookup handler: %s", ex.what());
628             }
629         }
630
631         // Process other handlers.
632         bool hardACS=false, hardSessionInit=false, hardArt=false;
633         const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
634         while (child) {
635             try {
636                 // A handler is based on the Binding property in conjunction with the element name.
637                 // If it's an ACS or SI, also handle index/id mappings and defaulting.
638                 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
639                     auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
640                     if (!bindprop.get() || !*(bindprop.get())) {
641                         log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
642                         child = XMLHelper::getNextSiblingElement(child);
643                         continue;
644                     }
645                     handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
646                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
647                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
648                     m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
649
650                     if (!hardACS) {
651                         pair<bool,bool> defprop=handler->getBool("isDefault");
652                         if (defprop.first) {
653                             if (defprop.second) {
654                                 hardACS=true;
655                                 m_acsDefault=handler;
656                             }
657                         }
658                         else if (!m_acsDefault)
659                             m_acsDefault=handler;
660                     }
661                 }
662                 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
663                     auto_ptr_char type(child->getAttributeNS(nullptr,_type));
664                     if (!type.get() || !*(type.get())) {
665                         log.warn("SessionInitiator element has no type attribute, skipping it...");
666                         child = XMLHelper::getNextSiblingElement(child);
667                         continue;
668                     }
669                     SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
670                     handler=sihandler;
671                     pair<bool,const char*> si_id=handler->getString("id");
672                     if (si_id.first && si_id.second)
673                         m_sessionInitMap[si_id.second]=sihandler;
674                     if (!hardSessionInit) {
675                         pair<bool,bool> defprop=handler->getBool("isDefault");
676                         if (defprop.first) {
677                             if (defprop.second) {
678                                 hardSessionInit=true;
679                                 m_sessionInitDefault=sihandler;
680                             }
681                         }
682                         else if (!m_sessionInitDefault)
683                             m_sessionInitDefault=sihandler;
684                     }
685                 }
686                 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
687                     auto_ptr_char type(child->getAttributeNS(nullptr,_type));
688                     if (!type.get() || !*(type.get())) {
689                         log.warn("LogoutInitiator element has no type attribute, skipping it...");
690                         child = XMLHelper::getNextSiblingElement(child);
691                         continue;
692                     }
693                     handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
694                 }
695                 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
696                     auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
697                     if (!bindprop.get() || !*(bindprop.get())) {
698                         log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
699                         child = XMLHelper::getNextSiblingElement(child);
700                         continue;
701                     }
702                     handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
703
704                     if (!hardArt) {
705                         pair<bool,bool> defprop=handler->getBool("isDefault");
706                         if (defprop.first) {
707                             if (defprop.second) {
708                                 hardArt=true;
709                                 m_artifactResolutionDefault=handler;
710                             }
711                         }
712                         else if (!m_artifactResolutionDefault)
713                             m_artifactResolutionDefault=handler;
714                     }
715                 }
716                 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
717                     auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
718                     if (!bindprop.get() || !*(bindprop.get())) {
719                         log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
720                         child = XMLHelper::getNextSiblingElement(child);
721                         continue;
722                     }
723                     handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
724                 }
725                 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
726                     auto_ptr_char bindprop(child->getAttributeNS(nullptr,Binding));
727                     if (!bindprop.get() || !*(bindprop.get())) {
728                         log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
729                         child = XMLHelper::getNextSiblingElement(child);
730                         continue;
731                     }
732                     handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
733                 }
734                 else {
735                     auto_ptr_char type(child->getAttributeNS(nullptr,_type));
736                     if (!type.get() || !*(type.get())) {
737                         log.warn("Handler element has no type attribute, skipping it...");
738                         child = XMLHelper::getNextSiblingElement(child);
739                         continue;
740                     }
741                     handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
742                 }
743
744                 m_handlers.push_back(handler);
745
746                 // Insert into location map.
747                 location=handler->getString("Location");
748                 if (location.first && *location.second == '/')
749                     m_handlerMap[location.second]=handler;
750                 else if (location.first)
751                     m_handlerMap[string("/") + location.second]=handler;
752
753             }
754             catch (exception& ex) {
755                 log.error("caught exception processing handler element: %s", ex.what());
756             }
757
758             child = XMLHelper::getNextSiblingElement(child);
759         }
760
761         // Notification.
762         DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
763         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
764             if (nlist->item(i)->getParentNode()->isSameNode(e)) {
765                 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr,Channel);
766                 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr,Location));
767                 if (loc.get() && *loc.get()) {
768                     if (channel && *channel == chLatin_f)
769                         m_frontLogout.push_back(loc.get());
770                     else
771                         m_backLogout.push_back(loc.get());
772                 }
773             }
774         }
775
776 #ifndef SHIBSP_LITE
777         nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
778         if (nlist && nlist->getLength()) {
779             log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
780             for (XMLSize_t i=0; i<nlist->getLength(); i++)
781                 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
782                     m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
783         }
784
785         if (conf.isEnabled(SPConfig::Metadata)) {
786             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
787             if (child) {
788                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
789                 log.info("building MetadataProvider of type %s...",type.get());
790                 try {
791                     auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
792                     mp->init();
793                     m_metadata = mp.release();
794                 }
795                 catch (exception& ex) {
796                     log.crit("error building/initializing MetadataProvider: %s", ex.what());
797                 }
798             }
799         }
800
801         if (conf.isEnabled(SPConfig::Trust)) {
802             child = XMLHelper::getFirstChildElement(e,_TrustEngine);
803             if (child) {
804                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
805                 log.info("building TrustEngine of type %s...",type.get());
806                 try {
807                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
808                 }
809                 catch (exception& ex) {
810                     log.crit("error building TrustEngine: %s", ex.what());
811                 }
812             }
813         }
814
815         if (conf.isEnabled(SPConfig::AttributeResolution)) {
816             child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
817             if (child) {
818                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
819                 log.info("building AttributeExtractor of type %s...",type.get());
820                 try {
821                     m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
822                 }
823                 catch (exception& ex) {
824                     log.crit("error building AttributeExtractor: %s", ex.what());
825                 }
826             }
827
828             child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
829             if (child) {
830                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
831                 log.info("building AttributeFilter of type %s...",type.get());
832                 try {
833                     m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
834                 }
835                 catch (exception& ex) {
836                     log.crit("error building AttributeFilter: %s", ex.what());
837                 }
838             }
839
840             child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
841             if (child) {
842                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
843                 log.info("building AttributeResolver of type %s...",type.get());
844                 try {
845                     m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
846                 }
847                 catch (exception& ex) {
848                     log.crit("error building AttributeResolver: %s", ex.what());
849                 }
850             }
851
852             if (m_unsetHeaders.empty()) {
853                 vector<string> unsetHeaders;
854                 if (m_attrExtractor) {
855                     Locker extlock(m_attrExtractor);
856                     m_attrExtractor->getAttributeIds(unsetHeaders);
857                 }
858                 else if (m_base && m_base->m_attrExtractor) {
859                     Locker extlock(m_base->m_attrExtractor);
860                     m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
861                 }
862                 if (m_attrResolver) {
863                     Locker reslock(m_attrResolver);
864                     m_attrResolver->getAttributeIds(unsetHeaders);
865                 }
866                 else if (m_base && m_base->m_attrResolver) {
867                     Locker extlock(m_base->m_attrResolver);
868                     m_base->m_attrResolver->getAttributeIds(unsetHeaders);
869                 }
870                 if (!unsetHeaders.empty()) {
871                     string transformedprefix(m_attributePrefix.second);
872                     const char* pch;
873                     pair<bool,const char*> prefix = getString("metadataAttributePrefix");
874                     if (prefix.first) {
875                         pch = prefix.second;
876                         while (*pch) {
877                             transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
878                             pch++;
879                         }
880                     }
881                     for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
882                         string transformed;
883                         pch = hdr->c_str();
884                         while (*pch) {
885                             transformed += (isalnum(*pch) ? toupper(*pch) : '_');
886                             pch++;
887                         }
888                         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
889                         if (prefix.first)
890                             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
891                     }
892                 }
893                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
894             }
895         }
896
897         if (conf.isEnabled(SPConfig::Credentials)) {
898             child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
899             if (child) {
900                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
901                 log.info("building CredentialResolver of type %s...",type.get());
902                 try {
903                     m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
904                 }
905                 catch (exception& ex) {
906                     log.crit("error building CredentialResolver: %s", ex.what());
907                 }
908             }
909         }
910
911         // Finally, load relying parties.
912         child = XMLHelper::getFirstChildElement(e,RelyingParty);
913         while (child) {
914             auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
915             rp->load(child,nullptr,this);
916             rp->setParent(this);
917             m_partyMap[child->getAttributeNS(nullptr,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
918             child = XMLHelper::getNextSiblingElement(child,RelyingParty);
919         }
920 #endif
921
922         // Out of process only, we register a listener endpoint.
923         if (!conf.isEnabled(SPConfig::InProcess)) {
924             ListenerService* listener = sp->getListenerService(false);
925             if (listener) {
926                 string addr=string(getId()) + "::getHeaders::Application";
927                 listener->regListener(addr.c_str(),this);
928             }
929             else
930                 log.info("no ListenerService available, Application remoting disabled");
931         }
932     }
933     catch (exception&) {
934         cleanup();
935         throw;
936     }
937 #ifndef _DEBUG
938     catch (...) {
939         cleanup();
940         throw;
941     }
942 #endif
943 }
944
945 void XMLApplication::cleanup()
946 {
947     ListenerService* listener=getServiceProvider().getListenerService(false);
948     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
949         string addr=string(getId()) + "::getHeaders::Application";
950         listener->unregListener(addr.c_str(),this);
951     }
952     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
953     m_handlers.clear();
954 #ifndef SHIBSP_LITE
955     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
956     m_partyMap.clear();
957     delete m_credResolver;
958     m_credResolver = nullptr;
959     delete m_attrResolver;
960     m_attrResolver = nullptr;
961     delete m_attrFilter;
962     m_attrFilter = nullptr;
963     delete m_attrExtractor;
964     m_attrExtractor = nullptr;
965     delete m_trust;
966     m_trust = nullptr;
967     delete m_metadata;
968     m_metadata = nullptr;
969 #endif
970 }
971
972 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
973 short
974 #else
975 DOMNodeFilter::FilterAction
976 #endif
977 XMLApplication::acceptNode(const DOMNode* node) const
978 {
979     const XMLCh* name=node->getLocalName();
980     if (XMLString::equals(name,ApplicationOverride) ||
981         XMLString::equals(name,_Audience) ||
982         XMLString::equals(name,Notify) ||
983         XMLString::equals(name,_Handler) ||
984         XMLString::equals(name,_AssertionConsumerService) ||
985         XMLString::equals(name,_ArtifactResolutionService) ||
986         XMLString::equals(name,_LogoutInitiator) ||
987         XMLString::equals(name,_ManageNameIDService) ||
988         XMLString::equals(name,_SessionInitiator) ||
989         XMLString::equals(name,_SingleLogoutService) ||
990         XMLString::equals(name,RelyingParty) ||
991         XMLString::equals(name,_MetadataProvider) ||
992         XMLString::equals(name,_TrustEngine) ||
993         XMLString::equals(name,_CredentialResolver) ||
994         XMLString::equals(name,_AttributeFilter) ||
995         XMLString::equals(name,_AttributeExtractor) ||
996         XMLString::equals(name,_AttributeResolver))
997         return FILTER_REJECT;
998
999     return FILTER_ACCEPT;
1000 }
1001
1002 #ifndef SHIBSP_LITE
1003
1004 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1005 {
1006     if (!provider)
1007         return this;
1008
1009     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1010     if (i!=m_partyMap.end())
1011         return i->second;
1012     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1013     while (group) {
1014         if (group->getName()) {
1015             i=m_partyMap.find(group->getName());
1016             if (i!=m_partyMap.end())
1017                 return i->second;
1018         }
1019         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1020     }
1021     return this;
1022 }
1023
1024 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1025 {
1026     if (!entityID)
1027         return this;
1028
1029     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1030     if (i!=m_partyMap.end())
1031         return i->second;
1032     return this;
1033 }
1034
1035 #endif
1036
1037 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1038 {
1039     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1040     if (locs.empty())
1041         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1042     else if (index >= locs.size())
1043         return string();
1044
1045 #ifdef HAVE_STRCASECMP
1046     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1047 #else
1048     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1049 #endif
1050         throw ConfigurationException("Request URL was not absolute.");
1051
1052     const char* handler=locs[index].c_str();
1053
1054     // Should never happen...
1055     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1056         throw ConfigurationException(
1057             "Invalid Location property ($1) in Notify element for Application ($2)",
1058             params(2, handler ? handler : "null", getId())
1059             );
1060
1061     // The "Location" property can be in one of three formats:
1062     //
1063     // 1) a full URI:       http://host/foo/bar
1064     // 2) a hostless URI:   http:///foo/bar
1065     // 3) a relative path:  /foo/bar
1066     //
1067     // #  Protocol  Host        Path
1068     // 1  handler   handler     handler
1069     // 2  handler   resource    handler
1070     // 3  resource  resource    handler
1071
1072     const char* path = nullptr;
1073
1074     // Decide whether to use the handler or the resource for the "protocol"
1075     const char* prot;
1076     if (*handler != '/') {
1077         prot = handler;
1078     }
1079     else {
1080         prot = resource;
1081         path = handler;
1082     }
1083
1084     // break apart the "protocol" string into protocol, host, and "the rest"
1085     const char* colon=strchr(prot,':');
1086     colon += 3;
1087     const char* slash=strchr(colon,'/');
1088     if (!path)
1089         path = slash;
1090
1091     // Compute the actual protocol and store.
1092     string notifyURL(prot, colon-prot);
1093
1094     // create the "host" from either the colon/slash or from the target string
1095     // If prot == handler then we're in either #1 or #2, else #3.
1096     // If slash == colon then we're in #2.
1097     if (prot != handler || slash == colon) {
1098         colon = strchr(resource, ':');
1099         colon += 3;      // Get past the ://
1100         slash = strchr(colon, '/');
1101     }
1102     string host(colon, (slash ? slash-colon : strlen(colon)));
1103
1104     // Build the URL
1105     notifyURL += host + path;
1106     return notifyURL;
1107 }
1108
1109 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1110 {
1111     if (!m_attributePrefix.first.empty()) {
1112         string temp = m_attributePrefix.first + rawname;
1113         string temp2 = m_attributePrefix.second + (cginame + 5);
1114         request.clearHeader(temp.c_str(), temp2.c_str());
1115     }
1116     else if (m_base) {
1117         m_base->clearHeader(request, rawname, cginame);
1118     }
1119     else {
1120         request.clearHeader(rawname, cginame);
1121     }
1122 }
1123
1124 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1125 {
1126     if (!m_attributePrefix.first.empty()) {
1127         string temp = m_attributePrefix.first + name;
1128         request.setHeader(temp.c_str(), value);
1129     }
1130     else if (m_base) {
1131         m_base->setHeader(request, name, value);
1132     }
1133     else {
1134         request.setHeader(name, value);
1135     }
1136 }
1137
1138 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1139 {
1140     if (!m_attributePrefix.first.empty()) {
1141         string temp = m_attributePrefix.first + name;
1142         return request.getSecureHeader(temp.c_str());
1143     }
1144     else if (m_base) {
1145         return m_base->getSecureHeader(request,name);
1146     }
1147     else {
1148         return request.getSecureHeader(name);
1149     }
1150 }
1151
1152 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1153 {
1154     if (m_sessionInitDefault) return m_sessionInitDefault;
1155     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1156 }
1157
1158 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1159 {
1160     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1161     if (i!=m_sessionInitMap.end()) return i->second;
1162     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1163 }
1164
1165 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1166 {
1167     if (m_acsDefault) return m_acsDefault;
1168     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1169 }
1170
1171 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1172 {
1173     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1174     if (i!=m_acsIndexMap.end()) return i->second;
1175     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1176 }
1177
1178 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1179 {
1180     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1181     if (i!=m_acsBindingMap.end())
1182         return i->second;
1183     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1184 }
1185
1186 const Handler* XMLApplication::getHandler(const char* path) const
1187 {
1188     string wrap(path);
1189     wrap = wrap.substr(0,wrap.find(';'));
1190     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1191     if (i!=m_handlerMap.end())
1192         return i->second;
1193     return m_base ? m_base->getHandler(path) : nullptr;
1194 }
1195
1196 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1197 {
1198     handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1199     if (m_base) {
1200         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1201             if (m_handlerMap.count(h->first) == 0)
1202                 handlers.push_back(h->second);
1203         }
1204     }
1205 }
1206
1207 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1208 short
1209 #else
1210 DOMNodeFilter::FilterAction
1211 #endif
1212 XMLConfigImpl::acceptNode(const DOMNode* node) const
1213 {
1214     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1215         return FILTER_ACCEPT;
1216     const XMLCh* name=node->getLocalName();
1217     if (XMLString::equals(name,ApplicationDefaults) ||
1218         XMLString::equals(name,_ArtifactMap) ||
1219         XMLString::equals(name,_Extensions) ||
1220         XMLString::equals(name,Listener) ||
1221         XMLString::equals(name,_RequestMapper) ||
1222         XMLString::equals(name,_ReplayCache) ||
1223         XMLString::equals(name,SecurityPolicies) ||
1224         XMLString::equals(name,_SessionCache) ||
1225         XMLString::equals(name,Site) ||
1226         XMLString::equals(name,_StorageService) ||
1227         XMLString::equals(name,TCPListener) ||
1228         XMLString::equals(name,TransportOption) ||
1229         XMLString::equals(name,UnixListener))
1230         return FILTER_REJECT;
1231
1232     return FILTER_ACCEPT;
1233 }
1234
1235 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1236 {
1237     const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1238     if (exts) {
1239         exts=XMLHelper::getFirstChildElement(exts,Library);
1240         while (exts) {
1241             auto_ptr_char path(exts->getAttributeNS(nullptr,_path));
1242             try {
1243                 if (path.get()) {
1244                     if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1245                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1246                     log.debug("loaded %s extension library (%s)", label, path.get());
1247                 }
1248             }
1249             catch (exception& e) {
1250                 const XMLCh* fatal=exts->getAttributeNS(nullptr,_fatal);
1251                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1252                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1253                     throw;
1254                 }
1255                 else {
1256                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1257                 }
1258             }
1259             exts=XMLHelper::getNextSiblingElement(exts,Library);
1260         }
1261     }
1262 }
1263
1264 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1265     : m_requestMapper(nullptr), m_outer(outer), m_document(nullptr)
1266 {
1267 #ifdef _DEBUG
1268     xmltooling::NDC ndc("XMLConfigImpl");
1269 #endif
1270
1271     try {
1272         SPConfig& conf=SPConfig::getConfig();
1273 #ifndef SHIBSP_LITE
1274         SAMLConfig& samlConf=SAMLConfig::getConfig();
1275 #endif
1276         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1277         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1278         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1279
1280         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1281         if (conf.isEnabled(SPConfig::Logging)) {
1282             const XMLCh* logconf=nullptr;
1283             if (conf.isEnabled(SPConfig::OutOfProcess))
1284                 logconf=SHAR->getAttributeNS(nullptr,logger);
1285             else if (conf.isEnabled(SPConfig::InProcess))
1286                 logconf=SHIRE->getAttributeNS(nullptr,logger);
1287             if (!logconf || !*logconf)
1288                 logconf=e->getAttributeNS(nullptr,logger);
1289             if (logconf && *logconf) {
1290                 auto_ptr_char logpath(logconf);
1291                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1292                 if (!XMLToolingConfig::getConfig().log_config(logpath.get()))
1293                     log.crit("failed to load new logging configuration from (%s)", logpath.get());
1294             }
1295
1296 #ifndef SHIBSP_LITE
1297             if (first)
1298                 m_outer->m_tranLog = new TransactionLog();
1299 #endif
1300         }
1301
1302         // Re-log library versions now that logging is set up.
1303         log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1304 #ifndef SHIBSP_LITE
1305         log.info(
1306             "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1307             XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1308             );
1309 #else
1310         log.info(
1311             "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1312             XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1313             );
1314 #endif
1315
1316         // First load any property sets.
1317         load(e,nullptr,this);
1318
1319         const DOMElement* child;
1320         string plugtype;
1321
1322         // Much of the processing can only occur on the first instantiation.
1323         if (first) {
1324             // Set clock skew.
1325             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1326             if (skew.first)
1327                 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1328
1329             pair<bool,const char*> unsafe = getString("unsafeChars");
1330             if (unsafe.first)
1331                 TemplateEngine::unsafe_chars = unsafe.second;
1332
1333             unsafe = getString("allowedSchemes");
1334             if (unsafe.first) {
1335                 HTTPResponse::getAllowedSchemes().clear();
1336                 string schemes=unsafe.second;
1337                 unsigned int j_sch=0;
1338                 for (unsigned int i_sch=0;  i_sch < schemes.length();  i_sch++) {
1339                     if (schemes.at(i_sch)==' ') {
1340                         HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, i_sch-j_sch));
1341                         j_sch = i_sch + 1;
1342                     }
1343                 }
1344                 HTTPResponse::getAllowedSchemes().push_back(schemes.substr(j_sch, schemes.length()-j_sch));
1345             }
1346
1347             // Extensions
1348             doExtensions(e, "global", log);
1349             if (conf.isEnabled(SPConfig::OutOfProcess))
1350                 doExtensions(SHAR, "out of process", log);
1351
1352             if (conf.isEnabled(SPConfig::InProcess))
1353                 doExtensions(SHIRE, "in process", log);
1354
1355             // Instantiate the ListenerService and SessionCache objects.
1356             if (conf.isEnabled(SPConfig::Listener)) {
1357                 child=XMLHelper::getFirstChildElement(e,UnixListener);
1358                 if (child)
1359                     plugtype=UNIX_LISTENER_SERVICE;
1360                 else {
1361                     child=XMLHelper::getFirstChildElement(e,TCPListener);
1362                     if (child)
1363                         plugtype=TCP_LISTENER_SERVICE;
1364                     else {
1365                         child=XMLHelper::getFirstChildElement(e,Listener);
1366                         if (child) {
1367                             auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1368                             if (type.get())
1369                                 plugtype=type.get();
1370                         }
1371                     }
1372                 }
1373                 if (child) {
1374                     log.info("building ListenerService of type %s...", plugtype.c_str());
1375                     m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1376                 }
1377                 else {
1378                     log.fatal("can't build ListenerService, missing conf:Listener element?");
1379                     throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1380                 }
1381             }
1382
1383 #ifndef SHIBSP_LITE
1384             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1385                 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1386                 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1387                 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1388                 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1389             }
1390 #endif
1391
1392             if (conf.isEnabled(SPConfig::Caching)) {
1393                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1394 #ifndef SHIBSP_LITE
1395                     // First build any StorageServices.
1396                     child=XMLHelper::getFirstChildElement(e,_StorageService);
1397                     while (child) {
1398                         auto_ptr_char id(child->getAttributeNS(nullptr,_id));
1399                         auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1400                         try {
1401                             log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1402                             m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1403                         }
1404                         catch (exception& ex) {
1405                             log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1406                         }
1407                         child=XMLHelper::getNextSiblingElement(child,_StorageService);
1408                     }
1409
1410                     // Replay cache.
1411                     StorageService* replaySS=nullptr;
1412                     child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1413                     if (child) {
1414                         auto_ptr_char ssid(child->getAttributeNS(nullptr,_StorageService));
1415                         if (ssid.get() && *ssid.get()) {
1416                             if (m_outer->m_storage.count(ssid.get()))
1417                                 replaySS = m_outer->m_storage[ssid.get()];
1418                             if (replaySS)
1419                                 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1420                             else
1421                                 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1422                         }
1423                         xmlConf.setReplayCache(new ReplayCache(replaySS));
1424                     }
1425                     else {
1426                         log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1427                     }
1428
1429                     // ArtifactMap
1430                     child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1431                     if (child) {
1432                         auto_ptr_char ssid(child->getAttributeNS(nullptr,_StorageService));
1433                         if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1434                             log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1435                             samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1436                         }
1437                     }
1438                     if (samlConf.getArtifactMap()==nullptr) {
1439                         log.info("building in-memory ArtifactMap...");
1440                         samlConf.setArtifactMap(new ArtifactMap(child));
1441                     }
1442 #endif
1443                 }
1444                 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1445                 if (child) {
1446                     auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1447                     log.info("building SessionCache of type %s...",type.get());
1448                     m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1449                 }
1450                 else {
1451                     log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1452                     throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1453                 }
1454             }
1455
1456 #ifndef SHIBSP_LITE
1457             child = XMLHelper::getLastChildElement(e, SecurityPolicies);
1458             if (child) {
1459                 const XMLCh* algs = nullptr;
1460                 const DOMElement* alglist = XMLHelper::getLastChildElement(child, AlgorithmBlacklist);
1461                 if (alglist && alglist->hasChildNodes()) {
1462                     algs = alglist->getFirstChild()->getNodeValue();
1463                 }
1464                 else if ((alglist = XMLHelper::getLastChildElement(child, AlgorithmWhitelist)) && alglist->hasChildNodes()) {
1465                     algs = alglist->getFirstChild()->getNodeValue();
1466                 }
1467                 if (algs) {
1468 #ifdef SHIBSP_XMLSEC_WHITELISTING
1469                     const XMLCh* token;
1470                     XMLStringTokenizer tokenizer(algs);
1471                     while (tokenizer.hasMoreTokens()) {
1472                         token = tokenizer.nextToken();
1473                         if (token) {
1474                             if (XMLString::equals(alglist->getLocalName(), AlgorithmBlacklist))
1475                                 XSECPlatformUtils::blacklistAlgorithm(token);
1476                             else
1477                                 XSECPlatformUtils::whitelistAlgorithm(token);
1478                         }
1479                     }
1480 #else
1481                     log.fatal("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
1482                     throw ConfigurationException("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists.");
1483 #endif
1484                 }
1485             }
1486 #endif
1487         } // end of first-time-only stuff
1488
1489         // Back to the fully dynamic stuff...next up is the RequestMapper.
1490         if (conf.isEnabled(SPConfig::RequestMapping)) {
1491             child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1492             if (child) {
1493                 auto_ptr_char type(child->getAttributeNS(nullptr,_type));
1494                 log.info("building RequestMapper of type %s...",type.get());
1495                 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1496             }
1497             else {
1498                 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1499                 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1500             }
1501         }
1502
1503 #ifndef SHIBSP_LITE
1504         // Load security policies.
1505         child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1506         if (child) {
1507             PolicyNodeFilter filter;
1508             child = XMLHelper::getFirstChildElement(child,Policy);
1509             while (child) {
1510                 auto_ptr_char id(child->getAttributeNS(nullptr,_id));
1511                 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1512                 rules.first = nullptr;
1513                 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1514                 settings->load(child, nullptr, &filter);
1515                 rules.first = settings.release();
1516
1517                 // Process PolicyRule elements.
1518                 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1519                 while (rule) {
1520                     auto_ptr_char type(rule->getAttributeNS(nullptr,_type));
1521                     try {
1522                         rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1523                     }
1524                     catch (exception& ex) {
1525                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1526                     }
1527                     rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1528                 }
1529
1530                 if (rules.second.size() == 0) {
1531                     // Process Rule elements.
1532                     log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1533                     rule = XMLHelper::getFirstChildElement(child,Rule);
1534                     while (rule) {
1535                         auto_ptr_char type(rule->getAttributeNS(nullptr,_type));
1536                         try {
1537                             rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1538                         }
1539                         catch (exception& ex) {
1540                             log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1541                         }
1542                         rule = XMLHelper::getNextSiblingElement(rule,Rule);
1543                     }
1544
1545                     // Manually add a basic Conditions rule.
1546                     log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1547                     rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, nullptr));
1548                 }
1549
1550                 child = XMLHelper::getNextSiblingElement(child,Policy);
1551             }
1552         }
1553
1554         // Process TransportOption elements.
1555         child = XMLHelper::getLastChildElement(e,TransportOption);
1556         while (child) {
1557             if (child->hasChildNodes()) {
1558                 auto_ptr_char provider(child->getAttributeNS(nullptr,_provider));
1559                 auto_ptr_char option(child->getAttributeNS(nullptr,_option));
1560                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1561                 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1562                     m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1563                 }
1564             }
1565             child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1566         }
1567 #endif
1568
1569         // Load the default application. This actually has a fixed ID of "default". ;-)
1570         child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1571         if (!child) {
1572             log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1573             throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1574         }
1575         XMLApplication* defapp=new XMLApplication(m_outer,child);
1576         m_appmap[defapp->getId()]=defapp;
1577
1578         // Load any overrides.
1579         child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1580         while (child) {
1581             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1582             if (m_appmap.count(iapp->getId()))
1583                 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1584             else {
1585                 const char* iappid=iapp->getId();
1586                 m_appmap[iappid]=iapp.release();
1587             }
1588
1589             child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1590         }
1591     }
1592     catch (exception&) {
1593         cleanup();
1594         throw;
1595     }
1596 }
1597
1598 XMLConfigImpl::~XMLConfigImpl()
1599 {
1600     cleanup();
1601 }
1602
1603 void XMLConfigImpl::cleanup()
1604 {
1605     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1606     m_appmap.clear();
1607 #ifndef SHIBSP_LITE
1608     for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1609         delete i->second.first;
1610         for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1611     }
1612     m_policyMap.clear();
1613 #endif
1614     delete m_requestMapper;
1615     m_requestMapper = nullptr;
1616     if (m_document)
1617         m_document->release();
1618     m_document = nullptr;
1619 }
1620
1621 #ifndef SHIBSP_LITE
1622 void XMLConfig::receive(DDF& in, ostream& out)
1623 {
1624     if (!strcmp(in.name(), "get::RelayState")) {
1625         const char* id = in["id"].string();
1626         const char* key = in["key"].string();
1627         if (!id || !key)
1628             throw ListenerException("Required parameters missing for RelayState recovery.");
1629
1630         string relayState;
1631         StorageService* storage = getStorageService(id);
1632         if (storage) {
1633             if (storage->readString("RelayState",key,&relayState)>0) {
1634                 if (in["clear"].integer())
1635                     storage->deleteString("RelayState",key);
1636             }
1637         }
1638         else {
1639             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1640                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1641                 );
1642         }
1643
1644         // Repack for return to caller.
1645         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
1646         DDFJanitor jret(ret);
1647         out << ret;
1648     }
1649     else if (!strcmp(in.name(), "set::RelayState")) {
1650         const char* id = in["id"].string();
1651         const char* value = in["value"].string();
1652         if (!id || !value)
1653             throw ListenerException("Required parameters missing for RelayState creation.");
1654
1655         string rsKey;
1656         StorageService* storage = getStorageService(id);
1657         if (storage) {
1658             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1659             rsKey = SAMLArtifact::toHex(rsKey);
1660             storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
1661         }
1662         else {
1663             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1664                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1665                 );
1666         }
1667
1668         // Repack for return to caller.
1669         DDF ret=DDF(nullptr).string(rsKey.c_str());
1670         DDFJanitor jret(ret);
1671         out << ret;
1672     }
1673     else if (!strcmp(in.name(), "get::PostData")) {
1674         const char* id = in["id"].string();
1675         const char* key = in["key"].string();
1676         if (!id || !key)
1677             throw ListenerException("Required parameters missing for PostData recovery.");
1678
1679         string postData;
1680         StorageService* storage = getStorageService(id);
1681         if (storage) {
1682             if (storage->readString("PostData",key,&postData) > 0) {
1683                 storage->deleteString("PostData",key);
1684             }
1685         }
1686         else {
1687             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1688                 "Storage-backed PostData with invalid StorageService ID (%s)", id
1689                 );
1690         }
1691         // If the data's empty, we'll send nothing back.
1692         // If not, we don't need to round trip it, just send back the serialized DDF list.
1693         if (postData.empty()) {
1694             DDF ret(nullptr);
1695             DDFJanitor jret(ret);
1696             out << ret;
1697         }
1698         else {
1699             out << postData;
1700         }
1701     }
1702     else if (!strcmp(in.name(), "set::PostData")) {
1703         const char* id = in["id"].string();
1704         if (!id || !in["parameters"].islist())
1705             throw ListenerException("Required parameters missing for PostData creation.");
1706
1707         string rsKey;
1708         StorageService* storage = getStorageService(id);
1709         if (storage) {
1710             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1711             rsKey = SAMLArtifact::toHex(rsKey);
1712             ostringstream params;
1713             params << in["parameters"];
1714             storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
1715         }
1716         else {
1717             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1718                 "Storage-backed PostData with invalid StorageService ID (%s)", id
1719                 );
1720         }
1721
1722         // Repack for return to caller.
1723         DDF ret=DDF(nullptr).string(rsKey.c_str());
1724         DDFJanitor jret(ret);
1725         out << ret;
1726     }
1727 }
1728 #endif
1729
1730 pair<bool,DOMElement*> XMLConfig::background_load()
1731 {
1732     // Load from source using base class.
1733     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1734
1735     // If we own it, wrap it.
1736     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1737
1738     XMLConfigImpl* impl = new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log);
1739
1740     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1741     impl->setDocument(docjanitor.release());
1742
1743     // Perform the swap inside a lock.
1744     if (m_lock)
1745         m_lock->wrlock();
1746     SharedLock locker(m_lock, false);
1747     delete m_impl;
1748     m_impl = impl;
1749
1750     return make_pair(false,(DOMElement*)nullptr);
1751 }