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