2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * XMLMetadataProvider.cpp
24 * Supplies metadata from an XML file
28 #include "binding/SAMLArtifact.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/MetadataFilter.h"
31 #include "saml2/metadata/AbstractMetadataProvider.h"
32 #include "saml2/metadata/DiscoverableMetadataProvider.h"
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/io/HTTPResponse.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/ReloadableXMLFile.h>
40 #include <xmltooling/util/Threads.h>
41 #include <xmltooling/validation/ValidatorSuite.h>
43 #if defined(OPENSAML_LOG4SHIB)
44 # include <log4shib/NDC.hh>
45 #elif defined(OPENSAML_LOG4CPP)
46 # include <log4cpp/NDC.hh>
49 using namespace opensaml::saml2md;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
62 class SAML_DLLLOCAL XMLMetadataProvider
63 : public AbstractMetadataProvider, public DiscoverableMetadataProvider, public ReloadableXMLFile
66 XMLMetadataProvider(const DOMElement* e);
68 virtual ~XMLMetadataProvider() {
77 threadid += m_id + ']';
78 logging::NDC::push(threadid);
96 const XMLObject* getMetadata() const {
101 pair<bool,DOMElement*> load(bool backup);
102 pair<bool,DOMElement*> background_load();
105 using AbstractMetadataProvider::index;
106 void index(time_t& validUntil);
107 time_t computeNextRefresh();
110 bool m_discoveryFeed;
111 double m_refreshDelayFactor;
112 unsigned int m_backoffFactor;
113 time_t m_minRefreshDelay,m_maxRefreshDelay,m_lastValidUntil;
116 MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
118 return new XMLMetadataProvider(e);
121 static const XMLCh discoveryFeed[] = UNICODE_LITERAL_13(d,i,s,c,o,v,e,r,y,F,e,e,d);
122 static const XMLCh minRefreshDelay[] = UNICODE_LITERAL_15(m,i,n,R,e,f,r,e,s,h,D,e,l,a,y);
123 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);
127 #if defined (_MSC_VER)
128 #pragma warning( pop )
131 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
132 : MetadataProvider(e), AbstractMetadataProvider(e), DiscoverableMetadataProvider(e),
133 ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
134 m_object(nullptr), m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
135 m_refreshDelayFactor(0.75), m_backoffFactor(1),
136 m_minRefreshDelay(XMLHelper::getAttrInt(e, 600, minRefreshDelay)),
137 m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
139 if (!m_local && m_maxRefreshDelay) {
140 const XMLCh* setting = e->getAttributeNS(nullptr, refreshDelayFactor);
141 if (setting && *setting) {
142 auto_ptr_char delay(setting);
143 m_refreshDelayFactor = atof(delay.get());
144 if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
145 m_log.error("invalid refreshDelayFactor setting, using default");
146 m_refreshDelayFactor = 0.75;
150 if (m_minRefreshDelay > m_maxRefreshDelay) {
151 m_log.warn("minRefreshDelay setting exceeds maxRefreshDelay/reloadInterval setting, lowering to match it");
152 m_minRefreshDelay = m_maxRefreshDelay;
157 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
160 // Lower the refresh rate in case of an error.
161 m_reloadInterval = m_minRefreshDelay;
164 // Call the base class to load/parse the appropriate XML resource.
165 pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
167 // If we own it, wrap it for now.
168 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
170 // Unmarshall objects, binding the document.
171 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
172 docjanitor.release();
174 if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
175 throw MetadataException(
176 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
179 // Preprocess the metadata (even if we schema-validated).
181 SchemaValidators.validate(xmlObject.get());
183 catch (exception& ex) {
184 m_log.error("metadata intance failed manual validation checking: %s", ex.what());
185 throw MetadataException("Metadata instance failed manual validation checking.");
188 // This is the best place to take a backup, since it's superficially "correct" metadata.
190 if (!backup && !m_backing.empty()) {
191 // We compute a random filename extension to the "real" location.
192 SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
193 backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
194 m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
196 ofstream backer(backupKey.c_str());
197 backer << *(raw.second->getOwnerDocument());
199 catch (exception& ex) {
200 m_log.crit("exception while backing up metadata: %s", ex.what());
206 doFilters(*xmlObject.get());
209 if (!backupKey.empty())
210 remove(backupKey.c_str());
214 if (!backupKey.empty()) {
215 m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
216 Locker locker(getBackupLock());
217 remove(m_backing.c_str());
218 if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
219 m_log.crit("unable to rename metadata backup file");
223 xmlObject->releaseThisAndChildrenDOM();
224 xmlObject->setDocument(nullptr);
226 // Swap it in after acquiring write lock if necessary.
229 SharedLock locker(m_lock, false);
230 bool changed = m_object!=nullptr;
232 m_object = xmlObject.release();
233 m_lastValidUntil = SAMLTIME_MAX;
234 index(m_lastValidUntil);
240 // Tracking cacheUntil through the tree is TBD, but
241 // validUntil is the tightest interval amongst the children.
243 // If a remote resource that's monitored, adjust the reload interval.
244 if (!backup && !m_local && m_lock) {
246 m_reloadInterval = computeNextRefresh();
247 m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
251 return make_pair(false,(DOMElement*)nullptr);
254 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
260 if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
261 // Unchanged document, so re-establish previous refresh interval.
262 m_reloadInterval = computeNextRefresh();
263 m_log.info("remote resource (%s) unchanged, adjusted reload interval to %u seconds", m_source.c_str(), m_reloadInterval);
266 // Any other status code, just treat as an error.
267 m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
268 if (m_reloadInterval > m_maxRefreshDelay)
269 m_reloadInterval = m_maxRefreshDelay;
270 m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
272 if (!m_loaded && !m_backing.empty())
278 m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
279 if (m_reloadInterval > m_maxRefreshDelay)
280 m_reloadInterval = m_maxRefreshDelay;
281 m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
282 if (!m_loaded && !m_backing.empty())
289 time_t XMLMetadataProvider::computeNextRefresh()
291 time_t now = time(nullptr);
293 // If some or all of the metadata is already expired, reload after the minimum.
294 if (m_lastValidUntil < now) {
295 return m_minRefreshDelay;
298 // Compute the smaller of the validUntil / cacheDuration constraints.
299 time_t ret = m_lastValidUntil - now;
300 const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object);
301 if (cacheable && cacheable->getCacheDuration())
302 ret = min(ret, cacheable->getCacheDurationEpoch());
304 // Adjust for the delay factor.
305 ret *= m_refreshDelayFactor;
307 // Bound by max and min.
308 if (ret > m_maxRefreshDelay)
309 return m_maxRefreshDelay;
310 else if (ret < m_minRefreshDelay)
311 return m_minRefreshDelay;
317 void XMLMetadataProvider::index(time_t& validUntil)
319 clearDescriptorIndex();
320 EntitiesDescriptor* group=dynamic_cast<EntitiesDescriptor*>(m_object);
322 indexGroup(group, validUntil);
325 indexEntity(dynamic_cast<EntityDescriptor*>(m_object), validUntil);