Project

General

Profile

1
/**
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: sgarg $'
12
 *     '$Date: 2005-10-27 16:15:00 -0700 (Thu, 27 Oct 2005) $'
13
 * '$Revision: 2697 $'
14
 *
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
 */
29

    
30
package edu.ucsb.nceas.metacat;
31

    
32
import java.net.ConnectException;
33
import javax.naming.AuthenticationException;
34
import javax.naming.Context;
35
import javax.naming.NamingEnumeration;
36
import javax.naming.NamingException;
37
import javax.naming.SizeLimitExceededException;
38
import javax.naming.InitialContext;
39
import javax.naming.directory.InvalidSearchFilterException;
40
import javax.naming.directory.Attribute;
41
import javax.naming.directory.Attributes;
42
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
import javax.naming.directory.SearchControls;
48
import javax.naming.ReferralException;
49
import javax.naming.ldap.*;
50

    
51
import org.apache.log4j.Logger;
52

    
53
import java.net.URLDecoder;
54
import java.util.Iterator;
55
import java.util.HashMap;
56
import java.util.Hashtable;
57
import java.util.Enumeration;
58
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
 * The LDAP authentication service is used to determine if a user
65
 * is authenticated, and whether they are a member of a particular group.
66
 */
67
public class AuthLdap
68
    implements AuthInterface, Runnable {
69
  private MetaCatUtil util = new MetaCatUtil();
70
  private String ldapUrl;
71
  private String ldapsUrl;
72
  private String ldapBase;
73
  private String referral;
74
  private Context referralContext;
75
  Hashtable env = new Hashtable(11);
76
  private Context rContext;
77
  private String userName;
78
  private String userPassword;
79
  ReferralException refExc;
80

    
81
  private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
82
  
83
  /**
84
   * Construct an AuthLdap
85
   */
86
  public AuthLdap() {
87
    // Read LDAP URI for directory service information
88
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
89
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
90
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
91
    this.referral = MetaCatUtil.getOption("referral");
92
  }
93

    
94
  /**
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
  public boolean authenticate(String user, String password) throws
103
      ConnectException {
104
    String ldapUrl = this.ldapUrl;
105
    String ldapsUrl = this.ldapsUrl;
106
    String ldapBase = this.ldapBase;
107
    boolean authenticated = false;
108
    String identifier = user;
109
    //get uid here.
110
    //uid=user.substring(0, user.indexOf(","));
111

    
112
    try {
113
      // 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
        logMetacat.info("Looking up DN for: " + identifier);
118
        identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
119
        logMetacat.info("DN found: " + identifier);
120
        String decoded = URLDecoder.decode(identifier);
121
        logMetacat.info("DN decoded: " + decoded);
122
        identifier = decoded;
123
        String refUrl = "";
124
        String refBase = "";
125
        if (identifier.startsWith("ldap")) {
126
          refUrl = identifier.substring(0,
127
                                        identifier.lastIndexOf("/") + 1);
128
          logMetacat.info("Ref ldapUrl: " + refUrl);
129
          int position = identifier.indexOf(",");
130
          int position2 = identifier.indexOf(",", position + 1);
131
          refBase = identifier.substring(position2 + 1);
132
          logMetacat.info("Ref ldapBase: " + refBase);
133
          identifier = identifier.substring(
134
              identifier.lastIndexOf("/") + 1);
135
          logMetacat.info("Trying: " + identifier);
136
          authenticated = ldapAuthenticate(identifier, password,
137
                                           refUrl, refBase);
138
        }
139
        else {
140
          identifier = identifier + "," + ldapBase;
141
          logMetacat.info("Trying: " + identifier);
142
          authenticated = ldapAuthenticate(identifier, password);
143
        }
144
        //authenticated = ldapAuthenticate(identifier, password);
145
      }
146

    
147
    }
148
    catch (NullPointerException e) {
149
      logMetacat.error("NullPointerException b' password is null");
150
      logMetacat.error("NullPointerException while authenticating in " +
151
                        "AuthLdap.authenticate: " + e);
152
      throw new ConnectException(
153
          "NullPointerException while authenticating in " +
154
          "AuthLdap.authenticate: " + e);
155
    }
156
    catch (NamingException e) {
157
      logMetacat.error("Naming exception while authenticating in " +
158
                        "AuthLdap.authenticate: " + e);
159
      e.printStackTrace();
160
    }
161
    catch (Exception e) {
162
      logMetacat.error(e.getMessage());
163
    }
164
    return authenticated;
165
  }
166

    
167
  /**
168
   * 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
  private boolean ldapAuthenticate(String identifier, String password) throws
175
      ConnectException, NamingException, NullPointerException {
176
    return ldapAuthenticate(identifier, password,
177
                            this.ldapsUrl, this.ldapBase);
178
  }
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
                                   String directoryUrl, String searchBase) throws
189
      ConnectException, NamingException, NullPointerException {
190
    double totStartTime = System.currentTimeMillis();
191
    boolean authenticated = false;
192
    if (identifier != null && !password.equals("")) {
193

    
194
      //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
              "com.sun.jndi.ldap.LdapCtxFactory");
201
      env.put(Context.REFERRAL, "throw");
202
      env.put(Context.PROVIDER_URL, directoryUrl + searchBase);
203
      logMetacat.info("PROVIDER_URL set to: " + directoryUrl + searchBase);
204
      if (!ldapsUrl.equals(ldapUrl)) {
205
        // ldap is set on default port 389
206
        // ldaps is set on second port - 636 by default
207
        // env.put(Context.SECURITY_PROTOCOL, "ssl");
208
       }
209
      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
        logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
220
                          (stopTime - startTime) / 1000 + " seconds.");
221
        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
        }
233
      }
234
      catch (javax.naming.InvalidNameException ine) {
235
        logMetacat.error("An invalid DN was provided!");
236
      }
237
      catch (javax.naming.ReferralException re) {
238
        logMetacat.error("referral during authentication");
239
        logMetacat.error("Referral information: " + re.getReferralInfo());
240
        try {
241
          refExc = re;
242

    
243
          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
          logMetacat.info("Awake after 5 seconds.");
248
          if (referralContext == null) {
249
            t.interrupt();
250
            authenticated = false;
251
          }
252
          else {
253
            authenticated = true;
254
          }
255
        }
256
        catch (Exception e) {
257
          authenticated = false;
258
        }
259
      }
260
    }
261
    else {
262
      logMetacat.info("User not found");
263
    }
264
    double totStopTime = System.currentTimeMillis();
265
    logMetacat.warn("total ldap authentication time: " +
266
                      (totStopTime - totStartTime) / 1000 + " seconds");
267
    return authenticated;
268
  }
269

    
270
  /**
271
   * 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
   * @returns String the identifying name for the user,
277
   *          or null if not found
278
   */
279
  private String getIdentifyingName(String user, String ldapUrl,
280
                                    String ldapBase) throws NamingException {
281
    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
    logMetacat.info("setting referrals to: " + referral);
287
    env.put(Context.REFERRAL, referral);
288
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
289
    //    non-secure LDAP context; dn are publicly readable
290
    try {
291

    
292
      // 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
      // Search for the user id or name using the uid, then cn and sn
298
      //attributes
299
      // If we find a record, determine the dn for the record
300
      // The following blocks need to be refactored into a subroutine
301
      // they have a ridiculous amount of redundancy
302

    
303
      // 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
      logMetacat.info("First comp is: " + comp1);
308
      String comp2 = user.substring(position + 1,
309
                                    user.indexOf(",", position + 1));
310
      logMetacat.info("Second comp is: " + comp2);
311

    
312
      //String filter = "(&(" + comp1 + "))";
313
      String filter = "(&(" + comp1 + ")(" + comp2 + "))";
314
      logMetacat.info("Filter is: " + filter);
315
      logMetacat.info("Provider URL is: " + ldapUrl + ldapBase);
316
      NamingEnumeration answer;
317
      try {
318
        logMetacat.info("Trying search 1: " + filter);
319
        answer = ctx.search("", filter, ctls);
320
        logMetacat.info("Search 1 complete");
321
        if (answer == null) {
322
          logMetacat.info("Search 1 answer is null.");
323
        }
324
        if (answer.hasMore()) {
325
          logMetacat.info("Search 1 has answers.");
326
          SearchResult sr = (SearchResult) answer.next();
327
          identifier = sr.getName();
328
          logMetacat.info("Originally Found: " + identifier);
329
          return identifier;
330
        }
331
      }
332
      catch (InvalidSearchFilterException e) {
333
        logMetacat.error("Invalid Filter exception thrown (if1)");
334
      }
335

    
336
      // That failed, so check if it is just a username
337
      filter = "(" + user + ")";
338
      try {
339
        logMetacat.info("Trying again: " + filter);
340
        answer = ctx.search("", filter, ctls);
341
        if (answer.hasMore()) {
342
          SearchResult sr = (SearchResult) answer.next();
343
          identifier = sr.getName();
344
          if (!sr.isRelative()) {
345
            this.ldapUrl = identifier.substring(0,
346
                                                identifier.lastIndexOf("/") + 1);
347
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
348
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
349
                                              identifier.indexOf(","));
350
          }
351
          logMetacat.info("Found: " + identifier);
352
          return identifier;
353
        }
354
      }
355
      catch (InvalidSearchFilterException e) {}
356

    
357
      // Maybe its a user id (uid)
358
      filter = "(uid=" + user + ")";
359
      logMetacat.info("Trying again: " + filter);
360
      answer = ctx.search("", filter, ctls);
361
      if (answer.hasMore()) {
362
        SearchResult sr = (SearchResult) answer.next();
363
        identifier = sr.getName();
364
        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
                                            identifier.indexOf(","));
370
        }
371
        logMetacat.info("Found: " + identifier);
372
      }
