Imported Upstream version 2.2.1+dfsg
[shibboleth/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     wrap = wrap.substr(0,wrap.find(';'));
1168     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1169     if (i!=m_handlerMap.end())
1170         return i->second;
1171     return m_base ? m_base->getHandler(path) : NULL;
1172 }
1173
1174 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1175 {
1176     handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1177     if (m_base) {
1178         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1179             if (m_handlerMap.count(h->first) == 0)
1180                 handlers.push_back(h->second);
1181         }
1182     }
1183 }
1184
1185 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1186 short
1187 #else
1188 DOMNodeFilter::FilterAction
1189 #endif
1190 XMLConfigImpl::acceptNode(const DOMNode* node) const
1191 {
1192     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1193         return FILTER_ACCEPT;
1194     const XMLCh* name=node->getLocalName();
1195     if (XMLString::equals(name,ApplicationDefaults) ||
1196         XMLString::equals(name,_ArtifactMap) ||
1197         XMLString::equals(name,_Extensions) ||
1198         XMLString::equals(name,Listener) ||
1199         XMLString::equals(name,_RequestMapper) ||
1200         XMLString::equals(name,_ReplayCache) ||
1201         XMLString::equals(name,SecurityPolicies) ||
1202         XMLString::equals(name,_SessionCache) ||
1203         XMLString::equals(name,Site) ||
1204         XMLString::equals(name,_StorageService) ||
1205         XMLString::equals(name,TCPListener) ||
1206         XMLString::equals(name,TransportOption) ||
1207         XMLString::equals(name,UnixListener))
1208         return FILTER_REJECT;
1209
1210     return FILTER_ACCEPT;
1211 }
1212
1213 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1214 {
1215     const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1216     if (exts) {
1217         exts=XMLHelper::getFirstChildElement(exts,Library);
1218         while (exts) {
1219             auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1220             try {
1221                 if (path.get()) {
1222                     if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1223                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1224                     log.debug("loaded %s extension library (%s)", label, path.get());
1225                 }
1226             }
1227             catch (exception& e) {
1228                 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1229                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1230                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1231                     throw;
1232                 }
1233                 else {
1234                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1235                 }
1236             }
1237             exts=XMLHelper::getNextSiblingElement(exts,Library);
1238         }
1239     }
1240 }
1241
1242 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1243     : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1244 {
1245 #ifdef _DEBUG
1246     xmltooling::NDC ndc("XMLConfigImpl");
1247 #endif
1248
1249     try {
1250         SPConfig& conf=SPConfig::getConfig();
1251 #ifndef SHIBSP_LITE
1252         SAMLConfig& samlConf=SAMLConfig::getConfig();
1253 #endif
1254         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1255         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1256         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1257
1258         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1259         if (conf.isEnabled(SPConfig::Logging)) {
1260             const XMLCh* logconf=NULL;
1261             if (conf.isEnabled(SPConfig::OutOfProcess))
1262                 logconf=SHAR->getAttributeNS(NULL,logger);
1263             else if (conf.isEnabled(SPConfig::InProcess))
1264                 logconf=SHIRE->getAttributeNS(NULL,logger);
1265             if (!logconf || !*logconf)
1266                 logconf=e->getAttributeNS(NULL,logger);
1267             if (logconf && *logconf) {
1268                 auto_ptr_char logpath(logconf);
1269                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1270                 if (!XMLToolingConfig::getConfig().log_config(logpath.get()))
1271                     log.crit("failed to load new logging configuration from (%s)", 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 }