LdapManager.java 77 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 2698 $
 * $Date: 2005-08-19 15:28:16 -0300 (Fri, 19 Aug 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7 8
 *
 * This software is published under the terms of the GNU Public License (GPL),
9 10
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
11 12
 */

13
package org.jivesoftware.openfire.ldap;
14 15 16

import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
17
import org.jivesoftware.openfire.user.UserNotFoundException;
18
import org.jivesoftware.openfire.group.GroupNotFoundException;
19 20 21 22 23 24 25 26

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
27
import javax.naming.ldap.*;
28
import java.net.URLEncoder;
Matt Tucker's avatar
Matt Tucker committed
29
import java.util.*;
30 31
import java.util.regex.Matcher;
import java.util.regex.Pattern;
32
import java.text.MessageFormat;
33 34

/**
Matt Tucker's avatar
Matt Tucker committed
35
 * Centralized administration of LDAP connections. The {@link #getInstance()} method
36 37 38 39 40 41 42 43 44
 * should be used to get an instace. The following properties configure this manager:
 *
 * <ul>
 *      <li>ldap.host</li>
 *      <li>ldap.port</li>
 *      <li>ldap.baseDN</li>
 *      <li>ldap.alternateBaseDN</li>
 *      <li>ldap.adminDN</li>
 *      <li>ldap.adminPassword</li>
Austen Rustrum's avatar
Austen Rustrum committed
45
 *      <li>ldap.encloseDNs</li>
46
 *      <li>ldap.usernameField -- default value is "uid".</li>
47
 *      <li>ldap.usernameSuffix -- default value is "".</li>
48 49
 *      <li>ldap.nameField -- default value is "cn".</li>
 *      <li>ldap.emailField -- default value is "mail".</li>
50 51 52
 *      <li>ldap.searchFilter -- the filter used to load the list of users. When defined, it
 *              will be used with the default filter, which is "([usernameField]={0})" where
 *              [usernameField] is the value of ldap.usernameField.
53 54 55 56 57 58 59 60
 *      <li>ldap.groupNameField</li>
 *      <li>ldap.groupMemberField</li>
 *      <li>ldap.groupDescriptionField</li>
 *      <li>ldap.posixMode</li>
 *      <li>ldap.groupSearchFilter</li>
 *      <li>ldap.debugEnabled</li>
 *      <li>ldap.sslEnabled</li>
 *      <li>ldap.autoFollowReferrals</li>
61
 *      <li>ldap.autoFollowAliasReferrals</li>
62 63
 *      <li>ldap.initialContextFactory --  if this value is not specified,
 *          "com.sun.jndi.ldap.LdapCtxFactory" will be used.</li>
Matt Tucker's avatar
Matt Tucker committed
64 65
 *      <li>ldap.connectionPoolEnabled -- true if an LDAP connection pool should be used.
 *          False if not set.</li>
66 67 68 69 70 71
 * </ul>
 *
 * @author Matt Tucker
 */
public class LdapManager {

Matt Tucker's avatar
Matt Tucker committed
72 73 74 75 76 77 78 79
    private static LdapManager instance;
    static {
        // Create a special Map implementation to wrap XMLProperties. We only implement
        // the get, put, and remove operations, since those are the only ones used. Using a Map
        // makes it easier to perform LdapManager testing.
        Map<String, String> properties = new Map<String, String>() {

            public String get(Object key) {
80
                return JiveGlobals.getProperty((String)key);
Matt Tucker's avatar
Matt Tucker committed
81 82 83
            }

            public String put(String key, String value) {
84
                JiveGlobals.setProperty(key, value);
Matt Tucker's avatar
Matt Tucker committed
85 86 87 88 89
                // Always return null since XMLProperties doesn't support the normal semantics.
                return null;
            }

            public String remove(Object key) {
90
                JiveGlobals.deleteProperty((String)key);
Matt Tucker's avatar
Matt Tucker committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                // Always return null since XMLProperties doesn't support the normal semantics.
                return null;
            }


            public int size() {
                return 0;
            }

            public boolean isEmpty() {
                return false;
            }

            public boolean containsKey(Object key) {
                return false;
            }

            public boolean containsValue(Object value) {
                return false;
            }

            public void putAll(Map<? extends String, ? extends String> t) {
            }

            public void clear() {
            }

            public Set<String> keySet() {
                return null;
            }

            public Collection<String> values() {
                return null;
            }

            public Set<Entry<String, String>> entrySet() {
                return null;
            }
        };
        instance = new LdapManager(properties);
    }


134
    private Collection<String> hosts = new ArrayList<String>();
135
    private int port;
136
    private int readTimeout = -1;
137
    private String usernameField;
138
    private String usernameSuffix;
139 140 141
    private String nameField;
    private String emailField;
    private String baseDN;
142 143 144
    private String alternateBaseDN = null;
    private String adminDN = null;
    private String adminPassword;
Austen Rustrum's avatar
Austen Rustrum committed
145
    private boolean encloseDNs;
146 147 148 149
    private boolean ldapDebugEnabled = false;
    private boolean sslEnabled = false;
    private String initialContextFactory;
    private boolean followReferrals = false;
150
    private boolean followAliasReferrals = true;
151 152
    private boolean connectionPoolEnabled = true;
    private String searchFilter = null;
153
    private boolean subTreeSearch;
154
    private boolean encloseUserDN;
155
    private boolean encloseGroupDN;
156

157 158
    private String groupNameField;
    private String groupMemberField;
Matt Tucker's avatar
Matt Tucker committed
159
    private String groupDescriptionField;
160 161 162
    private boolean posixMode = false;
    private String groupSearchFilter = null;

Austen Rustrum's avatar
Austen Rustrum committed
163
    private Pattern dnPattern;
164

Matt Tucker's avatar
Matt Tucker committed
165
    private Map<String, String> properties;
166 167 168 169 170 171 172 173 174 175 176

    /**
     * Provides singleton access to an instance of the LdapManager class.
     *
     * @return an LdapManager instance.
     */
    public static LdapManager getInstance() {
        return instance;
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
177 178 179 180 181 182
     * Constructs a new LdapManager instance. Typically, {@link #getInstance()} should be
     * called instead of this method. LdapManager instances should only be created directly
     * for testing purposes.
     *
     * @param properties the Map that contains properties used by the LDAP manager, such as
     *      LDAP host and base DN.
183
     */
Matt Tucker's avatar
Matt Tucker committed
184 185
    public LdapManager(Map<String, String> properties) {
        this.properties = properties;
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("ldap.host");
        JiveGlobals.migrateProperty("ldap.port");
        JiveGlobals.migrateProperty("ldap.readTimeout");
        JiveGlobals.migrateProperty("ldap.usernameField");
        JiveGlobals.migrateProperty("ldap.usernameSuffix");
        JiveGlobals.migrateProperty("ldap.baseDN");
        JiveGlobals.migrateProperty("ldap.alternateBaseDN");
        JiveGlobals.migrateProperty("ldap.nameField");
        JiveGlobals.migrateProperty("ldap.emailField");
        JiveGlobals.migrateProperty("ldap.connectionPoolEnabled");
        JiveGlobals.migrateProperty("ldap.searchFilter");
        JiveGlobals.migrateProperty("ldap.subTreeSearch");
        JiveGlobals.migrateProperty("ldap.groupNameField");
        JiveGlobals.migrateProperty("ldap.groupMemberField");
        JiveGlobals.migrateProperty("ldap.groupDescriptionField");
        JiveGlobals.migrateProperty("ldap.posixMode");
        JiveGlobals.migrateProperty("ldap.groupSearchFilter");
        JiveGlobals.migrateProperty("ldap.adminDN");
        JiveGlobals.migrateProperty("ldap.adminPassword");
        JiveGlobals.migrateProperty("ldap.debugEnabled");
        JiveGlobals.migrateProperty("ldap.sslEnabled");
        JiveGlobals.migrateProperty("ldap.autoFollowReferrals");
        JiveGlobals.migrateProperty("ldap.autoFollowAliasReferrals");
        JiveGlobals.migrateProperty("ldap.encloseUserDN");
        JiveGlobals.migrateProperty("ldap.encloseGroupDN");
Austen Rustrum's avatar
Austen Rustrum committed
213
        JiveGlobals.migrateProperty("ldap.encloseDNs");
214 215 216 217
        JiveGlobals.migrateProperty("ldap.initialContextFactory");
        JiveGlobals.migrateProperty("ldap.pagedResultsSize");
        JiveGlobals.migrateProperty("ldap.clientSideSorting");
        JiveGlobals.migrateProperty("ldap.ldapDebugEnabled");
Austen Rustrum's avatar
Austen Rustrum committed
218

Matt Tucker's avatar
Matt Tucker committed
219
        String host = properties.get("ldap.host");
220 221 222 223 224 225 226
        if (host != null) {
            // Parse the property and check if many hosts were defined. Hosts can be separated
            // by commas or white spaces
            StringTokenizer st = new StringTokenizer(host, " ,\t\n\r\f");
            while (st.hasMoreTokens()) {
                hosts.add(st.nextToken());
            }
227
        }
Matt Tucker's avatar
Matt Tucker committed
228 229 230 231 232 233 234 235 236 237
        String portStr = properties.get("ldap.port");
        port = 389;
        if (portStr != null) {
            try {
                this.port = Integer.parseInt(portStr);
            }
            catch (NumberFormatException nfe) {
                Log.error(nfe);
            }
        }
238 239 240 241 242 243 244 245 246
        String timeout = properties.get("ldap.readTimeout");
        if (timeout != null) {
            try {
                this.readTimeout = Integer.parseInt(timeout);
            }
            catch (NumberFormatException nfe) {
                Log.error(nfe);
            }
        }
Matt Tucker's avatar
Matt Tucker committed
247 248 249 250 251

        usernameField = properties.get("ldap.usernameField");
        if (usernameField == null) {
            usernameField = "uid";
        }
252 253 254 255
        usernameSuffix = properties.get("ldap.usernameSuffix");
        if (usernameSuffix == null) {
            usernameSuffix = "";
        }
Austen Rustrum's avatar
Austen Rustrum committed
256 257 258 259 260 261 262 263 264 265 266

        // Set the pattern to use to wrap DN values with "
        dnPattern = Pattern.compile("([^\\\\]=)([^\"].*?[^\\\\])(,|$)");

        // are we going to enclose DN values with quotes? (needed when DNs contain non-delimiting commas)
        encloseDNs = true;
        String encloseStr = properties.get("ldap.encloseDNs");
        if (encloseStr != null) {
            encloseDNs = Boolean.valueOf(encloseStr);
        }

Matt Tucker's avatar
Matt Tucker committed
267 268 269 270
        baseDN = properties.get("ldap.baseDN");
        if (baseDN == null) {
            baseDN = "";
        }
Austen Rustrum's avatar
Austen Rustrum committed
271 272 273 274
        if (encloseDNs) {
           baseDN = getEnclosedDN(baseDN);
        }

Matt Tucker's avatar
Matt Tucker committed
275
        alternateBaseDN = properties.get("ldap.alternateBaseDN");
Austen Rustrum's avatar
Austen Rustrum committed
276 277 278 279
        if (encloseDNs && alternateBaseDN != null) {
           alternateBaseDN = getEnclosedDN(alternateBaseDN);
        }

Matt Tucker's avatar
Matt Tucker committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        nameField = properties.get("ldap.nameField");
        if (nameField == null) {
            nameField = "cn";
        }
        emailField = properties.get("ldap.emailField");
        if (emailField == null) {
            emailField = "mail";
        }
        connectionPoolEnabled = true;
        String connectionPoolStr = properties.get("ldap.connectionPoolEnabled");
        if (connectionPoolStr != null) {
            connectionPoolEnabled = Boolean.valueOf(connectionPoolStr);
        }
        searchFilter = properties.get("ldap.searchFilter");
        subTreeSearch = true;
        String subTreeStr = properties.get("ldap.subTreeSearch");
        if (subTreeStr != null) {
            subTreeSearch = Boolean.valueOf(subTreeStr);
        }
        groupNameField = properties.get("ldap.groupNameField");
        if (groupNameField == null) {
            groupNameField = "cn";
        }
        groupMemberField = properties.get("ldap.groupMemberField");
        if (groupMemberField ==null) {
            groupMemberField = "member";
        }
        groupDescriptionField = properties.get("ldap.groupDescriptionField");
        if (groupDescriptionField == null) {
            groupDescriptionField = "description";
        }
        posixMode = false;
        String posixStr = properties.get("ldap.posixMode");
        if (posixStr != null) {
            posixMode = Boolean.valueOf(posixStr);
        }
        groupSearchFilter = properties.get("ldap.groupSearchFilter");

        adminDN = properties.get("ldap.adminDN");
319 320 321
        if (adminDN != null && adminDN.trim().equals("")) {
            adminDN = null;
        }
Austen Rustrum's avatar
Austen Rustrum committed
322 323 324 325
        if (encloseDNs && adminDN != null) {
           adminDN = getEnclosedDN(adminDN);
        }

Matt Tucker's avatar
Matt Tucker committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        adminPassword = properties.get("ldap.adminPassword");
        ldapDebugEnabled = false;
        String ldapDebugStr = properties.get("ldap.debugEnabled");
        if (ldapDebugStr != null) {
            ldapDebugEnabled = Boolean.valueOf(ldapDebugStr);
        }
        sslEnabled = false;
        String sslEnabledStr = properties.get("ldap.sslEnabled");
        if (sslEnabledStr != null) {
            sslEnabled = Boolean.valueOf(sslEnabledStr);
        }
        followReferrals = false;
        String followReferralsStr = properties.get("ldap.autoFollowReferrals");
        if (followReferralsStr != null) {
            followReferrals = Boolean.valueOf(followReferralsStr);
        }
342 343 344 345 346
        followAliasReferrals = true;
        String followAliasReferralsStr = properties.get("ldap.autoFollowAliasReferrals");
        if (followAliasReferralsStr != null) {
            followAliasReferrals = Boolean.valueOf(followAliasReferralsStr);
        }
Austen Rustrum's avatar
Austen Rustrum committed
347
        // the following two properties have been deprecated by ldap.encloseDNs.  keeping around for backwards compatibility
Matt Tucker's avatar
Matt Tucker committed
348 349 350
        encloseUserDN = true;
        String encloseUserStr = properties.get("ldap.encloseUserDN");
        if (encloseUserStr != null) {
Austen Rustrum's avatar
Austen Rustrum committed
351
            encloseUserDN = Boolean.valueOf(encloseUserStr) || encloseDNs;
Matt Tucker's avatar
Matt Tucker committed
352
        }
353 354 355
        encloseGroupDN = true;
        String encloseGroupStr = properties.get("ldap.encloseGroupDN");
        if (encloseGroupStr != null) {
Austen Rustrum's avatar
Austen Rustrum committed
356
            encloseGroupDN = Boolean.valueOf(encloseGroupStr) || encloseDNs;
357
        }
Matt Tucker's avatar
Matt Tucker committed
358
        this.initialContextFactory = properties.get("ldap.initialContextFactory");
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
        if (initialContextFactory != null) {
            try {
                Class.forName(initialContextFactory);
            }
            catch (ClassNotFoundException cnfe) {
                Log.error("Initial context factory class failed to load: " + initialContextFactory +
                        ".  Using default initial context factory class instead.");
                initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
            }
        }
        // Use default value if none was set.
        else {
            initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
        }

374 375 376 377 378
        StringBuilder buf = new StringBuilder();
        buf.append("Created new LdapManager() instance, fields:\n");
        buf.append("\t host: ").append(hosts).append("\n");
        buf.append("\t port: ").append(port).append("\n");
        buf.append("\t usernamefield: ").append(usernameField).append("\n");
379
        buf.append("\t usernameSuffix: ").append(usernameSuffix).append("\n");
380 381 382 383 384 385 386 387 388 389 390 391 392
        buf.append("\t baseDN: ").append(baseDN).append("\n");
        buf.append("\t alternateBaseDN: ").append(alternateBaseDN).append("\n");
        buf.append("\t nameField: ").append(nameField).append("\n");
        buf.append("\t emailField: ").append(emailField).append("\n");
        buf.append("\t adminDN: ").append(adminDN).append("\n");
        buf.append("\t adminPassword: ").append(adminPassword).append("\n");
        buf.append("\t searchFilter: ").append(searchFilter).append("\n");
        buf.append("\t subTreeSearch:").append(subTreeSearch).append("\n");
        buf.append("\t ldapDebugEnabled: ").append(ldapDebugEnabled).append("\n");
        buf.append("\t sslEnabled: ").append(sslEnabled).append("\n");
        buf.append("\t initialContextFactory: ").append(initialContextFactory).append("\n");
        buf.append("\t connectionPoolEnabled: ").append(connectionPoolEnabled).append("\n");
        buf.append("\t autoFollowReferrals: ").append(followReferrals).append("\n");
393
        buf.append("\t autoFollowAliasReferrals: ").append(followAliasReferrals).append("\n");
394 395 396 397 398 399
        buf.append("\t groupNameField: ").append(groupNameField).append("\n");
        buf.append("\t groupMemberField: ").append(groupMemberField).append("\n");
        buf.append("\t groupDescriptionField: ").append(groupDescriptionField).append("\n");
        buf.append("\t posixMode: ").append(posixMode).append("\n");
        buf.append("\t groupSearchFilter: ").append(groupSearchFilter).append("\n");

400
        if (Log.isDebugEnabled()) {
401
            Log.debug("LdapManager: "+buf.toString());
402 403 404
        }
        if (ldapDebugEnabled) {
            System.err.println(buf.toString());
405 406 407 408 409
        }
    }

    /**
     * Returns a DirContext for the LDAP server that can be used to perform
410 411
     * lookups and searches using the default base DN. The alternate DN will be used
     * in case there is a {@link NamingException} using base DN. The context uses the
412 413 414 415 416 417
     * admin login that is defined by <tt>adminDN</tt> and <tt>adminPassword</tt>.
     *
     * @return a connection to the LDAP server.
     * @throws NamingException if there is an error making the LDAP connection.
     */
    public LdapContext getContext() throws NamingException {
418 419 420 421 422 423 424 425 426 427
        try {
            return getContext(baseDN);
        }
        catch (NamingException e) {
            if (alternateBaseDN != null) {
                return getContext(alternateBaseDN);
            } else {
                throw(e);
            }
        }
428 429 430 431 432 433 434 435 436 437 438 439 440 441
    }

    /**
     * Returns a DirContext for the LDAP server that can be used to perform
     * lookups and searches using the specified base DN. The context uses the
     * admin login that is defined by <tt>adminDN</tt> and <tt>adminPassword</tt>.
     *
     * @param baseDN the base DN to use for the context.
     * @return a connection to the LDAP server.
     * @throws NamingException if there is an error making the LDAP connection.
     */
    public LdapContext getContext(String baseDN) throws NamingException {
        boolean debug = Log.isDebugEnabled();
        if (debug) {
442
            Log.debug("LdapManager: Creating a DirContext in LdapManager.getContext()...");
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        }

         // Set up the environment for creating the initial context
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
        if (sslEnabled) {
            env.put("java.naming.ldap.factory.socket",
                    "org.jivesoftware.util.SimpleSSLSocketFactory");
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        // Use simple authentication to connect as the admin.
        if (adminDN != null) {
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, adminDN);
            if (adminPassword != null) {
                env.put(Context.SECURITY_CREDENTIALS, adminPassword);
            }
        }
        // No login information so attempt to use anonymous login.
        else {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
        }

        if (ldapDebugEnabled) {
            env.put("com.sun.jndi.ldap.trace.ber", System.err);
        }
        if (connectionPoolEnabled) {
            env.put("com.sun.jndi.ldap.connect.pool", "true");
        }
        if (followReferrals) {
            env.put(Context.REFERRAL, "follow");
        }
477 478 479
        if (!followAliasReferrals) {
            env.put("java.naming.ldap.derefAliases", "never");
        }
480 481

        if (debug) {
482
            Log.debug("LdapManager: Created hashtable with context values, attempting to create context...");
483 484 485 486
        }
        // Create new initial context
        LdapContext context = new InitialLdapContext(env, null);
        if (debug) {
487
            Log.debug("LdapManager: ... context created successfully, returning.");
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        }
        return context;
    }

    /**
     * Returns true if the user is able to successfully authenticate against
     * the LDAP server. The "simple" authentication protocol is used.
     *
     * @param userDN the user's dn to authenticate (relative to <tt>baseDN</tt>).
     * @param password the user's password.
     * @return true if the user successfully authenticates.
     */
    public boolean checkAuthentication(String userDN, String password) {
        boolean debug = Log.isDebugEnabled();
        if (debug) {
503
            Log.debug("LdapManager: In LdapManager.checkAuthentication(userDN, password), userDN is: " + userDN + "...");
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        }

        DirContext ctx = null;
        try {
            // See if the user authenticates.
            Hashtable<String, Object> env = new Hashtable<String, Object>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
            env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
            if (sslEnabled) {
                env.put("java.naming.ldap.factory.socket",
                        "org.jivesoftware.util.SimpleSSLSocketFactory");
                env.put(Context.SECURITY_PROTOCOL, "ssl");
            }
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, userDN + "," + baseDN);
            env.put(Context.SECURITY_CREDENTIALS, password);
            // Specify timeout to be 10 seconds, only on non SSL since SSL connections
521
            // break with a timemout.
522 523 524
            if (!sslEnabled) {
                env.put("com.sun.jndi.ldap.connect.timeout", "10000");
            }
525 526 527
            if (readTimeout > 0) {
                env.put("com.sun.jndi.ldap.read.timeout", String.valueOf(readTimeout));
            }
528 529 530
            if (ldapDebugEnabled) {
                env.put("com.sun.jndi.ldap.trace.ber", System.err);
            }
531 532 533
            if (followReferrals) {
                env.put(Context.REFERRAL, "follow");
            }
534 535 536
            if (!followAliasReferrals) {
                env.put("java.naming.ldap.derefAliases", "never");
            }
537

538
            if (debug) {
539
                Log.debug("LdapManager: Created context values, attempting to create context...");
540 541 542
            }
            ctx = new InitialDirContext(env);
            if (debug) {
543
                Log.debug("LdapManager: ... context created successfully, returning.");
544 545 546 547 548
            }
        }
        catch (NamingException ne) {
            // If an alt baseDN is defined, attempt a lookup there.
            if (alternateBaseDN != null) {
Matt Tucker's avatar
Matt Tucker committed
549 550 551 552 553 554
                try {
                    if (ctx != null) {
                        ctx.close();
                    }
                }
                catch (Exception e) {
555
                    Log.error(e);
556
                }
557 558 559 560 561 562 563 564 565 566 567 568 569 570
                try {
                    // See if the user authenticates.
                    Hashtable<String, Object> env = new Hashtable<String, Object>();
                    // Use a custom initial context factory if specified. Otherwise, use the default.
                    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
                    env.put(Context.PROVIDER_URL, getProviderURL(alternateBaseDN));
                    if (sslEnabled) {
                        env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
                        env.put(Context.SECURITY_PROTOCOL, "ssl");
                    }
                    env.put(Context.SECURITY_AUTHENTICATION, "simple");
                    env.put(Context.SECURITY_PRINCIPAL, userDN + "," + alternateBaseDN);
                    env.put(Context.SECURITY_CREDENTIALS, password);
                    // Specify timeout to be 10 seconds, only on non SSL since SSL connections
Matt Tucker's avatar
Matt Tucker committed
571
                    // break with a timemout.
572 573 574 575 576 577
                    if (!sslEnabled) {
                        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
                    }
                    if (ldapDebugEnabled) {
                        env.put("com.sun.jndi.ldap.trace.ber", System.err);
                    }
578 579 580
                    if (followReferrals) {
                        env.put(Context.REFERRAL, "follow");
                    }
581 582 583
                    if (!followAliasReferrals) {
                        env.put("java.naming.ldap.derefAliases", "never");
                    }
584
                    if (debug) {
585
                        Log.debug("LdapManager: Created context values, attempting to create context...");
586 587 588 589 590
                    }
                    ctx = new InitialDirContext(env);
                }
                catch (NamingException e) {
                    if (debug) {
591
                        Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
592 593 594 595 596 597
                    }
                    return false;
                }
            }
            else {
                if (debug) {
598
                    Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
599 600 601 602 603
                }
                return false;
            }
        }
        finally {
Matt Tucker's avatar
Matt Tucker committed
604 605 606 607 608 609 610
            try {
                if (ctx != null) {
                    ctx.close();
                }
            }
            catch (Exception e) {
                Log.error(e);
611
            }
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
        }
        return true;
    }

    /**
     * Finds a user's dn using their username. Normally, this search will
     * be performed using the field "uid", but this can be changed by setting
     * the <tt>usernameField</tt> property.<p>
     *
     * Searches are performed over all subtrees relative to the <tt>baseDN</tt>.
     * If the search fails in the <tt>baseDN</tt> then another search will be
     * performed in the <tt>alternateBaseDN</tt>. For example, if the <tt>baseDN</tt>
     * is "o=jivesoftware, o=com" and we do a search for "mtucker", then we might
     * find a userDN of "uid=mtucker,ou=People". This kind of searching is a good
     * thing since it doesn't make the assumption that all user records are stored
     * in a flat structure. However, it does add the requirement that "uid" field
     * (or the other field specified) must be unique over the entire subtree from
     * the <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
     * in your LDAP directory with the same uid: "uid=mtucker,ou=People" and
     * "uid=mtucker,ou=Administrators". In such a case, it's not possible to
     * uniquely identify a user, so this method will throw an error.<p>
     *
     * The dn that's returned is relative to the default <tt>baseDN</tt>.
     *
     * @param username the username to lookup the dn for.
     * @return the dn associated with <tt>username</tt>.
     * @throws Exception if the search for the dn fails.
     */
    public String findUserDN(String username) throws Exception {
        try {
            return findUserDN(username, baseDN);
        }
        catch (Exception e) {
            if (alternateBaseDN != null) {
                return findUserDN(username, alternateBaseDN);
            }
            else {
                throw e;
            }
        }
    }

    /**
     * Finds a user's dn using their username in the specified baseDN. Normally, this search
     * will be performed using the field "uid", but this can be changed by setting
     * the <tt>usernameField</tt> property.<p>
     *
659 660 661
     * Searches are performed over all sub-trees relative to the <tt>baseDN</tt> unless
     * sub-tree searching has been disabled. For example, if the <tt>baseDN</tt> is
     * "o=jivesoftware, o=com" and we do a search for "mtucker", then we might find a userDN of
662 663 664 665 666 667 668 669 670
     * "uid=mtucker,ou=People". This kind of searching is a good thing since
     * it doesn't make the assumption that all user records are stored in a flat
     * structure. However, it does add the requirement that "uid" field (or the
     * other field specified) must be unique over the entire subtree from the
     * <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
     * in your LDAP directory with the same uid: "uid=mtucker,ou=People" and
     * "uid=mtucker,ou=Administrators". In such a case, it's not possible to
     * uniquely identify a user, so this method will throw an error.<p>
     *
671
     * The DN that's returned is relative to the <tt>baseDN</tt>.
672 673 674 675 676
     *
     * @param username the username to lookup the dn for.
     * @param baseDN the base DN to use for this search.
     * @return the dn associated with <tt>username</tt>.
     * @throws Exception if the search for the dn fails.
677
     * @see #findUserDN(String) to search using the default baseDN and alternateBaseDN.
678 679 680
     */
    public String findUserDN(String username, String baseDN) throws Exception {
        boolean debug = Log.isDebugEnabled();
681 682
        //Support for usernameSuffix
        username = username + usernameSuffix;
683
        if (debug) {
684
            Log.debug("LdapManager: Trying to find a user's DN based on their username. " + usernameField + ": " + username
685 686 687 688 689 690
                    + ", Base DN: " + baseDN + "...");
        }
        DirContext ctx = null;
        try {
            ctx = getContext(baseDN);
            if (debug) {
691
                Log.debug("LdapManager: Starting LDAP search...");
692 693 694
            }
            // Search for the dn based on the username.
            SearchControls constraints = new SearchControls();
695 696 697 698 699 700 701 702
            // If sub-tree searching is enabled (default is true) then search the entire tree.
            if (subTreeSearch) {
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            // Otherwise, only search a single level.
            else {
                constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
703 704
            constraints.setReturningAttributes(new String[] { usernameField });

705
            NamingEnumeration answer = ctx.search("", getSearchFilter(), new String[] {username},
706 707 708
                    constraints);

            if (debug) {
709
                Log.debug("LdapManager: ... search finished");
710 711 712 713
            }

            if (answer == null || !answer.hasMoreElements()) {
                if (debug) {
714
                    Log.debug("LdapManager: User DN based on username '" + username + "' not found.");
715 716 717 718 719 720 721 722 723 724 725
                }
                throw new UserNotFoundException("Username " + username + " not found");
            }
            String userDN = ((SearchResult)answer.next()).getName();
            // Make sure there are no more search results. If there are, then
            // the username isn't unique on the LDAP server (a perfectly possible
            // scenario since only fully qualified dn's need to be unqiue).
            // There really isn't a way to handle this, so throw an exception.
            // The baseDN must be set correctly so that this doesn't happen.
            if (answer.hasMoreElements()) {
                if (debug) {
726
                    Log.debug("LdapManager: Search for userDN based on username '" + username + "' found multiple " +
727 728 729 730 731
                            "responses, throwing exception.");
                }
                throw new UserNotFoundException("LDAP username lookup for " + username +
                        " matched multiple entries.");
            }
732 733 734 735 736
            // Close the enumeration.
            answer.close();
            // All other methods assume that userDN is not a full LDAP string.
            // However if a referal was followed this is not the case.  The
            // following code converts a referral back to a "partial" LDAP string.
737 738 739
            if (userDN.startsWith("ldap://")) {
                userDN = userDN.replace("," + baseDN, "");
                userDN = userDN.substring(userDN.lastIndexOf("/") + 1);
740
                userDN = java.net.URLDecoder.decode(userDN, "UTF-8");
741
            }
742
            if (encloseUserDN) {
Austen Rustrum's avatar
Austen Rustrum committed
743
                userDN = getEnclosedDN(userDN);
744
            }
745
            return userDN;
746 747 748
        }
        catch (Exception e) {
            if (debug) {
749
                Log.debug("LdapManager: Exception thrown when searching for userDN based on username '" + username + "'", e);
750 751 752 753 754
            }
            throw e;
        }
        finally {
            try { ctx.close(); }
755 756 757
            catch (Exception ignored) {
                // Ignore.
            }
758 759 760
        }
    }

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    /**
     * Finds a groups's dn using it's group name. Normally, this search will
     * be performed using the field "cn", but this can be changed by setting
     * the <tt>groupNameField</tt> property.<p>
     *
     * Searches are performed over all subtrees relative to the <tt>baseDN</tt>.
     * If the search fails in the <tt>baseDN</tt> then another search will be
     * performed in the <tt>alternateBaseDN</tt>. For example, if the <tt>baseDN</tt>
     * is "o=jivesoftware, o=com" and we do a search for "managers", then we might
     * find a groupDN of "uid=managers,ou=Groups". This kind of searching is a good
     * thing since it doesn't make the assumption that all user records are stored
     * in a flat structure. However, it does add the requirement that "cn" field
     * (or the other field specified) must be unique over the entire subtree from
     * the <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
     * in your LDAP directory with the same cn: "cn=managers,ou=Financial" and
     * "cn=managers,ou=Engineers". In such a case, it's not possible to
     * uniquely identify a group, so this method will throw an error.<p>
     *
     * The dn that's returned is relative to the default <tt>baseDN</tt>.
     *
     * @param groupname the groupname to lookup the dn for.
     * @return the dn associated with <tt>groupname</tt>.
     * @throws Exception if the search for the dn fails.
     */
    public String findGroupDN(String groupname) throws Exception {
        try {
            return findGroupDN(groupname, baseDN);
        }
        catch (Exception e) {
            if (alternateBaseDN != null) {
                return findGroupDN(groupname, alternateBaseDN);
            }
            else {
                throw e;
            }
        }
    }

    /**
     * Finds a groups's dn using it's group name. Normally, this search will
     * be performed using the field "cn", but this can be changed by setting
     * the <tt>groupNameField</tt> property.<p>
     *
     * Searches are performed over all subtrees relative to the <tt>baseDN</tt>.
     * If the search fails in the <tt>baseDN</tt> then another search will be
     * performed in the <tt>alternateBaseDN</tt>. For example, if the <tt>baseDN</tt>
     * is "o=jivesoftware, o=com" and we do a search for "managers", then we might
     * find a groupDN of "uid=managers,ou=Groups". This kind of searching is a good
     * thing since it doesn't make the assumption that all user records are stored
     * in a flat structure. However, it does add the requirement that "cn" field
     * (or the other field specified) must be unique over the entire subtree from
     * the <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
     * in your LDAP directory with the same cn: "cn=managers,ou=Financial" and
     * "cn=managers,ou=Engineers". In such a case, it's not possible to
     * uniquely identify a group, so this method will throw an error.<p>
     *
     * The dn that's returned is relative to the default <tt>baseDN</tt>.
     *
     * @param groupname the groupname to lookup the dn for.
     * @param baseDN the base DN to use for this search.
     * @return the dn associated with <tt>groupname</tt>.
     * @throws Exception if the search for the dn fails.
     * @see #findGroupDN(String) to search using the default baseDN and alternateBaseDN.
     */
    public String findGroupDN(String groupname, String baseDN) throws Exception {
        boolean debug = Log.isDebugEnabled();
        if (debug) {
            Log.debug("LdapManager: Trying to find a groups's DN based on it's groupname. " + groupNameField + ": " + groupname
                    + ", Base DN: " + baseDN + "...");
        }
        DirContext ctx = null;
        try {
            ctx = getContext(baseDN);
            if (debug) {
                Log.debug("LdapManager: Starting LDAP search...");
            }
            // Search for the dn based on the groupname.
            SearchControls constraints = new SearchControls();
            // If sub-tree searching is enabled (default is true) then search the entire tree.
            if (subTreeSearch) {
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            // Otherwise, only search a single level.
            else {
                constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            constraints.setReturningAttributes(new String[] { groupNameField });

            String filter = MessageFormat.format(getGroupSearchFilter(), groupname);
            NamingEnumeration answer = ctx.search("", filter, constraints);

            if (debug) {
                Log.debug("LdapManager: ... search finished");
            }

            if (answer == null || !answer.hasMoreElements()) {
                if (debug) {
                    Log.debug("LdapManager: Group DN based on groupname '" + groupname + "' not found.");
                }
                throw new GroupNotFoundException("Groupname " + groupname + " not found");
            }
            String groupDN = ((SearchResult)answer.next()).getName();
            // Make sure there are no more search results. If there are, then
            // the groupname isn't unique on the LDAP server (a perfectly possible
            // scenario since only fully qualified dn's need to be unqiue).
            // There really isn't a way to handle this, so throw an exception.
            // The baseDN must be set correctly so that this doesn't happen.
            if (answer.hasMoreElements()) {
                if (debug) {
                    Log.debug("LdapManager: Search for groupDN based on groupname '" + groupname + "' found multiple " +
                            "responses, throwing exception.");
                }
                throw new GroupNotFoundException("LDAP groupname lookup for " + groupname +
                        " matched multiple entries.");
            }
            // Close the enumeration.
            answer.close();
            // All other methods assume that groupDN is not a full LDAP string.
            // However if a referal was followed this is not the case.  The
            // following code converts a referral back to a "partial" LDAP string.
            if (groupDN.startsWith("ldap://")) {
                groupDN = groupDN.replace("," + baseDN, "");
                groupDN = groupDN.substring(groupDN.lastIndexOf("/") + 1);
                groupDN = java.net.URLDecoder.decode(groupDN, "UTF-8");
            }
            if (encloseGroupDN) {
Austen Rustrum's avatar
Austen Rustrum committed
887
                groupDN = getEnclosedDN(groupDN);
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
            }
            return groupDN;
        }
        catch (Exception e) {
            if (debug) {
                Log.debug("LdapManager: Exception thrown when searching for groupDN based on groupname '" + groupname + "'", e);
            }
            throw e;
        }
        finally {
            try { ctx.close(); }
            catch (Exception ignored) {
                // Ignore.
            }
        }
    }

905 906 907 908 909 910 911 912
    /**
     * Returns a properly encoded URL for use as the PROVIDER_URL.
     * If the encoding fails then the URL will contain the raw base dn.
     *
     * @param baseDN the base dn to use in the URL.
     * @return the properly encoded URL for use in as PROVIDER_URL.
     */
    private String getProviderURL(String baseDN) {
913
        StringBuffer ldapURL = new StringBuffer();
914
        try {
915
            baseDN = URLEncoder.encode(baseDN, "UTF-8");
916
            // The java.net.URLEncoder class encodes spaces as +, but they need to be %20
917
            baseDN = baseDN.replaceAll("\\+", "%20");
918 919 920 921
        }
        catch (java.io.UnsupportedEncodingException e) {
            // UTF-8 is not supported, fall back to using raw baseDN
        }
922 923 924 925 926 927 928 929 930 931 932
        for (String host : hosts) {
            // Create a correctly-encoded ldap URL for the PROVIDER_URL
            ldapURL.append("ldap://");
            ldapURL.append(host);
            ldapURL.append(":");
            ldapURL.append(port);
            ldapURL.append("/");
            ldapURL.append(baseDN);
            ldapURL.append(" ");
        }
        return ldapURL.toString();
933 934 935
    }

    /**
936
     * Returns the LDAP servers hosts; e.g. <tt>localhost</tt> or
937 938 939 940 941
     * <tt>machine.example.com</tt>, etc. This value is stored as the Jive
     * Property <tt>ldap.host</tt>.
     *
     * @return the LDAP server host name.
     */
942 943
    public Collection<String> getHosts() {
        return hosts;
944 945 946
    }

    /**
947
     * Sets the list of LDAP servers host; e.g., <tt>localhost</tt> or
948
     * <tt>machine.example.com</tt>, etc. This value is store as the Jive
949 950 951
     * Property <tt>ldap.host</tt> using a comma as a delimiter for each host.<p>
     *
     * Note that all LDAP servers have to share the same configuration.
952
     *
953
     * @param hosts the LDAP servers host names.
954
     */
955 956 957 958 959 960 961 962 963 964
    public void setHosts(Collection<String> hosts) {
        this.hosts = hosts;
        StringBuilder hostProperty = new StringBuilder();
        for (String host : hosts) {
            hostProperty.append(host).append(",");
        }
        if (!hosts.isEmpty()) {
            // Remove the last comma
            hostProperty.setLength(hostProperty.length()-1);
        }
Matt Tucker's avatar
Matt Tucker committed
965
        properties.put("ldap.host", hostProperty.toString());
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
    }

    /**
     * Returns the LDAP server port number. The default is 389. This value is
     * stored as the Jive Property <tt>ldap.port</tt>.
     *
     * @return the LDAP server port number.
     */
    public int getPort() {
        return port;
    }

    /**
     * Sets the LDAP server port number. The default is 389. This value is
     * stored as the Jive property <tt>ldap.port</tt>.
     *
     * @param port the LDAP server port number.
     */
    public void setPort(int port) {
        this.port = port;
Matt Tucker's avatar
Matt Tucker committed
986
        properties.put("ldap.port", Integer.toString(port));
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    }

    /**
     * Returns true if LDAP connection debugging is turned on. When on, trace
     * information about BER buffers sent and received by the LDAP provider is
     * written to System.out. Debugging is turned off by default.
     *
     * @return true if LDAP debugging is turned on.
     */
    public boolean isDebugEnabled() {
        return ldapDebugEnabled;
    }

    /**
     * Sets whether LDAP connection debugging is turned on. When on, trace
     * information about BER buffers sent and received by the LDAP provider is
     * written to System.out. Debugging is turned off by default.
     *
     * @param debugEnabled true if debugging should be turned on.
     */
    public void setDebugEnabled(boolean debugEnabled) {
        this.ldapDebugEnabled = debugEnabled;
Matt Tucker's avatar
Matt Tucker committed
1009
        properties.put("ldap.ldapDebugEnabled", Boolean.toString(debugEnabled));
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    }

    /**
     * Returns true if LDAP connection is via SSL or not. SSL is turned off by default.
     *
     * @return true if SSL connections are enabled or not.
     */
    public boolean isSslEnabled() {
        return sslEnabled;
    }

    /**
     * Sets whether the connection to the LDAP server should be made via ssl or not.
     *
     * @param sslEnabled true if ssl should be enabled, false otherwise.
     */
    public void setSslEnabled(boolean sslEnabled) {
        this.sslEnabled = sslEnabled;
Matt Tucker's avatar
Matt Tucker committed
1028
        properties.put("ldap.sslEnabled", Boolean.toString(sslEnabled));
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    }

    /**
     * Returns the LDAP field name that the username lookup will be performed
     * on. By default this is "uid".
     *
     * @return the LDAP field that the username lookup will be performed on.
     */
    public String getUsernameField() {
        return usernameField;
    }

1041 1042 1043
    /**
     * Returns the suffix appended to the username when LDAP lookups are performed.
     * By default this is "".
1044 1045
     *
     * @return the suffix appened to usernames when LDAP lookups are performed.
1046 1047 1048 1049 1050
     */
    public String getUsernameSuffix() {
        return usernameSuffix;
    }

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    /**
     * Sets the LDAP field name that the username lookup will be performed on.
     * By default this is "uid".
     *
     * @param usernameField the LDAP field that the username lookup will be
     *      performed on.
     */
    public void setUsernameField(String usernameField) {
        this.usernameField = usernameField;
        if (usernameField == null) {
Matt Tucker's avatar
Matt Tucker committed
1061
            properties.remove("ldap.usernameField");
1062
            this.usernameField = "uid";
1063 1064
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
1065
            properties.put("ldap.usernameField", usernameField);
1066 1067 1068
        }
    }

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    /**
     * Set the suffix appended to the username whenever LDAP lookups are performed.
     *
     * @param usernameSuffix the String to append to usernames for lookups
     */
    public void setUsernameSuffix(String usernameSuffix) {
        this.usernameSuffix = usernameSuffix;
        if (usernameSuffix == null) {
            properties.remove("ldap.usernameSuffix");
            this.usernameSuffix = "";
        }
        else {
            properties.put("ldap.usernameSuffix", usernameSuffix);
        }
    }

1085 1086 1087 1088
    /**
     * Returns the LDAP field name that the user's name is stored in. By default
     * this is "cn". Another common value is "displayName".
     *
Matt Tucker's avatar
Matt Tucker committed
1089
     * @return the LDAP field that that corresponds to the user's name.
1090 1091 1092 1093 1094 1095 1096 1097 1098
     */
    public String getNameField() {
        return nameField;
    }

    /**
     * Sets the LDAP field name that the user's name is stored in. By default
     * this is "cn". Another common value is "displayName".
     *
Matt Tucker's avatar
Matt Tucker committed
1099
     * @param nameField the LDAP field that that corresponds to the user's name.
1100 1101 1102 1103
     */
    public void setNameField(String nameField) {
        this.nameField = nameField;
        if (nameField == null) {
Matt Tucker's avatar
Matt Tucker committed
1104
            properties.remove("ldap.nameField");
1105 1106
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
1107
            properties.put("ldap.nameField", nameField);
1108 1109 1110 1111 1112 1113 1114
        }
    }

    /**
     * Returns the LDAP field name that the user's email address is stored in.
     * By default this is "mail".
     *
Matt Tucker's avatar
Matt Tucker committed
1115
     * @return the LDAP field that that corresponds to the user's email
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
     *      address.
     */
    public String getEmailField() {
        return emailField;
    }

    /**
     * Sets the LDAP field name that the user's email address is stored in.
     * By default this is "mail".
     *
Matt Tucker's avatar
Matt Tucker committed
1126
     * @param emailField the LDAP field that that corresponds to the user's
1127 1128 1129 1130 1131
     *      email address.
     */
    public void setEmailField(String emailField) {
        this.emailField = emailField;
        if (emailField == null) {
Matt Tucker's avatar
Matt Tucker committed
1132
            properties.remove("ldap.emailField");
1133 1134
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
1135
            properties.put("ldap.emailField", emailField);
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        }
    }

    /**
     * Returns the starting DN that searches for users will performed with.
     * Searches will performed on the entire sub-tree under the base DN.
     *
     * @return the starting DN used for performing searches.
     */
    public String getBaseDN() {
Austen Rustrum's avatar
Austen Rustrum committed
1146 1147 1148 1149
        if (encloseDNs)
            return getEnclosedDN(baseDN);
        else
            return baseDN;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    }

    /**
     * Sets the starting DN that searches for users will performed with.
     * Searches will performed on the entire sub-tree under the base DN.
     *
     * @param baseDN the starting DN used for performing searches.
     */
    public void setBaseDN(String baseDN) {
        this.baseDN = baseDN;
Matt Tucker's avatar
Matt Tucker committed
1160
        properties.put("ldap.baseDN", baseDN);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    }

    /**
     * Returns the alternate starting DN that searches for users will performed with.
     * Searches will performed on the entire sub-tree under the alternate base DN after
     * they are performed on the main base DN.
     *
     * @return the alternate starting DN used for performing searches. If no alternate
     *      DN is set, this method will return <tt>null</tt>.
     */
    public String getAlternateBaseDN() {
Austen Rustrum's avatar
Austen Rustrum committed
1172
        return getEnclosedDN(alternateBaseDN);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    }

    /**
     * Sets the alternate starting DN that searches for users will performed with.
     * Searches will performed on the entire sub-tree under the alternate base DN after
     * they are performed on the main base dn.
     *
     * @param alternateBaseDN the alternate starting DN used for performing searches.
     */
    public void setAlternateBaseDN(String alternateBaseDN) {
        this.alternateBaseDN = alternateBaseDN;
        if (alternateBaseDN == null) {
Matt Tucker's avatar
Matt Tucker committed
1185
            properties.remove("ldap.alternateBaseDN");
1186 1187
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
1188
            properties.put("ldap.alternateBaseDN", alternateBaseDN);
1189 1190 1191
        }
    }

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    /**
     * Returns the BaseDN for the given username.
     *
     * @param username username to return its base DN.
     * @return the BaseDN for the given username. If no baseDN is found,
     *         this method will return <tt>null</tt>.
     */
    public String getUsersBaseDN(String username) {
        try {
            findUserDN(username, baseDN);
            return baseDN;
        }
        catch (Exception e) {
            try {
                if (alternateBaseDN != null) {
                    findUserDN(username, alternateBaseDN);
                    return alternateBaseDN;
                }
            }
            catch (Exception ex) {
                Log.debug(ex);
            }
        }
        return null;
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    }

    /**
     * Returns the BaseDN for the given groupname.
     *
     * @param groupname groupname to return its base DN.
     * @return the BaseDN for the given groupname. If no baseDN is found,
     *         this method will return <tt>null</tt>.
     */
    public String getGroupsBaseDN(String groupname) {
        try {
            findGroupDN(groupname, baseDN);
            return baseDN;
        }
        catch (Exception e) {
            try {
                if (alternateBaseDN != null) {
                    findGroupDN(groupname, alternateBaseDN);
                    return alternateBaseDN;
                }
            }
            catch (Exception ex) {
                Log.debug(ex);
            }
        }
        return null;
1242 1243
    }

1244 1245 1246 1247 1248 1249 1250
    /**
     * Returns the starting admin DN that searches for admins will performed with.
     * Searches will performed on the entire sub-tree under the admin DN.
     *
     * @return the starting DN used for performing searches.
     */
    public String getAdminDN() {
Austen Rustrum's avatar
Austen Rustrum committed
1251 1252 1253 1254
        if (encloseDNs)
            return getEnclosedDN(adminDN);
        else
            return adminDN;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    }

    /**
     * Sets the starting admin DN that searches for admins will performed with.
     * Searches will performed on the entire sub-tree under the admins DN.
     *
     * @param adminDN the starting DN used for performing admin searches.
     */
    public void setAdminDN(String adminDN) {
        this.adminDN = adminDN;
Matt Tucker's avatar
Matt Tucker committed
1265
        properties.put("ldap.adminDN", adminDN);
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    }

    /**
     * Returns the starting admin DN that searches for admins will performed with.
     * Searches will performed on the entire sub-tree under the admin DN.
     *
     * @return the starting DN used for performing searches.
     */
    public String getAdminPassword() {
        return adminPassword;
    }

    /**
     * Sets the admin password for the LDAP server we're connecting to.
     *
     * @param adminPassword the admin password for the LDAP server we're
     * connecting to.
     */
    public void setAdminPassword(String adminPassword) {
        this.adminPassword = adminPassword;
Matt Tucker's avatar
Matt Tucker committed
1286
        properties.put("ldap.adminPassword", adminPassword);
1287 1288
    }

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    /**
     * Sets whether an LDAP connection pool should be used or not.
     *
     * @param connectionPoolEnabled true if an LDAP connection pool should be used.
     */
    public void setConnectionPoolEnabled(boolean connectionPoolEnabled) {
        this.connectionPoolEnabled = connectionPoolEnabled;
        properties.put("ldap.connectionPoolEnabled", Boolean.toString(connectionPoolEnabled));
    }

    /**
     * Returns whether an LDAP connection pool should be used or not.
     *
     * @return true if an LDAP connection pool should be used.
     */
    public boolean isConnectionPoolEnabled() {
        return connectionPoolEnabled;
    }

1308
    /**
1309 1310
     * Returns the filter used for searching the directory for users, which includes
     * the default filter (username field search) plus any custom-defined search filter.
1311 1312 1313 1314
     *
     * @return the search filter.
     */
    public String getSearchFilter() {
1315 1316 1317 1318 1319 1320 1321 1322 1323
        StringBuilder filter = new StringBuilder();
        if (searchFilter == null) {
            filter.append("(").append(usernameField).append("={0})");
        }
        else {
            filter.append("(&(").append(usernameField).append("={0})");
            filter.append(searchFilter).append(")");
        }
        return filter.toString();
1324 1325 1326
    }

    /**
1327
     * Sets the search filter appended to the default filter when searching for users.
1328
     *
1329 1330
     * @param searchFilter the search filter appended to the default filter
     *      when searching for users.
1331 1332
     */
    public void setSearchFilter(String searchFilter) {
1333
        this.searchFilter = searchFilter;
Matt Tucker's avatar
Matt Tucker committed
1334
        properties.put("ldap.searchFilter", searchFilter);
1335 1336
    }

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    /**
     * Returns true if the entire tree under the base DN will be searched (recursive search)
     * when doing LDAP queries (finding users, groups, etc). When false, only a single level
     * under the base DN will be searched. The default is <tt>true</tt> which is the best
     * option for most LDAP setups. In only a few cases will the directory be setup in such
     * a way that it's better to do single level searching.
     *
     * @return true if the entire tree under the base DN will be searched.
     */
    public boolean isSubTreeSearch() {
        return subTreeSearch;
    }

    /**
     * Sets whether the entire tree under the base DN will be searched (recursive search)
     * when doing LDAP queries (finding users, groups, etc). When false, only a single level
     * under the base DN will be searched. The default is <tt>true</tt> which is the best
     * option for most LDAP setups. In only a few cases will the directory be setup in such
     * a way that it's better to do single level searching.
     *
     * @param subTreeSearch true if the entire tree under the base DN will be searched.
     */
    public void setSubTreeSearch(boolean subTreeSearch) {
        this.subTreeSearch = subTreeSearch;
Matt Tucker's avatar
Matt Tucker committed
1361
        properties.put("ldap.subTreeSearch", String.valueOf(subTreeSearch));
1362 1363
    }

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    /**
     * Returns true if LDAP referrals will automatically be followed when found.
     *
     * @return true if LDAP referrals are automatically followed.
     */
    public boolean isFollowReferralsEnabled() {
        return followReferrals;
    }

    /**
     * Sets whether LDAP referrals should be automatically followed.
     *
     * @param followReferrals true if LDAP referrals should be automatically followed.
     */
    public void setFollowReferralsEnabled(boolean followReferrals) {
        this.followReferrals = followReferrals;
        properties.put("ldap.autoFollowReferrals", String.valueOf(followReferrals));
    }

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    /**
     * Returns true if LDAP alias referrals will automatically be followed when found.
     *
     * @return true if LDAP alias referrals are automatically followed.
     */
    public boolean isFollowAliasReferralsEnabled() {
        return followAliasReferrals;
    }

    /**
     * Sets whether LDAP alias referrals should be automatically followed.
     *
     * @param followAliasReferrals true if LDAP alias referrals should be automatically followed.
     */
    public void setFollowAliasReferralsEnabled(boolean followAliasReferrals) {
        this.followAliasReferrals = followAliasReferrals;
        properties.put("ldap.autoFollowAliasReferrals", String.valueOf(followAliasReferrals));
    }

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
    /**
     * Returns the field name used for groups.
     * Value of groupNameField defaults to "cn".
     *
     * @return the field used for groups.
     */
    public String getGroupNameField() {
        return groupNameField;
    }

    /**
     * Sets the field name used for groups.
     *
     * @param groupNameField the field used for groups.
     */
    public void setGroupNameField(String groupNameField) {
        this.groupNameField = groupNameField;
Matt Tucker's avatar
Matt Tucker committed
1419
        properties.put("ldap.groupNameField", groupNameField);
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    }

    /**
     * Return the field used to list members within a group.
     * Value of groupMemberField defaults to "member".
     *
     * @return the field used to list members within a group.
     */
    public String getGroupMemberField() {
        return groupMemberField;
    }

    /**
     * Sets the field used to list members within a group.
     * Value of groupMemberField defaults to "member".
     *
     * @param groupMemberField the field used to list members within a group.
     */
1438
    public void setGroupMemberField(String groupMemberField) {
1439
        this.groupMemberField = groupMemberField;
Matt Tucker's avatar
Matt Tucker committed
1440
        properties.put("ldap.groupMemberField", groupMemberField);
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    }

    /**
     * Return the field used to describe a group.
     * Value of groupDescriptionField defaults to "description".
     *
     * @return the field used to describe a group.
     */
    public String getGroupDescriptionField() {
        return groupDescriptionField;
    }

    /**
     * Sets the field used to describe a group.
     * Value of groupDescriptionField defaults to "description".
     *
     * @param groupDescriptionField the field used to describe a group.
     */
    public void setGroupDescriptionField(String groupDescriptionField) {
        this.groupDescriptionField = groupDescriptionField;
Matt Tucker's avatar
Matt Tucker committed
1461
        properties.put("ldap.groupDescriptionField", groupDescriptionField);
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    }

    /**
     * Return true if the LDAP server is operating in Posix mode. By default
     * false is returned. When in Posix mode, users are stored within a group
     * by their username alone. When not enabled, users are stored in a group using
     * their entire DN.
     *
     * @return true if posix mode is being used by the LDAP server.
     */
    public boolean isPosixMode() {
        return posixMode;
    }

    /**
     * Sets whether the LDAP server is operating in Posix mode. When in Posix mode,
     * users are stored within a group by their username alone. When not enabled,
     * users are stored in a group using their entire DN.
     *
     * @param posixMode true if posix mode is being used by the LDAP server.
     */
1483
    public void setPosixMode(boolean posixMode) {
1484
        this.posixMode = posixMode;
Matt Tucker's avatar
Matt Tucker committed
1485
        properties.put("ldap.posixMode", String.valueOf(posixMode));
1486 1487 1488
    }

    /**
1489 1490
     * Returns the filter used for searching the directory for groups, which includes
     * the default filter plus any custom-defined search filter.
1491
     *
1492
     * @return the search filter when searching for groups.
1493 1494
     */
    public String getGroupSearchFilter() {
1495 1496 1497 1498 1499 1500 1501 1502 1503
        StringBuilder groupFilter = new StringBuilder();
        if (groupSearchFilter == null) {
            groupFilter.append("(").append(groupNameField).append("={0})");
        }
        else {
            groupFilter.append("(&(").append(groupNameField).append("={0})");
            groupFilter.append(groupSearchFilter).append(")");
        }
        return groupFilter.toString();
1504 1505 1506
    }

    /**
1507
     * Sets the search filter appended to the default filter when searching for groups.
1508
     *
1509 1510
     * @param groupSearchFilter the search filter appended to the default filter
     *      when searching for groups.
1511 1512 1513
     */
    public void setGroupSearchFilter(String groupSearchFilter) {
        this.groupSearchFilter = groupSearchFilter;
Matt Tucker's avatar
Matt Tucker committed
1514
        properties.put("ldap.groupSearchFilter", groupSearchFilter);
1515
    }
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

    /**
     * Generic routine for retrieving a list of results from the LDAP server.  It's meant to be very
     * flexible so that just about any query for a list of results can make use of it without having
     * to reimplement their own calls to LDAP.  This routine also accounts for sorting settings,
     * paging settings, any other global settings, and alternate DNs.
     *
     * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
     * in the string before it is used as a string.
     *
     * @param attribute LDAP attribute to be pulled from each result and placed in the return results.
     *     Typically pulled from this manager.
     * @param searchFilter Filter to use to perform the search.  Typically pulled from this manager.
     * @param startIndex Number/index of first result to include in results.  (-1 for no limit)
     * @param numResults Number of results to include.  (-1 for no limit)
     * @param suffixToTrim An arbitrary string to trim from the end of every attribute returned.  null to disable.
     * @return A simple list of strings (that should be sorted) of the results.
     */
    public List<String> retrieveList(String attribute, String searchFilter, int startIndex, int numResults, String suffixToTrim) {
        List<String> results = new ArrayList<String>();
1536 1537 1538 1539 1540 1541
        int pageSize = -1;
        String pageSizeStr = properties.get("ldap.pagedResultsSize");
        if (pageSizeStr != null) pageSize = Integer.parseInt(pageSizeStr, -1);
        Boolean clientSideSort = false;
        String clientSideSortStr = properties.get("ldap.clientSideSorting");
        if (clientSideSortStr != null) clientSideSort = Boolean.valueOf(clientSideSortStr);
1542 1543 1544 1545 1546 1547
        LdapContext ctx = null;
        LdapContext ctx2 = null;
        try {
            ctx = getContext(baseDN);

            // Set up request controls, if appropriate.
1548
            List<Control> baseTmpRequestControls = new ArrayList<Control>();
1549 1550
            if (!clientSideSort) {
                // Server side sort on username field.
1551
                baseTmpRequestControls.add(new SortControl(new String[]{attribute}, Control.NONCRITICAL));
1552
            }
1553
            if (pageSize > 0) {
1554
                // Server side paging.
1555
                baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
1556
            }
1557 1558
            Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
            ctx.setRequestControls(baseRequestControls);
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { attribute });
            // If server side sort, we'll skip the initial ones we don't want, and stop when we've hit
            // the amount we do want.
            int skip = -1;
            int lastRes = -1;
            if (!clientSideSort) {
1574 1575 1576 1577 1578 1579
                if (startIndex != -1) {
                    skip = startIndex;
                }
                if (numResults != -1) {
                    lastRes = startIndex + numResults;
                }
1580
            }
1581
            byte[] cookie;
1582 1583 1584
            int count = 0;
            // Run through all pages of results (one page is also possible  ;)  )
            do {
1585
                cookie = null;
1586 1587 1588 1589 1590
                NamingEnumeration answer = ctx.search("", searchFilter, searchControls);

                // Examine all of the results on this page
                while (answer.hasMoreElements()) {
                    count++;
1591 1592
                    if (skip > 0 && count <= skip) {
                        answer.next();
1593 1594
                        continue;
                    }
1595 1596
                    if (lastRes != -1 && count > lastRes) {
                        answer.next();
1597 1598 1599 1600
                        break;
                    }

                    // Get the next result.
1601
                    String result = (String)((SearchResult)answer.next()).getAttributes().get(attribute).get();
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                    // Remove suffixToTrim if set
                    if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
                        result = result.substring(0,result.length()-suffixToTrim.length());
                    }
                    // Add this to the result.
                    results.add(result);
                }
                // Examine the paged results control response
                Control[] controls = ctx.getResponseControls();
                if (controls != null) {
                    for (Control control : controls) {
                        if (control instanceof PagedResultsResponseControl) {
1614
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
1615 1616 1617 1618 1619 1620
                            cookie = prrc.getCookie();
                        }
                    }
                }
                // Close the enumeration.
                answer.close();
1621
                // Re-activate paged results; affects nothing if no paging support
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                List<Control> tmpRequestControls = new ArrayList<Control>();
                if (!clientSideSort) {
                    // Server side sort on username field.
                    tmpRequestControls.add(new SortControl(new String[]{attribute}, Control.NONCRITICAL));
                }
                if (pageSize > 0) {
                    // Server side paging.
                    tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                }
                Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                ctx.setRequestControls(requestControls);
            } while (cookie != null && (lastRes == -1 || count <= lastRes));
1634 1635

            // Add groups found in alternate DN
1636
            if (alternateBaseDN != null && (lastRes == -1 || count <= lastRes)) {
1637
                ctx2 = getContext(alternateBaseDN);
1638
                ctx2.setRequestControls(baseRequestControls);
1639 1640 1641

                // Run through all pages of results (one page is also possible  ;)  )
                do {
1642 1643 1644
                    cookie = null;
                    NamingEnumeration answer = ctx2.search("", searchFilter, searchControls);

1645 1646 1647
                    // Examine all of the results on this page
                    while (answer.hasMoreElements()) {
                        count++;
1648 1649
                        if (skip > 0 && count <= skip) {
                            answer.next();
1650 1651
                            continue;
                        }
1652 1653
                        if (lastRes != -1 && count > lastRes) {
                            answer.next();
1654 1655 1656 1657
                            break;
                        }

                        // Get the next result.
1658
                        String result = (String)((SearchResult)answer.next()).getAttributes().get(attribute).get();
1659 1660 1661 1662 1663 1664 1665 1666
                        // Remove suffixToTrim if set
                        if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
                            result = result.substring(0,result.length()-suffixToTrim.length());
                        }
                        // Add this to the result.
                        results.add(result);
                    }
                    // Examine the paged results control response
1667
                    Control[] controls = ctx2.getResponseControls();
1668 1669 1670
                    if (controls != null) {
                        for (Control control : controls) {
                            if (control instanceof PagedResultsResponseControl) {
1671
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
1672 1673 1674 1675 1676 1677
                                cookie = prrc.getCookie();
                            }
                        }
                    }
                    // Close the enumeration.
                    answer.close();
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
                    // Re-activate paged results; affects nothing if no paging support
                    List<Control> tmpRequestControls = new ArrayList<Control>();
                    if (!clientSideSort) {
                        // Server side sort on username field.
                        tmpRequestControls.add(new SortControl(new String[]{attribute}, Control.NONCRITICAL));
                    }
                    if (pageSize > 0) {
                        // Server side paging.
                        tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                    }
                    Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                    ctx2.setRequestControls(requestControls);
                } while (cookie != null && (lastRes == -1 || count <= lastRes));
1691 1692
            }

1693
            // If client-side sorting is enabled, sort and trim.
1694 1695
            if (clientSideSort) {
                Collections.sort(results);
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
                if (startIndex != -1 || numResults != -1) {
                    if (startIndex == -1) {
                        startIndex = 0;
                    }
                    if (numResults == -1) {
                        numResults = results.size();
                    }
                    int endIndex = Math.min(startIndex + numResults, results.size()-1);
                    results = results.subList(startIndex, endIndex);
                }
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
                if (ctx2 != null) {
                    ctx2.setRequestControls(null);
                    ctx2.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return results;
    }

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    /**
     * Generic routine for retrieving the number of available results from the LDAP server that
     * match the passed search filter.  This routine also accounts for paging settings and
     * alternate DNs.
     *
     * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
     * in the string before it is used as a string.
     *
     * @param attribute LDAP attribute to be pulled from each result and used in the query.
     *     Typically pulled from this manager.
     * @param searchFilter Filter to use to perform the search.  Typically pulled from this manager.
     * @return The number of entries that match the filter.
     */
    public Integer retrieveListCount(String attribute, String searchFilter) {
1743 1744 1745
        int pageSize = -1;
        String pageSizeStr = properties.get("ldap.pagedResultsSize");
        if (pageSizeStr != null) pageSize = Integer.parseInt(pageSizeStr, -1);
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
        LdapContext ctx = null;
        LdapContext ctx2 = null;
        Integer count = 0;
        try {
            ctx = getContext(baseDN);

            // Set up request controls, if appropriate.
            List<Control> baseTmpRequestControls = new ArrayList<Control>();
            if (pageSize > 0) {
                // Server side paging.
                baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
            }
            Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
            ctx.setRequestControls(baseRequestControls);

            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { attribute });
            byte[] cookie;
            // Run through all pages of results (one page is also possible  ;)  )
            do {
                cookie = null;
                NamingEnumeration answer = ctx.search("", searchFilter, searchControls);

                // Examine all of the results on this page
                while (answer.hasMoreElements()) {
                    answer.next();
                    count++;
                }
                // Examine the paged results control response
                Control[] controls = ctx.getResponseControls();
                if (controls != null) {
                    for (Control control : controls) {
                        if (control instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                            cookie = prrc.getCookie();
                        }
                    }
                }
                // Close the enumeration.
                answer.close();
                // Re-activate paged results; affects nothing if no paging support
                List<Control> tmpRequestControls = new ArrayList<Control>();
                if (pageSize > 0) {
                    // Server side paging.
                    tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                }
                Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                ctx.setRequestControls(requestControls);
            } while (cookie != null);

            // Add groups found in alternate DN
            if (alternateBaseDN != null) {
                ctx2 = getContext(alternateBaseDN);
                ctx2.setRequestControls(baseRequestControls);

                // Run through all pages of results (one page is also possible  ;)  )
                do {
                    cookie = null;
                    NamingEnumeration answer = ctx2.search("", searchFilter, searchControls);

                    // Examine all of the results on this page
                    while (answer.hasMoreElements()) {
                        answer.next();
                        count++;
                    }
                    // Examine the paged results control response
                    Control[] controls = ctx2.getResponseControls();
                    if (controls != null) {
                        for (Control control : controls) {
                            if (control instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                                cookie = prrc.getCookie();
                            }
                        }
                    }
                    // Close the enumeration.
                    answer.close();
                    // Re-activate paged results; affects nothing if no paging support
                    List<Control> tmpRequestControls = new ArrayList<Control>();
                    if (pageSize > 0) {
                        // Server side paging.
                        tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                    }
                    Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                    ctx2.setRequestControls(requestControls);
                } while (cookie != null);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
                if (ctx2 != null) {
                    ctx2.setRequestControls(null);
                    ctx2.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return count;
    }
Austen Rustrum's avatar
Austen Rustrum committed
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

    /**
     * Encloses DN values with "
     *
     * @param dnValue the unenclosed value of a DN (e.g. ou=Jive Software\, Inc,dc=support,dc=jive,dc=com)
     * @return String the enclosed value of the DN (e.g. ou="Jive Software\, Inc",dc="support",dc="jive",dc="com")
     */
    private String getEnclosedDN(String dnValue) {
        if (dnValue == null || dnValue.equals("")) {
            return dnValue;
        }

        Matcher matcher = dnPattern.matcher(dnValue);
        dnValue = matcher.replaceAll("$1\"$2\"$3");
        dnValue = dnValue.replace("\\,", ",");

        return dnValue;
    }
1879
}