ArtifactMap support.
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
1 /*\r
2  *  Copyright 2001-2007 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * XMLServiceProvider.cpp\r
19  *\r
20  * XML-based SP configuration and mgmt\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "exceptions.h"\r
25 #include "AccessControl.h"\r
26 #include "Application.h"\r
27 #include "RequestMapper.h"\r
28 #include "ServiceProvider.h"\r
29 #include "SessionCache.h"\r
30 #include "SPConfig.h"\r
31 #include "SPRequest.h"\r
32 #include "TransactionLog.h"\r
33 #include "attribute/resolver/AttributeResolver.h"\r
34 #include "handler/Handler.h"\r
35 #include "remoting/ListenerService.h"\r
36 #include "security/PKIXTrustEngine.h"\r
37 #include "util/DOMPropertySet.h"\r
38 #include "util/SPConstants.h"\r
39 \r
40 #include <sys/types.h>\r
41 #include <sys/stat.h>\r
42 #include <log4cpp/Category.hh>\r
43 #include <log4cpp/PropertyConfigurator.hh>\r
44 #include <saml/SAMLConfig.h>\r
45 #include <saml/binding/ArtifactMap.h>\r
46 #include <saml/saml1/core/Assertions.h>\r
47 #include <saml/saml2/metadata/ChainingMetadataProvider.h>\r
48 #include <xmltooling/XMLToolingConfig.h>\r
49 #include <xmltooling/security/ChainingTrustEngine.h>\r
50 #include <xmltooling/util/NDC.h>\r
51 #include <xmltooling/util/ReloadableXMLFile.h>\r
52 #include <xmltooling/util/ReplayCache.h>\r
53 \r
54 using namespace shibsp;\r
55 using namespace opensaml::saml2;\r
56 using namespace opensaml::saml2md;\r
57 using namespace opensaml;\r
58 using namespace xmltooling;\r
59 using namespace log4cpp;\r
60 using namespace std;\r
61 \r
62 namespace {\r
63 \r
64 #if defined (_MSC_VER)\r
65     #pragma warning( push )\r
66     #pragma warning( disable : 4250 )\r
67 #endif\r
68 \r
69     class SHIBSP_DLLLOCAL TokenValidator : public Validator\r
70     {\r
71     public:\r
72         TokenValidator(const Application& app, time_t ts=0, const RoleDescriptor* role=NULL) : m_app(app), m_ts(ts), m_role(role) {}\r
73         void validate(const XMLObject*) const;\r
74 \r
75     private:\r
76         const Application& m_app;\r
77         time_t m_ts;\r
78         const RoleDescriptor* m_role;\r
79     };\r
80 \r
81     static vector<const Handler*> g_noHandlers;\r
82 \r
83     // Application configuration wrapper\r
84     class SHIBSP_DLLLOCAL XMLApplication : public virtual Application, public DOMPropertySet, public DOMNodeFilter\r
85     {\r
86     public:\r
87         XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);\r
88         ~XMLApplication() { cleanup(); }\r
89     \r
90         // PropertySet\r
91         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;\r
92         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;\r
93         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;\r
94         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;\r
95         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;\r
96         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:sp:config:2.0") const;\r
97 \r
98         // Application\r
99         const ServiceProvider& getServiceProvider() const {return *m_sp;}\r
100         const char* getId() const {return getString("id").second;}\r
101         const char* getHash() const {return m_hash.c_str();}\r
102 \r
103         MetadataProvider* getMetadataProvider() const {\r
104             return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;\r
105         }\r
106         TrustEngine* getTrustEngine() const {\r
107             return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;\r
108         }\r
109         AttributeResolver* getAttributeResolver() const {\r
110             return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;\r
111         }\r
112 \r
113         const PropertySet* getCredentialUse(const EntityDescriptor* provider) const;\r
114 \r
115         const Handler* getDefaultSessionInitiator() const;\r
116         const Handler* getSessionInitiatorById(const char* id) const;\r
117         const Handler* getDefaultAssertionConsumerService() const;\r
118         const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;\r
119         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;\r
120         const Handler* getHandler(const char* path) const;\r
121 \r
122         const vector<const XMLCh*>& getAudiences() const {\r
123             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;\r
124         }\r
125         Validator* getTokenValidator(time_t ts=0, const opensaml::saml2md::RoleDescriptor* role=NULL) const {\r
126             return new TokenValidator(*this, ts, role);\r
127         }\r
128 \r
129         // Provides filter to exclude special config elements.\r
130         short acceptNode(const DOMNode* node) const;\r
131     \r
132     private:\r
133         void cleanup();\r
134         const ServiceProvider* m_sp;   // this is ok because its locking scope includes us\r
135         const XMLApplication* m_base;\r
136         string m_hash;\r
137         MetadataProvider* m_metadata;\r
138         TrustEngine* m_trust;\r
139         AttributeResolver* m_attrResolver;\r
140         vector<const XMLCh*> m_audiences;\r
141 \r
142         // manage handler objects\r
143         vector<Handler*> m_handlers;\r
144 \r
145         // maps location (path info) to applicable handlers\r
146         map<string,const Handler*> m_handlerMap;\r
147 \r
148         // maps unique indexes to consumer services\r
149         map<unsigned int,const Handler*> m_acsIndexMap;\r
150         \r
151         // pointer to default consumer service\r
152         const Handler* m_acsDefault;\r
153 \r
154         // maps binding strings to supporting consumer service(s)\r
155 #ifdef HAVE_GOOD_STL\r
156         typedef map<xstring,vector<const Handler*> > ACSBindingMap;\r
157 #else\r
158         typedef map<string,vector<const Handler*> > ACSBindingMap;\r
159 #endif\r
160         ACSBindingMap m_acsBindingMap;\r
161 \r
162         // maps unique ID strings to session initiators\r
163         map<string,const Handler*> m_sessionInitMap;\r
164 \r
165         // pointer to default session initiator\r
166         const Handler* m_sessionInitDefault;\r
167 \r
168         DOMPropertySet* m_credDefault;\r
169 #ifdef HAVE_GOOD_STL\r
170         map<xstring,PropertySet*> m_credMap;\r
171 #else\r
172         map<const XMLCh*,PropertySet*> m_credMap;\r
173 #endif\r
174     };\r
175 \r
176     // Top-level configuration implementation\r
177     class SHIBSP_DLLLOCAL XMLConfig;\r
178     class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter\r
179     {\r
180     public:\r
181         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer);\r
182         ~XMLConfigImpl();\r
183         \r
184         RequestMapper* m_requestMapper;\r
185         map<string,Application*> m_appmap;\r
186         map<string,CredentialResolver*> m_credResolverMap;\r
187         map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;\r
188         \r
189         // Provides filter to exclude special config elements.\r
190         short acceptNode(const DOMNode* node) const;\r
191 \r
192         void setDocument(DOMDocument* doc) {\r
193             m_document = doc;\r
194         }\r
195 \r
196     private:\r
197         void doExtensions(const DOMElement* e, const char* label, Category& log);\r
198 \r
199         const XMLConfig* m_outer;\r
200         DOMDocument* m_document;\r
201     };\r
202 \r
203     class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile\r
204     {\r
205     public:\r
206         XMLConfig(const DOMElement* e)\r
207             : ReloadableXMLFile(e), m_impl(NULL), m_listener(NULL), m_sessionCache(NULL), m_tranLog(NULL) {\r
208         }\r
209         \r
210         void init() {\r
211             load();\r
212         }\r
213 \r
214         ~XMLConfig() {\r
215             delete m_impl;\r
216             delete m_sessionCache;\r
217             delete m_listener;\r
218             delete m_tranLog;\r
219             XMLToolingConfig::getConfig().setReplayCache(NULL);\r
220             SAMLConfig::getConfig().setArtifactMap(NULL);\r
221             for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());\r
222         }\r
223 \r
224         // PropertySet\r
225         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}\r
226         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}\r
227         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}\r
228         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}\r
229         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}\r
230         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:sp:config:2.0") const {return m_impl->getPropertySet(name,ns);}\r
231         const DOMElement* getElement() const {return m_impl->getElement();}\r
232 \r
233         // ServiceProvider\r
234         TransactionLog* getTransactionLog() const {\r
235             if (m_tranLog)\r
236                 return m_tranLog;\r
237             throw ConfigurationException("No TransactionLog available.");\r
238         }\r
239 \r
240         StorageService* getStorageService(const char* id) const {\r
241             if (id) {\r
242                 map<string,StorageService*>::const_iterator i=m_storage.find(id);\r
243                 if (i!=m_storage.end())\r
244                     return i->second;\r
245             }\r
246             return NULL;\r
247         }\r
248 \r
249         ListenerService* getListenerService(bool required=true) const {\r
250             if (required && !m_listener)\r
251                 throw ConfigurationException("No ListenerService available.");\r
252             return m_listener;\r
253         }\r
254 \r
255         SessionCache* getSessionCache(bool required=true) const {\r
256             if (required && !m_sessionCache)\r
257                 throw ConfigurationException("No SessionCache available.");\r
258             return m_sessionCache;\r
259         }\r
260 \r
261         RequestMapper* getRequestMapper(bool required=true) const {\r
262             if (required && !m_impl->m_requestMapper)\r
263                 throw ConfigurationException("No RequestMapper available.");\r
264             return m_impl->m_requestMapper;\r
265         }\r
266 \r
267         const Application* getApplication(const char* applicationId) const {\r
268             map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);\r
269             return (i!=m_impl->m_appmap.end()) ? i->second : NULL;\r
270         }\r
271 \r
272         CredentialResolver* getCredentialResolver(const char* id) const {\r
273             if (id) {\r
274                 map<string,CredentialResolver*>::const_iterator i=m_impl->m_credResolverMap.find(id);\r
275                 if (i!=m_impl->m_credResolverMap.end())\r
276                     return i->second;\r
277             }\r
278             return NULL;\r
279         }\r
280 \r
281         const PropertySet* getPolicySettings(const char* id) const {\r
282             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);\r
283             if (i!=m_impl->m_policyMap.end())\r
284                 return i->second.first;\r
285             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));\r
286         }\r
287 \r
288         const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {\r
289             map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);\r
290             if (i!=m_impl->m_policyMap.end())\r
291                 return i->second.second;\r
292             throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));\r
293         }\r
294 \r
295     protected:\r
296         pair<bool,DOMElement*> load();\r
297 \r
298     private:\r
299         friend class XMLConfigImpl;\r
300         XMLConfigImpl* m_impl;\r
301         mutable ListenerService* m_listener;\r
302         mutable SessionCache* m_sessionCache;\r
303         mutable TransactionLog* m_tranLog;\r
304         mutable map<string,StorageService*> m_storage;\r
305     };\r
306 \r
307 #if defined (_MSC_VER)\r
308     #pragma warning( pop )\r
309 #endif\r
310 \r
311     static const XMLCh _Application[] =         UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);\r
312     static const XMLCh Applications[] =         UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);\r
313     static const XMLCh _ArtifactMap[] =         UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);\r
314     static const XMLCh _AttributeResolver[] =   UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);\r
315     static const XMLCh Credentials[] =          UNICODE_LITERAL_11(C,r,e,d,e,n,t,i,a,l,s);\r
316     static const XMLCh CredentialUse[] =        UNICODE_LITERAL_13(C,r,e,d,e,n,t,i,a,l,U,s,e);\r
317     static const XMLCh fatal[] =                UNICODE_LITERAL_5(f,a,t,a,l);\r
318     static const XMLCh _Handler[] =             UNICODE_LITERAL_7(H,a,n,d,l,e,r);\r
319     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);\r
320     static const XMLCh Implementation[] =       UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);\r
321     static const XMLCh InProcess[] =            UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);\r
322     static const XMLCh Library[] =              UNICODE_LITERAL_7(L,i,b,r,a,r,y);\r
323     static const XMLCh Listener[] =             UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);\r
324     static const XMLCh logger[] =               UNICODE_LITERAL_6(l,o,g,g,e,r);\r
325     static const XMLCh MemoryListener[] =       UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);\r
326     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);\r
327     static const XMLCh OutOfProcess[] =         UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);\r
328     static const XMLCh _path[] =                UNICODE_LITERAL_4(p,a,t,h);\r
329     static const XMLCh Policy[] =               UNICODE_LITERAL_6(P,o,l,i,c,y);\r
330     static const XMLCh RelyingParty[] =         UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);\r
331     static const XMLCh _ReplayCache[] =         UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);\r
332     static const XMLCh _RequestMapper[] =       UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);\r
333     static const XMLCh Rule[] =                 UNICODE_LITERAL_4(R,u,l,e);\r
334     static const XMLCh SecurityPolicies[] =     UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);\r
335     static const XMLCh _SessionCache[] =        UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);\r
336     static const XMLCh SessionInitiator[] =     UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);\r
337     static const XMLCh _StorageService[] =      UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);\r
338     static const XMLCh TCPListener[] =          UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);\r
339     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);\r
340     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);\r
341     static const XMLCh UnixListener[] =         UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);\r
342 \r
343     class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter\r
344     {\r
345     public:\r
346         short acceptNode(const DOMNode* node) const {\r
347             if (XMLHelper::isNodeNamed(node,shibspconstants::SHIB2SPCONFIG_NS,Rule))\r
348                 return FILTER_REJECT;\r
349             return FILTER_ACCEPT;\r
350         }\r
351     };\r
352 };\r
353 \r
354 namespace shibsp {\r
355     ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)\r
356     {\r
357         return new XMLConfig(e);\r
358     }\r
359 };\r
360 \r
361 void TokenValidator::validate(const XMLObject* xmlObject) const\r
362 {\r
363 #ifdef _DEBUG\r
364     xmltooling::NDC ndc("validate");\r
365 #endif\r
366     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");\r
367 \r
368     const opensaml::RootObject* root = NULL;\r
369     const opensaml::saml2::Assertion* token2 = dynamic_cast<const opensaml::saml2::Assertion*>(xmlObject);\r
370     if (token2) {\r
371         const opensaml::saml2::Conditions* conds = token2->getConditions();\r
372         // First verify the time conditions, using the specified timestamp, if non-zero.\r
373         if (m_ts>0 && conds) {\r
374             unsigned int skew = XMLToolingConfig::getConfig().clock_skew_secs;\r
375             time_t t=conds->getNotBeforeEpoch();\r
376             if (m_ts+skew < t)\r
377                 throw ValidationException("Assertion is not yet valid.");\r
378             t=conds->getNotOnOrAfterEpoch();\r
379             if (t <= m_ts-skew)\r
380                 throw ValidationException("Assertion is no longer valid.");\r
381         }\r
382 \r
383         // Now we process conditions. Only audience restrictions at the moment.\r
384         const vector<opensaml::saml2::Condition*>& convec = conds->getConditions();\r
385         for (vector<opensaml::saml2::Condition*>::const_iterator c = convec.begin(); c!=convec.end(); ++c) {\r
386             const opensaml::saml2::AudienceRestriction* ac=dynamic_cast<const opensaml::saml2::AudienceRestriction*>(*c);\r
387             if (!ac) {\r
388                 log.error("unrecognized Condition in assertion (%s)",\r
389                     (*c)->getSchemaType() ? (*c)->getSchemaType()->toString().c_str() : (*c)->getElementQName().toString().c_str());\r
390                 throw ValidationException("Assertion contains an unrecognized condition.");\r
391             }\r
392 \r
393             bool found = false;\r
394             const vector<opensaml::saml2::Audience*>& auds1 = ac->getAudiences();\r
395             const vector<const XMLCh*>& auds2 = m_app.getAudiences();\r
396             for (vector<opensaml::saml2::Audience*>::const_iterator a = auds1.begin(); !found && a!=auds1.end(); ++a) {\r
397                 for (vector<const XMLCh*>::const_iterator a2 = auds2.begin(); !found && a2!=auds2.end(); ++a2) {\r
398                     found = XMLString::equals((*a)->getAudienceURI(), *a2);\r
399                 }\r
400             }\r
401 \r
402             if (!found) {\r
403                 ostringstream os;\r
404                 os << *ac;\r
405                 log.error("unacceptable AudienceRestriction in assertion (%s)", os.str().c_str());\r
406                 throw ValidationException("Assertion contains an unacceptable AudienceRestriction.");\r
407             }\r
408         }\r
409 \r
410         root = token2;\r
411     }\r
412     else {\r
413         const opensaml::saml1::Assertion* token1 = dynamic_cast<const opensaml::saml1::Assertion*>(xmlObject);\r
414         if (token1) {\r
415             const opensaml::saml1::Conditions* conds = token1->getConditions();\r
416             // First verify the time conditions, using the specified timestamp, if non-zero.\r
417             if (m_ts>0 && conds) {\r
418                 unsigned int skew = XMLToolingConfig::getConfig().clock_skew_secs;\r
419                 time_t t=conds->getNotBeforeEpoch();\r
420                 if (m_ts+skew < t)\r
421                     throw ValidationException("Assertion is not yet valid.");\r
422                 t=conds->getNotOnOrAfterEpoch();\r
423                 if (t <= m_ts-skew)\r
424                     throw ValidationException("Assertion is no longer valid.");\r
425             }\r
426 \r
427             // Now we process conditions. Only audience restrictions at the moment.\r
428             const vector<opensaml::saml1::Condition*>& convec = conds->getConditions();\r
429             for (vector<opensaml::saml1::Condition*>::const_iterator c = convec.begin(); c!=convec.end(); ++c) {\r
430                 const opensaml::saml1::AudienceRestrictionCondition* ac=dynamic_cast<const opensaml::saml1::AudienceRestrictionCondition*>(*c);\r
431                 if (!ac) {\r
432                     log.error("unrecognized Condition in assertion (%s)",\r
433                         (*c)->getSchemaType() ? (*c)->getSchemaType()->toString().c_str() : (*c)->getElementQName().toString().c_str());\r
434                     throw ValidationException("Assertion contains an unrecognized condition.");\r
435                 }\r
436 \r
437                 bool found = false;\r
438                 const vector<opensaml::saml1::Audience*>& auds1 = ac->getAudiences();\r
439                 const vector<const XMLCh*>& auds2 = m_app.getAudiences();\r
440                 for (vector<opensaml::saml1::Audience*>::const_iterator a = auds1.begin(); !found && a!=auds1.end(); ++a) {\r
441                     for (vector<const XMLCh*>::const_iterator a2 = auds2.begin(); !found && a2!=auds2.end(); ++a2) {\r
442                         found = XMLString::equals((*a)->getAudienceURI(), *a2);\r
443                     }\r
444                 }\r
445 \r
446                 if (!found) {\r
447                     ostringstream os;\r
448                     os << *ac;\r
449                     log.error("unacceptable AudienceRestrictionCondition in assertion (%s)", os.str().c_str());\r
450                     throw ValidationException("Assertion contains an unacceptable AudienceRestrictionCondition.");\r
451                 }\r
452             }\r
453 \r
454             root = token1;\r
455         }\r
456         else {\r
457             throw ValidationException("Unknown object type passed to token validator.");\r
458         }\r
459     }\r
460 \r
461     if (!m_role || !m_app.getTrustEngine()) {\r
462         log.warn("no issuer role or TrustEngine provided, so no signature validation performed");\r
463         return;\r
464     }\r
465 \r
466     const PropertySet* policy=m_app.getServiceProvider().getPolicySettings(m_app.getString("policyId").second);\r
467     pair<bool,bool> signedAssertions=policy ? policy->getBool("signedAssertions") : make_pair(false,false);\r
468 \r
469     if (root->getSignature()) {\r
470         if (!m_app.getTrustEngine()->validate(*(root->getSignature()),*m_role))\r
471             throw ValidationException("Assertion signature did not validate.");\r
472     }\r
473     else if (signedAssertions.first && signedAssertions.second)\r
474         throw ValidationException("Assertion was unsigned, violating policy.");\r
475 }\r
476 \r
477 XMLApplication::XMLApplication(\r
478     const ServiceProvider* sp,\r
479     const DOMElement* e,\r
480     const XMLApplication* base\r
481     ) : m_sp(sp), m_base(base), m_metadata(NULL), m_trust(NULL), m_attrResolver(NULL),\r
482         m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)\r
483 {\r
484 #ifdef _DEBUG\r
485     xmltooling::NDC ndc("XMLApplication");\r
486 #endif\r
487     Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");\r
488 \r
489     try {\r
490         // First load any property sets.\r
491         load(e,log,this);\r
492 \r
493         SPConfig& conf=SPConfig::getConfig();\r
494         SAMLConfig& samlConf=SAMLConfig::getConfig();\r
495         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();\r
496 \r
497         m_hash=getId();\r
498         m_hash+=getString("providerId").second;\r
499         m_hash=samlConf.hashSHA1(m_hash.c_str(), true);\r
500 \r
501         const PropertySet* sessions = getPropertySet("Sessions");\r
502 \r
503         // Process handlers.\r
504         Handler* handler=NULL;\r
505         bool hardACS=false, hardSessionInit=false;\r
506         const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;\r
507         while (child) {\r
508             try {\r
509                 // A handler is based on the Binding property in conjunction with the element name.\r
510                 // If it's an ACS or SI, also handle index/id mappings and defaulting.\r
511                 if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME)) {\r
512                     auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));\r
513                     if (!bindprop.get() || !*(bindprop.get())) {\r
514                         log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");\r
515                         child = XMLHelper::getNextSiblingElement(child);\r
516                         continue;\r
517                     }\r
518                     handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),child);\r
519                     // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)\r
520 #ifdef HAVE_GOOD_STL\r
521                     m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);\r
522 #else\r
523                     m_acsBindingMap[handler->getString("Binding").second].push_back(handler);\r
524 #endif\r
525                     m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;\r
526                     \r
527                     if (!hardACS) {\r
528                         pair<bool,bool> defprop=handler->getBool("isDefault");\r
529                         if (defprop.first) {\r
530                             if (defprop.second) {\r
531                                 hardACS=true;\r
532                                 m_acsDefault=handler;\r
533                             }\r
534                         }\r
535                         else if (!m_acsDefault)\r
536                             m_acsDefault=handler;\r
537                     }\r
538                 }\r
539                 else if (XMLString::equals(child->getLocalName(),SessionInitiator)) {\r
540                     auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));\r
541                     if (!bindprop.get() || !*(bindprop.get())) {\r
542                         log.warn("SessionInitiator element has no Binding attribute, skipping it...");\r
543                         child = XMLHelper::getNextSiblingElement(child);\r
544                         continue;\r
545                     }\r
546                     handler=conf.SessionInitiatorManager.newPlugin(bindprop.get(),child);\r
547                     pair<bool,const char*> si_id=handler->getString("id");\r
548                     if (si_id.first && si_id.second)\r
549                         m_sessionInitMap[si_id.second]=handler;\r
550                     if (!hardSessionInit) {\r
551                         pair<bool,bool> defprop=handler->getBool("isDefault");\r
552                         if (defprop.first) {\r
553                             if (defprop.second) {\r
554                                 hardSessionInit=true;\r
555                                 m_sessionInitDefault=handler;\r
556                             }\r
557                         }\r
558                         else if (!m_sessionInitDefault)\r
559                             m_sessionInitDefault=handler;\r
560                     }\r
561                 }\r
562                 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME)) {\r
563                     auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));\r
564                     if (!bindprop.get() || !*(bindprop.get())) {\r
565                         log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");\r
566                         child = XMLHelper::getNextSiblingElement(child);\r
567                         continue;\r
568                     }\r
569                     handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),child);\r
570                 }\r
571                 else if (XMLHelper::isNodeNamed(child,samlconstants::SAML20MD_NS,ManageNameIDService::LOCAL_NAME)) {\r
572                     auto_ptr_char bindprop(child->getAttributeNS(NULL,EndpointType::BINDING_ATTRIB_NAME));\r
573                     if (!bindprop.get() || !*(bindprop.get())) {\r
574                         log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");\r
575                         child = XMLHelper::getNextSiblingElement(child);\r
576                         continue;\r
577                     }\r
578                     handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),child);\r
579                 }\r
580                 else {\r
581                     auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
582                     if (!type.get() || !*(type.get())) {\r
583                         log.warn("Handler element has no type attribute, skipping it...");\r
584                         child = XMLHelper::getNextSiblingElement(child);\r
585                         continue;\r
586                     }\r
587                     handler=conf.HandlerManager.newPlugin(type.get(),child);\r
588                 }\r
589 \r
590                 // Save off the objects after giving the property set to the handler for its use.\r
591                 m_handlers.push_back(handler);\r
592 \r
593                 // Insert into location map.\r
594                 pair<bool,const char*> location=handler->getString("Location");\r
595                 if (location.first && *location.second == '/')\r
596                     m_handlerMap[location.second]=handler;\r
597                 else if (location.first)\r
598                     m_handlerMap[string("/") + location.second]=handler;\r
599 \r
600             }\r
601             catch (exception& ex) {\r
602                 log.error("caught exception processing handler element: %s", ex.what());\r
603             }\r
604             \r
605             child = XMLHelper::getNextSiblingElement(child);\r
606         }\r
607 \r
608         DOMNodeList* nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);\r
609         for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)\r
610             if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())\r
611                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());\r
612 \r
613         // Always include our own providerId as an audience.\r
614         m_audiences.push_back(getXMLString("providerId").second);\r
615 \r
616         if (conf.isEnabled(SPConfig::Metadata)) {\r
617             child = XMLHelper::getFirstChildElement(e,_MetadataProvider);\r
618             if (child) {\r
619                 auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
620                 log.info("building MetadataProvider of type %s...",type.get());\r
621                 try {\r
622                     auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));\r
623                     mp->init();\r
624                     m_metadata = mp.release();\r
625                 }\r
626                 catch (exception& ex) {\r
627                     log.crit("error building/initializing MetadataProvider: %s", ex.what());\r
628                 }\r
629             }\r
630         }\r
631 \r
632         if (conf.isEnabled(SPConfig::Trust)) {\r
633             child = XMLHelper::getFirstChildElement(e,_TrustEngine);\r
634             if (child) {\r
635                 auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
636                 log.info("building TrustEngine of type %s...",type.get());\r
637                 try {\r
638                     m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);\r
639                 }\r
640                 catch (exception& ex) {\r
641                     log.crit("error building TrustEngine: %s", ex.what());\r
642                 }\r
643             }\r
644         }\r
645 \r
646         if (conf.isEnabled(SPConfig::AttributeResolution)) {\r
647             child = XMLHelper::getFirstChildElement(e,_AttributeResolver);\r
648             if (child) {\r
649                 auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
650                 log.info("building AttributeResolver of type %s...",type.get());\r
651                 try {\r
652                     m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);\r
653                 }\r
654                 catch (exception& ex) {\r
655                     log.crit("error building AttributeResolver: %s", ex.what());\r
656                 }\r
657             }\r
658         }\r
659 \r
660         // Finally, load credential mappings.\r
661         child = XMLHelper::getFirstChildElement(e,CredentialUse);\r
662         if (child) {\r
663             m_credDefault=new DOMPropertySet();\r
664             m_credDefault->load(child,log,this);\r
665             child = XMLHelper::getFirstChildElement(child,RelyingParty);\r
666             while (child) {\r
667                 DOMPropertySet* rp=new DOMPropertySet();\r
668                 rp->load(child,log,this);\r
669                 m_credMap[child->getAttributeNS(NULL,opensaml::saml2::Attribute::NAME_ATTRIB_NAME)]=rp;\r
670                 child = XMLHelper::getNextSiblingElement(child,RelyingParty);\r
671             }\r
672         }\r
673         \r
674         if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
675             // Really finally, build local browser profile and binding objects.\r
676             // TODO: may need some bits here...\r
677         }\r
678     }\r
679     catch (exception&) {\r
680         cleanup();\r
681         throw;\r
682     }\r
683 #ifndef _DEBUG\r
684     catch (...) {\r
685         cleanup();\r
686         throw;\r
687     }\r
688 #endif\r
689 }\r
690 \r
691 void XMLApplication::cleanup()\r
692 {\r
693     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());\r
694     \r
695     delete m_credDefault;\r
696 #ifdef HAVE_GOOD_STL\r
697     for_each(m_credMap.begin(),m_credMap.end(),cleanup_pair<xstring,PropertySet>());\r
698 #else\r
699     for_each(m_credMap.begin(),m_credMap.end(),cleanup_pair<const XMLCh*,PropertySet>());\r
700 #endif\r
701 \r
702     delete m_attrResolver;\r
703     delete m_trust;\r
704     delete m_metadata;\r
705 }\r
706 \r
707 short XMLApplication::acceptNode(const DOMNode* node) const\r
708 {\r
709     if (XMLHelper::isNodeNamed(node,samlconstants::SAML20_NS,opensaml::saml2::Attribute::LOCAL_NAME))\r
710         return FILTER_REJECT;\r
711     else if (XMLHelper::isNodeNamed(node,samlconstants::SAML20_NS,Audience::LOCAL_NAME))\r
712         return FILTER_REJECT;\r
713     const XMLCh* name=node->getLocalName();\r
714     if (XMLString::equals(name,_Application) ||\r
715         XMLString::equals(name,AssertionConsumerService::LOCAL_NAME) ||\r
716         XMLString::equals(name,SingleLogoutService::LOCAL_NAME) ||\r
717         XMLString::equals(name,ManageNameIDService::LOCAL_NAME) ||\r
718         XMLString::equals(name,SessionInitiator) ||\r
719         XMLString::equals(name,CredentialUse) ||\r
720         XMLString::equals(name,RelyingParty) ||\r
721         XMLString::equals(name,_MetadataProvider) ||\r
722         XMLString::equals(name,_TrustEngine) ||\r
723         XMLString::equals(name,_AttributeResolver))\r
724         return FILTER_REJECT;\r
725 \r
726     return FILTER_ACCEPT;\r
727 }\r
728 \r
729 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const\r
730 {\r
731     pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);\r
732     if (ret.first)\r
733         return ret;\r
734     return m_base ? m_base->getBool(name,ns) : ret;\r
735 }\r
736 \r
737 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const\r
738 {\r
739     pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);\r
740     if (ret.first)\r
741         return ret;\r
742     return m_base ? m_base->getString(name,ns) : ret;\r
743 }\r
744 \r
745 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const\r
746 {\r
747     pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);\r
748     if (ret.first)\r
749         return ret;\r
750     return m_base ? m_base->getXMLString(name,ns) : ret;\r
751 }\r
752 \r
753 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const\r
754 {\r
755     pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);\r
756     if (ret.first)\r
757         return ret;\r
758     return m_base ? m_base->getUnsignedInt(name,ns) : ret;\r
759 }\r
760 \r
761 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const\r
762 {\r
763     pair<bool,int> ret=DOMPropertySet::getInt(name,ns);\r
764     if (ret.first)\r
765         return ret;\r
766     return m_base ? m_base->getInt(name,ns) : ret;\r
767 }\r
768 \r
769 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const\r
770 {\r
771     const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);\r
772     if (ret || !m_base)\r
773         return ret;\r
774     return m_base->getPropertySet(name,ns);\r
775 }\r
776 \r
777 const PropertySet* XMLApplication::getCredentialUse(const EntityDescriptor* provider) const\r
778 {\r
779     if (!m_credDefault && m_base)\r
780         return m_base->getCredentialUse(provider);\r
781         \r
782 #ifdef HAVE_GOOD_STL\r
783     map<xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getEntityID());\r
784     if (i!=m_credMap.end())\r
785         return i->second;\r
786     const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());\r
787     while (group) {\r
788         if (group->getName()) {\r
789             i=m_credMap.find(group->getName());\r
790             if (i!=m_credMap.end())\r
791                 return i->second;\r
792         }\r
793         group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());\r
794     }\r
795 #else\r
796     map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();\r
797     for (; i!=m_credMap.end(); i++) {\r
798         if (XMLString::equals(i->first,provider->getId()))\r
799             return i->second;\r
800         const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());\r
801         while (group) {\r
802             if (XMLString::equals(i->first,group->getName()))\r
803                 return i->second;\r
804             group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());\r
805         }\r
806     }\r
807 #endif\r
808     return m_credDefault;\r
809 }\r
810 \r
811 const Handler* XMLApplication::getDefaultSessionInitiator() const\r
812 {\r
813     if (m_sessionInitDefault) return m_sessionInitDefault;\r
814     return m_base ? m_base->getDefaultSessionInitiator() : NULL;\r
815 }\r
816 \r
817 const Handler* XMLApplication::getSessionInitiatorById(const char* id) const\r
818 {\r
819     map<string,const Handler*>::const_iterator i=m_sessionInitMap.find(id);\r
820     if (i!=m_sessionInitMap.end()) return i->second;\r
821     return m_base ? m_base->getSessionInitiatorById(id) : NULL;\r
822 }\r
823 \r
824 const Handler* XMLApplication::getDefaultAssertionConsumerService() const\r
825 {\r
826     if (m_acsDefault) return m_acsDefault;\r
827     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;\r
828 }\r
829 \r
830 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const\r
831 {\r
832     map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);\r
833     if (i!=m_acsIndexMap.end()) return i->second;\r
834     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;\r
835 }\r
836 \r
837 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const\r
838 {\r
839 #ifdef HAVE_GOOD_STL\r
840     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);\r
841 #else\r
842     auto_ptr_char temp(binding);\r
843     ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());\r
844 #endif\r
845     if (i!=m_acsBindingMap.end())\r
846         return i->second;\r
847     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;\r
848 }\r
849 \r
850 const Handler* XMLApplication::getHandler(const char* path) const\r
851 {\r
852     string wrap(path);\r
853     map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));\r
854     if (i!=m_handlerMap.end())\r
855         return i->second;\r
856     return m_base ? m_base->getHandler(path) : NULL;\r
857 }\r
858 \r
859 short XMLConfigImpl::acceptNode(const DOMNode* node) const\r
860 {\r
861     if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))\r
862         return FILTER_ACCEPT;\r
863     const XMLCh* name=node->getLocalName();\r
864     if (XMLString::equals(name,Applications) ||\r
865         XMLString::equals(name,_ArtifactMap) ||\r
866         XMLString::equals(name,Credentials) ||\r
867         XMLString::equals(name,Extensions::LOCAL_NAME) ||\r
868         XMLString::equals(name,Implementation) ||\r
869         XMLString::equals(name,Listener) ||\r
870         XMLString::equals(name,MemoryListener) ||\r
871         XMLString::equals(name,Policy) ||\r
872         XMLString::equals(name,_RequestMapper) ||\r
873         XMLString::equals(name,_ReplayCache) ||\r
874         XMLString::equals(name,_SessionCache) ||\r
875         XMLString::equals(name,_StorageService) ||\r
876         XMLString::equals(name,TCPListener) ||\r
877         XMLString::equals(name,UnixListener))\r
878         return FILTER_REJECT;\r
879 \r
880     return FILTER_ACCEPT;\r
881 }\r
882 \r
883 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)\r
884 {\r
885     const DOMElement* exts=XMLHelper::getFirstChildElement(e,Extensions::LOCAL_NAME);\r
886     if (exts) {\r
887         exts=XMLHelper::getFirstChildElement(exts,Library);\r
888         while (exts) {\r
889             auto_ptr_char path(exts->getAttributeNS(NULL,_path));\r
890             try {\r
891                 if (path.get()) {\r
892                     XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts);\r
893                     log.debug("loaded %s extension library (%s)", label, path.get());\r
894                 }\r
895             }\r
896             catch (exception& e) {\r
897                 const XMLCh* fatal=exts->getAttributeNS(NULL,fatal);\r
898                 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {\r
899                     log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());\r
900                     throw;\r
901                 }\r
902                 else {\r
903                     log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());\r
904                 }\r
905             }\r
906             exts=XMLHelper::getNextSiblingElement(exts,Library);\r
907         }\r
908     }\r
909 }\r
910 \r
911 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer) : m_requestMapper(NULL), m_outer(outer), m_document(NULL)\r
912 {\r
913 #ifdef _DEBUG\r
914     xmltooling::NDC ndc("XMLConfigImpl");\r
915 #endif\r
916     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");\r
917 \r
918     try {\r
919         SPConfig& conf=SPConfig::getConfig();\r
920         SAMLConfig& samlConf=SAMLConfig::getConfig();\r
921         XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();\r
922         const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);\r
923         const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);\r
924 \r
925         // Initialize log4cpp manually in order to redirect log messages as soon as possible.\r
926         if (conf.isEnabled(SPConfig::Logging)) {\r
927             const XMLCh* logconf=NULL;\r
928             if (conf.isEnabled(SPConfig::OutOfProcess))\r
929                 logconf=SHAR->getAttributeNS(NULL,logger);\r
930             else if (conf.isEnabled(SPConfig::InProcess))\r
931                 logconf=SHIRE->getAttributeNS(NULL,logger);\r
932             if (!logconf || !*logconf)\r
933                 logconf=e->getAttributeNS(NULL,logger);\r
934             if (logconf && *logconf) {\r
935                 auto_ptr_char logpath(logconf);\r
936                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());\r
937                 XMLToolingConfig::getConfig().log_config(logpath.get());\r
938             }\r
939             \r
940             if (first)\r
941                 m_outer->m_tranLog = new TransactionLog();\r
942         }\r
943         \r
944         // First load any property sets.\r
945         load(e,log,this);\r
946 \r
947         const DOMElement* child;\r
948         string plugtype;\r
949 \r
950         // Much of the processing can only occur on the first instantiation.\r
951         if (first) {\r
952             // Set clock skew.\r
953             pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");\r
954             if (skew.first)\r
955                 xmlConf.clock_skew_secs=skew.second;\r
956 \r
957             // Extensions\r
958             doExtensions(e, "global", log);\r
959             if (conf.isEnabled(SPConfig::OutOfProcess))\r
960                 doExtensions(SHAR, "out of process", log);\r
961 \r
962             if (conf.isEnabled(SPConfig::InProcess))\r
963                 doExtensions(SHIRE, "in process", log);\r
964             \r
965             // Instantiate the ListenerService and SessionCache objects.\r
966             if (conf.isEnabled(SPConfig::Listener)) {\r
967                 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);\r
968                 if (child)\r
969                     plugtype=UNIX_LISTENER_SERVICE;\r
970                 else {\r
971                     child=XMLHelper::getFirstChildElement(SHAR,TCPListener);\r
972                     if (child)\r
973                         plugtype=TCP_LISTENER_SERVICE;\r
974                     else {\r
975                         child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);\r
976                         if (child)\r
977                             plugtype=MEMORY_LISTENER_SERVICE;\r
978                         else {\r
979                             child=XMLHelper::getFirstChildElement(SHAR,Listener);\r
980                             if (child) {\r
981                                 auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
982                                 if (type.get())\r
983                                     plugtype=type.get();\r
984                             }\r
985                         }\r
986                     }\r
987                 }\r
988                 if (child) {\r
989                     log.info("building ListenerService of type %s...", plugtype.c_str());\r
990                     m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);\r
991                 }\r
992                 else {\r
993                     log.fatal("can't build ListenerService, missing conf:Listener element?");\r
994                     throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");\r
995                 }\r
996             }\r
997 \r
998             if (conf.isEnabled(SPConfig::Caching)) {\r
999                 if (conf.isEnabled(SPConfig::OutOfProcess)) {\r
1000                     // First build any StorageServices.\r
1001                     string inmemID;\r
1002                     child=XMLHelper::getFirstChildElement(SHAR,_StorageService);\r
1003                     while (child) {\r
1004                         auto_ptr_char id(child->getAttributeNS(NULL,_id));\r
1005                         auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
1006                         try {\r
1007                             log.info("building StorageService (%s) of type %s...", id.get(), type.get());\r
1008                             m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);\r
1009                             if (!strcmp(type.get(),MEMORY_STORAGE_SERVICE))\r
1010                                 inmemID = id.get();\r
1011                         }\r
1012                         catch (exception& ex) {\r
1013                             log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());\r
1014                         }\r
1015                         child=XMLHelper::getNextSiblingElement(child,_StorageService);\r
1016                     }\r
1017                 \r
1018                     child=XMLHelper::getFirstChildElement(SHAR,_SessionCache);\r
1019                     if (child) {\r
1020                         auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
1021                         log.info("building SessionCache of type %s...",type.get());\r
1022                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);\r
1023                     }\r
1024                     else {\r
1025                         log.warn("SessionCache unspecified, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);\r
1026                         if (inmemID.empty()) {\r
1027                             inmemID = "memory";\r
1028                             log.info("no StorageServices configured, providing in-memory version for session cache");\r
1029                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);\r
1030                         }\r
1031                         child = e->getOwnerDocument()->createElementNS(NULL,_SessionCache);\r
1032                         auto_ptr_XMLCh ssid(inmemID.c_str());\r
1033                         const_cast<DOMElement*>(child)->setAttributeNS(NULL,_StorageService,ssid.get());\r
1034                         m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);\r
1035                     }\r
1036 \r
1037                     // Replay cache.\r
1038                     StorageService* replaySS=NULL;\r
1039                     child=XMLHelper::getFirstChildElement(SHAR,_ReplayCache);\r
1040                     if (child) {\r
1041                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));\r
1042                         if (ssid.get() && *ssid.get()) {\r
1043                             if (m_outer->m_storage.count(ssid.get()))\r
1044                                 replaySS = m_outer->m_storage[ssid.get()];\r
1045                             if (replaySS)\r
1046                                 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());\r
1047                             else\r
1048                                 log.crit("unable to locate StorageService (%s) in configuration", ssid.get());\r
1049                         }\r
1050                     }\r
1051                     if (!replaySS) {\r
1052                         log.info("building ReplayCache using in-memory StorageService...");\r
1053                         if (inmemID.empty()) {\r
1054                             inmemID = "memory";\r
1055                             log.info("no StorageServices configured, providing in-memory version for legacy config");\r
1056                             m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);\r
1057                         }\r
1058                         replaySS = m_outer->m_storage[inmemID];\r
1059                     }\r
1060                     xmlConf.setReplayCache(new ReplayCache(replaySS));\r
1061                     \r
1062                     // ArtifactMap\r
1063                     child=XMLHelper::getFirstChildElement(SHAR,_ArtifactMap);\r
1064                     if (child) {\r
1065                         auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));\r
1066                         if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {\r
1067                             log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());\r
1068                             samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));\r
1069                         }\r
1070                     }\r
1071                     if (samlConf.getArtifactMap()==NULL) {\r
1072                         log.info("building in-memory ArtifactMap...");\r
1073                         samlConf.setArtifactMap(new ArtifactMap(child));\r
1074                     }\r
1075                 }\r
1076                 else {\r
1077                     log.info("building in-process SessionCache of type %s...",REMOTED_SESSION_CACHE);\r
1078                     m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(REMOTED_SESSION_CACHE,NULL);\r
1079                 }\r
1080             }\r
1081         } // end of first-time-only stuff\r
1082         \r
1083         // Back to the fully dynamic stuff...next up is the RequestMapper.\r
1084         if (conf.isEnabled(SPConfig::RequestMapping)) {\r
1085             child=XMLHelper::getFirstChildElement(SHIRE,_RequestMapper);\r
1086             if (child) {\r
1087                 auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
1088                 log.info("building RequestMapper of type %s...",type.get());\r
1089                 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);\r
1090             }\r
1091         }\r
1092         \r
1093         // Now we load the credentials map.\r
1094         if (conf.isEnabled(SPConfig::Credentials)) {\r
1095             child = XMLHelper::getLastChildElement(e,Credentials);\r
1096             if (child) {\r
1097                 // Step down and process resolvers.\r
1098                 child=XMLHelper::getFirstChildElement(child);\r
1099                 while (child) {\r
1100                     auto_ptr_char id(child->getAttributeNS(NULL,_id));\r
1101                     auto_ptr_char type(child->getAttributeNS(NULL,_type));\r
1102                     try {\r
1103                         CredentialResolver* cr=xmlConf.CredentialResolverManager.newPlugin(type.get(),child);\r
1104                         m_credResolverMap[id.get()] = cr;\r
1105                     }\r
1106                     catch (exception& ex) {\r
1107                         log.crit("failed to instantiate CredentialResolver (%s): %s", id.get(), ex.what());\r
1108                     }\r
1109                     child = XMLHelper::getNextSiblingElement(child);\r
1110                 }\r
1111             }\r
1112         }\r
1113 \r
1114         // Load security policies.\r
1115         child = XMLHelper::getLastChildElement(e,SecurityPolicies);\r
1116         if (child) {\r
1117             PolicyNodeFilter filter;\r
1118             child = XMLHelper::getFirstChildElement(child,Policy);\r
1119             while (child) {\r
1120                 auto_ptr_char id(child->getAttributeNS(NULL,_id));\r
1121                 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];\r
1122                 rules.first = NULL;\r
1123                 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());\r
1124                 settings->load(child, log, &filter);\r
1125                 rules.first = settings.release();\r
1126                 const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);\r
1127                 while (rule) {\r
1128                     auto_ptr_char type(rule->getAttributeNS(NULL,_type));\r
1129                     try {\r
1130                         rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));\r
1131                     }\r
1132                     catch (exception& ex) {\r
1133                         log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());\r
1134                     }\r
1135                     rule = XMLHelper::getNextSiblingElement(rule,Rule);\r
1136                 }\r
1137                 child = XMLHelper::getNextSiblingElement(child,Policy);\r
1138             }\r
1139         }\r
1140 \r
1141         // Load the default application. This actually has a fixed ID of "default". ;-)\r
1142         child=XMLHelper::getLastChildElement(e,Applications);\r
1143         if (!child) {\r
1144             log.fatal("can't build default Application object, missing conf:Applications element?");\r
1145             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");\r
1146         }\r
1147         XMLApplication* defapp=new XMLApplication(m_outer,child);\r
1148         m_appmap[defapp->getId()]=defapp;\r
1149         \r
1150         // Load any overrides.\r
1151         child = XMLHelper::getFirstChildElement(child,_Application);\r
1152         while (child) {\r
1153             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));\r
1154             if (m_appmap.count(iapp->getId()))\r
1155                 log.crit("found conf:Application element with duplicate id attribute (%s), skipping it", iapp->getId());\r
1156             else\r
1157                 m_appmap[iapp->getId()]=iapp.release();\r
1158 \r
1159             child = XMLHelper::getNextSiblingElement(child,_Application);\r
1160         }\r
1161     }\r
1162     catch (exception&) {\r
1163         this->~XMLConfigImpl();\r
1164         throw;\r
1165     }\r
1166 #ifndef _DEBUG\r
1167     catch (...) {\r
1168         this->~XMLConfigImpl();\r
1169         throw;\r
1170     }\r
1171 #endif\r
1172 }\r
1173 \r
1174 XMLConfigImpl::~XMLConfigImpl()\r
1175 {\r
1176     for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());\r
1177     for_each(m_credResolverMap.begin(),m_credResolverMap.end(),cleanup_pair<string,CredentialResolver>());\r
1178     for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {\r
1179         delete i->second.first;\r
1180         for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());\r
1181     }\r
1182     delete m_requestMapper;\r
1183     if (m_document)\r
1184         m_document->release();\r
1185 }\r
1186 \r
1187 pair<bool,DOMElement*> XMLConfig::load()\r
1188 {\r
1189     // Load from source using base class.\r
1190     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();\r
1191     \r
1192     // If we own it, wrap it.\r
1193     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);\r
1194 \r
1195     XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this);\r
1196     \r
1197     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.\r
1198     impl->setDocument(docjanitor.release());\r
1199 \r
1200     delete m_impl;\r
1201     m_impl = impl;\r
1202 \r
1203     return make_pair(false,(DOMElement*)NULL);\r
1204 }\r