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