Remove extra header
[shibboleth/cpp-sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLServiceProvider.cpp
23  *
24  * XML-based SP configuration and mgmt.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "version.h"
30 #include "AccessControl.h"
31 #include "Application.h"
32 #include "RequestMapper.h"
33 #include "ServiceProvider.h"
34 #include "SessionCache.h"
35 #include "SPConfig.h"
36 #include "SPRequest.h"
37 #include "binding/ProtocolProvider.h"
38 #include "handler/LogoutInitiator.h"
39 #include "handler/SessionInitiator.h"
40 #include "remoting/ListenerService.h"
41 #include "util/DOMPropertySet.h"
42 #include "util/SPConstants.h"
43
44 #if defined(XMLTOOLING_LOG4SHIB)
45 # include <log4shib/PropertyConfigurator.hh>
46 #elif defined(XMLTOOLING_LOG4CPP)
47 # include <log4cpp/PropertyConfigurator.hh>
48 #else
49 # error "Supported logging library not available."
50 #endif
51 #include <algorithm>
52 #include <boost/bind.hpp>
53 #include <boost/lexical_cast.hpp>
54 #include <boost/shared_ptr.hpp>
55 #include <boost/algorithm/string.hpp>
56 #include <boost/tuple/tuple.hpp>
57 #include <xercesc/util/XMLUniDefs.hpp>
58 #include <xercesc/util/XMLStringTokenizer.hpp>
59 #include <xmltooling/XMLToolingConfig.h>
60 #include <xmltooling/version.h>
61 #include <xmltooling/util/NDC.h>
62 #include <xmltooling/util/ReloadableXMLFile.h>
63 #include <xmltooling/util/TemplateEngine.h>
64 #include <xmltooling/util/Threads.h>
65 #include <xmltooling/util/XMLHelper.h>
66
67 #ifndef SHIBSP_LITE
68 # include "attribute/filtering/AttributeFilter.h"
69 # include "attribute/resolver/AttributeExtractor.h"
70 # include "attribute/resolver/AttributeResolver.h"
71 # include "security/PKIXTrustEngine.h"
72 # include "security/SecurityPolicyProvider.h"
73 # include <saml/exceptions.h>
74 # include <saml/version.h>
75 # include <saml/SAMLConfig.h>
76 # include <saml/binding/ArtifactMap.h>
77 # include <saml/binding/SAMLArtifact.h>
78 # include <saml/saml1/core/Assertions.h>
79 # include <saml/saml2/core/Assertions.h>
80 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
81 # include <saml/saml2/metadata/Metadata.h>
82 # include <saml/saml2/metadata/MetadataProvider.h>
83 # include <saml/util/SAMLConstants.h>
84 # include <xmltooling/security/ChainingTrustEngine.h>
85 # include <xmltooling/security/CredentialResolver.h>
86 # include <xmltooling/security/SecurityHelper.h>
87 # include <xmltooling/util/ReplayCache.h>
88 # include <xmltooling/util/StorageService.h>
89 # include <xsec/utils/XSECPlatformUtils.hpp>
90 using namespace opensaml::saml2;
91 using namespace opensaml::saml2p;
92 using namespace opensaml::saml2md;
93 using namespace opensaml;
94 #else
95 # include "lite/SAMLConstants.h"
96 #endif
97
98 using namespace shibsp;
99 using namespace xmltooling;
100 using namespace boost;
101 using namespace std;
102
103 #ifndef min
104 # define min(a,b)            (((a) < (b)) ? (a) : (b))
105 #endif
106
107 namespace {
108
109 #if defined (_MSC_VER)
110     #pragma warning( push )
111     #pragma warning( disable : 4250 )
112 #endif
113
114     static vector<const Handler*> g_noHandlers;
115
116     // Application configuration wrapper
117     class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
118     {
119     public:
120         XMLApplication(const ServiceProvider*, const ProtocolProvider*, DOMElement*, const XMLApplication* base=nullptr);
121         ~XMLApplication();
122
123         const char* getHash() const {return m_hash.c_str();}
124
125 #ifndef SHIBSP_LITE
126         SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
127             throw ConfigurationException("No support for SAML 1.x artifact generation.");
128         }
129         SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
130             pair<bool,int> index = make_pair(false,0);
131             const PropertySet* props = getRelyingParty(relyingParty);
132             index = props->getInt("artifactEndpointIndex");
133             if (!index.first)
134                 index = getArtifactEndpointIndex();
135             pair<bool,const char*> entityID = props->getString("entityID");
136             return new SAML2ArtifactType0004(
137                 SecurityHelper::doHash("SHA1", entityID.second, strlen(entityID.second), false),
138                 index.first ? index.second : 1
139                 );
140         }
141
142         MetadataProvider* getMetadataProvider(bool required=true) const {
143             if (required && !m_base && !m_metadata)
144                 throw ConfigurationException("No MetadataProvider available.");
145             return (!m_metadata && m_base) ? m_base->getMetadataProvider(required) : m_metadata.get();
146         }
147         TrustEngine* getTrustEngine(bool required=true) const {
148             if (required && !m_base && !m_trust)
149                 throw ConfigurationException("No TrustEngine available.");
150             return (!m_trust && m_base) ? m_base->getTrustEngine(required) : m_trust.get();
151         }
152         AttributeExtractor* getAttributeExtractor() const {
153             return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor.get();
154         }
155         AttributeFilter* getAttributeFilter() const {
156             return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter.get();
157         }
158         AttributeResolver* getAttributeResolver() const {
159             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver.get();
160         }
161         CredentialResolver* getCredentialResolver() const {
162             return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver.get();
163         }
164         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
165         const PropertySet* getRelyingParty(const XMLCh* entityID) const;
166         const vector<const XMLCh*>* getAudiences() const {
167             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
168         }
169 #endif
170         string getNotificationURL(const char* resource, bool front, unsigned int index) const;
171
172         const vector<string>& getRemoteUserAttributeIds() const {
173             return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
174         }
175
176         void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
177         void setHeader(SPRequest& request, const char* name, const char* value) const;
178         string getSecureHeader(const SPRequest& request, const char* name) const;
179
180         const SessionInitiator* getDefaultSessionInitiator() const;
181         const SessionInitiator* getSessionInitiatorById(const char* id) const;
182         const Handler* getDefaultAssertionConsumerService() const;
183         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
184         const Handler* getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding=nullptr) const;
185         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
186         const Handler* getHandler(const char* path) const;
187         void getHandlers(vector<const Handler*>& handlers) const;
188         void limitRedirect(const GenericRequest& request, const char* url) const;
189
190         void receive(DDF& in, ostream& out) {
191             // Only current function is to return the headers to clear.
192             DDF header;
193             DDF ret=DDF(nullptr).list();
194             DDFJanitor jret(ret);
195             for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
196                 header = DDF(i->first.c_str()).string(i->second.c_str());
197                 ret.add(header);
198             }
199             out << ret;
200         }
201
202         // Provides filter to exclude special config elements.
203 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
204         short
205 #else
206         FilterAction
207 #endif
208         acceptNode(const DOMNode* node) const;
209
210     private:
211         template <class T> T* doChainedPlugins(
212             PluginManager<T,string,const DOMElement*>& pluginMgr,
213             const char* pluginType,
214             const char* chainingType,
215             const XMLCh* localName,
216             DOMElement* e,
217             Category& log,
218             const char* dummyType=nullptr
219             );
220         void doAttributeInfo();
221         void doHandlers(const ProtocolProvider*, const DOMElement*, Category&);
222         void doSSO(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
223         void doLogout(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
224         void doNameIDMgmt(const ProtocolProvider&, set<string>&, DOMElement*, Category&);
225         void doArtifactResolution(const ProtocolProvider&, const char*, DOMElement*, Category&);
226         const XMLApplication* m_base;
227         string m_hash;
228         std::pair<std::string,std::string> m_attributePrefix;
229 #ifndef SHIBSP_LITE
230         void doAttributePlugins(DOMElement*, Category&);
231         scoped_ptr<MetadataProvider> m_metadata;
232         scoped_ptr<TrustEngine> m_trust;
233         scoped_ptr<AttributeExtractor> m_attrExtractor;
234         scoped_ptr<AttributeFilter> m_attrFilter;
235         scoped_ptr<AttributeResolver> m_attrResolver;
236         scoped_ptr<CredentialResolver> m_credResolver;
237         vector<const XMLCh*> m_audiences;
238
239         // RelyingParty properties
240         map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;
241 #endif
242         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
243
244         // manage handler objects
245         vector< boost::shared_ptr<Handler> > m_handlers;
246
247         // maps location (path info) to applicable handlers
248         map<string,const Handler*> m_handlerMap;
249
250         // maps unique indexes to consumer services
251         map<unsigned int,const Handler*> m_acsIndexMap;
252
253         // pointer to default consumer service
254         const Handler* m_acsDefault;
255
256         // maps binding strings to supporting consumer service(s)
257         typedef map< xstring,vector<const Handler*> > ACSBindingMap;
258         ACSBindingMap m_acsBindingMap;
259
260         // maps protocol strings to supporting consumer service(s)
261         typedef map< xstring,vector<const Handler*> > ACSProtocolMap;
262         ACSProtocolMap m_acsProtocolMap;
263
264         // pointer to default session initiator
265         const SessionInitiator* m_sessionInitDefault;
266
267         // maps unique ID strings to session initiators
268         map<string,const SessionInitiator*> m_sessionInitMap;
269
270         // pointer to default artifact resolution service
271         const Handler* m_artifactResolutionDefault;
272
273         pair<bool,int> getArtifactEndpointIndex() const {
274             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
275             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
276         }
277
278         enum {
279             REDIRECT_LIMIT_INHERIT,
280             REDIRECT_LIMIT_NONE,
281             REDIRECT_LIMIT_EXACT,
282             REDIRECT_LIMIT_HOST,
283             REDIRECT_LIMIT_WHITELIST,
284             REDIRECT_LIMIT_EXACT_WHITELIST,
285             REDIRECT_LIMIT_HOST_WHITELIST
286         } m_redirectLimit;
287         vector<string> m_redirectWhitelist;
288     };
289
290     // Top-level configuration implementation
291     class SHIBSP_DLLLOCAL XMLConfig;
292     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
293     {
294     public:
295         XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log);
296         ~XMLConfigImpl() {
297             if (m_document)
298                 m_document->release();
299         }
300
301 #ifndef SHIBSP_LITE
302         scoped_ptr<TransactionLog> m_tranLog;
303         scoped_ptr<SecurityPolicyProvider> m_policy;
304         vector< tuple<string,string,string> > m_transportOptions;
305 #endif
306         scoped_ptr<RequestMapper> m_requestMapper;
307         map< string,boost::shared_ptr<Application> > m_appmap;
308
309         // Provides filter to exclude special config elements.
310 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
311         short
312 #else
313         FilterAction
314 #endif
315         acceptNode(const DOMNode* node) const;
316
317         void setDocument(DOMDocument* doc) {
318             m_document = doc;
319         }
320
321     private:
322         void doExtensions(const DOMElement*, const char*, Category&);
323         void doListener(const DOMElement*, XMLConfig*, Category&);
324         void doCaching(const DOMElement*, XMLConfig*, Category&);
325
326         DOMDocument* m_document;
327     };
328
329     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
330 #ifndef SHIBSP_LITE
331         ,public Remoted
332 #endif
333     {
334     public:
335         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")) {}
336
337         void init() {
338             background_load();
339         }
340
341         ~XMLConfig() {
342             shutdown();
343 #ifndef SHIBSP_LITE
344             SAMLConfig::getConfig().setArtifactMap(nullptr);
345             XMLToolingConfig::getConfig().setReplayCache(nullptr);
346 #endif
347         }
348
349 #ifndef SHIBSP_LITE
350         // Lockable
351         Lockable* lock() {
352             ReloadableXMLFile::lock();
353             if (m_impl->m_policy)
354                 m_impl->m_policy->lock();
355             return this;
356         }
357         void unlock() {
358             if (m_impl->m_policy)
359                 m_impl->m_policy->unlock();
360             ReloadableXMLFile::unlock();
361         }
362 #endif
363
364         // PropertySet
365         const PropertySet* getParent() const { return m_impl->getParent(); }
366         void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
367         pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const {return m_impl->getBool(name,ns);}
368         pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const {return m_impl->getString(name,ns);}
369         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const {return m_impl->getXMLString(name,ns);}
370         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const {return m_impl->getUnsignedInt(name,ns);}
371         pair<bool,int> getInt(const char* name, const char* ns=nullptr) const {return m_impl->getInt(name,ns);}
372         void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
373         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
374         const DOMElement* getElement() const {return m_impl->getElement();}
375
376         // ServiceProvider
377 #ifndef SHIBSP_LITE
378         // Remoted
379         void receive(DDF& in, ostream& out);
380
381         TransactionLog* getTransactionLog() const {
382             if (m_impl->m_tranLog)
383                 return m_impl->m_tranLog.get();
384             throw ConfigurationException("No TransactionLog available.");
385         }
386
387         StorageService* getStorageService(const char* id) const {
388             if (id) {
389                 map< string,boost::shared_ptr<StorageService> >::const_iterator i = m_storage.find(id);
390                 if (i != m_storage.end())
391                     return i->second.get();
392             }
393             else if (!m_storage.empty())
394                 return m_storage.begin()->second.get();
395             return nullptr;
396         }
397 #endif
398
399         ListenerService* getListenerService(bool required=true) const {
400             if (required && !m_listener)
401                 throw ConfigurationException("No ListenerService available.");
402             return m_listener.get();
403         }
404
405         SessionCache* getSessionCache(bool required=true) const {
406             if (required && !m_sessionCache)
407                 throw ConfigurationException("No SessionCache available.");
408             return m_sessionCache.get();
409         }
410
411         RequestMapper* getRequestMapper(bool required=true) const {
412             if (required && !m_impl->m_requestMapper)
413                 throw ConfigurationException("No RequestMapper available.");
414             return m_impl->m_requestMapper.get();
415         }
416
417         const Application* getApplication(const char* applicationId) const {
418             map< string,boost::shared_ptr<Application> >::const_iterator i = m_impl->m_appmap.find(applicationId ? applicationId : "default");
419             return (i != m_impl->m_appmap.end()) ? i->second.get() : nullptr;
420         }
421
422 #ifndef SHIBSP_LITE
423         SecurityPolicyProvider* getSecurityPolicyProvider(bool required=true) const {
424             if (required && !m_impl->m_policy)
425                 throw ConfigurationException("No SecurityPolicyProvider available.");
426             return m_impl->m_policy.get();
427         }
428
429         const PropertySet* getPolicySettings(const char* id) const {
430             return getSecurityPolicyProvider()->getPolicySettings(id);
431         }
432
433         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
434             return getSecurityPolicyProvider()->getPolicyRules(id);
435         }
436
437         bool setTransportOptions(SOAPTransport& transport) const {
438             bool ret = true;
439             for (vector< tuple<string,string,string> >::const_iterator opt = m_impl->m_transportOptions.begin();
440                     opt != m_impl->m_transportOptions.end(); ++opt) {
441                 if (!transport.setProviderOption(opt->get<0>().c_str(), opt->get<1>().c_str(), opt->get<2>().c_str())) {
442                     m_log.error("failed to set SOAPTransport option (%s)", opt->get<1>().c_str());
443                     ret = false;
444                 }
445             }
446             return ret;
447         }
448 #endif
449
450     protected:
451         pair<bool,DOMElement*> background_load();
452
453     private:
454         friend class XMLConfigImpl;
455         // The order of these members actually matters. If we want to rely on auto-destruction, then
456         // anything dependent on anything else has to come later in the object so it will pop first.
457         // Storage is the lowest, then remoting, then the cache, and finally the rest.
458 #ifndef SHIBSP_LITE
459         map< string,boost::shared_ptr<StorageService> > m_storage;
460 #endif
461         scoped_ptr<ListenerService> m_listener;
462         scoped_ptr<SessionCache> m_sessionCache;
463         scoped_ptr<XMLConfigImpl> m_impl;
464     };
465
466 #if defined (_MSC_VER)
467     #pragma warning( pop )
468 #endif
469
470     static const XMLCh applicationId[] =        UNICODE_LITERAL_13(a,p,p,l,i,c,a,t,i,o,n,I,d);
471     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);
472     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);
473     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
474     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);
475     static const XMLCh _AttributeFilter[] =     UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
476     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
477     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);
478     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);
479     static const XMLCh _Audience[] =            UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
480     static const XMLCh Binding[] =              UNICODE_LITERAL_7(B,i,n,d,i,n,g);
481     static const XMLCh Channel[]=               UNICODE_LITERAL_7(C,h,a,n,n,e,l);
482     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);
483     static const XMLCh _default[] =             UNICODE_LITERAL_7(d,e,f,a,u,l,t);
484     static const XMLCh _Extensions[] =          UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
485     static const XMLCh _fatal[] =               UNICODE_LITERAL_5(f,a,t,a,l);
486     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);
487     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
488     static const XMLCh _index[] =               UNICODE_LITERAL_5(i,n,d,e,x);
489     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
490     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);
491     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
492     static const XMLCh Location[] =             UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
493     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);
494     static const XMLCh Logout[] =               UNICODE_LITERAL_6(L,o,g,o,u,t);
495     static const XMLCh _LogoutInitiator[] =     UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
496     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);
497     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
498     static const XMLCh NameIDMgmt[] =           UNICODE_LITERAL_10(N,a,m,e,I,D,M,g,m,t);
499     static const XMLCh Notify[] =               UNICODE_LITERAL_6(N,o,t,i,f,y);
500     static const XMLCh _option[] =              UNICODE_LITERAL_6(o,p,t,i,o,n);
501     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
502     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);
503     static const XMLCh _ProtocolProvider[] =    UNICODE_LITERAL_16(P,r,o,t,o,c,o,l,P,r,o,v,i,d,e,r);
504     static const XMLCh _provider[] =            UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
505     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
506     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
507     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
508     static const XMLCh RequestMap[] =           UNICODE_LITERAL_10(R,e,q,u,e,s,t,M,a,p);
509     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
510     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);
511     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
512     static const XMLCh _SessionInitiator[] =    UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
513     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);
514     static const XMLCh Site[] =                 UNICODE_LITERAL_4(S,i,t,e);
515     static const XMLCh SSO[] =                  UNICODE_LITERAL_3(S,S,O);
516     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
517     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
518     static const XMLCh tranLogFiller[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,i,l,l,e,r);
519     static const XMLCh tranLogFormat[] =        UNICODE_LITERAL_13(t,r,a,n,L,o,g,F,o,r,m,a,t);
520     static const XMLCh TransportOption[] =      UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
521     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
522     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
523     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
524 };
525
526 namespace shibsp {
527     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
528     {
529         return new XMLConfig(e);
530     }
531 };
532
533 XMLApplication::XMLApplication(
534     const ServiceProvider* sp,
535     const ProtocolProvider* pp,
536     DOMElement* e,
537     const XMLApplication* base
538     ) : Application(sp), m_base(base), m_acsDefault(nullptr), m_sessionInitDefault(nullptr), m_artifactResolutionDefault(nullptr)
539 {
540 #ifdef _DEBUG
541     xmltooling::NDC ndc("XMLApplication");
542 #endif
543     Category& log = Category::getInstance(SHIBSP_LOGCAT".Application");
544
545     // First load any property sets.
546     map<string,string> remapper;
547     remapper["relayStateLimit"] = "redirectLimit";
548     remapper["relayStateWhitelist"] = "redirectWhitelist";
549     load(e, nullptr, this, &remapper);
550
551     // Process redirect limit policy. Do this before assigning the parent pointer
552     // to ensure we get only our Sessions element.
553     const PropertySet* sessionProps = getPropertySet("Sessions");
554     if (sessionProps) {
555         pair<bool,const char*> redirectLimit = sessionProps->getString("redirectLimit");
556         if (redirectLimit.first) {
557             if (!strcmp(redirectLimit.second, "none"))
558                 m_redirectLimit = REDIRECT_LIMIT_NONE;
559             else if (!strcmp(redirectLimit.second, "exact"))
560                 m_redirectLimit = REDIRECT_LIMIT_EXACT;
561             else if (!strcmp(redirectLimit.second, "host"))
562                 m_redirectLimit = REDIRECT_LIMIT_HOST;
563             else {
564                 if (!strcmp(redirectLimit.second, "exact+whitelist"))
565                     m_redirectLimit = REDIRECT_LIMIT_EXACT_WHITELIST;
566                 else if (!strcmp(redirectLimit.second, "exact+host"))
567                     m_redirectLimit = REDIRECT_LIMIT_HOST_WHITELIST;
568                 else if (!strcmp(redirectLimit.second, "exact+host"))
569                     m_redirectLimit = REDIRECT_LIMIT_WHITELIST;
570                 else
571                     throw ConfigurationException("Unrecognized redirectLimit setting ($1)", params(1, redirectLimit.second));
572                 redirectLimit = sessionProps->getString("redirectWhitelist");
573                 if (redirectLimit.first) {
574                     string dup(redirectLimit.second);
575                     split(m_redirectWhitelist, dup, is_space(), algorithm::token_compress_on);
576                 }
577             }
578         }
579         else {
580             m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
581         }
582     }
583     else {
584         m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
585     }
586
587     // Assign parent.
588     if (base)
589         setParent(base);
590
591     SPConfig& conf=SPConfig::getConfig();
592 #ifndef SHIBSP_LITE
593     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
594 #endif
595
596     // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec dependency.
597     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
598     string tohash=getId();
599     tohash+=getString("entityID").second;
600     for (const char* ch = tohash.c_str(); *ch; ++ch) {
601         m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
602         m_hash += (DIGITS[0x0F & *ch]);
603     }
604
605     doAttributeInfo();
606
607     if (conf.isEnabled(SPConfig::Handlers))
608         doHandlers(pp, e, log);
609
610     // Notification.
611     DOMNodeList* nlist = e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS, Notify);
612     for (XMLSize_t i = 0; nlist && i < nlist->getLength(); ++i) {
613         if (nlist->item(i)->getParentNode()->isSameNode(e)) {
614             const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(nullptr, Channel);
615             string loc(XMLHelper::getAttrString(static_cast<DOMElement*>(nlist->item(i)), nullptr, Location));
616             if (!loc.empty()) {
617                 if (channel && *channel == chLatin_f)
618                     m_frontLogout.push_back(loc);
619                 else
620                     m_backLogout.push_back(loc);
621             }
622         }
623     }
624
625 #ifndef SHIBSP_LITE
626     nlist = e->getElementsByTagNameNS(samlconstants::SAML20_NS, Audience::LOCAL_NAME);
627     if (nlist && nlist->getLength()) {
628         log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
629         for (XMLSize_t i = 0; i < nlist->getLength(); ++i)
630             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
631                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
632     }
633
634     if (conf.isEnabled(SPConfig::Metadata)) {
635         m_metadata.reset(
636             doChainedPlugins(
637                 SAMLConfig::getConfig().MetadataProviderManager, "MetadataProvider", CHAINING_METADATA_PROVIDER, _MetadataProvider, e, log
638                 )
639             );
640         try {
641             if (m_metadata)
642                 m_metadata->init();
643             else if (!m_base)
644                 log.crit("no MetadataProvider available, configuration is probably unusable");
645         }
646         catch (std::exception& ex) {
647             log.crit("error initializing MetadataProvider: %s", ex.what());
648         }
649     }
650
651     if (conf.isEnabled(SPConfig::Trust)) {
652         m_trust.reset(doChainedPlugins(xmlConf.TrustEngineManager, "TrustEngine", CHAINING_TRUSTENGINE, _TrustEngine, e, log));
653         if (!m_trust && !m_base) {
654             log.info(
655                 "no TrustEngine specified or installed, using default chain {%s, %s}",
656                 EXPLICIT_KEY_TRUSTENGINE, SHIBBOLETH_PKIX_TRUSTENGINE
657                 );
658             m_trust.reset(xmlConf.TrustEngineManager.newPlugin(CHAINING_TRUSTENGINE, nullptr));
659             ChainingTrustEngine* trustchain = dynamic_cast<ChainingTrustEngine*>(m_trust.get());
660             if (trustchain) {
661                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(EXPLICIT_KEY_TRUSTENGINE, nullptr));
662                 trustchain->addTrustEngine(xmlConf.TrustEngineManager.newPlugin(SHIBBOLETH_PKIX_TRUSTENGINE, nullptr));
663             }
664         }
665     }
666
667     if (conf.isEnabled(SPConfig::AttributeResolution)) {
668         doAttributePlugins(e, log);
669     }
670
671     if (conf.isEnabled(SPConfig::Credentials)) {
672         m_credResolver.reset(
673             doChainedPlugins(xmlConf.CredentialResolverManager, "CredentialResolver", CHAINING_CREDENTIAL_RESOLVER, _CredentialResolver, e, log)
674             );
675     }
676
677     // Finally, load relying parties.
678     const DOMElement* child = XMLHelper::getFirstChildElement(e, RelyingParty);
679     while (child) {
680         if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
681             boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
682             rp->load(child, nullptr, this);
683             rp->setParent(this);
684             m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
685         }
686         child = XMLHelper::getNextSiblingElement(child, RelyingParty);
687     }
688     if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
689         // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
690         child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
691         while (child) {
692             if (child->hasAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)) {
693                 DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
694                 boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
695                 rp->load(rpclone, nullptr, this);
696                 rp->setParent(this);
697                 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
698             }
699             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
700         }
701     }
702 #endif
703
704     // Out of process only, we register a listener endpoint.
705     if (!conf.isEnabled(SPConfig::InProcess)) {
706         ListenerService* listener = sp->getListenerService(false);
707         if (listener) {
708             string addr=string(getId()) + "::getHeaders::Application";
709             listener->regListener(addr.c_str(), this);
710         }
711         else {
712             log.info("no ListenerService available, Application remoting disabled");
713         }
714     }
715 }
716
717 XMLApplication::~XMLApplication()
718 {
719     ListenerService* listener=getServiceProvider().getListenerService(false);
720     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
721         string addr=string(getId()) + "::getHeaders::Application";
722         listener->unregListener(addr.c_str(), this);
723     }
724 }
725
726 template <class T> T* XMLApplication::doChainedPlugins(
727     PluginManager<T,string,const DOMElement*>& pluginMgr,
728     const char* pluginType,
729     const char* chainingType,
730     const XMLCh* localName,
731     DOMElement* e,
732     Category& log,
733     const char* dummyType
734     )
735 {
736     string t;
737     DOMElement* child = XMLHelper::getFirstChildElement(e, localName);
738     if (child) {
739         // Check for multiple.
740         if (XMLHelper::getNextSiblingElement(child, localName)) {
741             log.info("multiple %s plugins, wrapping in a chain", pluginType);
742             DOMElement* chain = child->getOwnerDocument()->createElementNS(nullptr, localName);
743             while (child) {
744                 chain->appendChild(child);
745                 child = XMLHelper::getFirstChildElement(e, localName);
746             }
747             t = chainingType;
748             child = chain;
749             e->appendChild(chain);
750         }
751         else {
752             // Only a single one.
753             t = XMLHelper::getAttrString(child, nullptr, _type);
754         }
755
756         try {
757             if (!t.empty()) {
758                 log.info("building %s of type %s...", pluginType, t.c_str());
759                 return pluginMgr.newPlugin(t.c_str(), child);
760             }
761             else {
762                 throw ConfigurationException("$1 element had no type attribute.", params(1, pluginType));
763             }
764         }
765         catch (std::exception& ex) {
766             log.crit("error building %s: %s", pluginType, ex.what());
767             if (dummyType) {
768                 // Install a dummy version as a safety valve.
769                 log.crit("installing safe %s in place of failed version", pluginType);
770                 return pluginMgr.newPlugin(dummyType, nullptr);
771             }
772         }
773     }
774
775     return nullptr;
776 }
777
778 void XMLApplication::doAttributeInfo()
779 {
780     // Populate prefix pair.
781     m_attributePrefix.second = "HTTP_";
782     pair<bool,const char*> prefix = getString("attributePrefix");
783     if (prefix.first) {
784         m_attributePrefix.first = prefix.second;
785         const char* pch = prefix.second;
786         while (*pch) {
787             m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
788             pch++;
789         }
790     }
791
792     pair<bool,const char*> attributes = getString("REMOTE_USER");
793     if (attributes.first) {
794         string dup(attributes.second);
795         split(m_remoteUsers, dup, is_space(), algorithm::token_compress_on);
796     }
797
798     // Load attribute ID lists for REMOTE_USER and header clearing.
799     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
800         attributes = getString("unsetHeaders");
801         if (attributes.first) {
802             string transformedprefix(m_attributePrefix.second);
803             const char* pch;
804             prefix = getString("metadataAttributePrefix");
805             if (prefix.first) {
806                 pch = prefix.second;
807                 while (*pch) {
808                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
809                     pch++;
810                 }
811             }
812
813             string dup(attributes.second);
814             vector<string> headerNames;
815             split(headerNames, dup, is_space(), algorithm::token_compress_on);
816             for (vector<string>::const_iterator h = headerNames.begin(); h != headerNames.end(); ++h) {
817                 string transformed;
818                 const char* pch = h->c_str();
819                 while (*pch) {
820                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
821                     pch++;
822                 }
823                 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *h, m_attributePrefix.second + transformed));
824                 if (prefix.first)
825                     m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *h, transformedprefix + transformed));
826             }
827             m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
828         }
829     }
830 }
831
832 void XMLApplication::doHandlers(const ProtocolProvider* pp, const DOMElement* e, Category& log)
833 {
834     SPConfig& conf = SPConfig::getConfig();
835
836     const PropertySet* sessions = getPropertySet("Sessions");
837
838     // Process assertion export handler.
839     pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
840     if (location.first) {
841         try {
842             DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _Handler);
843             exportElement->setAttributeNS(nullptr,Location,sessions->getXMLString("exportLocation").second);
844             pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
845             if (exportACL.first) {
846                 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
847                 exportElement->setAttributeNS(nullptr,_acl,exportACL.second);
848             }
849             boost::shared_ptr<Handler> exportHandler(
850                 conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId()))
851                 );
852             m_handlers.push_back(exportHandler);
853
854             // Insert into location map. If it contains the handlerURL, we skip past that part.
855             const char* hurl = sessions->getString("handlerURL").second;
856             if (!hurl)
857                 hurl = "/Shibboleth.sso";
858             const char* pch = strstr(location.second, hurl);
859             if (pch)
860                 location.second = pch + strlen(hurl);
861             if (*location.second == '/')
862                 m_handlerMap[location.second] = exportHandler.get();
863             else
864                 m_handlerMap[string("/") + location.second] = exportHandler.get();
865         }
866         catch (std::exception& ex) {
867             log.error("caught exception installing assertion lookup handler: %s", ex.what());
868         }
869     }
870
871     // Look for "shorthand" elements first.
872     set<string> protocols;
873     DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : nullptr;
874     while (child) {
875         if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, SSO)) {
876             if (pp)
877                 doSSO(*pp, protocols, child, log);
878             else
879                 log.error("no ProtocolProvider, SSO auto-configure unsupported");
880         }
881         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, Logout)) {
882             if (pp)
883                 doLogout(*pp, protocols, child, log);
884             else
885                 log.error("no ProtocolProvider, Logout auto-configure unsupported");
886         }
887         else if (XMLHelper::isNodeNamed(child, shibspconstants::SHIB2SPCONFIG_NS, NameIDMgmt)) {
888             if (pp)
889                 doNameIDMgmt(*pp, protocols, child, log);
890             else
891                 log.error("no ProtocolProvider, NameIDMgmt auto-configure unsupported");
892         }
893         else {
894             break;  // drop into next while loop
895         }
896         child = XMLHelper::getNextSiblingElement(child);
897     }
898
899     // Process other handlers.
900     bool hardACS=false, hardSessionInit=false, hardArt=false;
901     while (child) {
902         if (!child->hasAttributeNS(nullptr, Location)) {
903             auto_ptr_char hclass(child->getLocalName());
904             log.error("%s handler with no Location property cannot be processed", hclass.get());
905             child = XMLHelper::getNextSiblingElement(child);
906             continue;
907         }
908         try {
909             boost::shared_ptr<Handler> handler;
910             if (XMLString::equals(child->getLocalName(), _AssertionConsumerService)) {
911                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
912                 if (bindprop.empty()) {
913                     log.error("AssertionConsumerService element has no Binding attribute, skipping it...");
914                     child = XMLHelper::getNextSiblingElement(child);
915                     continue;
916                 }
917                 handler.reset(conf.AssertionConsumerServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
918                 // Map by binding and protocol (may be > 1 per protocol and binding)
919                 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
920                 const XMLCh* protfamily = handler->getProtocolFamily();
921                 if (protfamily)
922                     m_acsProtocolMap[protfamily].push_back(handler.get());
923                 m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
924
925                 if (!hardACS) {
926                     pair<bool,bool> defprop = handler->getBool("isDefault");
927                     if (defprop.first) {
928                         if (defprop.second) {
929                             hardACS = true;
930                             m_acsDefault = handler.get();
931                         }
932                     }
933                     else if (!m_acsDefault)
934                         m_acsDefault = handler.get();
935                 }
936             }
937             else if (XMLString::equals(child->getLocalName(), _SessionInitiator)) {
938                 string t(XMLHelper::getAttrString(child, nullptr, _type));
939                 if (t.empty()) {
940                     log.error("SessionInitiator element has no type attribute, skipping it...");
941                     child = XMLHelper::getNextSiblingElement(child);
942                     continue;
943                 }
944                 boost::shared_ptr<SessionInitiator> sihandler(
945                     conf.SessionInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId()))
946                     );
947                 handler = sihandler;
948                 pair<bool,const char*> si_id = handler->getString("id");
949                 if (si_id.first && si_id.second)
950                     m_sessionInitMap[si_id.second] = sihandler.get();
951                 if (!hardSessionInit) {
952                     pair<bool,bool> defprop = handler->getBool("isDefault");
953                     if (defprop.first) {
954                         if (defprop.second) {
955                             hardSessionInit = true;
956                             m_sessionInitDefault = sihandler.get();
957                         }
958                     }
959                     else if (!m_sessionInitDefault) {
960                         m_sessionInitDefault = sihandler.get();
961                     }
962                 }
963             }
964             else if (XMLString::equals(child->getLocalName(), _LogoutInitiator)) {
965                 string t(XMLHelper::getAttrString(child, nullptr, _type));
966                 if (t.empty()) {
967                     log.error("LogoutInitiator element has no type attribute, skipping it...");
968                     child = XMLHelper::getNextSiblingElement(child);
969                     continue;
970                 }
971                 handler.reset(conf.LogoutInitiatorManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
972             }
973             else if (XMLString::equals(child->getLocalName(), _ArtifactResolutionService)) {
974                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
975                 if (bindprop.empty()) {
976                     log.error("ArtifactResolutionService element has no Binding attribute, skipping it...");
977                     child = XMLHelper::getNextSiblingElement(child);
978                     continue;
979                 }
980                 handler.reset(conf.ArtifactResolutionServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
981
982                 if (!hardArt) {
983                     pair<bool,bool> defprop = handler->getBool("isDefault");
984                     if (defprop.first) {
985                         if (defprop.second) {
986                             hardArt = true;
987                             m_artifactResolutionDefault = handler.get();
988                         }
989                     }
990                     else if (!m_artifactResolutionDefault)
991                         m_artifactResolutionDefault = handler.get();
992                 }
993             }
994             else if (XMLString::equals(child->getLocalName(), _SingleLogoutService)) {
995                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
996                 if (bindprop.empty()) {
997                     log.error("SingleLogoutService element has no Binding attribute, skipping it...");
998                     child = XMLHelper::getNextSiblingElement(child);
999                     continue;
1000                 }
1001                 handler.reset(conf.SingleLogoutServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1002             }
1003             else if (XMLString::equals(child->getLocalName(), _ManageNameIDService)) {
1004                 string bindprop(XMLHelper::getAttrString(child, nullptr, Binding));
1005                 if (bindprop.empty()) {
1006                     log.error("ManageNameIDService element has no Binding attribute, skipping it...");
1007                     child = XMLHelper::getNextSiblingElement(child);
1008                     continue;
1009                 }
1010                 handler.reset(conf.ManageNameIDServiceManager.newPlugin(bindprop.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1011             }
1012             else {
1013                 string t(XMLHelper::getAttrString(child, nullptr, _type));
1014                 if (t.empty()) {
1015                     log.error("Handler element has no type attribute, skipping it...");
1016                     child = XMLHelper::getNextSiblingElement(child);
1017                     continue;
1018                 }
1019                 handler.reset(conf.HandlerManager.newPlugin(t.c_str(), pair<const DOMElement*,const char*>(child, getId())));
1020             }
1021
1022             m_handlers.push_back(handler);
1023
1024             // Insert into location map.
1025             location = handler->getString("Location");
1026             if (location.first && *location.second == '/')
1027                 m_handlerMap[location.second] = handler.get();
1028             else if (location.first)
1029                 m_handlerMap[string("/") + location.second] = handler.get();
1030         }
1031         catch (std::exception& ex) {
1032             log.error("caught exception processing handler element: %s", ex.what());
1033         }
1034
1035         child = XMLHelper::getNextSiblingElement(child);
1036     }
1037 }
1038
1039 void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1040 {
1041     if (!e->hasChildNodes())
1042         return;
1043
1044     SPConfig& conf = SPConfig::getConfig();
1045
1046     // Tokenize the protocol list inside the element.
1047     XMLStringTokenizer prottokens(e->getTextContent());
1048     while (prottokens.hasMoreTokens()) {
1049         auto_ptr_char prot(prottokens.nextToken());
1050
1051         // Look for initiator.
1052         const PropertySet* initiator = pp.getInitiator(prot.get(), "SSO");
1053         if (initiator) {
1054             log.info("auto-configuring SSO initiation for protocol (%s)", prot.get());
1055             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1056             if (inittype.first) {
1057                 // Append a session initiator element of the designated type to the root element.
1058                 DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1059                 sidom->setAttributeNS(nullptr, _type, inittype.second);
1060                 e->appendChild(sidom);
1061                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", initiator->getString("id").second);
1062
1063                 doArtifactResolution(pp, prot.get(), e, log);
1064                 protocols.insert(prot.get());
1065             }
1066             else {
1067                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1068             }
1069         }
1070
1071         // Look for incoming bindings.
1072         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
1073         if (!bindings.empty()) {
1074             log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
1075             int index = 0;
1076             pair<bool,const XMLCh*> idprop,pathprop;
1077             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
1078                 idprop = (*b)->getXMLString("id");
1079                 pathprop = (*b)->getXMLString("path");
1080                 if (idprop.first && pathprop.first) {
1081                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
1082                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
1083                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
1084                     xstring indexbuf(chDigit_1 + (index % 10), 1);
1085                     if (index / 10)
1086                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1087                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1088
1089                     log.info("adding AssertionConsumerService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1090                     boost::shared_ptr<Handler> handler(
1091                         conf.AssertionConsumerServiceManager.newPlugin(
1092                             (*b)->getString("id").second, pair<const DOMElement*,const char*>(acsdom, getId())
1093                             )
1094                         );
1095                     m_handlers.push_back(handler);
1096
1097                     // Setup maps and defaults.
1098                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler.get());
1099                     const XMLCh* protfamily = handler->getProtocolFamily();
1100                     if (protfamily)
1101                         m_acsProtocolMap[protfamily].push_back(handler.get());
1102                     m_acsIndexMap[handler->getUnsignedInt("index").second] = handler.get();
1103                     if (!m_acsDefault)
1104                         m_acsDefault = handler.get();
1105
1106                     // Insert into location map.
1107                     pair<bool,const char*> location = handler->getString("Location");
1108                     if (location.first && *location.second == '/')
1109                         m_handlerMap[location.second] = handler.get();
1110                     else if (location.first)
1111                         m_handlerMap[string("/") + location.second] = handler.get();
1112                 }
1113                 else {
1114                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1115                 }
1116             }
1117         }
1118
1119         if (!initiator && bindings.empty()) {
1120             log.error("no SSO Initiator or Binding config for protocol (%s)", prot.get());
1121         }
1122     }
1123
1124     // Handle discovery.
1125     static const XMLCh discoveryProtocol[] = UNICODE_LITERAL_17(d,i,s,c,o,v,e,r,y,P,r,o,t,o,c,o,l);
1126     static const XMLCh discoveryURL[] = UNICODE_LITERAL_12(d,i,s,c,o,v,e,r,y,U,R,L);
1127     static const XMLCh _URL[] = UNICODE_LITERAL_3(U,R,L);
1128     const XMLCh* discop = e->getAttributeNS(nullptr, discoveryProtocol);
1129     if (discop && *discop) {
1130         const XMLCh* discou = e->getAttributeNS(nullptr, discoveryURL);
1131         if (discou && *discou) {
1132             // Append a session initiator element of the designated type to the root element.
1133             DOMElement* sidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _SessionInitiator);
1134             sidom->setAttributeNS(nullptr, _type, discop);
1135             sidom->setAttributeNS(nullptr, _URL, discou);
1136             e->appendChild(sidom);
1137             if (log.isInfoEnabled()) {
1138                 auto_ptr_char dp(discop);
1139                 log.info("adding SessionInitiator of type (%s) to chain (/Login)", dp.get());
1140             }
1141         }
1142         else {
1143             log.error("SSO discoveryProtocol specified without discoveryURL");
1144         }
1145     }
1146
1147     // Attach default Location to SSO element.
1148     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_i, chLatin_n, chNull };
1149     e->setAttributeNS(nullptr, Location, _loc);
1150
1151     // Instantiate Chaining initiator around the SSO element.
1152     boost::shared_ptr<SessionInitiator> chain(
1153         conf.SessionInitiatorManager.newPlugin(CHAINING_SESSION_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1154         );
1155     m_handlers.push_back(chain);
1156     m_sessionInitDefault = chain.get();
1157     m_handlerMap["/Login"] = chain.get();
1158 }
1159
1160 void XMLApplication::doLogout(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1161 {
1162     if (!e->hasChildNodes())
1163         return;
1164
1165     SPConfig& conf = SPConfig::getConfig();
1166
1167     // Tokenize the protocol list inside the element.
1168     XMLStringTokenizer prottokens(e->getTextContent());
1169     while (prottokens.hasMoreTokens()) {
1170         auto_ptr_char prot(prottokens.nextToken());
1171
1172         // Look for initiator.
1173         const PropertySet* initiator = pp.getInitiator(prot.get(), "Logout");
1174         if (initiator) {
1175             log.info("auto-configuring Logout initiation for protocol (%s)", prot.get());
1176             pair<bool,const XMLCh*> inittype = initiator->getXMLString("id");
1177             if (inittype.first) {
1178                 // Append a logout initiator element of the designated type to the root element.
1179                 DOMElement* lidom = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, _LogoutInitiator);
1180                 lidom->setAttributeNS(nullptr, _type, inittype.second);
1181                 e->appendChild(lidom);
1182                 log.info("adding LogoutInitiator of type (%s) to chain (/Logout)", initiator->getString("id").second);
1183
1184                 if (protocols.count(prot.get()) == 0) {
1185                     doArtifactResolution(pp, prot.get(), e, log);
1186                     protocols.insert(prot.get());
1187                 }
1188             }
1189             else {
1190                 log.error("missing id property on Initiator element, check config for protocol (%s)", prot.get());
1191             }
1192         }
1193
1194         // Look for incoming bindings.
1195         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "Logout");
1196         if (!bindings.empty()) {
1197             log.info("auto-configuring Logout endpoints for protocol (%s)", prot.get());
1198             pair<bool,const XMLCh*> idprop,pathprop;
1199             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1200                 idprop = (*b)->getXMLString("id");
1201                 pathprop = (*b)->getXMLString("path");
1202                 if (idprop.first && pathprop.first) {
1203                     DOMElement* slodom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _SingleLogoutService);
1204                     slodom->setAttributeNS(nullptr, Binding, idprop.second);
1205                     slodom->setAttributeNS(nullptr, Location, pathprop.second);
1206
1207                     log.info("adding SingleLogoutService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1208                     boost::shared_ptr<Handler> handler(
1209                         conf.SingleLogoutServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(slodom, getId()))
1210                         );
1211                     m_handlers.push_back(handler);
1212
1213                     // Insert into location map.
1214                     pair<bool,const char*> location = handler->getString("Location");
1215                     if (location.first && *location.second == '/')
1216                         m_handlerMap[location.second] = handler.get();
1217                     else if (location.first)
1218                         m_handlerMap[string("/") + location.second] = handler.get();
1219                 }
1220                 else {
1221                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1222                 }
1223             }
1224
1225             if (protocols.count(prot.get()) == 0) {
1226                 doArtifactResolution(pp, prot.get(), e, log);
1227                 protocols.insert(prot.get());
1228             }
1229         }
1230
1231         if (!initiator && bindings.empty()) {
1232             log.error("no Logout Initiator or Binding config for protocol (%s)", prot.get());
1233         }
1234     }
1235
1236     // Attach default Location to Logout element.
1237     static const XMLCh _loc[] = { chForwardSlash, chLatin_L, chLatin_o, chLatin_g, chLatin_o, chLatin_u, chLatin_t, chNull };
1238     e->setAttributeNS(nullptr, Location, _loc);
1239
1240     // Instantiate Chaining initiator around the SSO element.
1241     boost::shared_ptr<Handler> chain(
1242         conf.LogoutInitiatorManager.newPlugin(CHAINING_LOGOUT_INITIATOR, pair<const DOMElement*,const char*>(e, getId()))
1243         );
1244     m_handlers.push_back(chain);
1245     m_handlerMap["/Logout"] = chain.get();
1246 }
1247
1248 void XMLApplication::doNameIDMgmt(const ProtocolProvider& pp, set<string>& protocols, DOMElement* e, Category& log)
1249 {
1250     if (!e->hasChildNodes())
1251         return;
1252
1253     SPConfig& conf = SPConfig::getConfig();
1254
1255     // Tokenize the protocol list inside the element.
1256     XMLStringTokenizer prottokens(e->getTextContent());
1257     while (prottokens.hasMoreTokens()) {
1258         auto_ptr_char prot(prottokens.nextToken());
1259
1260         // Look for incoming bindings.
1261         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "NameIDMgmt");
1262         if (!bindings.empty()) {
1263             log.info("auto-configuring NameIDMgmt endpoints for protocol (%s)", prot.get());
1264             pair<bool,const XMLCh*> idprop,pathprop;
1265             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1266                 idprop = (*b)->getXMLString("id");
1267                 pathprop = (*b)->getXMLString("path");
1268                 if (idprop.first && pathprop.first) {
1269                     DOMElement* nimdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ManageNameIDService);
1270                     nimdom->setAttributeNS(nullptr, Binding, idprop.second);
1271                     nimdom->setAttributeNS(nullptr, Location, pathprop.second);
1272
1273                     log.info("adding ManageNameIDService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1274                     boost::shared_ptr<Handler> handler(
1275                         conf.ManageNameIDServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(nimdom, getId()))
1276                         );
1277                     m_handlers.push_back(handler);
1278
1279                     // Insert into location map.
1280                     pair<bool,const char*> location = handler->getString("Location");
1281                     if (location.first && *location.second == '/')
1282                         m_handlerMap[location.second] = handler.get();
1283                     else if (location.first)
1284                         m_handlerMap[string("/") + location.second] = handler.get();
1285                 }
1286                 else {
1287                     log.error("missing id or path property on Binding element, check config for protocol (%s)", prot.get());
1288                 }
1289             }
1290
1291             if (protocols.count(prot.get()) == 0) {
1292                 doArtifactResolution(pp, prot.get(), e, log);
1293                 protocols.insert(prot.get());
1294             }
1295         }
1296         else {
1297             log.error("no NameIDMgmt Binding config for protocol (%s)", prot.get());
1298         }
1299     }
1300 }
1301
1302 void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char* protocol, DOMElement* e, Category& log)
1303 {
1304     SPConfig& conf = SPConfig::getConfig();
1305
1306     // Look for incoming bindings.
1307     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
1308     if (!bindings.empty()) {
1309         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
1310         int index = 0;
1311         pair<bool,const XMLCh*> idprop,pathprop;
1312         for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
1313             idprop = (*b)->getXMLString("id");
1314             pathprop = (*b)->getXMLString("path");
1315             if (idprop.first && pathprop.first) {
1316                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
1317                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
1318                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
1319                 xstring indexbuf(chDigit_1 + (index % 10), 1);
1320                 if (index / 10)
1321                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
1322                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
1323
1324                 log.info("adding ArtifactResolutionService for Binding (%s) at (%s)", (*b)->getString("id").second, (*b)->getString("path").second);
1325                 boost::shared_ptr<Handler> handler(
1326                     conf.ArtifactResolutionServiceManager.newPlugin((*b)->getString("id").second, pair<const DOMElement*,const char*>(artdom, getId()))
1327                     );
1328                 m_handlers.push_back(handler);
1329
1330                 if (!m_artifactResolutionDefault)
1331                     m_artifactResolutionDefault = handler.get();
1332
1333                 // Insert into location map.
1334                 pair<bool,const char*> location = handler->getString("Location");
1335                 if (location.first && *location.second == '/')
1336                     m_handlerMap[location.second] = handler.get();
1337                 else if (location.first)
1338                     m_handlerMap[string("/") + location.second] = handler.get();
1339             }
1340             else {
1341                 log.error("missing id or path property on Binding element, check config for protocol (%s)", protocol);
1342             }
1343         }
1344     }
1345 }
1346
1347 #ifndef SHIBSP_LITE
1348 void XMLApplication::doAttributePlugins(DOMElement* e, Category& log)
1349 {
1350     SPConfig& conf = SPConfig::getConfig();
1351
1352     m_attrExtractor.reset(
1353         doChainedPlugins(conf.AttributeExtractorManager, "AttributeExtractor", CHAINING_ATTRIBUTE_EXTRACTOR, _AttributeExtractor, e, log)
1354         );
1355
1356     m_attrFilter.reset(
1357         doChainedPlugins(conf.AttributeFilterManager, "AttributeFilter", CHAINING_ATTRIBUTE_FILTER, _AttributeFilter, e, log, DUMMY_ATTRIBUTE_FILTER)
1358         );
1359
1360     m_attrResolver.reset(
1361         doChainedPlugins(conf.AttributeResolverManager, "AttributeResolver", CHAINING_ATTRIBUTE_RESOLVER, _AttributeResolver, e, log)
1362         );
1363
1364     if (m_unsetHeaders.empty()) {
1365         vector<string> unsetHeaders;
1366         if (m_attrExtractor) {
1367             Locker extlock(m_attrExtractor.get());
1368             m_attrExtractor->getAttributeIds(unsetHeaders);
1369         }
1370         else if (m_base && m_base->m_attrExtractor) {
1371             Locker extlock(m_base->m_attrExtractor.get());
1372             m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
1373         }
1374         if (m_attrResolver) {
1375             Locker reslock(m_attrResolver.get());
1376             m_attrResolver->getAttributeIds(unsetHeaders);
1377         }
1378         else if (m_base && m_base->m_attrResolver) {
1379             Locker extlock(m_base->m_attrResolver.get());
1380             m_base->m_attrResolver->getAttributeIds(unsetHeaders);
1381         }
1382         if (!unsetHeaders.empty()) {
1383             string transformedprefix(m_attributePrefix.second);
1384             const char* pch;
1385             pair<bool,const char*> prefix = getString("metadataAttributePrefix");
1386             if (prefix.first) {
1387                 pch = prefix.second;
1388                 while (*pch) {
1389                     transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
1390                     pch++;
1391                 }
1392             }
1393             for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
1394                 string transformed;
1395                 pch = hdr->c_str();
1396                 while (*pch) {
1397                     transformed += (isalnum(*pch) ? toupper(*pch) : '_');
1398                     pch++;
1399                 }
1400                 m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
1401                 if (prefix.first)
1402                     m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
1403             }
1404         }
1405         m_unsetHeaders.push_back(make_pair(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
1406     }
1407 }
1408 #endif
1409
1410 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1411 short
1412 #else
1413 DOMNodeFilter::FilterAction
1414 #endif
1415 XMLApplication::acceptNode(const DOMNode* node) const
1416 {
1417     const XMLCh* name=node->getLocalName();
1418     if (XMLString::equals(name,ApplicationOverride) ||
1419         XMLString::equals(name,_Audience) ||
1420         XMLString::equals(name,Notify) ||
1421         XMLString::equals(name,_Handler) ||
1422         XMLString::equals(name,_AssertionConsumerService) ||
1423         XMLString::equals(name,_ArtifactResolutionService) ||
1424         XMLString::equals(name,Logout) ||
1425         XMLString::equals(name,_LogoutInitiator) ||
1426         XMLString::equals(name,_ManageNameIDService) ||
1427         XMLString::equals(name,NameIDMgmt) ||
1428         XMLString::equals(name,_SessionInitiator) ||
1429         XMLString::equals(name,_SingleLogoutService) ||
1430         XMLString::equals(name,SSO) ||
1431         XMLString::equals(name,RelyingParty) ||
1432         XMLString::equals(name,_MetadataProvider) ||
1433         XMLString::equals(name,_TrustEngine) ||
1434         XMLString::equals(name,_CredentialResolver) ||
1435         XMLString::equals(name,_AttributeFilter) ||
1436         XMLString::equals(name,_AttributeExtractor) ||
1437         XMLString::equals(name,_AttributeResolver))
1438         return FILTER_REJECT;
1439
1440     return FILTER_ACCEPT;
1441 }
1442
1443 #ifndef SHIBSP_LITE
1444
1445 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1446 {
1447     if (!provider)
1448         return this;
1449
1450     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
1451     if (i != m_partyMap.end())
1452         return i->second.get();
1453     const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1454     while (group) {
1455         if (group->getName()) {
1456             i = m_partyMap.find(group->getName());
1457             if (i != m_partyMap.end())
1458                 return i->second.get();
1459         }
1460         group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1461     }
1462     return this;
1463 }
1464
1465 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1466 {
1467     if (!entityID)
1468         return this;
1469     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(entityID);
1470     return (i != m_partyMap.end()) ? i->second.get() : this;
1471 }
1472
1473 #endif
1474
1475 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1476 {
1477     const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1478     if (locs.empty())
1479         return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1480     else if (index >= locs.size())
1481         return string();
1482
1483 #ifdef HAVE_STRCASECMP
1484     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1485 #else
1486     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1487 #endif
1488         throw ConfigurationException("Request URL was not absolute.");
1489
1490     const char* handler = locs[index].c_str();
1491
1492     // Should never happen...
1493     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1494         throw ConfigurationException(
1495             "Invalid Location property ($1) in Notify element for Application ($2)",
1496             params(2, handler ? handler : "null", getId())
1497             );
1498
1499     // The "Location" property can be in one of three formats:
1500     //
1501     // 1) a full URI:       http://host/foo/bar
1502     // 2) a hostless URI:   http:///foo/bar
1503     // 3) a relative path:  /foo/bar
1504     //
1505     // #  Protocol  Host        Path
1506     // 1  handler   handler     handler
1507     // 2  handler   resource    handler
1508     // 3  resource  resource    handler
1509
1510     const char* path = nullptr;
1511
1512     // Decide whether to use the handler or the resource for the "protocol"
1513     const char* prot;
1514     if (*handler != '/') {
1515         prot = handler;
1516     }
1517     else {
1518         prot = resource;
1519         path = handler;
1520     }
1521
1522     // break apart the "protocol" string into protocol, host, and "the rest"
1523     const char* colon=strchr(prot,':');
1524     colon += 3;
1525     const char* slash=strchr(colon,'/');
1526     if (!path)
1527         path = slash;
1528
1529     // Compute the actual protocol and store.
1530     string notifyURL(prot, colon-prot);
1531
1532     // create the "host" from either the colon/slash or from the target string
1533     // If prot == handler then we're in either #1 or #2, else #3.
1534     // If slash == colon then we're in #2.
1535     if (prot != handler || slash == colon) {
1536         colon = strchr(resource, ':');
1537         colon += 3;      // Get past the ://
1538         slash = strchr(colon, '/');
1539     }
1540     string host(colon, (slash ? slash-colon : strlen(colon)));
1541
1542     // Build the URL
1543     notifyURL += host + path;
1544     return notifyURL;
1545 }
1546
1547 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1548 {
1549     if (!m_attributePrefix.first.empty()) {
1550         string temp = m_attributePrefix.first + rawname;
1551         string temp2 = m_attributePrefix.second + (cginame + 5);
1552         request.clearHeader(temp.c_str(), temp2.c_str());
1553     }
1554     else if (m_base) {
1555         m_base->clearHeader(request, rawname, cginame);
1556     }
1557     else {
1558         request.clearHeader(rawname, cginame);
1559     }
1560 }
1561
1562 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1563 {
1564     if (!m_attributePrefix.first.empty()) {
1565         string temp = m_attributePrefix.first + name;
1566         request.setHeader(temp.c_str(), value);
1567     }
1568     else if (m_base) {
1569         m_base->setHeader(request, name, value);
1570     }
1571     else {
1572         request.setHeader(name, value);
1573     }
1574 }
1575
1576 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1577 {
1578     if (!m_attributePrefix.first.empty()) {
1579         string temp = m_attributePrefix.first + name;
1580         return request.getSecureHeader(temp.c_str());
1581     }
1582     else if (m_base) {
1583         return m_base->getSecureHeader(request,name);
1584     }
1585     else {
1586         return request.getSecureHeader(name);
1587     }
1588 }
1589
1590 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1591 {
1592     if (m_sessionInitDefault) return m_sessionInitDefault;
1593     return m_base ? m_base->getDefaultSessionInitiator() : nullptr;
1594 }
1595
1596 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1597 {
1598     map<string,const SessionInitiator*>::const_iterator i = m_sessionInitMap.find(id);
1599     if (i != m_sessionInitMap.end()) return i->second;
1600     return m_base ? m_base->getSessionInitiatorById(id) : nullptr;
1601 }
1602
1603 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1604 {
1605     if (m_acsDefault) return m_acsDefault;
1606     return m_base ? m_base->getDefaultAssertionConsumerService() : nullptr;
1607 }
1608
1609 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1610 {
1611     map<unsigned int,const Handler*>::const_iterator i = m_acsIndexMap.find(index);
1612     if (i != m_acsIndexMap.end()) return i->second;
1613     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : nullptr;
1614 }
1615
1616 const Handler* XMLApplication::getAssertionConsumerServiceByProtocol(const XMLCh* protocol, const char* binding) const
1617 {
1618     ACSProtocolMap::const_iterator i = m_acsProtocolMap.find(protocol);
1619     if (i != m_acsProtocolMap.end() && !i->second.empty()) {
1620         if (!binding || !*binding)
1621             return i->second.front();
1622         for (ACSProtocolMap::value_type::second_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
1623             if (!strcmp(binding, (*j)->getString("Binding").second))
1624                 return *j;
1625         }
1626     }
1627     return m_base ? m_base->getAssertionConsumerServiceByProtocol(protocol, binding) : nullptr;
1628 }
1629
1630 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1631 {
1632     ACSBindingMap::const_iterator i = m_acsBindingMap.find(binding);
1633     if (i != m_acsBindingMap.end())
1634         return i->second;
1635     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1636 }
1637
1638 const Handler* XMLApplication::getHandler(const char* path) const
1639 {
1640     string wrap(path);
1641     wrap = wrap.substr(0, wrap.find(';'));
1642     map<string,const Handler*>::const_iterator i = m_handlerMap.find(wrap.substr(0, wrap.find('?')));
1643     if (i != m_handlerMap.end())
1644         return i->second;
1645     return m_base ? m_base->getHandler(path) : nullptr;
1646 }
1647
1648 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1649 {
1650     static void (vector<const Handler*>::* pb)(const Handler* const&) = &vector<const Handler*>::push_back;
1651     for_each(m_handlers.begin(), m_handlers.end(), boost::bind(pb, boost::ref(handlers), boost::bind(&boost::shared_ptr<Handler>::get, _1)));
1652     if (m_base) {
1653         for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1654             if (m_handlerMap.count(h->first) == 0)
1655                 handlers.push_back(h->second);
1656         }
1657     }
1658 }
1659
1660 void XMLApplication::limitRedirect(const GenericRequest& request, const char* url) const
1661 {
1662     if (!url || *url == '/')
1663         return;
1664     if (m_redirectLimit == REDIRECT_LIMIT_INHERIT)
1665         return m_base->limitRedirect(request, url);
1666     if (m_redirectLimit != REDIRECT_LIMIT_NONE) {
1667         vector<string> whitelist;
1668         if (m_redirectLimit == REDIRECT_LIMIT_EXACT || m_redirectLimit == REDIRECT_LIMIT_EXACT_WHITELIST) {
1669             // Scheme and hostname have to match.
1670             if (request.isDefaultPort()) {
1671                 whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + '/');
1672             }
1673             whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + ':' + lexical_cast<string>(request.getPort()) + '/');
1674         }
1675         else if (m_redirectLimit == REDIRECT_LIMIT_HOST || m_redirectLimit == REDIRECT_LIMIT_HOST_WHITELIST) {
1676             // Allow any scheme or port.
1677             whitelist.push_back(string("https://") + request.getHostname() + '/');
1678             whitelist.push_back(string("http://") + request.getHostname() + '/');
1679             whitelist.push_back(string("https://") + request.getHostname() + ':');
1680             whitelist.push_back(string("http://") + request.getHostname() + ':');
1681         }
1682
1683         static bool (*startsWithI)(const char*,const char*) = XMLString::startsWithI;
1684         if (!whitelist.empty() && find_if(whitelist.begin(), whitelist.end(),
1685                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != whitelist.end()) {
1686             return;
1687         }
1688         else if (!m_redirectWhitelist.empty() && find_if(m_redirectWhitelist.begin(), m_redirectWhitelist.end(),
1689                 boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != m_redirectWhitelist.end()) {
1690             return;
1691         }
1692         Category::getInstance(SHIBSP_LOGCAT".Application").warn("redirectLimit policy enforced, blocked redirect to (%s)", url);
1693         throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
1694     }
1695 }
1696
1697 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1698 short
1699 #else
1700 DOMNodeFilter::FilterAction
1701 #endif
1702 XMLConfigImpl::acceptNode(const DOMNode* node) const
1703 {
1704     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1705         return FILTER_ACCEPT;
1706     const XMLCh* name=node->getLocalName();
1707     if (XMLString::equals(name,ApplicationDefaults) ||
1708         XMLString::equals(name,_ArtifactMap) ||
1709         XMLString::equals(name,_Extensions) ||
1710         XMLString::equals(name,Listener) ||
1711         XMLString::equals(name,_ProtocolProvider) ||
1712         XMLString::equals(name,_RequestMapper) ||
1713         XMLString::equals(name,_ReplayCache) ||
1714         XMLString::equals(name,SecurityPolicies) ||
1715         XMLString::equals(name,_SecurityPolicyProvider) ||
1716         XMLString::equals(name,_SessionCache) ||
1717         XMLString::equals(name,Site) ||
1718         XMLString::equals(name,_StorageService) ||
1719         XMLString::equals(name,TCPListener) ||
1720         XMLString::equals(name,TransportOption) ||
1721         XMLString::equals(name,UnixListener))
1722         return FILTER_REJECT;
1723
1724     return FILTER_ACCEPT;
1725 }
1726
1727 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1728 {
1729     const DOMElement* exts = XMLHelper::getFirstChildElement(e, _Extensions);
1730     if (exts) {
1731         exts = XMLHelper::getFirstChildElement(exts, Library);
1732         while (exts) {
1733             string path(XMLHelper::getAttrString(exts, nullptr, _path));
1734             try {
1735                 if (!path.empty()) {
1736                     if (!XMLToolingConfig::getConfig().load_library(path.c_str(), (void*)exts))
1737                         throw ConfigurationException("XMLToolingConfig::load_library failed.");
1738                     log.debug("loaded %s extension library (%s)", label, path.c_str());
1739                 }
1740             }
1741             catch (std::exception& e) {
1742                 if (XMLHelper::getAttrBool(exts, false, _fatal)) {
1743                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.c_str(), e.what());
1744                     throw;
1745                 }
1746                 else {
1747                     log.crit("unable to load optional %s extension library %s: %s", label, path.c_str(), e.what());
1748                 }
1749             }
1750             exts = XMLHelper::getNextSiblingElement(exts, Library);
1751         }
1752     }
1753 }
1754
1755 void XMLConfigImpl::doListener(const DOMElement* e, XMLConfig* conf, Category& log)
1756 {
1757 #ifdef WIN32
1758     string plugtype(TCP_LISTENER_SERVICE);
1759 #else
1760     string plugtype(UNIX_LISTENER_SERVICE);
1761 #endif
1762     DOMElement* child = XMLHelper::getFirstChildElement(e, UnixListener);
1763     if (child)
1764         plugtype = UNIX_LISTENER_SERVICE;
1765     else {
1766         child = XMLHelper::getFirstChildElement(e, TCPListener);
1767         if (child)
1768             plugtype = TCP_LISTENER_SERVICE;
1769         else {
1770             child = XMLHelper::getFirstChildElement(e, Listener);
1771             if (child) {
1772                 auto_ptr_char type(child->getAttributeNS(nullptr, _type));
1773                 if (type.get() && *type.get())
1774                     plugtype = type.get();
1775             }
1776         }
1777     }
1778
1779     log.info("building ListenerService of type %s...", plugtype.c_str());
1780     conf->m_listener.reset(SPConfig::getConfig().ListenerServiceManager.newPlugin(plugtype.c_str(), child));
1781 }
1782
1783 void XMLConfigImpl::doCaching(const DOMElement* e, XMLConfig* conf, Category& log)
1784 {
1785     SPConfig& spConf = SPConfig::getConfig();
1786 #ifndef SHIBSP_LITE
1787     SAMLConfig& samlConf = SAMLConfig::getConfig();
1788 #endif
1789
1790     DOMElement* child;
1791 #ifndef SHIBSP_LITE
1792     if (spConf.isEnabled(SPConfig::OutOfProcess)) {
1793         XMLToolingConfig& xmlConf = XMLToolingConfig::getConfig();
1794         // First build any StorageServices.
1795         child = XMLHelper::getFirstChildElement(e, _StorageService);
1796         while (child) {
1797             string id(XMLHelper::getAttrString(child, nullptr, _id));
1798             string t(XMLHelper::getAttrString(child, nullptr, _type));
1799             if (!t.empty()) {
1800                 try {
1801                     log.info("building StorageService (%s) of type %s...", id.c_str(), t.c_str());
1802                     conf->m_storage[id] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(t.c_str(), child));
1803                 }
1804                 catch (std::exception& ex) {
1805                     log.crit("failed to instantiate StorageService (%s): %s", id.c_str(), ex.what());
1806                 }
1807             }
1808             child = XMLHelper::getNextSiblingElement(child, _StorageService);
1809         }
1810
1811         if (conf->m_storage.empty()) {
1812             log.info("no StorageService plugin(s) installed, using (mem) in-memory instance");
1813             conf->m_storage["mem"] = boost::shared_ptr<StorageService>(xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE, nullptr));
1814         }
1815
1816         // Replay cache.
1817         StorageService* replaySS = nullptr;
1818         child = XMLHelper::getFirstChildElement(e, _ReplayCache);
1819         if (child) {
1820             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1821             if (!ssid.empty()) {
1822                 if (conf->m_storage.count(ssid)) {
1823                     log.info("building ReplayCache on top of StorageService (%s)...", ssid.c_str());
1824                     replaySS = conf->m_storage[ssid].get();
1825                 }
1826                 else {
1827                     log.error("unable to locate StorageService (%s), using arbitrary instance for ReplayCache", ssid.c_str());
1828                     replaySS = conf->m_storage.begin()->second.get();
1829                 }
1830             }
1831             else {
1832                 log.info("no StorageService specified for ReplayCache, using arbitrary instance");
1833                 replaySS = conf->m_storage.begin()->second.get();
1834             }
1835         }
1836         else {
1837             log.info("no ReplayCache specified, using arbitrary StorageService instance");
1838             replaySS = conf->m_storage.begin()->second.get();
1839         }
1840         xmlConf.setReplayCache(new ReplayCache(replaySS));
1841
1842         // ArtifactMap
1843         child = XMLHelper::getFirstChildElement(e, _ArtifactMap);
1844         if (child) {
1845             string ssid(XMLHelper::getAttrString(child, nullptr, _StorageService));
1846             if (!ssid.empty()) {
1847                 if (conf->m_storage.count(ssid)) {
1848                     log.info("building ArtifactMap on top of StorageService (%s)...", ssid.c_str());
1849                     samlConf.setArtifactMap(new ArtifactMap(child, conf->m_storage[ssid].get()));
1850                 }
1851                 else {
1852                     log.error("unable to locate StorageService (%s), using in-memory ArtifactMap", ssid.c_str());
1853                     samlConf.setArtifactMap(new ArtifactMap(child));
1854                 }
1855             }
1856             else {
1857                 log.info("no StorageService specified, using in-memory ArtifactMap");
1858                 samlConf.setArtifactMap(new ArtifactMap(child));
1859             }
1860         }
1861         else {
1862             log.info("no ArtifactMap specified, building in-memory ArtifactMap...");
1863             samlConf.setArtifactMap(new ArtifactMap(child));
1864         }
1865     }   // end of out of process caching components
1866 #endif
1867
1868     child = XMLHelper::getFirstChildElement(e, _SessionCache);
1869     if (child) {
1870         string t(XMLHelper::getAttrString(child, nullptr, _type));
1871         if (!t.empty()) {
1872             log.info("building SessionCache of type %s...", t.c_str());
1873             conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(t.c_str(), child));
1874         }
1875     }
1876     if (!conf->m_sessionCache) {
1877         log.info("no SessionCache specified, using StorageService-backed instance");
1878         conf->m_sessionCache.reset(spConf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE, nullptr));
1879     }
1880 }
1881
1882 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer, Category& log) : m_document(nullptr)
1883 {
1884 #ifdef _DEBUG
1885     xmltooling::NDC ndc("XMLConfigImpl");
1886 #endif
1887     SPConfig& conf=SPConfig::getConfig();
1888     XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1889     const DOMElement* SHAR=XMLHelper::getFirstChildElement(e, OutOfProcess);
1890     const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
1891
1892     // Initialize logging manually in order to redirect log messages as soon as possible.
1893     if (conf.isEnabled(SPConfig::Logging)) {
1894         string logconf;
1895         if (conf.isEnabled(SPConfig::OutOfProcess))
1896             logconf = XMLHelper::getAttrString(SHAR, nullptr, logger);
1897         else if (conf.isEnabled(SPConfig::InProcess))
1898             logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
1899         if (logconf.empty())
1900             logconf = XMLHelper::getAttrString(e, nullptr, logger);
1901         if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
1902             // No properties found, so default them.
1903             if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
1904                 logconf = "shibd.logger";
1905             else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
1906                 logconf = "native.logger";
1907             else
1908                 logconf = "shibboleth.logger";
1909         }
1910         if (!logconf.empty()) {
1911             log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
1912             if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
1913                 log.crit("failed to load new logging configuration from (%s)", logconf.c_str());
1914         }
1915
1916 #ifndef SHIBSP_LITE
1917         m_tranLog.reset(
1918             new TransactionLog(
1919                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFormat).c_str(),
1920                 XMLHelper::getAttrString(SHAR, nullptr, tranLogFiller).c_str()
1921                 )
1922             );
1923 #endif
1924     }
1925
1926     // Re-log library versions now that logging is set up.
1927     log.info("Shibboleth SP Version %s", PACKAGE_VERSION);
1928 #ifndef SHIBSP_LITE
1929     log.info(
1930         "Library versions: %s %s, Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1931 # if defined(LOG4SHIB_VERSION)
1932     "log4shib", LOG4SHIB_VERSION,
1933 # elif defined(LOG4CPP_VERSION)
1934     "log4cpp", LOG4CPP_VERSION,
1935 # else
1936     "", "",
1937 # endif
1938         XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, gXMLToolingDotVersionStr, gOpenSAMLDotVersionStr, gShibSPDotVersionStr
1939         );
1940 #else
1941     log.info(
1942         "Library versions: %s %s, Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1943 # if defined(LOG4SHIB_VERSION)
1944     "log4shib", LOG4SHIB_VERSION,
1945 # elif defined(LOG4CPP_VERSION)
1946     "log4cpp", LOG4CPP_VERSION,
1947 # else
1948     "", "",
1949 # endif
1950         XERCES_FULLVERSIONDOT, gXMLToolingDotVersionStr, gShibSPDotVersionStr
1951         );
1952 #endif
1953
1954     // First load any property sets.
1955     load(e, nullptr, this);
1956
1957     DOMElement* child;
1958
1959     // Much of the processing can only occur on the first instantiation.
1960     if (first) {
1961         // Set clock skew.
1962         pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1963         if (skew.first)
1964             xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1965
1966         pair<bool,const char*> unsafe = getString("unsafeChars");
1967         if (unsafe.first)
1968             TemplateEngine::unsafe_chars = unsafe.second;
1969
1970         unsafe = getString("allowedSchemes");
1971         if (unsafe.first) {
1972             HTTPResponse::getAllowedSchemes().clear();
1973             string schemes(unsafe.second);
1974             split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
1975         }
1976
1977         // Default language handling.
1978         pair<bool,bool> langFromClient = getBool("langFromClient");
1979         pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
1980         GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
1981
1982 #ifndef SHIBSP_LITE
1983         langPriority = getXMLString("contactPriority");
1984         if (langPriority.first)
1985             SAMLConfig::getConfig().setContactPriority(langPriority.second);
1986 #endif
1987
1988         // Extensions
1989         doExtensions(e, "global", log);
1990         if (conf.isEnabled(SPConfig::OutOfProcess))
1991             doExtensions(SHAR, "out of process", log);
1992
1993         if (conf.isEnabled(SPConfig::InProcess))
1994             doExtensions(SHIRE, "in process", log);
1995
1996         // Instantiate the ListenerService and SessionCache objects.
1997         if (conf.isEnabled(SPConfig::Listener))
1998             doListener(e, outer, log);
1999
2000 #ifndef SHIBSP_LITE
2001         if (outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
2002             outer->m_listener->regListener("set::RelayState", outer);
2003             outer->m_listener->regListener("get::RelayState", outer);
2004             outer->m_listener->regListener("set::PostData", outer);
2005             outer->m_listener->regListener("get::PostData", outer);
2006         }
2007 #endif
2008         if (conf.isEnabled(SPConfig::Caching))
2009             doCaching(e, outer, log);
2010     } // end of first-time-only stuff
2011
2012     // Back to the fully dynamic stuff...next up is the RequestMapper.
2013     if (conf.isEnabled(SPConfig::RequestMapping)) {
2014         if (child = XMLHelper::getFirstChildElement(e, _RequestMapper)) {
2015             string t(XMLHelper::getAttrString(child, nullptr, _type));
2016             if (!t.empty()) {
2017                 log.info("building RequestMapper of type %s...", t.c_str());
2018                 m_requestMapper.reset(conf.RequestMapperManager.newPlugin(t.c_str(), child));
2019             }
2020         }
2021         if (!m_requestMapper) {
2022             log.info("no RequestMapper specified, using 'Native' plugin with empty/default map");
2023             child = e->getOwnerDocument()->createElementNS(nullptr, _RequestMapper);
2024             DOMElement* mapperDummy = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS, RequestMap);
2025             mapperDummy->setAttributeNS(nullptr, applicationId, _default);
2026             child->appendChild(mapperDummy);
2027             m_requestMapper.reset(conf.RequestMapperManager.newPlugin(NATIVE_REQUEST_MAPPER, child));
2028         }
2029     }
2030
2031 #ifndef SHIBSP_LITE
2032     // Load security policies.
2033     if (child = XMLHelper::getLastChildElement(e, _SecurityPolicyProvider)) {
2034         string t(XMLHelper::getAttrString(child, nullptr, _type));
2035         if (!t.empty()) {
2036             log.info("building SecurityPolicyProvider of type %s...", t.c_str());
2037             m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(t.c_str(), child));
2038         }
2039         else {
2040             throw ConfigurationException("can't build SecurityPolicyProvider, no type specified");
2041         }
2042     }
2043     else if (child = XMLHelper::getLastChildElement(e, SecurityPolicies)) {
2044         // For backward compatibility, wrap in a plugin element.
2045         DOMElement* polwrapper = e->getOwnerDocument()->createElementNS(nullptr, _SecurityPolicyProvider);
2046         polwrapper->appendChild(child);
2047         log.info("building SecurityPolicyProvider of type %s...", XML_SECURITYPOLICY_PROVIDER);
2048         m_policy.reset(conf.SecurityPolicyProviderManager.newPlugin(XML_SECURITYPOLICY_PROVIDER, polwrapper));
2049     }
2050     else {
2051         log.fatal("can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2052         throw ConfigurationException("Can't build SecurityPolicyProvider, missing conf:SecurityPolicyProvider element?");
2053     }
2054
2055     if (first) {
2056         if (!m_policy->getAlgorithmBlacklist().empty()) {
2057 #ifdef SHIBSP_XMLSEC_WHITELISTING
2058             for_each(
2059                 m_policy->getAlgorithmBlacklist().begin(), m_policy->getAlgorithmBlacklist().end(),
2060                 boost::bind(&XSECPlatformUtils::blacklistAlgorithm, boost::bind(&xstring::c_str, _1))
2061                 );
2062 #else
2063             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2064 #endif
2065         }
2066         else if (!m_policy->getAlgorithmWhitelist().empty()) {
2067 #ifdef SHIBSP_XMLSEC_WHITELISTING
2068             for_each(
2069                 m_policy->getAlgorithmWhitelist().begin(), m_policy->getAlgorithmWhitelist().end(),
2070                 boost::bind(&XSECPlatformUtils::whitelistAlgorithm, boost::bind(&xstring::c_str, _1))
2071                 );
2072 #else
2073             log.crit("XML-Security-C library prior to 1.6.0 does not support algorithm white/blacklists");
2074 #endif
2075         }
2076     }
2077
2078     // Process TransportOption elements.
2079     child = XMLHelper::getLastChildElement(e, TransportOption);
2080     while (child) {
2081         if (child->hasChildNodes()) {
2082             string provider(XMLHelper::getAttrString(child, nullptr, _provider));
2083             string option(XMLHelper::getAttrString(child, nullptr, _option));
2084             auto_ptr_char value(child->getFirstChild()->getNodeValue());
2085             if (!provider.empty() && !option.empty() && value.get() && *value.get()) {
2086                 m_transportOptions.push_back(make_tuple(provider, option, string(value.get())));
2087             }
2088         }
2089         child = XMLHelper::getPreviousSiblingElement(child, TransportOption);
2090     }
2091 #endif
2092
2093     scoped_ptr<ProtocolProvider> pp;
2094     if (conf.isEnabled(SPConfig::Handlers)) {
2095         if (child = XMLHelper::getLastChildElement(e, _ProtocolProvider)) {
2096             string t(XMLHelper::getAttrString(child, nullptr, _type));
2097             if (!t.empty()) {
2098                 log.info("building ProtocolProvider of type %s...", t.c_str());
2099                 pp.reset(conf.ProtocolProviderManager.newPlugin(t.c_str(), child));
2100             }
2101         }
2102     }
2103     Locker pplocker(pp.get());
2104
2105     // Load the default application.
2106     child = XMLHelper::getLastChildElement(e, ApplicationDefaults);
2107     if (!child) {
2108         log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
2109         throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
2110     }
2111     boost::shared_ptr<XMLApplication> defapp(new XMLApplication(outer, pp.get(), child));
2112     m_appmap[defapp->getId()] = defapp;
2113
2114     // Load any overrides.
2115     child = XMLHelper::getFirstChildElement(child, ApplicationOverride);
2116     while (child) {
2117         boost::shared_ptr<XMLApplication> iapp(new XMLApplication(outer, pp.get(), child, defapp.get()));
2118         if (m_appmap.count(iapp->getId()))
2119             log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
2120         else
2121             m_appmap[iapp->getId()] = iapp;
2122
2123         child = XMLHelper::getNextSiblingElement(child, ApplicationOverride);
2124     }
2125
2126     // Check for extra AuthTypes to recognize.
2127     if (conf.isEnabled(SPConfig::InProcess)) {
2128         const PropertySet* inprocs = getPropertySet("InProcess");
2129         if (inprocs) {
2130             pair<bool,const char*> extraAuthTypes = inprocs->getString("extraAuthTypes");
2131             if (extraAuthTypes.first) {
2132                 string types(extraAuthTypes.second);
2133                 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
2134             }
2135         }
2136     }
2137 }
2138
2139 #ifndef SHIBSP_LITE
2140 void XMLConfig::receive(DDF& in, ostream& out)
2141 {
2142     if (!strcmp(in.name(), "get::RelayState")) {
2143         const char* id = in["id"].string();
2144         const char* key = in["key"].string();
2145         if (!id || !key)
2146             throw ListenerException("Required parameters missing for RelayState recovery.");
2147
2148         string relayState;
2149         StorageService* storage = getStorageService(id);
2150         if (storage) {
2151             if (storage->readString("RelayState",key,&relayState)>0) {
2152                 if (in["clear"].integer())
2153                     storage->deleteString("RelayState",key);
2154             }
2155             else if (storage->readText("RelayState",key,&relayState)>0) {
2156                 if (in["clear"].integer())
2157                     storage->deleteText("RelayState",key);
2158             }
2159         }
2160         else {
2161             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2162                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2163                 );
2164         }
2165
2166         // Repack for return to caller.
2167         DDF ret=DDF(nullptr).unsafe_string(relayState.c_str());
2168         DDFJanitor jret(ret);
2169         out << ret;
2170     }
2171     else if (!strcmp(in.name(), "set::RelayState")) {
2172         const char* id = in["id"].string();
2173         const char* value = in["value"].string();
2174         if (!id || !value)
2175             throw ListenerException("Required parameters missing for RelayState creation.");
2176
2177         string rsKey;
2178         StorageService* storage = getStorageService(id);
2179         if (storage) {
2180             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2181             rsKey = SAMLArtifact::toHex(rsKey);
2182             if (strlen(value) <= storage->getCapabilities().getStringSize())
2183                 storage->createString("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2184             else
2185                 storage->createText("RelayState", rsKey.c_str(), value, time(nullptr) + 600);
2186         }
2187         else {
2188             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2189                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
2190                 );
2191         }
2192
2193         // Repack for return to caller.
2194         DDF ret=DDF(nullptr).string(rsKey.c_str());
2195         DDFJanitor jret(ret);
2196         out << ret;
2197     }
2198     else if (!strcmp(in.name(), "get::PostData")) {
2199         const char* id = in["id"].string();
2200         const char* key = in["key"].string();
2201         if (!id || !key)
2202             throw ListenerException("Required parameters missing for PostData recovery.");
2203
2204         string postData;
2205         StorageService* storage = getStorageService(id);
2206         if (storage) {
2207             if (storage->readText("PostData",key,&postData) > 0) {
2208                 storage->deleteText("PostData",key);
2209             }
2210         }
2211         else {
2212             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2213                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2214                 );
2215         }
2216         // If the data's empty, we'll send nothing back.
2217         // If not, we don't need to round trip it, just send back the serialized DDF list.
2218         if (postData.empty()) {
2219             DDF ret(nullptr);
2220             DDFJanitor jret(ret);
2221             out << ret;
2222         }
2223         else {
2224             out << postData;
2225         }
2226     }
2227     else if (!strcmp(in.name(), "set::PostData")) {
2228         const char* id = in["id"].string();
2229         if (!id || !in["parameters"].islist())
2230             throw ListenerException("Required parameters missing for PostData creation.");
2231
2232         string rsKey;
2233         StorageService* storage = getStorageService(id);
2234         if (storage) {
2235             SAMLConfig::getConfig().generateRandomBytes(rsKey,32);
2236             rsKey = SAMLArtifact::toHex(rsKey);
2237             ostringstream params;
2238             params << in["parameters"];
2239             storage->createText("PostData", rsKey.c_str(), params.str().c_str(), time(nullptr) + 600);
2240         }
2241         else {
2242             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
2243                 "Storage-backed PostData with invalid StorageService ID (%s)", id
2244                 );
2245         }
2246
2247         // Repack for return to caller.
2248         DDF ret=DDF(nullptr).string(rsKey.c_str());
2249         DDFJanitor jret(ret);
2250         out << ret;
2251     }
2252 }
2253 #endif
2254
2255 pair<bool,DOMElement*> XMLConfig::background_load()
2256 {
2257     // Load from source using base class.
2258     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
2259
2260     // If we own it, wrap it.
2261     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
2262
2263     scoped_ptr<XMLConfigImpl> impl(new XMLConfigImpl(raw.second, (m_impl==nullptr), this, m_log));
2264
2265     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
2266     impl->setDocument(docjanitor.release());
2267
2268     // Perform the swap inside a lock.
2269     if (m_lock)
2270         m_lock->wrlock();
2271     SharedLock locker(m_lock, false);
2272     m_impl.swap(impl);
2273
2274     return make_pair(false,(DOMElement*)nullptr);
2275 }