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