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