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