Project

General

Profile

1 503 bojilova
/**
2
 *  '$RCSfile$'
3
 *    Purpose: An implementation of the AuthInterface interface that
4
 *             allows Metacat to use the LDAP protocol for
5
 *             directory services
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Matt Jones
9
 *    Release: @release@
10
 *
11
 *   '$Author$'
12
 *     '$Date$'
13
 * '$Revision$'
14 669 jones
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 2 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28 503 bojilova
 */
29
30
package edu.ucsb.nceas.metacat;
31
32
import java.net.ConnectException;
33
import javax.naming.AuthenticationException;
34
import javax.naming.Context;
35 787 bojilova
import javax.naming.NamingEnumeration;
36
import javax.naming.NamingException;
37 873 jones
import javax.naming.SizeLimitExceededException;
38 730 bojilova
import javax.naming.InitialContext;
39 802 bojilova
import javax.naming.directory.InvalidSearchFilterException;
40 503 bojilova
import javax.naming.directory.Attribute;
41
import javax.naming.directory.Attributes;
42 504 jones
import javax.naming.directory.BasicAttribute;
43
import javax.naming.directory.BasicAttributes;
44
import javax.naming.directory.DirContext;
45
import javax.naming.directory.InitialDirContext;
46
import javax.naming.directory.SearchResult;
47 723 bojilova
import javax.naming.directory.SearchControls;
48 868 berkley
import javax.naming.ReferralException;
49 787 bojilova
import javax.naming.ldap.*;
50 2666 sgarg
51
import org.apache.log4j.Logger;
52
53 1988 jones
import java.net.URLDecoder;
54 503 bojilova
import java.util.Iterator;
55
import java.util.HashMap;
56
import java.util.Hashtable;
57 730 bojilova
import java.util.Enumeration;
58 503 bojilova
import java.util.Set;
59
import java.util.Vector;
60
61
/**
62
 * An implementation of the AuthInterface interface that
63
 * allows Metacat to use the LDAP protocol for directory services.
64 2058 sgarg
 * The LDAP authentication service is used to determine if a user
65 503 bojilova
 * is authenticated, and whether they are a member of a particular group.
66
 */
67 2121 sgarg
public class AuthLdap
68
    implements AuthInterface, Runnable {
69 787 bojilova
  private MetaCatUtil util = new MetaCatUtil();
70 728 bojilova
  private String ldapUrl;
71 787 bojilova
  private String ldapsUrl;
72 728 bojilova
  private String ldapBase;
73 865 jones
  private String referral;
74 991 tao
  private Context referralContext;
75 893 berkley
  Hashtable env = new Hashtable(11);
76
  private Context rContext;
77 934 tao
  private String userName;
78
  private String userPassword;
79 893 berkley
  ReferralException refExc;
80 503 bojilova
81 2666 sgarg
  private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
82
83 2058 sgarg
  /**
84 728 bojilova
   * Construct an AuthLdap
85
   */
86
  public AuthLdap() {
87
    // Read LDAP URI for directory service information
88 787 bojilova
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
89
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
90
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
91 865 jones
    this.referral = MetaCatUtil.getOption("referral");
92 728 bojilova
  }
93
94 503 bojilova
  /**
95
   * Determine if a user/password are valid according to the authentication
96
   * service.
97
   *
98
   * @param user the name of the principal to authenticate
99
   * @param password the password to use for authentication
100
   * @returns boolean true if authentication successful, false otherwise
101
   */
102 2121 sgarg
  public boolean authenticate(String user, String password) throws
103
      ConnectException {
104 730 bojilova
    String ldapUrl = this.ldapUrl;
105 787 bojilova
    String ldapsUrl = this.ldapsUrl;
106 730 bojilova
    String ldapBase = this.ldapBase;
107 503 bojilova
    boolean authenticated = false;
108 802 bojilova
    String identifier = user;
109 1004 tao
    //get uid here.
110 1988 jones
    //uid=user.substring(0, user.indexOf(","));
111 2058 sgarg
112 503 bojilova
    try {
113 2121 sgarg
      // Check the usename as passed in
114
      authenticated = ldapAuthenticate(identifier, password);
115
      // if not found, try looking up a valid DN then auth again
116
      if (!authenticated) {
117 2666 sgarg
        logMetacat.info("Looking up DN for: " + identifier);
118 2121 sgarg
        identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
119 2666 sgarg
        logMetacat.info("DN found: " + identifier);
120 2121 sgarg
        String decoded = URLDecoder.decode(identifier);
121 2666 sgarg
        logMetacat.info("DN decoded: " + decoded);
122 2121 sgarg
        identifier = decoded;
123
        String refUrl = "";
124
        String refBase = "";
125
        if (identifier.startsWith("ldap")) {
126
          refUrl = identifier.substring(0,
127
                                        identifier.lastIndexOf("/") + 1);
128 2666 sgarg
          logMetacat.info("Ref ldapUrl: " + refUrl);
129 2121 sgarg
          int position = identifier.indexOf(",");
130
          int position2 = identifier.indexOf(",", position + 1);
131
          refBase = identifier.substring(position2 + 1);
132 2666 sgarg
          logMetacat.info("Ref ldapBase: " + refBase);
133 2121 sgarg
          identifier = identifier.substring(
134
              identifier.lastIndexOf("/") + 1);
135 2666 sgarg
          logMetacat.info("Trying: " + identifier);
136 2121 sgarg
          authenticated = ldapAuthenticate(identifier, password,
137
                                           refUrl, refBase);
138 1004 tao
        }
139 2121 sgarg
        else {
140
          identifier = identifier + "," + ldapBase;
141 2666 sgarg
          logMetacat.info("Trying: " + identifier);
142 2121 sgarg
          authenticated = ldapAuthenticate(identifier, password);
143
        }
144
        //authenticated = ldapAuthenticate(identifier, password);
145
      }
146 2058 sgarg
147 2121 sgarg
    }
148
    catch (NullPointerException e) {
149 2666 sgarg
      logMetacat.error("NullPointerException b' password is null");
150
      logMetacat.error("NullPointerException while authenticating in " +
151 2589 sgarg
                        "AuthLdap.authenticate: " + e);
152 740 bojilova
      throw new ConnectException(
153 2121 sgarg
          "NullPointerException while authenticating in " +
154
          "AuthLdap.authenticate: " + e);
155
    }
156
    catch (NamingException e) {
157 2666 sgarg
      logMetacat.error("Naming exception while authenticating in " +
158 2589 sgarg
                        "AuthLdap.authenticate: " + e);
159 852 jones
      e.printStackTrace();
160 2121 sgarg
    }
161
    catch (Exception e) {
162 2666 sgarg
      logMetacat.error(e.getMessage());
163 503 bojilova
    }
164
    return authenticated;
165
  }
166
167
  /**
168 852 jones
   * Connect to the LDAP directory and do the authentication using the
169
   * username and password as passed into the routine.
170
   *
171
   * @param identifier the distinguished name to check against LDAP
172
   * @param password the password for authentication
173
   */
174 2121 sgarg
  private boolean ldapAuthenticate(String identifier, String password) throws
175
      ConnectException, NamingException, NullPointerException {
176
    return ldapAuthenticate(identifier, password,
177
                            this.ldapsUrl, this.ldapBase);
178 1005 jones
  }
179
180
  /**
181
   * Connect to the LDAP directory and do the authentication using the
182
   * username and password as passed into the routine.
183
   *
184
   * @param identifier the distinguished name to check against LDAP
185
   * @param password the password for authentication
186
   */
187
  private boolean ldapAuthenticate(String identifier, String password,
188 2121 sgarg
                                   String directoryUrl, String searchBase) throws
189
      ConnectException, NamingException, NullPointerException {
190 867 berkley
    double totStartTime = System.currentTimeMillis();
191 852 jones
    boolean authenticated = false;
192 1988 jones
    if (identifier != null && !password.equals("")) {
193 2058 sgarg
194 2121 sgarg
      //Pass the username and password to run() method
195
      userName = identifier;
196
      userPassword = password;
197
      // Identify service provider to use
198
      Hashtable env = new Hashtable(11);
199
      env.put(Context.INITIAL_CONTEXT_FACTORY,
200 934 tao
              "com.sun.jndi.ldap.LdapCtxFactory");
201 2121 sgarg
      env.put(Context.REFERRAL, "throw");
202
      env.put(Context.PROVIDER_URL, directoryUrl + searchBase);
203 2666 sgarg
      logMetacat.info("PROVIDER_URL set to: " + directoryUrl + searchBase);
204 2121 sgarg
      if (!ldapsUrl.equals(ldapUrl)) {
205
        // ldap is set on default port 389
206
        // ldaps is set on second port - 636 by default
207 2666 sgarg
        // env.put(Context.SECURITY_PROTOCOL, "ssl");
208
       }
209 2121 sgarg
      env.put(Context.SECURITY_AUTHENTICATION, "simple");
210
      env.put(Context.SECURITY_PRINCIPAL, identifier);
211
      env.put(Context.SECURITY_CREDENTIALS, password);
212
      // If our auth credentials are invalid, an exception will be thrown
213
      DirContext ctx = null;
214
      try {
215
        double startTime = System.currentTimeMillis();
216
        //Here to check the authorization
217
        ctx = new InitialDirContext(env);
218
        double stopTime = System.currentTimeMillis();
219 2666 sgarg
        logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
220 2589 sgarg
                          (stopTime - startTime) / 1000 + " seconds.");
221 2121 sgarg
        authenticated = true;
222
        //tls.close();
223
        ctx.close();
224
        this.ldapUrl = ldapUrl;
225
        this.ldapBase = ldapBase;
226
        //break;
227
      }
228
      catch (AuthenticationException ae) {
229
        authenticated = false;
230
        if (ctx != null) {
231
          ctx.close();
232 852 jones
        }
233 2121 sgarg
      }
234
      catch (javax.naming.InvalidNameException ine) {
235 2666 sgarg
        logMetacat.error("An invalid DN was provided!");
236 2121 sgarg
      }
237
      catch (javax.naming.ReferralException re) {
238 2666 sgarg
        logMetacat.error("referral during authentication");
239
        logMetacat.error("Referral information: " + re.getReferralInfo());
240 1988 jones
        try {
241 2121 sgarg
          refExc = re;
242 934 tao
243 2121 sgarg
          Thread t = new Thread(this);
244
          t.start();
245
          Thread.sleep(5000); //this is a manual override of ldap's
246
          //hideously long time out period.
247 2666 sgarg
          logMetacat.info("Awake after 5 seconds.");
248 2121 sgarg
          if (referralContext == null) {
249
            t.interrupt();
250 868 berkley
            authenticated = false;
251
          }
252 2121 sgarg
          else {
253
            authenticated = true;
254
          }
255 868 berkley
        }
256 2121 sgarg
        catch (Exception e) {
257
          authenticated = false;
258
        }
259
      }
260 852 jones
    }
261 2121 sgarg
    else {
262 2666 sgarg
      logMetacat.info("User not found");
263 2121 sgarg
    }
264 867 berkley
    double totStopTime = System.currentTimeMillis();
265 2666 sgarg
    logMetacat.warn("total ldap authentication time: " +
266 2589 sgarg
                      (totStopTime - totStartTime) / 1000 + " seconds");
267 852 jones
    return authenticated;
268
  }
