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