373
      else {
374

    
375
        // maybe its just a common name
376
        filter = "(cn=" + user + ")";
377
        logMetacat.info("Trying again: " + filter);
378
        NamingEnumeration answer2 = ctx.search("", filter, ctls);
379
        if (answer2.hasMore()) {
380
          SearchResult sr = (SearchResult) answer2.next();
381
          identifier = sr.getName();
382
          if (!sr.isRelative()) {
383
            this.ldapUrl = identifier.substring(0,
384
                                                identifier.lastIndexOf("/") + 1);
385
            this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
386
            identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
387
                                              identifier.indexOf(","));
388
          }
389
          logMetacat.info("Found: " + identifier);
390
        }
391
        else {
392

    
393
          // ok, last resort, is it a surname?
394
          filter = "(sn=" + user + ")";
395
          logMetacat.info("Trying again: " + filter);
396
          NamingEnumeration answer3 = ctx.search("", filter, ctls);
397
          if (answer3.hasMore()) {
398
            SearchResult sr = (SearchResult) answer3.next();
399
            identifier = sr.getName();
400
            if (!sr.isRelative()) {
401
              this.ldapUrl = identifier.substring(0,
402
                                                  identifier.lastIndexOf("/") +
403
                                                  1);
404
              this.ldapBase = identifier.substring(identifier.indexOf(",") + 1);
405
              identifier = identifier.substring(identifier.lastIndexOf("/") + 1,
406
                                                identifier.indexOf(","));
407
            }
408
            logMetacat.info("Found: " + identifier);
409
          }
410
        }
411
      }
