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