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