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