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
 *
10
 *   '$Author: cjones $'
11
 *     '$Date: 2007-01-25 22:35:19 -0800 (Thu, 25 Jan 2007) $'
12
 * '$Revision: 3157 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.net.ConnectException;
32
import javax.naming.AuthenticationException;
33
import javax.naming.Context;
34
import javax.naming.NamingEnumeration;
35
import javax.naming.NamingException;
36
import javax.naming.SizeLimitExceededException;
37
import javax.naming.directory.InvalidSearchFilterException;
38
import javax.naming.directory.Attribute;
39
import javax.naming.directory.Attributes;
40
import javax.naming.directory.DirContext;
41
import javax.naming.directory.InitialDirContext;
42
import javax.naming.directory.SearchResult;
43
import javax.naming.directory.SearchControls;
44
import javax.naming.ReferralException;
45
import javax.naming.ldap.InitialLdapContext;
46
import javax.naming.ldap.LdapContext;
47
import javax.naming.ldap.StartTlsRequest;
48
import javax.naming.ldap.StartTlsResponse;
49
import javax.net.ssl.SSLSession;
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 implements AuthInterface {
68
  private MetaCatUtil util = new MetaCatUtil();
69
  private String ldapUrl;
70
  private String ldapsUrl;
71
  private String ldapBase;
72
  private String referral;
73
  private String ldapConnectTimeLimit;
74
  private int ldapSearchTimeLimit;
75
  private int ldapSearchCountLimit;
76
  private Context referralContext;
77
  private String currentReferralInfo;
78
  Hashtable env = new Hashtable(11);
79
  private Context rContext;
80
  private String userName;
81
  private String userPassword;
82
  ReferralException refExc;
83

    
84
  private static Logger logMetacat = Logger.getLogger(AuthLdap.class);
85
  
86
  /**
87
   * Construct an AuthLdap
88
   */
89
  public AuthLdap() {
90
    // Read LDAP URI for directory service information
91
    this.ldapUrl = MetaCatUtil.getOption("ldapurl");
92
    this.ldapsUrl = MetaCatUtil.getOption("ldapsurl");
93
    this.ldapBase = MetaCatUtil.getOption("ldapbase");
94
    this.referral = MetaCatUtil.getOption("referral");
95
    this.ldapConnectTimeLimit = 
96
      MetaCatUtil.getOption("ldapconnecttimelimit");
97
    this.ldapSearchTimeLimit = Integer.parseInt(
98
      MetaCatUtil.getOption("ldapsearchtimelimit"));
99
    this.ldapSearchCountLimit = Integer.parseInt(
100
      MetaCatUtil.getOption("ldapsearchcountlimit"));
101
    
102
    // Store referral info for use in building group DNs in getGroups() 
103
    this.currentReferralInfo = "";
104
  }
105

    
106
  /**
107
   * Determine if a user/password are valid according to the authentication
108
   * service.
109
   *
110
   * @param user the name of the principal to authenticate
111
   * @param password the password to use for authentication
112
   * @returns boolean true if authentication successful, false otherwise
113
   */
114
  
115
  public boolean authenticate(String user, String password) throws 
116
    ConnectException {
117
    String ldapUrl = this.ldapUrl;
118
    String ldapsUrl = this.ldapsUrl;
119
    String ldapBase = this.ldapBase;
120
    boolean authenticated = false;
121
    String identifier = user;
122
    
123
    //get uid here.
124
    String uid=user.substring(0, user.indexOf(","));
125
    user = user.substring(user.indexOf(","), user.length());
126

    
127
    logMetacat.debug("identifier: " + identifier);
128
    logMetacat.debug("uid: " + uid);
129
    logMetacat.debug("user: " + user);
130
    
131
    try {
132
    	// Check the usename as passed in
133
        logMetacat.info("Calling ldapAuthenticate");
134
        logMetacat.info("with user as identifier: " + identifier);
135

    
136
        authenticated = ldapAuthenticate(identifier, password, 
137
        		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
138
        // if not found, try looking up a valid DN then auth again
139
        if (!authenticated) {
140
        	logMetacat.info("Not Authenticated");
141
        	logMetacat.info("Looking up DN for: " + identifier);
142
        	identifier = getIdentifyingName(identifier, ldapUrl, ldapBase);
143
        	if(identifier == null){
144
        		logMetacat.info("No DN found from getIdentifyingName");
145
        		return authenticated;
146
        	}
147
        	
148
           	logMetacat.info("DN found from getIdentifyingName: " + identifier);
149
        	String decoded = URLDecoder.decode(identifier);
150
        	logMetacat.info("DN decoded: " + decoded);
151
        	identifier = decoded;
152
        	String refUrl = "";
153
        	String refBase = "";
154
        	if (identifier.startsWith("ldap")) {
155
        		logMetacat.debug("identifier starts with \"ldap\"");
156

    
157
        		refUrl = identifier.substring(0, identifier.lastIndexOf("/") + 1);
158
        		int position = identifier.indexOf(",");
159
        		int position2 = identifier.indexOf(",", position + 1);
160
        		
161
        		refBase = identifier.substring(position2 + 1);
162
        		identifier = identifier.substring(identifier.lastIndexOf("/") + 1);
163
        		
164
        		logMetacat.info("Calling ldapAuthenticate:");
165
        		logMetacat.info("with user as identifier: " + identifier);
166
        		logMetacat.info("and refUrl as: " + refUrl);
167
        		logMetacat.info("and refBase as: " + refBase);
168

    
169
        		authenticated = ldapAuthenticate(identifier, password, refUrl, refBase,
170
                		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPReferalsConnection")))
171
                			.booleanValue());
172
        	} else {
173
        		logMetacat.info("identifier doesnt start with ldap");
174
        		identifier = identifier + "," + ldapBase;
175
        		
176
        		logMetacat.info("Calling ldapAuthenticate");
177
        		logMetacat.info("with user as identifier: " + identifier);
178
        		
179
        		authenticated = ldapAuthenticate(identifier, password,
180
            		(new Boolean(MetaCatUtil.getOption("onlySecureLDAPConnection"))).booleanValue());
181
        	}
182
        }
183
    } catch (NullPointerException e) {
184
    	logMetacat.error("NullPointerException while authenticating in " +
185
                        "AuthLdap.authenticate: " + e);
186
    	e.printStackTrace();
187

    
188
    	throw new ConnectException(
189
          "NullPointerException while authenticating in " +
190
          "AuthLdap.authenticate: " + e);
191
    } catch (NamingException e) {
192
    	logMetacat.error("Naming exception while authenticating in " +
193
                        "AuthLdap.authenticate: " + e);
194
    	e.printStackTrace();
195
    } catch (Exception e) {
196
    	logMetacat.error(e.getMessage());
197
    }
198
    
199
    return authenticated;
200
  }
201

    
202
  /**
203
   * Connect to the LDAP directory and do the authentication using the
204
   * username and password as passed into the routine.
205
   *
206
   * @param identifier the distinguished name to check against LDAP
207
   * @param password the password for authentication
208
   */
209
  private boolean ldapAuthenticate(String identifier, String password, boolean 
210
    secureConnectionOnly) throws ConnectException, NamingException, 
211
    NullPointerException {
212
    return ldapAuthenticate(identifier, password,
213
                            this.ldapsUrl, this.ldapBase, secureConnectionOnly);
214
  }
215

    
216
  /**
217
   * Connect to the LDAP directory and do the authentication using the
218
   * username and password as passed into the routine.
219
   *
220
   * @param identifier the distinguished name to check against LDAP
221
   * @param password the password for authentication
222
   */
223
  
224
  private boolean ldapAuthenticate(String dn, String password, 
225
    String rootServer, String rootBase, boolean secureConnectionOnly){
226
	  
227
	  boolean authenticated = false;
228
		
229
	  String server = "";
230
	  String userDN = "";
231
	  logMetacat.info("dn is: " + dn);
232

    
233
	  int position = dn.lastIndexOf("/");
234
      logMetacat.debug("position is: " + position);
235
	  if (position == -1) {
236
		  server = rootServer;
237
		  if(dn.indexOf(userDN) < 0){
238
			  userDN = dn + "," + rootBase;
239
		  } else {
240
			  userDN = dn;
241
		  }
242
		  logMetacat.info("userDN is: " + userDN);
243

    
244
       } else {
245
		  server = dn.substring(0, position+1);
246
		  userDN = dn.substring(position+1);
247
		  logMetacat.info("server is: " + server);
248
		  logMetacat.info("userDN is: " + userDN);
249
	   }
250
		          
251
	   logMetacat.warn("Trying to authenticate: " + userDN);
252
	   logMetacat.warn("          Using server: " + server);
253
		          
254
	   LdapContext ctx = null;
255
	   double startTime;
256
	   double stopTime;
257
	   try {
258
		   Hashtable env = new Hashtable();
259
		   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
260
		   env.put(Context.PROVIDER_URL, server);
261
		   env.put(Context.REFERRAL, "throw");
262

    
263
		   try {
264
			   
265
			   startTime = System.currentTimeMillis();
266
			   ctx = new InitialLdapContext(env, null);
267
			   
268
			   // Start up TLS here so that we don't pass our jewels in cleartext
269
		       StartTlsResponse tls =
270
		              (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
271
		       //tls.setHostnameVerifier(new SampleVerifier());
272
		       SSLSession sess = tls.negotiate();
273
			   
274
		       ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
275
			   ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
276
			   ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
277
			   ctx.reconnect(null);
278
			   
279
			   stopTime = System.currentTimeMillis();
280
			   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
281
                       	(stopTime - startTime) / 1000 + " seconds.");
282
			   
283
			   authenticated = true;
284
		   } catch (java.io.IOException ioe) {
285
			   logMetacat.warn("Caught IOException in login while negotiating TLS: "
286
	                                 + ioe.getMessage());
287
			   
288
			   if(secureConnectionOnly){
289
			   	  
290
				   return authenticated;
291
			   
292
			   } else {
293

    
294
				   logMetacat.info("Trying to authenticate without TLS");
295
				   env.put(Context.SECURITY_AUTHENTICATION, "simple");
296
				   env.put(Context.SECURITY_PRINCIPAL, userDN);
297
				   env.put(Context.SECURITY_CREDENTIALS, password);
298
				   
299
				   startTime = System.currentTimeMillis();
300
				   ctx = new InitialLdapContext(env, null);				
301
				   stopTime = System.currentTimeMillis();
302
				   logMetacat.info("Connection time thru " + ldapsUrl + " was: " +
303
	                       	(stopTime - startTime) / 1000 + " seconds.");
304
				   
305
				   authenticated = true;
306
			   }
307
		   }
308
	   } catch (AuthenticationException ae) {
309
		   authenticated = false;
310
	   } catch (javax.naming.InvalidNameException ine) {
311
	        logMetacat.error("An invalid DN was provided!");
312
	   } catch (NamingException e) {
313
		   logMetacat.warn("Caught NamingException in login: " + e.getClass().getName());
314
		   logMetacat.info(e.toString() + "  " + e.getRootCause());
315
       }
316

    
317
       return authenticated;
318
  }
319

    
320

    
321
  /**
322
   * Get the identifying name for a given userid or name.  This is the name
323
   * that is used in conjunction withthe LDAP BaseDN to create a
324
   * distinguished name (dn) for the record
325
   *
326
   * @param user the user for which the identifying name is requested
327
   * @returns String the identifying name for the user,
328
   *          or null if not found
329
   */
330
  private String getIdentifyingName(String user, String ldapUrl, 
331
    String ldapBase) throws NamingException {
332
	  
333
      String identifier = null;
334
      Hashtable env = new Hashtable();
335
      env.put(Context.INITIAL_CONTEXT_FACTORY,
336
              "com.sun.jndi.ldap.LdapCtxFactory");
337
      env.put(Context.REFERRAL, "throw");
338
      env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
339
      try {
340
    	  int position = user.indexOf(",");
341
          String uid = user.substring(user.indexOf("=") + 1, position);
342
          logMetacat.info("uid is: " + uid);
343
          String org = user.substring(user.indexOf("=", position + 1) + 1,
344
                                        user.indexOf(",", position + 1));
345
          logMetacat.info("org is: " + org);
346
           
347
          DirContext sctx = new InitialDirContext(env);
348
          SearchControls ctls = new SearchControls();
349
          ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
350
          String filter = "(&(uid=" + uid + ")(o=" + org + "))";
351
          logMetacat.warn("Searching for DNs with following filter: " + filter);
352
          
353
          for (boolean moreReferrals = true; moreReferrals;) {
354
              try {
355
                  // Perform the search
356
                  NamingEnumeration answer = 
357
                      sctx.search("", filter, ctls);
358

    
359
                  // Return the answer
360
                  while (answer.hasMore()) {
361
                      SearchResult sr = (SearchResult)answer.next();
362
                      identifier = sr.getName();
363
                      return identifier;
364
                  }
365
                  // The search completes with no more referrals
366
                  moreReferrals = false;
367
              } catch (ReferralException e) {
368
            	  logMetacat.info("Got referral: " + e.getReferralInfo());
369
            	  // Point to the new context from the referral
370
                  if (moreReferrals) {
371
                      sctx = (DirContext) e.getReferralContext();
372
                  }
373
              }
374
          }
375
      } catch (NamingException e) {
376
    	     logMetacat.error("Naming exception while getting dn: " + e);
377
    	      throw new NamingException(
378
    	          "Naming exception in AuthLdap.getIdentifyingName: " + e);
379
    	      }
380
      return identifier;
381
  }
382
  
383
  /**
384
   * Get all users from the authentication service
385
   *
386
   * @param user the user for authenticating against the service
387
   * @param password the password for authenticating against the service
388
   * @returns string array of all of the user names
389
   */
390
  public String[][] getUsers(String user, String password) throws 
391
    ConnectException {
392
    String[][] users = null;
393

    
394
    // Identify service provider to use
395
    Hashtable env = new Hashtable(11);
396
    env.put(Context.INITIAL_CONTEXT_FACTORY,
397
            "com.sun.jndi.ldap.LdapCtxFactory");
398
    env.put(Context.REFERRAL, referral);
399
    env.put(Context.PROVIDER_URL, ldapUrl);
400

    
401
    try {
402

    
403
      // Create the initial directory context
404
      DirContext ctx = new InitialDirContext(env);
405

    
406
      // Specify the attributes to match.
407
      // Users are objects that have the attribute objectclass=InetOrgPerson.
408
      SearchControls ctls = new SearchControls();
409
      String[] attrIDs = {
410
          "dn", "cn", "o", "ou", "mail"};
411
      ctls.setReturningAttributes(attrIDs);
412
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
413
      //ctls.setCountLimit(1000);
414
      String filter = "(objectClass=inetOrgPerson)";
415
      NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
416

    
417
      // Store the users in a vector
418
      Vector uvec = new Vector();
419
      Vector uname = new Vector();
420
      Vector uorg = new Vector();
421
      Vector uou = new Vector();
422
      Vector umail = new Vector();
423
      Attributes tempAttr = null;
424
      try {
425
        while (namingEnum.hasMore()) {
426
          SearchResult sr = (SearchResult) namingEnum.next();
427
          tempAttr = sr.getAttributes();
428

    
429
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
430
            uname.add( (tempAttr.get("cn") + "").substring(4));
431
          }
432
          else {
433
            uname.add(tempAttr.get("cn") + "");
434
          }
435

    
436
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
437
            uorg.add( (tempAttr.get("o") + "").substring(3));
438
          }
439
          else {
440
            uorg.add(tempAttr.get("o") + "");
441
          }
442

    
443
          if ( (tempAttr.get("ou") + "").startsWith("ou: ")) {
444
            uou.add( (tempAttr.get("ou") + "").substring(4));
445
          }
446
          else {
447
            uou.add(tempAttr.get("ou") + "");
448
          }
449

    
450
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
451
            umail.add( (tempAttr.get("mail") + "").substring(6));
452
          }
453
          else {
454
            umail.add(tempAttr.get("mail") + "");
455
          }
456

    
457
          uvec.add(sr.getName() + "," + ldapBase);
458
        }
459
      }
460
      catch (SizeLimitExceededException slee) {
461
        logMetacat.error("LDAP Server size limit exceeded. " +
462
                          "Returning incomplete record set.");
463
      }
464

    
465
      // initialize users[]; fill users[]
466
      users = new String[uvec.size()][5];
467
      for (int i = 0; i < uvec.size(); i++) {
468
        users[i][0] = (String) uvec.elementAt(i);
469
        users[i][1] = (String) uname.elementAt(i);
470
        users[i][2] = (String) uorg.elementAt(i);
471
        users[i][3] = (String) uorg.elementAt(i);
472
        users[i][4] = (String) umail.elementAt(i);
473
      }
474

    
475
      // Close the context when we're done
476
      ctx.close();
477

    
478
    }
