807e798db805395c7ad143d03f013439cb3ab911
[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< 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         pair< boost::shared_ptr<AttributeDecoder>,vector<string> >& decl = m_attrMap[pair<xstring,xstring>(name,format)];
324         if (decl.first) {
325             m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
326             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
327             continue;
328         }
329
330         if (m_log.isInfoEnabled()) {
331             auto_ptr_char n(name);
332             auto_ptr_char f(format);
333             m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
334         }
335
336         decl.first = decoder;
337         decl.second.push_back(id.get());
338         m_attributeIds.push_back(id.get());
339
340         // Check for isRequired/isRequested.
341         bool requested = XMLHelper::getAttrBool(child, false, isRequested);
342         bool required = XMLHelper::getAttrBool(child, false, RequestedAttribute::ISREQUIRED_ATTRIB_NAME);
343         if (required || requested)
344             m_requestedAttrs.push_back(tuple<xstring,xstring,bool>(name,format,required));
345
346         name = child->getAttributeNS(nullptr, _aliases);
347         if (name && *name) {
348             m_log.warn("attribute mapping rule (%s) uses deprecated aliases feature, consider revising", id.get());
349             auto_ptr_char aliases(name);
350             string dup(aliases.get());
351             set<string> new_aliases;
352             split(new_aliases, dup, is_space(), algorithm::token_compress_on);
353             set<string>::iterator ru = new_aliases.find("REMOTE_USER");
354             if (ru != new_aliases.end()) {
355                 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
356                 new_aliases.erase(ru);
357             }
358             decl.second.insert(decl.second.end(), new_aliases.begin(), new_aliases.end());
359             m_attributeIds.insert(m_attributeIds.end(), new_aliases.begin(), new_aliases.end());
360         }
361
362         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
363     }
364
365     if (m_metaAttrCaching)
366         m_attrLock.reset(RWLock::create());
367 }
368
369 void XMLExtractorImpl::generateMetadata(SPSSODescriptor& role) const
370 {
371     if (m_requestedAttrs.empty())
372         return;
373     int index = 1;
374     const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(&role)->getAttributeConsumingServices();
375     for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
376         pair<bool,int> i = (*s)->getIndex();
377         if (i.first && index == i.second)
378             index = i.second + 1;
379     }
380     AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
381     role.getAttributeConsumingServices().push_back(svc);
382     svc->setIndex(index);
383     ServiceName* sn = ServiceNameBuilder::buildServiceName();
384     svc->getServiceNames().push_back(sn);
385     sn->setName(dynamic_cast<EntityDescriptor*>(role.getParent())->getEntityID());
386     static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
387     sn->setLang(english);
388
389     for (vector< tuple<xstring,xstring,bool> >::const_iterator i = m_requestedAttrs.begin(); i != m_requestedAttrs.end(); ++i) {
390         RequestedAttribute* req = RequestedAttributeBuilder::buildRequestedAttribute();
391         svc->getRequestedAttributes().push_back(req);
392         req->setName(i->get<0>().c_str());
393         if (i->get<1>().empty())
394             req->setNameFormat(saml2::Attribute::URI_REFERENCE);
395         else
396             req->setNameFormat(i->get<1>().c_str());
397         if (i->get<2>())
398             req->isRequired(true);
399     }
400 }
401
402 void XMLExtractorImpl::extractAttributes(
403     const Application& application,
404     const char* assertingParty,
405     const char* relyingParty,
406     const NameIdentifier& nameid,
407     ptr_vector<Attribute>& attributes
408     ) const
409 {
410     const XMLCh* format = nameid.getFormat();
411     if (!format || !*format)
412         format = NameIdentifier::UNSPECIFIED;
413     attrmap_t::const_iterator rule;
414     if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
415         auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
416         if (a.get()) {
417             attributes.push_back(a.get());
418             a.release();
419         }
420     }
421     else if (m_log.isDebugEnabled()) {
422         auto_ptr_char temp(format);
423         m_log.debug("skipping unmapped NameIdentifier with format (%s)", temp.get());
424     }
425 }
426
427 void XMLExtractorImpl::extractAttributes(
428     const Application& application,
429     const char* assertingParty,
430     const char* relyingParty,
431     const NameID& nameid,
432     ptr_vector<Attribute>& attributes
433     ) const
434 {
435     const XMLCh* format = nameid.getFormat();
436     if (!format || !*format)
437         format = NameID::UNSPECIFIED;
438     attrmap_t::const_iterator rule;
439     if ((rule = m_attrMap.find(pair<xstring,xstring>(format,xstring()))) != m_attrMap.end()) {
440         auto_ptr<Attribute> a(rule->second.first->decode(nullptr, rule->second.second, &nameid, assertingParty, relyingParty));
441         if (a.get()) {
442             attributes.push_back(a.get());
443             a.release();
444         }
445     }
446     else if (m_log.isDebugEnabled()) {
447         auto_ptr_char temp(format);
448         m_log.debug("skipping unmapped NameID with format (%s)", temp.get());
449     }
450 }
451
452 void XMLExtractorImpl::extractAttributes(
453     const Application& application,
454     const GenericRequest* request,
455     const char* assertingParty,
456     const char* relyingParty,
457     const saml1::Attribute& attr,
458     ptr_vector<Attribute>& attributes
459     ) const
460 {
461     const XMLCh* name = attr.getAttributeName();
462     const XMLCh* format = attr.getAttributeNamespace();
463     if (!name || !*name)
464         return;
465     if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
466         format = &chNull;
467     attrmap_t::const_iterator rule;
468     if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
469         auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
470         if (a.get()) {
471             attributes.push_back(a.get());
472             a.release();
473         }
474     }
475     else if (m_log.isInfoEnabled()) {
476         auto_ptr_char temp1(name);
477         auto_ptr_char temp2(format);
478         m_log.info("skipping unmapped SAML 1.x Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Namespace:" : "", temp2.get());
479     }
480 }
481
482 void XMLExtractorImpl::extractAttributes(
483     const Application& application,
484     const GenericRequest* request,
485     const char* assertingParty,
486     const char* relyingParty,
487     const saml2::Attribute& attr,
488     ptr_vector<Attribute>& attributes
489     ) const
490 {
491     const XMLCh* name = attr.getName();
492     const XMLCh* format = attr.getNameFormat();
493     if (!name || !*name)
494         return;
495     if (!format || !*format)
496         format = saml2::Attribute::UNSPECIFIED;
497     else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
498         format = &chNull;
499     attrmap_t::const_iterator rule;
500     if ((rule = m_attrMap.find(pair<xstring,xstring>(name,format))) != m_attrMap.end()) {
501         auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
502         if (a.get()) {
503             attributes.push_back(a.get());
504             a.release();
505             return;
506         }
507     }
508     else if (XMLString::equals(format, saml2::Attribute::UNSPECIFIED)) {
509         // As a fallback, if the format is "unspecified", null out the value and re-map.
510         if ((rule = m_attrMap.find(pair<xstring,xstring>(name,xstring()))) != m_attrMap.end()) {
511             auto_ptr<Attribute> a(rule->second.first->decode(request, rule->second.second, &attr, assertingParty, relyingParty));
512             if (a.get()) {
513                 attributes.push_back(a.get());
514                 a.release();
515                 return;
516             }
517         }
518     }
519
520     if (m_log.isInfoEnabled()) {
521         auto_ptr_char temp1(name);
522         auto_ptr_char temp2(format);
523         m_log.info("skipping unmapped SAML 2.0 Attribute with Name: %s%s%s", temp1.get(), *temp2.get() ? ", Format:" : "", temp2.get());
524     }
525 }
526
527 void XMLExtractorImpl::extractAttributes(
528     const Application& application,
529     const GenericRequest* request,
530     const char* assertingParty,
531     const char* relyingParty,
532     const saml1::AttributeStatement& statement,
533     ptr_vector<Attribute>& attributes
534     ) const
535 {
536     static void (XMLExtractorImpl::* extract)(
537         const Application&, const GenericRequest*, const char*, const char*, const saml1::Attribute&, ptr_vector<Attribute>&
538         ) const = &XMLExtractorImpl::extractAttributes;
539     for_each(
540         make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
541         boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
542         );
543 }
544
545 void XMLExtractorImpl::extractAttributes(
546     const Application& application,
547     const GenericRequest* request,
548     const char* assertingParty,
549     const char* relyingParty,
550     const saml2::AttributeStatement& statement,
551     ptr_vector<Attribute>& attributes
552     ) const
553 {
554     static void (XMLExtractorImpl::* extract)(
555         const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
556         ) const = &XMLExtractorImpl::extractAttributes;
557     for_each(
558         make_indirect_iterator(statement.getAttributes().begin()), make_indirect_iterator(statement.getAttributes().end()),
559         boost::bind(extract, this, boost::cref(application), request, assertingParty, relyingParty, _1, boost::ref(attributes))
560         );
561 }
562
563 void XMLExtractorImpl::extractAttributes(
564     const Application& application,
565     const GenericRequest* request,
566     const ObservableMetadataProvider* observable,
567     const XMLCh* entityID,
568     const char* relyingParty,
569     const Extensions& ext,
570     ptr_vector<Attribute>& attributes
571     ) const
572 {
573     const vector<XMLObject*>& exts = ext.getUnknownXMLObjects();
574     for (vector<XMLObject*>::const_iterator i = exts.begin(); i != exts.end(); ++i) {
575         const EntityAttributes* container = dynamic_cast<const EntityAttributes*>(*i);
576         if (!container)
577             continue;
578
579         bool useCache = false;
580         map<const ObservableMetadataProvider*,decoded_t>::iterator cacheEntry;
581
582         // Check for cached result.
583         if (observable && m_metaAttrCaching) {
584             m_attrLock->rdlock();
585             cacheEntry = m_decodedMap.find(observable);
586             if (cacheEntry == m_decodedMap.end()) {
587                 // We need to elevate the lock and retry.
588                 m_attrLock->unlock();
589                 m_attrLock->wrlock();
590                 cacheEntry = m_decodedMap.find(observable);
591                 if (cacheEntry == m_decodedMap.end()) {
592                     SharedLock locker(m_attrLock, false);   // guard in case these throw
593
594                     // It's still brand new, so hook it for cache activation.
595                     observable->addObserver(this);
596
597                     // Prime the map reference with an empty decoded map.
598                     cacheEntry = m_decodedMap.insert(make_pair(observable,decoded_t())).first;
599
600                     // Downgrade the lock.
601                     // We don't have to recheck because we never erase the master map entry entirely, even on changes.
602                     locker.release();   // unguard for lock downgrade
603                     m_attrLock->unlock();
604                     m_attrLock->rdlock();
605                 }
606             }
607             useCache = true;
608         }
609
610         if (useCache) {
611             // We're holding the lock, so check the cache.
612             decoded_t::iterator d = cacheEntry->second.find(container);
613             if (d != cacheEntry->second.end()) {
614                 SharedLock locker(m_attrLock, false);   // pop the lock when we're done
615                 for (vector<DDF>::iterator obj = d->second.begin(); obj != d->second.end(); ++obj) {
616                     auto_ptr<Attribute> wrapper(Attribute::unmarshall(*obj));
617                     m_log.debug("recovered cached metadata attribute (%s)", wrapper->getId());
618                     attributes.push_back(wrapper.get());
619                     wrapper.release();
620                 }
621                 break;
622             }
623         }
624
625         // Add a guard for the lock if we're caching.
626         SharedLock locker(useCache ? m_attrLock.get() : nullptr, false);
627
628         // Use a holding area to support caching.
629         ptr_vector<Attribute> holding;
630
631         // Extract attributes into holding area with no asserting party set.
632         static void (XMLExtractorImpl::* extractV2Attr)(
633             const Application&, const GenericRequest*, const char*, const char*, const saml2::Attribute&, ptr_vector<Attribute>&
634             ) const = &XMLExtractorImpl::extractAttributes;
635         for_each(
636             make_indirect_iterator(container->getAttributes().begin()), make_indirect_iterator(container->getAttributes().end()),
637             boost::bind(extractV2Attr, this, boost::ref(application), request, (const char*)nullptr, relyingParty, _1, boost::ref(holding))
638             );
639
640         if (entityID && m_entityAssertions) {
641             const vector<saml2::Assertion*>& asserts = container->getAssertions();
642             for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> assert = make_indirect_iterator(asserts.begin());
643                     assert != make_indirect_iterator(asserts.end()); ++assert) {
644                 if (!(assert->getSignature())) {
645                     if (m_log.isDebugEnabled()) {
646                         auto_ptr_char eid(entityID);
647                         m_log.debug("skipping unsigned assertion in metadata extension for entity (%s)", eid.get());
648                     }
649                     continue;
650                 }
651                 else if (assert->getAttributeStatements().empty()) {
652                     if (m_log.isDebugEnabled()) {
653                         auto_ptr_char eid(entityID);
654                         m_log.debug("skipping assertion with no AttributeStatement in metadata extension for entity (%s)", eid.get());
655                     }
656                     continue;
657                 }
658                 else {
659                     // Check subject.
660                     const NameID* subject = assert->getSubject() ? assert->getSubject()->getNameID() : nullptr;
661                     if (!subject ||
662                             !XMLString::equals(subject->getFormat(), NameID::ENTITY) ||
663                             !XMLString::equals(subject->getName(), entityID)) {
664                         if (m_log.isDebugEnabled()) {
665                             auto_ptr_char eid(entityID);
666                             m_log.debug("skipping assertion with improper Subject in metadata extension for entity (%s)", eid.get());
667                         }
668                         continue;
669                     }
670                 }
671
672                 try {
673                     // Set up and evaluate a policy for an AA asserting attributes to us.
674                     shibsp::SecurityPolicy policy(application, &AttributeAuthorityDescriptor::ELEMENT_QNAME, false, m_policyId.c_str());
675                     Locker locker(m_metadata.get());
676                     if (m_metadata)
677                         policy.setMetadataProvider(m_metadata.get());
678                     if (m_trust)
679                         policy.setTrustEngine(m_trust.get());
680                     // Populate recipient as audience.
681                     const XMLCh* issuer = assert->getIssuer() ? assert->getIssuer()->getName() : nullptr;
682                     policy.getAudiences().push_back(application.getRelyingParty(issuer)->getXMLString("entityID").second);
683
684                     // Extract assertion information for policy.
685                     policy.setMessageID(assert->getID());
686                     policy.setIssueInstant(assert->getIssueInstantEpoch());
687                     policy.setIssuer(assert->getIssuer());
688
689                     // Look up metadata for issuer.
690                     if (policy.getIssuer() && policy.getMetadataProvider()) {
691                         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
692                             m_log.debug("non-system entity issuer, skipping metadata lookup");
693                         }
694                         else {
695                             m_log.debug("searching metadata for entity assertion issuer...");
696                             pair<const EntityDescriptor*,const RoleDescriptor*> lookup;
697                             MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
698                             mc.entityID_unicode = policy.getIssuer()->getName();
699                             mc.role = &AttributeAuthorityDescriptor::ELEMENT_QNAME;
700                             mc.protocol = samlconstants::SAML20P_NS;
701                             lookup = policy.getMetadataProvider()->getEntityDescriptor(mc);
702                             if (!lookup.first) {
703                                 auto_ptr_char iname(policy.getIssuer()->getName());
704                                 m_log.debug("no metadata found, can't establish identity of issuer (%s)", iname.get());
705                             }
706                             else if (!lookup.second) {
707                                 m_log.debug("unable to find compatible AA role in metadata");
708                             }
709                             else {
710                                 policy.setIssuerMetadata(lookup.second);
711                             }
712                         }
713                     }
714
715                     // Authenticate the assertion. We have to clone and marshall it to establish the signature for verification.
716                     scoped_ptr<saml2::Assertion> tokencopy(assert->cloneAssertion());
717                     tokencopy->marshall();
718                     policy.evaluate(*tokencopy);
719                     if (!policy.isAuthenticated()) {
720                         if (m_log.isDebugEnabled()) {
721                             auto_ptr_char tempid(tokencopy->getID());
722                             auto_ptr_char eid(entityID);
723                             m_log.debug(
724                                 "failed to authenticate assertion (%s) in metadata extension for entity (%s)", tempid.get(), eid.get()
725                                 );
726                         }
727                         continue;
728                     }
729
730                     // Override the asserting/relying party names based on this new issuer.
731                     const EntityDescriptor* inlineEntity =
732                         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
733                     auto_ptr_char inlineAssertingParty(inlineEntity ? inlineEntity->getEntityID() : nullptr);
734                     relyingParty = application.getRelyingParty(inlineEntity)->getString("entityID").second;
735
736                     // Use a private holding area for filtering purposes.
737                     ptr_vector<Attribute> holding2;
738                     const vector<saml2::Attribute*>& attrs2 =
739                         const_cast<const saml2::AttributeStatement*>(tokencopy->getAttributeStatements().front())->getAttributes();
740                     for_each(
741                         make_indirect_iterator(attrs2.begin()), make_indirect_iterator(attrs2.end()),
742                         boost::bind(extractV2Attr, this, boost::ref(application), request, inlineAssertingParty.get(), relyingParty, _1, boost::ref(holding2))
743                         );
744
745                     // Now we locally filter the attributes so that the actual issuer can be properly set.
746                     // If we relied on outside filtering, the attributes couldn't be distinguished from the
747                     // ones that come from the user's IdP.
748                     if (m_filter && !holding2.empty()) {
749
750                         // The filter API uses an unsafe container, so we have to transfer everything into one and back.
751                         vector<Attribute*> unsafe_holding2;
752
753                         // Use a local exception context since the container is unsafe.
754                         try {
755                             while (!holding2.empty()) {
756                                 ptr_vector<Attribute>::auto_type ptr = holding2.pop_back();
757                                 unsafe_holding2.push_back(ptr.get());
758                                 ptr.release();
759                             }
760                             BasicFilteringContext fc(application, unsafe_holding2, policy.getIssuerMetadata());
761                             Locker filtlocker(m_filter.get());
762                             m_filter->filterAttributes(fc, unsafe_holding2);
763
764                             // Transfer back to safe container
765                             while (!unsafe_holding2.empty()) {
766                                 auto_ptr<Attribute> ptr(unsafe_holding2.back());
767                                 unsafe_holding2.pop_back();
768                                 holding2.push_back(ptr.get());
769                                 ptr.release();
770                             }
771                         }
772                         catch (std::exception& ex) {
773                             m_log.error("caught exception filtering attributes: %s", ex.what());
774                             m_log.error("dumping extracted attributes due to filtering exception");
775                             for_each(unsafe_holding2.begin(), unsafe_holding2.end(), xmltooling::cleanup<Attribute>());
776                             holding2.clear();   // in case the exception was during transfer between containers
777                         }
778                     }
779
780                     if (!holding2.empty()) {
781                         // Copy them over to the main holding tank, which transfers ownership.
782                         holding.transfer(holding.end(), holding2);
783                     }
784                 }
785                 catch (std::exception& ex) {
786                     // Known exceptions are handled gracefully by skipping the assertion.
787                     if (m_log.isDebugEnabled()) {
788                         auto_ptr_char tempid(assert->getID());
789                         auto_ptr_char eid(entityID);
790                         m_log.debug(
791                             "exception authenticating assertion (%s) in metadata extension for entity (%s): %s",
792                             tempid.get(),
793                             eid.get(),
794                             ex.what()
795                             );
796                     }
797                     continue;
798                 }
799             }
800         }
801
802         if (!holding.empty()) {
803             if (useCache) {
804                 locker.release();   // unguard to upgrade lock
805                 m_attrLock->unlock();
806                 m_attrLock->wrlock();
807                 SharedLock locker2(m_attrLock, false);   // pop the lock when we're done
808                 if (cacheEntry->second.count(container) == 0) {
809                     static void (vector<DDF>::* push_back)(DDF const &) = &vector<DDF>::push_back;
810                     vector<DDF>& marshalled = cacheEntry->second[container];
811                     for_each(
812                         holding.begin(), holding.end(),
813                         boost::bind(push_back, boost::ref(marshalled), boost::bind(&Attribute::marshall, _1))
814                         );
815                 }
816             }
817
818             // Copy them to the output parameter, which transfers ownership.
819             attributes.transfer(attributes.end(), holding);
820         }
821
822         // If the lock is held, it's guarded.
823
824         break;  // only process a single extension element
825     }
826 }
827
828 void XMLExtractor::extractAttributes(
829     const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
830     ) const
831 {
832     if (!m_impl)
833         return;
834
835     ptr_vector<Attribute> holding;
836     extractAttributes(application, request, issuer, xmlObject, holding);
837
838     // Transfer ownership from the ptr_vector to the unsafe vector for API compatibility.
839     // Any throws should leave each container in a consistent state. The holding container
840     // is freed by us, and the result container by the caller.
841     while (!holding.empty()) {
842         ptr_vector<Attribute>::auto_type ptr = holding.pop_back();
843         attributes.push_back(ptr.get());
844         ptr.release();
845     }
846 }
847
848 void XMLExtractor::extractAttributes(
849     const Application& application, const GenericRequest* request, const RoleDescriptor* issuer, const XMLObject& xmlObject, ptr_vector<Attribute>& attributes
850     ) const
851 {
852     static void (XMLExtractor::* extractEncrypted)(
853         const Application&, const GenericRequest*, const RoleDescriptor*, const XMLObject&, ptr_vector<Attribute>&
854         ) const = &XMLExtractor::extractAttributes;
855     static void (XMLExtractorImpl::* extractV1Statement)(
856         const Application&, const GenericRequest*, const char*, const char*, const saml1::AttributeStatement&, ptr_vector<Attribute>&
857         ) const = &XMLExtractorImpl::extractAttributes;
858
859     const EntityDescriptor* entity = issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent()) : nullptr;
860     const char* relyingParty = application.getRelyingParty(entity)->getString("entityID").second;
861
862     // Check for statements.
863     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::AttributeStatement::LOCAL_NAME)) {
864         const saml2::AttributeStatement* statement2 = dynamic_cast<const saml2::AttributeStatement*>(&xmlObject);
865         if (statement2) {
866             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
867             m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement2, attributes);
868             // Handle EncryptedAttributes inline so we have access to the role descriptor.
869             const vector<saml2::EncryptedAttribute*>& encattrs = statement2->getEncryptedAttributes();
870             for_each(
871                 make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
872                 boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
873                 );
874             return;
875         }
876
877         const saml1::AttributeStatement* statement1 = dynamic_cast<const saml1::AttributeStatement*>(&xmlObject);
878         if (statement1) {
879             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
880             m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *statement1, attributes);
881             return;
882         }
883
884         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
885     }
886
887     // Check for assertions.
888     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
889         const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
890         if (token2) {
891             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
892             const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
893             for (indirect_iterator<vector<saml2::AttributeStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
894                     s != make_indirect_iterator(statements.end()); ++s) {
895                 m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *s, attributes);
896                 // Handle EncryptedAttributes inline so we have access to the role descriptor.
897                 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement&>(*s).getEncryptedAttributes();
898                 for_each(
899                     make_indirect_iterator(encattrs.begin()), make_indirect_iterator(encattrs.end()),
900                     boost::bind(extractEncrypted, this, boost::ref(application), request, issuer, _1, boost::ref(attributes))
901                     );
902             }
903             return;
904         }
905
906         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
907         if (token1) {
908             auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
909             const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
910             for_each(make_indirect_iterator(statements.begin()), make_indirect_iterator(statements.end()),
911                 boost::bind(extractV1Statement, m_impl.get(), boost::ref(application), request, assertingParty.get(), relyingParty, _1, boost::ref(attributes))
912                 );
913             return;
914         }
915
916         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
917     }
918
919     // Check for metadata.
920     if (XMLString::equals(xmlObject.getElementQName().getNamespaceURI(), samlconstants::SAML20MD_NS)) {
921         const RoleDescriptor* roleToExtract = dynamic_cast<const RoleDescriptor*>(&xmlObject);
922         const EntityDescriptor* entityToExtract = roleToExtract ? dynamic_cast<const EntityDescriptor*>(roleToExtract->getParent()) : nullptr;
923         if (!entityToExtract)
924             throw AttributeExtractionException("Unable to extract attributes, unknown metadata object type.");
925         const Extensions* ext = entityToExtract->getExtensions();
926         if (ext) {
927             m_impl->extractAttributes(
928                 application,
929                 request,
930                 dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
931                 entityToExtract->getEntityID(),
932                 relyingParty,
933                 *ext,
934                 attributes
935                 );
936         }
937         const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(entityToExtract->getParent());
938         while (group) {
939             ext = group->getExtensions();
940             if (ext) {
941                 m_impl->extractAttributes(
942                     application,
943                     request,
944                     dynamic_cast<const ObservableMetadataProvider*>(application.getMetadataProvider(false)),
945                     nullptr,   // not an entity, so inline assertions won't be processed
946                     relyingParty,
947                     *ext,
948                     attributes
949                     );
950             }
951             group = dynamic_cast<const EntitiesDescriptor*>(group->getParent());
952         }
953         return;
954     }
955
956     // Check for attributes.
957     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
958         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
959         const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
960         if (attr2)
961             return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr2, attributes);
962
963         const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
964         if (attr1)
965             return m_impl->extractAttributes(application, request, assertingParty.get(), relyingParty, *attr1, attributes);
966
967         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
968     }
969
970     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
971         const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
972         if (encattr) {
973             const XMLCh* recipient = application.getXMLString("entityID").second;
974             CredentialResolver* cr = application.getCredentialResolver();
975             if (!cr) {
976                 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
977                 return;
978             }
979
980             try {
981                 Locker credlocker(cr);
982                 if (issuer) {
983                     MetadataCredentialCriteria mcc(*issuer);
984                     scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
985                     if (m_log.isDebugEnabled())
986                         m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
987                     return extractAttributes(application, request, issuer, *decrypted, attributes);
988                 }
989                 else {
990                     scoped_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
991                     if (m_log.isDebugEnabled())
992                         m_log.debugStream() << "decrypted Attribute: " << *decrypted << logging::eol;
993                     return extractAttributes(application, request, issuer, *decrypted, attributes);
994                 }
995             }
996             catch (std::exception& ex) {
997                 m_log.error("failed to decrypt Attribute: %s", ex.what());
998                 return;
999             }
1000         }
1001     }
1002
1003     // Check for NameIDs.
1004     const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
1005     if (name2) {
1006         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1007         return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name2, attributes);
1008     }
1009
1010     const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
1011     if (name1) {
1012         auto_ptr_char assertingParty(entity ? entity->getEntityID() : nullptr);
1013         return m_impl->extractAttributes(application, assertingParty.get(), relyingParty, *name1, attributes);
1014     }
1015
1016     m_log.debug("unable to extract attributes, unknown XML object type: %s", xmlObject.getElementQName().toString().c_str());
1017 }
1018
1019 pair<bool,DOMElement*> XMLExtractor::background_load()
1020 {
1021     // Load from source using base class.
1022     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1023
1024     // If we own it, wrap it.
1025     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
1026
1027     scoped_ptr<XMLExtractorImpl> impl(new XMLExtractorImpl(raw.second, m_log));
1028
1029     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1030     impl->setDocument(docjanitor.release());
1031
1032     // Perform the swap inside a lock.
1033     if (m_lock)
1034         m_lock->wrlock();
1035     SharedLock locker(m_lock, false);
1036     m_impl.swap(impl);
1037
1038     return make_pair(false,(DOMElement*)nullptr);
1039 }