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