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