9faca915c911514ed64cb8b24c4391e5785ac50a
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / ChainingMetadataProvider.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * ChainingMetadataProvider.cpp
19  * 
20  * MetadataProvider that uses multiple providers in sequence.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "saml/binding/SAMLArtifact.h"
26 #include "saml2/metadata/ChainingMetadataProvider.h"
27
28 #include <memory>
29 #include <xercesc/util/XMLUniDefs.hpp>
30 #include <xmltooling/logging.h>
31 #include <xmltooling/util/XMLHelper.h>
32
33
34 using namespace opensaml::saml2md;
35 using namespace opensaml;
36 using namespace xmlsignature;
37 using namespace xmltooling::logging;
38 using namespace xmltooling;
39 using namespace std;
40
41 namespace opensaml {
42     namespace saml2md {
43         MetadataProvider* SAML_DLLLOCAL ChainingMetadataProviderFactory(const DOMElement* const & e)
44         {
45             return new ChainingMetadataProvider(e);
46         }
47     };
48 };
49
50 static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
51 static const XMLCh precedence[] =           UNICODE_LITERAL_10(p,r,e,c,e,d,e,n,c,e);
52 static const XMLCh last[] =                 UNICODE_LITERAL_4(l,a,s,t);
53 static const XMLCh type[] =                 UNICODE_LITERAL_4(t,y,p,e);
54
55 ChainingMetadataProvider::ChainingMetadataProvider(const DOMElement* e)
56     : ObservableMetadataProvider(e), m_firstMatch(true), m_tlsKey(NULL), m_log(Category::getInstance(SAML_LOGCAT".Metadata.Chaining"))
57 {
58     if (XMLString::equals(e ? e->getAttributeNS(NULL, precedence) : NULL, last))
59         m_firstMatch = false;
60
61     e = e ? XMLHelper::getFirstChildElement(e, _MetadataProvider) : NULL;
62     while (e) {
63         auto_ptr_char temp(e->getAttributeNS(NULL,type));
64         if (temp.get() && *temp.get()) {
65             try {
66                 m_log.info("building MetadataProvider of type %s", temp.get());
67                 auto_ptr<MetadataProvider> provider(
68                     SAMLConfig::getConfig().MetadataProviderManager.newPlugin(temp.get(), e)
69                     );
70                 ObservableMetadataProvider* obs = dynamic_cast<ObservableMetadataProvider*>(provider.get());
71                 if (obs)
72                     obs->addObserver(this);
73                 m_providers.push_back(provider.get());
74                 provider.release();
75             }
76             catch (exception& ex) {
77                 m_log.error("error building MetadataProvider: %s", ex.what());
78             }
79         }
80         e = XMLHelper::getNextSiblingElement(e, _MetadataProvider);
81     }
82     m_tlsKey = ThreadKey::create(NULL);
83 }
84
85 ChainingMetadataProvider::~ChainingMetadataProvider()
86 {
87     delete m_tlsKey;
88     for_each(m_providers.begin(), m_providers.end(), xmltooling::cleanup<MetadataProvider>());
89 }
90
91 void ChainingMetadataProvider::onEvent(const ObservableMetadataProvider& provider) const
92 {
93     emitChangeEvent();
94 }
95
96 void ChainingMetadataProvider::init()
97 {
98     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
99         try {
100             (*i)->init();
101         }
102         catch (exception& ex) {
103             m_log.error("failure initializing MetadataProvider: %s", ex.what());
104         }
105     }
106 }
107
108 Lockable* ChainingMetadataProvider::lock()
109 {
110     return this;   // we're not lockable ourselves...
111 }
112
113 void ChainingMetadataProvider::unlock()
114 {
115     // Check for a locked provider.
116     void* ptr=m_tlsKey->getData();
117     if (ptr) {
118         m_tlsKey->setData(NULL);
119         reinterpret_cast<MetadataProvider*>(ptr)->unlock();
120     }
121 }
122
123 const XMLObject* ChainingMetadataProvider::getMetadata() const
124 {
125     throw MetadataException("getMetadata operation not implemented on this provider.");
126 }
127
128 const EntitiesDescriptor* ChainingMetadataProvider::getEntitiesDescriptor(const char* name, bool requireValidMetadata) const
129 {
130     // Clear any existing lock.
131     const_cast<ChainingMetadataProvider*>(this)->unlock();
132
133     // Do a search.
134     MetadataProvider* held = NULL;
135     const EntitiesDescriptor* ret=NULL;
136     const EntitiesDescriptor* cur=NULL;
137     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
138         (*i)->lock();
139         if (cur=(*i)->getEntitiesDescriptor(name,requireValidMetadata)) {
140             // Are we using a first match policy?
141             if (m_firstMatch) {
142                 // Save locked provider.
143                 m_tlsKey->setData(*i);
144                 return cur;
145             }
146
147             // Using last match wins. Did we already have one?
148             if (held) {
149                 m_log.warn("found duplicate EntitiesDescriptor (%s), using last matching copy", name);
150                 held->unlock();
151             }
152
153             // Save off the latest match.
154             held = *i;
155             ret = cur;
156         }
157         else {
158             // No match, so just unlock this one and move on.
159             (*i)->unlock();
160         }
161     }
162
163     // Preserve any lock we're holding.
164     if (held)
165         m_tlsKey->setData(held);
166     return ret;
167 }
168
169 pair<const EntityDescriptor*,const RoleDescriptor*> ChainingMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
170 {
171     // Clear any existing lock.
172     const_cast<ChainingMetadataProvider*>(this)->unlock();
173
174     // Do a search.
175     MetadataProvider* held = NULL;
176     pair<const EntityDescriptor*,const RoleDescriptor*> ret = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
177     pair<const EntityDescriptor*,const RoleDescriptor*> cur = ret;
178     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
179         (*i)->lock();
180         cur = (*i)->getEntityDescriptor(criteria);
181         if (cur.first) {
182             if (criteria.role) {
183                 // We want a role also. Did we find one?
184                 if (cur.second) {
185                     // Are we using a first match policy?
186                     if (m_firstMatch) {
187                         // We could have an entity-only match from earlier, so unlock it.
188                         if (held)
189                             held->unlock();
190                         // Save locked provider.
191                         m_tlsKey->setData(*i);
192                         return cur;
193                     }
194
195                     // Using last match wins. Did we already have one?
196                     if (held) {
197                         if (ret.second) {
198                             // We had a "complete" match, so log it.
199                             if (criteria.entityID_ascii) {
200                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
201                                     criteria.entityID_ascii, criteria.role->toString().c_str());
202                             }
203                             else if (criteria.entityID_unicode) {
204                                 auto_ptr_char temp(criteria.entityID_unicode);
205                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
206                                     temp.get(), criteria.role->toString().c_str());
207                             }
208                             else if (criteria.artifact) {
209                                 m_log.warn("found duplicate EntityDescriptor for artifact source (%s) with role (%s), using last matching copy",
210                                     criteria.artifact->getSource().c_str(), criteria.role->toString().c_str());
211                             }
212                         }
213                         held->unlock();
214                     }
215
216                     // Save off the latest match.
217                     held = *i;
218                     ret = cur;
219                 }
220                 else {
221                     // We didn't find the role, so we're going to keep looking,
222                     // but save this one if we didn't have the role yet.
223                     if (ret.second) {
224                         // We already had a role, so let's stick with that.
225                         (*i)->unlock();
226                     }
227                     else {
228                         // This is at least as good, so toss anything we had and keep it.
229                         if (held)
230                             held->unlock();
231                         held = *i;
232                         ret = cur;
233                     }
234                 }
235             }
236             else {
237                 // Are we using a first match policy?
238                 if (m_firstMatch) {
239                     // I don't think this can happen, but who cares, check anyway.
240                     if (held)
241                         held->unlock();
242                     
243                     // Save locked provider.
244                     m_tlsKey->setData(*i);
245                     return cur;
246                 }
247
248                 // Using last match wins. Did we already have one?
249                 if (held) {
250                     if (criteria.entityID_ascii) {
251                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", criteria.entityID_ascii);
252                     }
253                     else if (criteria.entityID_unicode) {
254                         auto_ptr_char temp(criteria.entityID_unicode);
255                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", temp.get());
256                     }
257                     else if (criteria.artifact) {
258                         m_log.warn("found duplicate EntityDescriptor for artifact source (%s), using last matching copy",
259                             criteria.artifact->getSource().c_str());
260                     }
261                     held->unlock();
262                 }
263
264                 // Save off the latest match.
265                 held = *i;
266                 ret = cur;
267             }
268         }
269         else {
270             // No match, so just unlock this one and move on.
271             (*i)->unlock();
272         }
273     }
274
275     // Preserve any lock we're holding.
276     if (held)
277         m_tlsKey->setData(held);
278     return ret;
279 }
280
281 const Credential* ChainingMetadataProvider::resolve(const CredentialCriteria* criteria) const
282 {
283     // Check for a locked provider.
284     void* ptr=m_tlsKey->getData();
285     if (!ptr)
286         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
287
288     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(criteria);
289 }
290
291 vector<const Credential*>::size_type ChainingMetadataProvider::resolve(
292     vector<const Credential*>& results, const CredentialCriteria* criteria
293     ) const
294 {
295     // Check for a locked provider.
296     void* ptr=m_tlsKey->getData();
297     if (!ptr)
298         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
299
300     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(results, criteria);
301 }