Fix comments, add a missing const.
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / AbstractMetadataProvider.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  * AbstractMetadataProvider.cpp
19  * 
20  * Base class for caching metadata providers.
21  */
22
23 #include "internal.h"
24 #include "binding/SAMLArtifact.h"
25 #include "saml2/metadata/Metadata.h"
26 #include "saml2/metadata/AbstractMetadataProvider.h"
27 #include "saml2/metadata/MetadataCredentialContext.h"
28 #include "saml2/metadata/MetadataCredentialCriteria.h"
29
30 #include <xercesc/util/XMLUniDefs.hpp>
31 #include <xmltooling/security/KeyInfoResolver.h>
32 #include <xmltooling/util/XMLHelper.h>
33
34 using namespace opensaml::saml2md;
35 using namespace xmltooling;
36 using namespace std;
37 using opensaml::SAMLArtifact;
38
39 static const XMLCh _KeyInfoResolver[] = UNICODE_LITERAL_15(K,e,y,I,n,f,o,R,e,s,o,l,v,e,r);
40 static const XMLCh type[] =             UNICODE_LITERAL_4(t,y,p,e);
41
42 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
43     : ObservableMetadataProvider(e), m_resolver(NULL), m_credentialLock(NULL)
44 {
45     e = e ? XMLHelper::getFirstChildElement(e, _KeyInfoResolver) : NULL;
46     if (e) {
47         auto_ptr_char t(e->getAttributeNS(NULL,type));
48         if (t.get())
49             m_resolver = XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.get(),e);
50         else
51             throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
52     }
53     m_credentialLock = Mutex::create();
54 }
55
56 AbstractMetadataProvider::~AbstractMetadataProvider()
57 {
58     for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
59         for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
60     delete m_credentialLock;
61     delete m_resolver;
62 }
63
64 void AbstractMetadataProvider::emitChangeEvent() const
65 {
66     for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
67         for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
68     m_credentialMap.clear();
69     ObservableMetadataProvider::emitChangeEvent();
70 }
71
72 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil)
73 {
74     if (validUntil < site->getValidUntilEpoch())
75         site->setValidUntil(validUntil);
76
77     auto_ptr_char id(site->getEntityID());
78     if (id.get()) {
79         m_sites.insert(make_pair(id.get(),site));
80     }
81     
82     // Process each IdP role.
83     const vector<IDPSSODescriptor*>& roles=const_cast<const EntityDescriptor*>(site)->getIDPSSODescriptors();
84     for (vector<IDPSSODescriptor*>::const_iterator i=roles.begin(); i!=roles.end(); i++) {
85         // SAML 1.x?
86         if ((*i)->hasSupport(samlconstants::SAML10_PROTOCOL_ENUM) || (*i)->hasSupport(samlconstants::SAML11_PROTOCOL_ENUM)) {
87             // Check for SourceID extension element.
88             const Extensions* exts=(*i)->getExtensions();
89             if (exts && exts->hasChildren()) {
90                 const vector<XMLObject*>& children=exts->getUnknownXMLObjects();
91                 for (vector<XMLObject*>::const_iterator ext=children.begin(); ext!=children.end(); ++ext) {
92                     SourceID* sid=dynamic_cast<SourceID*>(*ext);
93                     if (sid) {
94                         auto_ptr_char sourceid(sid->getID());
95                         if (sourceid.get()) {
96                             m_sources.insert(pair<string,const EntityDescriptor*>(sourceid.get(),site));
97                             break;
98                         }
99                     }
100                 }
101             }
102             
103             // Hash the ID.
104             m_sources.insert(
105                 pair<string,const EntityDescriptor*>(SAMLConfig::getConfig().hashSHA1(id.get(), true),site)
106                 );
107                 
108             // Load endpoints for type 0x0002 artifacts.
109             const vector<ArtifactResolutionService*>& locs=const_cast<const IDPSSODescriptor*>(*i)->getArtifactResolutionServices();
110             for (vector<ArtifactResolutionService*>::const_iterator loc=locs.begin(); loc!=locs.end(); loc++) {
111                 auto_ptr_char location((*loc)->getLocation());
112                 if (location.get())
113                     m_sources.insert(pair<string,const EntityDescriptor*>(location.get(),site));
114             }
115         }
116         
117         // SAML 2.0?
118         if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
119             // Hash the ID.
120             m_sources.insert(
121                 pair<string,const EntityDescriptor*>(SAMLConfig::getConfig().hashSHA1(id.get(), true),site)
122                 );
123         }
124     }
125 }
126
127 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil)
128 {
129     if (validUntil < group->getValidUntilEpoch())
130         group->setValidUntil(validUntil);
131
132     auto_ptr_char name(group->getName());
133     if (name.get()) {
134         m_groups.insert(make_pair(name.get(),group));
135     }
136     
137     const vector<EntitiesDescriptor*>& groups=const_cast<const EntitiesDescriptor*>(group)->getEntitiesDescriptors();
138     for (vector<EntitiesDescriptor*>::const_iterator i=groups.begin(); i!=groups.end(); i++)
139         index(*i,group->getValidUntilEpoch());
140
141     const vector<EntityDescriptor*>& sites=const_cast<const EntitiesDescriptor*>(group)->getEntityDescriptors();
142     for (vector<EntityDescriptor*>::const_iterator j=sites.begin(); j!=sites.end(); j++)
143         index(*j,group->getValidUntilEpoch());
144 }
145
146 void AbstractMetadataProvider::clearDescriptorIndex()
147 {
148     m_sources.clear();
149     m_sites.clear();
150     m_groups.clear();
151 }
152
153 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
154 {
155     pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=m_groups.equal_range(name);
156
157     time_t now=time(NULL);
158     for (groupmap_t::const_iterator i=range.first; i!=range.second; i++)
159         if (now < i->second->getValidUntilEpoch())
160             return i->second;
161     
162     if (!strict && range.first!=range.second)
163         return range.first->second;
164         
165     return NULL;
166 }
167
168 const EntityDescriptor* AbstractMetadataProvider::getEntityDescriptor(const char* name, bool strict) const
169 {
170     pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range=m_sites.equal_range(name);
171
172     time_t now=time(NULL);
173     for (sitemap_t::const_iterator i=range.first; i!=range.second; i++)
174         if (now < i->second->getValidUntilEpoch())
175             return i->second;
176     
177     if (!strict && range.first!=range.second)
178         return range.first->second;
179         
180     return NULL;
181 }
182
183 const EntityDescriptor* AbstractMetadataProvider::getEntityDescriptor(const SAMLArtifact* artifact) const
184 {
185     pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range=m_sources.equal_range(artifact->getSource());
186
187     time_t now=time(NULL);
188     for (sitemap_t::const_iterator i=range.first; i!=range.second; i++)
189         if (now < i->second->getValidUntilEpoch())
190             return i->second;
191
192     return NULL;
193 }
194
195 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
196 {
197     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
198     if (!metacrit)
199         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
200
201     Lock lock(m_credentialLock);
202     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
203
204     for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
205         if (metacrit->matches(*(*c)))
206             return *c;
207     return NULL;
208 }
209
210 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
211     vector<const Credential*>& results, const CredentialCriteria* criteria
212     ) const
213 {
214     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
215     if (!metacrit)
216         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
217
218     Lock lock(m_credentialLock);
219     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
220
221     for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
222         if (metacrit->matches(*(*c)))
223             results.push_back(*c);
224     return results.size();
225 }
226
227 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
228 {
229     credmap_t::const_iterator i = m_credentialMap.find(&role);
230     if (i!=m_credentialMap.end())
231         return i->second;
232
233     const KeyInfoResolver* resolver = m_resolver ? m_resolver : XMLToolingConfig::getConfig().getKeyInfoResolver();
234     const vector<KeyDescriptor*>& keys = role.getKeyDescriptors();
235     AbstractMetadataProvider::credmap_t::mapped_type& resolved = m_credentialMap[&role];
236     for (vector<KeyDescriptor*>::const_iterator k = keys.begin(); k!=keys.end(); ++k) {
237         if ((*k)->getKeyInfo()) {
238             auto_ptr<MetadataCredentialContext> mcc(new MetadataCredentialContext(*(*k)));
239             Credential* c = resolver->resolve(mcc.get());
240             mcc.release();
241             resolved.push_back(c);
242         }
243     }
244     return resolved;
245 }