412
      // Close the context when we're done the initial search
413
      ctx.close();
414
    }
415
    catch (NamingException e) {
416
      logMetacat.error("Naming exception while getting dn: " + e);
417
      throw new NamingException(
418
          "Naming exception in AuthLdap.getIdentifyingName: " + e);
419
    }
420
    logMetacat.error("Returning found identifier as: " + identifier);
421
    return identifier;
422
  }
423

    
424
  /**
425
   * Get all users from the authentication service
426
   *
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
   */
431
  public String[][] getUsers(String user, String password) throws
432
      ConnectException {
433
    String[][] users = null;
434

    
435
    // Identify service provider to use
436
    Hashtable env = new Hashtable(11);
437
    env.put(Context.INITIAL_CONTEXT_FACTORY,
438
            "com.sun.jndi.ldap.LdapCtxFactory");
439
    env.put(Context.REFERRAL, referral);
440
    env.put(Context.PROVIDER_URL, ldapUrl);
441

    
442
    try {
443

    
444
      // Create the initial directory context
445
      DirContext ctx = new InitialDirContext(env);
446

    
447
      // Specify the attributes to match.
448
      // Users are objects that have the attribute objectclass=InetOrgPerson.
449
      SearchControls ctls = new SearchControls();
450
      String[] attrIDs = {
451
          "dn", "cn", "o", "ou", "mail"};
452
      ctls.setReturningAttributes(attrIDs);
453
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
454
      //ctls.setCountLimit(1000);
455
      String filter = "(objectClass=inetOrgPerson)";
456
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
457

    
458
      // Store the users in a vector
459
      Vector uvec = new Vector();
460
      Vector uname = new Vector();
461
      Vector uorg = new Vector();
462
      Vector uou = new Vector();
463
      Vector umail = new Vector();
464
      Attributes tempAttr = null;
465
      try {
466
        while (namingEnum.hasMore()) {
467
          SearchResult sr = (SearchResult) namingEnum.next();
468
          tempAttr = sr.getAttributes();
469

    
470
          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

    
477
          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

    
484
          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
          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

    
498
          uvec.add(sr.getName() + "," + ldapBase);
499
        }
500
      }
501
      catch (SizeLimitExceededException slee) {
502
        logMetacat.error("LDAP Server size limit exceeded. " +
503
                          "Returning incomplete record set.");
504
      }
505

    
506
      // initialize users[]; fill users[]
507
      users = new String[uvec.size()][5];
508
      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
        users[i][3] = (String) uorg.elementAt(i);
513
        users[i][4] = (String) umail.elementAt(i);
514
      }
515

    
516
      // Close the context when we're done
517
      ctx.close();
518

    
519
    }
520
    catch (NamingException e) {
521
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
522
      //e.printStackTrace(System.err);
523
      throw new ConnectException(
524
          "Problem getting users in AuthLdap.getUsers:" + e);
525
    }
526

    
527
    return users;
528
  }
529

    
530
  
531
  /**
532
   * Get all users from the authentication service
533
   *
534
   * @param user the user for authenticating against the service
535
   * @param password the password for authenticating against the service
536
   * @returns string array of all of the user names
537
   */
538
  public String[] getUserInfo(String user, String password) throws
539
      ConnectException {
540
    String[] userinfo = new String[3];
541

    
542
    // Identify service provider to use
543
    Hashtable env = new Hashtable(11);
544
    env.put(Context.INITIAL_CONTEXT_FACTORY,
545
            "com.sun.jndi.ldap.LdapCtxFactory");
546
    env.put(Context.REFERRAL, referral);
547
    env.put(Context.PROVIDER_URL, ldapUrl);
548

    
549
    try {
550
      
551
      // Create the initial directory context
552
      DirContext ctx = new InitialDirContext(env);
553
      // Specify the attributes to match.
554
      // Users are objects that have the attribute objectclass=InetOrgPerson.
555
      SearchControls ctls = new SearchControls();
556
      String[] attrIDs = {
557
          "cn", "o", "mail"};
558
      ctls.setReturningAttributes(attrIDs);
559
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
560
      //ctls.setCountLimit(1000);
561
      // create the filter based on the uid
562
      
563
      String filter = null;
564
      
565
      if(user.indexOf("o=")>0){
566
    	  String tempStr = user.substring(user.indexOf("o="));
567
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
568
			+ ")(" + tempStr.substring(0, tempStr.indexOf(",")) 
569
			+ "))";      
570
      } else{
571
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
572
			+ "))";          		  
573
      }
574
   	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
575
		+ "))";          		  
576

    
577
      NamingEnumeration namingEnum = ctx.search(user, filter, ctls);
578
      
579
      Attributes tempAttr = null;
580
      try {
581
        while (namingEnum.hasMore()) {
582
          SearchResult sr = (SearchResult) namingEnum.next();
583
          tempAttr = sr.getAttributes();
584

    
585
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
586
        	  userinfo[0] = (tempAttr.get("cn") + "").substring(4);
587
          }
588
          else {
589
        	  userinfo[0] = (tempAttr.get("cn") + "");
590
          }
591

    
592
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
593
        	  userinfo[1] = (tempAttr.get("o") + "").substring(3);
594
          }
595
          else {
596
        	  userinfo[1] = (tempAttr.get("o") + "");
597
          }
598

    
599
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
600
        	  userinfo[2] =  (tempAttr.get("mail") + "").substring(6);
601
          }
602
          else {
603
        	  userinfo[2] = (tempAttr.get("mail") + "");
604
          }
605
        }
606
      }
607
      catch (SizeLimitExceededException slee) {
608
        logMetacat.error("LDAP Server size limit exceeded. " +
609
                          "Returning incomplete record set.");
610
      }
