19730baf1cba913fc4046534ce3180930655594f
[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;
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 minRefreshDelay[] =      UNICODE_LITERAL_15(m,i,n,R,e,f,r,e,s,h,D,e,l,a,y);
153         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);
154     };
155 };
156
157 #if defined (_MSC_VER)
158     #pragma warning( pop )
159 #endif
160
161 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
162     : MetadataProvider(e), AbstractMetadataProvider(e), DiscoverableMetadataProvider(e),
163         ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
164         m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
165         m_refreshDelayFactor(0.75), m_backoffFactor(1),
166         m_minRefreshDelay(XMLHelper::getAttrInt(e, 600, minRefreshDelay)),
167         m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
168 {
169     if (!m_local && m_maxRefreshDelay) {
170         const XMLCh* setting = e->getAttributeNS(nullptr, refreshDelayFactor);
171         if (setting && *setting) {
172             auto_ptr_char delay(setting);
173             m_refreshDelayFactor = atof(delay.get());
174             if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
175                 m_log.error("invalid refreshDelayFactor setting, using default");
176                 m_refreshDelayFactor = 0.75;
177             }
178         }
179
180         if (m_minRefreshDelay > m_maxRefreshDelay) {
181             m_log.warn("minRefreshDelay setting exceeds maxRefreshDelay/reloadInterval setting, lowering to match it");
182             m_minRefreshDelay = m_maxRefreshDelay;
183         }
184     }
185 }
186
187 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
188 {
189     if (!backup) {
190         // Lower the refresh rate in case of an error.
191         m_reloadInterval = m_minRefreshDelay;
192     }
193
194     // Call the base class to load/parse the appropriate XML resource.
195     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
196
197     // If we own it, wrap it for now.
198     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
199
200     // Unmarshall objects, binding the document.
201     scoped_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
202     docjanitor.release();
203
204     if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
205         throw MetadataException(
206             "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
207             );
208
209     // Preprocess the metadata (even if we schema-validated).
210     try {
211         SchemaValidators.validate(xmlObject.get());
212     }
213     catch (exception& ex) {
214         m_log.error("metadata intance failed manual validation checking: %s", ex.what());
215         throw MetadataException("Metadata instance failed manual validation checking.");
216     }
217
218     // This is the best place to take a backup, since it's superficially "correct" metadata.
219     string backupKey;
220     if (!backup && !m_backing.empty()) {
221         // We compute a random filename extension to the "real" location.
222         SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
223         backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
224         m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
225         try {
226             ofstream backer(backupKey.c_str());
227             backer << *(raw.second->getOwnerDocument());
228         }
229         catch (exception& ex) {
230             m_log.crit("exception while backing up metadata: %s", ex.what());
231             backupKey.erase();
232         }
233     }
234
235     try {
236         doFilters(*xmlObject);
237     }
238     catch (exception&) {
239         if (!backupKey.empty())
240             remove(backupKey.c_str());
241         throw;
242     }
243
244     if (!backupKey.empty()) {
245         m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
246         Locker locker(getBackupLock());
247         remove(m_backing.c_str());
248         if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
249             m_log.crit("unable to rename metadata backup file");
250         preserveCacheTag();
251     }
252
253     xmlObject->releaseThisAndChildrenDOM();
254     xmlObject->setDocument(nullptr);
255
256     // Swap it in after acquiring write lock if necessary.
257     if (m_lock)
258         m_lock->wrlock();
259     SharedLock locker(m_lock, false);
260     bool changed = m_object!=nullptr;
261     m_object.swap(xmlObject);
262     m_lastValidUntil = SAMLTIME_MAX;
263     index(m_lastValidUntil);
264     if (m_discoveryFeed)
265         generateFeed();
266     if (changed)
267         emitChangeEvent();
268     m_lastUpdate = time(nullptr);
269
270     // Tracking cacheUntil through the tree is TBD, but
271     // validUntil is the tightest interval amongst the children.
272
273     // If a remote resource that's monitored, adjust the reload interval.
274     if (!backup && !m_local && m_lock) {
275         m_backoffFactor = 1;
276         m_reloadInterval = computeNextRefresh();
277         m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
278     }
279
280     m_loaded = true;
281     return make_pair(false,(DOMElement*)nullptr);
282 }
283
284 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
285 {
286     try {
287         return load(false);
288     }
289     catch (long& ex) {
290         if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
291             // Unchanged document, so re-establish previous refresh interval.
292             m_reloadInterval = computeNextRefresh();
293             m_log.info("remote resource (%s) unchanged, adjusted reload interval to %u seconds", m_source.c_str(), m_reloadInterval);
294         }
295         else {
296             // Any other status code, just treat as an error.
297             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
298             if (m_reloadInterval > m_maxRefreshDelay)
299                 m_reloadInterval = m_maxRefreshDelay;
300             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
301         }
302         if (!m_loaded && !m_backing.empty())
303             return load(true);
304         throw;
305     }
306     catch (exception&) {
307         if (!m_local) {
308             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
309             if (m_reloadInterval > m_maxRefreshDelay)
310                 m_reloadInterval = m_maxRefreshDelay;
311             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
312             if (!m_loaded && !m_backing.empty())
313                 return load(true);
314         }
315         throw;
316     }
317 }
318
319 time_t XMLMetadataProvider::computeNextRefresh()
320 {
321     time_t now = time(nullptr);
322
323     // If some or all of the metadata is already expired, reload after the minimum.
324     if (m_lastValidUntil < now) {
325         return m_minRefreshDelay;
326     }
327     else {
328         // Compute the smaller of the validUntil / cacheDuration constraints.
329         time_t ret = m_lastValidUntil - now;
330         const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object.get());
331         if (cacheable && cacheable->getCacheDuration())
332             ret = min(ret, cacheable->getCacheDurationEpoch());
333             
334         // Adjust for the delay factor.
335         ret *= m_refreshDelayFactor;
336
337         // Bound by max and min.
338         if (ret > m_maxRefreshDelay)
339             return m_maxRefreshDelay;
340         else if (ret < m_minRefreshDelay)
341             return m_minRefreshDelay;
342
343         return ret;
344     }
345 }
346
347 void XMLMetadataProvider::index(time_t& validUntil)
348 {
349     clearDescriptorIndex();
350     EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(m_object.get());
351     if (group) {
352         indexGroup(group, validUntil);
353         return;
354     }
355     indexEntity(dynamic_cast<EntityDescriptor*>(m_object.get()), validUntil);
356 }