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