Port up spoof checking
[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
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         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
449 #endif
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
495                     string transformed("HTTP_");
496                     const char* pch = start;
497                     while (*pch) {
498                         transformed += (isalnum(*pch) ? toupper(*pch) : '_');
499                         pch++;
500                     }
501                     m_unsetHeaders.push_back(pair<string,string>(start,transformed));
502                     start = pos ? pos+1 : NULL;
503                 }
504                 free(dup);
505                 m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
506             }
507         }
508
509         Handler* handler=NULL;
510         const PropertySet* sessions = getPropertySet("Sessions");
511
512         // Process assertion export handler.
513         pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
514         if (location.first) {
515             try {
516                 handler = conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, make_pair(sessions->getElement(), getId()));
517                 m_handlers.push_back(handler);
518
519                 // Insert into location map.
520                 if (*location.second == '/')
521                     m_handlerMap[location.second]=handler;
522                 else
523                     m_handlerMap[string("/") + location.second]=handler;
524             }
525             catch (exception& ex) {
526                 log.error("caught exception installing assertion lookup handler: %s", ex.what());
527             }
528         }
529
530         // Process other handlers.
531         bool hardACS=false, hardSessionInit=false, hardArt=false;
532         const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
533         while (child) {
534             try {
535                 // A handler is based on the Binding property in conjunction with the element name.
536                 // If it's an ACS or SI, also handle index/id mappings and defaulting.
537                 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
538                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
539                     if (!bindprop.get() || !*(bindprop.get())) {
540                         log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
541                         child = XMLHelper::getNextSiblingElement(child);
542                         continue;
543                     }
544                     handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
545                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
546 #ifdef HAVE_GOOD_STL
547                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
548 #else
549                     m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
550 #endif
551                     m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
552                     
553                     if (!hardACS) {
554                         pair<bool,bool> defprop=handler->getBool("isDefault");
555                         if (defprop.first) {
556                             if (defprop.second) {
557                                 hardACS=true;
558                                 m_acsDefault=handler;
559                             }
560                         }
561                         else if (!m_acsDefault)
562                             m_acsDefault=handler;
563                     }
564                 }
565                 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
566                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
567                     if (!type.get() || !*(type.get())) {
568                         log.warn("SessionInitiator element has no type attribute, skipping it...");
569                         child = XMLHelper::getNextSiblingElement(child);
570                         continue;
571                     }
572                     SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
573                     handler=sihandler;
574                     pair<bool,const char*> si_id=handler->getString("id");
575                     if (si_id.first && si_id.second)
576                         m_sessionInitMap[si_id.second]=sihandler;
577                     if (!hardSessionInit) {
578                         pair<bool,bool> defprop=handler->getBool("isDefault");
579                         if (defprop.first) {
580                             if (defprop.second) {
581                                 hardSessionInit=true;
582                                 m_sessionInitDefault=sihandler;
583                             }
584                         }
585                         else if (!m_sessionInitDefault)
586                             m_sessionInitDefault=sihandler;
587                     }
588                 }
589                 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
590                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
591                     if (!bindprop.get() || !*(bindprop.get())) {
592                         log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
593                         child = XMLHelper::getNextSiblingElement(child);
594                         continue;
595                     }
596                     handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
597                     
598                     if (!hardArt) {
599                         pair<bool,bool> defprop=handler->getBool("isDefault");
600                         if (defprop.first) {
601                             if (defprop.second) {
602                                 hardArt=true;
603                                 m_artifactResolutionDefault=handler;
604                             }
605                         }
606                         else if (!m_artifactResolutionDefault)
607                             m_artifactResolutionDefault=handler;
608                     }
609                 }
610                 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
611                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
612                     if (!bindprop.get() || !*(bindprop.get())) {
613                         log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
614                         child = XMLHelper::getNextSiblingElement(child);
615                         continue;
616                     }
617                     handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
618                 }
619                 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
620                     auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
621                     if (!bindprop.get() || !*(bindprop.get())) {
622                         log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
623                         child = XMLHelper::getNextSiblingElement(child);
624                         continue;
625                     }
626                     handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
627                 }
628                 else {
629                     auto_ptr_char type(child->getAttributeNS(NULL,_type));
630                     if (!type.get() || !*(type.get())) {
631                         log.warn("Handler element has no type attribute, skipping it...");
632                         child = XMLHelper::getNextSiblingElement(child);
633                         continue;
634                     }
635                     handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
636                 }
637
638                 m_handlers.push_back(handler);
639
640                 // Insert into location map.
641                 location=handler->getString("Location");
642                 if (location.first && *location.second == '/')
643                     m_handlerMap[location.second]=handler;
644                 else if (location.first)
645                     m_handlerMap[string("/") + location.second]=handler;
646
647             }
648             catch (exception& ex) {
649                 log.error("caught exception processing handler element: %s", ex.what());
650             }
651             
652             child = XMLHelper::getNextSiblingElement(child);
653         }
654
655 #ifndef SHIBSP_LITE
656         DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
657         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
658             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
659                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
660
661         // Always include our own entityID as an audience.
662         m_audiences.push_back(getXMLString("entityID").second);
663
664         if (conf.isEnabled(SPConfig::Metadata)) {
665             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
666             if (child) {
667                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
668                 log.info("building MetadataProvider of type %s...",type.get());
669                 try {
670                     auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
671                     mp->init();
672                     m_metadata = mp.release();
673                 }
674                 catch (exception& ex) {
675                     log.crit("error building/initializing MetadataProvider: %s", ex.what());
676                 }
677             }
678         }
679
680         if (conf.isEnabled(SPConfig::Trust)) {
681             child = XMLHelper::getFirstChildElement(e,_TrustEngine);
682             if (child) {
683                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
684                 log.info("building TrustEngine of type %s...",type.get());
685                 try {
686                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
687                 }
688                 catch (exception& ex) {
689                     log.crit("error building TrustEngine: %s", ex.what());
690                 }
691             }
692         }
693
694         if (conf.isEnabled(SPConfig::AttributeResolution)) {
695             child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
696             if (child) {
697                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
698                 log.info("building AttributeExtractor of type %s...",type.get());
699                 try {
700                     m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
701                 }
702                 catch (exception& ex) {
703                     log.crit("error building AttributeExtractor: %s", ex.what());
704                 }
705             }
706
707             child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
708             if (child) {
709                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
710                 log.info("building AttributeFilter of type %s...",type.get());
711                 try {
712                     m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
713                 }
714                 catch (exception& ex) {
715                     log.crit("error building AttributeFilter: %s", ex.what());
716                 }
717             }
718
719             child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
720             if (child) {
721                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
722                 log.info("building AttributeResolver of type %s...",type.get());
723                 try {
724                     m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
725                 }
726                 catch (exception& ex) {
727                     log.crit("error building AttributeResolver: %s", ex.what());
728                 }
729             }
730
731             if (m_unsetHeaders.empty()) {
732                 vector<string> unsetHeaders;
733                 if (m_attrExtractor) {
734                     Locker extlock(m_attrExtractor);
735                     m_attrExtractor->getAttributeIds(unsetHeaders);
736                 }
737                 if (m_attrResolver) {
738                     Locker reslock(m_attrResolver);
739                     m_attrResolver->getAttributeIds(unsetHeaders);
740                 }
741                 if (unsetHeaders.empty()) {
742                     if (m_base)
743                         m_unsetHeaders.insert(m_unsetHeaders.end(), m_base->m_unsetHeaders.begin(), m_base->m_unsetHeaders.end());
744                     else
745                         m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
746                 }
747                 else {
748                     for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
749                         string transformed("HTTP_");
750                         const char* pch = hdr->c_str();
751                         while (*pch) {
752                             transformed += (isalnum(*pch) ? toupper(*pch) : '_');
753                             pch++;
754                         }
755                         m_unsetHeaders.push_back(pair<string,string>(*hdr,transformed));
756                     }
757                     m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
758                 }
759             }
760         }
761
762         if (conf.isEnabled(SPConfig::Credentials)) {
763             child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
764             if (child) {
765                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
766                 log.info("building CredentialResolver of type %s...",type.get());
767                 try {
768                     m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
769                 }
770                 catch (exception& ex) {
771                     log.crit("error building CredentialResolver: %s", ex.what());
772                 }
773             }
774         }
775
776         // Finally, load relying parties.
777         child = XMLHelper::getFirstChildElement(e,DefaultRelyingParty);
778         if (child) {
779             m_partyDefault=new DOMPropertySet();
780             m_partyDefault->load(child,log,this);
781             child = XMLHelper::getFirstChildElement(child,RelyingParty);
782             while (child) {
783                 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
784                 rp->load(child,log,this);
785                 rp->setParent(m_partyDefault);
786                 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
787                 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
788             }
789         }
790 #endif
791
792         // In process only, we need a shared lock around accessing the header clearing list.
793         if (!conf.isEnabled(SPConfig::OutOfProcess)) {
794             m_unsetLock = RWLock::create();
795         }
796         else if (!conf.isEnabled(SPConfig::InProcess)) {
797             ListenerService* listener = sp->getListenerService(false);
798             if (listener) {
799                 string addr=string(getId()) + "::getHeaders::Application";
800                 listener->regListener(addr.c_str(),this);
801             }
802             else
803                 log.info("no ListenerService available, Application remoting disabled");
804         }
805     }
806     catch (exception&) {
807         cleanup();
808         throw;
809     }
810 #ifndef _DEBUG
811     catch (...) {
812         cleanup();
813         throw;
814     }
815 #endif
816 }
817
818 void XMLApplication::cleanup()
819 {
820     ListenerService* listener=getServiceProvider().getListenerService(false);
821     if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
822         string addr=string(getId()) + "::getHeaders::Application";
823         listener->unregListener(addr.c_str(),this);
824     }
825     delete m_unsetLock;
826     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
827 #ifndef SHIBSP_LITE
828     delete m_partyDefault;
829 #ifdef HAVE_GOOD_STL
830     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
831 #else
832     for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
833 #endif
834     delete m_credResolver;
835     delete m_attrResolver;
836     delete m_attrFilter;
837     delete m_attrExtractor;
838     delete m_trust;
839     delete m_metadata;
840 #endif
841 }
842
843 short XMLApplication::acceptNode(const DOMNode* node) const
844 {
845     const XMLCh* name=node->getLocalName();
846     if (XMLString::equals(name,_Application) ||
847         XMLString::equals(name,_Audience) ||
848         XMLString::equals(name,_AssertionConsumerService) ||
849         XMLString::equals(name,_ArtifactResolutionService) ||
850         XMLString::equals(name,_SingleLogoutService) ||
851         XMLString::equals(name,_ManageNameIDService) ||
852         XMLString::equals(name,_SessionInitiator) ||
853         XMLString::equals(name,DefaultRelyingParty) ||
854         XMLString::equals(name,RelyingParty) ||
855         XMLString::equals(name,_MetadataProvider) ||
856         XMLString::equals(name,_TrustEngine) ||
857         XMLString::equals(name,_CredentialResolver) ||
858         XMLString::equals(name,_AttributeFilter) ||
859         XMLString::equals(name,_AttributeExtractor) ||
860         XMLString::equals(name,_AttributeResolver))
861         return FILTER_REJECT;
862
863     return FILTER_ACCEPT;
864 }
865
866 #ifndef SHIBSP_LITE
867
868 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
869 {
870     if (!m_partyDefault && m_base)
871         return m_base->getRelyingParty(provider);
872     else if (!provider)
873         return m_partyDefault;
874         
875 #ifdef HAVE_GOOD_STL
876     map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
877     if (i!=m_partyMap.end())
878         return i->second;
879     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
880     while (group) {
881         if (group->getName()) {
882             i=m_partyMap.find(group->getName());
883             if (i!=m_partyMap.end())
884                 return i->second;
885         }
886         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
887     }
888 #else
889     map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
890     for (; i!=m_partyMap.end(); i++) {
891         if (XMLString::equals(i->first,provider->getId()))
892             return i->second;
893         const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
894         while (group) {
895             if (XMLString::equals(i->first,group->getName()))
896                 return i->second;
897             group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
898         }
899     }
900 #endif
901     return m_partyDefault;
902 }
903
904 #endif
905
906 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
907 {
908     if (m_sessionInitDefault) return m_sessionInitDefault;
909     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
910 }
911
912 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
913 {
914     map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
915     if (i!=m_sessionInitMap.end()) return i->second;
916     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
917 }
918
919 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
920 {
921     if (m_acsDefault) return m_acsDefault;
922     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
923 }
924
925 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
926 {
927     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
928     if (i!=m_acsIndexMap.end()) return i->second;
929     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
930 }
931
932 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
933 {
934 #ifdef HAVE_GOOD_STL
935     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
936 #else
937     auto_ptr_char temp(binding);
938     ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
939 #endif
940     if (i!=m_acsBindingMap.end())
941         return i->second;
942     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
943 }
944
945 const Handler* XMLApplication::getHandler(const char* path) const
946 {
947     string wrap(path);
948     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
949     if (i!=m_handlerMap.end())
950         return i->second;
951     return m_base ? m_base->getHandler(path) : NULL;
952 }
953
954 void XMLApplication::clearAttributeHeaders(SPRequest& request) const
955 {
956     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
957         for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
958             request.clearHeader(i->first.c_str(), i->second.c_str());
959         return;
960     }
961
962     m_unsetLock->rdlock();
963     if (m_unsetHeaders.empty()) {
964         // No headers yet, so we have to request them from the remote half.
965         m_unsetLock->unlock();
966         m_unsetLock->wrlock();
967         if (m_unsetHeaders.empty()) {
968             SharedLock wrlock(m_unsetLock, false);
969             string addr=string(getId()) + "::getHeaders::Application";
970             DDF out,in = DDF(addr.c_str());
971             DDFJanitor jin(in),jout(out);
972             out = getServiceProvider().getListenerService()->send(in);
973             if (out.islist()) {
974                 DDF header = out.first();
975                 while (header.isstring()) {
976                     m_unsetHeaders.push_back(pair<string,string>(header.name(),header.string()));
977                     header = out.next();
978                 }
979             }
980         }
981         else {
982             m_unsetLock->unlock();
983         }
984         m_unsetLock->rdlock();
985     }
986
987     // Now holding read lock.
988     SharedLock unsetLock(m_unsetLock, false);
989     for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
990         request.clearHeader(i->first.c_str(), i->second.c_str());
991 }
992
993 short XMLConfigImpl::acceptNode(const DOMNode* node) const
994 {
995     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
996         return FILTER_ACCEPT;
997     const XMLCh* name=node->getLocalName();
998     if (XMLString::equals(name,Applications) ||
999         XMLString::equals(name,_ArtifactMap) ||
1000         XMLString::equals(name,_Extensions) ||
1001         XMLString::equals(name,Implementation) ||
1002         XMLString::equals(name,Listener) ||
1003         XMLString::equals(name,MemoryListener) ||
1004         XMLString::equals(name,Policy) ||
1005         XMLString::equals(name,_RequestMapper) ||
1006         XMLString::equals(name,_ReplayCache) ||
1007         XMLString::equals(name,_SessionCache) ||
1008         XMLString::equals(name,_StorageService) ||
1009         XMLString::equals(name,TCPListener) ||
1010         XMLString::equals(name,UnixListener))
1011         return FILTER_REJECT;
1012
1013     return FILTER_ACCEPT;
1014 }
1015
1016 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1017 {
1018     const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1019     if (exts) {
1020         exts=XMLHelper::getFirstChildElement(exts,Library);
1021         while (exts) {
1022             auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1023             try {
1024                 if (path.get()) {
1025                     XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts);
1026                     log.debug("loaded %s extension library (%s)", label, path.get());
1027                 }
1028             }
1029             catch (exception& e) {
1030                 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1031                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1032                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1033                     throw;
1034                 }
1035                 else {
1036                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1037                 }
1038             }
1039             exts=XMLHelper::getNextSiblingElement(exts,Library);
1040         }
1041     }
1042 }
1043
1044 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1045     : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1046 {
1047 #ifdef _DEBUG
1048     xmltooling::NDC ndc("XMLConfigImpl");
1049 #endif
1050
1051     try {
1052         SPConfig& conf=SPConfig::getConfig();
1053 #ifndef SHIBSP_LITE
1054         SAMLConfig& samlConf=SAMLConfig::getConfig();
1055 #endif
1056         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1057         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1058         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1059
1060         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1061         if (conf.isEnabled(SPConfig::Logging)) {
1062             const XMLCh* logconf=NULL;
1063             if (conf.isEnabled(SPConfig::OutOfProcess))
1064                 logconf=SHAR->getAttributeNS(NULL,logger);
1065             else if (conf.isEnabled(SPConfig::InProcess))
1066                 logconf=SHIRE->getAttributeNS(NULL,logger);
1067             if (!logconf || !*logconf)
1068                 logconf=e->getAttributeNS(NULL,logger);
1069             if (logconf && *logconf) {
1070                 auto_ptr_char logpath(logconf);
1071                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1072                 XMLToolingConfig::getConfig().log_config(logpath.get());
1073             }
1074             
1075 #ifndef SHIBSP_LITE
1076             if (first)
1077                 m_outer->m_tranLog = new TransactionLog();
1078 #endif
1079         }
1080         
1081         // First load any property sets.
1082         load(e,log,this);
1083
1084         const DOMElement* child;
1085         string plugtype;
1086
1087         // Much of the processing can only occur on the first instantiation.
1088         if (first) {
1089             // Set clock skew.
1090             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1091             if (skew.first)
1092                 xmlConf.clock_skew_secs=skew.second;
1093
1094             // Extensions
1095             doExtensions(e, "global", log);
1096             if (conf.isEnabled(SPConfig::OutOfProcess))
1097                 doExtensions(SHAR, "out of process", log);
1098
1099             if (conf.isEnabled(SPConfig::InProcess))
1100                 doExtensions(SHIRE, "in process", log);
1101             
1102             // Instantiate the ListenerService and SessionCache objects.
1103             if (conf.isEnabled(SPConfig::Listener)) {
1104                 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
1105                 if (child)
1106                     plugtype=UNIX_LISTENER_SERVICE;
1107                 else {
1108                     child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
1109                     if (child)
1110                         plugtype=TCP_LISTENER_SERVICE;
1111                     else {
1112                         child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
1113                         if (child)
1114                             plugtype=MEMORY_LISTENER_SERVICE;
1115                         else {
1116                             child=XMLHelper::getFirstChildElement(SHAR,Listener);
1117                             if (child) {
1118                                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1119                                 if (type.get())
1120                                     plugtype=type.get();
1121                             }
1122                         }
1123                     }
1124                 }
1125                 if (child) {
1126                     log.info("building ListenerService of type %s...", plugtype.c_str());
1127                     m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
1128                 }
1129                 else {
1130                     log.fatal("can't build ListenerService, missing conf:Listener element?");
1131                     throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1132                 }
1133             }
1134
1135             if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1136                 m_outer->m_listener->regListener("set::RelayState",m_outer->m_listener);
1137                 m_outer->m_listener->regListener("get::RelayState",m_outer->m_listener);
1138             }
1139
1140             if (conf.isEnabled(SPConfig::Caching)) {
1141                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1142 #ifndef SHIBSP_LITE
1143                     // First build any StorageServices.
1144                     string inmemID;
1145                     child=XMLHelper::getFirstChildElement(SHAR,_StorageService);
1146                     while (child) {
1147                         auto_ptr_char id(child->getAttributeNS(NULL,_id));
1148                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1149                         try {
1150                             log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1151                             m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1152                             if (!strcmp(type.get(),MEMORY_STORAGE_SERVICE))
1153                                 inmemID = id.get();
1154                         }
1155                         catch (exception& ex) {
1156                             log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1157                         }
1158                         child=XMLHelper::getNextSiblingElement(child,_StorageService);
1159                     }
1160                 
1161                     child=XMLHelper::getFirstChildElement(SHAR,_SessionCache);
1162                     if (child) {
1163                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1164                         log.info("building SessionCache of type %s...",type.get());
1165                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1166                     }
1167                     else {
1168                         log.warn("SessionCache unspecified, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);
1169                         if (inmemID.empty()) {
1170                             inmemID = "memory";
1171                             log.info("no StorageServices configured, providing in-memory version for session cache");
1172                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1173                         }
1174                         child = e->getOwnerDocument()->createElementNS(NULL,_SessionCache);
1175                         auto_ptr_XMLCh ssid(inmemID.c_str());
1176                         const_cast<DOMElement*>(child)->setAttributeNS(NULL,_StorageService,ssid.get());
1177                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
1178                     }
1179
1180                     // Replay cache.
1181                     StorageService* replaySS=NULL;
1182                     child=XMLHelper::getFirstChildElement(SHAR,_ReplayCache);
1183                     if (child) {
1184                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1185                         if (ssid.get() && *ssid.get()) {
1186                             if (m_outer->m_storage.count(ssid.get()))
1187                                 replaySS = m_outer->m_storage[ssid.get()];
1188                             if (replaySS)
1189                                 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1190                             else
1191                                 log.crit("unable to locate StorageService (%s) in configuration", ssid.get());
1192                         }
1193                     }
1194                     if (!replaySS) {
1195                         log.info("building ReplayCache using in-memory StorageService...");
1196                         if (inmemID.empty()) {
1197                             inmemID = "memory";
1198                             log.info("no StorageServices configured, providing in-memory version for legacy config");
1199                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1200                         }
1201                         replaySS = m_outer->m_storage[inmemID];
1202                     }
1203                     xmlConf.setReplayCache(new ReplayCache(replaySS));
1204                     
1205                     // ArtifactMap
1206                     child=XMLHelper::getFirstChildElement(SHAR,_ArtifactMap);
1207                     if (child) {
1208                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1209                         if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1210                             log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1211                             samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1212                         }
1213                     }
1214                     if (samlConf.getArtifactMap()==NULL) {
1215                         log.info("building in-memory ArtifactMap...");
1216                         samlConf.setArtifactMap(new ArtifactMap(child));
1217                     }
1218 #endif
1219                 }
1220                 else {
1221                     child=XMLHelper::getFirstChildElement(SHIRE,_SessionCache);
1222                     if (child) {
1223                         auto_ptr_char type(child->getAttributeNS(NULL,_type));
1224                         log.info("building SessionCache of type %s...",type.get());
1225                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1226                     }
1227                     else {
1228                         log.warn("SessionCache unspecified, building SessionCache of type %s...",REMOTED_SESSION_CACHE);
1229                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(REMOTED_SESSION_CACHE,child);
1230                     }
1231                 }
1232             }
1233         } // end of first-time-only stuff
1234         
1235         // Back to the fully dynamic stuff...next up is the RequestMapper.
1236         if (conf.isEnabled(SPConfig::RequestMapping)) {
1237             child=XMLHelper::getFirstChildElement(SHIRE,_RequestMapper);
1238             if (child) {
1239                 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1240                 log.info("building RequestMapper of type %s...",type.get());
1241                 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1242             }
1243         }
1244         
1245 #ifndef SHIBSP_LITE
1246         // Load security policies.
1247         child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1248         if (child) {
1249             PolicyNodeFilter filter;
1250             child = XMLHelper::getFirstChildElement(child,Policy);
1251             while (child) {
1252                 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1253                 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1254                 rules.first = NULL;
1255                 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1256                 settings->load(child, log, &filter);
1257                 rules.first = settings.release();
1258                 const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);
1259                 while (rule) {
1260                     auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1261                     try {
1262                         rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1263                     }
1264                     catch (exception& ex) {
1265                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1266                     }
1267                     rule = XMLHelper::getNextSiblingElement(rule,Rule);
1268                 }
1269                 child = XMLHelper::getNextSiblingElement(child,Policy);
1270             }
1271         }
1272 #endif
1273
1274         // Load the default application. This actually has a fixed ID of "default". ;-)
1275         child=XMLHelper::getLastChildElement(e,Applications);
1276         if (!child) {
1277             log.fatal("can't build default Application object, missing conf:Applications element?");
1278             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1279         }
1280         XMLApplication* defapp=new XMLApplication(m_outer,child);
1281         m_appmap[defapp->getId()]=defapp;
1282         
1283         // Load any overrides.
1284         child = XMLHelper::getFirstChildElement(child,_Application);
1285         while (child) {
1286             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1287             if (m_appmap.count(iapp->getId()))
1288                 log.crit("found conf:Application element with duplicate id attribute (%s), skipping it", iapp->getId());
1289             else
1290                 m_appmap[iapp->getId()]=iapp.release();
1291
1292             child = XMLHelper::getNextSiblingElement(child,_Application);
1293         }
1294     }
1295     catch (exception&) {
1296         this->~XMLConfigImpl();
1297         throw;
1298     }
1299 #ifndef _DEBUG
1300     catch (...) {
1301         this->~XMLConfigImpl();
1302         throw;
1303     }
1304 #endif
1305 }
1306
1307 XMLConfigImpl::~XMLConfigImpl()
1308 {
1309     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1310 #ifndef SHIBSP_LITE
1311     for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1312         delete i->second.first;
1313         for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1314     }
1315 #endif
1316     delete m_requestMapper;
1317     if (m_document)
1318         m_document->release();
1319 }
1320
1321 void XMLConfig::receive(DDF& in, ostream& out)
1322 {
1323 #ifndef SHIBSP_LITE
1324     if (!strcmp(in.name(), "get::RelayState")) {
1325         const char* id = in["id"].string();
1326         const char* key = in["key"].string();
1327         if (!id || !key)
1328             throw ListenerException("Required parameters missing for RelayState recovery.");
1329
1330         string relayState;
1331         StorageService* storage = getStorageService(id);
1332         if (storage) {
1333             if (storage->readString("RelayState",key,&relayState)>0) {
1334                 if (in["clear"].integer())
1335                     storage->deleteString("RelayState",key);
1336             }
1337         }
1338         else {
1339             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1340                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1341                 );
1342         }
1343
1344         // Repack for return to caller.
1345         DDF ret=DDF(NULL).string(relayState.c_str());
1346         DDFJanitor jret(ret);
1347         out << ret;
1348     }
1349     else if (!strcmp(in.name(), "set::RelayState")) {
1350         const char* id = in["id"].string();
1351         const char* value = in["value"].string();
1352         if (!id || !value)
1353             throw ListenerException("Required parameters missing for RelayState creation.");
1354
1355         string rsKey;
1356         StorageService* storage = getStorageService(id);
1357         if (storage) {
1358             SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1359             rsKey = SAMLArtifact::toHex(rsKey);
1360             storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1361         }
1362         else {
1363             Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1364                 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1365                 );
1366         }
1367
1368         // Repack for return to caller.
1369         DDF ret=DDF(NULL).string(rsKey.c_str());
1370         DDFJanitor jret(ret);
1371         out << ret;
1372     }
1373 #endif
1374 }
1375
1376 pair<bool,DOMElement*> XMLConfig::load()
1377 {
1378     // Load from source using base class.
1379     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1380     
1381     // If we own it, wrap it.
1382     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1383
1384     XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1385     
1386     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1387     impl->setDocument(docjanitor.release());
1388
1389     delete m_impl;
1390     m_impl = impl;
1391
1392     return make_pair(false,(DOMElement*)NULL);
1393 }