611

    
612
      // Close the context when we're done
613
      ctx.close();
614

    
615
    }
616
    catch (NamingException e) {
617
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
618
      //e.printStackTrace(System.err);
619
      throw new ConnectException(
620
          "Problem getting users in AuthLdap.getUsers:" + e);
621
    }
622

    
623
    return userinfo;
624
  }
625

    
626
  /**
627
   * Get the users for a particular group from the authentication service
628
   *
629
   * @param user the user for authenticating against the service
630
   * @param password the password for authenticating against the service
631
   * @param group the group whose user list should be returned
632
   * @returns string array of the user names belonging to the group
633
   */
634
  public String[] getUsers(String user, String password, String group) throws
635
      ConnectException {
636
    String[] users = null;
637

    
638
    // Identify service provider to use
639
    Hashtable env = new Hashtable(11);
640
    env.put(Context.INITIAL_CONTEXT_FACTORY,
641
            "com.sun.jndi.ldap.LdapCtxFactory");
642
    env.put(Context.REFERRAL, referral);
643
    env.put(Context.PROVIDER_URL, ldapUrl);
644

    
645
    try {
646

    
647
      // Create the initial directory context
648
      DirContext ctx = new InitialDirContext(env);
649

    
650
      // Specify the ids of the attributes to return
651
      String[] attrIDs = {
652
          "uniqueMember"};
653

    
654
      Attributes answer = ctx.getAttributes(group, attrIDs);
655

    
656
      Vector uvec = new Vector();
657
      try {
658
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
659
          Attribute attr = (Attribute) ae.next();
660
          for (NamingEnumeration e = attr.getAll();
661
               e.hasMore();
662
               uvec.add(e.next())
663
               ) {
664
            ;
665
          }
666
        }
667
      }
668
      catch (SizeLimitExceededException slee) {
669
        logMetacat.error("LDAP Server size limit exceeded. " +
670
                          "Returning incomplete record set.");
671
      }
672

    
673
      // initialize users[]; fill users[]
674
      users = new String[uvec.size()];
675
      for (int i = 0; i < uvec.size(); i++) {
676
        users[i] = (String) uvec.elementAt(i);
677
      }
678

    
679
      // Close the context when we're done
680
      ctx.close();
681

    
682
    }
683
    catch (NamingException e) {
684
      logMetacat.error("Problem getting users for a group in " +
685
                        "AuthLdap.getUsers:" + e);
686
      throw new ConnectException(
687
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
688
    }
689

    
690
    return users;
691
  }
692

    
693
  /**
694
   * Get all groups from the authentication service
695
   *
696
   * @param user the user for authenticating against the service
697
   * @param password the password for authenticating against the service
698
   * @returns string array of the group names
699
   */
700
  public String[][] getGroups(String user, String password) throws
701
      ConnectException {
702
    return getGroups(user, password, null);
703
  }
704

    
705
  /**
706
   * Get the groups for a particular user from the authentication service
707
   *
708
   * @param user the user for authenticating against the service
709
   * @param password the password for authenticating against the service
710
   * @param foruser the user whose group list should be returned
711
   * @returns string array of the group names
712
   */
713
  public String[][] getGroups(String user, String password, String foruser) throws
