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