LdapGroupProvider.java 21.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * $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.
 */

package org.jivesoftware.wildfire.ldap;

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

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

/**
34 35
 * 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.
36 37 38 39 40 41 42 43 44 45 46 47
 *
 * @author Greg Ferguson and Cameron Moore
 */
public class LdapGroupProvider implements GroupProvider {

    private LdapManager manager;
    private UserManager userManager;
    private int groupCount;
    private long expiresStamp;
    private String[] standardAttributes;

    /**
48
     * Constructor of the LdapGroupProvider class. Gets an LdapManager instance from the LdapManager class.
49 50 51 52 53 54 55 56 57 58 59 60 61
     */
    public LdapGroupProvider() {
        manager = LdapManager.getInstance();
        userManager = UserManager.getInstance();
        groupCount = -1;
        expiresStamp = System.currentTimeMillis();
        standardAttributes = new String[3];
        standardAttributes[0] = manager.getGroupNameField();
        standardAttributes[1] = manager.getGroupDescriptionField();
        standardAttributes[2] = manager.getGroupMemberField();
    }

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

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

    public Group getGroup(String group) throws GroupNotFoundException {
        String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
        String searchFilter = "(&" + filter + "(" +
                manager.getGroupNameField() + "=" + group + "))";
85 86 87 88 89 90 91 92
        Collection<Group> groups;
        try {
            groups = populateGroups(searchForGroups(searchFilter, standardAttributes));
        }
        catch (NamingException e) {
            Log.error("Error populating groups from LDAP", e);
            throw new GroupNotFoundException("Error populating groups from LDAP", e);
        }
93
        if (groups.size() > 1) {
Matt Tucker's avatar
Matt Tucker committed
94
            // If multiple groups found, throw exception.
95 96
            throw new GroupNotFoundException("Too many groups with name " + group + " were found.");
        }
Matt Tucker's avatar
Matt Tucker committed
97 98 99 100 101
        else if (groups.isEmpty()) {
            throw new GroupNotFoundException("Group with name " + group + " not found.");
        }
        else {
            return groups.iterator().next();
102 103 104 105
        }
    }

    /**
106
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
107 108 109 110 111 112 113 114 115 116
     *
     * @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();
    }

    /**
117
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
118
     *
119
     * @param name the group name.
120 121 122
     * @param description the group description.
     * @throws UnsupportedOperationException when called.
     */
123 124
    public void setDescription(String name, String description)
            throws UnsupportedOperationException {
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        throw new UnsupportedOperationException();
    }

    public int getGroupCount() {
        // Cache group count for 5 minutes.
        if (groupCount != -1 && System.currentTimeMillis() < expiresStamp) {
            return groupCount;
        }
        int count = 0;

        if (manager.isDebugEnabled()) {
            Log.debug("Trying to get the number of groups in the system.");
        }

        String searchFilter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
        String returningAttributes[] = {manager.getGroupNameField()};
141 142 143 144 145 146 147 148 149
        try {
            NamingEnumeration<SearchResult> answer = searchForGroups(searchFilter, returningAttributes);
            for (; answer.hasMoreElements(); count++) {
                try {
                    answer.next();
                }
                catch (Exception e) {
                    // Ignore.
                }
150 151
            }

152 153 154 155 156 157
            this.groupCount = count;
            this.expiresStamp = System.currentTimeMillis() + JiveConstants.MINUTE * 5;
        }
        catch (NamingException ex) {
            Log.error("Error searching for groups in LDAP", ex);
        }
158 159 160 161 162
        return count;
    }

    public Collection<Group> getGroups() {
        String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
163 164 165 166 167 168
        try {
            return populateGroups(searchForGroups(filter, standardAttributes));
        }
        catch (NamingException ex) {
            return Collections.emptyList();
        }
169 170
    }

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 213 214 215 216 217 218 219
    public Collection<Group> getGroups(Set<String> groupNames) {
        if (groupNames.isEmpty()) {
            return Collections.emptyList();
        }
        Collection<Group> groups = new ArrayList<Group>(groupNames.size());

        String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
        // Instead of loading all groups at once which may not work for super big collections
        // of group names, we are going to make many queries and load by 10 groups at onces
        Collection<String> searchFilters = new ArrayList<String>(groupNames.size());
        List<String> names = new ArrayList<String>(groupNames);
        int i = 0;
        int range = 10;
        do {
            List<String> subset = names.subList(i, Math.min(i + range, groupNames.size()));

            if (subset.size() == 1) {
                String searchFilter = "(&" + filter + "(" +
                        manager.getGroupNameField() + "=" + subset.get(0) + "))";
                searchFilters.add(searchFilter);
            }
            else {
                StringBuilder sb = new StringBuilder(300);
                sb.append("(&").append(filter).append("(|");
                for (String groupName : subset) {
                    sb.append("(").append(manager.getGroupNameField()).append("=");
                    sb.append(groupName).append(")");
                }
                sb.append("))");
                searchFilters.add(sb.toString());
            }
            // Increment counter to get next range
            i = i + range;
        }
        while (groupNames.size() > i);

        // Perform all required queries to load all requested groups
        for (String searchFilter : searchFilters) {
            try {
                groups.addAll(populateGroups(searchForGroups(searchFilter, standardAttributes)));
            }
            catch (NamingException e) {
                Log.error("Error populating groups from LDAP", e);
                return Collections.emptyList();
            }
        }
        return new ArrayList<Group>(groups);
    }

220 221 222
    public Collection<Group> getGroups(int start, int num) {
        // Get an enumeration of all groups in the system
        String searchFilter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
223 224 225 226 227 228 229 230
        NamingEnumeration<SearchResult> answer;
        try {
            answer = searchForGroups(searchFilter, standardAttributes);
        }
        catch (NamingException e) {
            Log.error("Error searching for groups in LDAP", e);
            return Collections.emptyList();
        }
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

        // Place all groups that are wanted into an enumeration
        Vector<SearchResult> v = new Vector<SearchResult>();
        for (int i = 1; answer.hasMoreElements() && i <= (start + num); i++) {
            try {
                SearchResult sr = answer.next();
                if (i >= start) {
                    v.add(sr);
                }
            }
            catch (Exception e) {
                // Ignore.
            }
        }

246 247 248 249 250 251 252
        try {
            return populateGroups(v.elements());
        }
        catch (NamingException e) {
            Log.error("Error populating groups recieved from LDAP", e);
            return Collections.emptyList();
        }
253 254 255 256
    }

