f1e58815acd0cd5d428711dc881087b8c2877a67
[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     bool bRole = (criteria.role && criteria.protocol);  // searching for role also?
171
172     // Clear any existing lock.
173     const_cast<ChainingMetadataProvider*>(this)->unlock();
174
175     // Do a search.
176     MetadataProvider* held = NULL;
177     pair<const EntityDescriptor*,const RoleDescriptor*> ret = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
178     pair<const EntityDescriptor*,const RoleDescriptor*> cur = ret;
179     for (vector<MetadataProvider*>::const_iterator i=m_providers.begin(); i!=m_providers.end(); ++i) {
180         (*i)->lock();
181         cur = (*i)->getEntityDescriptor(criteria);
182         if (cur.first) {
183             if (bRole) {
184                 // We want a role also. Did we find one?
185                 if (cur.second) {
186                     // Are we using a first match policy?
187                     if (m_firstMatch) {
188                         // We could have an entity-only match from earlier, so unlock it.
189                         if (held)
190                             held->unlock();
191                         // Save locked provider.
192                         m_tlsKey->setData(*i);
193                         return cur;
194                     }
195
196                     // Using last match wins. Did we already have one?
197                     if (held) {
198                         if (ret.second) {
199                             // We had a "complete" match, so log it.
200                             if (criteria.entityID_ascii) {
201                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
202                                     criteria.entityID_ascii, criteria.role->toString().c_str());
203                             }
204                             else if (criteria.entityID_unicode) {
205                                 auto_ptr_char temp(criteria.entityID_unicode);
206                                 m_log.warn("found duplicate EntityDescriptor (%s) with role (%s), using last matching copy",
207                                     temp.get(), criteria.role->toString().c_str());
208                             }
209                             else if (criteria.artifact) {
210                                 m_log.warn("found duplicate EntityDescriptor for artifact source (%s) with role (%s), using last matching copy",
211                                     criteria.artifact->getSource().c_str(), criteria.role->toString().c_str());
212                             }
213                         }
214                         held->unlock();
215                     }
216
217                     // Save off the latest match.
218                     held = *i;
219                     ret = cur;
220                 }
221                 else {
222                     // We didn't find the role, so we're going to keep looking,
223                     // but save this one if we didn't have the role yet.
224                     if (ret.second) {
225                         // We already had a role, so let's stick with that.
226                         (*i)->unlock();
227                     }
228                     else {
229                         // This is at least as good, so toss anything we had and keep it.
230                         if (held)
231                             held->unlock();
232                         held = *i;
233                         ret = cur;
234                     }
235                 }
236             }
237             else {
238                 // Are we using a first match policy?
239                 if (m_firstMatch) {
240                     // I don't think this can happen, but who cares, check anyway.
241                     if (held)
242                         held->unlock();
243                     
244                     // Save locked provider.
245                     m_tlsKey->setData(*i);
246                     return cur;
247                 }
248
249                 // Using last match wins. Did we already have one?
250                 if (held) {
251                     if (criteria.entityID_ascii) {
252                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", criteria.entityID_ascii);
253                     }
254                     else if (criteria.entityID_unicode) {
255                         auto_ptr_char temp(criteria.entityID_unicode);
256                         m_log.warn("found duplicate EntityDescriptor (%s), using last matching copy", temp.get());
257                     }
258                     else if (criteria.artifact) {
259                         m_log.warn("found duplicate EntityDescriptor for artifact source (%s), using last matching copy",
260                             criteria.artifact->getSource().c_str());
261                     }
262                     held->unlock();
263                 }
264
265                 // Save off the latest match.
266                 held = *i;
267                 ret = cur;
268             }
269         }
270         else {
271             // No match, so just unlock this one and move on.
272             (*i)->unlock();
273         }
274     }
275
276     // Preserve any lock we're holding.
277     if (held)
278         m_tlsKey->setData(held);
279     return ret;
280 }
281
282 const Credential* ChainingMetadataProvider::resolve(const CredentialCriteria* criteria) const
283 {
284     // Check for a locked provider.
285     void* ptr=m_tlsKey->getData();
286     if (!ptr)
287         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
288
289     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(criteria);
290 }
291
292 vector<const Credential*>::size_type ChainingMetadataProvider::resolve(
293     vector<const Credential*>& results, const CredentialCriteria* criteria
294     ) const
295 {
296     // Check for a locked provider.
297     void* ptr=m_tlsKey->getData();
298     if (!ptr)
299         throw MetadataException("No locked MetadataProvider, where did the role object come from?");
300
301     return reinterpret_cast<MetadataProvider*>(ptr)->resolve(results, criteria);
302 }