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