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