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