Redesign condition and profile processing based on new policy rules. Fix element...
[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 PolicyRule[] =           UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
434     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
435     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
436     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
437     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
438     static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);
439     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
440     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
441     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
442     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);
443     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
444     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
445     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
446     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
447     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
448     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
449     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
450
451 #ifndef SHIBSP_LITE
452     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
453     {
454     public:
455 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
456         short
457 #else
458         FilterAction
459 #endif
460         acceptNode(const DOMNode* node) const {
461             return FILTER_REJECT;
462         }
463     };
464 #endif
465 };
466
467 namespace shibsp {
468     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
469     {
470         return new XMLConfig(e);
471     }
472 };
473
474 XMLApplication::XMLApplication(
475     const ServiceProvider* sp,
476     const DOMElement* e,
477     const XMLApplication* base
478     ) : Application(sp), m_base(base),
479 #ifndef SHIBSP_LITE
480         m_metadata(NULL), m_trust(NULL),
481         m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
482         m_credResolver(NULL),
483 #endif
484         m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
485 {
486 #ifdef _DEBUG
487     xmltooling::NDC ndc("XMLApplication");
488 #endif
489     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
490
491     try {
492         // First load any property sets.
493         load(e,NULL,this);
494         if (base)
495             setParent(base);
496
497         SPConfig& conf=SPConfig::getConfig();
498 #ifndef SHIBSP_LITE
499         SAMLConfig& samlConf=SAMLConfig::getConfig();
500         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
501 #endif
502
503         // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
504         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
505         string tohash=getId();
506         tohash+=getString("entityID").second;
507         for (const char* ch = tohash.c_str(); *ch; ++ch) {
508             m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
509             m_hash += (DIGITS[0x0F & *ch]);
510         }
511
512         // Populate prefix pair.
513         m_attributePrefix.second = "HTTP_";
514         pair<bool,const char*> prefix = getString("attributePrefix");
515         if (prefix.first) {
516             m_attributePrefix.first = prefix.second;
517             const char* pch = prefix.second;
518             while (*pch) {
519                 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
520                 pch++;
521             }
522         }
523
524         // Load attribute ID lists for REMOTE_USER and header clearing.
525         if (conf.isEnabled(SPConfig::InProcess)) {
526             pair<bool,const char*> attributes = getString("REMOTE_USER");
527             if (attributes.first) {
528                 char* dup = strdup(attributes.second);
529                 char* pos;
530                 char* start = dup;
531                 while (start && *start) {
532                     while (*start && isspace(*start))
533                         start++;
534                     if (!*start)
535                         break;
536                     pos = strchr(start,' ');
537                     if (pos)
538                         *pos=0;
539                     m_remoteUsers.push_back(start);
540                     start = pos ? pos+1 : NULL;
541                 }
542                 free(dup);
543             }
544
545             attributes = getString("unsetHeaders");
546             if (attributes.first) {
547                 string transformedprefix(m_attributePrefix.second);
548                 const char* pch;
549                 prefix = getString("metadataAttributePrefix");
550                 if (prefix.first) {
551                     pch = prefix.second;
552                     while (*pch) {
553                         transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
554                         pch++;
555                     }
556                 }
557                 char* dup = strdup(attributes.second);
558                 char* pos;
559                 char* start = dup;
560                 while (start && *start) {
561                     while (*start && isspace(*start))
562                         start++;
563                     if (!*start)
564                         break;
565                     pos = strchr(start,' ');
566                     if (pos)
567                         *pos=0;
568
569                     string transformed;
570                     pch = start;
571                     while (*pch) {
572                         transformed += (isalnum(*pch) ? toupper(*pch) : '_');
573                         pch++;
574                     }
575
576                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
577                     if (prefix.first)
578                         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
579                     start = pos ? pos+1 : NULL;
580                 }
581                 free(dup);
582                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
583             }
584         }
585
586         Handler* handler=NULL;
587         const PropertySet* sessions = getPropertySet("Sessions");
588
589         // Process assertion export handler.
590         pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
591         if (location.first) {
592             try {
593                 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
594                 exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
595                 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
596                 if (exportACL.first) {
597                     static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
598                     exportElement->setAttributeNS(NULL,_acl,exportACL.second);
599                 }
600                 handler = conf.HandlerManager.newPlugin(
601                     samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
602                     );
603                 m_handlers.push_back(handler);
604
605                 // Insert into location map. If it contains the handlerURL, we skip past that part.
606                 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
607                 if (pch)
608                     location.second = pch + strlen(sessions->getString("handlerURL").second);
609                 if (*location.second == '/')
610                     m_handlerMap[location.second]=handler;
611                 else
612                     m_handlerMap[string("/") + location.second]=handler;
613             }
614             catch (exception& ex) {
615                 log.error("caught exception installing assertion lookup handler: %s", ex.what());
616             }
617         }
618
619         // Process other handlers.
620         bool hardACS=false, hardSessionInit=false, hardArt=false;
621         const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
622         while (child) {
623             try {
624                 // A handler is based on the Binding property in conjunction with the element name.
625                 // If it's an ACS or SI, also handle index/id mappings and defaulting.
626                 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
627                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
628                     if (!bindprop.get() || !*(bindprop.get())) {
629                         log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
630                         child = XMLHelper::getNextSiblingElement(child);
631                         continue;
632                     }
633                     handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
634                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
635 #ifdef HAVE_GOOD_STL
636                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
637 #else
638                     m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
639 #endif
640                     m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
641
642                     if (!hardACS) {
643                         pair<bool,bool> defprop=handler->getBool("isDefault");
644                         if (defprop.first) {
645                             if (defprop.second) {
646                                 hardACS=true;
647                                 m_acsDefault=handler;
648                             }
649                         }
650                         else if (!m_acsDefault)
651                             m_acsDefault=handler;
652                     }
653                 }
654                 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
655                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
656                     if (!type.get() || !*(type.get())) {
657                         log.warn("SessionInitiator element has no type attribute, skipping it...");
658                         child = XMLHelper::getNextSiblingElement(child);
659                         continue;
660                     }
661                     SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
662                     handler=sihandler;
663                     pair<bool,const char*> si_id=handler->getString("id");
664                     if (si_id.first && si_id.second)
665                         m_sessionInitMap[si_id.second]=sihandler;
666                     if (!hardSessionInit) {
667                         pair<bool,bool> defprop=handler->getBool("isDefault");
668                         if (defprop.first) {
669                             if (defprop.second) {
670                                 hardSessionInit=true;
671                                 m_sessionInitDefault=sihandler;
672                             }
673                         }
674                         else if (!m_sessionInitDefault)
675                             m_sessionInitDefault=sihandler;
676                     }
677                 }
678                 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
679                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
680                     if (!type.get() || !*(type.get())) {
681                         log.warn("LogoutInitiator element has no type attribute, skipping it...");
682                         child = XMLHelper::getNextSiblingElement(child);
683                         continue;
684                     }
685                     handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
686                 }
687                 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
688                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
689                     if (!bindprop.get() || !*(bindprop.get())) {
690                         log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
691                         child = XMLHelper::getNextSiblingElement(child);
692                         continue;
693                     }
694                     handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
695
696                     if (!hardArt) {
697                         pair<bool,bool> defprop=handler->getBool("isDefault");
698                         if (defprop.first) {
699                             if (defprop.second) {
700                                 hardArt=true;
701                                 m_artifactResolutionDefault=handler;
702                             }
703                         }
704                         else if (!m_artifactResolutionDefault)
705                             m_artifactResolutionDefault=handler;
706                     }
707                 }
708                 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
709                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
710                     if (!bindprop.get() || !*(bindprop.get())) {
711                         log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
712                         child = XMLHelper::getNextSiblingElement(child);
713                         continue;
714                     }
715                     handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
716                 }
717                 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
718                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
719                     if (!bindprop.get() || !*(bindprop.get())) {
720                         log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
721                         child = XMLHelper::getNextSiblingElement(child);
722                         continue;
723                     }
724                     handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
725                 }
726                 else {
727                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
728                     if (!type.get() || !*(type.get())) {
729                         log.warn("Handler element has no type attribute, skipping it...");
730                         child = XMLHelper::getNextSiblingElement(child);
731                         continue;
732                     }
733                     handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
734                 }
735
736                 m_handlers.push_back(handler);
737
738                 // Insert into location map.
739                 location=handler->getString("Location");
740                 if (location.first && *location.second == '/')
741                     m_handlerMap[location.second]=handler;
742                 else if (location.first)
743                     m_handlerMap[string("/") + location.second]=handler;
744
745             }
746             catch (exception& ex) {
747                 log.error("caught exception processing handler element: %s", ex.what());
748             }
749
750             child = XMLHelper::getNextSiblingElement(child);
751         }
752
753         // Notification.
754         DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
755         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
756             if (nlist->item(i)->getParentNode()->isSameNode(e)) {
757                 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
758                 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
759                 if (loc.get() && *loc.get()) {
760                     if (channel && *channel == chLatin_f)
761                         m_frontLogout.push_back(loc.get());
762                     else
763                         m_backLogout.push_back(loc.get());
764                 }
765             }
766         }
767
768 #ifndef SHIBSP_LITE
769         nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
770         if (nlist && nlist->getLength()) {
771             log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
772             for (XMLSize_t i=0; i<nlist->getLength(); i++)
773                 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
774                     m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
775         }
776
777         if (conf.isEnabled(SPConfig::Metadata)) {
778             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
779             if (child) {
780                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
781                 log.info("building MetadataProvider of type %s...",type.get());
782                 try {
783                     auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
784                     mp->init();
785                     m_metadata = mp.release();
786                 }
787                 catch (exception& ex) {
788                     log.crit("error building/initializing MetadataProvider: %s", ex.what());
789                 }
790             }
791         }
792
793         if (conf.isEnabled(SPConfig::Trust)) {
794             child = XMLHelper::getFirstChildElement(e,_TrustEngine);
795             if (child) {
796                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
797                 log.info("building TrustEngine of type %s...",type.get());
798                 try {
799                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
800                 }
801                 catch (exception& ex) {
802                     log.crit("error building TrustEngine: %s", ex.what());
803                 }
804             }
805         }
806
807         if (conf.isEnabled(SPConfig::AttributeResolution)) {
808             child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
809             if (child) {
810                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
811                 log.info("building AttributeExtractor of type %s...",type.get());
812                 try {
813                     m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
814                 }
815                 catch (exception& ex) {
816                     log.crit("error building AttributeExtractor: %s", ex.what());
817                 }
818             }
819
820             child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
821             if (child) {
822                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
823                 log.info("building AttributeFilter of type %s...",type.get());
824                 try {
825                     m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
826                 }
827                 catch (exception& ex) {
828                     log.crit("error building AttributeFilter: %s", ex.what());
829                 }
830             }
831
832             child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
833             if (child) {
834                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
835                 log.info("building AttributeResolver of type %s...",type.get());
836                 try {
837                     m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
838                 }
839                 catch (exception& ex) {
840                     log.crit("error building AttributeResolver: %s", ex.what());
841                 }
842             }
843
844             if (m_unsetHeaders.empty()) {
845                 vector<string> unsetHeaders;
846                 if (m_attrExtractor) {
847                     Locker extlock(m_attrExtractor);
848                     m_attrExtractor->getAttributeIds(unsetHeaders);
849                 }
850                 else if (m_base && m_base->m_attrExtractor) {
851                     Locker extlock(m_base->m_attrExtractor);
852                     m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
853                 }
854                 if (m_attrResolver) {
855                     Locker reslock(m_attrResolver);
856                     m_attrResolver->getAttributeIds(unsetHeaders);
857                 }
858                 else if (m_base && m_base->m_attrResolver) {
859                     Locker extlock(m_base->m_attrResolver);
860                     m_base->m_attrResolver->getAttributeIds(unsetHeaders);
861                 }
862                 if (!unsetHeaders.empty()) {
863                     string transformedprefix(m_attributePrefix.second);
864                     const char* pch;
865                     pair<bool,const char*> prefix = getString("metadataAttributePrefix");
866                     if (prefix.first) {
867                         pch = prefix.second;
868                         while (*pch) {
869                             transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
870                             pch++;
871                         }
872                     }
873                     for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
874                         string transformed;
875                         pch = hdr->c_str();
876                         while (*pch) {
877                             transformed += (isalnum(*pch) ? toupper(*pch) : '_');
878                             pch++;
879                         }
880                         m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
881                         if (prefix.first)
882                             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
883                     }
884                 }
885                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
886             }
887         }
888
889         if (conf.isEnabled(SPConfig::Credentials)) {
890             child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
891             if (child) {
892                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
893                 log.info("building CredentialResolver of type %s...",type.get());
894                 try {
895                     m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
896                 }
897                 catch (exception& ex) {
898                     log.crit("error building CredentialResolver: %s", ex.what());
899                 }
900             }
901         }
902
903         // Finally, load relying parties.
904         child = XMLHelper::getFirstChildElement(e,RelyingParty);
905         while (child) {
906             auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
907             rp->load(child,NULL,this);
908             rp->setParent(this);
909             m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
910             child = XMLHelper::getNextSiblingElement(child,RelyingParty);
911         }
912 #endif
913
914         // Out of process only, we register a listener endpoint.
915         if (!conf.isEnabled(SPConfig::InProcess)) {
916             ListenerService* listener = sp->getListenerService(false);
917             if (listener) {
918                 string addr=string(getId()) + "::getHeaders::Application";
919                 listener->regListener(addr.c_str(),this);
920             }
921             else
922                 log.info("no ListenerService available, Application remoting disabled");
923         }
924     }
925     catch (exception&) {
926         cleanup();
927         throw;
928     }
929 #ifndef _DEBUG
930     catch (...) {
931         cleanup();
932         throw;
933     }
934 #endif
935 }
936
937 void XMLApplication::cleanup()
938 {
939     ListenerService* listener=getServiceProvider().getListenerService(false);
940     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
941         string addr=string(getId()) + "::getHeaders::Application";
942         listener->unregListener(addr.c_str(),this);
943     }
944     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
945     m_handlers.clear();
946 #ifndef SHIBSP_LITE
947 #ifdef HAVE_GOOD_STL
948     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
949 #else
950     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
951 #endif
952     m_partyMap.clear();
953     delete m_credResolver;
954     m_credResolver = NULL;
955     delete m_attrResolver;
956     m_attrResolver = NULL;
957     delete m_attrFilter;
958     m_attrFilter = NULL;
959     delete m_attrExtractor;
960     m_attrExtractor = NULL;
961     delete m_trust;
962     m_trust = NULL;
963     delete m_metadata;
964     m_metadata = NULL;
965 #endif
966 }
967
968 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
969 short
970 #else
971 DOMNodeFilter::FilterAction
972 #endif
973 XMLApplication::acceptNode(const DOMNode* node) const
974 {
975     const XMLCh* name=node->getLocalName();
976     if (XMLString::equals(name,ApplicationOverride) ||
977         XMLString::equals(name,_Audience) ||
978         XMLString::equals(name,Notify) ||
979         XMLString::equals(name,_Handler) ||
980         XMLString::equals(name,_AssertionConsumerService) ||
981         XMLString::equals(name,_ArtifactResolutionService) ||
982         XMLString::equals(name,_LogoutInitiator) ||
983         XMLString::equals(name,_ManageNameIDService) ||
984         XMLString::equals(name,_SessionInitiator) ||
985         XMLString::equals(name,_SingleLogoutService) ||
986         XMLString::equals(name,RelyingParty) ||
987         XMLString::equals(name,_MetadataProvider) ||
988         XMLString::equals(name,_TrustEngine) ||
989         XMLString::equals(name,_CredentialResolver) ||
990         XMLString::equals(name,_AttributeFilter) ||
991         XMLString::equals(name,_AttributeExtractor) ||
992         XMLString::equals(name,_AttributeResolver))
993         return FILTER_REJECT;
994
995     return FILTER_ACCEPT;
996 }
997
998 #ifndef SHIBSP_LITE
999
1000 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1001 {
1002     if (!provider)
1003         return this;
1004
1005 #ifdef HAVE_GOOD_STL
1006     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1007     if (i!=m_partyMap.end())
1008         return i->second;
1009     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1010     while (group) {
1011         if (group->getName()) {
1012             i=m_partyMap.find(group->getName());
1013             if (i!=m_partyMap.end())
1014                 return i->second;
1015         }
1016         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1017     }
1018 #else
1019     map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1020     for (; i!=m_partyMap.end(); i++) {
1021         if (XMLString::equals(i->first,provider->getEntityID()))
1022             return i->second;
1023         const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1024         while (group) {
1025             if (XMLString::equals(i->first,group->getName()))
1026                 return i->second;
1027             group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1028         }
1029     }
1030 #endif
1031     return this;
1032 }
1033
1034 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1035 {
1036     if (!entityID)
1037         return this;
1038
1039 #ifdef HAVE_GOOD_STL
1040     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1041     if (i!=m_partyMap.end())
1042         return i->second;
1043 #else
1044     map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1045     for (; i!=m_partyMap.end(); i++) {
1046         if (XMLString::equals(i->first,entityID))
1047             return i->second;
1048     }
1049 #endif
1050     return this;
1051 }
1052
1053 #endif
1054
1055 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1056 {
1057     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1058     if (locs.empty())
1059         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1060     else if (index >= locs.size())
1061         return string();
1062
1063 #ifdef HAVE_STRCASECMP
1064     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1065 #else
1066     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1067 #endif
1068         throw ConfigurationException("Request URL was not absolute.");
1069
1070     const char* handler=locs[index].c_str();
1071
1072     // Should never happen...
1073     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1074         throw ConfigurationException(
1075             "Invalid Location property ($1) in Notify element for Application ($2)",
1076             params(2, handler ? handler : "null", getId())
1077             );
1078
1079     // The "Location" property can be in one of three formats:
1080     //
1081     // 1) a full URI:       http://host/foo/bar
1082     // 2) a hostless URI:   http:///foo/bar
1083     // 3) a relative path:  /foo/bar
1084     //
1085     // #  Protocol  Host        Path
1086     // 1  handler   handler     handler
1087     // 2  handler   resource    handler
1088     // 3  resource  resource    handler
1089
1090     const char* path = NULL;
1091
1092     // Decide whether to use the handler or the resource for the "protocol"
1093     const char* prot;
1094     if (*handler != '/') {
1095         prot = handler;
1096     }
1097     else {
1098         prot = resource;
1099         path = handler;
1100     }
1101
1102     // break apart the "protocol" string into protocol, host, and "the rest"
1103     const char* colon=strchr(prot,':');
1104     colon += 3;
1105     const char* slash=strchr(colon,'/');
1106     if (!path)
1107         path = slash;
1108
1109     // Compute the actual protocol and store.
1110     string notifyURL(prot, colon-prot);
1111
1112     // create the "host" from either the colon/slash or from the target string
1113     // If prot == handler then we're in either #1 or #2, else #3.
1114     // If slash == colon then we're in #2.
1115     if (prot != handler || slash == colon) {
1116         colon = strchr(resource, ':');
1117         colon += 3;      // Get past the ://
1118         slash = strchr(colon, '/');
1119     }
1120     string host(colon, (slash ? slash-colon : strlen(colon)));
1121
1122     // Build the URL
1123     notifyURL += host + path;
1124     return notifyURL;
1125 }
1126
1127 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1128 {
1129     if (!m_attributePrefix.first.empty()) {
1130         string temp = m_attributePrefix.first + rawname;
1131         string temp2 = m_attributePrefix.second + (cginame + 5);
1132         request.clearHeader(temp.c_str(), temp2.c_str());
1133     }
1134     else if (m_base) {
1135         m_base->clearHeader(request, rawname, cginame);
1136     }
1137     else {
1138         request.clearHeader(rawname, cginame);
1139     }
1140 }
1141
1142 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1143 {
1144     if (!m_attributePrefix.first.empty()) {
1145         string temp = m_attributePrefix.first + name;
1146         request.setHeader(temp.c_str(), value);
1147     }
1148     else if (m_base) {
1149         m_base->setHeader(request, name, value);
1150     }
1151     else {
1152         request.setHeader(name, value);
1153     }
1154 }
1155
1156 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1157 {
1158     if (!m_attributePrefix.first.empty()) {
1159         string temp = m_attributePrefix.first + name;
1160         return request.getSecureHeader(temp.c_str());
1161     }
1162     else if (m_base) {
1163         return m_base->getSecureHeader(request,name);
1164     }
1165     else {
1166         return request.getSecureHeader(name);
1167     }
1168 }
1169
1170 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1171 {
1172     if (m_sessionInitDefault) return m_sessionInitDefault;
1173     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1174 }
1175
1176 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1177 {
1178     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1179     if (i!=m_sessionInitMap.end()) return i->second;
1180     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1181 }
1182
1183 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1184 {
1185     if (m_acsDefault) return m_acsDefault;
1186     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1187 }
1188
1189 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1190 {
1191     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1192     if (i!=m_acsIndexMap.end()) return i->second;
1193     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1194 }
1195
1196 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1197 {
1198 #ifdef HAVE_GOOD_STL
1199     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1200 #else
1201     auto_ptr_char temp(binding);
1202     ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
1203 #endif
1204     if (i!=m_acsBindingMap.end())
1205         return i->second;
1206     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1207 }
1208
1209 const Handler* XMLApplication::getHandler(const char* path) const
1210 {
1211     string wrap(path);
1212     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1213     if (i!=m_handlerMap.end())
1214         return i->second;
1215     return m_base ? m_base->getHandler(path) : NULL;
1216 }
1217
1218 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1219 {
1220     handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1221     if (m_base) {
1222         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1223             if (m_handlerMap.count(h->first) == 0)
1224                 handlers.push_back(h->second);
1225         }
1226     }
1227 }
1228
1229 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1230 short
1231 #else
1232 DOMNodeFilter::FilterAction
1233 #endif
1234 XMLConfigImpl::acceptNode(const DOMNode* node) const
1235 {
1236     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1237         return FILTER_ACCEPT;
1238     const XMLCh* name=node->getLocalName();
1239     if (XMLString::equals(name,ApplicationDefaults) ||
1240         XMLString::equals(name,_ArtifactMap) ||
1241         XMLString::equals(name,_Extensions) ||
1242         XMLString::equals(name,Listener) ||
1243         XMLString::equals(name,_RequestMapper) ||
1244         XMLString::equals(name,_ReplayCache) ||
1245         XMLString::equals(name,SecurityPolicies) ||
1246         XMLString::equals(name,_SessionCache) ||
1247         XMLString::equals(name,Site) ||
1248         XMLString::equals(name,_StorageService) ||
1249         XMLString::equals(name,TCPListener) ||
1250         XMLString::equals(name,TransportOption) ||
1251         XMLString::equals(name,UnixListener))
1252         return FILTER_REJECT;
1253
1254     return FILTER_ACCEPT;
1255 }
1256
1257 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1258 {
1259     const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1260     if (exts) {
1261         exts=XMLHelper::getFirstChildElement(exts,Library);
1262         while (exts) {
1263             auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1264             try {
1265                 if (path.get()) {
1266                     if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1267                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1268                     log.debug("loaded %s extension library (%s)", label, path.get());
1269                 }
1270             }
1271             catch (exception& e) {
1272                 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1273                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1274                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1275                     throw;
1276                 }
1277                 else {
1278                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1279                 }
1280             }
1281             exts=XMLHelper::getNextSiblingElement(exts,Library);
1282         }
1283     }
1284 }
1285
1286 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1287     : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1288 {
1289 #ifdef _DEBUG
1290     xmltooling::NDC ndc("XMLConfigImpl");
1291 #endif
1292
1293     try {
1294         SPConfig& conf=SPConfig::getConfig();
1295 #ifndef SHIBSP_LITE
1296         SAMLConfig& samlConf=SAMLConfig::getConfig();
1297 #endif
1298         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1299         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1300         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1301
1302         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1303         if (conf.isEnabled(SPConfig::Logging)) {
1304             const XMLCh* logconf=NULL;
1305             if (conf.isEnabled(SPConfig::OutOfProcess))
1306                 logconf=SHAR->getAttributeNS(NULL,logger);
1307             else if (conf.isEnabled(SPConfig::InProcess))
1308                 logconf=SHIRE->getAttributeNS(NULL,logger);
1309             if (!logconf || !*logconf)
1310                 logconf=e->getAttributeNS(NULL,logger);
1311             if (logconf && *logconf) {
1312                 auto_ptr_char logpath(logconf);
1313                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1314                 XMLToolingConfig::getConfig().log_config(logpath.get());
1315             }
1316
1317 #ifndef SHIBSP_LITE
1318             if (first)
1319                 m_outer->m_tranLog = new TransactionLog();
1320 #endif
1321         }
1322
1323         // Re-log library versions now that logging is set up.
1324 #ifndef SHIBSP_LITE
1325         log.info(
1326             "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1327             XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1328             );
1329 #else
1330         log.info(
1331             "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1332             XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1333             );
1334 #endif
1335
1336         // First load any property sets.
1337         load(e,NULL,this);
1338
1339         const DOMElement* child;
1340         string plugtype;
1341
1342         // Much of the processing can only occur on the first instantiation.
1343         if (first) {
1344             // Set clock skew.
1345             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1346             if (skew.first)
1347                 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1348
1349             pair<bool,const char*> unsafe = getString("unsafeChars");
1350             if (unsafe.first)
1351                 TemplateEngine::unsafe_chars = unsafe.second;
1352
1353             // Extensions
1354             doExtensions(e, "global", log);
1355             if (conf.isEnabled(SPConfig::OutOfProcess))
1356                 doExtensions(SHAR, "out of process", log);
1357
1358             if (conf.isEnabled(SPConfig::InProcess))
1359                 doExtensions(SHIRE, "in process", log);
1360
1361             // Instantiate the ListenerService and SessionCache objects.
1362             if (conf.isEnabled(SPConfig::Listener)) {
1363                 child=XMLHelper::getFirstChildElement(e,UnixListener);
1364                 if (child)
1365                     plugtype=UNIX_LISTENER_SERVICE;
1366                 else {
1367                     child=XMLHelper::getFirstChildElement(e,TCPListener);
1368                     if (child)
1369                         plugtype=TCP_LISTENER_SERVICE;
1370                     else {
1371                         child=XMLHelper::getFirstChildElement(e,Listener);
1372                         if (child) {
1373                             auto_ptr_char type(child->getAttributeNS(NULL,_type));
1374                             if (type.get())
1375                                 plugtype=type.get();
1376                         }
1377                     }
1378                 }
1379                 if (child) {
1380                     log.info("building ListenerService of type %s...", plugtype.c_str());
1381                     m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1382                 }
1383                 else {
1384                     log.fatal("can't build ListenerService, missing conf:Listener element?");
1385                     throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1386                 }
1387             }
1388
1389 #ifndef SHIBSP_LITE
1390             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1391                 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1392                 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1393                 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1394                 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1395             }
1396 #endif
1397
1398             if (conf.isEnabled(SPConfig::Caching)) {
1399                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1400 #ifndef SHIBSP_LITE
1401                     // First build any StorageServices.
1402                     child=XMLHelper::getFirstChildElement(e,_StorageService);
1403                     while (child) {
1404                         auto_ptr_char id(child->getAttributeNS(NULL,_id));
1405                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1406                         try {
1407                             log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1408                             m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1409                         }
1410                         catch (exception& ex) {
1411                             log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1412                         }
1413                         child=XMLHelper::getNextSiblingElement(child,_StorageService);
1414                     }
1415
1416                     // Replay cache.
1417                     StorageService* replaySS=NULL;
1418                     child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1419                     if (child) {
1420                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1421                         if (ssid.get() && *ssid.get()) {
1422                             if (m_outer->m_storage.count(ssid.get()))
1423                                 replaySS = m_outer->m_storage[ssid.get()];
1424                             if (replaySS)
1425                                 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1426                             else
1427                                 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1428                         }
1429                         xmlConf.setReplayCache(new ReplayCache(replaySS));
1430                     }
1431                     else {
1432                         log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1433                     }
1434
1435                     // ArtifactMap
1436                     child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1437                     if (child) {
1438                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1439                         if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1440                             log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1441                             samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1442                         }
1443                     }
1444                     if (samlConf.getArtifactMap()==NULL) {
1445                         log.info("building in-memory ArtifactMap...");
1446                         samlConf.setArtifactMap(new ArtifactMap(child));
1447                     }
1448 #endif
1449                 }
1450                 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1451                 if (child) {
1452                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
1453                     log.info("building SessionCache of type %s...",type.get());
1454                     m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1455                 }
1456                 else {
1457                     log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1458                     throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1459                 }
1460             }
1461         } // end of first-time-only stuff
1462
1463         // Back to the fully dynamic stuff...next up is the RequestMapper.
1464         if (conf.isEnabled(SPConfig::RequestMapping)) {
1465             child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1466             if (child) {
1467                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1468                 log.info("building RequestMapper of type %s...",type.get());
1469                 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1470             }
1471             else {
1472                 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1473                 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1474             }
1475         }
1476
1477 #ifndef SHIBSP_LITE
1478         // Load security policies.
1479         child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1480         if (child) {
1481             PolicyNodeFilter filter;
1482             child = XMLHelper::getFirstChildElement(child,Policy);
1483             while (child) {
1484                 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1485                 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1486                 rules.first = NULL;
1487                 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1488                 settings->load(child, NULL, &filter);
1489                 rules.first = settings.release();
1490
1491                 // Process PolicyRule elements.
1492                 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1493                 while (rule) {
1494                     auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1495                     try {
1496                         rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1497                     }
1498                     catch (exception& ex) {
1499                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1500                     }
1501                     rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1502                 }
1503
1504                 if (rules.second.size() == 0) {
1505                     // Process Rule elements.
1506                     log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1507                     rule = XMLHelper::getFirstChildElement(child,Rule);
1508                     while (rule) {
1509                         auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1510                         try {
1511                             rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1512                         }
1513                         catch (exception& ex) {
1514                             log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1515                         }
1516                         rule = XMLHelper::getNextSiblingElement(rule,Rule);
1517                     }
1518
1519                     // Manually add a basic Conditions rule.
1520                     log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1521                     rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, NULL));
1522                 }
1523
1524                 child = XMLHelper::getNextSiblingElement(child,Policy);
1525             }
1526         }
1527
1528         // Process TransportOption elements.
1529         child = XMLHelper::getLastChildElement(e,TransportOption);
1530         while (child) {
1531             if (child->hasChildNodes()) {
1532                 auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
1533                 auto_ptr_char option(child->getAttributeNS(NULL,_option));
1534                 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1535                 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1536                     m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1537                 }
1538             }
1539             child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1540         }
1541 #endif
1542
1543         // Load the default application. This actually has a fixed ID of "default". ;-)
1544         child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1545         if (!child) {
1546             log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1547             throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1548         }
1549         XMLApplication* defapp=new XMLApplication(m_outer,child);
1550         m_appmap[defapp->getId()]=defapp;
1551
1552         // Load any overrides.
1553         child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1554         while (child) {
1555             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1556             if (m_appmap.count(iapp->getId()))
1557                 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1558             else {
1559                 const char* iappid=iapp->getId();
1560                 m_appmap[iappid]=iapp.release();
1561             }
1562
1563             child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1564         }
1565     }
1566     catch (exception&) {
1567         cleanup();
1568         throw;
1569     }
1570 }
1571
1572 XMLConfigImpl::~XMLConfigImpl()
1573 {
1574     cleanup();
1575 }
1576
1577 void XMLConfigImpl::cleanup()
1578 {
1579     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1580     m_appmap.clear();
1581 #ifndef SHIBSP_LITE
1582     for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1583         delete i->second.first;
1584         for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1585     }
1586     m_policyMap.clear();
1587 #endif
1588     delete m_requestMapper;
1589     m_requestMapper = NULL;
1590     if (m_document)
1591         m_document->release();
1592     m_document = NULL;
1593 }
1594
1595 #ifndef SHIBSP_LITE
1596 void XMLConfig::receive(DDF& in, ostream& out)
1597 {
1598     if (!strcmp(in.name(), "get::RelayState")) {
1599         const char* id = in["id"].string();
1600         const char* key = in["key"].string();
1601         if (!id || !key)
1602             throw ListenerException("Required parameters missing for RelayState recovery.");
1603
1604         string relayState;
1605         StorageService* storage = getStorageService(id);
1606         if (storage) {
1607             if (storage->readString("RelayState",key,&relayState)>0) {
1608                 if (in["clear"].integer())
1609                     storage->deleteString("RelayState",key);
1610             }
1611         }
1612         else {
1613             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1614                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1615                 );
1616         }
1617
1618         // Repack for return to caller.
1619         DDF ret=DDF(NULL).string(relayState.c_str());
1620         DDFJanitor jret(ret);
1621         out << ret;
1622     }
1623     else if (!strcmp(in.name(), "set::RelayState")) {
1624         const char* id = in["id"].string();
1625         const char* value = in["value"].string();
1626         if (!id || !value)
1627             throw ListenerException("Required parameters missing for RelayState creation.");
1628
1629         string rsKey;
1630         StorageService* storage = getStorageService(id);
1631         if (storage) {
1632             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1633             rsKey = SAMLArtifact::toHex(rsKey);
1634             storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1635         }
1636         else {
1637             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1638                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1639                 );
1640         }
1641
1642         // Repack for return to caller.
1643         DDF ret=DDF(NULL).string(rsKey.c_str());
1644         DDFJanitor jret(ret);
1645         out << ret;
1646     }
1647     else if (!strcmp(in.name(), "get::PostData")) {
1648         const char* id = in["id"].string();
1649         const char* key = in["key"].string();
1650         if (!id || !key)
1651             throw ListenerException("Required parameters missing for PostData recovery.");
1652
1653         string postData;
1654         StorageService* storage = getStorageService(id);
1655         if (storage) {
1656             if (storage->readString("PostData",key,&postData) > 0) {
1657                 storage->deleteString("PostData",key);
1658             }
1659         }
1660         else {
1661             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1662                 "Storage-backed PostData with invalid StorageService ID (%s)", id
1663                 );
1664         }
1665         // If the data's empty, we'll send nothing back.
1666         // If not, we don't need to round trip it, just send back the serialized DDF list.
1667         if (postData.empty()) {
1668             DDF ret(NULL);
1669             DDFJanitor jret(ret);
1670             out << ret;
1671         }
1672         else {
1673             out << postData;
1674         }
1675     }
1676     else if (!strcmp(in.name(), "set::PostData")) {
1677         const char* id = in["id"].string();
1678         if (!id || !in["parameters"].islist())
1679             throw ListenerException("Required parameters missing for PostData creation.");
1680
1681         string rsKey;
1682         StorageService* storage = getStorageService(id);
1683         if (storage) {
1684             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1685             rsKey = SAMLArtifact::toHex(rsKey);
1686             ostringstream params;
1687             params << in["parameters"];
1688             storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(NULL) + 600);
1689         }
1690         else {
1691             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1692                 "Storage-backed PostData with invalid StorageService ID (%s)", id
1693                 );
1694         }
1695
1696         // Repack for return to caller.
1697         DDF ret=DDF(NULL).string(rsKey.c_str());
1698         DDFJanitor jret(ret);
1699         out << ret;
1700     }
1701 }
1702 #endif
1703
1704 pair<bool,DOMElement*> XMLConfig::load()
1705 {
1706     // Load from source using base class.
1707     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1708
1709     // If we own it, wrap it.
1710     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1711
1712     XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1713
1714     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1715     impl->setDocument(docjanitor.release());
1716
1717     delete m_impl;
1718     m_impl = impl;
1719
1720     return make_pair(false,(DOMElement*)NULL);
1721 }