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