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