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