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