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