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