b154c64b30e942eec053c4c549e557a0f8967527
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / metadata / provider / XMLMetadataProvider.java
1 /*
2  * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.metadata.provider;
18
19 import java.net.MalformedURLException;
20 import java.net.URL;
21 import java.security.NoSuchAlgorithmException;
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.Map;
30 import java.util.TimeZone;
31
32 import javax.xml.namespace.QName;
33
34 import org.apache.log4j.Logger;
35 import org.apache.xml.security.encryption.EncryptionMethod;
36 import org.apache.xml.security.exceptions.XMLSecurityException;
37 import org.apache.xml.security.keys.KeyInfo;
38 import org.bouncycastle.util.encoders.Hex;
39 import org.opensaml.SAMLAttribute;
40 import org.opensaml.SAMLBinding;
41 import org.opensaml.SAMLBrowserProfile;
42 import org.opensaml.SAMLException;
43 import org.opensaml.XML;
44 import org.opensaml.artifact.Artifact;
45 import org.opensaml.artifact.SAMLArtifactType0001;
46 import org.opensaml.artifact.SAMLArtifactType0002;
47 import org.opensaml.artifact.Util;
48 import org.w3c.dom.Attr;
49 import org.w3c.dom.Element;
50 import org.w3c.dom.NamedNodeMap;
51 import org.w3c.dom.Node;
52 import org.w3c.dom.NodeList;
53
54 import edu.internet2.middleware.shibboleth.common.Constants;
55 import edu.internet2.middleware.shibboleth.metadata.*;
56
57 /**
58  * @author Scott Cantor
59  */
60 public class XMLMetadataProvider implements Metadata {
61
62         private static Logger log = Logger.getLogger(XMLMetadataProvider.class.getName());
63         private Map     /* <String,ArrayList<EntityDescriptor> > */ sites = new HashMap();
64     private Map /* <String,ArrayList<EntityDescriptor> > */ sources = new HashMap();
65     private XMLEntityDescriptor rootProvider = null;
66     private XMLEntitiesDescriptor rootGroup = null;
67
68         public XMLMetadataProvider(Element e) throws SAMLException {
69         if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EntitiesDescriptor"))
70             rootGroup=new XMLEntitiesDescriptor(e,this, Long.MAX_VALUE, null);
71         else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EntityDescriptor"))
72             rootProvider=new XMLEntityDescriptor(e,this, Long.MAX_VALUE, null);
73         else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"SiteGroup"))
74             rootGroup=new XMLEntitiesDescriptor(e,this, Long.MAX_VALUE, null);
75         else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"OriginSite"))
76             rootProvider=new XMLEntityDescriptor(e,this, Long.MAX_VALUE, null);
77         else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"DestinationSite"))
78             rootProvider=new XMLEntityDescriptor(e,this, Long.MAX_VALUE, null);
79         else {
80             log.error("Construction requires a valid SAML metadata file");
81             throw new MetadataException("Construction requires a valid SAML metadata file");
82         }
83         }
84
85         public EntityDescriptor lookup(String id) {
86                 ArrayList list = (ArrayList)sites.get(id);
87                 if (list != null) {
88                     long now = System.currentTimeMillis();
89             for (int i=0; i<list.size(); i++) {
90                 if (now < ((XMLEntityDescriptor)list.get(i)).getValidUntil())
91                     return (EntityDescriptor)list.get(i);
92             }
93         }
94                 return null;
95         }
96
97     public EntityDescriptor lookup(Artifact artifact) {
98         ArrayList list = null;
99         
100         if (artifact instanceof SAMLArtifactType0001) {
101             list = (ArrayList)sources.get(((SAMLArtifactType0001)artifact).getSourceId());
102         }
103         else if (artifact instanceof SAMLArtifactType0002) {
104             list = (ArrayList)sources.get(((SAMLArtifactType0002)artifact).getSourceLocation().toString());
105         }
106         else {
107             log.error("unsupported artifact type (" + artifact.getTypeCode().toString() + ")");
108         }
109
110         if (list != null) {
111             long now = System.currentTimeMillis();
112             for (int i=0; i<list.size(); i++) {
113                 if (now < ((XMLEntityDescriptor)list.get(i)).getValidUntil())
114                     return (EntityDescriptor)list.get(i);
115             }
116         }
117         return null;
118     }
119
120     class XMLEndpoint implements Endpoint {
121         private Element root = null;
122         private String binding = null;
123         private String location = null;
124         private String resploc = null;
125
126         XMLEndpoint(Element e) {
127             root = e;
128             binding = XML.assign(e.getAttributeNS(null,"Binding"));
129             location = XML.assign(e.getAttributeNS(null,"Location"));
130             resploc = XML.assign(e.getAttributeNS(null,"ResponseLocation"));
131         }
132         
133         XMLEndpoint(String binding, String location) {
134             this.binding = binding;
135             this.location = location;
136         }
137
138         public String getBinding() {
139             return binding;
140         }
141
142         public String getLocation() {
143             return location;
144         }
145
146         public String getResponseLocation() {
147             return resploc;
148         }
149         
150         public Element getElement() {
151             return root;
152         }
153     }
154
155     class XMLIndexedEndpoint extends XMLEndpoint implements IndexedEndpoint {
156         private int index = 0;
157         
158         XMLIndexedEndpoint(Element e) {
159             super(e);
160             index = Integer.parseInt(e.getAttributeNS(null,"index"));
161         }
162
163         public int getIndex() {
164             return index;
165         }
166     }
167     
168     class XMLEndpointManager implements EndpointManager {
169         private ArrayList endpoints = new ArrayList();
170         Endpoint soft = null;   // Soft default (not explicit)
171         Endpoint hard = null;   // Hard default (explicit)
172
173         public Iterator getEndpoints() {
174             return endpoints.iterator();
175         }
176         
177         public Endpoint getDefaultEndpoint() {
178             if (hard != null) return hard;
179             if (soft != null) return soft;
180             if (!endpoints.isEmpty()) return (Endpoint)endpoints.get(0);
181             return null;
182         }
183         
184         public Endpoint getEndpointByIndex(int index) {
185             for (int i=0; i < endpoints.size(); i++) {
186                 if (endpoints.get(i) instanceof IndexedEndpoint && index==((IndexedEndpoint)endpoints.get(i)).getIndex())
187                     return (Endpoint)endpoints.get(i);
188             }
189             return null;
190         }
191         
192         public Endpoint getEndpointByBinding(String binding) {
193             for (int i=0; i < endpoints.size(); i++) {
194                 if (binding.equals(((Endpoint)endpoints.get(i)).getBinding()))
195                     return (Endpoint)endpoints.get(i);
196             }
197             return null;
198         }
199         
200         protected void add(Endpoint e) {
201             endpoints.add(e);
202             if (hard == null && e.getElement() != null) {
203                 String v=XML.assign(e.getElement().getAttributeNS(null,"isDefault"));
204                 if (v != null && (v.equals("1") || v.equals("true")))  // explicit default
205                     hard=e;
206                 else if (v == null && soft == null)            // implicit default
207                     soft=e;
208             }
209             else if (hard == null && soft == null) {
210                 // No default yet, so this one qualifies as an implicit.
211                 soft=e;
212             }
213         }
214     }
215     
216     class XMLKeyDescriptor implements KeyDescriptor {
217
218         private int use = KeyDescriptor.UNSPECIFIED;
219         private KeyInfo keyInfo = null;
220         private ArrayList /* <XMLEncryptionMethod> */ methods = new ArrayList();
221
222         XMLKeyDescriptor(Element e) {
223             if (XML.safeCompare(e.getAttributeNS(null,"use"),"encryption"))
224                 use = KeyDescriptor.ENCRYPTION;
225             else if (XML.safeCompare(e.getAttributeNS(null,"use"),"signing"))
226                 use = KeyDescriptor.SIGNING;
227             
228             e = XML.getFirstChildElement(e);
229             try {
230                 keyInfo = new KeyInfo(e, null);
231             }
232             catch (XMLSecurityException e1) {
233                 log.error("unable to process ds:KeyInfo element: " + e1.getMessage());
234             }
235             
236             e = XML.getNextSiblingElement(e);
237             while (e != null && XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EncryptionMethod")) {
238                 methods.add(new XMLEncryptionMethod(e));
239             }
240         }
241
242         public int getUse() {
243             return use;
244         }
245
246         public Iterator getEncryptionMethods() {
247             return methods.iterator();
248         }
249
250         public KeyInfo getKeyInfo() {
251             return keyInfo;
252         }
253     }
254
255     class XMLEncryptionMethod implements EncryptionMethod {
256
257         String alg = null;
258         String params = null;
259         int size = 0;
260         
261         public XMLEncryptionMethod(Element e) {
262             alg = XML.assign(e.getAttributeNS(null, "Algorithm"));
263             e = XML.getFirstChildElement(e);
264             while (e != null) {
265                 if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.XMLENC_NS,"KeySize")) {
266                     if (e.hasChildNodes())
267                         size = Integer.parseInt(e.getFirstChild().getNodeValue());
268                 }
269                 else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.XMLENC_NS,"OAEParams")) {
270                     if (e.hasChildNodes())
271                         params = XML.assign(e.getFirstChild().getNodeValue());
272                 }
273                 e = XML.getNextSiblingElement(e);
274             }
275         }
276         
277         public String getAlgorithm() {
278             return alg;
279         }
280
281         public int getKeySize() {
282             return size;
283         }
284
285         public byte[] getOAEPparams() {
286             return params.getBytes();
287         }
288
289         public Iterator getEncryptionMethodInformation() {
290             return null;
291         }
292
293         public void setKeySize(int arg0) {
294             throw new UnsupportedOperationException("EncryptionMethod implementation is read-only.");
295         }
296
297         public void setOAEPparams(byte[] arg0) {
298             throw new UnsupportedOperationException("EncryptionMethod implementation is read-only.");
299         }
300
301         public void addEncryptionMethodInformation(Element arg0) {
302             throw new UnsupportedOperationException("EncryptionMethod implementation is read-only.");
303         }
304
305         public void removeEncryptionMethodInformation(Element arg0) {
306             throw new UnsupportedOperationException("EncryptionMethod implementation is read-only.");
307         }
308     }
309
310     class XMLKeyAuthority implements KeyAuthority {
311         private int depth = 1;
312         private ArrayList /* <KeyInfo> */ keys = new ArrayList();
313         
314         XMLKeyAuthority(Element e) {
315             if (e.hasAttributeNS(null,"VerifyDepth"))
316                 depth = Integer.parseInt(e.getAttributeNS(null,"VerifyDepth"));
317             e = XML.getFirstChildElement(e, XML.XMLSIG_NS, "KeyInfo");
318             while (e != null) {
319                 try {
320                     keys.add(new KeyInfo(e, null));
321                 }
322                 catch (XMLSecurityException e1) {
323                     log.error("unable to process ds:KeyInfo element: " + e1.getMessage());
324                 }
325                 e = XML.getNextSiblingElement(e, XML.XMLSIG_NS, "KeyInfo");
326             }
327         }
328         
329         public int getVerifyDepth() {
330             return depth;
331         }
332
333         public Iterator getKeyInfos() {
334             return keys.iterator();
335         }
336         
337     }
338         
339     class XMLOrganization implements Organization {
340         private Element root = null;
341         private HashMap /* <String,String> */ names = new HashMap();
342         private HashMap /* <String,String> */ displays = new HashMap();
343         private HashMap /* <String,URL> */ urls = new HashMap();
344
345         public XMLOrganization(Element e) throws MetadataException {
346             root = e;
347             e=XML.getFirstChildElement(e);
348             while (e != null) {
349                 if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"OrganizationName")) {
350                     if (e.hasChildNodes()) {
351                         names.put(e.getAttributeNS(XML.XML_NS,"lang"),XML.assign(e.getFirstChild().getNodeValue()));
352                     }
353                 }
354                 else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"OrganizationDisplayName")) {
355                     if (e.hasChildNodes()) {
356                         displays.put(e.getAttributeNS(XML.XML_NS,"lang"),XML.assign(e.getFirstChild().getNodeValue()));
357                     }
358                 }
359                 else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"OrganizationURL")) {
360                     if (e.hasChildNodes()) {
361                         URL u;
362                         try {
363                             u = new URL(e.getFirstChild().getNodeValue());
364                         }
365                         catch (MalformedURLException e1) {
366                             throw new MetadataException("OrganizationURL was invalid: " + e1);
367                         }
368                         urls.put(e.getAttributeNS(XML.XML_NS,"lang"),u);
369                     }
370                 }
371                 e=XML.getNextSiblingElement(e);
372             }
373         }
374         
375         public String getName() {
376             return getName("en");
377         }
378
379         public String getName(String lang) {
380             return (String)names.get(lang);
381         }
382
383         public String getDisplayName() {
384             return getDisplayName("en");
385         }
386
387         public String getDisplayName(String lang) {
388             return (String)displays.get(lang);
389         }
390
391         public URL getURL() {
392             return getURL("en");
393         }
394
395         public URL getURL(String lang) {
396             return (URL)urls.get(lang);
397         }
398         
399     }
400     
401         class XMLContactPerson implements ContactPerson {
402             private Element root = null;
403                 private int             type;
404         private String  company = null;
405                 private String  givenName = null;
406         private String  surName = null;
407                 private ArrayList /* <String> */ emails = new ArrayList();
408         private ArrayList /* <String> */ telephones = new ArrayList();
409
410                 public XMLContactPerson(Element e) throws MetadataException {
411             root = e;
412             String rawType = null;
413             
414             // Old metadata or new?
415             if (XML.isElementNamed(root, edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"Contact")) {
416                 rawType = root.getAttributeNS(null,"Type");
417                 surName = XML.assign(root.getAttributeNS(null,"Name"));
418                 if (XML.isEmpty(surName)) {
419                     throw new MetadataException("Contact is missing Name attribute.");
420                 }
421                 if (root.hasAttributeNS(null,"Email"))
422                     emails.add(e.getAttributeNS(null,"Email"));
423             }
424             else {
425                 rawType = root.getAttributeNS(null,"contactType");
426                 Node n=null;
427                 e=XML.getFirstChildElement(root);
428                 while (e != null) {
429                     if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Company")) {
430                         if (e.hasChildNodes())
431                             company=XML.assign(e.getFirstChild().getNodeValue());
432                     }
433                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"GivenName")) {
434                         if (e.hasChildNodes())
435                             givenName=XML.assign(e.getFirstChild().getNodeValue());
436                     }
437                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"SurName")) {
438                         if (e.hasChildNodes())
439                             surName=XML.assign(e.getFirstChild().getNodeValue());
440                     }
441                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EmailAddress")) {
442                         if (e.hasChildNodes())
443                             emails.add(XML.assign(e.getFirstChild().getNodeValue()));
444                     }
445                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"TelephoneNumber")) {
446                         if (e.hasChildNodes())
447                             telephones.add(XML.assign(e.getFirstChild().getNodeValue()));
448                     }
449                     e=XML.getNextSiblingElement(e);
450                 }
451             }
452                         
453                         if (rawType.equalsIgnoreCase("TECHNICAL")) {
454                                 type = ContactPerson.TECHNICAL;
455                         } else if (rawType.equalsIgnoreCase("SUPPORT")) {
456                                 type = ContactPerson.SUPPORT;
457                         } else if (rawType.equalsIgnoreCase("ADMINISTRATIVE")) {
458                                 type = ContactPerson.ADMINISTRATIVE;
459                         } else if (rawType.equalsIgnoreCase("BILLING")) {
460                                 type = ContactPerson.BILLING;
461                         } else if (rawType.equalsIgnoreCase("OTHER")) {
462                                 type = ContactPerson.OTHER;
463                         } else {
464                                 throw new MetadataException("Contact has unknown contact type.");
465                         }
466                 }
467
468                 public int getType() {
469                         return type;
470                 }
471
472                 public String getGivenName() {
473                         return givenName;
474                 }
475
476         public String getSurName() {
477             return surName;
478         }
479         
480         public String getCompany() {
481             return company;
482         }
483
484         public Iterator getEmailAddresses() {
485                         return emails.iterator();
486                 }
487
488                 public Iterator getTelephoneNumbers() {
489                         return telephones.iterator();
490                 }
491         
492         public Element getElement() {
493             return root;
494         }
495         }
496     
497     class Role implements RoleDescriptor {
498         private Element root = null;
499         private XMLEntityDescriptor provider = null;
500         private URL errorURL = null;
501         private Organization org = null;
502         private ArrayList /* <ContactPerson> */ contacts = new ArrayList();
503         private long validUntil = Long.MAX_VALUE;
504         protected ArrayList /* <String> */ protocolEnum = new ArrayList();
505         protected ArrayList /* <KeyDescriptor> */ keys = new ArrayList();
506
507         public Role(XMLEntityDescriptor provider, long validUntil, Element e) throws MetadataException {
508             root = e;
509             this.validUntil = validUntil;
510             this.provider = provider;
511             
512             // Check the root element namespace. If SAML2, assume it's the std schema.
513             if (e != null && edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
514                
515                 if (e.hasAttributeNS(null,"validUntil")) {
516                     SimpleDateFormat formatter = null;
517                     String dateTime = XML.assign(e.getAttributeNS(null,"validUntil"));
518                     int dot = dateTime.indexOf('.');
519                     if (dot > 0)
520                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
521                     else
522                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
523                     formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
524                     try {
525                         validUntil=Math.min(validUntil,formatter.parse(dateTime).getTime());
526                     }
527                     catch (ParseException e1) {
528                         log.warn("Role descriptor contains invalid expiration time");
529                     }
530                 }
531                 
532                 if (e.hasAttributeNS(null,"errorURL")) {
533                     try {
534                         errorURL=new URL(e.getAttributeNS(null,"errorURL"));
535                     }
536                     catch (MalformedURLException e1) {
537                         log.error("Role descriptor contains malformed errorURL");
538                     }
539                 }
540                 
541                 // Chop the protocol list into pieces...assume any whitespace can appear in between.   
542                 protocolEnum.addAll(Arrays.asList(e.getAttributeNS(null,"protocolSupportEnumeration").split("\\s")));
543                 
544                 e = XML.getFirstChildElement(root,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"KeyDescriptor");
545                 while (e != null) {
546                     keys.add(new XMLKeyDescriptor(e));
547                     e = XML.getNextSiblingElement(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"KeyDescriptor");
548                 }
549
550                 e = XML.getFirstChildElement(root,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Organization");
551                 if (e != null)
552                     org=new XMLOrganization(e);
553
554                 e = XML.getFirstChildElement(root,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"ContactPerson");
555                 while (e != null) {
556                     contacts.add(new XMLContactPerson(e));
557                     e = XML.getNextSiblingElement(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"ContactPerson");
558                 }
559             }
560         }
561         
562         public EntityDescriptor getEntityDescriptor() {
563             return provider;
564         }
565
566         public Iterator getProtocolSupportEnumeration() {
567             return protocolEnum.iterator();
568         }
569
570         public boolean hasSupport(String version) {
571             return protocolEnum.contains(version);
572         }
573
574         public boolean isValid() {
575             return System.currentTimeMillis() < validUntil;
576         }
577
578         public URL getErrorURL() {
579             return (errorURL != null) ? errorURL : provider.getErrorURL();
580         }
581
582         public Iterator getKeyDescriptors() {
583             return keys.iterator();
584         }
585
586         public Organization getOrganization() {
587             return (org != null) ? org : provider.getOrganization();
588         }
589
590         public Iterator getContactPersons() {
591             return (contacts.isEmpty()) ? provider.getContactPersons() : contacts.iterator();
592         }
593
594         public Element getElement() {
595             return root;
596         }
597     }
598     
599     class SSORole extends Role implements SSODescriptor {
600         private XMLEndpointManager artifact = new XMLEndpointManager();
601         private XMLEndpointManager logout = new XMLEndpointManager();
602         private XMLEndpointManager nameid = new XMLEndpointManager();
603         private ArrayList /* <String> */ formats = new ArrayList();
604
605         public SSORole(XMLEntityDescriptor provider, long validUntil, Element e) throws MetadataException {
606             super(provider, validUntil, e);
607             
608             // Check the root element namespace. If SAML2, assume it's the std schema.
609             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
610                 int i;
611                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"ArtifactResolutionService");
612                 for (i=0; i<nlist.getLength(); i++)
613                     artifact.add(new XMLIndexedEndpoint((Element)nlist.item(i)));
614
615                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"SingleLogoutService");
616                 for (i=0; i<nlist.getLength(); i++)
617                     logout.add(new XMLEndpoint((Element)nlist.item(i)));
618
619                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"ManageNameIDService");
620                 for (i=0; i<nlist.getLength(); i++)
621                     nameid.add(new XMLEndpoint((Element)nlist.item(i)));
622
623                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"NameIDFormat");
624                 for (i = 0; i < nlist.getLength(); i++) {
625                                         if (nlist.item(i).hasChildNodes()) {
626                                                 Node tnode = nlist.item(i).getFirstChild();
627                                                 if (tnode != null && tnode.getNodeType() == Node.TEXT_NODE) {
628                                                         formats.add(tnode.getNodeValue());
629                                                 }
630                                         }
631                                 }
632             }
633             else {
634                 // For old style, we just do SAML 1.1 compatibility with Shib handles.
635                 protocolEnum.add(XML.SAML11_PROTOCOL_ENUM);
636                 formats.add(Constants.SHIB_NAMEID_FORMAT_URI);
637             }
638         }
639
640         public EndpointManager getArtifactResolutionServiceManager() {
641             return artifact;
642         }
643
644         public EndpointManager getSingleLogoutServiceManager() {
645             return logout;
646         }
647
648         public EndpointManager getManageNameIDServiceManager() {
649             return nameid;
650         }
651
652         public Iterator getNameIDFormats() {
653             return formats.iterator();
654         }
655     }
656     
657     class IDPRole extends SSORole implements IDPSSODescriptor, ScopedRoleDescriptor {
658         private ArrayList /* <Scope> */ scopes = new ArrayList();
659         private XMLEndpointManager sso = new XMLEndpointManager();
660         private XMLEndpointManager mapping = new XMLEndpointManager();
661         private XMLEndpointManager idreq = new XMLEndpointManager();
662         private ArrayList /* <String> */ attrprofs = new ArrayList();
663         private ArrayList /* <SAMLAttribute> */ attrs = new ArrayList();
664         private boolean wantAuthnRequestsSigned = false;
665         private String sourceId = null;
666
667         public IDPRole(XMLEntityDescriptor provider, long validUntil, Element e) throws SAMLException {
668             super(provider, validUntil, e);
669             NodeList domains=null;
670             
671             // Check the root element namespace. If SAML2, assume it's the std schema.
672             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
673                 String flag=XML.assign(e.getAttributeNS(null,"WantAuthnRequestsSigned"));
674                 wantAuthnRequestsSigned=(XML.safeCompare(flag,"1") || XML.safeCompare(flag,"true"));
675                 
676                 // Check for extensions.
677                 Element ext=XML.getFirstChildElement(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Extensions");
678                 if (ext != null) {
679                     Element ext1=XML.getFirstChildElement(ext,XML.SAML_ARTIFACT_SOURCEID,"SourceID");
680                     if (ext1 != null && ext1.hasChildNodes())
681                         sourceId=ext1.getFirstChild().getNodeValue();
682                     // Save off any domain elements for later.
683                     domains = ext.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"Scope");
684                 }
685                 
686                 int i;
687                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"SingleSignOnService");
688                 for (i=0; i<nlist.getLength(); i++)
689                     sso.add(new XMLEndpoint((Element)(nlist.item(i))));
690
691                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"NameIDMappingService");
692                 for (i=0; i<nlist.getLength(); i++)
693                     mapping.add(new XMLEndpoint((Element)(nlist.item(i))));
694
695                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AssertionIDRequestService");
696                 for (i=0; i<nlist.getLength(); i++)
697                     idreq.add(new XMLEndpoint((Element)(nlist.item(i))));
698
699                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AttributeProfile");
700                 for (i=0; i<nlist.getLength(); i++) {
701                     if (nlist.item(i).hasChildNodes())
702                         attrprofs.add(nlist.item(i).getFirstChild().getNodeValue());
703                 }
704
705                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"Attribute");
706                 for (i=0; i<nlist.getLength(); i++) {
707                     // For now, we need to convert these to plain SAML 1.1 attributes.
708                     Element src=(Element)(nlist.item(i));
709                     Element copy=e.getOwnerDocument().createElementNS(XML.SAML_NS,"Attribute");
710                     copy.setAttributeNS(null,"AttributeName",src.getAttributeNS(null,"Name"));
711                     copy.setAttributeNS(null,"AttributeNamespace",src.getAttributeNS(null,"NameFormat"));
712                     src=XML.getFirstChildElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
713                     while (src != null) {
714                         src=XML.getNextSiblingElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
715                         Element val=e.getOwnerDocument().createElementNS(XML.SAML_NS,"AttributeValue");
716                         NamedNodeMap attrs = src.getAttributes();
717                         for (int j=0; j<attrs.getLength(); j++)
718                             val.setAttributeNodeNS((Attr)(e.getOwnerDocument().importNode(attrs.item(j),true)));
719                         while (src.hasChildNodes())
720                             val.appendChild(src.getFirstChild());
721                         copy.appendChild(val);
722                     }
723                     attrs.add(SAMLAttribute.getInstance(copy));
724                 }
725             }
726             else {
727                 attrprofs.add(Constants.SHIB_ATTRIBUTE_NAMESPACE_URI);
728                 int i;
729                 domains = e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"Domain");
730                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"HandleService");
731                 for (i=0; i<nlist.getLength(); i++) {
732                     // Manufacture an endpoint for the "Shib" binding.
733                     sso.add(
734                         new XMLEndpoint(Constants.SHIB_AUTHNREQUEST_PROFILE_URI,((Element)nlist.item(i)).getAttributeNS(null,"Location"))
735                         );
736
737                     // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
738                     Element kd=e.getOwnerDocument().createElementNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"KeyDescriptor");
739                     Element ki=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyInfo");
740                     Element kn=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyName");
741                     kn.appendChild(
742                         e.getOwnerDocument().createTextNode(((Element)nlist.item(i)).getAttributeNS(null,"Name"))
743                         );
744                     ki.appendChild(kn);
745                     kd.appendChild(ki);
746                     kd.setAttributeNS(null,"use","signing");
747                     keys.add(new XMLKeyDescriptor(kd));
748                 }
749             }
750             
751             if (domains != null) {
752                 for (int i=0; i < domains.getLength(); i++) {
753                     String dom=(domains.item(i).hasChildNodes()) ? domains.item(i).getFirstChild().getNodeValue() : null;
754                     if (dom != null) {
755                         String regexp=XML.assign(((Element)domains.item(i)).getAttributeNS(null,"regexp"));
756                         scopes.add(
757                             new Scope(dom,(XML.safeCompare(regexp,"true") || XML.safeCompare(regexp,"1")))
758                             );
759                     }
760                 }
761             }
762         }
763
764         public Iterator getScopes() {
765             return scopes.iterator();
766         }
767
768         public boolean getWantAuthnRequestsSigned() {
769             return wantAuthnRequestsSigned;
770         }
771
772         public EndpointManager getSingleSignOnServiceManager() {
773             return sso;
774         }
775
776         public EndpointManager getNameIDMappingServiceManager() {
777             return mapping;
778         }
779
780         public EndpointManager getAssertionIDRequestServiceManager() {
781             return idreq;
782         }
783
784         public Iterator getAttributeProfiles() {
785             return attrprofs.iterator();
786         }
787
788         public Iterator getAttributes() {
789             return attrs.iterator();
790         }
791     }
792
793     class AARole extends Role implements AttributeAuthorityDescriptor, ScopedRoleDescriptor {
794         private ArrayList /* <Scope> */ scopes = new ArrayList();
795         private XMLEndpointManager query = new XMLEndpointManager();
796         private XMLEndpointManager idreq = new XMLEndpointManager();
797         private ArrayList /* <String> */ attrprofs = new ArrayList();
798         private ArrayList /* <String> */ formats = new ArrayList();
799         private ArrayList /* <SAMLAttribute> */ attrs = new ArrayList();
800
801         public AARole(XMLEntityDescriptor provider, long validUntil, Element e) throws SAMLException {
802             super(provider, validUntil, e);
803             NodeList domains=null;
804             
805             // Check the root element namespace. If SAML2, assume it's the std schema.
806             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
807                 
808                 // Check for extensions.
809                 Element ext=XML.getFirstChildElement(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Extensions");
810                 if (ext != null) {
811                     // Save off any domain elements for later.
812                     domains = ext.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"Scope");
813                 }
814                 
815                 int i;
816                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AttributeService");
817                 for (i=0; i<nlist.getLength(); i++)
818                     query.add(new XMLEndpoint((Element)(nlist.item(i))));
819
820                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AssertionIDRequestService");
821                 for (i=0; i<nlist.getLength(); i++)
822                     idreq.add(new XMLEndpoint((Element)(nlist.item(i))));
823
824                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AttributeProfile");
825                 for (i=0; i<nlist.getLength(); i++) {
826                     if (nlist.item(i).hasChildNodes())
827                         attrprofs.add(nlist.item(i).getFirstChild().getNodeValue());
828                 }
829
830                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"Attribute");
831                 for (i=0; i<nlist.getLength(); i++) {
832                     // For now, we need to convert these to plain SAML 1.1 attributes.
833                     Element src=(Element)(nlist.item(i));
834                     Element copy=e.getOwnerDocument().createElementNS(XML.SAML_NS,"Attribute");
835                     copy.setAttributeNS(null,"AttributeName",src.getAttributeNS(null,"Name"));
836                     copy.setAttributeNS(null,"AttributeNamespace",src.getAttributeNS(null,"NameFormat"));
837                     src=XML.getFirstChildElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
838                     while (src != null) {
839                         src=XML.getNextSiblingElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
840                         Element val=e.getOwnerDocument().createElementNS(XML.SAML_NS,"AttributeValue");
841                         NamedNodeMap attrs = src.getAttributes();
842                         for (int j=0; j<attrs.getLength(); j++)
843                             val.setAttributeNodeNS((Attr)(e.getOwnerDocument().importNode(attrs.item(j),true)));
844                         while (src.hasChildNodes())
845                             val.appendChild(src.getFirstChild());
846                         copy.appendChild(val);
847                     }
848                     attrs.add(SAMLAttribute.getInstance(copy));
849                 }
850             }
851             else {
852                 // For old style, we just do SAML 1.1 compatibility with Shib handles.
853                 protocolEnum.add(XML.SAML11_PROTOCOL_ENUM);
854                 formats.add(Constants.SHIB_NAMEID_FORMAT_URI);
855                 attrprofs.add(Constants.SHIB_ATTRIBUTE_NAMESPACE_URI);
856                 domains = e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"Domain");
857                 int i;
858                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AttributeAuthority");
859                 for (i=0; i<nlist.getLength(); i++) {
860                     // Manufacture an endpoint for the SOAP binding.
861                     query.add(
862                         new XMLEndpoint(
863                             SAMLBinding.SOAP,
864                             ((Element)nlist.item(i)).getAttributeNS(null,"Location")
865                             )
866                         );
867
868                     // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
869                     Element kd=e.getOwnerDocument().createElementNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"KeyDescriptor");
870                     Element ki=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyInfo");
871                     Element kn=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyName");
872                     kn.appendChild(
873                         e.getOwnerDocument().createTextNode(((Element)nlist.item(i)).getAttributeNS(null,"Name"))
874                         );
875                     ki.appendChild(kn);
876                     kd.appendChild(ki);
877                     kd.setAttributeNS(null,"use","signing");
878                     keys.add(new XMLKeyDescriptor(kd));
879                 }
880             }
881
882             if (domains != null) {
883                 for (int i=0; i < domains.getLength(); i++) {
884                     String dom=(domains.item(i).hasChildNodes()) ? domains.item(i).getFirstChild().getNodeValue() : null;
885                     if (dom != null) {
886                         String regexp=XML.assign(((Element)domains.item(i)).getAttributeNS(null,"regexp"));
887                         scopes.add(
888                             new Scope(dom,(XML.safeCompare(regexp,"true") || XML.safeCompare(regexp,"1")))
889                             );
890                     }
891                 }
892             }
893         }
894
895         public Iterator getScopes() {
896             return scopes.iterator();
897         }
898
899         public EndpointManager getAttributeServiceManager() {
900             return query;
901         }
902
903         public EndpointManager getAssertionIDRequestServiceManager() {
904             return idreq;
905         }
906
907         public Iterator getAttributeProfiles() {
908             return attrprofs.iterator();
909         }
910
911         public Iterator getAttributes() {
912             return attrs.iterator();
913         }
914
915         public Iterator getNameIDFormats() {
916             return formats.iterator();
917         }
918     }
919     
920     class SPRole extends SSORole implements SPSSODescriptor {
921         private boolean authnRequestsSigned = false;
922         private boolean wantAssertionsSigned = false;
923         private XMLEndpointManager asc = new XMLEndpointManager();
924         
925         public SPRole(XMLEntityDescriptor provider, long validUntil, Element e) throws MetadataException {
926             super(provider, validUntil, e);
927
928             // Check the root element namespace. If SAML2, assume it's the std schema.
929             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
930                 String flag=XML.assign(e.getAttributeNS(null,"AuthnRequestsSigned"));
931                 authnRequestsSigned=(XML.safeCompare(flag,"1") || XML.safeCompare(flag,"true"));
932                 flag=XML.assign(e.getAttributeNS(null,"WantAssertionsSigned"));
933                 wantAssertionsSigned=(XML.safeCompare(flag,"1") || XML.safeCompare(flag,"true"));
934                 
935                 int i;
936                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AssertionConsumerService");
937                 for (i=0; i<nlist.getLength(); i++)
938                     asc.add(new XMLIndexedEndpoint((Element)(nlist.item(i))));
939
940                 /*
941                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"Attribute");
942                 for (i=0; i<nlist.getLength(); i++) {
943                     // For now, we need to convert these to plain SAML 1.1 attributes.
944                     Element src=(Element)(nlist.item(i));
945                     Element copy=e.getOwnerDocument().createElementNS(XML.SAML_NS,"Attribute");
946                     copy.setAttributeNS(null,"AttributeName",src.getAttributeNS(null,"Name"));
947                     copy.setAttributeNS(null,"AttributeNamespace",src.getAttributeNS(null,"NameFormat"));
948                     src=XML.getFirstChildElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
949                     while (src != null) {
950                         src=XML.getNextSiblingElement(src,edu.internet2.middleware.shibboleth.common.XML.SAML2ASSERT_NS,"AttributeValue");
951                         Element val=e.getOwnerDocument().createElementNS(XML.SAML_NS,"AttributeValue");
952                         NamedNodeMap attrs = src.getAttributes();
953                         for (int j=0; j<attrs.getLength(); j++)
954                             val.setAttributeNodeNS((Attr)(e.getOwnerDocument().importNode(attrs.item(j),true)));
955                         while (src.hasChildNodes())
956                             val.appendChild(src.getFirstChild());
957                         copy.appendChild(val);
958                     }
959                     attrs.add(SAMLAttribute.getInstance(copy));
960                 }
961                 */
962             }
963             else {
964                 int i;
965                 NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AssertionConsumerServiceURL");
966                 for (i=0; i<nlist.getLength(); i++) {
967                     // Manufacture an endpoint for the POST profile.
968                     asc.add(
969                         new XMLEndpoint(SAMLBrowserProfile.PROFILE_POST_URI,((Element)nlist.item(i)).getAttributeNS(null,"Location"))
970                         );
971                 }
972                 
973                 nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AttributeRequester");
974                 for (i=0; i<nlist.getLength(); i++) {
975                     // We're going to "mock up" a KeyDescriptor that contains the specified Name as a ds:KeyName.
976                     Element kd=e.getOwnerDocument().createElementNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"KeyDescriptor");
977                     Element ki=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyInfo");
978                     Element kn=e.getOwnerDocument().createElementNS(XML.XMLSIG_NS,"KeyName");
979                     kn.appendChild(
980                         e.getOwnerDocument().createTextNode(((Element)nlist.item(i)).getAttributeNS(null,"Name"))
981                         );
982                     ki.appendChild(kn);
983                     kd.appendChild(ki);
984                     kd.setAttributeNS(null,"use","signing");
985                     keys.add(new XMLKeyDescriptor(kd));
986                 }
987             }
988         }
989
990         public boolean getAuthnRequestsSigned() {
991             return authnRequestsSigned;
992         }
993
994         public boolean getWantAssertionsSigned() {
995             return wantAssertionsSigned;
996         }
997
998         public EndpointManager getAssertionConsumerServiceManager() {
999             return asc;
1000         }
1001
1002         public Iterator getAttributeConsumingServices() {
1003             // TODO Auto-generated method stub
1004             return null;
1005         }
1006
1007         public AttributeConsumingService getDefaultAttributeConsumingService() {
1008             // TODO Auto-generated method stub
1009             return null;
1010         }
1011
1012         public AttributeConsumingService getAttributeConsumingServiceByID(String id) {
1013             // TODO Auto-generated method stub
1014             return null;
1015         }
1016     }
1017
1018     class AttributeRequesterRole extends Role implements AttributeRequesterDescriptor {
1019         private boolean wantAssertionsSigned = false;
1020         private ArrayList /* <String> */ formats = new ArrayList();
1021         
1022         public AttributeRequesterRole(XMLEntityDescriptor provider, long validUntil, Element e) throws MetadataException {
1023             super(provider, validUntil, e);
1024
1025             String flag=XML.assign(e.getAttributeNS(null,"WantAssertionsSigned"));
1026             wantAssertionsSigned=(XML.safeCompare(flag,"1") || XML.safeCompare(flag,"true"));
1027
1028             NodeList nlist=e.getElementsByTagNameNS(edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"NameIDFormat");
1029             for (int i = 0; i < nlist.getLength(); i++) {
1030                 if (nlist.item(i).hasChildNodes()) {
1031                     Node tnode = nlist.item(i).getFirstChild();
1032                     if (tnode != null && tnode.getNodeType() == Node.TEXT_NODE) {
1033                         formats.add(tnode.getNodeValue());
1034                     }
1035                 }
1036             }
1037         }
1038
1039         public boolean getWantAssertionsSigned() {
1040             return wantAssertionsSigned;
1041         }
1042
1043         public Iterator getNameIDFormats() {
1044             return formats.iterator();
1045         }
1046
1047         public Iterator getAttributeConsumingServices() {
1048             // TODO Auto-generated method stub
1049             return null;
1050         }
1051
1052         public AttributeConsumingService getDefaultAttributeConsumingService() {
1053             // TODO Auto-generated method stub
1054             return null;
1055         }
1056
1057         public AttributeConsumingService getAttributeConsumingServiceByID(String id) {
1058             // TODO Auto-generated method stub
1059             return null;
1060         }
1061     }
1062     
1063     class XMLEntityDescriptor implements ExtendedEntityDescriptor {
1064         private Element root = null;
1065         private EntitiesDescriptor parent = null;
1066         private String id = null;
1067         private URL errorURL = null;
1068         private Organization org = null;
1069         private ArrayList /* <ContactPerson> */ contacts = new ArrayList();
1070         private ArrayList /* <RoleDescriptor> */ roles = new ArrayList();
1071         private AffiliationDescriptor affiliation = null;
1072         private HashMap /* <String,String> */ locs = new HashMap();
1073         private long validUntil = Long.MAX_VALUE;
1074         private ArrayList /* <KeyAuthority> */ keyauths = new ArrayList();
1075         
1076         public XMLEntityDescriptor(Element e, XMLMetadataProvider wrapper, long validUntil, EntitiesDescriptor parent) throws SAMLException {
1077             root = e;
1078             this.parent = parent;
1079             this.validUntil = validUntil;
1080
1081             // Check the root element namespace. If SAML2, assume it's the std schema.
1082             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
1083                 id=e.getAttributeNS(null,"entityID");
1084
1085                 if (e.hasAttributeNS(null,"validUntil")) {
1086                     SimpleDateFormat formatter = null;
1087                     String dateTime = XML.assign(e.getAttributeNS(null,"validUntil"));
1088                     int dot = dateTime.indexOf('.');
1089                     if (dot > 0)
1090                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
1091                     else
1092                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
1093                     formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
1094                     try {
1095                         validUntil=Math.min(validUntil,formatter.parse(dateTime).getTime());
1096                     }
1097                     catch (ParseException e1) {
1098                         log.warn("Entity descriptor contains invalid expiration time");
1099                     }
1100                 }
1101
1102                 Element child=XML.getFirstChildElement(e);
1103                 while (child != null) {
1104                     // Process the various kinds of children that we care about...
1105                     if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Extensions")) {
1106                         Element ext = XML.getFirstChildElement(child,edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"KeyAuthority");
1107                         while (ext != null) {
1108                             keyauths.add(new XMLKeyAuthority(ext));
1109                             ext = XML.getNextSiblingElement(ext,edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"KeyAuthority");
1110                         }
1111                     }
1112                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"ContactPerson")) {
1113                         contacts.add(new XMLContactPerson(child));
1114                     }
1115                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Organization")) {
1116                         org=new XMLOrganization(child);
1117                     }
1118                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AdditionalMetadataLocation")) {
1119                         Node loc=child.getFirstChild();
1120                         if (loc != null)
1121                             locs.put(child.getAttributeNS(null,"namespace"),loc.getNodeValue());
1122                     }
1123                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"IDPSSODescriptor")) {
1124                         roles.add(new IDPRole(this,validUntil,child));
1125                     }
1126                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"AttributeAuthorityDescriptor")) {
1127                         roles.add(new AARole(this,validUntil,child));
1128                     }
1129                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"SPSSODescriptor")) {
1130                         roles.add(new SPRole(this,validUntil,child));
1131                     }
1132                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"RoleDescriptor")) {
1133                         QName xsitype = XML.getQNameAttribute(child,XML.XSI_NS,"type");
1134                         if (edu.internet2.middleware.shibboleth.common.XML.SAML2METAEXT_NS.equals(xsitype.getNamespaceURI()) &&
1135                                 "AttributeRequesterDescriptorType".equals(xsitype.getLocalPart()))
1136                             roles.add(new AttributeRequesterRole(this,validUntil,child));
1137                     }
1138                     child = XML.getNextSiblingElement(child);
1139                 }
1140             }
1141             else {
1142                 id=e.getAttributeNS(null,"Name");
1143                 if (e.hasAttributeNS(null,"ErrorURL")) {
1144                     try {
1145                         errorURL=new URL(e.getAttributeNS(null,"ErrorURL"));
1146                     }
1147                     catch (MalformedURLException e1) {
1148                         log.error("Site descriptor contains invalid ErrorURL");
1149                     }
1150                 }
1151                 
1152                 boolean idp=false,aa=false,sp=false;    // only want to build a role once
1153                 Element child=XML.getFirstChildElement(e);
1154                 while (child != null) {
1155                     // Process the various kinds of OriginSite children that we care about...
1156                     if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"Contact")) {
1157                         contacts.add(new XMLContactPerson(child));
1158                     }
1159                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"HandleService") && !idp) {
1160                         // Create the IDP role if needed.
1161                         roles.add(new IDPRole(this, validUntil, e));
1162                         idp=true;
1163                     }
1164                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AttributeAuthority") && !aa) {
1165                         // Create the AA role if needed.
1166                         roles.add(new AARole(this, validUntil, e));
1167                         aa=true;
1168                     }
1169                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AssertionConsumerServiceURL") && !sp) {
1170                         // Create the SP role if needed.
1171                         roles.add(new SPRole(this, validUntil, e));
1172                         sp=true;
1173                     }
1174                     else if (XML.isElementNamed(child,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"AttributeRequester") && !sp) {
1175                         // Create the SP role if needed.
1176                         roles.add(new SPRole(this, validUntil, e));
1177                         sp=true;
1178                     }
1179                     child = XML.getNextSiblingElement(child);
1180                 }
1181             }
1182
1183             // Each map entry is a list of the descriptors with this ID.
1184             ArrayList list;
1185             if (wrapper.sites.containsKey(id)) {
1186                 list = (ArrayList)wrapper.sites.get(id);
1187             }
1188             else {
1189                 list = new ArrayList();
1190                 wrapper.sites.put(id,list);
1191             }
1192             list.add(this);
1193             
1194             // Look for an IdP role, and register the artifact source ID and endpoints.
1195             IDPRole idp=null;
1196             for (int i=0; i<roles.size(); i++) {
1197                 if (roles.get(i) instanceof IDPRole) {
1198                     idp = (IDPRole)roles.get(i);
1199                     if (idp.sourceId != null) {
1200                         if (wrapper.sources.containsKey(idp.sourceId)) {
1201                             list = (ArrayList)wrapper.sources.get(idp.sourceId);
1202                         }
1203                         else {
1204                             list = new ArrayList();
1205                             wrapper.sources.put(idp.sourceId,list);
1206                         }
1207                         list.add(this);
1208                     }
1209                     else {
1210                         String sourceId;
1211                         try {
1212                             sourceId = new String(Hex.encode(Util.generateSourceId(id)));
1213                         }
1214                         catch (NoSuchAlgorithmException e1) {
1215                             log.error("caught exception while encoding sourceId: " + e1.getMessage());
1216                             continue;
1217                         }
1218                         if (wrapper.sources.containsKey(sourceId)) {
1219                             list = (ArrayList)wrapper.sources.get(sourceId);
1220                         }
1221                         else {
1222                             list = new ArrayList();
1223                             wrapper.sources.put(sourceId,list);
1224                         }
1225                         list.add(this);
1226                     }
1227                     Iterator locs=idp.getArtifactResolutionServiceManager().getEndpoints();
1228                     while (locs.hasNext()) {
1229                         String loc=((Endpoint)locs.next()).getLocation();
1230                         if (wrapper.sources.containsKey(loc)) {
1231                             list = (ArrayList)wrapper.sources.get(loc);
1232                         }
1233                         else {
1234                             list = new ArrayList();
1235                             wrapper.sources.put(loc,list);
1236                         }
1237                         list.add(this);
1238                     }
1239                 }
1240             }
1241         }
1242         
1243         public String getId() {
1244             return id;
1245         }
1246
1247         public boolean isValid() {
1248             return System.currentTimeMillis() < validUntil;
1249         }
1250
1251         public Iterator getRoleDescriptors() {
1252             return roles.iterator();
1253         }
1254
1255         public RoleDescriptor getRoleByType(Class type, String protocol) {
1256             for (int i=0; i<roles.size(); i++) {
1257                 RoleDescriptor role = (RoleDescriptor)roles.get(i);
1258                 if (type.isInstance(role) && role.hasSupport(protocol))
1259                     return role;
1260             }
1261             return null;
1262         }
1263
1264         public IDPSSODescriptor getIDPSSODescriptor(String protocol) {
1265             return (IDPSSODescriptor)getRoleByType(IDPSSODescriptor.class, protocol);
1266         }
1267
1268         public SPSSODescriptor getSPSSODescriptor(String protocol) {
1269             return (SPSSODescriptor)getRoleByType(SPSSODescriptor.class, protocol);
1270         }
1271
1272         public AuthnAuthorityDescriptor getAuthnAuthorityDescriptor(String protocol) {
1273             return (AuthnAuthorityDescriptor)getRoleByType(AuthnAuthorityDescriptor.class, protocol);
1274         }
1275
1276         public AttributeAuthorityDescriptor getAttributeAuthorityDescriptor(String protocol) {
1277             return (AttributeAuthorityDescriptor)getRoleByType(AttributeAuthorityDescriptor.class, protocol);
1278         }
1279
1280         public AttributeRequesterDescriptor getAttributeRequesterDescriptor(String protocol) {
1281             return (AttributeRequesterDescriptor)getRoleByType(AttributeRequesterDescriptor.class, protocol);
1282         }
1283         
1284         public PDPDescriptor getPDPDescriptor(String protocol) {
1285             return (PDPDescriptor)getRoleByType(PDPDescriptor.class, protocol);
1286         }
1287
1288         public AffiliationDescriptor getAffiliationDescriptor() {
1289             return affiliation;
1290         }
1291
1292         public Organization getOrganization() {
1293             return org;
1294         }
1295
1296         public Iterator getContactPersons() {
1297             return contacts.iterator();
1298         }
1299
1300         public Map getAdditionalMetadataLocations() {
1301             return Collections.unmodifiableMap(locs);
1302         }
1303
1304         public EntitiesDescriptor getEntitiesDescriptor() {
1305             return parent;
1306         }
1307
1308         public Element getElement() {
1309             return root;
1310         }
1311         
1312         public long getValidUntil() {
1313             return validUntil;
1314         }
1315         
1316         public URL getErrorURL() {
1317             return errorURL;
1318         }
1319
1320         public Iterator getKeyAuthorities() {
1321             return keyauths.iterator();
1322         }
1323     }
1324     
1325     class XMLEntitiesDescriptor implements ExtendedEntitiesDescriptor {
1326         private Element root = null;
1327         private EntitiesDescriptor parent = null;
1328         private String name = null;
1329         private ArrayList /* <EntitiesDescriptor> */ groups = new ArrayList();
1330         private ArrayList /* <EntityDescriptor> */ providers = new ArrayList();
1331         private long validUntil = Long.MAX_VALUE;
1332         private ArrayList /* <KeyAuthority> */ keyauths = new ArrayList();
1333         
1334         public XMLEntitiesDescriptor(Element e, XMLMetadataProvider wrapper, long validUntil, EntitiesDescriptor parent) throws SAMLException {
1335             root = e;
1336             this.parent = parent;
1337             this.validUntil = validUntil;
1338             name = XML.assign(e.getAttributeNS(null, "Name"));
1339
1340             // Check the root element namespace. If SAML2, assume it's the std schema.
1341             if (edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS.equals(e.getNamespaceURI())) {
1342
1343                 if (e.hasAttributeNS(null,"validUntil")) {
1344                     SimpleDateFormat formatter = null;
1345                     String dateTime = XML.assign(e.getAttributeNS(null,"validUntil"));
1346                     int dot = dateTime.indexOf('.');
1347                     if (dot > 0)
1348                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
1349                     else
1350                         formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
1351                     formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
1352                     try {
1353                         validUntil=Math.min(validUntil,formatter.parse(dateTime).getTime());
1354                     }
1355                     catch (ParseException e1) {
1356                         log.warn("Entities descriptor contains invalid expiration time");
1357                     }
1358                 }
1359
1360                 e = XML.getFirstChildElement(e);
1361                 while (e != null) {
1362                     if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"Extensions")) {
1363                         Element ext = XML.getFirstChildElement(e,edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"KeyAuthority");
1364                         while (ext != null) {
1365                             keyauths.add(new XMLKeyAuthority(ext));
1366                             ext = XML.getNextSiblingElement(ext,edu.internet2.middleware.shibboleth.common.XML.SHIBMETA_NS,"KeyAuthority");
1367                         }
1368                     }
1369                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EntitiesDescriptor"))
1370                         groups.add(new XMLEntitiesDescriptor(e, wrapper, this.validUntil, this));
1371                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SAML2META_NS,"EntityDescriptor"))
1372                         providers.add(new XMLEntityDescriptor(e, wrapper, this.validUntil, this));
1373                     e = XML.getNextSiblingElement(e);
1374                 }
1375             }
1376             else {
1377                 e = XML.getFirstChildElement(e);
1378                 while (e != null) {
1379                     if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"SiteGroup"))
1380                         groups.add(new XMLEntitiesDescriptor(e, wrapper, this.validUntil, this));
1381                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"OriginSite"))
1382                         providers.add(new XMLEntityDescriptor(e, wrapper, this.validUntil, this));
1383                     else if (XML.isElementNamed(e,edu.internet2.middleware.shibboleth.common.XML.SHIB_NS,"DestinationSite"))
1384                         providers.add(new XMLEntityDescriptor(e, wrapper, this.validUntil, this));
1385                     e = XML.getNextSiblingElement(e);
1386                 }
1387             }
1388         }
1389
1390         public String getName() {
1391             return name;
1392         }
1393
1394         public boolean isValid() {
1395             return System.currentTimeMillis() < validUntil;
1396         }
1397
1398         public EntitiesDescriptor getEntitiesDescriptor() {
1399             return parent;
1400         }
1401
1402         public Iterator getEntitiesDescriptors() {
1403             return groups.iterator();
1404         }
1405
1406         public Iterator getEntityDescriptors() {
1407             return providers.iterator();
1408         }
1409
1410         public Element getElement() {
1411             return root;
1412         }
1413
1414         public Iterator getKeyAuthorities() {
1415             return keyauths.iterator();
1416         }
1417     }
1418 }