269
270
  /**
271 730 bojilova
   * Get the identifying name for a given userid or name.  This is the name
272
   * that is used in conjunction withthe LDAP BaseDN to create a
273
   * distinguished name (dn) for the record
274
   *
275
   * @param user the user for which the identifying name is requested
276 2058 sgarg
   * @returns String the identifying name for the user,
277 730 bojilova
   *          or null if not found
278
   */
279 934 tao
  private String getIdentifyingName(String user, String ldapUrl,
280 2121 sgarg
                                    String ldapBase) throws NamingException {
281 730 bojilova
    String identifier = null;
282
    // Identify service provider to use
283
    Hashtable env = new Hashtable(11);
284
    env.put(Context.INITIAL_CONTEXT_FACTORY,
285
            "com.sun.jndi.ldap.LdapCtxFactory");
286 2666 sgarg
    logMetacat.info("setting referrals to: " + referral);
287 865 jones
    env.put(Context.REFERRAL, referral);
288 730 bojilova
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
289 867 berkley
    //    non-secure LDAP context; dn are publicly readable
290 730 bojilova
    try {
291 2058 sgarg
292 730 bojilova
      // Bind to the LDAP server, in order to search for the right
293
      // distinguished name (dn) based on userid (uid) or common name (cn)
294
      DirContext ctx = new InitialDirContext(env);
295
      SearchControls ctls = new SearchControls();
296
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
297 2058 sgarg
      // Search for the user id or name using the uid, then cn and sn
298 934 tao
      //attributes
299 730 bojilova
      // If we find a record, determine the dn for the record
300 1005 jones
      // The following blocks need to be refactored into a subroutine
301
      // they have a ridiculous amount of redundancy
302 730 bojilova
303 1005 jones
      // Parse out the uid and org components and look up the real DN
304
      // This assumes a dn like "uid=x,o=y,dc=someinst,dc=org"
305
      int position = user.indexOf(",");
306
      String comp1 = user.substring(0, position);
307 2666 sgarg
      logMetacat.info("First comp is: " + comp1);
308 2121 sgarg
      String comp2 = user.substring(position + 1,
309
                                    user.indexOf(",", position + 1));
310 2666 sgarg
      logMetacat.info("Second comp is: " + comp2);
311 1005 jones
312 1998 jones
      //String filter = "(&(" + comp1 + "))";
313
      String filter = "(&(" + comp1 + ")(" + comp2 + "))";
314 2666 sgarg
      logMetacat.info("Filter is: " + filter);
315
      logMetacat.info("Provider URL is: " + ldapUrl + ldapBase);
316 802 bojilova
      NamingEnumeration answer;
317
      try {
318 2666 sgarg
        logMetacat.info("Trying search 1: " + filter);
319 802 bojilova
        answer = ctx.search("", filter, ctls);
320 2666 sgarg
        logMetacat.info("Search 1 complete");
321 1988 jones
        if (answer == null) {
322 2666 sgarg
          logMetacat.info("Search 1 answer is null.");
323 1988 jones
        }
324 802 bojilova
        if (answer.hasMore()) {
325 2666 sgarg
          logMetacat.info("Search 1 has answers.");
326 2121 sgarg
          SearchResult sr = (SearchResult) answer.next();
327 802 bojilova
          identifier = sr.getName();
328 2666 sgarg
          logMetacat.info("Originally Found: " + identifier);
329 1005 jones
          return identifier;
330
        }
331 1988 jones
      }
332 2121 sgarg
      catch (InvalidSearchFilterException e) {
333 2666 sgarg
        logMetacat.error("Invalid Filter exception thrown (if1)");
334 2121 sgarg
      }
335 1005 jones
336
      // That failed, so check if it is just a username
337
      filter = "(" + user + ")";
338
      try {
339 2666 sgarg
        logMetacat.info("Trying again: " + filter);
340 1005 jones
        answer = ctx.search("", filter, ctls);
341
        if (answer.hasMore()) {
342 2121 sgarg
          SearchResult sr = (SearchResult) answer.next();
343 1005 jones
          identifier = sr.getName();
344 2121 sgarg
          if (!sr.isRelative()) {
345 934 tao
            this.ldapUrl = identifier.substring(0,
346 2121 sgarg
                                                identifier.lastIndexOf("/") + 1);
347
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
348
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
349 802 bojilova
                                              identifier.indexOf(","));
350
          }
351 2666 sgarg
          logMetacat.info("Found: " + identifier);
352 802 bojilova
          return identifier;
353
        }
354 2121 sgarg
      }
355
      catch (InvalidSearchFilterException e) {}
356 1005 jones
357
      // Maybe its a user id (uid)
358 802 bojilova
      filter = "(uid=" + user + ")";
359 2666 sgarg
      logMetacat.info("Trying again: " + filter);
360 802 bojilova
      answer = ctx.search("", filter, ctls);
361 730 bojilova
      if (answer.hasMore()) {
362 2121 sgarg
        SearchResult sr = (SearchResult) answer.next();
363 730 bojilova
        identifier = sr.getName();
364 2121 sgarg
        if (!sr.isRelative()) {
365
          this.ldapUrl = identifier.substring(0,
366
                                              identifier.lastIndexOf("/") + 1);
367
          this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
368
          identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
369 730 bojilova
                                            identifier.indexOf(","));
370
        }
371 2666 sgarg
        logMetacat.info("Found: " + identifier);
372 2121 sgarg
      }