714
      ConnectException {
715
    Vector gvec = new Vector();
716
    Vector desc = new Vector();
717
    Attributes tempAttr = null;
718

    
719
    //Pass the username and password to run() method
720
    userName = user;
721
    userPassword = password;
722
    // Identify service provider to use
723
    env.put(Context.INITIAL_CONTEXT_FACTORY,
724
            "com.sun.jndi.ldap.LdapCtxFactory");
725
    env.put(Context.REFERRAL, "throw");
726
    env.put(Context.PROVIDER_URL, ldapUrl);
727
    try {
728
      // Create the initial directory context
729
      DirContext ctx = new InitialDirContext(env);
730
      // Specify the ids of the attributes to return
731
      String[] attrIDs = {
732
          "cn", "o", "description"};
733
      // Specify the attributes to match.
734
      // Groups are objects with attribute objectclass=groupofuniquenames.
735
      // and have attribute uniquemember: uid=foruser,ldapbase.
736
      SearchControls ctls = new SearchControls();
737
      ctls.setReturningAttributes(attrIDs);
738
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
739

    
740
      String filter = null;
741
      String gfilter = "(objectClass=groupOfUniqueNames)";
742
      if (null == foruser) {
743
        filter = gfilter;
744
      }
745
      else {
746
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
747
      }
748
      logMetacat.info("searching for groups: " + filter);
749
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
750

    
751
      // Print the groups
752
      logMetacat.info("getting group results.");
753
      while (namingEnum.hasMore()) {
754
        SearchResult sr = (SearchResult) namingEnum.next();
755
        tempAttr = sr.getAttributes();
756

    
757
        if ( (tempAttr.get("description") + "").startsWith("description: ")) {
758
          desc.add( (tempAttr.get("description") + "").substring(13));
759
        }
760
        else {
761
          desc.add(tempAttr.get("description") + "");
762
        }
763

    
764
        gvec.add(sr.getName() + "," + ldapBase);
765
        logMetacat.info("group " + sr.getName() +
766
                                 " added to Group vector");
767
      }
768
      // Close the context when we're done
769
      ctx.close();
770

    
771
    }
772
    catch (ReferralException re) {
773
      refExc = re;
774
      Thread t = new Thread(new GetGroup());
775
      logMetacat.info("Starting thread...");
776
      t.start();
777
      logMetacat.info("sleeping for 5 seconds.");
778
      try {
779
        Thread.sleep(5000);
780
      }
781
      catch (InterruptedException ie) {
782
        logMetacat.error("main thread interrupted: " + ie.getMessage());
783
      }
784
      //this is a manual override of jndi's hideously long time
785
      //out period.
786
      logMetacat.info("Awake after 5 seconds.");
787
      if (referralContext == null) {
788
        logMetacat.info("thread timed out...returning groups: " +
789
                          gvec.toString());
790
        String groups[][] = new String[gvec.size()][2];
791
        for (int i = 0; i < gvec.size(); i++) {
792
          groups[i][0] = (String) gvec.elementAt(i);
793
          groups[i][1] = (String) desc.elementAt(i);
794
        }
795
        t.interrupt();
796
        return groups;
797
      }
798
      DirContext dc = (DirContext) referralContext;
799
      String[] attrIDs = {
800
          "cn", "o", "description"};
801
      // Specify the attributes to match.
802
      // Groups are objects with attribute objectclass=groupofuniquenames.
803
      // and have attribute uniquemember: uid=foruser,ldapbase.
804
      SearchControls ctls = new SearchControls();
805
      ctls.setReturningAttributes(attrIDs);
806
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
807

    
808
      String filter = null;
809
      String gfilter = "(objectClass=groupOfUniqueNames)";
810
      if (null == foruser) {
811
        filter = gfilter;
812
      }
813
      else {
814
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
815
      }
816

    
817
      try {
818
        NamingEnumeration namingEnum = dc.search(ldapBase, filter, ctls);
819
        // Print the groups
820
        while (namingEnum.hasMore()) {
821
          SearchResult sr = (SearchResult) namingEnum.next();
822
          tempAttr = sr.getAttributes();
823

    
824
          if ( (tempAttr.get("description") + "").startsWith("description: ")) {
825
            desc.add( (tempAttr.get("description") + "").substring(13));
826
          }
827
          else {
828
            desc.add(tempAttr.get("description") + "");
829
          }
830

    
831
          gvec.add(sr.getName() + "," + ldapBase);
832
        }
833

    
834
        referralContext.close();
835
        dc.close();
836
      }
837
      catch (NamingException ne) {
838
        logMetacat.warn("Naming Exception in AuthLdap.getGroups" +
839
                                 ne.getExplanation() + ne.getMessage());
840
      }
841
    }
842
    catch (NamingException e) {
843
      e.printStackTrace(System.err);
844
      String groups[][] = new String[gvec.size()][2];
845
      for (int i = 0; i < gvec.size(); i++) {
846
        groups[i][0] = (String) gvec.elementAt(i);
847
        groups[i][1] = (String) desc.elementAt(i);
848
      }
849
      return groups;
850
      /*throw new ConnectException(
851
             "Problem getting groups for a user in AuthLdap.getGroups:" + e);*/
852
    }
853

    
854
    logMetacat.warn("The user is in the following groups: " +
855
                             gvec.toString());
856
    String groups[][] = new String[gvec.size()][2];
857
    for (int i = 0; i < gvec.size(); i++) {
858
      groups[i][0] = (String) gvec.elementAt(i);
859
      groups[i][1] = (String) desc.elementAt(i);
860
    }
861
    return groups;
862
  }
863

    
864
  /**
865
   * Get attributes describing a user or group
866
   *
867
   * @param foruser the user for which the attribute list is requested
868
   * @returns HashMap a map of attribute name to a Vector of values
869
   */
870
  public HashMap getAttributes(String foruser) throws ConnectException {
871
    return getAttributes(null, null, foruser);
872
  }
873

    
874
  /**
875
   * Get attributes describing a user or group
876
   *
877
   * @param user the user for authenticating against the service
878
   * @param password the password for authenticating against the service
879
   * @param foruser the user whose attributes should be returned
880
   * @returns HashMap a map of attribute name to a Vector of values
881
   */
882
  public HashMap getAttributes(String user, String password, String foruser) throws
