Added a strict flag to permit loose metadata lookup for contact info.
[shibboleth/sp.git] / xmlproviders / XMLMetadata.cpp
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /* XMLMetadata.cpp - a metadata implementation that uses an XML-based registry
51
52    Scott Cantor
53    9/27/02
54
55    $History:$
56 */
57
58 #include "internal.h"
59
60 #include <sys/types.h>
61 #include <sys/stat.h>
62
63 #include <log4cpp/Category.hh>
64 #include <xercesc/util/XMLChar.hpp>
65 #include <xsec/enc/XSECCryptoException.hpp>
66 #include <xsec/enc/XSECKeyInfoResolverDefault.hpp>
67 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
68
69 using namespace shibboleth;
70 using namespace saml;
71 using namespace log4cpp;
72 using namespace std;
73
74 namespace {
75
76     class XMLMetadataImpl : public ReloadableXMLFileImpl
77     {
78     public:
79         class ContactPerson : public IContactPerson
80         {
81         public:
82             ContactPerson(const DOMElement* e);
83             ~ContactPerson() {}
84         
85             ContactType getType() const { return m_type; }
86             const char* getCompany() const { return m_company.get(); }
87             const char* getGivenName() const { return m_givenName.get(); }
88             const char* getSurName() const { return m_surName.get(); }
89             Iterator<string> getEmailAddresses() const { return m_emails; }
90             Iterator<string> getTelephoneNumbers() const { return m_phones; }
91             const DOMElement* getElement() const { return m_root; }
92         
93         private:
94             const DOMElement* m_root;
95             ContactType m_type;
96             auto_ptr<char> m_givenName,m_surName,m_company;
97             vector<string> m_emails,m_phones;
98         };
99         
100         class Organization : public IOrganization
101         {
102         public:
103             Organization(const DOMElement* e);
104             ~Organization() {}
105             
106             const char* getName(const char* lang="en") const { return forLang(m_names,lang); }
107             const char* getDisplayName(const char* lang="en") const { return forLang(m_displays,lang); }
108             const char* getURL(const char* lang="en") const { return forLang(m_urls,lang); }
109             const DOMElement* getElement() const { return m_root; }
110         
111         private:
112             const char* forLang(const map<string,string>& m, const char* lang) const {
113                 map<string,string>::const_iterator i=m.find(lang);
114                 return (i==m.end()) ? NULL : i->second.c_str();
115             }
116             const DOMElement* m_root;
117             map<string,string> m_names,m_displays,m_urls;
118         };
119
120         class EntityDescriptor;
121         
122         class EncryptionMethod : public XENCEncryptionMethod
123         {
124         public:
125             EncryptionMethod(const DOMElement* e);
126             ~EncryptionMethod() {}
127             
128             const XMLCh * getAlgorithm(void) const { return m_alg; }
129             const XMLCh * getDigestMethod(void) const { return m_digest; }
130             const XMLCh * getOAEPparams(void) const { return m_params; }
131             int getKeySize(void) const { return m_size; }
132             DOMElement* getElement(void) const { return const_cast<DOMElement*>(m_root); }
133             void setDigestMethod(const XMLCh * method) {throw exception();}
134             void setOAEPparams(const XMLCh * params) {throw exception();}
135             void setKeySize(int size) {throw exception();}
136         
137         private:
138             const DOMElement* m_root;
139             const XMLCh* m_alg;
140             const XMLCh* m_digest;
141             const XMLCh* m_params;
142             int m_size;
143         };
144         
145         class KeyDescriptor : public IKeyDescriptor
146         {
147         public:
148             KeyDescriptor(const DOMElement* e);
149             ~KeyDescriptor();
150             
151             KeyUse getUse() const { return m_use; }
152             DSIGKeyInfoList* getKeyInfo() const { return m_klist; }
153             saml::Iterator<const XENCEncryptionMethod*> getEncryptionMethods() const { return m_methods; }
154             const DOMElement* getElement() const { return m_root; }
155         
156         private:
157             const DOMElement* m_root;
158             KeyUse m_use;
159             mutable DSIGKeyInfoList* m_klist;
160             vector<const XENCEncryptionMethod*> m_methods;
161         };
162         
163         class KeyAuthority : public IKeyAuthority
164         {
165         public:
166             KeyAuthority(const DOMElement* e);
167             ~KeyAuthority();
168             
169             int getVerifyDepth() const { return m_depth; }
170             Iterator<DSIGKeyInfoList*> getKeyInfos() const { return m_klists; }
171         
172         private:
173             int m_depth;
174             vector<DSIGKeyInfoList*> m_klists;
175         };
176         
177         class Role : public virtual IRoleDescriptor
178         {
179         public:
180             Role(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
181             ~Role();
182             
183             // External contract
184             const IEntityDescriptor* getEntityDescriptor() const {return m_provider;}
185             Iterator<const XMLCh*> getProtocolSupportEnumeration() const {return m_protocolEnum;}
186             bool hasSupport(const XMLCh* protocol) const;
187             const char* getErrorURL() const {return (m_errorURL ? m_errorURL : m_provider->getErrorURL());}
188             bool isValid() const {return time(NULL) < m_validUntil;}
189             Iterator<const IKeyDescriptor*> getKeyDescriptors() const {return m_keys;}
190             const IOrganization* getOrganization() const {return m_org ? m_org : m_provider->getOrganization();}
191             Iterator<const IContactPerson*> getContactPersons() const
192                 {return (m_contacts.empty() ? m_provider->getContactPersons() : m_contacts);}
193             const DOMElement* getElement() const {return m_root;}
194         
195         protected:
196             vector<const XMLCh*> m_protocolEnum;
197             vector<const IKeyDescriptor*> m_keys;
198
199         private:
200             const EntityDescriptor* m_provider;
201             const DOMElement* m_root;
202             XMLCh* m_protocolEnumCopy;
203             char* m_errorURL;
204             Organization* m_org;
205             vector<const IContactPerson*> m_contacts;
206             time_t m_validUntil;
207         };
208         
209         class Endpoint : public virtual IEndpoint
210         {
211         public:
212             Endpoint(const DOMElement* e) : m_root(e),
213                 m_binding(e->getAttributeNS(NULL,L(Binding))),
214                 m_location(e->getAttributeNS(NULL,SHIB_L(Location))),
215                 m_resploc(e->getAttributeNS(NULL,SHIB_L(ResponseLocation))) {}
216             Endpoint(const XMLCh* binding, const XMLCh* loc)
217                 : m_root(NULL), m_binding(binding), m_location(loc), m_resploc(NULL) {}
218             ~Endpoint() {}
219             
220             const XMLCh* getBinding() const { return m_binding; }
221             const XMLCh* getLocation() const { return m_location; }
222             const XMLCh* getResponseLocation() const { return m_resploc; }
223             const DOMElement* getElement() const { return m_root; }
224         
225         private:
226             const DOMElement* m_root;
227             const XMLCh* m_binding;
228             const XMLCh* m_location;
229             const XMLCh* m_resploc;
230         };
231         
232         class IndexedEndpoint : public Endpoint, public virtual IIndexedEndpoint
233         {
234         public:
235             IndexedEndpoint(const DOMElement* e) : Endpoint(e), m_index(XMLString::parseInt(e->getAttributeNS(NULL,SHIB_L(index)))) {}
236             unsigned short getIndex() const {return m_index;}
237             
238         private:
239             unsigned short m_index;
240         };
241         
242         class EndpointManager : public IEndpointManager
243         {
244         public:
245             EndpointManager() : m_soft(NULL), m_hard(NULL) {}
246             ~EndpointManager() {
247                 for (vector<const IEndpoint*>::iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++)
248                     delete const_cast<IEndpoint*>(*i);
249             }
250             saml::Iterator<const IEndpoint*> getEndpoints() const {return m_endpoints;}
251             const IEndpoint* getDefaultEndpoint() const {
252                 if (m_hard) return m_hard;
253                 if (m_soft) return m_soft;
254                 if (!m_endpoints.empty()) return *(m_endpoints.begin());
255                 return NULL;
256             }
257             const IEndpoint* getEndpointByIndex(unsigned short index) const {
258                 for (vector<const IEndpoint*>::const_iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++) {
259                     const IIndexedEndpoint* temp=dynamic_cast<const IIndexedEndpoint*>(*i);
260                     if (temp && index==temp->getIndex())
261                         return temp;
262                 }
263                 return NULL;
264             }
265             const IEndpoint* getEndpointByBinding(const XMLCh* binding) const {
266                 for (vector<const IEndpoint*>::const_iterator i=m_endpoints.begin(); i!=m_endpoints.end(); i++)
267                     if (!XMLString::compareString(binding,(*i)->getBinding()))
268                         return *i;
269                 return NULL;
270             }
271             void add(IEndpoint* e) {
272                 m_endpoints.push_back(e);
273                 if (!m_hard && e->getElement()) {
274                     const XMLCh* v=e->getElement()->getAttributeNS(NULL,SHIB_L(isDefault));
275                     if (v && (*v==chDigit_1 || *v==chLatin_t))  // explicit default
276                         m_hard=e;
277                     else if ((!v || !*v) && !m_soft)            // implicit default
278                         m_soft=e;
279                 }
280                 else if (!m_hard && !m_soft) {
281                     // No default yet, so this one qualifies as an implicit.
282                     m_soft=e;
283                 }
284             }
285             
286         private:
287             vector<const IEndpoint*> m_endpoints;
288             const IEndpoint* m_soft;    // Soft default (not explicit)
289             const IEndpoint* m_hard;    // Hard default (explicit)
290         };
291         
292         class SSORole : public Role, public virtual ISSODescriptor
293         {
294         public:
295             SSORole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
296             ~SSORole() {}
297             const IEndpointManager* getArtifactResolutionServiceManager() const {return &m_artifact;}
298             const IEndpointManager* getSingleLogoutServiceManager() const {return &m_logout;}
299             const IEndpointManager* getManageNameIDServiceManager() const {return &m_nameid;}
300             saml::Iterator<const XMLCh*> getNameIDFormats() const {return m_formats;}
301             
302         private:
303             EndpointManager m_artifact,m_logout,m_nameid;
304             vector<const XMLCh*> m_formats;
305         };
306
307         class ScopedRole : public virtual IScopedRoleDescriptor
308         {
309         public:
310             ScopedRole(const DOMElement* e);
311             saml::Iterator<std::pair<const XMLCh*,bool> > getScopes() const {return m_scopes;}
312
313         private:
314             vector<pair<const XMLCh*,bool> > m_scopes;
315         };
316         
317         class IDPRole : public SSORole, public ScopedRole, public virtual IIDPSSODescriptor
318         {
319         public:
320             IDPRole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
321             ~IDPRole();
322             bool getWantAuthnRequestsSigned() const {return m_wantAuthnRequestsSigned;}
323             const IEndpointManager* getSingleSignOnServiceManager() const {return &m_sso;}
324             const IEndpointManager* getNameIDMappingServiceManager() const {return &m_mapping;}
325             const IEndpointManager* getAssertionIDRequestServiceManager() const {return &m_idreq;}
326             saml::Iterator<const XMLCh*> getAttributeProfiles() const {return m_attrprofs;}
327             saml::Iterator<const saml::SAMLAttribute*> getAttributes() const {return m_attrs;}
328         
329         private:
330             EndpointManager m_sso,m_mapping,m_idreq;
331             vector<const XMLCh*> m_attrprofs;
332             vector<const SAMLAttribute*> m_attrs;
333             bool m_wantAuthnRequestsSigned;
334             const XMLCh* m_sourceId;
335             friend class EntityDescriptor;
336         };
337
338         class AARole : public Role, public ScopedRole, public virtual IAttributeAuthorityDescriptor
339         {
340         public:
341             AARole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e);
342             ~AARole();
343             const IEndpointManager* getAttributeServiceManager() const {return &m_query;}
344             const IEndpointManager* getAssertionIDRequestServiceManager() const {return &m_idreq;}
345             saml::Iterator<const XMLCh*> getNameIDFormats() const {return m_formats;}
346             saml::Iterator<const XMLCh*> getAttributeProfiles() const {return m_attrprofs;}
347             saml::Iterator<const saml::SAMLAttribute*> getAttributes() const {return m_attrs;}
348         
349         private:
350             EndpointManager m_query,m_idreq;
351             vector<const XMLCh*> m_formats,m_attrprofs;
352             vector<const SAMLAttribute*> m_attrs;
353         };
354     
355         class EntityDescriptor : public IExtendedEntityDescriptor
356         {
357         public:
358             EntityDescriptor(
359                 const DOMElement* e,
360                 XMLMetadataImpl* wrapper,
361                 time_t validUntil=LONG_MAX,
362                 const IEntitiesDescriptor* parent=NULL
363                 );
364             ~EntityDescriptor();
365         
366             // External contract
367             const XMLCh* getId() const {return m_id;}
368             bool isValid() const {return time(NULL) < m_validUntil;}
369             Iterator<const IRoleDescriptor*> getRoleDescriptors() const {return m_roles;}
370             const IIDPSSODescriptor* getIDPSSODescriptor(const XMLCh* protocol) const;
371             const ISPSSODescriptor* getSPSSODescriptor(const XMLCh* protocol) const {return NULL;}
372             const IAuthnAuthorityDescriptor* getAuthnAuthorityDescriptor(const XMLCh* protocol) const {return NULL;}
373             const IAttributeAuthorityDescriptor* getAttributeAuthorityDescriptor(const XMLCh* protocol) const;
374             const IPDPDescriptor* getPDPDescriptor(const XMLCh* protocol) const {return NULL;}
375             const IAffiliationDescriptor* getAffiliationDescriptor() const {return NULL;}
376             const IOrganization* getOrganization() const {return m_org;}
377             Iterator<const IContactPerson*> getContactPersons() const {return m_contacts;}
378             Iterator<pair<const XMLCh*,const XMLCh*> > getAdditionalMetadataLocations() const {return m_locs;}
379             const IEntitiesDescriptor* getEntitiesDescriptor() const {return m_parent;}
380             Iterator<const IKeyAuthority*> getKeyAuthorities() const {return m_keyauths;}
381             const DOMElement* getElement() const {return m_root;}
382
383             // Used internally
384             const char* getErrorURL() const {return m_errorURL.get();}
385             time_t getValidUntil() const {return m_validUntil;}
386         private:
387             const DOMElement* m_root;
388             const IEntitiesDescriptor* m_parent;
389             const XMLCh* m_id;
390             auto_ptr<char> m_errorURL;
391             IOrganization* m_org;
392             vector<const IContactPerson*> m_contacts;
393             vector<const IRoleDescriptor*> m_roles;
394             vector<pair<const XMLCh*,const XMLCh*> > m_locs;
395             vector<const IKeyAuthority*> m_keyauths;
396             time_t m_validUntil;
397         };
398
399         class EntitiesDescriptor : public IExtendedEntitiesDescriptor
400         {
401         public:
402             EntitiesDescriptor(
403                 const DOMElement* e,
404                 XMLMetadataImpl* wrapper,
405                 time_t validUntil=LONG_MAX,
406                 const IEntitiesDescriptor* parent=NULL
407                 );
408             ~EntitiesDescriptor();
409             
410             const XMLCh* getName() const {return m_name;}
411             bool isValid() const {return time(NULL) < m_validUntil;}
412             const IEntitiesDescriptor* getEntitiesDescriptor() const {return m_parent;}
413             Iterator<const IEntitiesDescriptor*> getEntitiesDescriptors() const {return m_groups;}
414             Iterator<const IEntityDescriptor*> getEntityDescriptors() const {return m_providers;}
415             Iterator<const IKeyAuthority*> getKeyAuthorities() const {return m_keyauths;}
416             const DOMElement* getElement() const {return m_root;}
417         
418         private:
419             const DOMElement* m_root;
420             const IEntitiesDescriptor* m_parent;
421             const XMLCh* m_name;
422             vector<const IEntitiesDescriptor*> m_groups;
423             vector<const IEntityDescriptor*> m_providers;
424             vector<const IKeyAuthority*> m_keyauths;
425             time_t m_validUntil;
426         };
427
428         XMLMetadataImpl(const char* pathname) : ReloadableXMLFileImpl(pathname), m_rootProvider(NULL), m_rootGroup(NULL) { init(); }
429         XMLMetadataImpl(const DOMElement* e) : ReloadableXMLFileImpl(e), m_rootProvider(NULL), m_rootGroup(NULL) { init(); }
430         void init();
431         ~XMLMetadataImpl();
432
433         typedef multimap<string,const EntityDescriptor*> sitemap_t;
434         sitemap_t m_sites;
435         sitemap_t m_sources;
436         EntityDescriptor* m_rootProvider;
437         EntitiesDescriptor* m_rootGroup;
438     };
439
440     class XMLMetadata : public IMetadata, public ReloadableXMLFile
441     {
442     public:
443         XMLMetadata(const DOMElement* e) : ReloadableXMLFile(e), m_exclusions(true) {
444             static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
445             if (e->hasAttributeNS(NULL,uri)) {
446                 // First check for explicit enablement of entities.
447                 DOMNodeList* nlist=e->getElementsByTagName(SHIB_L(Include));
448                 for (int i=0; nlist && i<nlist->getLength(); i++) {
449                     if (nlist->item(i)->hasChildNodes()) {
450                         auto_ptr_char temp(nlist->item(i)->getFirstChild()->getNodeValue());
451                         if (temp.get()) {
452                             m_set.insert(temp.get());
453                             m_exclusions=false;
454                         }
455                     }
456                 }
457                 // If there was no explicit enablement, build a set of exclusions.
458                 if (m_exclusions) {
459                     nlist=e->getElementsByTagName(SHIB_L(Exclude));
460                     for (int j=0; nlist && j<nlist->getLength(); j++) {
461                         if (nlist->item(j)->hasChildNodes()) {
462                             auto_ptr_char temp(nlist->item(j)->getFirstChild()->getNodeValue());
463                             if (temp.get())
464                                 m_set.insert(temp.get());
465                         }
466                     }
467                 }
468             }
469         }
470         ~XMLMetadata() {}
471
472         const IEntityDescriptor* lookup(const char* providerId, bool strict=true) const;
473         const IEntityDescriptor* lookup(const XMLCh* providerId, bool strict=true) const;
474         const IEntityDescriptor* lookup(const saml::SAMLArtifact* artifact) const;
475         
476     protected:
477         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
478         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
479         
480     private:
481         bool m_exclusions;
482         set<string> m_set;
483     };
484 }
485
486 IPlugIn* XMLMetadataFactory(const DOMElement* e)
487 {
488     auto_ptr<XMLMetadata> m(new XMLMetadata(e));
489     m->getImplementation();
490     return m.release();
491 }
492
493 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const DOMElement* e, bool first) const
494 {
495     return new XMLMetadataImpl(e);
496 }
497
498 ReloadableXMLFileImpl* XMLMetadata::newImplementation(const char* pathname, bool first) const
499 {
500     return new XMLMetadataImpl(pathname);
501 }
502
503 XMLMetadataImpl::ContactPerson::ContactPerson(const DOMElement* e) : m_root(e)
504 {
505     const XMLCh* type=NULL;
506     
507     // Old metadata or new?
508     if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(Contact))) {
509         type=e->getAttributeNS(NULL,SHIB_L(Type));
510         m_surName=auto_ptr<char>(toUTF8(e->getAttributeNS(NULL,SHIB_L(Name))));
511         if (e->hasAttributeNS(NULL,SHIB_L(Email))) {
512             auto_ptr<char> temp(toUTF8(e->getAttributeNS(NULL,SHIB_L(Email))));
513             if (temp.get())
514                 m_emails.push_back(temp.get());
515         }
516     }
517     else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
518         type=e->getAttributeNS(NULL,SHIB_L(contactType));
519         DOMNode* n=NULL;
520         e=saml::XML::getFirstChildElement(e);
521         while (e) {
522             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Company))) {
523                 n=e->getFirstChild();
524                 if (n) m_company=auto_ptr<char>(toUTF8(n->getNodeValue()));
525             }
526             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(GivenName))) {
527                 n=e->getFirstChild();
528                 if (n) m_givenName=auto_ptr<char>(toUTF8(n->getNodeValue()));
529             }
530             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(SurName))) {
531                 n=e->getFirstChild();
532                 if (n) m_surName=auto_ptr<char>(toUTF8(n->getNodeValue()));
533             }
534             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EmailAddress))) {
535                 n=e->getFirstChild();
536                 if (n) {
537                     auto_ptr<char> temp(toUTF8(n->getNodeValue()));
538                     if (temp.get()) m_emails.push_back(temp.get());
539                 }
540             }
541             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(TelephoneNumber))) {
542                 n=e->getFirstChild();
543                 if (n) {
544                     auto_ptr<char> temp(toUTF8(n->getNodeValue()));
545                     if (temp.get()) m_phones.push_back(temp.get());
546                 }
547             }
548             e=saml::XML::getNextSiblingElement(e);
549         }
550     }
551     
552     if (!XMLString::compareString(type,SHIB_L(technical)))
553         m_type=IContactPerson::technical;
554     else if (!XMLString::compareString(type,SHIB_L(support)))
555         m_type=IContactPerson::support;
556     else if (!XMLString::compareString(type,SHIB_L(administrative)))
557         m_type=IContactPerson::administrative;
558     else if (!XMLString::compareString(type,SHIB_L(billing)))
559         m_type=IContactPerson::billing;
560     else if (!XMLString::compareString(type,SHIB_L(other)))
561         m_type=IContactPerson::other;
562 }
563
564 XMLMetadataImpl::Organization::Organization(const DOMElement* e) : m_root(e)
565 {
566     DOMNode* n=NULL;
567     e=saml::XML::getFirstChildElement(e);
568     while (e) {
569         if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationName))) {
570             n=e->getFirstChild();
571             if (n) {
572                 auto_ptr<char> name(toUTF8(n->getNodeValue()));
573                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
574                 m_names[lang.get()]=name.get();
575             }
576         }
577         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationDisplayName))) {
578             n=e->getFirstChild();
579             if (n) {
580                 auto_ptr<char> display(toUTF8(n->getNodeValue()));
581                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
582                 m_displays[lang.get()]=display.get();
583             }
584         }
585         else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(OrganizationURL))) {
586             n=e->getFirstChild();
587             if (n) {
588                 auto_ptr<char> url(toUTF8(n->getNodeValue()));
589                 auto_ptr_char lang(e->getAttributeNS(saml::XML::XML_NS,L(lang)));
590                 m_urls[lang.get()]=url.get();
591             }
592         }
593         e=saml::XML::getNextSiblingElement(e);
594     }
595 }
596
597 XMLMetadataImpl::EncryptionMethod::EncryptionMethod(const DOMElement* e) : m_root(e)
598 {
599     m_alg=e->getAttributeNS(NULL,SHIB_L(Algorithm));
600     e=saml::XML::getFirstChildElement(e);
601     while (e) {
602         if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(KeySize))) {
603             DOMNode* n=e->getFirstChild();
604             if (n) m_size=XMLString::parseInt(n->getNodeValue());
605         }
606         else if (saml::XML::isElementNamed(e,saml::XML::XMLSIG_NS,SHIB_L(DigestMethod))) {
607             DOMNode* n=e->getFirstChild();
608             if (n) m_digest=n->getNodeValue();
609         }
610         else if (saml::XML::isElementNamed(e,::XML::XMLENC_NS,SHIB_L(OAEParams))) {
611             DOMNode* n=e->getFirstChild();
612             if (n) m_params=n->getNodeValue();
613         }
614         e=saml::XML::getNextSiblingElement(e);
615     }
616 }
617
618 XMLMetadataImpl::KeyDescriptor::KeyDescriptor(const DOMElement* e) : m_root(e), m_use(unspecified), m_klist(NULL)
619 {
620 #ifdef _DEBUG
621     saml::NDC ndc("KeyDescriptor");
622 #endif
623     if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(encryption)))
624         m_use=encryption;
625     else if (!XMLString::compareString(e->getAttributeNS(NULL,SHIB_L(use)),SHIB_L(signing)))
626         m_use=signing;
627     
628     m_klist = new DSIGKeyInfoList(NULL);
629
630     // Process ds:KeyInfo
631     e=saml::XML::getFirstChildElement(e);
632
633     // We let XMLSec hack through anything it can. This should evolve over time, or we can
634     // plug in our own KeyResolver later...
635     DOMElement* child=saml::XML::getFirstChildElement(e);
636     while (child) {
637         try {
638             if (!m_klist->addXMLKeyInfo(child)) {
639                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
640                     "skipped unsupported ds:KeyInfo child element");
641             }
642         }
643         catch (XSECCryptoException& xe) {
644             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error(
645                 "unable to process ds:KeyInfo child element: %s",xe.getMsg());
646         }
647         child=saml::XML::getNextSiblingElement(child);
648     }
649     
650     // Check for encryption methods.
651     e=saml::XML::getNextSiblingElement(e);
652     while (e && saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EncryptionMethod)))
653         m_methods.push_back(new EncryptionMethod(e));
654 }
655
656 XMLMetadataImpl::KeyDescriptor::~KeyDescriptor()
657 {
658     for (vector<const XENCEncryptionMethod*>::iterator i=m_methods.begin(); i!=m_methods.end(); i++)
659         delete const_cast<XENCEncryptionMethod*>(*i);
660     delete m_klist;
661 }
662
663 XMLMetadataImpl::KeyAuthority::KeyAuthority(const DOMElement* e) : m_depth(1)
664 {
665 #ifdef _DEBUG
666     saml::NDC ndc("KeyAuthority");
667 #endif
668     if (e->hasAttributeNS(NULL,SHIB_L(VerifyDepth)))
669         m_depth=XMLString::parseInt(e->getAttributeNS(NULL,SHIB_L(VerifyDepth)));
670     
671     // Process ds:KeyInfo children
672     e=saml::XML::getFirstChildElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
673     while (e) {
674         auto_ptr<DSIGKeyInfoList> klist(new DSIGKeyInfoList(NULL));
675
676         // We let XMLSec hack through anything it can. This should evolve over time, or we can
677         // plug in our own KeyResolver later...
678         DOMElement* child=saml::XML::getFirstChildElement(e);
679         while (child) {
680             try {
681                 if (!klist->addXMLKeyInfo(child)) {
682                     Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
683                         "skipped unresolvable ds:KeyInfo child element");
684                 }
685             }
686             catch (XSECCryptoException& xe) {
687                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").error(
688                     "unable to process ds:KeyInfo child element: %s",xe.getMsg());
689             }
690             child=saml::XML::getNextSiblingElement(child);
691         }
692         
693         if (klist->getSize()>0)
694             m_klists.push_back(klist.release());
695         else
696             Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").warn(
697                 "skipping ds:KeyInfo with no resolvable child elements");
698         e=saml::XML::getNextSiblingElement(e,saml::XML::XMLSIG_NS,L(KeyInfo));
699     }
700 }
701
702 XMLMetadataImpl::KeyAuthority::~KeyAuthority()
703 {
704     for (vector<DSIGKeyInfoList*>::iterator i=m_klists.begin(); i!=m_klists.end(); i++)
705         delete (*i);
706 }
707
708 XMLMetadataImpl::Role::Role(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
709     : m_provider(provider), m_errorURL(NULL), m_protocolEnumCopy(NULL), m_org(NULL), m_validUntil(validUntil), m_root(e)
710 {
711     // Check the root element namespace. If SAML2, assume it's the std schema.
712     if (e && !XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
713        
714         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
715             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
716             exp.parseDateTime();
717             m_validUntil=min(m_validUntil,exp.getEpoch());
718         }
719         
720         if (e->hasAttributeNS(NULL,SHIB_L(errorURL)))
721             m_errorURL=toUTF8(e->getAttributeNS(NULL,SHIB_L(errorURL)));
722         
723         // Chop the protocol list into pieces...assume any whitespace can appear in between.
724         m_protocolEnumCopy=XMLString::replicate(e->getAttributeNS(NULL,SHIB_L(protocolSupportEnumeration)));
725         XMLCh* temp=m_protocolEnumCopy;
726         while (temp && *temp) {
727             XMLCh* start=temp++;
728             while (*temp && !XMLChar1_1::isWhitespace(*temp)) temp++;
729             if (*temp)
730                 *temp++=chNull;
731             m_protocolEnum.push_back(start);
732             while (*temp && XMLChar1_1::isWhitespace(*temp)) temp++;
733         }
734         
735         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
736         while (e) {
737             m_keys.push_back(new KeyDescriptor(e));
738             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
739         }
740
741         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(Organization));
742         if (e)
743             m_org=new Organization(e);
744
745         e=saml::XML::getFirstChildElement(m_root,::XML::SAML2META_NS,SHIB_L(ContactPerson));
746         while (e) {
747             m_contacts.push_back(new ContactPerson(e));
748             e=saml::XML::getNextSiblingElement(e,::XML::SAML2META_NS,SHIB_L(ContactPerson));
749         }
750     }
751 }
752
753 XMLMetadataImpl::Role::~Role()
754 {
755     delete m_org;
756     delete m_errorURL;
757     if (m_protocolEnumCopy) XMLString::release(&m_protocolEnumCopy);
758     for (vector<const IKeyDescriptor*>::iterator i=m_keys.begin(); i!=m_keys.end(); i++)
759         delete const_cast<IKeyDescriptor*>(*i);
760     for (vector<const IContactPerson*>::iterator j=m_contacts.begin(); j!=m_contacts.end(); j++)
761         delete const_cast<IContactPerson*>(*j);
762 }
763
764 bool XMLMetadataImpl::Role::hasSupport(const XMLCh* protocol) const
765 {
766     Iterator<const XMLCh*> i(m_protocolEnum);
767     while (i.hasNext()) {
768         if (!XMLString::compareString(protocol,i.next()))
769             return true;
770     }
771     return false;
772 }
773
774 XMLMetadataImpl::SSORole::SSORole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
775     : Role(provider,validUntil,e)
776 {
777     // Check the root element namespace. If SAML2, assume it's the std schema.
778     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
779         int i;
780         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ArtifactResolutionService));
781         for (i=0; nlist && i<nlist->getLength(); i++)
782             m_artifact.add(new IndexedEndpoint(static_cast<DOMElement*>(nlist->item(i))));
783
784         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleLogoutService));
785         for (i=0; nlist && i<nlist->getLength(); i++)
786             m_logout.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
787
788         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(ManageNameIDService));
789         for (i=0; nlist && i<nlist->getLength(); i++)
790             m_nameid.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
791
792         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
793         for (i=0; nlist && i<nlist->getLength(); i++) {
794             DOMNode* n=nlist->item(i)->getFirstChild();
795             if (n) m_formats.push_back(n->getNodeValue());
796         }
797     }
798     else {
799         // For old style, we just do SAML 1.1 compatibility with Shib handles.
800         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
801         m_formats.push_back(shibboleth::Constants::SHIB_NAMEID_FORMAT_URI);
802     }
803 }
804
805 XMLMetadataImpl::ScopedRole::ScopedRole(const DOMElement* e)
806 {
807     // Check the root element namespace. If SAML2, assume it's the std schema.
808     DOMNodeList* nlist=NULL;
809     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
810         e=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
811         nlist=e->getElementsByTagNameNS(::XML::SHIBMETA_NS,SHIB_L(Scope));
812     }
813     else {
814         nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(Domain));
815     }
816     
817     for (int i=0; nlist && i < nlist->getLength(); i++) {
818         const XMLCh* dom=(nlist->item(i)->hasChildNodes()) ? nlist->item(i)->getFirstChild()->getNodeValue() : NULL;
819         if (dom && *dom) {
820             const XMLCh* regexp=static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(regexp));
821             m_scopes.push_back(
822                 pair<const XMLCh*,bool>(dom,(regexp && (*regexp==chLatin_t || *regexp==chDigit_1)))
823                 );
824         }
825     }
826 }
827
828 XMLMetadataImpl::IDPRole::IDPRole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
829     : SSORole(provider,validUntil,e), ScopedRole(e), m_wantAuthnRequestsSigned(false), m_sourceId(NULL)
830 {
831     // Check the root element namespace. If SAML2, assume it's the std schema.
832     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
833         const XMLCh* flag=e->getAttributeNS(NULL,SHIB_L(WantAuthnRequestsSigned));
834         m_wantAuthnRequestsSigned=(flag && (*flag==chDigit_1 || *flag==chLatin_t));
835         
836         // Check for SourceID extension.
837         DOMElement* ext=saml::XML::getFirstChildElement(e,::XML::SAML2META_NS,SHIB_L(Extensions));
838         if (ext) {
839             ext=saml::XML::getFirstChildElement(ext,saml::XML::SAML_ARTIFACT_SOURCEID,SHIB_L(SourceID));
840             if (ext && ext->hasChildNodes())
841                 m_sourceId=ext->getFirstChild()->getNodeValue();
842         }
843         
844         int i;
845         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(SingleSignOnService));
846         for (i=0; nlist && i<nlist->getLength(); i++)
847             m_sso.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
848
849         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDMappingService));
850         for (i=0; nlist && i<nlist->getLength(); i++)
851             m_mapping.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
852
853         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
854         for (i=0; nlist && i<nlist->getLength(); i++)
855             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
856
857         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
858         for (i=0; nlist && i<nlist->getLength(); i++) {
859             DOMNode* n=nlist->item(i)->getFirstChild();
860             if (n) m_attrprofs.push_back(n->getNodeValue());
861         }
862
863         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
864         for (i=0; nlist && i<nlist->getLength(); i++) {
865             // For now, we need to convert these to plain SAML 1.1 attributes.
866             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
867             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
868             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
869             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
870             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
871             while (src) {
872                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
873                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
874                 DOMNamedNodeMap* attrs = src->getAttributes();
875                 for (int j=0; j<attrs->getLength(); j++)
876                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
877                 while (src->hasChildNodes())
878                     val->appendChild(src->getFirstChild());
879                 copy->appendChild(val);
880             }
881             m_attrs.push_back(SAMLAttribute::getInstance(copy));
882         }
883     }
884     else {
885         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
886         int i;
887         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(HandleService));
888         for (i=0; nlist && i<nlist->getLength(); i++) {
889             // Manufacture an endpoint for the "Shib" binding.
890             m_sso.add(
891                 new Endpoint(Constants::SHIB_AUTHNREQUEST_PROFILE_URI,static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Location)))
892                 );
893
894             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
895             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
896             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
897             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
898             kn->appendChild(
899                 e->getOwnerDocument()->createTextNode(
900                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
901                     )
902                 );
903             ki->appendChild(kn);
904             kd->appendChild(ki);
905             kd->setAttributeNS(NULL,SHIB_L(use),SHIB_L(signing));
906             m_keys.push_back(new KeyDescriptor(kd));
907         }
908     }
909 }
910
911 XMLMetadataImpl::IDPRole::~IDPRole()
912 {
913     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
914         delete const_cast<SAMLAttribute*>(*i);
915 }
916
917 XMLMetadataImpl::AARole::AARole(const EntityDescriptor* provider, time_t validUntil, const DOMElement* e)
918     : Role(provider,validUntil,e), ScopedRole(e)
919 {
920     // Check the root element namespace. If SAML2, assume it's the std schema.
921     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
922         int i;
923         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeService));
924         for (i=0; nlist && i<nlist->getLength(); i++)
925             m_query.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
926
927         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AssertionIDRequestService));
928         for (i=0; nlist && i<nlist->getLength(); i++)
929             m_idreq.add(new Endpoint(static_cast<DOMElement*>(nlist->item(i))));
930
931         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(NameIDFormat));
932         for (i=0; nlist && i<nlist->getLength(); i++) {
933             DOMNode* n=nlist->item(i)->getFirstChild();
934             if (n) m_formats.push_back(n->getNodeValue());
935         }
936
937         nlist=e->getElementsByTagNameNS(::XML::SAML2META_NS,SHIB_L(AttributeProfile));
938         for (i=0; nlist && i<nlist->getLength(); i++) {
939             DOMNode* n=nlist->item(i)->getFirstChild();
940             if (n) m_attrprofs.push_back(n->getNodeValue());
941         }
942
943         nlist=e->getElementsByTagNameNS(::XML::SAML2ASSERT_NS,L(Attribute));
944         for (i=0; nlist && i<nlist->getLength(); i++) {
945             // For now, we need to convert these to plain SAML 1.1 attributes.
946             DOMElement* src=static_cast<DOMElement*>(nlist->item(i));
947             DOMElement* copy=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(Attribute));
948             copy->setAttributeNS(NULL,L(AttributeName),src->getAttributeNS(NULL,SHIB_L(Name)));
949             copy->setAttributeNS(NULL,L(AttributeNamespace),src->getAttributeNS(NULL,SHIB_L(NameFormat)));
950             src=saml::XML::getFirstChildElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
951             while (src) {
952                 src=saml::XML::getNextSiblingElement(src,::XML::SAML2ASSERT_NS,L(AttributeValue));
953                 DOMElement* val=e->getOwnerDocument()->createElementNS(saml::XML::SAML_NS,L(AttributeValue));
954                 DOMNamedNodeMap* attrs = src->getAttributes();
955                 for (int j=0; j<attrs->getLength(); j++)
956                     val->setAttributeNodeNS(static_cast<DOMAttr*>(e->getOwnerDocument()->importNode(attrs->item(j),true)));
957                 while (src->hasChildNodes())
958                     val->appendChild(src->getFirstChild());
959                 copy->appendChild(val);
960             }
961             m_attrs.push_back(SAMLAttribute::getInstance(copy));
962         }
963     }
964     else {
965         // For old style, we just do SAML 1.1 compatibility with Shib handles.
966         m_protocolEnum.push_back(saml::XML::SAML11_PROTOCOL_ENUM);
967         m_formats.push_back(Constants::SHIB_NAMEID_FORMAT_URI);
968         m_attrprofs.push_back(Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
969         int i;
970         DOMNodeList* nlist=e->getElementsByTagNameNS(::XML::SHIB_NS,SHIB_L(AttributeAuthority));
971         for (i=0; nlist && i<nlist->getLength(); i++) {
972             // Manufacture an endpoint for the SOAP binding.
973             m_query.add(
974                 new Endpoint(
975                     SAMLBinding::SOAP,
976                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Location))
977                     )
978                 );
979
980             // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
981             DOMElement* kd=e->getOwnerDocument()->createElementNS(::XML::SAML2META_NS,SHIB_L(KeyDescriptor));
982             DOMElement* ki=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,L(KeyInfo));
983             DOMElement* kn=e->getOwnerDocument()->createElementNS(saml::XML::XMLSIG_NS,SHIB_L(KeyName));
984             kn->appendChild(
985                 e->getOwnerDocument()->createTextNode(
986                     static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIB_L(Name))
987                     )
988                 );
989             ki->appendChild(kn);
990             kd->appendChild(ki);
991             m_keys.push_back(new KeyDescriptor(kd));
992         }
993     }
994 }
995
996 XMLMetadataImpl::AARole::~AARole()
997 {
998     for (vector<const SAMLAttribute*>::iterator i=m_attrs.begin(); i!=m_attrs.end(); i++)
999         delete const_cast<SAMLAttribute*>(*i);
1000 }
1001
1002 XMLMetadataImpl::EntityDescriptor::EntityDescriptor(
1003     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
1004     ) : m_root(e), m_parent(parent), m_org(NULL), m_validUntil(validUntil)
1005 {
1006     // Check the root element namespace. If SAML2, assume it's the std schema.
1007     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
1008         m_id=e->getAttributeNS(NULL,SHIB_L(entityID));
1009
1010         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
1011             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
1012             exp.parseDateTime();
1013             m_validUntil=min(validUntil,exp.getEpoch());
1014         }
1015
1016         DOMElement* child=saml::XML::getFirstChildElement(e);
1017         while (child) {
1018             // Process the various kinds of children that we care about...
1019             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Extensions))) {
1020                 DOMElement* ext = saml::XML::getFirstChildElement(child,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1021                 while (ext) {
1022                     m_keyauths.push_back(new KeyAuthority(ext));
1023                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1024                 }
1025             }
1026             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(ContactPerson))) {
1027                 m_contacts.push_back(new ContactPerson(child));
1028             }
1029             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(Organization))) {
1030                 m_org=new Organization(child);
1031             }
1032             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AdditionalMetadataLocation))) {
1033                 DOMNode* loc=child->getFirstChild();
1034                 if (loc)
1035                     m_locs.push_back(
1036                     pair<const XMLCh*,const XMLCh*>(child->getAttributeNS(NULL,::XML::Literals::_namespace),loc->getNodeValue())
1037                         );
1038             }
1039             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(IDPSSODescriptor))) {
1040                 m_roles.push_back(new IDPRole(this,m_validUntil,child));
1041             }
1042             else if (saml::XML::isElementNamed(child,::XML::SAML2META_NS,SHIB_L(AttributeAuthorityDescriptor))) {
1043                 m_roles.push_back(new AARole(this,m_validUntil,child));
1044             }
1045             child = saml::XML::getNextSiblingElement(child);
1046         }
1047     }
1048     else {
1049         m_id=e->getAttributeNS(NULL,SHIB_L(Name));
1050         m_errorURL=auto_ptr<char>(toUTF8(e->getAttributeNS(NULL,SHIB_L(ErrorURL))));
1051         
1052         bool idp=false,aa=false;    // only want to build a role once
1053         DOMElement* child=saml::XML::getFirstChildElement(e);
1054         while (child) {
1055             // Process the various kinds of OriginSite children that we care about...
1056             if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(Contact))) {
1057                 m_contacts.push_back(new ContactPerson(child));
1058             }
1059             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(HandleService)) && !idp) {
1060                 // Create the IDP role if needed.
1061                 m_roles.push_back(new IDPRole(this, m_validUntil, e));
1062                 idp=true;
1063             }
1064             else if (saml::XML::isElementNamed(child,::XML::SHIB_NS,SHIB_L(AttributeAuthority)) && !aa) {
1065                 // Create the AA role if needed.
1066                 m_roles.push_back(new AARole(this, m_validUntil, e));
1067                 aa=true;
1068             }
1069             child = saml::XML::getNextSiblingElement(child);
1070         }
1071     }
1072
1073     auto_ptr_char id(m_id);
1074     wrapper->m_sites.insert(pair<string,const EntityDescriptor*>(id.get(),this));
1075     
1076     // Look for an IdP role, and register the artifact source ID and endpoints.
1077     const IDPRole* idp=NULL;
1078     for (vector<const IRoleDescriptor*>::const_iterator r=m_roles.begin(); r!=m_roles.end(); r++) {
1079         if (idp=dynamic_cast<const IDPRole*>(*r)) {
1080             if (idp->m_sourceId) {
1081                 auto_ptr_char sourceid(idp->m_sourceId);
1082                 wrapper->m_sources.insert(pair<string,const EntityDescriptor*>(sourceid.get(),this));
1083             }
1084             else {
1085                 string sourceid=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(id.get()));
1086                 Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata").debug(
1087                     "generated artifact SourceID (%s) for entity (%s)",sourceid.c_str(),id.get()
1088                     );
1089                 wrapper->m_sources.insert(pair<string,const EntityDescriptor*>(sourceid,this));
1090             }
1091             Iterator<const IEndpoint*> locs=idp->getArtifactResolutionServiceManager()->getEndpoints();
1092             while (locs.hasNext()) {
1093                 auto_ptr_char loc(locs.next()->getLocation());
1094                 wrapper->m_sources.insert(pair<string,const EntityDescriptor*>(loc.get(),this));
1095             }
1096         }
1097     }
1098 }
1099
1100 const IIDPSSODescriptor* XMLMetadataImpl::EntityDescriptor::getIDPSSODescriptor(const XMLCh* protocol) const
1101 {
1102     const IIDPSSODescriptor* ret=NULL;
1103     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1104         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IIDPSSODescriptor*>(*i)))
1105             return ret;
1106     }
1107     return NULL;
1108 }
1109
1110 const IAttributeAuthorityDescriptor* XMLMetadataImpl::EntityDescriptor::getAttributeAuthorityDescriptor(const XMLCh* protocol) const
1111 {
1112     const IAttributeAuthorityDescriptor* ret=NULL;
1113     for (vector<const IRoleDescriptor*>::const_iterator i=m_roles.begin(); i!=m_roles.end(); i++) {
1114         if ((*i)->hasSupport(protocol) && (*i)->isValid() && (ret=dynamic_cast<const IAttributeAuthorityDescriptor*>(*i)))
1115             return ret;
1116     }
1117     return NULL;
1118 }
1119
1120 XMLMetadataImpl::EntityDescriptor::~EntityDescriptor()
1121 {
1122     delete m_org;
1123     for (vector<const IContactPerson*>::iterator i=m_contacts.begin(); i!=m_contacts.end(); i++)
1124         delete const_cast<IContactPerson*>(*i);
1125     for (vector<const IRoleDescriptor*>::iterator j=m_roles.begin(); j!=m_roles.end(); j++)
1126         delete const_cast<IRoleDescriptor*>(*j);
1127     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1128         delete const_cast<IKeyAuthority*>(*k);
1129 }
1130
1131 XMLMetadataImpl::EntitiesDescriptor::EntitiesDescriptor(
1132     const DOMElement* e, XMLMetadataImpl* wrapper, time_t validUntil, const IEntitiesDescriptor* parent
1133     ) : m_root(e), m_name(e->getAttributeNS(NULL,SHIB_L(Name))), m_parent(parent), m_validUntil(validUntil)
1134 {
1135     // Check the root element namespace. If SAML2, assume it's the std schema.
1136     if (!XMLString::compareString(e->getNamespaceURI(),::XML::SAML2META_NS)) {
1137
1138         if (e->hasAttributeNS(NULL,SHIB_L(validUntil))) {
1139             SAMLDateTime exp(e->getAttributeNS(NULL,SHIB_L(validUntil)));
1140             exp.parseDateTime();
1141             m_validUntil=min(validUntil,exp.getEpoch());
1142         }
1143
1144         e=saml::XML::getFirstChildElement(e);
1145         while (e) {
1146             if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(Extensions))) {
1147                 DOMElement* ext = saml::XML::getFirstChildElement(e,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1148                 while (ext) {
1149                     m_keyauths.push_back(new KeyAuthority(ext));
1150                     ext = saml::XML::getNextSiblingElement(ext,::XML::SHIBMETA_NS,SHIB_L(KeyAuthority));
1151                 }
1152             }
1153             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor)))
1154                 m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1155             else if (saml::XML::isElementNamed(e,::XML::SAML2META_NS,SHIB_L(EntityDescriptor)))
1156                 m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1157             e=saml::XML::getNextSiblingElement(e);
1158         }
1159     }
1160     else {
1161         e=saml::XML::getFirstChildElement(e);
1162         while (e) {
1163             if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(SiteGroup)))
1164                 m_groups.push_back(new EntitiesDescriptor(e,wrapper,m_validUntil,this));
1165             else if (saml::XML::isElementNamed(e,::XML::SHIB_NS,SHIB_L(OriginSite)))
1166                 m_providers.push_back(new EntityDescriptor(e,wrapper,m_validUntil,this));
1167             e=saml::XML::getNextSiblingElement(e);
1168         }
1169     }
1170 }
1171
1172 XMLMetadataImpl::EntitiesDescriptor::~EntitiesDescriptor()
1173 {
1174     for (vector<const IEntityDescriptor*>::iterator i=m_providers.begin(); i!=m_providers.end(); i++)
1175         delete const_cast<IEntityDescriptor*>(*i);
1176     for (vector<const IEntitiesDescriptor*>::iterator j=m_groups.begin(); j!=m_groups.end(); j++)
1177         delete const_cast<IEntitiesDescriptor*>(*j);
1178     for (vector<const IKeyAuthority*>::iterator k=m_keyauths.begin(); k!=m_keyauths.end(); k++)
1179         delete const_cast<IKeyAuthority*>(*k);
1180 }
1181
1182 void XMLMetadataImpl::init()
1183 {
1184 #ifdef _DEBUG
1185     NDC ndc("init");
1186 #endif
1187     Category& log=Category::getInstance(XMLPROVIDERS_LOGCAT".Metadata");
1188
1189     try
1190     {
1191         if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntitiesDescriptor)))
1192             m_rootGroup=new EntitiesDescriptor(m_root,this);
1193         else if (saml::XML::isElementNamed(m_root,::XML::SAML2META_NS,SHIB_L(EntityDescriptor)))
1194             m_rootProvider=new EntityDescriptor(m_root,this);
1195         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(SiteGroup)))
1196             m_rootGroup=new EntitiesDescriptor(m_root,this);
1197         else if (saml::XML::isElementNamed(m_root,::XML::SHIB_NS,SHIB_L(OriginSite)))
1198             m_rootProvider=new EntityDescriptor(m_root,this);
1199         else {
1200             log.error("Construction requires a valid SAML metadata file");
1201             throw MetadataException("Construction requires a valid SAML metadata file");
1202         }
1203     }
1204     catch (SAMLException& e)
1205     {
1206         log.errorStream() << "Error while parsing SAML metadata: " << e.what() << CategoryStream::ENDLINE;
1207         this->~XMLMetadataImpl();
1208         throw;
1209     }
1210 #ifndef _DEBUG
1211     catch (...)
1212     {
1213         log.error("Unexpected error while parsing SAML metadata");
1214         this->~XMLMetadataImpl();
1215         throw;
1216     }
1217 #endif
1218 }
1219
1220 XMLMetadataImpl::~XMLMetadataImpl()
1221 {
1222     delete m_rootGroup;
1223     delete m_rootProvider;
1224 }
1225
1226 const IEntityDescriptor* XMLMetadata::lookup(const char* providerId, bool strict) const
1227 {
1228     if (strict && m_exclusions && m_set.find(providerId)!=m_set.end())
1229         return NULL;
1230     else if (strict && !m_exclusions && m_set.find(providerId)==m_set.end())
1231         return NULL;
1232         
1233     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1234     pair<XMLMetadataImpl::sitemap_t::const_iterator,XMLMetadataImpl::sitemap_t::const_iterator> range=
1235         impl->m_sites.equal_range(providerId);
1236
1237     time_t now=time(NULL);
1238     for (XMLMetadataImpl::sitemap_t::const_iterator i=range.first; i!=range.second; i++)
1239         if (now < i->second->getValidUntil())
1240             return i->second;
1241     
1242     if (!strict && range.first!=range.second)
1243         return range.first->second;
1244         
1245     return NULL;
1246 }
1247
1248 const IEntityDescriptor* XMLMetadata::lookup(const XMLCh* providerId, bool strict) const
1249 {
1250     auto_ptr_char temp(providerId);
1251     return lookup(temp.get(),strict);
1252 }
1253
1254 const IEntityDescriptor* XMLMetadata::lookup(const SAMLArtifact* artifact) const
1255 {
1256     time_t now=time(NULL);
1257     XMLMetadataImpl* impl=dynamic_cast<XMLMetadataImpl*>(getImplementation());
1258     pair<XMLMetadataImpl::sitemap_t::const_iterator,XMLMetadataImpl::sitemap_t::const_iterator> range;
1259     
1260     // Depends on type of artifact.
1261     const SAMLArtifactType0001* type1=dynamic_cast<const SAMLArtifactType0001*>(artifact);
1262     if (type1) {
1263         range=impl->m_sources.equal_range(SAMLArtifact::toHex(type1->getSourceID()));
1264     }
1265     else {
1266         const SAMLArtifactType0002* type2=dynamic_cast<const SAMLArtifactType0002*>(artifact);
1267         if (type2) {
1268             range=impl->m_sources.equal_range(type2->getSourceLocation());
1269         }
1270         else
1271             return NULL;
1272     }
1273
1274     // Check exclude list.
1275     if (range.first!=range.second) {
1276         auto_ptr_char id(range.first->second->getId());
1277         if (m_exclusions && m_set.find(id.get())!=m_set.end())
1278             return NULL;
1279         else if (!m_exclusions && m_set.find(id.get())==m_set.end())
1280             return NULL;
1281
1282         for (XMLMetadataImpl::sitemap_t::const_iterator i=range.first; i!=range.second; i++)
1283             if (now < i->second->getValidUntil())
1284                 return i->second;
1285     }
1286     
1287     return NULL;
1288 }