479
    catch (NamingException e) {
480
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
481
      //e.printStackTrace(System.err);
482
      throw new ConnectException(
483
          "Problem getting users in AuthLdap.getUsers:" + e);
484
    }
485

    
486
    return users;
487
  }
488

    
489
  
490
  /**
491
   * Get all users from the authentication service
492
   *
493
   * @param user the user for authenticating against the service
494
   * @param password the password for authenticating against the service
495
   * @returns string array of all of the user names
496
   */
497
  public String[] getUserInfo(String user, String password) throws 
498
    ConnectException {
499
    String[] userinfo = new String[3];
500

    
501
    // Identify service provider to use
502
    Hashtable env = new Hashtable(11);
503
    env.put(Context.INITIAL_CONTEXT_FACTORY,
504
            "com.sun.jndi.ldap.LdapCtxFactory");
505
    env.put(Context.REFERRAL, referral);
506
    env.put(Context.PROVIDER_URL, ldapUrl);
507

    
508
    try {
509
      
510
      // Create the initial directory context
511
      DirContext ctx = new InitialDirContext(env);
512
      // Specify the attributes to match.
513
      // Users are objects that have the attribute objectclass=InetOrgPerson.
514
      SearchControls ctls = new SearchControls();
515
      String[] attrIDs = {
516
          "cn", "o", "mail"};
517
      ctls.setReturningAttributes(attrIDs);
518
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
519
      //ctls.setCountLimit(1000);
520
      // create the filter based on the uid
521
      
522
      String filter = null;
523
      
524
      if(user.indexOf("o=")>0){
525
    	  String tempStr = user.substring(user.indexOf("o="));
526
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
527
			+ ")(" + tempStr.substring(0, tempStr.indexOf(",")) 
528
			+ "))";      
529
      } else{
530
    	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
531
			+ "))";          		  
532
      }
533
   	  filter = "(&(" + user.substring(0, user.indexOf(",")) 
534
		+ "))";          		  
535

    
536
      NamingEnumeration namingEnum = ctx.search(user, filter, ctls);
537
      
538
      Attributes tempAttr = null;
539
      try {
540
        while (namingEnum.hasMore()) {
541
          SearchResult sr = (SearchResult) namingEnum.next();
542
          tempAttr = sr.getAttributes();
543

    
544
          if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
545
        	  userinfo[0] = (tempAttr.get("cn") + "").substring(4);
546
          }
547
          else {
548
        	  userinfo[0] = (tempAttr.get("cn") + "");
549
          }
550

    
551
          if ( (tempAttr.get("o") + "").startsWith("o: ")) {
552
        	  userinfo[1] = (tempAttr.get("o") + "").substring(3);
553
          }
554
          else {
555
        	  userinfo[1] = (tempAttr.get("o") + "");
556
          }
557

    
558
          if ( (tempAttr.get("mail") + "").startsWith("mail: ")) {
559
        	  userinfo[2] =  (tempAttr.get("mail") + "").substring(6);
560
          }
561
          else {
562
        	  userinfo[2] = (tempAttr.get("mail") + "");
563
          }
564
        }
565
      }
566
      catch (SizeLimitExceededException slee) {
567
        logMetacat.error("LDAP Server size limit exceeded. " +
568
                          "Returning incomplete record set.");
569
      }
570

    
571
      // Close the context when we're done
572
      ctx.close();
573

    
574
    }
