Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / DynamicMetadataProvider.cpp
1 /*
2  *  Copyright 2001-2009 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  * DynamicMetadataProvider.cpp
19  *
20  * Simple implementation of a dynamic caching MetadataProvider.
21  */
22
23 #include "internal.h"
24 #include "binding/SAMLArtifact.h"
25 #include "saml2/metadata/Metadata.h"
26 #include "saml2/metadata/DynamicMetadataProvider.h"
27
28 #include <xercesc/framework/Wrapper4InputSource.hpp>
29 #include <xercesc/util/XMLUniDefs.hpp>
30 #include <xmltooling/logging.h>
31 #include <xmltooling/XMLToolingConfig.h>
32 #include <xmltooling/util/ParserPool.h>
33 #include <xmltooling/util/Threads.h>
34 #include <xmltooling/util/XMLHelper.h>
35 #include <xmltooling/validation/ValidatorSuite.h>
36
37 using namespace opensaml::saml2md;
38 using namespace xmltooling::logging;
39 using namespace xmltooling;
40 using namespace std;
41
42 # ifndef min
43 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
44 # endif
45
46 static const XMLCh maxCacheDuration[] = UNICODE_LITERAL_16(m,a,x,C,a,c,h,e,D,u,r,a,t,i,o,n);
47 static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
48
49 namespace opensaml {
50     namespace saml2md {
51         MetadataProvider* SAML_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
52         {
53             return new DynamicMetadataProvider(e);
54         }
55     };
56 };
57
58 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
59     : AbstractMetadataProvider(e), m_maxCacheDuration(28800), m_lock(RWLock::create())
60 {
61     const XMLCh* flag=e ? e->getAttributeNS(NULL,validate) : NULL;
62     m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));
63     flag = e ? e->getAttributeNS(NULL,maxCacheDuration) : NULL;
64     if (flag && *flag) {
65         m_maxCacheDuration = XMLString::parseInt(flag);
66         if (m_maxCacheDuration == 0)
67             m_maxCacheDuration = 28800;
68     }
69 }
70
71 DynamicMetadataProvider::~DynamicMetadataProvider()
72 {
73     // Each entity in the map is unique (no multimap semantics), so this is safe.
74     clearDescriptorIndex(true);
75     delete m_lock;
76 }
77
78 const XMLObject* DynamicMetadataProvider::getMetadata() const
79 {
80     throw MetadataException("getMetadata operation not implemented on this provider.");
81 }
82
83 Lockable* DynamicMetadataProvider::lock()
84 {
85     m_lock->rdlock();
86     return this;
87 }
88
89 void DynamicMetadataProvider::unlock()
90 {
91     m_lock->unlock();
92 }
93
94 void DynamicMetadataProvider::init()
95 {
96 }
97
98 pair<const EntityDescriptor*,const RoleDescriptor*> DynamicMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
99 {
100     // Check cache while holding the read lock.
101     pair<const EntityDescriptor*,const RoleDescriptor*> entity = AbstractMetadataProvider::getEntityDescriptor(criteria);
102     if (entity.first)   // even if the role isn't found, we're done
103         return entity;
104
105     string name;
106     if (criteria.entityID_ascii)
107         name = criteria.entityID_ascii;
108     else if (criteria.entityID_unicode) {
109         auto_ptr_char temp(criteria.entityID_unicode);
110         name = temp.get();
111     }
112     else if (criteria.artifact) {
113         name = criteria.artifact->getSource();
114     }
115     else
116         return entity;
117
118     Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic");
119     log.info("resolving metadata for (%s)", name.c_str());
120
121     try {
122         // Try resolving it.
123         auto_ptr<EntityDescriptor> entity2(resolve(criteria));
124
125         // Verify the entityID.
126         if (criteria.entityID_unicode && !XMLString::equals(criteria.entityID_unicode, entity2->getEntityID())) {
127             log.error("metadata instance did not match expected entityID");
128             return entity;
129         }
130         else {
131             auto_ptr_XMLCh temp2(name.c_str());
132             if (!XMLString::equals(temp2.get(), entity2->getEntityID())) {
133                 log.error("metadata instance did not match expected entityID");
134                 return entity;
135             }
136         }
137
138         // Preprocess the metadata (even if we schema-validated).
139         try {
140             SchemaValidators.validate(entity2.get());
141         }
142         catch (exception& ex) {
143             log.error("metadata intance failed manual validation checking: %s", ex.what());
144             throw MetadataException("Metadata instance failed manual validation checking.");
145         }
146
147         // Filter it, which may throw.
148         doFilters(*entity2.get());
149
150         time_t now = time(NULL);
151
152         if (entity2->getValidUntil() && entity2->getValidUntilEpoch() < now + 60)
153             throw MetadataException("Metadata was already invalid at the time of retrieval.");
154
155         log.info("caching resolved metadata for (%s)", name.c_str());
156
157         // Upgrade our lock so we can cache the new metadata.
158         m_lock->unlock();
159         m_lock->wrlock();
160
161         // Notify observers.
162         emitChangeEvent();
163
164         // Make sure we clear out any existing copies, including stale metadata or if somebody snuck in.
165         time_t exp = m_maxCacheDuration;
166         if (entity2->getCacheDuration())
167             exp = min(m_maxCacheDuration, entity2->getCacheDurationEpoch());
168         exp += now;
169         index(entity2.release(), exp, true);
170
171         // Downgrade back to a read lock.
172         m_lock->unlock();
173         m_lock->rdlock();
174     }
175     catch (exception& e) {
176         log.error("error while resolving entityID (%s): %s", name.c_str(), e.what());
177         return entity;
178     }
179
180     // Rinse and repeat.
181     return getEntityDescriptor(criteria);
182 }
183
184 EntityDescriptor* DynamicMetadataProvider::resolve(const Criteria& criteria) const
185 {
186     string name;
187     if (criteria.entityID_ascii) {
188         name = criteria.entityID_ascii;
189     }
190     else if (criteria.entityID_unicode) {
191         auto_ptr_char temp(criteria.entityID_unicode);
192         name = temp.get();
193     }
194     else if (criteria.artifact) {
195         throw MetadataException("Unable to resolve metadata dynamically from an artifact.");
196     }
197
198     try {
199         DOMDocument* doc=NULL;
200         auto_ptr_XMLCh widenit(name.c_str());
201         URLInputSource src(widenit.get());
202         Wrapper4InputSource dsrc(&src,false);
203         if (m_validate)
204             doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
205         else
206             doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
207
208         // Wrap the document for now.
209         XercesJanitor<DOMDocument> docjanitor(doc);
210
211         // Unmarshall objects, binding the document.
212         auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
213         docjanitor.release();
214
215         // Make sure it's metadata.
216         EntityDescriptor* entity = dynamic_cast<EntityDescriptor*>(xmlObject.get());
217         if (!entity) {
218             throw MetadataException(
219                 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
220                 );
221         }
222         xmlObject.release();
223         return entity;
224     }
225     catch (XMLException& e) {
226         auto_ptr_char msg(e.getMessage());
227         Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(
228             "Xerces error while resolving entityID (%s): %s", name.c_str(), msg.get()
229             );
230         throw MetadataException(msg.get());
231     }
232 }