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