Bump library version.
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / DynamicMetadataProvider.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  * DynamicMetadataProvider.cpp
19  *
20  * Simple implementation of a dynamic caching MetadataProvider.
21  */
22
23 #include "internal.h"
24 #include "binding/SAMLArtifact.h"
25 #include "saml2/metadata/Metadata.h"
26 #include "saml2/metadata/DynamicMetadataProvider.h"
27
28 #include <xercesc/framework/Wrapper4InputSource.hpp>
29 #include <xercesc/framework/URLInputSource.hpp>
30 #include <xercesc/util/XMLUniDefs.hpp>
31 #include <xmltooling/logging.h>
32 #include <xmltooling/util/XMLHelper.h>
33
34 using namespace opensaml::saml2md;
35 using namespace xmltooling::logging;
36 using namespace xmltooling;
37 using namespace std;
38
39 # ifndef min
40 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
41 # endif
42
43 static const XMLCh maxCacheDuration[] = UNICODE_LITERAL_16(m,a,x,C,a,c,h,e,D,u,r,a,t,i,o,n);
44 static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
45
46 namespace opensaml {
47     namespace saml2md {
48         MetadataProvider* SAML_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
49         {
50             return new DynamicMetadataProvider(e);
51         }
52     };
53 };
54
55 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
56     : AbstractMetadataProvider(e), m_maxCacheDuration(28800), m_lock(RWLock::create())
57 {
58     const XMLCh* flag=e ? e->getAttributeNS(NULL,validate) : NULL;
59     m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));
60     flag = e ? e->getAttributeNS(NULL,maxCacheDuration) : NULL;
61     if (flag && *flag) {
62         m_maxCacheDuration = XMLString::parseInt(flag);
63         if (m_maxCacheDuration == 0)
64             m_maxCacheDuration = 28800;
65     }
66 }
67
68 DynamicMetadataProvider::~DynamicMetadataProvider()
69 {
70     // Each entity in the map is unique (no multimap semantics), so this is safe.
71     clearDescriptorIndex(true);
72     delete m_lock;
73 }
74
75 pair<const EntityDescriptor*,const RoleDescriptor*> DynamicMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
76 {
77     // Check cache while holding the read lock.
78     pair<const EntityDescriptor*,const RoleDescriptor*> entity = AbstractMetadataProvider::getEntityDescriptor(criteria);
79     if (entity.first)   // even if the role isn't found, we're done
80         return entity;
81
82     string name;
83     if (criteria.entityID_ascii)
84         name = criteria.entityID_ascii;
85     else if (criteria.entityID_unicode) {
86         auto_ptr_char temp(criteria.entityID_unicode);
87         name = temp.get();
88     }
89     else if (criteria.artifact)
90         name = criteria.artifact->getSource();
91     else
92         return entity;
93
94     Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic");
95     log.info("resolving metadata for (%s)", name.c_str());
96
97     try {
98         // Try resolving it.
99         auto_ptr<EntityDescriptor> entity2(resolve(criteria));
100
101         // Verify the entityID.
102         if (criteria.entityID_unicode && !XMLString::equals(criteria.entityID_unicode, entity2->getEntityID())) {
103             Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error("metadata instance did not match expected entityID");
104             return entity;
105         }
106         else {
107             auto_ptr_XMLCh temp2(name.c_str());
108             if (!XMLString::equals(temp2.get(), entity2->getEntityID())) {
109                 Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error("metadata instance did not match expected entityID");
110                 return entity;
111             }
112         }
113
114         // Filter it, which may throw.
115         doFilters(*entity2.get());
116
117         log.info("caching resolved metadata for (%s)", name.c_str());
118
119         // Translate cacheDuration into validUntil.
120         time_t exp = m_maxCacheDuration;
121         if (entity2->getCacheDuration())
122             exp = min(m_maxCacheDuration, entity2->getCacheDurationEpoch());
123         exp += time(NULL);
124         if (entity2->getValidUntil()) {
125             if (exp < entity2->getValidUntilEpoch())
126                 entity2->setValidUntil(exp);
127         }
128         else {
129             entity2->setValidUntil(exp);
130         }
131
132         // Upgrade our lock so we can cache the new metadata.
133         m_lock->unlock();
134         m_lock->wrlock();
135
136         // Notify observers.
137         emitChangeEvent();
138
139         // Make sure we clear out any existing copies, including stale metadata or if somebody snuck in.
140         index(entity2.release(), SAMLTIME_MAX, true);
141
142         // Downgrade back to a read lock.
143         m_lock->unlock();
144         m_lock->rdlock();
145     }
146     catch (exception& e) {
147         Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(
148             "error while resolving entityID (%s): %s", name.c_str(), e.what()
149             );
150         return entity;
151     }
152
153     // Rinse and repeat.
154     return getEntityDescriptor(criteria);
155 }
156
157 EntityDescriptor* DynamicMetadataProvider::resolve(const Criteria& criteria) const
158 {
159     string name;
160     if (criteria.entityID_ascii)
161         name = criteria.entityID_ascii;
162     else if (criteria.entityID_unicode) {
163         auto_ptr_char temp(criteria.entityID_unicode);
164         name = temp.get();
165     }
166     else if (criteria.artifact)
167         name = criteria.artifact->getSource();
168
169     try {
170         DOMDocument* doc=NULL;
171         auto_ptr_XMLCh widenit(name.c_str());
172         URLInputSource src(widenit.get());
173         Wrapper4InputSource dsrc(&src,false);
174         if (m_validate)
175             doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
176         else
177             doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
178
179         // Wrap the document for now.
180         XercesJanitor<DOMDocument> docjanitor(doc);
181
182         // Unmarshall objects, binding the document.
183         auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
184         docjanitor.release();
185
186         // Make sure it's metadata.
187         EntityDescriptor* entity = dynamic_cast<EntityDescriptor*>(xmlObject.get());
188         if (!entity) {
189             throw MetadataException(
190                 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
191                 );
192         }
193         xmlObject.release();
194         return entity;
195     }
196     catch (XMLException& e) {
197         auto_ptr_char msg(e.getMessage());
198         Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(
199             "Xerces error while resolving entityID (%s): %s", name.c_str(), msg.get()
200             );
201         throw MetadataException(msg.get());
202     }
203 }