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