575
    catch (NamingException e) {
576
      logMetacat.error("Problem getting users in AuthLdap.getUsers:" + e);
577
      //e.printStackTrace(System.err);
578
      throw new ConnectException(
579
          "Problem getting users in AuthLdap.getUsers:" + e);
580
    }
581

    
582
    return userinfo;
583
  }
584

    
585
  /**
586
   * Get the users for a particular group from the authentication service
587
   *
588
   * @param user the user for authenticating against the service
589
   * @param password the password for authenticating against the service
590
   * @param group the group whose user list should be returned
591
   * @returns string array of the user names belonging to the group
592
   */
593
  public String[] getUsers(String user, String password, String group) throws 
594
    ConnectException {
595
    String[] users = null;
596

    
597
    // Identify service provider to use
598
    Hashtable env = new Hashtable(11);
599
    env.put(Context.INITIAL_CONTEXT_FACTORY,
600
            "com.sun.jndi.ldap.LdapCtxFactory");
601
    env.put(Context.REFERRAL, referral);
602
    env.put(Context.PROVIDER_URL, ldapUrl);
603

    
604
    try {
605

    
606
      // Create the initial directory context
607
      DirContext ctx = new InitialDirContext(env);
608

    
609
      // Specify the ids of the attributes to return
610
      String[] attrIDs = {
611
          "uniqueMember"};
612

    
613
      Attributes answer = ctx.getAttributes(group, attrIDs);
614

    
615
      Vector uvec = new Vector();
616
      try {
617
        for (NamingEnumeration ae = answer.getAll(); ae.hasMore(); ) {
618
          Attribute attr = (Attribute) ae.next();
619
          for (NamingEnumeration e = attr.getAll();
620
               e.hasMore();
621
               uvec.add(e.next())
622
               ) {
623
            ;
624
          }
625
        }
626
      }
627
      catch (SizeLimitExceededException slee) {
628
        logMetacat.error("LDAP Server size limit exceeded. " +
629
                          "Returning incomplete record set.");
630
      }
631

    
632
      // initialize users[]; fill users[]
633
      users = new String[uvec.size()];
634
      for (int i = 0; i < uvec.size(); i++) {
635
        users[i] = (String) uvec.elementAt(i);
636
      }
637

    
638
      // Close the context when we're done
639
      ctx.close();
640

    
641
    }
642
    catch (NamingException e) {
643
      logMetacat.error("Problem getting users for a group in " +
644
                        "AuthLdap.getUsers:" + e);
645
      throw new ConnectException(
646
          "Problem getting users for a group in AuthLdap.getUsers:" + e);
647
    }
648

    
649
    return users;
650
  }
