a55057e03ab5d4b7b36ea757c45e86c5cca015ee
[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 <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     return this;   // we're not lockable ourselves...
110 }
111
112 void ChainingMetadataProvider::unlock()
113 {
114     // Check for a locked provider.
115     void* ptr=m_tlsKey->getData();
116     if (ptr) {
117         m_tlsKey->setData(NULL);
118         reinterpret_cast<MetadataProvider*>(ptr)->unlock();
119     }
120 }
121
122 const XMLObject* ChainingMetadataProvider::getMetadata() const
123 {
124     throw MetadataException("getMetadata operation not implemented on this provider.");
125 }
126
127 const EntitiesDescriptor* ChainingMetadataProvider::getEntitiesDescriptor(const char* name, bool requireValidMetadata) const
128 {
129     // Clear any existing lock.
130     const_cast<ChainingMetadataProvider*>(this)->unlock();
131
132     // Do a search.
133     MetadataProvider* held = NULL;
134     const EntitiesDescriptor* ret=NULL;
135     const EntitiesDescriptor* cur=NULL;
136     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
137         (*i)->lock();
138         if (cur=(*i)->getEntitiesDescriptor(name,requireValidMetadata)) {
139             // Are we using a first match policy?
140             if (m_firstMatch) {
141                 // Save locked provider.
142                 m_tlsKey->setData(*i);
143                 return cur;
144             }
145
146             // Using last match wins. Did we already have one?
147             if (held) {
148                 m_log.warn("found duplicate EntitiesDescriptor (%s), using last matching copy", name);
149                 held->unlock();
150             }
151
152             // Save off the latest match.
153             held = *i;
154             ret = cur;
155         }
156         else {
157             // No match, so just unlock this one and move on.
158             (*i)->unlock();
159         }
160     }
161
162     // Preserve any lock we're holding.
163     if (held)
164         m_tlsKey->setData(held);
165     return ret;
166 }
167
168 pair<const EntityDescriptor*,const RoleDescriptor*> ChainingMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
169 {
170     // Clear any existing lock.
171     const_cast<ChainingMetadataProvider*>(this)->unlock();
172
173     // Do a search.
174     MetadataProvider* held = NULL;
175     pair<const EntityDescriptor*,const RoleDescriptor*> ret = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
176     pair<const EntityDescriptor*,const RoleDescriptor*> cur = ret;
177     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
178         (*i)->lock();
179         cur = (*i)->getEntityDescriptor(criteria);
180         if (cur.first) {
181             if (criteria.role) {
182                 // We want a role also. Did we find one?
183                 if (cur.second) {
184                     // Are we using a first match policy?
185                     if (m_firstMatch) {
186                         // We could have an entity-only match from earlier, so unlock it.
187                         if (held)
188                             held->unlock();
189                         // Save locked provider.
190                         m_tlsKey->setData(*i);
191                         return cur;
192                     }
193
194                     // Using last match wins. Did we already have one?
195                     if (held) {
196                         if (ret.second) {
197                             // We had a "complete" match, so log it.
198                             if (criteria.entityID_ascii) {
199                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
200                                     criteria.entityID_ascii, criteria.role->toString().c_str());
201                             }
202                             else if (criteria.entityID_unicode) {
203                                 auto_ptr_char temp(criteria.entityID_unicode);
204                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
205                                     temp.get(), criteria.role->toString().c_str());
206                             }
207                             else if (criteria.artifact) {
208                                 m_log.warn("found duplicate EntityDescriptor for artifact source (%s) with role (%s), using last matching copy",
209                                     criteria.artifact->getSource().c_str(), criteria.role->toString().c_str());
210                             }
211                         }
212                         held->unlock();
213                     }
214
215                     // Save off the latest match.
216                     held = *i;
217                     ret = cur;
218                 }
219                 else {
220                     // We didn't find the role, so we're going to keep looking,
221                     // but save this one if we didn't have the role yet.
222                     if (ret.second) {
223                         // We already had a role, so let's stick with that.
224                         (*i)->unlock();
225                     }
226                     else {
227                         // This is at least as good, so toss anything we had and keep it.
228                         if (held)
229                             held->unlock();
230                         held = *i;
231                         ret = cur;
232                     }
233                 }
234             }
235             else {
236                 // Are we using a first match policy?
237                 if (m_firstMatch) {
238                     // I don't think this can happen, but who cares, check anyway.
239                     if (held)
240                         held->unlock();
241                     
242                     // Save locked provider.
243                     m_tlsKey->setData(*i);
244                     return cur;
245                 }
246
247                 // Using last match wins. Did we already have one?
248                 if (held) {
249                     if (criteria.entityID_ascii) {
250                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", criteria.entityID_ascii);
251                     }
252                     else if (criteria.entityID_unicode) {
253                         auto_ptr_char temp(criteria.entityID_unicode);
254                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", temp.get());
255                     }
256                     else if (criteria.artifact) {
257                         m_log.warn("found duplicate EntityDescriptor for artifact source (%s), using last matching copy",
258                             criteria.artifact->getSource().c_str());
259                     }
260                     held->unlock();
261                 }
262
263                 // Save off the latest match.
264                 held = *i;
265                 ret = cur;
266             }
267         }
268         else {
269             // No match, so just unlock this one and move on.
270             (*i)->unlock();
271         }
272     }
273
274     // Preserve any lock we're holding.
275     if (held)
276         m_tlsKey->setData(held);
277     return ret;
278 }
279
280 const Credential* ChainingMetadataProvider::resolve(const CredentialCriteria* criteria) const
281 {
282     // Check for a locked provider.
283     void* ptr=m_tlsKey->getData();
284     if (!ptr)
285         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
286
287     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(criteria);
288 }
289
290 vector<const Credential*>::size_type ChainingMetadataProvider::resolve(
291     vector<const Credential*>& results, const CredentialCriteria* criteria
292     ) const
293 {
294     // Check for a locked provider.
295     void* ptr=m_tlsKey->getData();
296     if (!ptr)
297         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
298
299     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(results, criteria);
300 }