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