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