373
      else {
374 1005 jones
375
        // maybe its just a common name
376 730 bojilova
        filter = "(cn=" + user + ")";
377 2666 sgarg
        logMetacat.info("Trying again: " + filter);
378 730 bojilova
        NamingEnumeration answer2 = ctx.search("", filter, ctls);
379
        if (answer2.hasMore()) {
380 2121 sgarg
          SearchResult sr = (SearchResult) answer2.next();
381 730 bojilova
          identifier = sr.getName();
382 2121 sgarg
          if (!sr.isRelative()) {
383 934 tao
            this.ldapUrl = identifier.substring(0,
384 2121 sgarg
                                                identifier.lastIndexOf("/") + 1);
385
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
386
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
387 730 bojilova
                                              identifier.indexOf(","));
388
          }
389 2666 sgarg
          logMetacat.info("Found: " + identifier);
390 2121 sgarg
        }
391
        else {
392 1005 jones
393
          // ok, last resort, is it a surname?
394 730 bojilova
          filter = "(sn=" + user + ")";
395 2666 sgarg
          logMetacat.info("Trying again: " + filter);
396 730 bojilova
          NamingEnumeration answer3 = ctx.search("", filter, ctls);
397
          if (answer3.hasMore()) {
398 2121 sgarg
            SearchResult sr = (SearchResult) answer3.next();
399 730 bojilova
            identifier = sr.getName();
400 2121 sgarg
            if (!sr.isRelative()) {
401 934 tao
              this.ldapUrl = identifier.substring(0,
402 2121 sgarg
                                                  identifier.lastIndexOf("/") +
403
                                                  1);
404
              this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
405
              identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
406 730 bojilova
                                                identifier.indexOf(","));
407
            }
408 2666 sgarg
            logMetacat.info("Found: " + identifier);
409 730 bojilova
          }
410
        }
411
      }
412
      // Close the context when we're done the initial search
413
      ctx.close();
414 2121 sgarg
    }
415
    catch (NamingException e) {
416 2666 sgarg
      logMetacat.error("Naming exception while getting dn: " + e);
417 730 bojilova
      throw new NamingException(
418 2121 sgarg
          "Naming exception in AuthLdap.getIdentifyingName: " + e);
419 730 bojilova
    }
420 2666 sgarg
    logMetacat.error("Returning found identifier as: " + identifier);
421 730 bojilova
    return identifier;
422
  }
423
424
  /**
425 503 bojilova
   * Get all users from the authentication service
426 871 jones
   *
427
   * @param user the user for authenticating against the service
428
   * @param password the password for authenticating against the service
429
   * @returns string array of all of the user names
430 503 bojilova
   */
431 2121 sgarg
  public String[][] getUsers(String user, String password) throws
432
      ConnectException {
433 2058 sgarg
    String[][] users = null;
434 723 bojilova
435
    // Identify service provider to use
436
    Hashtable env = new Hashtable(11);
437 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
438 723 bojilova
            "com.sun.jndi.ldap.LdapCtxFactory");
439 865 jones
    env.put(Context.REFERRAL, referral);
440 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
441 2058 sgarg
442 723 bojilova
    try {
443
444 2121 sgarg
      // Create the initial directory context
445
      DirContext ctx = new InitialDirContext(env);
446 723 bojilova
447 2121 sgarg
      // Specify the attributes to match.
448
      // Users are objects that have the attribute objectclass=InetOrgPerson.
449
      SearchControls ctls = new SearchControls();
450
      String[] attrIDs = {
451 2130 sgarg
          "dn", "cn", "o", "ou", "mail"};
452 2121 sgarg
      ctls.setReturningAttributes(attrIDs);
453
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
454
      //ctls.setCountLimit(1000);
455
      String filter = "(objectClass=inetOrgPerson)";
456 2447 sgarg
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
457 2058 sgarg
458 2121 sgarg
      // Store the users in a vector
459
      Vector uvec = new Vector();
460
      Vector uname = new Vector();
461
      Vector uorg = new Vector();
462 2130 sgarg
      Vector uou = new Vector();
463 2121 sgarg
      Vector umail = new Vector();
464
      Attributes tempAttr = null;
465
      try {
466 2447 sgarg
        while (namingEnum.hasMore()) {
467
          SearchResult sr = (SearchResult) namingEnum.next();
468 2121 sgarg
          tempAttr = sr.getAttributes();
469 2058 sgarg
470 2121 sgarg
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
471
            uname.add( (tempAttr.get("cn") + "").substring(4));
472
          }
473
          else {
474
            uname.add(tempAttr.get("cn") + "");
475
          }
476 2058 sgarg
477 2121 sgarg
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
478
            uorg.add( (tempAttr.get("o") + "").substring(3));
479
          }
480
          else {
481
            uorg.add(tempAttr.get("o") + "");
482
          }
483 2116 sgarg
484 2130 sgarg
          if ( (tempAttr.get("ou") + "").startsWith("ou: ")) {
485
            uou.add( (tempAttr.get("ou") + "").substring(4));
486
          }
487
          else {
488
            uou.add(tempAttr.get("ou") + "");
489
          }
490
491 2121 sgarg
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
492
            umail.add( (tempAttr.get("mail") + "").substring(6));
493
          }
