SSPCPP-616 - clean up concatenated string literals
[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
76             const char* getId() const {
77                 return m_id.c_str();
78             }
79
80             void outputStatus(ostream& os) const;
81
82             const XMLObject* getMetadata() const {
83                 return m_object.get();
84             }
85
86         protected:
87             pair<bool,DOMElement*> load(bool backup);
88             pair<bool,DOMElement*> background_load();
89
90         private:
91             using AbstractMetadataProvider::index;
92             void index(time_t& validUntil);
93             time_t computeNextRefresh();
94
95             scoped_ptr<XMLObject> m_object;
96             bool m_discoveryFeed,m_dropDOM;
97             double m_refreshDelayFactor;
98             unsigned int m_backoffFactor;
99             time_t m_minRefreshDelay,m_maxRefreshDelay,m_lastValidUntil;
100         };
101
102         MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
103         {
104             return new XMLMetadataProvider(e);
105         }
106
107         static const XMLCh discoveryFeed[] =        UNICODE_LITERAL_13(d,i,s,c,o,v,e,r,y,F,e,e,d);
108         static const XMLCh dropDOM[] =              UNICODE_LITERAL_7(d,r,o,p,D,O,M);
109         static const XMLCh minRefreshDelay[] =      UNICODE_LITERAL_15(m,i,n,R,e,f,r,e,s,h,D,e,l,a,y);
110         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);
111
112         // TODO: need to move this into xmltooling as a utility function
113         static void xml_encode(ostream& os, const char* start)
114         {
115             size_t pos;
116             while (start && *start) {
117                 pos = strcspn(start, "\"<>&");
118                 if (pos > 0) {
119                     os.write(start,pos);
120                     start += pos;
121                 }
122                 else {
123                     switch (*start) {
124                         case '"':   os << "&quot;";     break;
125                         case '<':   os << "&lt;";       break;
126                         case '>':   os << "&gt;";       break;
127                         case '&':   os << "&amp;";      break;
128                         default:    os << *start;
129                     }
130                     start++;
131                 }
132             }
133         }
134     };
135 };
136
137 #if defined (_MSC_VER)
138     #pragma warning( pop )
139 #endif
140
141 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
142     : MetadataProvider(e), AbstractMetadataProvider(e), DiscoverableMetadataProvider(e),
143         ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT ".MetadataProvider.XML"), false),
144         m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
145         m_dropDOM(XMLHelper::getAttrBool(e, true, dropDOM)),
146         m_refreshDelayFactor(0.75), m_backoffFactor(1),
147         m_minRefreshDelay(XMLHelper::getAttrInt(e, 600, minRefreshDelay)),
148         m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
149 {
150     if (!m_local && m_maxRefreshDelay) {
151         const XMLCh* setting = e->getAttributeNS(nullptr, refreshDelayFactor);
152         if (setting && *setting) {
153             auto_ptr_char delay(setting);
154             m_refreshDelayFactor = atof(delay.get());
155             if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
156                 m_log.error("invalid refreshDelayFactor setting, using default");
157                 m_refreshDelayFactor = 0.75;
158             }
159         }
160
161         if (m_minRefreshDelay > m_maxRefreshDelay) {
162             m_log.warn("minRefreshDelay setting exceeds maxRefreshDelay/reloadInterval setting, lowering to match it");
163             m_minRefreshDelay = m_maxRefreshDelay;
164         }
165     }
166 }
167
168 void XMLMetadataProvider::init()
169 {
170     try {
171         if (!m_id.empty()) {
172             string threadid("[");
173             threadid += m_id + ']';
174             logging::NDC::push(threadid);
175         }
176         background_load();
177         startup();
178     }
179     catch (...) {
180         startup();
181         if (!m_id.empty()) {
182             logging::NDC::pop();
183         }
184         throw;
185     }
186
187     if (!m_id.empty()) {
188         logging::NDC::pop();
189     }
190 }
191
192 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
193 {
194     if (!backup) {
195         // Lower the refresh rate in case of an error.
196         m_reloadInterval = m_minRefreshDelay;
197     }
198
199     // Call the base class to load/parse the appropriate XML resource.
200     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
201
202     // If we own it, wrap it for now.
203     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
204
205     // Unmarshall objects, binding the document.
206     scoped_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
207     docjanitor.release();
208
209     if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
210         throw MetadataException(
211             "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
212             );
213
214     // Preprocess the metadata (even if we schema-validated).
215     try {
216         SchemaValidators.validate(xmlObject.get());
217     }
218     catch (std::exception& ex) {
219         m_log.error("metadata instance failed manual validation checking: %s", ex.what());
220         throw MetadataException("Metadata instance failed manual validation checking.");
221     }
222
223     const TimeBoundSAMLObject* validityCheck = dynamic_cast<TimeBoundSAMLObject*>(xmlObject.get());
224     if (!validityCheck || !validityCheck->isValid()) {
225         m_log.error("metadata instance was invalid at time of acquisition");
226         throw MetadataException("Metadata instance was invalid at time of acquisition.");
227     }
228
229     // This is the best place to take a backup, since it's superficially "correct" metadata.
230     string backupKey;
231     if (!backup && !m_backing.empty()) {
232         // We compute a random filename extension to the "real" location.
233         SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
234         backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
235         m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
236         try {
237             ofstream backer(backupKey.c_str());
238             backer << *(raw.second->getOwnerDocument());
239         }
240         catch (std::exception& ex) {
241             m_log.crit("exception while backing up metadata: %s", ex.what());
242             backupKey.erase();
243         }
244     }
245
246     try {
247         doFilters(*xmlObject);
248     }
249     catch (std::exception&) {
250         if (!backupKey.empty())
251             remove(backupKey.c_str());
252         throw;
253     }
254
255     if (!backupKey.empty()) {
256         m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
257         Locker locker(getBackupLock());
258         remove(m_backing.c_str());
259         if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
260             m_log.crit("unable to rename metadata backup file");
261         preserveCacheTag();
262     }
263
264     if (m_dropDOM) {
265         xmlObject->releaseThisAndChildrenDOM();
266         xmlObject->setDocument(nullptr);
267     }
268
269     // Swap it in after acquiring write lock if necessary.
270     if (m_lock)
271         m_lock->wrlock();
272     SharedLock locker(m_lock, false);
273     bool changed = m_object!=nullptr;
274     m_object.swap(xmlObject);
275     m_lastValidUntil = SAMLTIME_MAX;
276     index(m_lastValidUntil);
277     if (m_discoveryFeed)
278         generateFeed();
279     if (changed)
280         emitChangeEvent();
281     m_lastUpdate = time(nullptr);
282
283     // Tracking cacheUntil through the tree is TBD, but
284     // validUntil is the tightest interval amongst the children.
285
286     // If a remote resource that's monitored, adjust the reload interval.
287     if (!backup && !m_local && m_lock) {
288         m_backoffFactor = 1;
289         m_reloadInterval = computeNextRefresh();
290         m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
291     }
292
293     m_loaded = true;
294     return make_pair(false,(DOMElement*)nullptr);
295 }
296
297 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
298 {
299     try {
300         return load(false);
301     }
302     catch (long& ex) {
303         if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
304             // Unchanged document, so re-establish previous refresh interval.
305             m_reloadInterval = computeNextRefresh();
306             m_log.info("remote resource (%s) unchanged, adjusted reload interval to %u seconds", m_source.c_str(), m_reloadInterval);
307         }
308         else {
309             // Any other status code, just treat as an error.
310             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
311             if (m_reloadInterval > m_maxRefreshDelay)
312                 m_reloadInterval = m_maxRefreshDelay;
313             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
314         }
315         if (!m_loaded && !m_backing.empty())
316             return load(true);
317         throw;
318     }
319     catch (std::exception& ex) {
320         if (!m_local) {
321             m_reloadInterval = m_minRefreshDelay * m_backoffFactor++;
322             if (m_reloadInterval > m_maxRefreshDelay)
323                 m_reloadInterval = m_maxRefreshDelay;
324             m_log.warn("adjusted reload interval to %u seconds", m_reloadInterval);
325             if (!m_loaded && !m_backing.empty()) {
326                 m_log.warn("trying backup file, exception loading remote resource: %s", ex.what());
327                 return load(true);
328             }
329         }
330         throw;
331     }
332 }
333
334 time_t XMLMetadataProvider::computeNextRefresh()
335 {
336     time_t now = time(nullptr);
337
338     // If some or all of the metadata is already expired, reload after the minimum.
339     if (m_lastValidUntil < now) {
340         return m_minRefreshDelay;
341     }
342     else {
343         // Compute the smaller of the validUntil / cacheDuration constraints.
344         time_t ret = m_lastValidUntil - now;
345         const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object.get());
346         if (cacheable && cacheable->getCacheDuration())
347             ret = min(ret, cacheable->getCacheDurationEpoch());
348             
349         // Adjust for the delay factor.
350         ret *= m_refreshDelayFactor;
351
352         // Bound by max and min.
353         if (ret > m_maxRefreshDelay)
354             return m_maxRefreshDelay;
355         else if (ret < m_minRefreshDelay)
356             return m_minRefreshDelay;
357
358         return ret;
359     }
360 }
361
362 void XMLMetadataProvider::index(time_t& validUntil)
363 {
364     clearDescriptorIndex();
365     EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(m_object.get());
366     if (group) {
367         indexGroup(group, validUntil);
368         return;
369     }
370     indexEntity(dynamic_cast<EntityDescriptor*>(m_object.get()), validUntil);
371 }
372
373 void XMLMetadataProvider::outputStatus(ostream& os) const
374 {
375     os << "<MetadataProvider";
376
377     if (getId() && *getId()) {
378         os << " id='"; xml_encode(os, getId()); os << "'";
379     }
380
381     if (!m_source.empty()) {
382         os << " source='"; xml_encode(os, m_source.c_str()); os << "'";
383     }
384
385     if (m_lastUpdate > 0) {
386         DateTime ts(m_lastUpdate);
387         ts.parseDateTime();
388         auto_ptr_char timestamp(ts.getFormattedString());
389         os << " lastUpdate='" << timestamp.get() << "'";
390     }
391
392     if (!m_local && m_reloadInterval > 0) {
393         os << " reloadInterval='" << m_reloadInterval << "'";
394     }
395
396     os << "/>";
397 }