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