2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * XMLMetadataProvider.cpp
20 * Supplies metadata from an XML file
24 #include "binding/SAMLArtifact.h"
25 #include "saml2/metadata/Metadata.h"
26 #include "saml2/metadata/MetadataFilter.h"
27 #include "saml2/metadata/AbstractMetadataProvider.h"
30 #include <xmltooling/io/HTTPResponse.h>
31 #include <xmltooling/util/NDC.h>
32 #include <xmltooling/util/ReloadableXMLFile.h>
33 #include <xmltooling/util/Threads.h>
34 #include <xmltooling/validation/ValidatorSuite.h>
36 using namespace opensaml::saml2md;
37 using namespace xmltooling::logging;
38 using namespace xmltooling;
41 #if defined (_MSC_VER)
42 #pragma warning( push )
43 #pragma warning( disable : 4250 )
49 static const XMLCh minRefreshDelay[] = UNICODE_LITERAL_15(m,i,n,R,e,f,r,e,s,h,D,e,l,a,y);
50 static const XMLCh refreshDelayFactor[] = UNICODE_LITERAL_18(r,e,f,r,e,s,h,D,e,l,a,y,F,a,c,t,o,r);
52 class SAML_DLLLOCAL XMLMetadataProvider : public AbstractMetadataProvider, public ReloadableXMLFile
55 XMLMetadataProvider(const DOMElement* e);
57 virtual ~XMLMetadataProvider() {
67 const XMLObject* getMetadata() const {
72 pair<bool,DOMElement*> load(bool backup);
73 pair<bool,DOMElement*> background_load();
76 using AbstractMetadataProvider::index;
77 void index(time_t& validUntil);
78 time_t computeNextRefresh();
81 double m_refreshDelayFactor;
82 unsigned int m_backoffFactor;
83 time_t m_minRefreshDelay,m_maxRefreshDelay,m_lastValidUntil;
86 MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
88 return new XMLMetadataProvider(e);
94 #if defined (_MSC_VER)
95 #pragma warning( pop )
98 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
99 : AbstractMetadataProvider(e), ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
100 m_object(nullptr), m_refreshDelayFactor(0.75), m_backoffFactor(1), m_minRefreshDelay(600),
101 m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
103 if (!m_local && m_maxRefreshDelay) {
104 const XMLCh* setting = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : NULL;
105 if (setting && *setting) {
106 auto_ptr_char delay(setting);
107 m_refreshDelayFactor = atof(delay.get());
108 if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
109 m_log.error("invalid refreshDelayFactor setting, using default");
110 m_refreshDelayFactor = 0.75;
113 setting = e ? e->getAttributeNS(nullptr, minRefreshDelay) : NULL;
114 if (setting && *setting) {
115 m_minRefreshDelay = XMLString::parseInt(setting);
116 if (m_minRefreshDelay == 0) {
117 m_log.error("invalid minRefreshDelay setting, using default");
118 m_minRefreshDelay = 600;
120 else if (m_minRefreshDelay > m_maxRefreshDelay) {
121 m_log.error("minRefreshDelay setting exceeds maxRefreshDelay/refreshInterval setting, lowering to match it");
122 m_minRefreshDelay = m_maxRefreshDelay;
128 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
130 // Lower the refresh rate in case of an error.
131 m_reloadInterval = m_minRefreshDelay;
133 // Call the base class to load/parse the appropriate XML resource.
134 pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
136 // If we own it, wrap it for now.
137 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
139 // Unmarshall objects, binding the document.
140 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
141 docjanitor.release();
143 if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
144 throw MetadataException(
145 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
148 // Preprocess the metadata (even if we schema-validated).
150 SchemaValidators.validate(xmlObject.get());
152 catch (exception& ex) {
153 m_log.error("metadata intance failed manual validation checking: %s", ex.what());
154 throw MetadataException("Metadata instance failed manual validation checking.");
157 // This is the best place to take a backup, since it's superficially "correct" metadata.
159 if (!backup && !m_backing.empty()) {
160 // We compute a random filename extension to the "real" location.
161 SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
162 backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
163 m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
165 ofstream backer(backupKey.c_str());
166 backer << *(raw.second->getOwnerDocument());
168 catch (exception& ex) {
169 m_log.crit("exception while backing up metadata: %s", ex.what());
175 doFilters(*xmlObject.get());
178 if (!backupKey.empty())
179 remove(backupKey.c_str());
183 if (!backupKey.empty()) {
184 m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
185 Locker locker(getBackupLock());
186 remove(m_backing.c_str());
187 if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
188 m_log.crit("unable to rename metadata backup file");
192 xmlObject->releaseThisAndChildrenDOM();
193 xmlObject->setDocument(nullptr);
195 // Swap it in after acquiring write lock if necessary.
198 SharedLock locker(m_lock, false);
199 bool changed = m_object!=nullptr;
201 m_object = xmlObject.release();
202 m_lastValidUntil = SAMLTIME_MAX;
203 index(m_lastValidUntil);
207 // Tracking cacheUntil through the tree is TBD, but
208 // validUntil is the tightest interval amongst the children.
210 // If a remote resource, adjust the reload interval.
211 if (!backup && !m_local) {
213 m_reloadInterval = computeNextRefresh();
214 m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
218 return make_pair(false,(DOMElement*)nullptr);
221 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
227 if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
228 // Unchanged document, so re-establish previous refresh interval.
229 m_reloadInterval = computeNextRefresh();
230 m_log.info("remote resource (%s) unchanged, adjusted reload interval to %u seconds", m_source.c_str(), m_reloadInterval);
233 // Any other status code, just treat as an error.
234 m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
235 if (m_reloadInterval > m_maxRefreshDelay)
236 m_reloadInterval = m_maxRefreshDelay;
237 m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
239 if (!m_loaded && !m_backing.empty())
245 m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
246 if (m_reloadInterval > m_maxRefreshDelay)
247 m_reloadInterval = m_maxRefreshDelay;
248 m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
249 if (!m_loaded && !m_backing.empty())
256 void XMLMetadataProvider::index(time_t& validUntil)
258 clearDescriptorIndex();
259 EntitiesDescriptor* group=dynamic_cast<EntitiesDescriptor*>(m_object);
261 indexGroup(group, validUntil);
264 indexEntity(dynamic_cast<EntityDescriptor*>(m_object), validUntil);
267 time_t XMLMetadataProvider::computeNextRefresh()
269 time_t now = time(nullptr);
271 // If some or all of the metadata is already expired, reload after the minimum.
272 if (m_lastValidUntil < now) {
273 return m_minRefreshDelay;
276 // Compute the smaller of the validUntil / cacheDuration constraints.
277 time_t ret = m_lastValidUntil - now;
278 const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object);
279 if (cacheable && cacheable->getCacheDuration())
280 ret = min(ret, cacheable->getCacheDurationEpoch());
282 // Adjust for the delay factor.
283 ret *= m_refreshDelayFactor;
285 // Bound by max and min.
286 if (ret > m_maxRefreshDelay)
287 return m_maxRefreshDelay;
288 else if (ret < m_minRefreshDelay)
289 return m_minRefreshDelay;