LdapGroupProvider.java 31.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/**
 * $RCSfile$
 * $Revision: 3191 $
 * $Date: 2005-12-12 13:41:22 -0300 (Mon, 12 Dec 2005) $
 *
 * Copyright (C) 2005 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

12
package org.jivesoftware.openfire.ldap;
13

14 15 16 17 18 19
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.group.Group;
import org.jivesoftware.openfire.group.GroupNotFoundException;
import org.jivesoftware.openfire.group.GroupProvider;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
20 21
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
22 23 24
import org.xmpp.packet.JID;

import javax.naming.NamingEnumeration;
25
import javax.naming.NamingException;
26
import javax.naming.directory.*;
27
import javax.naming.ldap.Control;
28 29
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
30
import javax.naming.ldap.SortControl;
31 32
import java.text.MessageFormat;
import java.util.*;
33 34
import java.util.regex.Matcher;
import java.util.regex.Pattern;
35 36

/**
37 38
 * LDAP implementation of the GroupProvider interface.  All data in the directory is treated as
 * read-only so any set operations will result in an exception.
39
 *
40
 * @author Matt Tucker, Greg Ferguson and Cameron Moore
41 42 43 44 45 46 47 48
 */
public class LdapGroupProvider implements GroupProvider {

    private LdapManager manager;
    private UserManager userManager;
    private String[] standardAttributes;

    /**
49
     * Constructs a new LDAP group provider.
50 51 52 53 54 55 56 57 58 59 60
     */
    public LdapGroupProvider() {
        manager = LdapManager.getInstance();
        userManager = UserManager.getInstance();
        standardAttributes = new String[3];
        standardAttributes[0] = manager.getGroupNameField();
        standardAttributes[1] = manager.getGroupDescriptionField();
        standardAttributes[2] = manager.getGroupMemberField();
    }

    /**
61
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
62 63 64 65 66 67 68 69 70
     *
     * @param name the name of the group to create.
     * @throws UnsupportedOperationException when called.
     */
    public Group createGroup(String name) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
71
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
72 73 74 75 76 77 78 79
     *
     * @param name the name of the group to delete
     * @throws UnsupportedOperationException when called.
     */
    public void deleteGroup(String name) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

80
    public Group getGroup(String groupName) throws GroupNotFoundException {
81
        Collection<Group> groups;
82
        LdapContext ctx = null;
83
        try {
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
            ctx = manager.getContext();

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(standardAttributes);
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), groupName);
            NamingEnumeration<SearchResult> answer = ctx.search("", filter, searchControls);

99
            groups = populateGroups(answer);
100 101
            // Close the enumeration.
            answer.close();
102
            if (groups.size() == 1) {
103 104
                return groups.iterator().next();
            }
105
        }
106
        catch (Exception e) {
107 108
            Log.error(e);
            throw new GroupNotFoundException(e);
Matt Tucker's avatar
Matt Tucker committed
109
        }
110 111 112 113 114 115 116 117 118 119
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
120
        }
121 122 123 124 125 126
        if (groups.size() > 1) {
            // If multiple groups found, throw exception.
            throw new GroupNotFoundException(
                    "Too many groups with name " + groupName + " were found.");
        }
        throw new GroupNotFoundException("Group with name " + groupName + " not found.");
127 128 129
    }

    /**
130
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
131 132 133 134 135 136 137 138 139 140
     *
     * @param oldName the current name of the group.
     * @param newName the desired new name of the group.
     * @throws UnsupportedOperationException when called.
     */
    public void setName(String oldName, String newName) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
141
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
142
     *
143
     * @param name the group name.
144 145 146
     * @param description the group description.
     * @throws UnsupportedOperationException when called.
     */
147
    public void setDescription(String name, String description)
148 149
            throws UnsupportedOperationException
    {
150 151 152 153 154
        throw new UnsupportedOperationException();
    }

    public int getGroupCount() {
        if (manager.isDebugEnabled()) {
155
            Log.debug("LdapGroupProvider: Trying to get the number of groups in the system.");
156 157
        }

158 159
        int count = 0;
        LdapContext ctx = null;
160
        try {
161
            ctx = manager.getContext();
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            while (answer.hasMoreElements()) {
                answer.next();
                count++;
            }
178 179
            // Close the enumeration.
            answer.close();
180
        }
181 182 183 184 185 186 187 188 189 190 191 192 193
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
194
        }