883
      ConnectException {
884
    HashMap attributes = new HashMap();
885
    String ldapUrl = this.ldapUrl;
886
    String ldapBase = this.ldapBase;
887
    String userident = foruser;
888

    
889
    // Identify service provider to use
890
    Hashtable env = new Hashtable(11);
891
    env.put(Context.INITIAL_CONTEXT_FACTORY,
892
            "com.sun.jndi.ldap.LdapCtxFactory");
893
    env.put(Context.REFERRAL, referral);
894
    env.put(Context.PROVIDER_URL, ldapUrl);
895

    
896
    try {
897

    
898
      // Create the initial directory context
899
      DirContext ctx = new InitialDirContext(env);
900

    
901
      // Ask for all attributes of the user
902
      //Attributes attrs = ctx.getAttributes(userident);
903
      Attributes attrs = ctx.getAttributes(foruser);
904

    
905
      // Print all of the attributes
906
      NamingEnumeration en = attrs.getAll();
907
      while (en.hasMore()) {
908
        Attribute att = (Attribute) en.next();
909
        Vector values = new Vector();
910
        String attName = att.getID();
911
        NamingEnumeration attvalues = att.getAll();
912
        while (attvalues.hasMore()) {
913
          String value = (String) attvalues.next();
914
          values.add(value);
915
        }
916
        attributes.put(attName, values);
917
      }
918

    
919
      // Close the context when we're done
920
      ctx.close();
921
    }
922
    catch (NamingException e) {
923
      logMetacat.error("Problem getting attributes in " +
924
                        "AuthLdap.getAttributes:" + e);
925
      throw new ConnectException(
926
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
927
    }
928

    
929
    return attributes;
930
  }
931

    
932
  /**
933
   * Get list of all subtrees holding Metacat's groups and users
934
   * starting from the Metacat LDAP root,
935
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
936
   */
937
  private Hashtable getSubtrees(String user, String password,
938
                                String ldapUrl, String ldapBase) throws
939
      ConnectException {
940
    Hashtable trees = new Hashtable();
941

    
942
    // Identify service provider to use
943
    Hashtable env = new Hashtable(11);
944
    env.put(Context.INITIAL_CONTEXT_FACTORY,
945
            "com.sun.jndi.ldap.LdapCtxFactory");
946
    // env.put(Context.REFERRAL, referral);
947
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
948
    // to do the job better. 'follow' was not bringing up the UCNRS
949
    // and PISCO tree whereas 'ignore' brings up the tree.
950

    
951
    env.put(Context.REFERRAL, "ignore");
952
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
953

    
954
    try {
955

    
956
      // Create the initial directory context
957
      DirContext ctx = new InitialDirContext(env);
958

    
959
      // Specify the ids of the attributes to return
960
      String[] attrIDs = {
961
          "o", "ref"};
962
      SearchControls ctls = new SearchControls();
963
      ctls.setReturningAttributes(attrIDs);
964
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
965

    
966
      // Specify the attributes to match.
967
      // Subtrees from the main server are found as objects with attribute
968
      // objectclass=organization or objectclass=referral to the subtree
969
      // resided on other server.
970
      String filter = "(|(objectclass=organization)(objectclass=referral))";
971

    
972
      // Search for objects in the current context
973
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
974

    
975
      // Print the subtrees' <ldapURL, baseDN>
976
      while (namingEnum.hasMore()) {
977

    
978
        SearchResult sr = (SearchResult) namingEnum.next();
979

    
980
        Attributes attrs = sr.getAttributes();
981
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
982

    
983
        if (enum1.hasMore()) {
984
          Attribute attr = (Attribute) enum1.next();
985
          String attrValue = (String) attr.get();
986
          String attrName = (String) attr.getID();
987

    
988
          if (enum1.hasMore()) {
989
            attr = (Attribute) enum1.next();
990
            String refValue = (String) attr.get();
991
            String refName = (String) attr.getID();
992
            if (ldapBase.startsWith(refName + "=" + refValue)) {
993
              trees.put(ldapBase,
994
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
995
            }
996
            else {
997
              // this is a referral - so organization name is appended in
998
              // front of the ldapbase.... later it is stripped out
999
              // in getPrincipals
1000
              trees.put("[" + refName + "=" + refValue + "]" +
1001
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
1002
                                            attrValue.length()),
1003
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1004

    
1005
              // trees.put(refName + "=" + refValue + "," + ldapBase,
1006
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1007
            }
1008

    
1009
          }
1010
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
1011
            trees.put(ldapBase, ldapUrl);
1012
          }
1013
          else {
1014
            if (sr.isRelative()) {
1015
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
1016
            }
1017
            else {
1018
              String referenceURL = sr.getName();
1019
              referenceURL = referenceURL.substring(0,
1020
                  referenceURL.lastIndexOf("/") + 1);
1021
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
1022
                        referenceURL);
1023
            }
1024

    
1025
          }
1026
        }
1027
      }
1028

    
1029
      // Close the context when we're done
1030
      ctx.close();
1031

    
1032
    }
1033
    catch (NamingException e) {
1034
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
1035
                        + e);
1036
      throw new ConnectException(
1037
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
1038
    }
1039

    
1040
    return trees;
1041
  }
1042

    
1043
  /**
1044
   * Get all groups and users from authentication scheme.
1045
   * The output is formatted in XML.
1046
   * @param user the user which requests the information
1047
   * @param password the user's password
1048
   */
1049
  public String getPrincipals(String user, String password) throws
1050
      ConnectException {
1051
    StringBuffer out = new StringBuffer();
1052
   
1053
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
1054
    out.append("<principals>\n");
1055

    
1056
    /*
1057
     * get all subtrees first in the current dir context
1058
     * and then the Metacat users under them
1059
     */
1060
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
1061
                                     this.ldapBase);
1062

    
1063
    Enumeration keyEnum = subtrees.keys();
1064
    while (keyEnum.hasMoreElements()) {
1065
      this.ldapBase = (String) keyEnum.nextElement();
1066
      this.ldapUrl = (String) subtrees.get(ldapBase);
1067

    
1068
      /*
1069
       * code to get the organization name from ldapBase
1070
       */
1071
      String orgName = this.ldapBase;
1072
      if (orgName.startsWith("[")) {
1073
        // if orgName starts with [ then it is a referral URL...
1074
        // (see code in getSubtress)
1075
        // hence orgName can be retrieved  by getting the string between
1076
        // 'o=' and ']'
1077
        // also the string between [ and ] needs to be striped out from
1078
        // this.ldapBase
1079
        this.ldapBase = orgName.substring(orgName.indexOf("]") + 1);
1080
        if (orgName != null && orgName.indexOf("o=") > -1) {
1081
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1082
          orgName = orgName.substring(0, orgName.indexOf("]"));
1083
        }
1084
      }
1085
      else {
1086
        // else it is not referral
1087
        // hence orgName can be retrieved  by getting the string between
1088
        // 'o=' and ','
1089
        if (orgName != null && orgName.indexOf("o=") > -1) {
1090
          orgName = orgName.substring(orgName.indexOf("o=") + 2);
1091
          if (orgName.indexOf(",") > -1) {
1092
            orgName = orgName.substring(0, orgName.indexOf(","));
1093
          }
1094
        }
1095
      }
1096

    
1097
      out.append("  <authSystem URI=\"" +
1098
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1099
                 "\">\n");
1100

    
1101
      // get all groups for directory context
1102
      String[][] groups = getGroups(user, password);
1103
      String[][] users = getUsers(user, password);
1104
      int userIndex = 0;
1105

    
1106
      // for the groups and users that belong to them
1107
      if (groups != null && groups.length > 0) {
1108
        for (int i = 0; i < groups.length; i++) {
1109
          out.append("    <group>\n");
1110
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1111
          out.append("      <description>" + groups[i][1] + "</description>\n");
1112
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1113
          for (int j = 0; j < usersForGroup.length; j++) {
1114
            
1115
            userIndex = searchUser(usersForGroup[j], users);
1116
            out.append("      <user>\n");
1117

    
1118
            if (userIndex < 0) {
1119
              out.append("        <username>" + usersForGroup[j] +
1120
                         "</username>\n");
1121
            }
1122
            else {
1123
              out.append("        <username>" + users[userIndex][0] +
1124
                         "</username>\n");
1125
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1126
              out.append("        <organization>" + users[userIndex][2] +
1127
                         "</organization>\n");
1128
              if (users[userIndex][3].compareTo("null") != 0) {
1129
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1130
                           "</organizationUnitName>\n");
1131
              }
1132
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1133
            }
1134

    
1135
            out.append("      </user>\n");
1136
          }
1137
          out.append("    </group>\n");
1138
        }
1139
      }
