d37720d16a12974e660cc828133d4e36b94b10df
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / XMLAttributeExtractor.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLAttributeExtractor.cpp
23  *
24  * AttributeExtractor based on an XML mapping file.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "attribute/Attribute.h"
32 #include "attribute/AttributeDecoder.h"
33 #include "attribute/filtering/AttributeFilter.h"
34 #include "attribute/filtering/BasicFilteringContext.h"
35 #include "attribute/resolver/AttributeExtractor.h"
36 #include "remoting/ddf.h"
37 #include "security/SecurityPolicy.h"
38 #include "util/SPConstants.h"
39
40 #include <boost/bind.hpp>
41 #include <boost/shared_ptr.hpp>
42 #include <boost/algorithm/string.hpp>
43 #include <boost/iterator/indirect_iterator.hpp>
44 #include <boost/ptr_container/ptr_vector.hpp>
45 #include <boost/tuple/tuple.hpp>
46 #include <saml/SAMLConfig.h>
47 #include <saml/saml1/core/Assertions.h>
48 #include <saml/saml2/core/Assertions.h>
49 #include <saml/saml2/metadata/Metadata.h>
50 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
51 #include <saml/saml2/metadata/ObservableMetadataProvider.h>
52 #include <xmltooling/XMLToolingConfig.h>
53 #include <xmltooling/security/TrustEngine.h>
54 #include <xmltooling/util/NDC.h>
55 #include <xmltooling/util/ReloadableXMLFile.h>
56 #include <xmltooling/util/Threads.h>
57 #include <xmltooling/util/XMLHelper.h>
58 #include <xercesc/util/XMLUniDefs.hpp>
59
60 using namespace shibsp;
61 using namespace opensaml::saml2md;
62 using namespace opensaml;
63 using namespace xmltooling;
64 using namespace boost;
65 using namespace std;
66 using saml1::NameIdentifier;
67 using saml2::NameID;
68 using saml2::EncryptedAttribute;
69
70 namespace shibsp {
71
72 #if defined (_MSC_VER)
73     #pragma warning( push )
74     #pragma warning( disable : 4250 )
75 #endif
76
77     class XMLExtractorImpl : public ObservableMetadataProvider::Observer
78     {
79     public:
80         XMLExtractorImpl(const DOMElement* e, Category& log);
81         ~XMLExtractorImpl() {
82             for (map<const ObservableMetadataProvider*,decoded_t>::iterator i=m_decodedMap.begin(); i!=m_decodedMap.end(); ++i) {
83                 i->first->removeObserver(this);
84                 for (decoded_t::iterator attrs = i->second.begin(); attrs!=i->second.end(); ++attrs)
85                     for_each(attrs->second.begin(), attrs->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
86             }
87             if (m_document)
88                 m_document->release();
89         }
90
91         void setDocument(DOMDocument* doc) {
92             m_document = doc;
93         }
94
95         void onEvent(const ObservableMetadataProvider& metadata) const {
96             // Destroy attributes we cached from this provider.
97             m_attrLock->wrlock();
98             SharedLock wrapper(m_attrLock, false);
99             decoded_t& d = m_decodedMap[&metadata];
100             for (decoded_t::iterator a = d.begin(); a!=d.end(); ++a)
101                 for_each(a->second.begin(), a->second.end(), mem_fun_ref<DDF&,DDF>(&DDF::destroy));
102             d.clear();
103         }
104
105         void extractAttributes(const Application&, const char*, const char*, const NameIdentifier&, ptr_vector<Attribute>&) const;
106         void extractAttributes(const Application&, const char*, const char*, const NameID&, ptr_vector<Attribute>&) const;
107         void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&) const;
108         void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&) const;
109         void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&) const;
110         void extractAttributes(const Application&, const GenericRequest*, const char*, const char*, const saml2::AttributeStatement&, ptr_vector<Attribute>&) const;
111         void extractAttributes(
112             const Application&, const GenericRequest*, const ObservableMetadataProvider*, const XMLCh*, const char*, const Extensions&, ptr_vector<Attribute>&
113             ) const;
114
115         void getAttributeIds(vector<string>& attributes) const {
116             attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
117         }
118
119         void generateMetadata(SPSSODescriptor& role) const;
120
121     private:
122         Category& m_log;
123         DOMDocument* m_document;
124         typedef map< pair<xstring,xstring>,pair< boost::shared_ptr<AttributeDecoder>,vector<string> > > attrmap_t;
125         attrmap_t m_attrMap;
126         vector<string> m_attributeIds;
127         vector< boost::tuple<xstring,xstring,bool> > m_requestedAttrs;
128
129         // settings for embedded assertions in metadata
130         string m_policyId;
131         scoped_ptr<AttributeFilter> m_filter;
132         scoped_ptr<MetadataProvider> m_metadata;
133         scoped_ptr<TrustEngine> m_trust;
134         bool m_entityAssertions,m_metaAttrCaching;
135
136         // manages caching of decoded Attributes
137         scoped_ptr<RWLock> m_attrLock;
138         typedef map< const EntityAttributes*,vector<DDF> > decoded_t;
139         mutable map<const ObservableMetadataProvider*,decoded_t> m_decodedMap;
140     };
141
142     class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
143     {
144     public:
145         XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT ".AttributeExtractor.XML")) {
146             if (m_local && m_lock)
147                 m_log.warn("attribute mappings are reloadable; be sure to restart web server when adding new attribute IDs");
148             background_load();
149         }
150         ~XMLExtractor() {
151             shutdown();
152         }
153
154         // deprecated method
155         void extractAttributes(
156             const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
157             ) const {
158             extractAttributes(application, nullptr, issuer, xmlObject, attributes);
159         }
160
161         void extractAttributes(const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, vector<Attribute*>&) const;
162
163         void getAttributeIds(std::vector<std::string>& attributes) const {
164             if (m_impl)
165                 m_impl->getAttributeIds(attributes);
166         }
167
168         void generateMetadata(SPSSODescriptor& role) const {
169             if (m_impl)
170                 m_impl->generateMetadata(role);
171         }
172
173     protected:
174         pair<bool,DOMElement*> background_load();
175
176     private:
177         scoped_ptr<XMLExtractorImpl> m_impl;
178
179         void extractAttributes(const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&) const;
180     };
181
182 #if defined (_MSC_VER)
183     #pragma warning( pop )
184 #endif
185
186     AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
187     {
188         return new XMLExtractor(e);
189     }
190
191     static const XMLCh _aliases[] =                 UNICODE_LITERAL_7(a,l,i,a,s,e,s);
192     static const XMLCh _AttributeDecoder[] =        UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
193     static const XMLCh _AttributeFilter[] =         UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
194     static const XMLCh Attributes[] =               UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
195     static const XMLCh _id[] =                      UNICODE_LITERAL_2(i,d);
196     static const XMLCh isRequested[] =              UNICODE_LITERAL_11(i,s,R,e,q,u,e,s,t,e,d);
197     static const XMLCh _MetadataProvider[] =        UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
198     static const XMLCh metadataAttributeCaching[] = UNICODE_LITERAL_24(m,e,t,a,d,a,t,a,A,t,t,r,i,b,u,t,e,C,a,c,h,i,n,g);
199     static const XMLCh metadataPolicyId[] =         UNICODE_LITERAL_16(m,e,t,a,d,a,t,a,P,o,l,i,c,y,I,d);
200     static const XMLCh _name[] =                    UNICODE_LITERAL_4(n,a,m,e);
201     static const XMLCh nameFormat[] =               UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
202     static const XMLCh _TrustEngine[] =             UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
203     static const XMLCh _type[] =                    UNICODE_LITERAL_4(t,y,p,e);
204 };
205
206 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log)
207     : m_log(log),
208         m_document(nullptr),
209         m_policyId(XMLHelper::getAttrString(e, nullptr, metadataPolicyId)),
210         m_entityAssertions(true),
211         m_metaAttrCaching(XMLHelper::getAttrBool(e, true, metadataAttributeCaching))
212 {
213 #ifdef _DEBUG
214     xmltooling::NDC ndc("XMLExtractorImpl");
215 #endif
216
217     if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
218         throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
219
220     DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _MetadataProvider);
221     if (child) {
222         try {
223             string t(XMLHelper::getAttrString(child, nullptr, _type));
224             if (t.empty())
225                 throw ConfigurationException("MetadataProvider element missing type attribute.");
226             m_log.info("building MetadataProvider of type %s...", t.c_str());
227             m_metadata.reset(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
228             m_metadata->init();
229         }
230         catch (std::exception& ex) {
231             m_metadata.reset();
232             m_entityAssertions = false;
233             m_log.crit("error building/initializing dedicated MetadataProvider: %s", ex.what());
234             m_log.crit("disabling support for Assertions in EntityAttributes extension");
235         }
236     }
237
238     if (m_entityAssertions) {
239         child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _TrustEngine);
240         if (child) {
241             try {
242                 string t(XMLHelper::getAttrString(child, nullptr, _type));
243                 if (t.empty())
244                     throw ConfigurationException("TrustEngine element missing type attribute.");
245                 m_log.info("building TrustEngine of type %s...", t.c_str());
246                 m_trust.reset(XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child));
247             }
248             catch (std::exception& ex) {
249                 m_entityAssertions = false;
250                 m_log.crit("error building/initializing dedicated TrustEngine: %s", ex.what());
251                 m_log.crit("disabling support for Assertions in EntityAttributes extension");
252             }
253         }
254     }
255
256     if (m_entityAssertions) {
257         child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeFilter);
258         if (child) {
259             try {
260                 string t(XMLHelper::getAttrString(child, nullptr, _type));
261                 if (t.empty())
262                     throw ConfigurationException("AttributeFilter element missing type attribute.");
263                 m_log.info("building AttributeFilter of type %s...", t.c_str());
264                 m_filter.reset(SPConfig::getConfig().AttributeFilterManager.newPlugin(t.c_str(), child));
265             }
266             catch (std::exception& ex) {
267                 m_entityAssertions = false;
268                 m_log.crit("error building/initializing dedicated AttributeFilter: %s", ex.what());
269                 m_log.crit("disabling support for Assertions in EntityAttributes extension");
270             }
271         }
272     }
273
274     child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
275     while (child) {
276         // Check for missing name or id.
277         const XMLCh* name = child->getAttributeNS(nullptr, _name);
278         if (!name || !*name) {
279             m_log.warn("skipping Attribute with no name");
280             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
281             continue;
282         }
283
284         auto_ptr_char id(child->getAttributeNS(nullptr, _id));
285         if (!id.get() || !*id.get()) {
286             m_log.warn("skipping Attribute with no id");
287             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
288             continue;
289         }
290         else if (!strcmp(id.get(), "REMOTE_USER")) {
291             m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
292             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
293             continue;
294         }
295
296         boost::shared_ptr<AttributeDecoder> decoder;
297         try {
298             DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
299             if (dchild) {
300                 auto_ptr<xmltooling::QName> q(XMLHelper::getXSIType(dchild));
301                 if (q.get())
302                     decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild));
303             }
304             if (!decoder)
305                 decoder.reset(SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, nullptr));
306         }
307         catch (std::exception& ex) {
308             m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
309         }
310
311         if (!decoder) {
312             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
313             continue;
314         }
315
316         // Empty NameFormat implies the usual Shib URI naming defaults.
317         const XMLCh* format = child->getAttributeNS(nullptr, nameFormat);
318         if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
319                 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
320             format = &chNull;  // ignore default Format/Namespace values
321
322         // Fetch/create the map entry and see if it's a duplicate rule.
323         // Trim the format and the name only if the format is the default (URI).
324         pair<xstring,xstring> entryKey(name,format);
325         if (*format == chNull) {
326             trim(entryKey.first);
327         }
328         trim(entryKey.second);
329         pair< boost::shared_ptr<AttributeDecoder>,vector<string> >& decl = m_attrMap[entryKey];
330         if (decl.first) {
331             m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
332             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
333             continue;
334         }
335
336         if (m_log.isInfoEnabled()) {
337             auto_ptr_char n(entryKey.first.c_str());
338             auto_ptr_char f(entryKey.second.c_str());
339             m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
340         }
341
342         decl.first = decoder;
343         decl.second.push_back(id.get());
344         m_attributeIds.push_back(id.get());
345
346         // Check for isRequired/isRequested.
347         bool requested = XMLHelper::getAttrBool(child, false, isRequested);
348         bool required = XMLHelper::getAttrBool(child, false, RequestedAttribute::ISREQUIRED_ATTRIB_NAME);
349         if (required || requested) {
350             m_requestedAttrs.push_back(boost::tuple<xstring,xstring,bool>(entryKey.first, entryKey.second, required));
351         }
352
353         name = child->getAttributeNS(nullptr, _aliases);
354         if (name && *name) {
355             m_log.warn("attribute mapping rule (%s) uses deprecated aliases feature, consider revising", id.get());
356             auto_ptr_char aliases(name);
357             string dup(aliases.get());
358             trim(dup);
359             set<string> new_aliases;
360             split(new_aliases, dup, is_space(), algorithm::token_compress_on);
361             set<string>::iterator ru = new_aliases.find("REMOTE_USER");
362             if (ru != new_aliases.end()) {
363                 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
364                 new_aliases.erase(ru);
365             }
366             decl.second.insert(decl.second.end(), new_aliases.begin(), new_aliases.end());
367             m_attributeIds.insert(m_attributeIds.end(), new_aliases.begin(), new_aliases.end());
368         }
369
370         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
371     }
372
373     if (m_metaAttrCaching)
374         m_attrLock.reset(RWLock::create());
375 }
376
377 void XMLExtractorImpl::generateMetadata(SPSSODescriptor& role) const
378 {
379     if (m_requestedAttrs.empty())
380         return;
381     int index = 1;
382     const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(&role)->getAttributeConsumingServices();
383     for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
384         pair<bool,int> i = (*s)->getIndex();
385         if (i.first && index == i.second)
386             index = i.second + 1;
387     }
388     AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
389     role.getAttributeConsumingServices().push_back(svc);
390     svc->setIndex(index);
391     ServiceName* sn = ServiceNameBuilder::buildServiceName();
392     svc->getServiceNames().push_back(sn);
393     sn->setName(dynamic_cast<EntityDescriptor*>(role.getParent())->getEntityID());
394     static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
395     sn->setLang(english);
396
397     for (vector< boost::tuple<xstring,xstring,bool> >::const_iterator i = m_requestedAttrs.begin(); i != m_requestedAttrs.end(); ++i) {
398         RequestedAttribute* req = RequestedAttributeBuilder::buildRequestedAttribute();
399         svc->getRequestedAttributes().push_back(req);
400         req->setName(i->get<0>().c_str());
401         if (i->get<1>().empty())
402             req->setNameFormat(saml2::Attribute::URI_REFERENCE);
403         else
404             req->setNameFormat(i->get<1>().c_str());
405         if (i->get<2>())
406             req->isRequired(true);
407     }
408 }
409
410 void XMLExtractorImpl::extractAttributes(
411     const Application& application,
412     const char* assertingParty,
413     const char* relyingParty,
414     const NameIdentifier& nameid,
415     ptr_vector<Attribute>& attributes
416     ) const
417 {
418     const XMLCh* format = nameid.getFormat();
419     if (!format || !*format)
420         format = NameIdentifier::UNSPECIFIED;
421     attrmap_t::const_iterator rule;
422     if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
423         auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
424         if (a.get()) {
425             attributes.push_back(a.get());
426             a.release();
427         }
428     }
429     else if (m_log.isDebugEnabled()) {
430         auto_ptr_char temp(format);
431         m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
432     }
433 }
434
435 void XMLExtractorImpl::extractAttributes(
436     const Application& application,
437     const char* assertingParty,
438     const char* relyingParty,
439     const NameID& nameid,
440     ptr_vector<Attribute>& attributes
441     ) const
442 {
443     const XMLCh* format = nameid.getFormat();
444     if (!format || !*format)
445         format = NameID::UNSPECIFIED;
446     attrmap_t::const_iterator rule;
447     if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
448         auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
449         if (a.get()) {
450             attributes.push_back(a.get());
451             a.release();
452         }
453     }
454     else if (m_log.isDebugEnabled()) {
455         auto_ptr_char temp(format);
456         m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
457     }
458 }
459
460 void XMLExtractorImpl::extractAttributes(
461     const Application& application,
462     const GenericRequest* request,
463     const char* assertingParty,
464     const char* relyingParty,
465     const saml1::Attribute& attr,
466     ptr_vector<Attribute>& attributes
467     ) const
468 {
469     const XMLCh* name = attr.getAttributeName();
470     const XMLCh* format = attr.getAttributeNamespace();
471     if (!name || !*name)
472         return;
473     if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
474         format = &chNull;
475     attrmap_t::const_iterator rule;
476     if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
477         auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
478         if (a.get()) {
479             attributes.push_back(a.get());
480             a.release();
481         }
482     }
483     else if (m_log.isInfoEnabled()) {
484         auto_ptr_char temp1(name);
485         auto_ptr_char temp2(format);
486         m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
487     }
488 }
489
490 void XMLExtractorImpl::extractAttributes(
491     const Application& application,
492     const GenericRequest* request,
493     const char* assertingParty,
494     const char* relyingParty,
495     const saml2::Attribute& attr,
496     ptr_vector<Attribute>& attributes
497     ) const
498 {
499     const XMLCh* name = attr.getName();
500     const XMLCh* format = attr.getNameFormat();
501     if (!name || !*name)
502         return;
503     if (!format || !*format)
504         format = saml2::Attribute::UNSPECIFIED;
505     else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
506         format = &chNull;
507     attrmap_t::const_iterator rule;
508     if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
509         auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
510         if (a.get()) {
511             attributes.push_back(a.get());
512             a.release();
513             return;
514         }
515     }
516     else if (XMLString::equals(format, saml2::Attribute::UNSPECIFIED)) {
517         // As a fallback, if the format is "unspecified", null out the value and re-map.
518         if ((rule = m_attrMap.find(pair<xstring,xstring>(name,xstring()))) != m_attrMap.end()) {
519             auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
520             if (a.get()) {
521                 attributes.push_back(a.get());
522                 a.release();
523                 return;
524             }
525         }
526     }
527
528     if (m_log.isInfoEnabled()) {
529         auto_ptr_char temp1(name);
530         auto_ptr_char temp2(format);
531         m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
532     }
533 }
534
535 void XMLExtractorImpl::extractAttributes(
536     const Application& application,
537     const GenericRequest* request,
538     const char* assertingParty,
539     const char* relyingParty,
540     const saml1::AttributeStatement& statement,
541     ptr_vector<Attribute>& attributes
542     ) const
543 {
544     static void (XMLExtractorImpl::* extract)(
545         const Application&, const GenericRequest*, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&
546         ) const = &XMLExtractorImpl::extractAttributes;
547     for_each(
548         make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
549         boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
550         );
551 }
552
553 void XMLExtractorImpl::extractAttributes(
554     const Application& application,
555     const GenericRequest* request,
556     const char* assertingParty,
557     const char* relyingParty,
558     const saml2::AttributeStatement& statement,
559     ptr_vector<Attribute>& attributes
560     ) const
561 {
562     static void (XMLExtractorImpl::* extract)(
563         const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
564         ) const = &XMLExtractorImpl::extractAttributes;
565     for_each(
566         make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
567         boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
568         );
569 }
570
571 void XMLExtractorImpl::extractAttributes(
572     const Application& application,
573     const GenericRequest* request,
574     const ObservableMetadataProvider* observable,
575     const XMLCh* entityID,
576     const char* relyingParty,
577     const Extensions& ext,
578     ptr_vector<Attribute>& attributes
579     ) const
580 {
581     const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
582     for (vector<XMLObject*>::const_iterator i = exts.begin(); i != exts.end(); ++i) {
583         const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
584         if (!container)
585             continue;
586
587         bool useCache = false;
588         map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
589
590         // Check for cached result.
591         if (observable && m_metaAttrCaching) {
592             m_attrLock->rdlock();
593             cacheEntry = m_decodedMap.find(observable);
594             if (cacheEntry == m_decodedMap.end()) {
595                 // We need to elevate the lock and retry.
596                 m_attrLock->unlock();
597                 m_attrLock->wrlock();
598                 cacheEntry = m_decodedMap.find(observable);
599                 if (cacheEntry == m_decodedMap.end()) {
600                     SharedLock locker(m_attrLock, false);   // guard in case these throw
601
602                     // It's still brand new, so hook it for cache activation.
603                     observable->addObserver(this);
604
605                     // Prime the map reference with an empty decoded map.
606                     cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
607
608                     // Downgrade the lock.
609                     // We don't have to recheck because we never erase the master map entry entirely, even on changes.
610                     locker.release();   // unguard for lock downgrade
611                     m_attrLock->unlock();
612                     m_attrLock->rdlock();
613                 }
614             }
615             useCache = true;
616         }
617
618         if (useCache) {
619             // We're holding the lock, so check the cache.
620             decoded_t::iterator d = cacheEntry->second.find(container);
621             if (d != cacheEntry->second.end()) {
622                 SharedLock locker(m_attrLock, false);   // pop the lock when we're done
623                 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
624                     auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
625                     m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
626                     attributes.push_back(wrapper.get());
627                     wrapper.release();
628                 }
629                 break;
630             }
631         }
632
633         // Add a guard for the lock if we're caching.
634         SharedLock locker(useCache ? m_attrLock.get() : nullptr, false);
635
636         // Use a holding area to support caching.
637         ptr_vector<Attribute> holding;
638
639         // Extract attributes into holding area with no asserting party set.
640         static void (XMLExtractorImpl::* extractV2Attr)(
641             const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
642             ) const = &XMLExtractorImpl::extractAttributes;
643         for_each(
644             make_indirect_iterator(container->getAttributes().begin()), make_indirect_iterator(container->getAttributes().end()),
645             boost::bind(extractV2Attr, this, boost::ref(application), request, (const char*)nullptr, relyingParty, _1, boost::ref(holding))
646             );
647
648         if (entityID && m_entityAssertions) {
649             const vector<saml2::Assertion*>& asserts = container->getAssertions();
650             for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> assert = make_indirect_iterator(asserts.begin());
651                     assert != make_indirect_iterator(asserts.end()); ++assert) {
652                 if (!(assert->getSignature())) {
653                     if (m_log.isDebugEnabled()) {
654                         auto_ptr_char eid(entityID);
655                         m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
656                     }
657                     continue;
658                 }
659                 else if (assert->getAttributeStatements().empty()) {
660                     if (m_log.isDebugEnabled()) {
661                         auto_ptr_char eid(entityID);
662                         m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
663                     }
664                     continue;
665                 }
666                 else {
667                     // Check subject.
668                     const NameID* subject = assert->getSubject() ? assert->getSubject()->getNameID() : nullptr;
669                     if (!subject ||
670                             !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
671                             !XMLString::equals(subject->getName(), entityID)) {
672                         if (m_log.isDebugEnabled()) {
673                             auto_ptr_char eid(entityID);
674                             m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
675                         }
676                         continue;
677                     }
678                 }
679
680                 try {
681                     // Set up and evaluate a policy for an AA asserting attributes to us.
682                     shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.c_str());
683                     Locker locker(m_metadata.get());
684                     if (m_metadata)
685                         policy.setMetadataProvider(m_metadata.get());
686                     if (m_trust)
687                         policy.setTrustEngine(m_trust.get());
688                     // Populate recipient as audience.
689                     const XMLCh* issuer = assert->getIssuer() ? assert->getIssuer()->getName() : nullptr;
690                     policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
691
692                     // Extract assertion information for policy.
693                     policy.setMessageID(assert->getID());
694                     policy.setIssueInstant(assert->getIssueInstantEpoch());
695                     policy.setIssuer(assert->getIssuer());
696
697                     // Look up metadata for issuer.
698                     if (policy.getIssuer() && policy.getMetadataProvider()) {
699                         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
700                             m_log.debug("non-system entity issuer, skipping metadata lookup");
701                         }
702                         else {
703                             m_log.debug("searching metadata for entity assertion issuer...");
704                             pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
705                             MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
706                             mc.entityID_unicode = policy.getIssuer()->getName();
707                             mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
708                             mc.protocol = samlconstants::SAML20P_NS;
709                             lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
710                             if (!lookup.first) {
711                                 auto_ptr_char iname(policy.getIssuer()->getName());
712                                 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
713                             }
714                             else if (!lookup.second) {
715                                 m_log.debug("unable to find compatible AA role in metadata");
716                             }
717                             else {
718                                 policy.setIssuerMetadata(lookup.second);
719                             }
720                         }
721                     }
722
723                     // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
724                     scoped_ptr<saml2::Assertion> tokencopy(assert->cloneAssertion());
725                     tokencopy->marshall();
726                     policy.evaluate(*tokencopy);
727                     if (!policy.isAuthenticated()) {
728                         if (m_log.isDebugEnabled()) {
729                             auto_ptr_char tempid(tokencopy->getID());
730                             auto_ptr_char eid(entityID);
731                             m_log.debug(
732                                 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
733                                 );
734                         }
735                         continue;
736                     }
737
738                     // Override the asserting/relying party names based on this new issuer.
739                     const EntityDescriptor* inlineEntity =
740                         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
741                     auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : nullptr);
742                     relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
743
744                     // Use a private holding area for filtering purposes.
745                     ptr_vector<Attribute> holding2;
746                     const vector<saml2::Attribute*>& attrs2 =
747                         const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
748                     for_each(
749                         make_indirect_iterator(attrs2.begin()), make_indirect_iterator(attrs2.end()),
750                         boost::bind(extractV2Attr, this, boost::ref(application), request, inlineAssertingParty.get(), relyingParty, _1, boost::ref(holding2))
751                         );
752
753                     // Now we locally filter the attributes so that the actual issuer can be properly set.
754                     // If we relied on outside filtering, the attributes couldn't be distinguished from the
755                     // ones that come from the user's IdP.
756                     if (m_filter && !holding2.empty()) {
757
758                         // The filter API uses an unsafe container, so we have to transfer everything into one and back.
759                         vector<Attribute*> unsafe_holding2;
760
761                         // Use a local exception context since the container is unsafe.
762                         try {
763                             while (!holding2.empty()) {
764                                 ptr_vector<Attribute>::auto_type ptr = holding2.pop_back();
765                                 unsafe_holding2.push_back(ptr.get());
766                                 ptr.release();
767                             }
768                             BasicFilteringContext fc(application, unsafe_holding2, policy.getIssuerMetadata());
769                             Locker filtlocker(m_filter.get());
770                             m_filter->filterAttributes(fc, unsafe_holding2);
771
772                             // Transfer back to safe container
773                             while (!unsafe_holding2.empty()) {
774                                 auto_ptr<Attribute> ptr(unsafe_holding2.back());
775                                 unsafe_holding2.pop_back();
776                                 holding2.push_back(ptr.get());
777                                 ptr.release();
778                             }
779                         }
780                         catch (std::exception& ex) {
781                             m_log.error("caught exception filtering attributes: %s", ex.what());
782                             m_log.error("dumping extracted attributes due to filtering exception");
783                             for_each(unsafe_holding2.begin(), unsafe_holding2.end(), xmltooling::cleanup<Attribute>());
784                             holding2.clear();   // in case the exception was during transfer between containers
785                         }
786                     }
787
788                     if (!holding2.empty()) {
789                         // Copy them over to the main holding tank, which transfers ownership.
790                         holding.transfer(holding.end(), holding2);
791                     }
792                 }
793                 catch (std::exception& ex) {
794                     // Known exceptions are handled gracefully by skipping the assertion.
795                     if (m_log.isDebugEnabled()) {
796                         auto_ptr_char tempid(assert->getID());
797                         auto_ptr_char eid(entityID);
798                         m_log.debug(
799                             "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
800                             tempid.get(),
801                             eid.get(),
802                             ex.what()
803                             );
804                     }
805                     continue;
806                 }
807             }
808         }
809
810         if (!holding.empty()) {
811             if (useCache) {
812                 locker.release();   // unguard to upgrade lock
813                 m_attrLock->unlock();
814                 m_attrLock->wrlock();
815                 SharedLock locker2(m_attrLock, false);   // pop the lock when we're done
816                 if (cacheEntry->second.count(container) == 0) {
817                     static void (vector<DDF>::* push_back)(DDF const &) = &vector<DDF>::push_back;
818                     vector<DDF>& marshalled = cacheEntry->second[container];
819                     for_each(
820                         holding.begin(), holding.end(),
821                         boost::bind(push_back, boost::ref(marshalled), boost::bind(&Attribute::marshall, _1))
822                         );
823                 }
824             }
825
826             // Copy them to the output parameter, which transfers ownership.
827             attributes.transfer(attributes.end(), holding);
828         }
829
830         // If the lock is held, it's guarded.
831
832         break;  // only process a single extension element
833     }
834 }
835
836 void XMLExtractor::extractAttributes(
837     const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
838     ) const
839 {
840     if (!m_impl)
841         return;
842
843     ptr_vector<Attribute> holding;
844     extractAttributes(application, request, issuer, xmlObject, holding);
845
846     // Transfer ownership from the ptr_vector to the unsafe vector for API compatibility.
847     // Any throws should leave each container in a consistent state. The holding container
848     // is freed by us, and the result container by the caller.
849     while (!holding.empty()) {
850         ptr_vector<Attribute>::auto_type ptr = holding.pop_back();
851         attributes.push_back(ptr.get());
852         ptr.release();
853     }
854 }
855
856 void XMLExtractor::extractAttributes(
857     const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, ptr_vector<Attribute>& attributes
858     ) const
859 {
860     static void (XMLExtractor::* extractEncrypted)(
861         const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&
862         ) const = &XMLExtractor::extractAttributes;
863     static void (XMLExtractorImpl::* extractV1Statement)(
864         const Application&, const GenericRequest*, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&
865         ) const = &XMLExtractorImpl::extractAttributes;
866
867     const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : nullptr;
868     const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
869
870     // Check for statements.
871     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::AttributeStatement::LOCAL_NAME)) {
872         const saml2::AttributeStatement* statement2 = dynamic_cast<const saml2::AttributeStatement*>(&xmlObject);
873         if (statement2) {
874             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
875             m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement2, attributes);
876             // Handle EncryptedAttributes inline so we have access to the role descriptor.
877             const vector<saml2::EncryptedAttribute*>& encattrs = statement2->getEncryptedAttributes();
878             for_each(
879                 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
880                 boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
881                 );
882             return;
883         }
884
885         const saml1::AttributeStatement* statement1 = dynamic_cast<const saml1::AttributeStatement*>(&xmlObject);
886         if (statement1) {
887             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
888             m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement1, attributes);
889             return;
890         }
891
892         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
893     }
894
895     // Check for assertions.
896     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
897         const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
898         if (token2) {
899             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
900             const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
901             for (indirect_iterator<vector<saml2::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
902                     s != make_indirect_iterator(statements.end()); ++s) {
903                 m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *s, attributes);
904                 // Handle EncryptedAttributes inline so we have access to the role descriptor.
905                 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement&>(*s).getEncryptedAttributes();
906                 for_each(
907                     make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
908                     boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
909                     );
910             }
911             return;
912         }
913
914         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
915         if (token1) {
916             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
917             const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
918             for_each(make_indirect_iterator(statements.begin()), make_indirect_iterator(statements.end()),
919                 boost::bind(extractV1Statement, m_impl.get(), boost::ref(application), request, assertingParty.get(), relyingParty, _1, boost::ref(attributes))
920                 );
921             return;
922         }
923
924         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
925     }
926
927     // Check for metadata.
928     if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
929         const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
930         const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : nullptr;
931         if (!entityToExtract)
932             throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
933         const Extensions* ext = entityToExtract->getExtensions();
934         if (ext) {
935             m_impl->extractAttributes(
936                 application,
937                 request,
938                 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
939                 entityToExtract->getEntityID(),
940                 relyingParty,
941                 *ext,
942                 attributes
943                 );
944         }
945         const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
946         while (group) {
947             ext = group->getExtensions();
948             if (ext) {
949                 m_impl->extractAttributes(
950                     application,
951                     request,
952                     dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
953                     nullptr,   // not an entity, so inline assertions won't be processed
954                     relyingParty,
955                     *ext,
956                     attributes
957                     );
958             }
959             group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
960         }
961         return;
962     }
963
964     // Check for attributes.
965     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
966         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
967         const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
968         if (attr2)
969             return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr2, attributes);
970
971         const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
972         if (attr1)
973             return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr1, attributes);
974
975         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
976     }
977
978     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
979         const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
980         if (encattr) {
981             const XMLCh* recipient = application.getXMLString("entityID").second;
982             CredentialResolver* cr = application.getCredentialResolver();
983             if (!cr) {
984                 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
985                 return;
986             }
987
988             try {
989                 Locker credlocker(cr);
990                 if (issuer) {
991                     MetadataCredentialCriteria mcc(*issuer);
992                     scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
993                     if (m_log.isDebugEnabled())
994                         m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
995                     return extractAttributes(application, request, issuer, *decrypted, attributes);
996                 }
997                 else {
998                     scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
999                     if (m_log.isDebugEnabled())
1000                         m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
1001                     return extractAttributes(application, request, issuer, *decrypted, attributes);
1002                 }
1003             }
1004             catch (std::exception& ex) {
1005                 m_log.error("failed to decrypt Attribute: %s", ex.what());
1006                 return;
1007             }
1008         }
1009     }
1010
1011     // Check for NameIDs.
1012     const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
1013     if (name2) {
1014         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1015         return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
1016     }
1017
1018     const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
1019     if (name1) {
1020         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1021         return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
1022     }
1023
1024     m_log.debug("unable to extract attributes, unknown XML object type: %s", xmlObject.getElementQName().toString().c_str());
1025 }
1026
1027 pair<bool,DOMElement*> XMLExtractor::background_load()
1028 {
1029     // Load from source using base class.
1030     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1031
1032     // If we own it, wrap it.
1033     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1034
1035     scoped_ptr<XMLExtractorImpl> impl(new XMLExtractorImpl(raw.second, m_log));
1036
1037     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1038     impl->setDocument(docjanitor.release());
1039
1040     // Perform the swap inside a lock.
1041     if (m_lock)
1042         m_lock->wrlock();
1043     SharedLock locker(m_lock, false);
1044     m_impl.swap(impl);
1045
1046     return make_pair(false,(DOMElement*)nullptr);
1047 }