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