1140

    
1141
      // for the users not belonging to any grou8p
1142
      for (int j = 0; j < users.length; j++) {
1143
          out.append("    <user>\n");
1144
          out.append("      <username>" + users[j][0] + "</username>\n");
1145
          out.append("      <name>" + users[j][1] + "</name>\n");
1146
          out.append("      <organization>" + users[j][2] +
1147
                     "</organization>\n");
1148
          if (users[j][3].compareTo("null") != 0) {
1149
            out.append("      <organizationUnitName>" + users[j][3] +
1150
                       "</organizationUnitName>\n");
1151
          }
1152
          out.append("      <email>" + users[j][4] + "</email>\n");
1153
          out.append("    </user>\n");
1154
      }
1155

    
1156
      out.append("  </authSystem>\n");
1157
    }
1158
    out.append("</principals>");
1159
    return out.toString();
1160
  }
1161

    
1162
  /**
1163
   * Method for getting index of user DN in User info array
1164
   */
1165
  int searchUser(String user, String userGroup[][]) {
1166
    for (int j = 0; j < userGroup.length; j++) {
1167
      if (user.compareTo(userGroup[j][0]) == 0) {
1168
        return j;
1169
      }
1170
    }
1171
    return -1;
1172
  }
1173

    
1174
  /**
1175
   * Test method for the class
1176
   */
1177
  public static void main(String[] args) {
1178

    
1179
    // Provide a user, such as: "Matt Jones", or "jones"
1180
    String user = args[0];
1181
    String password = args[1];
1182

    
1183
    logMetacat.warn("Creating session...");
1184
    AuthLdap authservice = new AuthLdap();
1185
    logMetacat.warn("Session exists...");
1186

    
1187
    boolean isValid = false;
1188
    try {
1189
      logMetacat.warn("Authenticating...");
1190
      isValid = authservice.authenticate(user, password);
1191
      if (isValid) {
1192
    	  logMetacat.warn("Authentication successful for: " + user);
1193
      }
1194
      else {
1195
        logMetacat.warn("Authentication failed for: " + user);
1196
      }
1197

    
1198
      // Get attributes for the user
1199
      if (isValid) {
1200
        logMetacat.info("\nGetting attributes for user....");
1201
        HashMap userInfo = authservice.getAttributes(user, password, user);
1202
        // Print all of the attributes
1203
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1204
        while (attList.hasNext()) {
1205
          String att = (String) attList.next();
1206
          Vector values = (Vector) userInfo.get(att);
1207
          Iterator attvalues = values.iterator();
1208
          while (attvalues.hasNext()) {
1209
            String value = (String) attvalues.next();
1210
            logMetacat.warn(att + ": " + value);
1211
          }
1212
        }
1213
      }
1214

    
1215
      // get the groups
1216
      if (isValid) {
1217
        logMetacat.warn("\nGetting all groups....");
1218
        String[][] groups = authservice.getGroups(user, password);
1219
        logMetacat.info("Groups found: " + groups.length);
1220
        for (int i = 0; i < groups.length; i++) {
1221
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1222
        }
1223
      }
1224

    
1225
      // get the groups for the user
1226
      String savedGroup = null;
1227
      if (isValid) {
1228
        logMetacat.warn("\nGetting groups for user....");
1229
        String[][] groups = authservice.getGroups(user, password, user);
1230
        logMetacat.info("Groups found: " + groups.length);
1231
        for (int i = 0; i < groups.length; i++) {
1232
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1233
          savedGroup = groups[i][0];
1234
        }
1235
      }
1236

    
1237
      // get the users for a group
1238
      if (isValid) {
1239
        logMetacat.warn("\nGetting users for group....");
1240
        logMetacat.info("Group: " + savedGroup);
1241
        String[] users = authservice.getUsers(user, password, savedGroup);
1242
        logMetacat.info("Users found: " + users.length);
1243
        for (int i = 0; i < users.length; i++) {
1244
          logMetacat.warn("User " + i + ": " + users[i]);
1245
        }
1246
      }
1247

    
1248
      // get all users
1249
      if (isValid) {
1250
        logMetacat.warn("\nGetting all users ....");
1251
        String[][] users = authservice.getUsers(user, password);
1252
        logMetacat.info("Users found: " + users.length);
1253

    
1254
      }
1255

    
1256
      // get the whole list groups and users in XML format
1257
      if (isValid) {
1258
        logMetacat.warn("\nTrying principals....");
1259
        authservice = new AuthLdap();
1260
        String out = authservice.getPrincipals(user, password);
1261
        java.io.File f = new java.io.File("principals.xml");
1262
        java.io.FileWriter fw = new java.io.FileWriter(f);
1263
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1264
        buff.write(out);
1265
        buff.flush();
1266
        buff.close();
1267
        fw.close();
1268
        logMetacat.warn("\nFinished getting principals.");
1269
      }
1270

    
1271
    }
1272
    catch (ConnectException ce) {
1273
      logMetacat.error(ce.getMessage());
1274
    }
1275
    catch (java.io.IOException ioe) {
1276
      logMetacat.error("I/O Error writing to file principals.txt");
1277
    }
1278
  }
