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