195

196 197 198
        return count;
    }

199 200 201
    public Collection<String> getGroupNames() {
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
202
        try {
203 204 205 206 207 208
            ctx = manager.getContext();
            // Sort on group name field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);
209

210 211 212 213
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
214 215
            }
            else {
216 217 218 219 220 221 222 223 224 225 226 227
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
228 229
            // Close the enumeration.
            answer.close();
230 231 232
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
233 234
            }
        }
235 236 237 238
        catch (Exception e) {
            Log.error(e);
        }
        finally {
239
            try {
240 241 242 243
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
244
            }
245 246
            catch (Exception ignored) {
                // Ignore.
247 248
            }
        }
249
        return groupNames;
250 251
    }

252 253 254
    public Collection<String> getGroupNames(int startIndex, int numResults) {
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
255
        try {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            ctx = manager.getContext();
            // Sort on group name field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");

Matt Tucker's avatar
Matt Tucker committed
274
            // TODO: used paged results if supported by LDAP server.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            for (int i=0; i < startIndex; i++) {
                if (answer.hasMoreElements()) {
                    answer.next();
                }
                else {
                    return Collections.emptyList();
                }
            }
            // Now read in desired number of results (or stop if we run out of results).
            for (int i = 0; i < numResults; i++) {
                if (answer.hasMoreElements()) {
                    // Get the next group.
                    String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                            manager.getGroupNameField()).get();
                    // Escape group name and add to results.
                    groupNames.add(JID.escapeNode(groupName));
                }
                else {
                    break;
                }
            }
297 298
            // Close the enumeration.
            answer.close();
299 300 301 302
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
303
        }
304
        catch (Exception e) {
305
            Log.error(e);
306
        }
307
        finally {
308
            try {
309 310 311
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
312 313
                }
            }
314
            catch (Exception ignored) {
315 316 317
                // Ignore.
            }
        }
318
        return groupNames;
319 320
    }

321
    public Collection<String> getGroupNames(JID user) {
322 323
        // Get DN of specified user
        XMPPServer server = XMPPServer.getInstance();
324
        String username;
325
        if (!manager.isPosixMode()) {
326 327 328 329 330
            // Check if the user exists (only if user is a local user)
            if (!server.isLocal(user)) {
                return Collections.emptyList();
            }
            username = JID.unescapeNode(user.getNode());
331
            try {
332
                username = manager.findUserDN(username) + "," + manager.getBaseDN();
333 334
            }
            catch (Exception e) {
335
                Log.error("Could not find user in LDAP " + username);
336
                return Collections.emptyList();
337 338
            }
        }
339 340 341
        else {
            username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString();
        }
342 343 344 345 346 347 348
        // Do nothing if the user is empty or null
        if (username == null || "".equals(username)) {
            return Collections.emptyList();
        }
        // Perform the LDAP query
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
349
        try {
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
            ctx = manager.getContext();
            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });

            StringBuilder filter = new StringBuilder();
            filter.append("(&");
            filter.append(MessageFormat.format(manager.getGroupSearchFilter(), "*"));
            filter.append("(").append(manager.getGroupMemberField()).append("=").append(username);
            filter.append("))");
367 368 369
            if (Log.isDebugEnabled()) {
                Log.debug("Trying to find group names for user: " + user + " using query: " + filter.toString());
            }
370 371 372 373 374 375 376 377 378 379 380 381 382 383
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
            // Close the enumeration.
            answer.close();
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
384
        }
385
        catch (Exception e) {
386
            Log.error("Error getting groups for user: " + user, e);
387
            return Collections.emptyList();
388 389 390 391 392 393 394 395 396 397 398 399 400
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return groupNames;
401 402 403
    }

    /**
404
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
405
     *
406 407
     * @param groupName name of a group.
     * @param user the JID of the user to add
408 409 410 411
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void addMember(String groupName, JID user, boolean administrator)
412 413
            throws UnsupportedOperationException
    {
414 415 416 417
        throw new UnsupportedOperationException();
    }

    /**
418
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
419
     *
420 421
     * @param groupName the naame of a group.
     * @param user the JID of the user with new privileges
422 423 424 425
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void updateMember(String groupName, JID user, boolean administrator)
426
            throws UnsupportedOperationException {
427 428 429 430
        throw new UnsupportedOperationException();
    }

    /**
431
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
432 433
     *
     * @param groupName the name of a group.
434
     * @param user the JID of the user to delete.
435 436
     * @throws UnsupportedOperationException when called.
     */
