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