494
          else {
495
            umail.add(tempAttr.get("mail") + "");
496
          }
497 2058 sgarg
498 2121 sgarg
          uvec.add(sr.getName() + "," + ldapBase);
499 723 bojilova
        }
500 2121 sgarg
      }
501
      catch (SizeLimitExceededException slee) {
502 2666 sgarg
        logMetacat.error("LDAP Server size limit exceeded. " +
503 2589 sgarg
                          "Returning incomplete record set.");
504 2121 sgarg
      }
505 723 bojilova
506 2121 sgarg
      // initialize users[]; fill users[]
507 2130 sgarg
      users = new String[uvec.size()][5];
508 2121 sgarg
      for (int i = 0; i < uvec.size(); i++) {
509
        users[i][0] = (String) uvec.elementAt(i);
510
        users[i][1] = (String) uname.elementAt(i);
511
        users[i][2] = (String) uorg.elementAt(i);
512 2130 sgarg
        users[i][3] = (String) uorg.elementAt(i);
513
        users[i][4] = (String) umail.elementAt(i);
514 2121 sgarg
      }
515 723 bojilova
516 2121 sgarg
      // Close the context when we're done
517
      ctx.close();
518 723 bojilova
519 2121 sgarg
    }
520
    catch (NamingException e) {
521 2666 sgarg
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
522 1477 tao
      //e.printStackTrace(System.err);
523 723 bojilova
      throw new ConnectException(
524 2121 sgarg
          "Problem getting users in AuthLdap.getUsers:" + e);
525 723 bojilova
    }
526
527
    return users;
528 503 bojilova
  }
529
530
  /**
531
   * Get the users for a particular group from the authentication service
532 871 jones
   *
533
   * @param user the user for authenticating against the service
534
   * @param password the password for authenticating against the service
535
   * @param group the group whose user list should be returned
536
   * @returns string array of the user names belonging to the group
537 503 bojilova
   */
538 2121 sgarg
  public String[] getUsers(String user, String password, String group) throws
539
      ConnectException {
540 723 bojilova
    String[] users = null;
541
542
    // Identify service provider to use
543
    Hashtable env = new Hashtable(11);
544 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
545 723 bojilova
            "com.sun.jndi.ldap.LdapCtxFactory");
546 865 jones
    env.put(Context.REFERRAL, referral);
547 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
548 723 bojilova
549
    try {
550
551 2121 sgarg
      // Create the initial directory context
552
      DirContext ctx = new InitialDirContext(env);
553 723 bojilova
554 2121 sgarg
      // Specify the ids of the attributes to return
555
      String[] attrIDs = {
556
          "uniqueMember"};
557 723 bojilova
558 2121 sgarg
      Attributes answer = ctx.getAttributes(group, attrIDs);
559 723 bojilova
560 2121 sgarg
      Vector uvec = new Vector();
561
      try {
562
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
563
          Attribute attr = (Attribute) ae.next();
564
          for (NamingEnumeration e = attr.getAll();
565
               e.hasMore();
566
               uvec.add(e.next())
567
               ) {
568
            ;
569
          }
570 723 bojilova
        }
571 2121 sgarg
      }
572
      catch (SizeLimitExceededException slee) {
573 2666 sgarg
        logMetacat.error("LDAP Server size limit exceeded. " +
574 2589 sgarg
                          "Returning incomplete record set.");
575 2121 sgarg
      }
576 723 bojilova
577 2121 sgarg
      // initialize users[]; fill users[]
578
      users = new String[uvec.size()];
579
      for (int i = 0; i < uvec.size(); i++) {
580
        users[i] = (String) uvec.elementAt(i);
581
      }
582 723 bojilova
583 2121 sgarg
      // Close the context when we're done
584
      ctx.close();
585 723 bojilova
586 2121 sgarg
    }
587
    catch (NamingException e) {
588 2666 sgarg
      logMetacat.error("Problem getting users for a group in " +
589 2589 sgarg
                        "AuthLdap.getUsers:" + e);
590 723 bojilova
      throw new ConnectException(
591 2121 sgarg
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
592 723 bojilova
    }
593
594
    return users;
595 503 bojilova
  }
596
597
  /**
598
   * Get all groups from the authentication service
599 871 jones
   *
600
   * @param user the user for authenticating against the service
601
   * @param password the password for authenticating against the service
602
   * @returns string array of the group names
603 503 bojilova
   */
604 2121 sgarg
  public String[][] getGroups(String user, String password) throws
605
      ConnectException {
606
    return getGroups(user, password, null);
607 503 bojilova
  }
608
609
  /**
610
   * Get the groups for a particular user from the authentication service
611 871 jones
   *
612
   * @param user the user for authenticating against the service
613
   * @param password the password for authenticating against the service
614
   * @param foruser the user whose group list should be returned
615
   * @returns string array of the group names
616 503 bojilova
   */
617 2121 sgarg
  public String[][] getGroups(String user, String password, String foruser) throws
618
      ConnectException {
619 2116 sgarg
    Vector gvec = new Vector();
620 2058 sgarg
    Vector desc = new Vector();
621
    Attributes tempAttr = null;
622
623 976 tao
    //Pass the username and password to run() method
624 2121 sgarg
    userName = user;
625
    userPassword = password;
626 723 bojilova
    // Identify service provider to use
627 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
628 723 bojilova
            "com.sun.jndi.ldap.LdapCtxFactory");
629 888 berkley
    env.put(Context.REFERRAL, "throw");
630 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
631 723 bojilova
    try {
632 2121 sgarg
      // Create the initial directory context
633
      DirContext ctx = new InitialDirContext(env);
634
      // Specify the ids of the attributes to return
635
      String[] attrIDs = {
636
          "cn", "o", "description"};
637
      // Specify the attributes to match.
638
      // Groups are objects with attribute objectclass=groupofuniquenames.
639
      // and have attribute uniquemember: uid=foruser,ldapbase.
640
      SearchControls ctls = new SearchControls();
641
      ctls.setReturningAttributes(attrIDs);
642
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
643 2058 sgarg
644 2121 sgarg
      String filter = null;
645
      String gfilter = "(objectClass=groupOfUniqueNames)";
646
      if (null == foruser) {
647
        filter = gfilter;
648
      }
649
      else {
650
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
651
      }
652 2666 sgarg
      logMetacat.info("searching for groups: " + filter);
653 2447 sgarg
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
654 991 tao
655 2121 sgarg
      // Print the groups
656 2666 sgarg
      logMetacat.info("getting group results.");
657 2447 sgarg
      while (namingEnum.hasMore()) {
658
        SearchResult sr = (SearchResult) namingEnum.next();
659 2121 sgarg
        tempAttr = sr.getAttributes();
660 2058 sgarg
661 2121 sgarg
        if ( (tempAttr.get("description") + "").startsWith("description: ")) {
662
          desc.add( (tempAttr.get("description") + "").substring(13));
663 723 bojilova
        }
664 2121 sgarg
        else {
665
          desc.add(tempAttr.get("description") + "");
666
        }
667 991 tao
668 2121 sgarg
        gvec.add(sr.getName() + "," + ldapBase);
669 2666 sgarg
        logMetacat.info("group " + sr.getName() +
670 2589 sgarg
                                 " added to Group vector");
671 2121 sgarg
      }
672
      // Close the context when we're done
673
      ctx.close();
674
675 2058 sgarg
    }
