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