93834cdc1c1b169a64948ebd67c65668dd447f13
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / attrresolv / provider / JNDIDirectoryDataConnector.java
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 package edu.internet2.middleware.shibboleth.aa.attrresolv.provider;
51
52 import java.security.Principal;
53 import java.util.Properties;
54
55 import javax.naming.CommunicationException;
56 import javax.naming.NamingEnumeration;
57 import javax.naming.NamingException;
58 import javax.naming.directory.Attributes;
59 import javax.naming.directory.InitialDirContext;
60 import javax.naming.directory.SearchControls;
61 import javax.naming.directory.SearchResult;
62
63 import org.apache.log4j.Logger;
64 import org.w3c.dom.Element;
65 import org.w3c.dom.NodeList;
66
67 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
68 import edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn;
69 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolutionPlugInException;
70
71 /**
72  * <code>DataConnectorPlugIn</code> implementation that utilizes a user specified JNDI 
73  * <code>DirContext</code> to retrieve attribute data.
74  * 
75  * @author Walter Hoehn (wassa@columbia.edu)
76  *
77  */
78 public class JNDIDirectoryDataConnector extends BaseResolutionPlugIn implements DataConnectorPlugIn {
79
80         private static Logger log = Logger.getLogger(JNDIDirectoryDataConnector.class.getName());
81         protected String searchFilter;
82         protected Properties properties;
83         protected SearchControls controls;
84
85         public JNDIDirectoryDataConnector(Element e) throws ResolutionPlugInException {
86
87                 super(e);
88                 NodeList searchNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Search");
89                 if (searchNodes.getLength() != 1) {
90                         log.error("JNDI Directory Data Connector requires a \"Search\" specification.");
91                         throw new ResolutionPlugInException("JNDI Directory Data Connector requires a \"Search\" specification.");
92                 }
93
94                 String searchFilterSpec = ((Element) searchNodes.item(0)).getAttribute("filter");
95                 if (searchFilterSpec != null && !searchFilterSpec.equals("")) {
96                         searchFilter = searchFilterSpec;
97                         log.debug("Search Filter: (" + searchFilter + ").");
98                 } else {
99                         log.error("Search spec requires a filter attribute.");
100                         throw new ResolutionPlugInException("Search spec requires a filter attribute.");
101                 }
102
103                 defineSearchControls(((Element) searchNodes.item(0)));
104
105                 NodeList propertyNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Property");
106                 properties = System.getProperties();
107                 for (int i = 0; propertyNodes.getLength() > i; i++) {
108                         Element property = (Element) propertyNodes.item(i);
109                         String propName = property.getAttribute("name");
110                         String propValue = property.getAttribute("value");
111
112                         if (propName != null && !propName.equals("") && propValue != null && !propValue.equals("")) {
113                                 properties.setProperty(propName, propValue);
114                                 log.debug("Property: (" + propName + ").");
115                                 log.debug("   Value: (" + propValue + ").");
116                         } else {
117                                 log.error("Property is malformed.");
118                                 throw new ResolutionPlugInException("Property is malformed.");
119                         }
120                 }
121                 try {
122                         InitialDirContext context = new InitialDirContext(properties);
123                         context.close();
124                         log.debug("JNDI Directory context activated.");
125                 } catch (NamingException e1) {
126                         log.error("Failed to startup directory context: " + e1);
127                         throw new ResolutionPlugInException("Failed to startup directory context.");
128                 }
129
130         }
131
132         protected void defineSearchControls(Element searchNode) {
133
134                 controls = new SearchControls();
135
136                 NodeList controlNodes = searchNode.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Controls");
137                 if (controlNodes.getLength() < 1) {
138                         log.debug("No Search Control spec found.");
139                 } else {
140                         if (controlNodes.getLength() > 1) {
141                                 log.error("Found multiple Search Control specs for a Connector.  Ignoring all but the first.");
142                         }
143
144                         String searchScopeSpec = ((Element) controlNodes.item(0)).getAttribute("searchScope");
145                         if (searchScopeSpec != null && !searchScopeSpec.equals("")) {
146                                 if (searchScopeSpec.equals("OBJECT_SCOPE")) {
147                                         controls.setSearchScope(SearchControls.OBJECT_SCOPE);
148                                 } else if (searchScopeSpec.equals("ONELEVEL_SCOPE")) {
149                                         controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
150                                 } else if (searchScopeSpec.equals("SUBTREE_SCOPE")) {
151                                         controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
152                                 } else {
153                                         try {
154                                                 controls.setSearchScope(Integer.parseInt(searchScopeSpec));
155                                         } catch (NumberFormatException nfe) {
156                                                 log.error("Control spec included an invalid (searchScope) attribute value.");
157                                         }
158                                 }
159                         }
160
161                         String timeLimitSpec = ((Element) controlNodes.item(0)).getAttribute("timeLimit");
162                         if (timeLimitSpec != null && !timeLimitSpec.equals("")) {
163                                 try {
164                                         System.err.println("hey");
165                                         controls.setTimeLimit(Integer.parseInt(timeLimitSpec));
166                                 } catch (NumberFormatException nfe) {
167                                         log.error("Control spec included an invalid (timeLimit) attribute value.");
168                                 }
169                         }
170
171                         String returningObjectsSpec = ((Element) controlNodes.item(0)).getAttribute("returningObjects");
172                         if (returningObjectsSpec != null && !returningObjectsSpec.equals("")) {
173                                 controls.setReturningObjFlag(new Boolean(returningObjectsSpec).booleanValue());
174                         }
175
176                         String linkDereferencingSpec = ((Element) controlNodes.item(0)).getAttribute("linkDereferencing");
177                         if (linkDereferencingSpec != null && !linkDereferencingSpec.equals("")) {
178                                 if (linkDereferencingSpec != null && !linkDereferencingSpec.equals("")) {
179                                         controls.setDerefLinkFlag(new Boolean(linkDereferencingSpec).booleanValue());
180                                 }
181                         }
182
183                         String countLimitSpec = ((Element) controlNodes.item(0)).getAttribute("countLimit");
184                         if (countLimitSpec != null && !countLimitSpec.equals("")) {
185                                 try {
186                                         controls.setCountLimit(Long.parseLong(countLimitSpec));
187                                 } catch (NumberFormatException nfe) {
188                                         log.error("Control spec included an invalid (countLimit) attribute value.");
189                                 }
190                         }
191                 }
192
193                 if (log.isDebugEnabled()) {
194                         log.debug("Search Control (searchScope): " + controls.getSearchScope());
195                         log.debug("Search Control (timeLimit): " + controls.getTimeLimit());
196                         log.debug("Search Control (returningObjects): " + controls.getReturningObjFlag());
197                         log.debug("Search Control (linkDereferencing): " + controls.getDerefLinkFlag());
198                         log.debug("Search Control (countLimit): " + controls.getCountLimit());
199                 }
200         }
201
202         /**
203          * @see edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn#resolve(java.security.Principal)
204          */
205         public Attributes resolve(Principal principal) throws ResolutionPlugInException {
206
207                 try {
208                         InitialDirContext context = new InitialDirContext(properties);
209                         NamingEnumeration enum = null;
210
211                         try {
212                                 enum = context.search("", searchFilter.replaceAll("%PRINCIPAL%", principal.getName()), controls);
213                         } catch (CommunicationException e) {
214                                 log.debug(e);
215                                 log.warn(
216                                         "Encountered a connection problem while querying for attributes.  Re-initializing JNDI context and retrying...");
217                                 context = new InitialDirContext(context.getEnvironment());
218                                 enum = context.search("", searchFilter.replaceAll("%PRINCIPAL%", principal.getName()), controls);
219                         }
220
221                         if (enum == null || !enum.hasMore()) {
222                                 log.error("Could not locate a principal with the name (" + principal.getName() + ").");
223                                 throw new ResolutionPlugInException("No data available for this principal.");
224                         }
225
226                         SearchResult result = (SearchResult) enum.next();
227                         Attributes attributes = result.getAttributes();
228
229                         if (enum.hasMore()) {
230                                 log.error("Unable to disambiguate date for principal (" + principal.getName() + ") in search.");
231                                 throw new ResolutionPlugInException("Cannot disambiguate data for this principal.");
232                         }
233
234                         context.close();
235                         return attributes;
236
237                 } catch (NamingException e) {
238                         log.error(
239                                 "An error occurred while retieving data for principal ("
240                                         + principal.getName()
241                                         + ") :"
242                                         + e.getMessage());
243                         throw new ResolutionPlugInException("Error retrieving data for principal.");
244                 }
245         }
246
247 }