651

    
652
  /**
653
   * Get all groups from the authentication service
654
   *
655
   * @param user the user for authenticating against the service
656
   * @param password the password for authenticating against the service
657
   * @returns string array of the group names
658
   */
659
  public String[][] getGroups(String user, String password) throws 
660
    ConnectException {
661
    return getGroups(user, password, null);
662
  }
663

    
664
  /**
665
   * Get the groups for a particular user from the authentication service
666
   *
667
   * @param user the user for authenticating against the service
668
   * @param password the password for authenticating against the service
669
   * @param foruser the user whose group list should be returned
670
   * @returns string array of the group names
671
   */
672
  public String[][] getGroups(String user, String password, 
673
    String foruser) throws ConnectException {
674
    
675
    logMetacat.debug("getGroups() called.");
676
    
677
    // create vectors to store group and dscription values returned from the
678
    // ldap servers
679
    Vector gvec = new Vector();
680
    Vector desc = new Vector();
681
    Attributes tempAttr = null;
682
    Attributes rsrAttr = null;
683
    
684
    // DURING getGroups(), DO WE NOT BIND USING userName AND userPassword??
685
    // NEED TO FIX THIS ...
686
    userName = user;
687
    userPassword = password;
688
    // Identify service provider to use
689
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
690
    env.put(Context.REFERRAL, "throw");
691
    env.put(Context.PROVIDER_URL, ldapUrl);
692
    env.put("com.sun.jndi.ldap.connect.timeout", ldapConnectTimeLimit);
693
    
694
        
695
    // Iterate through the referrals, handling NamingExceptions in the 
696
    // outer catch statement, ReferralExceptions in the inner catch statement
697
    try { // outer try
698
       
699
      // Create the initial directory context
700
      DirContext ctx = new InitialDirContext(env);
701
      
702
      // Specify the attributes to match.
703
      // Groups are objects with attribute objectclass=groupofuniquenames.
704
      // and have attribute uniquemember: uid=foruser,ldapbase.
705
      SearchControls ctls = new SearchControls();
706
      // Specify the ids of the attributes to return
707
      String[] attrIDs = {"cn", "o", "description"};
708
      ctls.setReturningAttributes(attrIDs);
709
      // set the ldap search scope
710
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
711
      // set a 10 second time limit on searches to limit non-responding servers
712
      ctls.setTimeLimit(ldapSearchTimeLimit);
713
      // return at most 20000 entries
714
      ctls.setCountLimit(ldapSearchCountLimit);
715

    
716
      // build the ldap search filter that represents the "group" concept
717
      String filter = null;
718
      String gfilter = "(objectClass=groupOfUniqueNames)";
719
      if (null == foruser) {
720
        filter = gfilter;
721
      } else {
722
        filter = "(& " + gfilter + "(uniqueMember=" + foruser + "))";
723
      }
724
      logMetacat.info("group filter is: " + filter);
725
      
726
      // now, search and iterate through the referrals
727
      for (boolean moreReferrals = true; moreReferrals;) {  
728
        try { // inner try
729
      
730
          NamingEnumeration namingEnum = ctx.search(ldapBase, filter, ctls);
731

    
732
          // Print the groups
733
          while (namingEnum.hasMore()) {
734
            SearchResult sr = (SearchResult) namingEnum.next();
735
            
736
            tempAttr = sr.getAttributes();
737

    
738
            if ( (tempAttr.get("description") + "").startsWith("description: ")) {
739
              desc.add( (tempAttr.get("description") + "").substring(13));
740
            }
741
            else {
742
              desc.add(tempAttr.get("description") + "");
743
            }
744
            
745
            // check for an absolute URL value or an answer value relative 
746
            // to the target context  
747
            if ( !sr.getName().startsWith("ldap") &&
748
                  sr.isRelative()) {
749
              logMetacat.debug("Search result entry is relative ...");
750
              gvec.add(sr.getName() + "," + ldapBase);
751
              logMetacat.info("group " + sr.getName() + "," +ldapBase + 
752
              " added to the group vector"); 
753
            } else {
754
              logMetacat.debug("Search result entry is absolute ...");
755
              
756
              // search the top level directory for referral objects and match
757
              // that of the search result's absolute URL.  This will let us
758
              // rebuild the group name from the search result, referral point
759
              // in the top directory tree, and ldapBase.
760
              
761
              // configure a new directory search first
762
              Hashtable envHash = new Hashtable(11);
763
              // Identify service provider to use
764
              envHash.put(Context.INITIAL_CONTEXT_FACTORY, 
765
                "com.sun.jndi.ldap.LdapCtxFactory");
766
              envHash.put(Context.REFERRAL, "ignore");
767
              envHash.put(Context.PROVIDER_URL, ldapUrl);
768
              envHash.put("com.sun.jndi.ldap.connect.timeout", 
769
                ldapConnectTimeLimit);
770
              
771
              try {
772
                // Create the initial directory context
773
                DirContext DirCtx = new InitialDirContext(envHash);
774

    
775
                SearchControls searchCtls = new SearchControls();
776
                // Specify the ids of the attributes to return
777
                String[] attrNames = {"o"};
778
                searchCtls.setReturningAttributes(attrNames);
779
                // set the ldap search scope - only look for top level referrals
780
                searchCtls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
781
                // set a time limit on searches to limit non-responding servers
782
                searchCtls.setTimeLimit(ldapSearchTimeLimit);
783
                // return the configured number of entries
784
                searchCtls.setCountLimit(ldapSearchCountLimit);
785
                
786
                // Specify the attributes to match.
787
                // build the ldap search filter to match referral entries that 
788
                // match the search result
789
                String rFilter = "(&(objectClass=referral)(ref=" + 
790
                currentReferralInfo.substring(0, 
791
                currentReferralInfo.indexOf("?")) + "))";
792
                logMetacat.debug("rFilter is: " + rFilter);
793
                
794
                NamingEnumeration rNamingEnum = 
795
                  DirCtx.search(ldapBase, rFilter, searchCtls);
796
                  
797
                while (rNamingEnum.hasMore()) {
798
                  SearchResult rsr = (SearchResult) rNamingEnum.next();
799
                  rsrAttr = rsr.getAttributes();
800
                  logMetacat.debug("referral search result is: " +
801
                    rsr.toString());
802
                    
803
                  // add the returned groups to the group vector.  Test the 
804
                  // syntax of the returned attributes - sometimes they are 
805
                  // preceded with the attribute id and a colon
806
                  if ( (tempAttr.get("cn") + "").startsWith("cn: ")) {
807
                    gvec.add( "cn=" + (tempAttr.get("cn") + "").substring(4) + 
808
                    "," + "o=" + (rsrAttr.get("o") + "").substring(3 ) + "," + 
809
                    ldapBase);
810
                    logMetacat.info("group " + 
811
                    (tempAttr.get("cn") + "").substring(4) + "," + 
812
                    "o=" + (rsrAttr.get("o") + "").substring(3) + "," + 
813
                    ldapBase + " added to the group vector");
814
                  } else {
815
                    gvec.add( "cn=" + tempAttr.get("cn") + "," + 
816
                    "o=" + rsrAttr.get("o") +
817
                    "," + ldapBase);
818
                    logMetacat.info("group " + 
819
                    "cn=" + tempAttr.get("cn") + "," + 
820
                    "o=" + rsrAttr.get("o") + "," + 
821
                    ldapBase + " added to the group vector");
822
                  }  
823
                }
824
                
825
              } catch (NamingException nameEx){
826
                logMetacat.debug("Caught naming exception: ");
827
                nameEx.printStackTrace(System.err);
828
              }
829
            }
830
          }// end while
831
          
832
          moreReferrals = false;
833
          
834
        } catch (ReferralException re) {
835
          
836
          logMetacat.info(
837
            "In AuthLdap.getGroups(), caught referral exception: " +
838
            re.getReferralInfo()
839
          );
840
          this.currentReferralInfo = (String) re.getReferralInfo();
841
          
842
          // set moreReferrals to true and set the referral context
843
          moreReferrals = true;
844
          ctx = (DirContext) re.getReferralContext();
845
           
846
        }// end inner try
847
      }// end for
848
      
849
      // close the context now that all initial and referral 
850
      // searches are processed
851
      ctx.close();
852
      
853
    } catch (NamingException e) {
854
      
855
      // naming exceptions get logged, groups are returned
856
      logMetacat.info("In AuthLdap.getGroups(), caught naming exception: ");
857
      e.printStackTrace(System.err);
858
      
859
    } finally {
860
      // once all referrals are followed, report and return the groups found
861
      logMetacat.warn("The user is in the following groups: " +
862
                               gvec.toString());
863
      //build and return the groups array
864
      String groups[][] = new String[gvec.size()][2];
865
      for (int i = 0; i < gvec.size(); i++) {
866
        groups[i][0] = (String) gvec.elementAt(i);
867
        groups[i][1] = (String) desc.elementAt(i);
868
      }
869
      return groups;
870
    }// end outer try
871
  }
