Multi-line svn commit, see body.
[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/util/NDC.h>
31 #include <xmltooling/util/ReloadableXMLFile.h>
32 #include <xmltooling/util/Threads.h>
33 #include <xmltooling/validation/ValidatorSuite.h>
34
35 using namespace opensaml::saml2md;
36 using namespace xmltooling::logging;
37 using namespace xmltooling;
38 using namespace std;
39
40 #if defined (_MSC_VER)
41     #pragma warning( push )
42     #pragma warning( disable : 4250 )
43 #endif
44
45 namespace opensaml {
46     namespace saml2md {
47
48         class SAML_DLLLOCAL XMLMetadataProvider : public AbstractMetadataProvider, public ReloadableXMLFile
49         {
50         public:
51             XMLMetadataProvider(const DOMElement* e)
52                 : AbstractMetadataProvider(e), ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML")),
53                     m_object(NULL), m_maxCacheDuration(m_reloadInterval) {
54             }
55             virtual ~XMLMetadataProvider() {
56                 delete m_object;
57             }
58
59             void init() {
60                 background_load(); // guarantees an exception or the metadata is loaded
61             }
62
63             const XMLObject* getMetadata() const {
64                 return m_object;
65             }
66
67         protected:
68             pair<bool,DOMElement*> background_load();
69
70         private:
71             using AbstractMetadataProvider::index;
72             void index();
73
74             XMLObject* m_object;
75             time_t m_maxCacheDuration;
76         };
77
78         MetadataProvider* SAML_DLLLOCAL XMLMetadataProviderFactory(const DOMElement* const & e)
79         {
80             return new XMLMetadataProvider(e);
81         }
82
83     };
84 };
85
86 #if defined (_MSC_VER)
87     #pragma warning( pop )
88 #endif
89
90 pair<bool,DOMElement*> XMLMetadataProvider::background_load()
91 {
92     // Turn off auto-backup so we can filter first.
93     m_backupIndicator = false;
94
95     // Load from source using base class.
96     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
97
98     // If we own it, wrap it for now.
99     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
100
101     // Unmarshall objects, binding the document.
102     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
103     docjanitor.release();
104
105     if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
106         throw MetadataException(
107             "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
108             );
109
110     // Preprocess the metadata (even if we schema-validated).
111     try {
112         SchemaValidators.validate(xmlObject.get());
113     }
114     catch (exception& ex) {
115         m_log.error("metadata intance failed manual validation checking: %s", ex.what());
116         throw MetadataException("Metadata instance failed manual validation checking.");
117     }
118
119     // If the backup indicator is flipped, then this was a remote load and we need a backup.
120     // This is the best place to take a backup, since it's superficially "correct" metadata.
121     string backupKey;
122     if (m_backupIndicator) {
123         // We compute a random filename extension to the "real" location.
124         SAMLConfig::getConfig().generateRandomBytes(backupKey, 2);
125         backupKey = m_backing + '.' + SAMLArtifact::toHex(backupKey);
126         m_log.debug("backing up remote metadata resource to (%s)", backupKey.c_str());
127         try {
128             ofstream backer(backupKey.c_str());
129             backer << *raw.second->getOwnerDocument();
130         }
131         catch (exception& ex) {
132             m_log.crit("exception while backing up metadata: %s", ex.what());
133             backupKey.erase();
134         }
135     }
136
137     try {
138         doFilters(*xmlObject.get());
139     }
140     catch (exception&) {
141         if (!backupKey.empty())
142             remove(backupKey.c_str());
143         throw;
144     }
145
146     if (!backupKey.empty()) {
147         m_log.debug("committing backup file to permanent location (%s)", m_backing.c_str());
148         Locker locker(getBackupLock());
149         remove(m_backing.c_str());
150         if (rename(backupKey.c_str(), m_backing.c_str()) != 0)
151             m_log.crit("unable to rename metadata backup file");
152     }
153
154     xmlObject->releaseThisAndChildrenDOM();
155     xmlObject->setDocument(NULL);
156
157     // Swap it in after acquiring write lock if necessary.
158     if (m_lock)
159         m_lock->wrlock();
160     SharedLock locker(m_lock, false);
161     bool changed = m_object!=NULL;
162     delete m_object;
163     m_object = xmlObject.release();
164     index();
165     if (changed)
166         emitChangeEvent();
167
168     // If a remote resource, adjust the reload interval if cacheDuration is set.
169     if (!m_local) {
170         const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object);
171         if (cacheable && cacheable->getCacheDuration() && cacheable->getCacheDurationEpoch() < m_maxCacheDuration)
172             m_reloadInterval = cacheable->getCacheDurationEpoch();
173         else
174             m_reloadInterval = m_maxCacheDuration;
175     }
176
177     return make_pair(false,(DOMElement*)NULL);
178 }
179
180 void XMLMetadataProvider::index()
181 {
182     clearDescriptorIndex();
183     EntitiesDescriptor* group=dynamic_cast<EntitiesDescriptor*>(m_object);
184     if (group) {
185         AbstractMetadataProvider::index(group, SAMLTIME_MAX);
186         return;
187     }
188     AbstractMetadataProvider::index(dynamic_cast<EntityDescriptor*>(m_object), SAMLTIME_MAX);
189 }