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