872

    
873
  /**
874
   * Get attributes describing a user or group
875
   *
876
   * @param foruser the user for which the attribute list is requested
877
   * @returns HashMap a map of attribute name to a Vector of values
878
   */
879
  public HashMap getAttributes(String foruser) throws ConnectException {
880
    return getAttributes(null, null, foruser);
881
  }
882

    
883
  /**
884
   * Get attributes describing a user or group
885
   *
886
   * @param user the user for authenticating against the service
887
   * @param password the password for authenticating against the service
888
   * @param foruser the user whose attributes should be returned
889
   * @returns HashMap a map of attribute name to a Vector of values
890
   */
891
  public HashMap getAttributes(String user, String password, 
892
    String foruser) throws ConnectException {
893
    HashMap attributes = new HashMap();
894
    String ldapUrl = this.ldapUrl;
895
    String ldapBase = this.ldapBase;
896
    String userident = foruser;
897

    
898
    // Identify service provider to use
899
    Hashtable env = new Hashtable(11);
900
    env.put(Context.INITIAL_CONTEXT_FACTORY,
901
            "com.sun.jndi.ldap.LdapCtxFactory");
902
    env.put(Context.REFERRAL, referral);
903
    env.put(Context.PROVIDER_URL, ldapUrl);
904

    
905
    try {
906

    
907
      // Create the initial directory context
908
      DirContext ctx = new InitialDirContext(env);
909

    
910
      // Ask for all attributes of the user
911
      //Attributes attrs = ctx.getAttributes(userident);
912
      Attributes attrs = ctx.getAttributes(foruser);
913

    
914
      // Print all of the attributes
915
      NamingEnumeration en = attrs.getAll();
916
      while (en.hasMore()) {
917
        Attribute att = (Attribute) en.next();
918
        Vector values = new Vector();
919
        String attName = att.getID();
920
        NamingEnumeration attvalues = att.getAll();
921
        while (attvalues.hasMore()) {
922
          String value = (String) attvalues.next();
923
          values.add(value);
924
        }
925
        attributes.put(attName, values);
926
      }
927

    
928
      // Close the context when we're done
929
      ctx.close();
930
    }
931
    catch (NamingException e) {
932
      logMetacat.error("Problem getting attributes in " +
933
                        "AuthLdap.getAttributes:" + e);
934
      throw new ConnectException(
935
          "Problem getting attributes in AuthLdap.getAttributes:" + e);
936
    }
937

    
938
    return attributes;
939
  }
