Change license header, remove stale pkg files.
[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/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>
42
43 #if defined(OPENSAML_LOG4SHIB)
44 # include <log4shib/NDC.hh>
45 #elif defined(OPENSAML_LOG4CPP)
46 # include <log4cpp/NDC.hh>
47 #endif
48
49 using namespace opensaml::saml2md;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
52 using namespace std;
53
54 #if defined (_MSC_VER)
55     #pragma warning( push )
56     #pragma warning( disable : 4250 )
57 #endif
58
59 namespace opensaml {
60     namespace saml2md {
61
62         class SAML_DLLLOCAL XMLMetadataProvider
63             : public AbstractMetadataProvider, public DiscoverableMetadataProvider, public ReloadableXMLFile
64         {
65         public:
66             XMLMetadataProvider(const DOMElement* e);
67
68             virtual ~XMLMetadataProvider() {
69                 shutdown();
70                 delete m_object;
71             }
72
73             void init() {
74                 try {
75                     if (!m_id.empty()) {
76                         string threadid("[");
77                         threadid += m_id + ']';
78                         logging::NDC::push(threadid);
79                     }
80                     background_load();
81                     startup();
82                 }
83                 catch (...) {
84                     startup();
85                     if (!m_id.empty()) {
86                         logging::NDC::pop();
87                     }
88                     throw;
89                 }
90
91                 if (!m_id.empty()) {
92                     logging::NDC::pop();
93                 }
94             }
95
96             const XMLObject* getMetadata() const {
97                 return m_object;
98             }
99
100         protected:
101             pair<bool,DOMElement*> load(bool backup);
102             pair<bool,DOMElement*> background_load();
103
104         private:
105             using AbstractMetadataProvider::index;
106             void index(time_t& validUntil);
107             time_t computeNextRefresh();
108
109             XMLObject* m_object;
110             bool m_discoveryFeed;
111             double m_refreshDelayFactor;
112             unsigned int m_backoffFactor;
113             time_t m_minRefreshDelay,m_maxRefreshDelay,m_lastValidUntil;
114         };
115
116         MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
117         {
118             return new XMLMetadataProvider(e);
119         }
120
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);
124     };
125 };
126
127 #if defined (_MSC_VER)
128     #pragma warning( pop )
129 #endif
130
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)
138 {
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;
147             }
148         }
149
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;
153         }
154     }
155 }
156
157 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
158 {
159     if (!backup) {
160         // Lower the refresh rate in case of an error.
161         m_reloadInterval = m_minRefreshDelay;
162     }
163
164     // Call the base class to load/parse the appropriate XML resource.
165     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
166
167     // If we own it, wrap it for now.
168     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
169
170     // Unmarshall objects, binding the document.
171     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
172     docjanitor.release();
173
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())
177             );
178
179     // Preprocess the metadata (even if we schema-validated).
180     try {
181         SchemaValidators.validate(xmlObject.get());
182     }
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.");
186     }
187
188     // This is the best place to take a backup, since it's superficially "correct" metadata.
189     string backupKey;
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());
195         try {
196             ofstream backer(backupKey.c_str());
197             backer << *(raw.second->getOwnerDocument());
198         }
199         catch (exception& ex) {
200             m_log.crit("exception while backing up metadata: %s", ex.what());
201             backupKey.erase();
202         }
203     }
204
205     try {
206         doFilters(*xmlObject.get());
207     }
208     catch (exception&) {
209         if (!backupKey.empty())
210             remove(backupKey.c_str());
211         throw;
212     }
213
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");
220         preserveCacheTag();
221     }
222
223     xmlObject->releaseThisAndChildrenDOM();
224     xmlObject->setDocument(nullptr);
225
226     // Swap it in after acquiring write lock if necessary.
227     if (m_lock)
228         m_lock->wrlock();
229     SharedLock locker(m_lock, false);
230     bool changed = m_object!=nullptr;
231     delete m_object;
232     m_object = xmlObject.release();
233     m_lastValidUntil = SAMLTIME_MAX;
234     index(m_lastValidUntil);
235     if (m_discoveryFeed)
236         generateFeed();
237     if (changed)
238         emitChangeEvent();
239
240     // Tracking cacheUntil through the tree is TBD, but
241     // validUntil is the tightest interval amongst the children.
242
243     // If a remote resource that's monitored, adjust the reload interval.
244     if (!backup && !m_local && m_lock) {
245         m_backoffFactor = 1;
246         m_reloadInterval = computeNextRefresh();
247         m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
248     }
249
250     m_loaded = true;
251     return make_pair(false,(DOMElement*)nullptr);
252 }
253
254 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
255 {
256     try {
257         return load(false);
258     }
259     catch (long& ex) {
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);
264         }
265         else {
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);
271         }
272         if (!m_loaded && !m_backing.empty())
273             return load(true);
274         throw;
275     }
276     catch (exception&) {
277         if (!m_local) {
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())
283                 return load(true);
284         }
285         throw;
286     }
287 }
288
289 time_t XMLMetadataProvider::computeNextRefresh()
290 {
291     time_t now = time(nullptr);
292
293     // If some or all of the metadata is already expired, reload after the minimum.
294     if (m_lastValidUntil < now) {
295         return m_minRefreshDelay;
296     }
297     else {
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());
303             
304         // Adjust for the delay factor.
305         ret *= m_refreshDelayFactor;
306
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;
312
313         return ret;
314     }
315 }
316
317 void XMLMetadataProvider::index(time_t& validUntil)
318 {
319     clearDescriptorIndex();
320     EntitiesDescriptor* group=dynamic_cast<EntitiesDescriptor*>(m_object);
321     if (group) {
322         indexGroup(group, validUntil);
323         return;
324     }
325     indexEntity(dynamic_cast<EntityDescriptor*>(m_object), validUntil);
326 }