c26b74859a7aeddbae65cdc40711b16c7dfc08a2
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / XMLMetadataProvider.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * XMLMetadataProvider.cpp
23  *
24  * Supplies metadata from an XML file
25  */
26
27 #include "internal.h"
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"
33
34 #include <fstream>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/io/HTTPResponse.h>
37 #include <xmltooling/util/DateTime.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/PathResolver.h>
40 #include <xmltooling/util/ReloadableXMLFile.h>
41 #include <xmltooling/util/Threads.h>
42 #include <xmltooling/validation/ValidatorSuite.h>
43
44 #if defined(OPENSAML_LOG4SHIB)
45 # include <log4shib/NDC.hh>
46 #elif defined(OPENSAML_LOG4CPP)
47 # include <log4cpp/NDC.hh>
48 #endif
49
50 using namespace opensaml::saml2md;
51 using namespace xmltooling::logging;
52 using namespace xmltooling;
53 using namespace boost;
54 using namespace std;
55
56 #if defined (_MSC_VER)
57     #pragma warning( push )
58     #pragma warning( disable : 4250 )
59 #endif
60
61 namespace opensaml {
62     namespace saml2md {
63
64         class SAML_DLLLOCAL XMLMetadataProvider
65             : public AbstractMetadataProvider, public DiscoverableMetadataProvider, public ReloadableXMLFile
66         {
67         public:
68             XMLMetadataProvider(const DOMElement* e);
69
70             virtual ~XMLMetadataProvider() {
71                 shutdown();
72             }
73
74             void init() {
75                 try {
76                     if (!m_id.empty()) {
77                         string threadid("[");
78                         threadid += m_id + ']';
79                         logging::NDC::push(threadid);
80                     }
81                     background_load();
82                     startup();
83                 }
84                 catch (...) {
85                     startup();
86                     if (!m_id.empty()) {
87                         logging::NDC::pop();
88                     }
89                     throw;
90                 }
91
92                 if (!m_id.empty()) {
93                     logging::NDC::pop();
94                 }
95             }
96
97             const char* getId() const {
98                 return m_id.c_str();
99             }
100
101             void outputStatus(ostream& os) const {
102                 os << "<MetadataProvider";
103
104                 if (getId() && *getId()) {
105                     os << " id='" << getId() << "'";
106                 }
107
108                 if (!m_source.empty()) {
109                     os << " source='" << m_source << "'";
110                 }
111
112                 if (m_lastUpdate > 0) {
113                     DateTime ts(m_lastUpdate);
114                     ts.parseDateTime();
115                     auto_ptr_char timestamp(ts.getFormattedString());
116                     os << " lastUpdate='" << timestamp.get() << "'";
117                 }
118
119                 if (!m_local && m_reloadInterval > 0) {
120                     os << " reloadInterval='" << m_reloadInterval << "'";
121                 }
122
123                 os << "/>";
124             }
125
126             const XMLObject* getMetadata() const {
127                 return m_object.get();
128             }
129
130         protected:
131             pair<bool,DOMElement*> load(bool backup);
132             pair<bool,DOMElement*> background_load();
133
134         private:
135             using AbstractMetadataProvider::index;
136             void index(time_t& validUntil);
137             time_t computeNextRefresh();
138
139             scoped_ptr<XMLObject> m_object;
140             bool m_discoveryFeed,m_dropDOM;
141             double m_refreshDelayFactor;
142             unsigned int m_backoffFactor;
143             time_t m_minRefreshDelay,m_maxRefreshDelay,m_lastValidUntil;
144         };
145
146         MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
147         {
148             return new XMLMetadataProvider(e);
149         }
150
151         static const XMLCh discoveryFeed[] =        UNICODE_LITERAL_13(d,i,s,c,o,v,e,r,y,F,e,e,d);
152         static const XMLCh dropDOM[] =              UNICODE_LITERAL_7(d,r,o,p,D,O,M);
153         static const XMLCh minRefreshDelay[] =      UNICODE_LITERAL_15(m,i,n,R,e,f,r,e,s,h,D,e,l,a,y);
154         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);
155     };
156 };
157
158 #if defined (_MSC_VER)
159     #pragma warning( pop )
160 #endif
161
162 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
163     : MetadataProvider(e), AbstractMetadataProvider(e), DiscoverableMetadataProvider(e),
164         ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
165         m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
166         m_dropDOM(XMLHelper::getAttrBool(e, true, dropDOM)),
167         m_refreshDelayFactor(0.75), m_backoffFactor(1),
168         m_minRefreshDelay(XMLHelper::getAttrInt(e, 600, minRefreshDelay)),
169         m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
170 {
171     if (!m_local && m_maxRefreshDelay) {
172         const XMLCh* setting = e->getAttributeNS(nullptr, refreshDelayFactor);
173         if (setting && *setting) {
174             auto_ptr_char delay(setting);
175             m_refreshDelayFactor = atof(delay.get());
176             if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
177                 m_log.error("invalid refreshDelayFactor setting, using default");
178                 m_refreshDelayFactor = 0.75;
179             }
180         }
181
182         if (m_minRefreshDelay > m_maxRefreshDelay) {
183             m_log.warn("minRefreshDelay setting exceeds maxRefreshDelay/reloadInterval setting, lowering to match it");
184             m_minRefreshDelay = m_maxRefreshDelay;
185         }
186     }
187 }
188
189 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
190 {
191     if (!backup) {
192         // Lower the refresh rate in case of an error.
193         m_reloadInterval = m_minRefreshDelay;
194     }
195
196     // Call the base class to load/parse the appropriate XML resource.
197     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
198
199     // If we own it, wrap it for now.
200     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
201
202     // Unmarshall objects, binding the document.
203     scoped_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
204     docjanitor.release();
205
206     if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
207         throw MetadataException(
208             "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
209             );
210
211     // Preprocess the metadata (even if we schema-validated).
212     try {
213         SchemaValidators.validate(xmlObject.get());
214     }
215     catch (std::exception& ex) {
216         m_log.error("metadata instance failed manual validation checking: %s", ex.what());
217         throw MetadataException("Metadata instance failed manual validation checking.");
218     }
219
220     const TimeBoundSAMLObject* validityCheck = dynamic_cast<TimeBoundSAMLObject*>(xmlObject.get());
221     if (!validityCheck || !validityCheck->isValid()) {
222         m_log.error("metadata instance was invalid at time of acquisition");
223         throw MetadataException("Metadata instance was invalid at time of acquisition.");
224     }
225
226     // This is the best place to take a backup, since it's superficially "correct" metadata.
227     string backupKey;
228     if (!backup && !m_backing.empty()) {
229         // We compute a random filename extension to the "real" location.
230         SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
231         backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
232         m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
233         try {
234             ofstream backer(backupKey.c_str());
235             backer << *(raw.second->getOwnerDocument());
236         }
237         catch (std::exception& ex) {
238             m_log.crit("exception while backing up metadata: %s", ex.what());
239             backupKey.erase();
240         }
241     }
242
243     try {
244         doFilters(*xmlObject);
245     }
246     catch (std::exception&) {
247         if (!backupKey.empty())
248             remove(backupKey.c_str());
249         throw;
250     }
251
252     if (!backupKey.empty()) {
253         m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
254         Locker locker(getBackupLock());
255         remove(m_backing.c_str());
256         if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
257             m_log.crit("unable to rename metadata backup file");
258         preserveCacheTag();
259     }
260
261     if (m_dropDOM) {
262         xmlObject->releaseThisAndChildrenDOM();
263         xmlObject->setDocument(nullptr);
264     }
265
266     // Swap it in after acquiring write lock if necessary.
267     if (m_lock)
268         m_lock->wrlock();
269     SharedLock locker(m_lock, false);
270     bool changed = m_object!=nullptr;
271     m_object.swap(xmlObject);
272     m_lastValidUntil = SAMLTIME_MAX;
273     index(m_lastValidUntil);
274     if (m_discoveryFeed)
275         generateFeed();
276     if (changed)
277         emitChangeEvent();
278     m_lastUpdate = time(nullptr);
279
280     // Tracking cacheUntil through the tree is TBD, but
281     // validUntil is the tightest interval amongst the children.
282
283     // If a remote resource that's monitored, adjust the reload interval.
284     if (!backup && !m_local && m_lock) {
285         m_backoffFactor = 1;
286         m_reloadInterval = computeNextRefresh();
287         m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
288     }
289
290     m_loaded = true;
291     return make_pair(false,(DOMElement*)nullptr);
292 }
293
294 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
295 {
296     try {
297         return load(false);
298     }
299     catch (long& ex) {
300         if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
301             // Unchanged document, so re-establish previous refresh interval.
302             m_reloadInterval = computeNextRefresh();
303             m_log.info("remote resource (%s) unchanged, adjusted reload interval to %u seconds", m_source.c_str(), m_reloadInterval);
304         }
305         else {
306             // Any other status code, just treat as an error.
307             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
308             if (m_reloadInterval > m_maxRefreshDelay)
309                 m_reloadInterval = m_maxRefreshDelay;
310             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
311         }
312         if (!m_loaded && !m_backing.empty())
313             return load(true);
314         throw;
315     }
316     catch (std::exception& ex) {
317         if (!m_local) {
318             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
319             if (m_reloadInterval > m_maxRefreshDelay)
320                 m_reloadInterval = m_maxRefreshDelay;
321             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
322             if (!m_loaded && !m_backing.empty()) {
323                 m_log.warn("trying backup file, exception loading remote resource: %s", ex.what());
324                 return load(true);
325             }
326         }
327         throw;
328     }
329 }
330
331 time_t XMLMetadataProvider::computeNextRefresh()
332 {
333     time_t now = time(nullptr);
334
335     // If some or all of the metadata is already expired, reload after the minimum.
336     if (m_lastValidUntil < now) {
337         return m_minRefreshDelay;
338     }
339     else {
340         // Compute the smaller of the validUntil / cacheDuration constraints.
341         time_t ret = m_lastValidUntil - now;
342         const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object.get());
343         if (cacheable && cacheable->getCacheDuration())
344             ret = min(ret, cacheable->getCacheDurationEpoch());
345             
346         // Adjust for the delay factor.
347         ret *= m_refreshDelayFactor;
348
349         // Bound by max and min.
350         if (ret > m_maxRefreshDelay)
351             return m_maxRefreshDelay;
352         else if (ret < m_minRefreshDelay)
353             return m_minRefreshDelay;
354
355         return ret;
356     }
357 }
358
359 void XMLMetadataProvider::index(time_t& validUntil)
360 {
361     clearDescriptorIndex();
362     EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(m_object.get());
363     if (group) {
364         indexGroup(group, validUntil);
365         return;
366     }
367     indexEntity(dynamic_cast<EntityDescriptor*>(m_object.get()), validUntil);
368 }