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