676 2121 sgarg
    catch (ReferralException re) {
677 1000 berkley
      refExc = re;
678
      Thread t = new Thread(new GetGroup());
679 2666 sgarg
      logMetacat.info("Starting thread...");
680 1000 berkley
      t.start();
681 2666 sgarg
      logMetacat.info("sleeping for 5 seconds.");
682 2121 sgarg
      try {
683 1000 berkley
        Thread.sleep(5000);
684
      }
685 2121 sgarg
      catch (InterruptedException ie) {
686 2666 sgarg
        logMetacat.error("main thread interrupted: " + ie.getMessage());
687 1000 berkley
      }
688
      //this is a manual override of jndi's hideously long time
689
      //out period.
690 2666 sgarg
      logMetacat.info("Awake after 5 seconds.");
691 2121 sgarg
      if (referralContext == null) {
692 2666 sgarg
        logMetacat.info("thread timed out...returning groups: " +
693 2589 sgarg
                          gvec.toString());
694 2116 sgarg
        String groups[][] = new String[gvec.size()][2];
695 2121 sgarg
        for (int i = 0; i < gvec.size(); i++) {
696
          groups[i][0] = (String) gvec.elementAt(i);
697
          groups[i][1] = (String) desc.elementAt(i);
698 991 tao
        }
699 1000 berkley
        t.interrupt();
700
        return groups;
701
      }
702 2121 sgarg
      DirContext dc = (DirContext) referralContext;
703
      String[] attrIDs = {
704
          "cn", "o", "description"};
705 1000 berkley
      // Specify the attributes to match.
706
      // Groups are objects with attribute objectclass=groupofuniquenames.
707
      // and have attribute uniquemember: uid=foruser,ldapbase.
708
      SearchControls ctls = new SearchControls();
709
      ctls.setReturningAttributes(attrIDs);
710
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
711 2058 sgarg
712 1000 berkley
      String filter = null;
713
      String gfilter = "(objectClass=groupOfUniqueNames)";
714
      if (null == foruser) {
715 2121 sgarg
        filter = gfilter;
716 1000 berkley
      }
717 2121 sgarg
      else {
718
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
719
      }
720 2058 sgarg
721 2121 sgarg
      try {
722 2447 sgarg
        NamingEnumeration namingEnum = dc.search(ldapBase, filter, ctls);
723 991 tao
        // Print the groups
724 2447 sgarg
        while (namingEnum.hasMore()) {
725
          SearchResult sr = (SearchResult) namingEnum.next();
726 2058 sgarg
          tempAttr = sr.getAttributes();
727
728 2121 sgarg
          if ( (tempAttr.get("description") + "").startsWith("description: ")) {
729 2058 sgarg
            desc.add( (tempAttr.get("description") + "").substring(13));
730
          }
731 2121 sgarg
          else {
732
            desc.add(tempAttr.get("description") + "");
733
          }
734 2058 sgarg
735 2121 sgarg
          gvec.add(sr.getName() + "," + ldapBase);
736 991 tao
        }
737 2058 sgarg
738 991 tao
        referralContext.close();
739
        dc.close();
740
      }
741 2121 sgarg
      catch (NamingException ne) {
742 2668 sgarg
        logMetacat.warn("Naming Exception in AuthLdap.getGroups" +
743 2589 sgarg
                                 ne.getExplanation() + ne.getMessage());
744 991 tao
      }
745 2121 sgarg
    }
