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