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