746
    catch (NamingException e) {
747 868 berkley
      e.printStackTrace(System.err);
748 2116 sgarg
      String groups[][] = new String[gvec.size()][2];
749 2121 sgarg
      for (int i = 0; i < gvec.size(); i++) {
750
        groups[i][0] = (String) gvec.elementAt(i);
751
        groups[i][1] = (String) desc.elementAt(i);
752 1006 tao
      }
753
      return groups;
754 2121 sgarg
      /*throw new ConnectException(
755
             "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
756 2058 sgarg
    }
757
758 2666 sgarg
    logMetacat.warn("The user is in the following groups: " +
759 2589 sgarg
                             gvec.toString());
760 2116 sgarg
    String groups[][] = new String[gvec.size()][2];
761 2121 sgarg
    for (int i = 0; i < gvec.size(); i++) {
762
      groups[i][0] = (String) gvec.elementAt(i);
763
      groups[i][1] = (String) desc.elementAt(i);
764 1000 berkley
    }
765 723 bojilova
    return groups;
766 503 bojilova
  }
767
768
  /**
769
   * Get attributes describing a user or group
770
   *
771 871 jones
   * @param foruser the user for which the attribute list is requested
772 503 bojilova
   * @returns HashMap a map of attribute name to a Vector of values
773
   */
774 2121 sgarg
  public HashMap getAttributes(String foruser) throws ConnectException {
775 514 jones
    return getAttributes(null, null, foruser);
776 503 bojilova
  }
777
778
  /**
779
   * Get attributes describing a user or group
780
   *
781 871 jones
   * @param user the user for authenticating against the service
782 503 bojilova
   * @param password the password for authenticating against the service
783 871 jones
   * @param foruser the user whose attributes should be returned
784 503 bojilova
   * @returns HashMap a map of attribute name to a Vector of values
785
   */
786 2121 sgarg
  public HashMap getAttributes(String user, String password, String foruser) throws
787
      ConnectException {
788 503 bojilova
    HashMap attributes = new HashMap();
789 802 bojilova
    String ldapUrl = this.ldapUrl;
790
    String ldapBase = this.ldapBase;
791
    String userident = foruser;
792 2058 sgarg
793 503 bojilova
    // Identify service provider to use
794
    Hashtable env = new Hashtable(11);
795 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
796 2121 sgarg
            "com.sun.jndi.ldap.LdapCtxFactory");
797 865 jones
    env.put(Context.REFERRAL, referral);
798 871 jones
    env.put(Context.PROVIDER_URL, ldapUrl);
799 503 bojilova
800
    try {
801 2058 sgarg
802 503 bojilova
      // Create the initial directory context
803
      DirContext ctx = new InitialDirContext(env);
804 2058 sgarg
805
      // Ask for all attributes of the user
806 871 jones
      //Attributes attrs = ctx.getAttributes(userident);
807
      Attributes attrs = ctx.getAttributes(foruser);
808 2058 sgarg
809 503 bojilova
      // Print all of the attributes
810
      NamingEnumeration en = attrs.getAll();
811
      while (en.hasMore()) {
812 2121 sgarg
        Attribute att = (Attribute) en.next();
813 503 bojilova
        Vector values = new Vector();
814
        String attName = att.getID();
815
        NamingEnumeration attvalues = att.getAll();
816
        while (attvalues.hasMore()) {
817 2121 sgarg
          String value = (String) attvalues.next();
818 503 bojilova
          values.add(value);
819
        }
820
        attributes.put(attName, values);
821
      }
822 2058 sgarg
823 503 bojilova
      // Close the context when we're done
824
      ctx.close();
825 2121 sgarg
    }
826
    catch (NamingException e) {
827 2666 sgarg
      logMetacat.error("Problem getting attributes in " +
828 2589 sgarg
                        "AuthLdap.getAttributes:" + e);
829 723 bojilova
      throw new ConnectException(
830 2121 sgarg
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
831 503 bojilova
    }
832
833
    return attributes;
834
  }
835
836
  /**
837 730 bojilova
   * Get list of all subtrees holding Metacat's groups and users
838 2058 sgarg
   * starting from the Metacat LDAP root,
839 730 bojilova
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
840 504 jones
   */
841 730 bojilova
  private Hashtable getSubtrees(String user, String password,
842 2121 sgarg
                                String ldapUrl, String ldapBase) throws
843
      ConnectException {
844 730 bojilova
    Hashtable trees = new Hashtable();
845 504 jones
846
    // Identify service provider to use
847
    Hashtable env = new Hashtable(11);
848 2058 sgarg
    env.put(Context.INITIAL_CONTEXT_FACTORY,
849 504 jones
            "com.sun.jndi.ldap.LdapCtxFactory");
850 2129 sgarg
    // env.put(Context.REFERRAL, referral);
851
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
852
    // to do the job better. 'follow' was not bringing up the UCNRS
853
    // and PISCO tree whereas 'ignore' brings up the tree.
854
855
    env.put(Context.REFERRAL, "ignore");
856 504 jones
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
857
858
    try {
859
860 2121 sgarg
      // Create the initial directory context
861
      DirContext ctx = new InitialDirContext(env);
862 730 bojilova
863 2121 sgarg
      // Specify the ids of the attributes to return
864
      String[] attrIDs = {
865
          "o", "ref"};
866
      SearchControls ctls = new SearchControls();
867
      ctls.setReturningAttributes(attrIDs);
868
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
869 2058 sgarg
870 2121 sgarg
      // Specify the attributes to match.
871
      // Subtrees from the main server are found as objects with attribute
872
      // objectclass=organization or objectclass=referral to the subtree
873
      // resided on other server.
874
      String filter = "(|(objectclass=organization)(objectclass=referral))";
875 730 bojilova
876 2121 sgarg
      // Search for objects in the current context
877 2447 sgarg
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
878 730 bojilova
879 2121 sgarg
      // Print the subtrees' <ldapURL, baseDN>
880 2447 sgarg
      while (namingEnum.hasMore()) {
881 2121 sgarg
882 2447 sgarg
        SearchResult sr = (SearchResult) namingEnum.next();
883 2121 sgarg
884
        Attributes attrs = sr.getAttributes();
885
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
886
887
        if (enum1.hasMore()) {
888
          Attribute attr = (Attribute) enum1.next();
889
          String attrValue = (String) attr.get();
890
          String attrName = (String) attr.getID();
891
892 730 bojilova
          if (enum1.hasMore()) {
893 2121 sgarg
            attr = (Attribute) enum1.next();
894
            String refValue = (String) attr.get();
895
            String refName = (String) attr.getID();
896
            if (ldapBase.startsWith(refName + "=" + refValue)) {
897
              trees.put(ldapBase,
898
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
899
            }
900
            else {
901 2129 sgarg
              // this is a referral - so organization name is appended in
902
              // front of the ldapbase.... later it is stripped out
903
              // in getPrincipals
904
              trees.put("[" + refName + "=" + refValue + "]" +
905
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
906
                                            attrValue.length()),
907 2121 sgarg
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
908 2129 sgarg
909
              // trees.put(refName + "=" + refValue + "," + ldapBase,
910
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
911 2121 sgarg
            }
912 2058 sgarg
913 2121 sgarg
          }
914
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
915
            trees.put(ldapBase, ldapUrl);
916
          }
917
          else {
918 2129 sgarg
            if (sr.isRelative()) {
919 2121 sgarg
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
920 2130 sgarg
            }
921
            else {
922 2121 sgarg
              String referenceURL = sr.getName();
923 2129 sgarg
              referenceURL = referenceURL.substring(0,
924
                  referenceURL.lastIndexOf("/") + 1);
925
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
926
                        referenceURL);
927 730 bojilova
            }
928 2121 sgarg
929 504 jones
          }
930
        }
931 2121 sgarg
      }
932 730 bojilova
933 2121 sgarg
      // Close the context when we're done
934
      ctx.close();
935 730 bojilova
936 2121 sgarg
    }
937
    catch (NamingException e) {
938 2666 sgarg
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
939 2589 sgarg
                        + e);
940 730 bojilova
      throw new ConnectException(
941 2121 sgarg
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
942 504 jones
    }
943
944 730 bojilova
    return trees;
945 504 jones
  }
946
947
  /**
948 730 bojilova
   * Get all groups and users from authentication scheme.
949 725 bojilova
   * The output is formatted in XML.
950 730 bojilova
   * @param user the user which requests the information
951
   * @param password the user's password
952 725 bojilova
   */
953 2121 sgarg
  public String getPrincipals(String user, String password) throws
954
      ConnectException {
955 725 bojilova
    StringBuffer out = new StringBuffer();
956 2559 sgarg
957 2058 sgarg
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
958 730 bojilova
    out.append("<principals>\n");
959 2058 sgarg
960 730 bojilova
    /*
961 2058 sgarg
     * get all subtrees first in the current dir context
962 730 bojilova
     * and then the Metacat users under them
963
     */
964 2121 sgarg
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
965
                                     this.ldapBase);
966 2058 sgarg
967 2447 sgarg
    Enumeration keyEnum = subtrees.keys();
968
    while (keyEnum.hasMoreElements()) {
969
      this.ldapBase = (String) keyEnum.nextElement();
970 2121 sgarg
      this.ldapUrl = (String) subtrees.get(ldapBase);
971 2058 sgarg
972 2129 sgarg
      /*
973
       * code to get the organization name from ldapBase
974
       */
975 2116 sgarg
      String orgName = this.ldapBase;
976 2130 sgarg
      if (orgName.startsWith("[")) {
977 2129 sgarg
        // if orgName starts with [ then it is a referral URL...
978
        // (see code in getSubtress)
979
        // hence orgName can be retrieved  by getting the string between
980
        // 'o=' and ']'
981
        // also the string between [ and ] needs to be striped out from
982
        // this.ldapBase
983
        this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
984
        if (orgName != null && orgName.indexOf("o=") > -1) {
985
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
986
          orgName = orgName.substring(0, orgName.indexOf("]"));
987
        }
988 2130 sgarg
      }
989
      else {
990 2129 sgarg
        // else it is not referral
991
        // hence orgName can be retrieved  by getting the string between
992
        // 'o=' and ','
993
        if (orgName != null && orgName.indexOf("o=") > -1) {
994
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
995
          if (orgName.indexOf(",") > -1) {
996
            orgName = orgName.substring(0, orgName.indexOf(","));
997
          }
998
        }
999 2121 sgarg
      }
1000
1001 2058 sgarg
      out.append("  <authSystem URI=\"" +
1002 2121 sgarg
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1003
                 "\">\n");
1004 730 bojilova
1005
      // get all groups for directory context
1006 2058 sgarg
      String[][] groups = getGroups(user, password);
1007
      String[][] users = getUsers(user, password);
1008
      int userIndex = 0;
1009 730 bojilova
1010
      // for the groups and users that belong to them
1011 2121 sgarg
      if (groups != null && groups.length > 0) {
1012
        for (int i = 0; i < groups.length; i++) {
1013 730 bojilova
          out.append("    <group>\n");
1014 2058 sgarg
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1015
          out.append("      <description>" + groups[i][1] + "</description>\n");
1016 2121 sgarg
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1017
          for (int j = 0; j < usersForGroup.length; j++) {
1018 2559 sgarg
1019 2058 sgarg
            userIndex = searchUser(usersForGroup[j], users);
1020 730 bojilova
            out.append("      <user>\n");
1021 2058 sgarg
1022 2121 sgarg
            if (userIndex < 0) {
1023 2095 sgarg
              out.append("        <username>" + usersForGroup[j] +
1024
                         "</username>\n");
1025 2121 sgarg
            }
1026
            else {
1027 2130 sgarg
              out.append("        <username>" + users[userIndex][0] +
1028 2121 sgarg
                         "</username>\n");
1029 2130 sgarg
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1030
              out.append("        <organization>" + users[userIndex][2] +
1031 2121 sgarg
                         "</organization>\n");
1032 2130 sgarg
              if (users[userIndex][3].compareTo("null") != 0) {
1033
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1034
                           "</organizationUnitName>\n");
1035
              }
1036
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1037 2058 sgarg
            }
1038
1039 730 bojilova
            out.append("      </user>\n");
1040
          }
1041
          out.append("    </group>\n");
1042
        }
1043
      }