Matt Tucker's avatar
Matt Tucker committed
437
    public void deleteMember(String groupName, JID user) throws UnsupportedOperationException {
438 439 440 441
        throw new UnsupportedOperationException();
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
442
     * Returns true because LDAP groups are read-only.
443 444 445 446 447 448 449
     *
     * @return true because all LDAP functions are read-only.
     */
    public boolean isReadOnly() {
        return true;
    }

450
    public Collection<String> search(String query) {
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 477 478 479 480 481 482 483 484 485 486 487 488
        if (query == null || "".equals(query)) {
            return Collections.emptyList();
        }
        // Make the query be a wildcard search by default. So, if the user searches for
        // "Test", make the search be "Test*" instead.
        if (!query.endsWith("*")) {
            query = query + "*";
        }
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
        try {
            ctx = manager.getContext();
            // Sort on username field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            StringBuilder filter = new StringBuilder();
            filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
489 490
            // Close the enumeration.
            answer.close();
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
510
        return groupNames;
511 512
    }

513
    public Collection<String> search(String query, int startIndex, int numResults) {
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        if (query == null || "".equals(query)) {
            return Collections.emptyList();
        }
        // Make the query be a wildcard search by default. So, if the user searches for
        // "Test", make the search be "Test*" instead.
        if (!query.endsWith("*")) {
            query = query + "*";
        }
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
        try {
            ctx = manager.getContext();
            // Sort on username field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            StringBuilder filter = new StringBuilder();
            filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");

Matt Tucker's avatar
Matt Tucker committed
545
            // TODO: used paged results if supported by LDAP server.
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            for (int i=0; i < startIndex; i++) {
                if (answer.hasMoreElements()) {
                    answer.next();
                }
                else {
                    return Collections.emptyList();
                }
            }
            // Now read in desired number of results (or stop if we run out of results).
            for (int i = 0; i < numResults; i++) {
                if (answer.hasMoreElements()) {
                    // Get the next group.
                    String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                            manager.getGroupNameField()).get();
                    // Escape group name and add to results.
                    groupNames.add(JID.escapeNode(groupName));
                }
                else {
                    break;
                }
            }
568 569
            // Close the enumeration.
            answer.close();
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
589
        return groupNames;
590 591 592 593 594 595
    }

    public boolean isSearchSupported() {
        return true;
    }

596
    /**
597
     * An auxilary method used to populate LDAP groups based on a provided LDAP search result.
598 599 600
     *
     * @param answer LDAP search result.
     * @return a collection of groups.
601
     * @throws javax.naming.NamingException
602
     */
603
    private Collection<Group> populateGroups(Enumeration<SearchResult> answer) throws NamingException {
604
        if (manager.isDebugEnabled()) {
605
            Log.debug("LdapGroupProvider: Starting to populate groups with users.");
606
        }
607
        DirContext ctx = null;
608
        try {
609 610
            TreeMap<String, Group> groups = new TreeMap<String, Group>();

611
            ctx = manager.getContext();
612

613
            SearchControls searchControls = new SearchControls();
614
            searchControls.setReturningAttributes(new String[] { manager.getUsernameField() });
615 616 617 618 619 620 621
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
622

623
            XMPPServer server = XMPPServer.getInstance();
624
            String serverName = server.getServerInfo().getXMPPDomain();
625 626 627 628 629 630
            // Build 3 groups.
            // group 1: uid=
            // group 2: rest of the text until first comma
            // group 3: rest of the text
            Pattern pattern =
                    Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
631

632 633
            while (answer.hasMoreElements()) {
                String name = "";
634
                try {
635 636 637
                    Attributes a = answer.nextElement().getAttributes();
                    String description;
                    try {
638
                        name = ((String)((a.get(manager.getGroupNameField())).get()));
639
                        description =
640
                                ((String)((a.get(manager.getGroupDescriptionField())).get()));
641 642 643 644
                    }
                    catch (Exception e) {
                        description = "";
                    }
645 646 647 648 649 650 651 652 653 654 655 656 657 658
                    Set<JID> members = new TreeSet<JID>();
                    Attribute memberField = a.get(manager.getGroupMemberField());
                    if (memberField != null) {
                        NamingEnumeration ne = memberField.getAll();
                        while (ne.hasMore()) {
                            String username = (String) ne.next();
                            // If not posix mode, each group member is stored as a full DN.
                            if (!manager.isPosixMode()) {
                                try {
                                    // Try to find the username with a regex pattern match.
                                    Matcher matcher = pattern.matcher(username);
                                    if (matcher.matches() && matcher.groupCount() == 3) {
                                        // The username is in the DN, no additional search needed
                                        username = matcher.group(2);
659
                                    }
660 661 662 663
                                    // The regex pattern match failed. This will happen if the
                                    // the member DN's don't use the standard username field. For
                                    // example, Active Directory has a username field of
                                    // sAMAccountName, but stores group members as "CN=...".
664
                                    else {
665 666 667 668 669 670 671 672 673 674 675 676
                                        // Create an LDAP name with the full DN.
                                        LdapName ldapName = new LdapName(username);
                                        // Turn the LDAP name into something we can use in a
                                        // search by stripping off the comma.
                                        String userDNPart = ldapName.get(ldapName.size() - 1);
                                        NamingEnumeration usrAnswer = ctx.search("",
                                                userDNPart, searchControls);
                                        if (usrAnswer.hasMoreElements()) {
                                            username = (String) ((SearchResult) usrAnswer.next())
                                                    .getAttributes().get(
                                                    manager.getUsernameField()).get();
                                        }
677 678
                                        // Close the enumeration.
                                        usrAnswer.close();
679
                                    }
680
                                }
681 682
                                catch (Exception e) {
                                    Log.error(e);
683 684
                                }
                            }
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
                            // A search filter may have been defined in the LdapUserProvider.
                            // Therefore, we have to try to load each user we found to see if
                            // it passes the filter.
                            try {
                                JID userJID;
                                int position = username.indexOf("@" + serverName);
                                // Create JID of local user if JID does not match a component's JID
                                if (position == -1) {
                                    // In order to lookup a username from the manager, the username
                                    // must be a properly escaped JID node.
                                    String escapedUsername = JID.escapeNode(username);
                                    if (!escapedUsername.equals(username)) {
                                        // Check if escaped username is valid
                                        userManager.getUser(escapedUsername);
                                    }
                                    // No exception, so the user must exist. Add the user as a group
                                    // member using the escaped username.
                                    userJID = server.createJID(escapedUsername, null);
703
                                }
704 705 706 707 708 709 710
                                else {
                                    // This is a JID of a component or node of a server's component
                                    String node = username.substring(0, position);
                                    String escapedUsername = JID.escapeNode(node);
                                    userJID = new JID(escapedUsername + "@" + serverName);
                                }
                                members.add(userJID);
711
                            }
712 713 714 715 716
                            catch (UserNotFoundException e) {
                                // We can safely ignore this error. It likely means that
                                // the user didn't pass the search filter that's defined.
                                // So, we want to simply ignore the user as a group member.
                                if (manager.isDebugEnabled()) {
717
                                    Log.debug("LdapGroupProvider: User not found: " + username);
718
                                }
719 720
                            }
                        }
721 722
                        // Close the enumeration.
                        ne.close();
723
                    }
724
                    if (manager.isDebugEnabled()) {
725
                        Log.debug("LdapGroupProvider: Adding group \"" + name + "\" with " + members.size() +
726
                                " members.");
727
                    }
728 729 730
                    Collection<JID> admins = Collections.emptyList();
                    Group group = new Group(name, description, members, admins);
                    groups.put(name, group);
731 732
                }
                catch (Exception e) {
733
                    e.printStackTrace();
734
                    if (manager.isDebugEnabled()) {
735
                        Log.debug("LdapGroupProvider: Error while populating group, " + name + ".", e);
736 737
                    }
                }
738 739
            }
            if (manager.isDebugEnabled()) {
740
                Log.debug("LdapGroupProvider: Finished populating group(s) with users.");
741 742 743 744 745 746 747 748
            }

            return groups.values();
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.close();
749 750 751
                }
            }
            catch (Exception e) {
752
                // Ignore.
753 754 755 756
            }
        }
    }
}