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