1044 2058 sgarg
1045 2130 sgarg
      // for the users not belonging to any grou8p
1046 2121 sgarg
      for (int j = 0; j < users.length; j++) {
1047 725 bojilova
          out.append("    <user>\n");
1048 2058 sgarg
          out.append("      <username>" + users[j][0] + "</username>\n");
1049
          out.append("      <name>" + users[j][1] + "</name>\n");
1050 2130 sgarg
          out.append("      <organization>" + users[j][2] +
1051
                     "</organization>\n");
1052
          if (users[j][3].compareTo("null") != 0) {
1053
            out.append("      <organizationUnitName>" + users[j][3] +
1054
                       "</organizationUnitName>\n");
1055
          }
1056
          out.append("      <email>" + users[j][4] + "</email>\n");
1057 725 bojilova
          out.append("    </user>\n");
1058
      }
1059 2058 sgarg
1060 730 bojilova
      out.append("  </authSystem>\n");
1061 725 bojilova
    }
1062
    out.append("</principals>");
1063
    return out.toString();
1064
  }
1065
1066
  /**
1067 2058 sgarg
   * Method for getting index of user DN in User info array
1068
   */
1069 2121 sgarg
  int searchUser(String user, String userGroup[][]) {
1070
    for (int j = 0; j < userGroup.length; j++) {
1071
      if (user.compareTo(userGroup[j][0]) == 0) {
1072 2058 sgarg
        return j;
1073
      }
1074
    }
1075
    return -1;
1076
  }
1077
1078
  /**
1079 503 bojilova
   * Test method for the class
1080
   */
1081
  public static void main(String[] args) {
1082
1083 504 jones
    // Provide a user, such as: "Matt Jones", or "jones"
1084 503 bojilova
    String user = args[0];
1085
    String password = args[1];
1086
1087 2666 sgarg
    logMetacat.warn("Creating session...");
1088 503 bojilova
    AuthLdap authservice = new AuthLdap();
1089 2666 sgarg
    logMetacat.warn("Session exists...");
1090 2058 sgarg
1091 503 bojilova
    boolean isValid = false;
1092
    try {
1093 2666 sgarg
      logMetacat.warn("Authenticating...");
1094 503 bojilova
      isValid = authservice.authenticate(user, password);
1095
      if (isValid) {
1096 2666 sgarg
    	  logMetacat.warn("Authentication successful for: " + user);
1097 2121 sgarg
      }
1098
      else {
1099 2666 sgarg
        logMetacat.warn("Authentication failed for: " + user);
1100 503 bojilova
      }
1101 725 bojilova
1102 871 jones
      // Get attributes for the user
1103 503 bojilova
      if (isValid) {
1104 2666 sgarg
        logMetacat.info("\nGetting attributes for user....");
1105 991 tao
        HashMap userInfo = authservice.getAttributes(user, password, user);
1106 503 bojilova
        // Print all of the attributes
1107 2121 sgarg
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1108 503 bojilova
        while (attList.hasNext()) {
1109 2121 sgarg
          String att = (String) attList.next();
1110
          Vector values = (Vector) userInfo.get(att);
1111 503 bojilova
          Iterator attvalues = values.iterator();
1112
          while (attvalues.hasNext()) {
1113 2121 sgarg
            String value = (String) attvalues.next();
1114 2666 sgarg
            logMetacat.warn(att + ": " + value);
1115 503 bojilova
          }
1116
        }
1117 871 jones
      }
1118 723 bojilova
1119 871 jones
      // get the groups
1120
      if (isValid) {
1121 2666 sgarg
        logMetacat.warn("\nGetting all groups....");
1122 2058 sgarg
        String[][] groups = authservice.getGroups(user, password);
1123 2666 sgarg
        logMetacat.info("Groups found: " + groups.length);
1124 2121 sgarg
        for (int i = 0; i < groups.length; i++) {
1125 2666 sgarg
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1126 871 jones
        }
1127 503 bojilova
      }
1128 725 bojilova
1129 871 jones
      // get the groups for the user
1130
      String savedGroup = null;
1131
      if (isValid) {
1132 2666 sgarg
        logMetacat.warn("\nGetting groups for user....");
1133 2058 sgarg
        String[][] groups = authservice.getGroups(user, password, user);
1134 2666 sgarg
        logMetacat.info("Groups found: " + groups.length);
1135 2121 sgarg
        for (int i = 0; i < groups.length; i++) {
1136 2666 sgarg
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1137 2121 sgarg
          savedGroup = groups[i][0];
1138 871 jones
        }
1139
      }
1140
1141
      // get the users for a group
1142
      if (isValid) {
1143 2666 sgarg
        logMetacat.warn("\nGetting users for group....");
1144
        logMetacat.info("Group: " + savedGroup);
1145 871 jones
        String[] users = authservice.getUsers(user, password, savedGroup);
1146 2666 sgarg
        logMetacat.info("Users found: " + users.length);
1147 2121 sgarg
        for (int i = 0; i < users.length; i++) {
1148 2666 sgarg
          logMetacat.warn("User " + i + ": " + users[i]);
1149 871 jones
        }
1150
      }
1151
1152
      // get all users
1153
      if (isValid) {
1154 2666 sgarg
        logMetacat.warn("\nGetting all users ....");
1155 2058 sgarg
        String[][] users = authservice.getUsers(user, password);
1156 2666 sgarg
        logMetacat.info("Users found: " + users.length);
1157 2058 sgarg
1158 871 jones
      }
1159 873 jones
1160 726 bojilova
      // get the whole list groups and users in XML format
1161 725 bojilova
      if (isValid) {
1162 2666 sgarg
        logMetacat.warn("\nTrying principals....");
1163 730 bojilova
        authservice = new AuthLdap();
1164 725 bojilova
        String out = authservice.getPrincipals(user, password);
1165 802 bojilova
        java.io.File f = new java.io.File("principals.xml");
1166 725 bojilova
        java.io.FileWriter fw = new java.io.FileWriter(f);
1167
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1168
        buff.write(out);
1169
        buff.flush();
1170
        buff.close();
1171
        fw.close();
1172 2666 sgarg
        logMetacat.warn("\nFinished getting principals.");
1173 725 bojilova
      }
1174 873 jones
1175 2121 sgarg
    }
1176
    catch (ConnectException ce) {
1177 2666 sgarg
      logMetacat.error(ce.getMessage());
1178 2121 sgarg
    }
1179
    catch (java.io.IOException ioe) {
1180 2666 sgarg
      logMetacat.error("I/O Error writing to file principals.txt");
1181 503 bojilova
    }
1182
  }
