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