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