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