    public Collection<Group> getGroups(JID user) {
        XMPPServer server = XMPPServer.getInstance();
257
        String username;
258
        if (!manager.isPosixMode()) {
259 260 261 262 263
            // Check if the user exists (only if user is a local user)
            if (!server.isLocal(user)) {
                return Collections.emptyList();
            }
            username = JID.unescapeNode(user.getNode());
264
            try {
265
                username = manager.findUserDN(username) + "," + manager.getBaseDN();
266 267
            }
            catch (Exception e) {
268
                Log.error("Could not find user in LDAP " + username);
269
                return Collections.emptyList();
270 271
            }
        }
272 273 274
        else {
            username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString();
        }
275 276

        String filter = MessageFormat.format(manager.getGroupSearchFilter(), username);
277 278 279 280 281 282 283
        try {
            return populateGroups(searchForGroups(filter, standardAttributes));
        }
        catch (NamingException e) {
            Log.error("Error populating groups recieved from LDAP", e);
            return Collections.emptyList();
        }
284 285 286
    }

    /**
287
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
288
     *
289 290
     * @param groupName name of a group.
     * @param user the JID of the user to add
291 292 293 294
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void addMember(String groupName, JID user, boolean administrator)
295
            throws UnsupportedOperationException {
296 297 298 299
        throw new UnsupportedOperationException();
    }

    /**
300
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
301
     *
302 303
     * @param groupName the naame of a group.
     * @param user the JID of the user with new privileges
304 305 306 307
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void updateMember(String groupName, JID user, boolean administrator)
308
            throws UnsupportedOperationException {
309 310 311 312
        throw new UnsupportedOperationException();
    }

    /**
313
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
314 315
     *
     * @param groupName the name of a group.
316
     * @param user the JID of the user to delete.
317 318
     * @throws UnsupportedOperationException when called.
     */
Matt Tucker's avatar
Matt Tucker committed
319
    public void deleteMember(String groupName, JID user) throws UnsupportedOperationException {
320 321 322 323
        throw new UnsupportedOperationException();
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
324
     * Returns true because LDAP groups are read-only.
325 326 327 328 329 330 331 332
     *
     * @return true because all LDAP functions are read-only.
     */
    public boolean isReadOnly() {
        return true;
    }

    /**
333
     * An auxilary method used to perform LDAP queries based on a provided LDAP search filter.
334 335 336 337 338
     *
     * @param searchFilter LDAP search filter used to query.
     * @return an enumeration of SearchResult.
     */
    private NamingEnumeration<SearchResult> searchForGroups(String searchFilter,
339 340
            String[] returningAttributes) throws NamingException
    {
341 342 343
        if (manager.isDebugEnabled()) {
            Log.debug("Trying to find all groups in the system.");
        }
344 345
        DirContext ctx = null;
        NamingEnumeration<SearchResult> answer;
346 347 348 349 350 351 352 353 354 355
        try {
            ctx = manager.getContext();
            if (manager.isDebugEnabled()) {
                Log.debug("Starting LDAP search...");
                Log.debug("Using groupSearchFilter: " + searchFilter);
            }

            // Search for the dn based on the groupname.
            SearchControls searchControls = new SearchControls();
            searchControls.setReturningAttributes(returningAttributes);
356 357 358 359 360 361 362
            // 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);
            }
363 364 365 366 367
            answer = ctx.search("", searchFilter, searchControls);

            if (manager.isDebugEnabled()) {
                Log.debug("... search finished");
            }
368 369

            return answer;
370
        }
371 372 373 374 375 376 377
        finally {
            if (ctx != null) {
                try {
                    ctx.close();
                }
                catch (Exception ex) { /* do nothing */ }
            }
378 379 380 381
        }
    }