940

    
941
  /**
942
   * Get list of all subtrees holding Metacat's groups and users
943
   * starting from the Metacat LDAP root,
944
   * i.e. ldap://dev.nceas.ucsb.edu/dc=ecoinformatics,dc=org
945
   */
946
  private Hashtable getSubtrees(String user, String password, 
947
    String ldapUrl, String ldapBase) throws ConnectException {
948
    Hashtable trees = new Hashtable();
949

    
950
    // Identify service provider to use
951
    Hashtable env = new Hashtable(11);
952
    env.put(Context.INITIAL_CONTEXT_FACTORY,
953
            "com.sun.jndi.ldap.LdapCtxFactory");
954
    // env.put(Context.REFERRAL, referral);
955
    // Using 'ignore' here instead of 'follow' as 'ignore' seems
956
    // to do the job better. 'follow' was not bringing up the UCNRS
957
    // and PISCO tree whereas 'ignore' brings up the tree.
958

    
959
    env.put(Context.REFERRAL, "ignore");
960
    env.put(Context.PROVIDER_URL, ldapUrl + ldapBase);
961

    
962
    try {
963

    
964
      // Create the initial directory context
965
      DirContext ctx = new InitialDirContext(env);
966

    
967
      // Specify the ids of the attributes to return
968
      String[] attrIDs = {
969
          "o", "ref"};
970
      SearchControls ctls = new SearchControls();
971
      ctls.setReturningAttributes(attrIDs);
972
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
973

    
974
      // Specify the attributes to match.
975
      // Subtrees from the main server are found as objects with attribute
976
      // objectclass=organization or objectclass=referral to the subtree
977
      // resided on other server.
978
      String filter = "(|(objectclass=organization)(objectclass=referral))";
979

    
980
      // Search for objects in the current context
981
      NamingEnumeration namingEnum = ctx.search("", filter, ctls);
982

    
983
      // Print the subtrees' <ldapURL, baseDN>
984
      while (namingEnum.hasMore()) {
985

    
986
        SearchResult sr = (SearchResult) namingEnum.next();
987

    
988
        Attributes attrs = sr.getAttributes();
989
        NamingEnumeration enum1 = attrs.getAll(); // "dc" and "ref" attrs
990

    
991
        if (enum1.hasMore()) {
992
          Attribute attr = (Attribute) enum1.next();
993
          String attrValue = (String) attr.get();
994
          String attrName = (String) attr.getID();
995

    
996
          if (enum1.hasMore()) {
997
            attr = (Attribute) enum1.next();
998
            String refValue = (String) attr.get();
999
            String refName = (String) attr.getID();
1000
            if (ldapBase.startsWith(refName + "=" + refValue)) {
1001
              trees.put(ldapBase,
1002
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1003
            }
1004
            else {
1005
              // this is a referral - so organization name is appended in
1006
              // front of the ldapbase.... later it is stripped out
1007
              // in getPrincipals
1008
              trees.put("[" + refName + "=" + refValue + "]" +
1009
                        attrValue.substring(attrValue.lastIndexOf("/") + 1,
1010
                                            attrValue.length()),
1011
                        attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1012

    
1013
              // trees.put(refName + "=" + refValue + "," + ldapBase,
1014
              //           attrValue.substring(0, attrValue.lastIndexOf("/") + 1));
1015
            }
1016

    
1017
          }
1018
          else if (ldapBase.startsWith(attrName + "=" + attrValue)) {
1019
            trees.put(ldapBase, ldapUrl);
1020
          }
1021
          else {
1022
            if (sr.isRelative()) {
1023
              trees.put(attrName + "=" + attrValue + "," + ldapBase, ldapUrl);
1024
            }
1025
            else {
1026
              String referenceURL = sr.getName();
1027
              referenceURL = referenceURL.substring(0,
1028
                  referenceURL.lastIndexOf("/") + 1);
1029
              trees.put(attrName + "=" + attrValue + "," + ldapBase,
1030
                        referenceURL);
1031
            }
1032

    
1033
          }
1034
        }
1035
      }
1036

    
1037
      // Close the context when we're done
1038
      ctx.close();
1039

    
1040
    }
1041
    catch (NamingException e) {
1042
      logMetacat.error("Problem getting subtrees in AuthLdap.getSubtrees:"
1043
                        + e);
1044
      throw new ConnectException(
1045
          "Problem getting subtrees in AuthLdap.getSubtrees:" + e);
1046
    }
1047

    
1048
    return trees;
1049
  }
1050

    
1051
  /**
1052
   * Get all groups and users from authentication scheme.
1053
   * The output is formatted in XML.
1054
   * @param user the user which requests the information
1055
   * @param password the user's password
1056
   */
1057
  public String getPrincipals(String user, String password) throws 
1058
    ConnectException {
1059
    StringBuffer out = new StringBuffer();
1060
   
1061
    out.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
1062
    out.append("<principals>\n");
1063

    
1064
    /*
1065
     * get all subtrees first in the current dir context
1066
     * and then the Metacat users under them
1067
     */
1068
    Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
1069
                                     this.ldapBase);
1070

    
1071
    Enumeration keyEnum = subtrees.keys();
1072
    while (keyEnum.hasMoreElements()) {
1073
      this.ldapBase = (String) keyEnum.nextElement();
1074
      this.ldapUrl = (String) subtrees.get(ldapBase);
1075

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

    
1105
      out.append("  <authSystem URI=\"" +
1106
                 this.ldapUrl + this.ldapBase + "\" organization=\"" + orgName +
1107
                 "\">\n");
1108

    
1109
      // get all groups for directory context
1110
      String[][] groups = getGroups(user, password);
1111
      String[][] users = getUsers(user, password);
1112
      int userIndex = 0;
1113

    
1114
      // for the groups and users that belong to them
1115
      if (groups != null && groups.length > 0) {
1116
        for (int i = 0; i < groups.length; i++) {
1117
          out.append("    <group>\n");
1118
          out.append("      <groupname>" + groups[i][0] + "</groupname>\n");
1119
          out.append("      <description>" + groups[i][1] + "</description>\n");
1120
          String[] usersForGroup = getUsers(user, password, groups[i][0]);
1121
          for (int j = 0; j < usersForGroup.length; j++) {
1122
            
1123
            userIndex = searchUser(usersForGroup[j], users);
1124
            out.append("      <user>\n");
1125

    
1126
            if (userIndex < 0) {
1127
              out.append("        <username>" + usersForGroup[j] +
1128
                         "</username>\n");
1129
            }
1130
            else {
1131
              out.append("        <username>" + users[userIndex][0] +
1132
                         "</username>\n");
1133
              out.append("        <name>" + users[userIndex][1] + "</name>\n");
1134
              out.append("        <organization>" + users[userIndex][2] +
1135
                         "</organization>\n");
1136
              if (users[userIndex][3].compareTo("null") != 0) {
1137
                out.append("      <organizationUnitName>" + users[userIndex][3] +
1138
                           "</organizationUnitName>\n");
1139
              }
1140
              out.append("        <email>" + users[userIndex][4] + "</email>\n");
1141
            }
1142

    
1143
            out.append("      </user>\n");
1144
          }
1145
          out.append("    </group>\n");
1146
        }
1147
      }
1148

    
1149
      // for the users not belonging to any grou8p
1150
      for (int j = 0; j < users.length; j++) {
1151
          out.append("    <user>\n");
1152
          out.append("      <username>" + users[j][0] + "</username>\n");
1153
          out.append("      <name>" + users[j][1] + "</name>\n");
1154
          out.append("      <organization>" + users[j][2] +
1155
                     "</organization>\n");
1156
          if (users[j][3].compareTo("null") != 0) {
1157
            out.append("      <organizationUnitName>" + users[j][3] +
1158
                       "</organizationUnitName>\n");
1159
          }
1160
          out.append("      <email>" + users[j][4] + "</email>\n");
1161
          out.append("    </user>\n");
1162
      }
1163

    
1164
      out.append("  </authSystem>\n");
1165
    }
1166
    out.append("</principals>");
1167
    return out.toString();
1168
  }
1169

    
1170
  /**
1171
   * Method for getting index of user DN in User info array
1172
   */
1173
  int searchUser(String user, String userGroup[][]) {
1174
    for (int j = 0; j < userGroup.length; j++) {
1175
      if (user.compareTo(userGroup[j][0]) == 0) {
1176
        return j;
1177
      }
1178
    }
1179
    return -1;
1180
  }
1181

    
1182
  /**
1183
   * Test method for the class
1184
   */
1185
  public static void main(String[] args) {
1186

    
1187
    // Provide a user, such as: "Matt Jones", or "jones"
1188
    String user = args[0];
1189
    String password = args[1];
1190

    
1191
    logMetacat.warn("Creating session...");
1192
    AuthLdap authservice = new AuthLdap();
1193
    logMetacat.warn("Session exists...");
1194

    
1195
    boolean isValid = false;
1196
    try {
1197
      logMetacat.warn("Authenticating...");
1198
      isValid = authservice.authenticate(user, password);
1199
      if (isValid) {
1200
    	  logMetacat.warn("Authentication successful for: " + user);
1201
      }
1202
      else {
1203
        logMetacat.warn("Authentication failed for: " + user);
1204
      }
1205

    
1206
      // Get attributes for the user
1207
      if (isValid) {
1208
        logMetacat.info("\nGetting attributes for user....");
1209
        HashMap userInfo = authservice.getAttributes(user, password, user);
1210
        // Print all of the attributes
1211
        Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
1212
        while (attList.hasNext()) {
1213
          String att = (String) attList.next();
1214
          Vector values = (Vector) userInfo.get(att);
1215
          Iterator attvalues = values.iterator();
1216
          while (attvalues.hasNext()) {
1217
            String value = (String) attvalues.next();
1218
            logMetacat.warn(att + ": " + value);
1219
          }
1220
        }
1221
      }
1222

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

    
1233
      // get the groups for the user
1234
      String savedGroup = null;
1235
      if (isValid) {
1236
        logMetacat.warn("\nGetting groups for user....");
1237
        String[][] groups = authservice.getGroups(user, password, user);
1238
        logMetacat.info("Groups found: " + groups.length);
1239
        for (int i = 0; i < groups.length; i++) {
1240
          logMetacat.info("Group " + i + ": " + groups[i][0]);
1241
          savedGroup = groups[i][0];
1242
        }
1243
      }
1244

    
1245
      // get the users for a group
1246
      if (isValid) {
1247
        logMetacat.warn("\nGetting users for group....");
1248
        logMetacat.info("Group: " + savedGroup);
1249
        String[] users = authservice.getUsers(user, password, savedGroup);
1250
        logMetacat.info("Users found: " + users.length);
1251
        for (int i = 0; i < users.length; i++) {
1252
          logMetacat.warn("User " + i + ": " + users[i]);
1253
        }
1254
      }
1255

    
1256
      // get all users
1257
      if (isValid) {
1258
        logMetacat.warn("\nGetting all users ....");
1259
        String[][] users = authservice.getUsers(user, password);
1260
        logMetacat.info("Users found: " + users.length);
1261

    
1262
      }
1263

    
1264
      // get the whole list groups and users in XML format
1265
      if (isValid) {
1266
        logMetacat.warn("\nTrying principals....");
1267
        authservice = new AuthLdap();
1268
        String out = authservice.getPrincipals(user, password);
1269
        java.io.File f = new java.io.File("principals.xml");
1270
        java.io.FileWriter fw = new java.io.FileWriter(f);
1271
        java.io.BufferedWriter buff = new java.io.BufferedWriter(fw);
1272
        buff.write(out);
1273
        buff.flush();
1274
        buff.close();
1275
        fw.close();
1276
        logMetacat.warn("\nFinished getting principals.");
1277
      }
1278

    
1279
    }
1280
    catch (ConnectException ce) {
1281
      logMetacat.error(ce.getMessage());
1282
    }
1283
    catch (java.io.IOException ioe) {
1284
      logMetacat.error("I/O Error writing to file principals.txt");
1285
    }
1286
  }
1287

    
1288
  /**
1289
   * This method will be called by start a thread.
1290
   * It can handle if a referral exception happend.
1291
   */
1292
}
(11-11/66)