More name mapping updates.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / hs / provider / SharedMemoryShibHandle.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation
3  * for Advanced Internet Development, Inc. All rights reserved
4  * 
5  * 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  * 
9  * Redistributions of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  * 
12  * Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution, if any, must include
15  * the following acknowledgment: "This product includes software developed by
16  * the University Corporation for Advanced Internet Development
17  * <http://www.ucaid.edu> Internet2 Project. Alternately, this acknowledegement
18  * may appear in the software itself, if and wherever such third-party
19  * acknowledgments normally appear.
20  * 
21  * Neither the name of Shibboleth nor the names of its contributors, nor
22  * Internet2, nor the University Corporation for Advanced Internet Development,
23  * Inc., nor UCAID may be used to endorse or promote products derived from this
24  * software without specific prior written permission. For written permission,
25  * please contact shibboleth@shibboleth.org
26  * 
27  * Products derived from this software may not be called Shibboleth, Internet2,
28  * UCAID, or the University Corporation for Advanced Internet Development, nor
29  * may Shibboleth appear in their name, without prior written permission of the
30  * University Corporation for Advanced Internet Development.
31  * 
32  * 
33  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
34  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
35  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
36  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
37  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
38  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
39  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY
40  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
41  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
45  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  */
47 package edu.internet2.middleware.shibboleth.hs.provider;
48
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.Map.Entry;
55
56 import org.apache.log4j.Logger;
57 import org.doomdark.uuid.UUIDGenerator;
58 import org.opensaml.SAMLException;
59 import org.opensaml.SAMLNameIdentifier;
60 import org.w3c.dom.Element;
61
62 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
63 import edu.internet2.middleware.shibboleth.common.IdentityProvider;
64 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
65 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
66 import edu.internet2.middleware.shibboleth.common.ServiceProvider;
67 import edu.internet2.middleware.shibboleth.hs.HSNameIdentifierMapping;
68
69 /**
70  * @author Walter Hoehn
71  */
72 public class SharedMemoryShibHandle extends AQHNameIdentifierMapping implements HSNameIdentifierMapping {
73
74         protected HandleCache cache = HandleCache.instance();
75         private static Logger log = Logger.getLogger(SharedMemoryShibHandle.class.getName());
76
77         public SharedMemoryShibHandle(Element config) throws NameIdentifierMappingException {
78                 super(config);
79                 //If we add anything to this constructor, 
80         }
81
82         public SAMLNameIdentifier getNameIdentifierName(
83                 AuthNPrincipal principal,
84                 ServiceProvider sProv,
85                 IdentityProvider idProv)
86                 throws NameIdentifierMappingException {
87
88                 if (principal == null) {
89                         log.error("A principal must be supplied for Attribute Query Handle creation.");
90                         throw new IllegalArgumentException("A principal must be supplied for Attribute Query Handle creation.");
91                 }
92
93                 String handle = UUIDGenerator.getInstance().generateRandomBasedUUID().toString();
94                 log.debug("Assigning handle (" + handle + ") to principal (" + principal.getName() + ").");
95                 synchronized (cache.handleEntries) {
96                         cache.handleEntries.put(handle, createHandleEntry(principal));
97                 }
98
99                 try {
100                         return new SAMLNameIdentifier(handle, idProv.getId(), getNameIdentifierFormat().toString());
101                 } catch (SAMLException e) {
102                         throw new NameIdentifierMappingException("Unable to generate Attribute Query Handle: " + e);
103                 }
104
105         }
106
107         public AuthNPrincipal getPrincipal(SAMLNameIdentifier nameId, ServiceProvider sProv, IdentityProvider idProv)
108                 throws NameIdentifierMappingException, InvalidNameIdentifierException {
109
110                 synchronized (cache.handleEntries) {
111                         if (!cache.handleEntries.containsKey(nameId.getName())) {
112                                 log.debug("The Name Mapping Cache does not contain an entry for this Attribute Query Handle.");
113                                 throw new InvalidNameIdentifierException("The Name Mapping Cache does not contain an entry for this Attribute Query Handle.");
114                         }
115                 }
116
117                 HandleEntry handleEntry;
118                 synchronized (cache.handleEntries) {
119                         handleEntry = (HandleEntry) cache.handleEntries.get(nameId.getName());
120                 }
121
122                 if (handleEntry.isExpired()) {
123                         log.debug("Attribute Query Handle is expired.");
124                         synchronized (cache.handleEntries) {
125                                 cache.handleEntries.remove(nameId.getName());
126                         }
127                         throw new InvalidNameIdentifierException("Attribute Query Handle is expired.");
128                 } else {
129                         log.debug("Attribute Query Handle recognized.");
130                         return handleEntry.principal;
131                 }
132         }
133
134 }
135
136 class HandleCache {
137
138         protected Map handleEntries = new HashMap();
139         private static HandleCache instance;
140         protected MemoryRepositoryCleaner cleaner = new MemoryRepositoryCleaner();
141         private static Logger log = Logger.getLogger(HandleCache.class.getName());
142
143         protected HandleCache() {
144         }
145
146         public static synchronized HandleCache instance() {
147                 if (instance == null) {
148                         instance = new HandleCache();
149                         return instance;
150                 }
151                 return instance;
152         }
153         /**
154          * @see java.lang.Object#finalize()
155          */
156         protected void finalize() throws Throwable {
157                 super.finalize();
158                 synchronized (cleaner) {
159                         cleaner.shutdown = true;
160                         cleaner.interrupt();
161                 }
162         }
163
164         private class MemoryRepositoryCleaner extends Thread {
165
166                 private boolean shutdown = false;
167
168                 public MemoryRepositoryCleaner() {
169                         super();
170                         log.debug("Starting memory-based shib handle cache cleanup thread.");
171                         start();
172                 }
173
174                 public void run() {
175                         try {
176                                 sleep(1 * 60 * 1000);
177                         } catch (InterruptedException e) {
178                                 log.debug("Memory-based shib handle cache cleanup interrupted.");
179                         }
180                         while (true) {
181                                 try {
182                                         if (shutdown) {
183                                                 log.debug("Stopping Memory-based shib handle cache cleanup thread.");
184                                                 return;
185                                         }
186                                         Set needsDeleting = new HashSet();
187                                         synchronized (handleEntries) {
188                                                 Iterator iterator = handleEntries.entrySet().iterator();
189                                                 while (iterator.hasNext()) {
190                                                         Entry entry = (Entry) iterator.next();
191                                                         HandleEntry handleEntry = (HandleEntry) entry.getValue();
192                                                         if (handleEntry.isExpired()) {
193                                                                 needsDeleting.add(entry.getKey());
194                                                         }
195                                                 }
196                                                 //release the lock to be friendly
197                                                 Iterator deleteIterator = needsDeleting.iterator();
198                                                 while (deleteIterator.hasNext()) {
199                                                         synchronized (handleEntries) {
200                                                                 log.debug("Expiring an Attribute Query Handle from the memory cache.");
201                                                                 handleEntries.remove(deleteIterator.next());
202                                                         }
203                                                 }
204                                         }
205                                         sleep(1 * 60 * 1000);
206                                 } catch (InterruptedException e) {
207                                         log.debug("Memory-based shib handle cache cleanup interrupted.");
208                                 }
209                         }
210                 }
211         }
212
213 }