    /**
382
     * An auxilary method used to populate LDAP groups based on a provided LDAP search result.
383 384 385 386
     *
     * @param answer LDAP search result.
     * @return a collection of groups.
     */
387
    private Collection<Group> populateGroups(Enumeration<SearchResult> answer) throws NamingException {
388 389 390
        if (manager.isDebugEnabled()) {
            Log.debug("Starting to populate groups with users.");
        }
391
        DirContext ctx = null;
392
        try {
393 394
            TreeMap<String, Group> groups = new TreeMap<String, Group>();

395
            ctx = manager.getContext();
396

397 398 399 400 401 402 403 404 405
            SearchControls searchControls = new SearchControls();
            searchControls.setReturningAttributes(new String[]{manager.getUsernameField()});
            // 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);
            }
406

407 408 409
            String userSearchFilter = MessageFormat.format(manager.getSearchFilter(), "*");
            XMPPServer server = XMPPServer.getInstance();
            String serverName = server.getServerInfo().getName();
410 411 412 413 414 415
            // 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() + "=)([^,]+)(.+)");
416

417 418
            while (answer.hasMoreElements()) {
                String name = "";
419
                try {
420 421 422
                    Attributes a = answer.nextElement().getAttributes();
                    String description;
                    try {
423
                        name = ((String)((a.get(manager.getGroupNameField())).get()));
424
                        description =
425
                                ((String)((a.get(manager.getGroupDescriptionField())).get()));
426 427 428 429 430 431 432 433
                    }
                    catch (Exception e) {
                        description = "";
                    }
                    TreeSet<JID> members = new TreeSet<JID>();
                    Attribute member = a.get(manager.getGroupMemberField());
                    NamingEnumeration ne = member.getAll();
                    while (ne.hasMore()) {
434
                        String username = (String) ne.next();
435 436
                        if (!manager.isPosixMode()) {   //userName is full dn if not posix
                            try {
437 438 439 440 441 442
                                // LdapName will not generate spaces around an '='
                                // (according to the docs)
                                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);
443 444
                                }
                                else {
445 446 447 448 449 450 451 452
                                    // We have to do a new search to find the username field

                                    // Get the CN using LDAP
                                    LdapName ldapname = new LdapName(username);
                                    String ldapcn = ldapname.get(ldapname.size() - 1);
                                    String combinedFilter =
                                            "(&(" + ldapcn + ")" + userSearchFilter + ")";
                                    NamingEnumeration usrAnswer =
453
                                            ctx.search("", combinedFilter, searchControls);
454 455 456 457 458 459 460 461
                                    if (usrAnswer.hasMoreElements()) {
                                        username = (String) ((SearchResult) usrAnswer.next())
                                                .getAttributes().get(
                                                manager.getUsernameField()).get();
                                    }
                                    else {
                                        throw new UserNotFoundException();
                                    }
462 463 464 465 466 467 468 469 470 471 472
                                }
                            }
                            catch (Exception e) {
                                if (manager.isDebugEnabled()) {
                                    Log.debug("Error populating user with DN: " + username, e);
                                }
                            }
                        }
                        // 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.
473
                        try {
474 475 476 477 478 479
                            JID userJID;
                            // Create JID of local user if JID does not match a component's JID
                            if (!username.contains(serverName)) {
                                // In order to lookup a username from the manager, the username
                                // must be a properly escaped JID node.
                                String escapedUsername = JID.escapeNode(username);
480 481 482 483
                                if (!escapedUsername.equals(username)) {
                                    // Check if escaped username is valid
                                    userManager.getUser(escapedUsername);
                                }
484 485 486
                                // No exception, so the user must exist. Add the user as a group
                                // member using the escaped username.
                                userJID = server.createJID(escapedUsername, null);
487 488
                            }
                            else {
489 490
                                // This is a JID of a component or node of a server's component
                                userJID = new JID(username);
491
                            }
492
                            members.add(userJID);
493
                        }
494
                        catch (UserNotFoundException e) {
495
                            if (manager.isDebugEnabled()) {
496
                                Log.debug("User not found: " + username);
497 498 499
                            }
                        }
                    }
500 501 502
                    if (manager.isDebugEnabled()) {
                        Log.debug("Adding group \"" + name + "\" with " + members.size() +
                                " members.");
503
                    }
504 505 506 507 508 509
                    Group g = new Group(name, description, members, new ArrayList<JID>());
                    groups.put(name, g);
                }
                catch (Exception e) {
                    if (manager.isDebugEnabled()) {
                        Log.debug("Error while populating group, " + name + ".", e);
510 511
                    }
                }
512 513 514 515 516 517 518 519 520 521 522
            }
            if (manager.isDebugEnabled()) {
                Log.debug("Finished populating group(s) with users.");
            }

            return groups.values();
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.close();
523 524 525
                }
            }
            catch (Exception e) {
526
                // Ignore.
527 528 529 530
            }
        }
    }
}