1183 2058 sgarg
1184 934 tao
  /**
1185
   * This method will be called by start a thread.
1186
   * It can handle if a referral exception happend.
1187 2058 sgarg
   */
1188 2121 sgarg
  public void run() {
1189 893 berkley
    referralContext = null;
1190 2121 sgarg
    DirContext refDirContext = null;
1191
    boolean moreReferrals = true;
1192
    String referralInfo = null;
1193 934 tao
    //set a while loop is because we don't know if a referral excption contains
1194
    //another referral exception
1195 2121 sgarg
    while (moreReferrals) {
1196
      try {
1197 934 tao
        //revise environment variable
1198 2121 sgarg
        referralInfo = (String) refExc.getReferralInfo();
1199 2666 sgarg
        logMetacat.info("Processing referral (pr0): ");
1200
        logMetacat.info("PROVIDER_URL set to (pr1): " + referralInfo);
1201 1988 jones
        //env.put(Context.PROVIDER_URL,referralInfo);
1202
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1203
        //env.put(Context.SECURITY_PRINCIPAL, userName);
1204
        //env.put(Context.SECURITY_CREDENTIALS, userPassword);
1205
        //env.put(Context.REFERRAL, "throw");
1206 2666 sgarg
        //logMetacat.info("Processing referral (pr1.info): " + userName,35);
1207
        //logMetacat.info("Processing referral (pr2)",35);
1208 1988 jones
        //rContext = refExc.getReferralContext(env);
1209
        rContext = refExc.getReferralContext();
1210 2666 sgarg
        logMetacat.info("Processing referral (pr3)");
1211 934 tao
        //casting the context to dircontext and it will create a
1212
        //autherntication or naming exception if DN and password is incorrect
1213 2121 sgarg
        referralContext = rContext;
1214
        refDirContext = (DirContext) rContext;
1215 991 tao
        refDirContext.close();
1216 934 tao
        //get context and jump out the while loop
1217 2121 sgarg
        moreReferrals = false;
1218 2666 sgarg
        logMetacat.info("Processing referral (pr4)");
1219 2121 sgarg
      } //try
1220 991 tao
      //if referral have another referral excption
1221 2121 sgarg
      catch (ReferralException re) {
1222 2666 sgarg
        logMetacat.warn("GOT referral exception (re1): " + re.getMessage());
1223
        logMetacat.warn("RE details (re2): " + re.toString(true));
1224 934 tao
        //keep running in while loop
1225 2121 sgarg
        moreReferrals = true;
1226 934 tao
        //assign refExc to new referral exception re
1227 2121 sgarg
        refExc = re;
1228 934 tao
      }
1229 991 tao
      //catch a authentication exception
1230 2121 sgarg
      catch (AuthenticationException ae) {
1231 2666 sgarg
        logMetacat.error("Error running referral handler thread (ae1): " +
1232 2589 sgarg
                          ae.getMessage());
1233 934 tao
        //check if has another referral
1234 2121 sgarg
        moreReferrals = refExc.skipReferral();
1235 934 tao
        //don't get the context
1236
        referralContext = null;
1237
      }
1238 991 tao
      //catch a naming exception
1239 2121 sgarg
      catch (NamingException ne) {
1240 2666 sgarg
        logMetacat.error("Error running referral handler thread (ne1): " +
1241 2589 sgarg
                          ne.getMessage());
1242 934 tao
        //check if has another referral
1243 2121 sgarg
        moreReferrals = refExc.skipReferral();
1244 934 tao
        //don't get context
1245 2058 sgarg
        referralContext = null;
1246 934 tao
      }
1247 2121 sgarg
    } //while
1248
  } //run()
1249 2058 sgarg
1250 2121 sgarg
  private class GetGroup
1251
      implements Runnable {
1252
    public void run() {
1253 991 tao
      referralContext = null;
1254 2666 sgarg
      logMetacat.info("getting groups context");
1255 2121 sgarg
      DirContext refDirContext = null;
1256
      boolean moreReferrals = true;
1257 2058 sgarg
      //set a while loop is because we don't know if a referral excption
1258 991 tao
      //contains another referral exception
1259 2121 sgarg
      while (moreReferrals) {
1260
        try {
1261 991 tao
          //revise environment variable
1262
          String refInfo = null;
1263 2121 sgarg
          refInfo = (String) refExc.getReferralInfo();
1264
          if (refInfo != null) {
1265 2666 sgarg
            logMetacat.info("Referral in thread to: " +
1266 2589 sgarg
                                     refInfo.toString());
1267 991 tao
          }
1268 2121 sgarg
          else {
1269 2666 sgarg
            logMetacat.info("getting refInfo Manually");
1270 2121 sgarg
            refInfo = (String) refExc.getReferralContext().getEnvironment().
1271
                get(Context.PROVIDER_URL);
1272 991 tao
          }
1273 2666 sgarg
          logMetacat.info("refInfo: " + refInfo);
1274 2058 sgarg
1275
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1276 2121 sgarg
                  "com.sun.jndi.ldap.LdapCtxFactory");
1277 991 tao
          env.put(Context.REFERRAL, "throw");
1278
          env.put(Context.PROVIDER_URL, refInfo);
1279 2058 sgarg
1280 2666 sgarg
          logMetacat.info("creating referralContext");
1281 991 tao
          referralContext = new InitialDirContext(env);
1282 2666 sgarg
          logMetacat.info("referralContext created");
1283 991 tao
          //get context and jump out the while loop
1284 2121 sgarg
          moreReferrals = false;
1285
        } //try
1286
        catch (ReferralException re) {
1287 991 tao
          //keep running in while loop
1288 2121 sgarg
          moreReferrals = true;
1289 991 tao
          //assign refExc to new referral exception re
1290 2121 sgarg
          refExc = re;
1291 991 tao
        }
1292 2121 sgarg
        catch (AuthenticationException ae) {
1293 2666 sgarg
          logMetacat.error("Error running referral handler thread (ae2): " +
1294 2589 sgarg
                            ae.getMessage());
1295 991 tao
          //check if has another referral
1296 2121 sgarg
          moreReferrals = refExc.skipReferral();
1297 991 tao
          //don't get the context
1298
          referralContext = null;
1299
        }
1300 2121 sgarg
        catch (NamingException ne) {
1301 2666 sgarg
          logMetacat.error("Error running referral handler thread (ne2): " +
1302 2589 sgarg
                            ne.getMessage());
1303 991 tao
          //check if has another referral
1304 2121 sgarg
          moreReferrals = refExc.skipReferral();
1305 991 tao
          //don't get context
1306 2058 sgarg
          referralContext = null;
1307 991 tao
        }
1308 2121 sgarg
      } //while
1309
    } //run()
1310
  }
1311 503 bojilova
}