1279

    
1280
  /**
1281
   * This method will be called by start a thread.
1282
   * It can handle if a referral exception happend.
1283
   */
1284
  public void run() {
1285
    referralContext = null;
1286
    DirContext refDirContext = null;
1287
    boolean moreReferrals = true;
1288
    String referralInfo = null;
1289
    //set a while loop is because we don't know if a referral excption contains
1290
    //another referral exception
1291
    while (moreReferrals) {
1292
      try {
1293
        //revise environment variable
1294
        referralInfo = (String) refExc.getReferralInfo();
1295
        logMetacat.info("Processing referral (pr0): ");
1296
        logMetacat.info("PROVIDER_URL set to (pr1): " + referralInfo);
1297
        //env.put(Context.PROVIDER_URL,referralInfo);
1298
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
1299
        //env.put(Context.SECURITY_PRINCIPAL, userName);
1300
        //env.put(Context.SECURITY_CREDENTIALS, userPassword);
1301
        //env.put(Context.REFERRAL, "throw");
1302
        //logMetacat.info("Processing referral (pr1.info): " + userName,35);
1303
        //logMetacat.info("Processing referral (pr2)",35);
1304
        //rContext = refExc.getReferralContext(env);
1305
        rContext = refExc.getReferralContext();
1306
        logMetacat.info("Processing referral (pr3)");
1307
        //casting the context to dircontext and it will create a
1308
        //autherntication or naming exception if DN and password is incorrect
1309
        referralContext = rContext;
1310
        refDirContext = (DirContext) rContext;
1311
        refDirContext.close();
1312
        //get context and jump out the while loop
1313
        moreReferrals = false;
1314
        logMetacat.info("Processing referral (pr4)");
1315
      } //try
1316
      //if referral have another referral excption
1317
      catch (ReferralException re) {
1318
        logMetacat.warn("GOT referral exception (re1): " + re.getMessage());
1319
        logMetacat.warn("RE details (re2): " + re.toString(true));
1320
        //keep running in while loop
1321
        moreReferrals = true;
1322
        //assign refExc to new referral exception re
1323
        refExc = re;
1324
      }
1325
      //catch a authentication exception
1326
      catch (AuthenticationException ae) {
1327
        logMetacat.error("Error running referral handler thread (ae1): " +
1328
                          ae.getMessage());
1329
        //check if has another referral
1330
        moreReferrals = refExc.skipReferral();
1331
        //don't get the context
1332
        referralContext = null;
1333
      }
1334
      //catch a naming exception
1335
      catch (NamingException ne) {
1336
        logMetacat.error("Error running referral handler thread (ne1): " +
1337
                          ne.getMessage());
1338
        //check if has another referral
1339
        moreReferrals = refExc.skipReferral();
1340
        //don't get context
1341
        referralContext = null;
1342
      }
1343
    } //while
1344
  } //run()
1345

    
1346
  private class GetGroup
1347
      implements Runnable {
1348
    public void run() {
1349
      referralContext = null;
1350
      logMetacat.info("getting groups context");
1351
      DirContext refDirContext = null;
1352
      boolean moreReferrals = true;
1353
      //set a while loop is because we don't know if a referral excption
1354
      //contains another referral exception
1355
      while (moreReferrals) {
1356
        try {
1357
          //revise environment variable
1358
          String refInfo = null;
1359
          refInfo = (String) refExc.getReferralInfo();
1360
          if (refInfo != null) {
1361
            logMetacat.info("Referral in thread to: " +
1362
                                     refInfo.toString());
1363
          }
1364
          else {
1365
            logMetacat.info("getting refInfo Manually");
1366
            refInfo = (String) refExc.getReferralContext().getEnvironment().
1367
                get(Context.PROVIDER_URL);
1368
          }
1369
          logMetacat.info("refInfo: " + refInfo);
1370

    
1371
          env.put(Context.INITIAL_CONTEXT_FACTORY,
1372
                  "com.sun.jndi.ldap.LdapCtxFactory");
1373
          env.put(Context.REFERRAL, "throw");
1374
          env.put(Context.PROVIDER_URL, refInfo);
1375

    
1376
          logMetacat.info("creating referralContext");
1377
          referralContext = new InitialDirContext(env);
1378
          logMetacat.info("referralContext created");
1379
          //get context and jump out the while loop
1380
          moreReferrals = false;
1381
        } //try
1382
        catch (ReferralException re) {
1383
          //keep running in while loop
1384
          moreReferrals = true;
1385
          //assign refExc to new referral exception re
1386
          refExc = re;
1387
        }
1388
        catch (AuthenticationException ae) {
1389
          logMetacat.error("Error running referral handler thread (ae2): " +
1390
                            ae.getMessage());
1391
          //check if has another referral
1392
          moreReferrals = refExc.skipReferral();
1393
          //don't get the context
1394
          referralContext = null;
1395
        }
1396
        catch (NamingException ne) {
1397
          logMetacat.error("Error running referral handler thread (ne2): " +
1398
                            ne.getMessage());
1399
          //check if has another referral
1400
          moreReferrals = refExc.skipReferral();
1401
          //don't get context
1402
          referralContext = null;
1403
        }
1404
      } //while
1405
    } //run()
1406
  }
1407
}
(12-12/63)