Roster.java 52.4 KB
Newer Older
1 2
/**
 * $RCSfile$
3 4
 * $Revision: $
 * $Date: $
5
 *
6
 * Copyright (C) 2007 Jive Software. All rights reserved.
7 8 9 10 11
 *
 * 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.roster;
13

14
import org.jivesoftware.database.JiveID;
15 16 17 18 19 20 21 22 23
import org.jivesoftware.openfire.*;
import org.jivesoftware.openfire.group.Group;
import org.jivesoftware.openfire.group.GroupManager;
import org.jivesoftware.openfire.privacy.PrivacyList;
import org.jivesoftware.openfire.privacy.PrivacyListManager;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserNameManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
Gaston Dombiak's avatar
Gaston Dombiak committed
24 25 26 27 28
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
import org.jivesoftware.util.cache.ExternalizableUtil;
29 30 31
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Presence;
32

Gaston Dombiak's avatar
Gaston Dombiak committed
33 34 35 36
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>A roster is a list of users that the user wishes to know if they are online.</p>
 * <p>Rosters are similar to buddy groups in popular IM clients. The Roster class is
 * a representation of the roster data.<p/>
 *
 * <p>Updates to this roster is effectively a change to the user's roster. To reflect this,
 * the changes to this class will automatically update the persistently stored roster, as well as
 * send out update announcements to all logged in user sessions.</p>
 *
 * @author Gaston Dombiak
 */
@JiveID(JiveConstants.ROSTER)
Gaston Dombiak's avatar
Gaston Dombiak committed
52
public class Roster implements Cacheable, Externalizable {
53 54

    /**
55
     * Roster item cache - table: key jabberid string; value roster item.
56 57
     */
    protected ConcurrentHashMap<String, RosterItem> rosterItems = new ConcurrentHashMap<String, RosterItem>();
58 59
    /**
     * Contacts with subscription FROM that only exist due to shared groups
60
     * key: jabberid string; value: groups why the implicit roster item exists (aka invisibleSharedGroups).
61
     */
62
    protected ConcurrentHashMap<String, Set<String>> implicitFrom = new ConcurrentHashMap<String, Set<String>>();
63 64 65 66 67 68 69 70 71 72 73 74 75

    private RosterItemProvider rosterItemProvider;
    private String username;
    private SessionManager sessionManager;
    private XMPPServer server = XMPPServer.getInstance();
    private RoutingTable routingTable;
    private PresenceManager presenceManager;
    /**
     * Note: Used only for shared groups logic.
     */
    private RosterManager rosterManager;


Gaston Dombiak's avatar
Gaston Dombiak committed
76 77 78 79 80 81
    /**
     * Constructor added for Externalizable. Do not use this constructor.
     */
    public Roster() {
    }

82
    /**
83
     * Create a roster for the given user, pulling the existing roster items
84
     * out of the backend storage provider. The roster will also include items that
85
     * belong to the user's shared groups.<p>
86
     *
87
     * RosterItems that ONLY belong to shared groups won't be persistent unless the user
88
     * explicitly subscribes to the contact's presence, renames the contact in his roster or adds
89 90 91
     * the item to a personal group.<p>
     *
     * This constructor is not public and instead you should use
92
     * {@link org.jivesoftware.openfire.roster.RosterManager#getRoster(String)}.
93 94 95
     *
     * @param username The username of the user that owns this roster
     */
96
    Roster(String username) {
97 98 99
        presenceManager = XMPPServer.getInstance().getPresenceManager();
        rosterManager = XMPPServer.getInstance().getRosterManager();
        sessionManager = SessionManager.getInstance();
Gaston Dombiak's avatar
Gaston Dombiak committed
100
        routingTable = XMPPServer.getInstance().getRoutingTable();
101 102 103
        this.username = username;

        // Get the shared groups of this user
104
        Collection<Group> sharedGroups = rosterManager.getSharedGroups(username);
105
        Collection<Group> userGroups = GroupManager.getInstance().getGroups(getUserJID());
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

        // Add RosterItems that belong to the personal roster
        rosterItemProvider =  RosterItemProvider.getInstance();
        Iterator items = rosterItemProvider.getItems(username);
        while (items.hasNext()) {
            RosterItem item = (RosterItem)items.next();
            // Check if the item (i.e. contact) belongs to a shared group of the user. Add the
            // shared group (if any) to this item
            for (Group group : sharedGroups) {
                if (group.isUser(item.getJid())) {
                    // TODO Group name conflicts are not being considered (do we need this?)
                    item.addSharedGroup(group);
                    item.setSubStatus(RosterItem.SUB_BOTH);
                }
            }
            rosterItems.put(item.getJid().toBareJID(), item);
        }
        // Add RosterItems that belong only to shared groups
        Map<JID,List<Group>> sharedUsers = getSharedUsers(sharedGroups);
        for (JID jid : sharedUsers.keySet()) {
            try {
                Collection<Group> itemGroups = new ArrayList<Group>();
128
                String nickname = "";
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
                RosterItem item = new RosterItem(jid, RosterItem.SUB_TO, RosterItem.ASK_NONE,
                        RosterItem.RECV_NONE, nickname , null);
                // Add the shared groups to the new roster item
                for (Group group : sharedUsers.get(jid)) {
                    if (group.isUser(jid)) {
                        item.addSharedGroup(group);
                        itemGroups.add(group);
                    }
                    else {
                        item.addInvisibleSharedGroup(group);
                    }
                }
                // Set subscription type to BOTH if the roster user belongs to a shared group
                // that is mutually visible with a shared group of the new roster item
                if (rosterManager.hasMutualVisibility(username, userGroups, jid, itemGroups)) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
                }
                else {
                    // Set subscription type to FROM if the contact does not belong to any of
                    // the associated shared groups
                    boolean belongsToGroup = false;
                    for (Group group : sharedUsers.get(jid)) {
                        if (group.isUser(jid)) {
                            belongsToGroup = true;
                        }
                    }
                    if (!belongsToGroup) {
                        item.setSubStatus(RosterItem.SUB_FROM);
                    }
                }
159 160 161 162 163 164 165 166 167 168
                // Set nickname and store in memory only if subscription type is not FROM.
                // Roster items with subscription type FROM that exist only because of shared
                // groups will be recreated on demand in #getRosterItem(JID) and #isRosterItem()
                // but will never be stored in memory nor in the database. This is an important
                // optimization to reduce objects in memory and avoid loading users in memory
                // to get their nicknames that will never be shown
                if (item.getSubStatus() != RosterItem.SUB_FROM) {
                    item.setNickname(UserNameManager.getUserName(jid));
                    rosterItems.put(item.getJid().toBareJID(), item);
                }
169 170
                else {
                    // Cache information about shared contacts with subscription status FROM
171 172
                    implicitFrom
                            .put(item.getJid().toBareJID(), item.getInvisibleSharedGroupsNames());
173
                }
174 175 176 177 178 179 180
            }
            catch (UserNotFoundException e) {
                Log.error("Groups (" + sharedUsers.get(jid) + ") include non-existent username (" +
                        jid.getNode() +
                        ")");
            }
        }
181 182
        // Fire event indicating that a roster has just been loaded
        RosterEventDispatcher.rosterLoaded(this);
183 184 185 186 187 188 189 190 191
    }

    /**
     * Returns true if the specified user is a member of the roster, false otherwise.
     *
     * @param user the user object to check.
     * @return true if the specified user is a member of the roster, false otherwise.
     */
    public boolean isRosterItem(JID user) {
192 193 194
        // Optimization: Check if the contact has a FROM subscription due to shared groups
        // (only when not present in the rosterItems collection)
        return rosterItems.containsKey(user.toBareJID()) || getImplicitRosterItem(user) != null;
195 196 197
    }

    /**
198 199 200 201
     * Returns a collection of users in this roster.<p>
     *
     * Note: Roster items with subscription type FROM that exist only because of shared groups
     * are not going to be returned.
202 203 204 205 206 207 208 209
     *
     * @return a collection of users in this roster.
     */
    public Collection<RosterItem> getRosterItems() {
        return Collections.unmodifiableCollection(rosterItems.values());
    }

    /**
210 211
     * Returns the roster item that is associated with the specified JID. If no roster item
     * was found then a UserNotFoundException will be thrown.
212 213
     *
     * @param user the XMPPAddress for the roster item to retrieve
214 215
     * @return The roster item associated with the user XMPPAddress.
     * @throws UserNotFoundException if no roster item was found for the specified JID.
216 217 218 219
     */
    public RosterItem getRosterItem(JID user) throws UserNotFoundException {
        RosterItem item = rosterItems.get(user.toBareJID());
        if (item == null) {
220 221 222 223 224
            // Optimization: Check if the contact has a FROM subscription due to shared groups
            item = getImplicitRosterItem(user);
            if (item == null) {
                throw new UserNotFoundException(user.toBareJID());
            }
225 226 227 228
        }
        return item;
    }

229 230 231 232 233 234 235 236 237 238 239 240
    /**
     * Returns a roster item if the specified user has a subscription of type FROM to this
     * user and the susbcription only exists due to some shared groups or otherwise
     * <tt>null</tt>. This method assumes that this user does not have a subscription to
     * the contact. In other words, this method will not check if there should be a subscription
     * of type TO ot BOTH.
     *
     * @param user the contact to check if he is subscribed to the presence of this user.
     * @return a roster item if the specified user has a subscription of type FROM to this
     *         user and the susbcription only exists due to some shared groups or otherwise null.
     */
    private RosterItem getImplicitRosterItem(JID user) {
241 242 243
        Set<String> invisibleSharedGroups = implicitFrom.get(user.toBareJID());
        if (invisibleSharedGroups != null) {
            RosterItem rosterItem = new RosterItem(user, RosterItem.SUB_FROM, RosterItem.ASK_NONE,
244
                    RosterItem.RECV_NONE, "", null);
245 246
            rosterItem.setInvisibleSharedGroupsNames(invisibleSharedGroups);
            return rosterItem;
247 248 249 250
        }
        return null;
    }

251 252 253 254
    /**
     * Create a new item to the roster. Roster items may not be created that contain the same user
     * address as an existing item.
     *
255 256 257
     * @param user       The item to add to the roster.
     * @param push       True if the new item must be pushed to the user.
     * @param persistent True if the new roster item should be persisted to the DB.
258
     */
259 260 261
    public RosterItem createRosterItem(JID user, boolean push, boolean persistent)
            throws UserAlreadyExistsException, SharedGroupException {
        return createRosterItem(user, null, null, push, persistent);
262 263 264 265 266 267
    }

    /**
     * Create a new item to the roster. Roster items may not be created that contain the same user
     * address as an existing item.
     *
268 269 270 271
     * @param user       The item to add to the roster.
     * @param nickname   The nickname for the roster entry (can be null).
     * @param push       True if the new item must be push to the user.
     * @param persistent True if the new roster item should be persisted to the DB.
272 273
     * @param groups   The list of groups to assign this roster item to (can be null)
     */
274 275
    public RosterItem createRosterItem(JID user, String nickname, List<String> groups, boolean push,
                                       boolean persistent)
276
            throws UserAlreadyExistsException, SharedGroupException {
277
        return provideRosterItem(user, nickname, groups, push, persistent);
278 279 280 281 282 283 284 285 286 287 288
    }

    /**
     * Create a new item to the roster based as a copy of the given item.
     * Roster items may not be created that contain the same user address
     * as an existing item in the roster.
     *
     * @param item the item to copy and add to the roster.
     */
    public void createRosterItem(org.xmpp.packet.Roster.Item item)
            throws UserAlreadyExistsException, SharedGroupException {
289
        provideRosterItem(item.getJID(), item.getName(), new ArrayList<String>(item.getGroups()), true, true);
290 291 292
    }

    /**
293
     * Generate a new RosterItem for use with createRosterItem.
294
     *
295 296 297 298 299
     * @param user       The roster jid address to create the roster item for.
     * @param nickname   The nickname to assign the item (or null for none).
     * @param groups     The groups the item belongs to (or null for none).
     * @param push       True if the new item must be push to the user.
     * @param persistent True if the new roster item should be persisted to the DB.
300 301
     * @return The newly created roster items ready to be stored by the Roster item's hash table
     */
302
    protected RosterItem provideRosterItem(JID user, String nickname, List<String> groups,
303 304
                                           boolean push, boolean persistent)
            throws UserAlreadyExistsException, SharedGroupException {
305 306
        if (groups != null && !groups.isEmpty()) {
            // Raise an error if the groups the item belongs to include a shared group
307
            Collection<Group> sharedGroups = GroupManager.getInstance().getSharedGroups();
308 309 310 311 312 313 314 315 316 317 318 319 320
            for (String group : groups) {
                for (Group sharedGroup : sharedGroups) {
                    if (group.equals(sharedGroup.getProperties().get("sharedRoster.displayName"))) {
                        throw new SharedGroupException("Cannot add an item to a shared group");
                    }
                }
            }
        }
        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
        roster.setType(IQ.Type.set);
        org.xmpp.packet.Roster.Item item = roster.addItem(user, nickname, null,
                org.xmpp.packet.Roster.Subscription.none, groups);

321
        RosterItem rosterItem = new RosterItem(item);
322 323 324
        // Fire event indicating that a roster item is about to be added
        persistent = RosterEventDispatcher.addingContact(this, rosterItem, persistent);

325 326 327 328
        // Check if we need to make the new roster item persistent
        if (persistent) {
            rosterItemProvider.createItem(username, rosterItem);
        }
329

330 331 332 333
        if (push) {
            // Broadcast the roster push to the user
            broadcast(roster);
        }
334

335 336
        rosterItems.put(user.toBareJID(), rosterItem);

337 338 339
        // Fire event indicating that a roster item has been added
        RosterEventDispatcher.contactAdded(this, rosterItem);

340 341 342 343 344 345 346 347 348 349
        return rosterItem;
    }

    /**
     * Update an item that is already in the roster.
     *
     * @param item the item to update in the roster.
     * @throws UserNotFoundException If the roster item for the given user doesn't already exist
     */
    public void updateRosterItem(RosterItem item) throws UserNotFoundException {
350 351 352 353
        // Check if we need to convert an implicit roster item into an explicit one
        if (implicitFrom.remove(item.getJid().toBareJID()) != null) {
            // Ensure that the item is an explicit roster item
            rosterItems.put(item.getJid().toBareJID(), item);
354 355
            // Fire event indicating that a roster item has been updated
            RosterEventDispatcher.contactUpdated(this, item);
356
        }
357 358
        if (rosterItems.putIfAbsent(item.getJid().toBareJID(), item) == null) {
            rosterItems.remove(item.getJid().toBareJID());
359 360 361 362
            if (item.getSubStatus() != RosterItem.SUB_NONE) {
                throw new UserNotFoundException(item.getJid().toBareJID());
            }
            return;
363
        }
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        // Check if the item is not persistent
        if (item.getID() == 0) {
            // Make the item persistent if a new nickname has been set for a shared contact
            if (item.isShared()) {
                // Do nothing if item is only shared and it is using the default user name
                if (item.isOnlyShared()) {
                    String defaultContactName;
                    try {
                        defaultContactName = UserNameManager.getUserName(item.getJid());
                    }
                    catch (UserNotFoundException e) {
                        // Cannot update a roster item for a local user that does not exist
                        defaultContactName = item.getNickname();
                    }
                    if (defaultContactName.equals(item.getNickname())) {
                        return;
                    }
381
                }
382 383
                try {
                    rosterItemProvider.createItem(username, item);
384
                }
385 386
                catch (UserAlreadyExistsException e) {
                    // Do nothing. We shouldn't be here.
387
                }
388
            }
389 390
            else {
                // Item is not persistent and it does not belong to a shared contact so do nothing
391 392 393 394 395 396 397
            }
        }
        else {
            // Update the backend data store
            rosterItemProvider.updateItem(username, item);
        }
        // broadcast roster update
398 399
        // Do not push items with a state of "None + Pending In"
        if (item.getSubStatus() != RosterItem.SUB_NONE ||
400
                item.getRecvStatus() != RosterItem.RECV_SUBSCRIBE) {
401
            broadcast(item, true);
402
        }
403 404 405
        /*if (item.getSubStatus() == RosterItem.SUB_BOTH || item.getSubStatus() == RosterItem.SUB_TO) {
            probePresence(item.getJid());
        }*/
406 407
        // Fire event indicating that a roster item has been updated
        RosterEventDispatcher.contactUpdated(this, item);
408 409 410 411 412 413 414 415 416 417 418 419 420
    }

    /**
     * Remove a user from the roster.
     *
     * @param user the user to remove from the roster.
     * @param doChecking flag that indicates if checkings should be done before deleting the user.
     * @return The roster item being removed or null if none existed
     * @throws SharedGroupException if the user to remove belongs to a shared group
     */
    public RosterItem deleteRosterItem(JID user, boolean doChecking) throws SharedGroupException {
        // Answer an error if user (i.e. contact) to delete belongs to a shared group
        RosterItem itemToRemove = rosterItems.get(user.toBareJID());
421
        if (doChecking && itemToRemove != null && !itemToRemove.getSharedGroups().isEmpty()) {
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
            throw new SharedGroupException("Cannot remove contact that belongs to a shared group");
        }

        if (itemToRemove != null) {
            RosterItem.SubType subType = itemToRemove.getSubStatus();

            // Cancel any existing presence subscription between the user and the contact
            if (subType == RosterItem.SUB_TO || subType == RosterItem.SUB_BOTH) {
                Presence presence = new Presence();
                presence.setFrom(server.createJID(username, null));
                presence.setTo(itemToRemove.getJid());
                presence.setType(Presence.Type.unsubscribe);
                server.getPacketRouter().route(presence);
            }

            // cancel any existing presence subscription between the contact and the user
            if (subType == RosterItem.SUB_FROM || subType == RosterItem.SUB_BOTH) {
                Presence presence = new Presence();
                presence.setFrom(server.createJID(username, null));
                presence.setTo(itemToRemove.getJid());
                presence.setType(Presence.Type.unsubscribed);
                server.getPacketRouter().route(presence);
            }

            // If removing the user was successful, remove the user from the subscriber list:
            RosterItem item = rosterItems.remove(user.toBareJID());

            if (item != null) {
                // Delete the item from the provider if the item is persistent. RosteItems that only
                // belong to shared groups won't be persistent
                if (item.getID() > 0) {
                    // If removing the user was successful, remove the user from the backend store
                    rosterItemProvider.deleteItem(username, item.getID());
                }

                // Broadcast the update to the user
                org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
                roster.setType(IQ.Type.set);
                roster.addItem(user, org.xmpp.packet.Roster.Subscription.remove);
                broadcast(roster);
462 463
                // Fire event indicating that a roster item has been deleted
                RosterEventDispatcher.contactDeleted(this, item);
464 465 466 467
            }

            return item;
        }
468 469 470
        else {
            // Verify if the item being removed is an implicit roster item
            // that only exists due to some shared group
471 472 473
            RosterItem item = getImplicitRosterItem(user);
            if (item != null) {
                implicitFrom.remove(user.toBareJID());
474 475 476 477 478 479 480 481
                // If the contact being removed is not a local user then ACK unsubscription
                if (!server.isLocal(user)) {
                    Presence presence = new Presence();
                    presence.setFrom(server.createJID(username, null));
                    presence.setTo(user);
                    presence.setType(Presence.Type.unsubscribed);
                    server.getPacketRouter().route(presence);
                }
482 483
                // Fire event indicating that a roster item has been deleted
                RosterEventDispatcher.contactDeleted(this, item);
484 485
            }
        }
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

        return null;
    }

    /**
     * <p>Return the username of the user or chatbot that owns this roster.</p>
     *
     * @return the username of the user or chatbot that owns this roster
     */
    public String getUsername() {
        return username;
    }

    /**
     * <p>Obtain a 'roster reset', a snapshot of the full cached roster as an Roster.</p>
     *
     * @return The roster reset (snapshot) as an Roster
     */
    public org.xmpp.packet.Roster getReset() {
        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();

        // Add the roster items (includes the personal roster and shared groups) to the answer
        for (RosterItem item : rosterItems.values()) {
            // Do not include items with status FROM that exist only because of shared groups
            if (item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
                continue;
            }
            org.xmpp.packet.Roster.Ask ask = getAskStatus(item.getAskStatus());
            org.xmpp.packet.Roster.Subscription sub = org.xmpp.packet.Roster.Subscription.valueOf(item.getSubStatus()
                    .getName());
            // Set the groups to broadcast (include personal and shared groups)
            List<String> groups = new ArrayList<String>(item.getGroups());
            if (groups.contains(null)) {
                Log.warn("A group is null in roster item: " + item.getJid() + " of user: " +
                        getUsername());
            }
            for (Group sharedGroup : item.getSharedGroups()) {
                String displayName = sharedGroup.getProperties().get("sharedRoster.displayName");
                if (displayName != null) {
                    groups.add(displayName);
                }
                else {
                    // Do not add the shared group if it does not have a displayName. 
                    Log.warn("Found shared group: " + sharedGroup.getName() +
                            " with no displayName");
                }
            }
533 534
            // Do not push items with a state of "None + Pending In"
            if (item.getSubStatus() != RosterItem.SUB_NONE ||
535
                    item.getRecvStatus() != RosterItem.RECV_SUBSCRIBE) {
536
                roster.addItem(item.getJid(), item.getNickname(), ask, sub, groups);
537
            }
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        }
        return roster;
    }

    private org.xmpp.packet.Roster.Ask getAskStatus(RosterItem.AskType askType) {
        if (askType == null || "".equals(askType.getName())) {
            return null;
        }
        return org.xmpp.packet.Roster.Ask.valueOf(askType.getName());
    }

    /**
     * <p>Broadcast the presence update to all subscribers of the roter.</p>
     * <p/>
     * <p>Any presence change typically results in a broadcast to the roster members.</p>
     *
     * @param packet The presence packet to broadcast
     */
    public void broadcastPresence(Presence packet) {
        if (routingTable == null) {
            return;
        }
560 561
        // Get the privacy list of this user
        PrivacyList list = null;
562 563
        JID from = packet.getFrom();
        if (from != null) {
564 565
            // Try to use the active list of the session. If none was found then try to use
            // the default privacy list of the session
566
            ClientSession session = sessionManager.getSession(from);
567 568 569 570 571 572 573 574 575
            if (session != null) {
                list = session.getActiveList();
                list = list == null ? session.getDefaultList() : list;
            }
        }
        if (list == null) {
            // No privacy list was found (based on the session) so check if there is a default list
            list = PrivacyListManager.getInstance().getDefaultPrivacyList(username);
        }
576
        // Broadcast presence to subscribed entities
577
        for (RosterItem item : rosterItems.values()) {
Gaston Dombiak's avatar
Gaston Dombiak committed
578
            if (item.getSubStatus() == RosterItem.SUB_BOTH || item.getSubStatus() == RosterItem.SUB_FROM) {
579
                packet.setTo(item.getJid());
580 581 582 583
                if (list != null && list.shouldBlockPacket(packet)) {
                    // Outgoing presence notifications are blocked for this contact
                    continue;
                }
Gaston Dombiak's avatar
Gaston Dombiak committed
584 585
                JID searchNode = new JID(item.getJid().getNode(), item.getJid().getDomain(), null, true);
                for (JID jid : routingTable.getRoutes(searchNode)) {
586
                    try {
Gaston Dombiak's avatar
Gaston Dombiak committed
587
                        routingTable.routePacket(jid, packet, false);
588 589
                    }
                    catch (Exception e) {
590 591
                        // Theoretically only happens if session has been closed.
                        Log.debug(e);
592 593 594 595
                    }
                }
            }
        }
596 597 598 599 600 601 602
        // Broadcast presence to shared contacts whose subscription status is FROM
        for (String contact : implicitFrom.keySet()) {
            packet.setTo(contact);
            if (list != null && list.shouldBlockPacket(packet)) {
                // Outgoing presence notifications are blocked for this contact
                continue;
            }
Gaston Dombiak's avatar
Gaston Dombiak committed
603
            for (JID jid: routingTable.getRoutes(new JID(contact))) {
604
                try {
Gaston Dombiak's avatar
Gaston Dombiak committed
605
                    routingTable.routePacket(jid, packet, false);
606 607 608 609 610 611 612
                }
                catch (Exception e) {
                    // Theoretically only happens if session has been closed.
                    Log.debug(e);
                }
            }
        }
613 614 615 616
        if (from != null) {
            // Broadcast presence to other user's resources
            sessionManager.broadcastPresenceToOtherResources(from, packet);
        }
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    }

    /**
     * Returns the list of users that belong ONLY to a shared group of this user. If the contact
     * belongs to the personal roster and a shared group then it wont' be included in the answer.
     *
     * @param sharedGroups the shared groups of this user.
     * @return the list of users that belong ONLY to a shared group of this user.
     */
    private Map<JID,List<Group>> getSharedUsers(Collection<Group> sharedGroups) {
        // Get the users to process from the shared groups. Users that belong to different groups
        // will have one entry in the map associated with all the groups
        Map<JID,List<Group>> sharedGroupUsers = new HashMap<JID,List<Group>>();
        for (Group group : sharedGroups) {
            // Get all the users that should be in this roster
            Collection<JID> users = rosterManager.getSharedUsersForRoster(group, this);
            // Add the users of the group to the general list of users to process
634
            JID userJID = getUserJID();
635 636 637
            for (JID jid : users) {
                // Add the user to the answer if the user doesn't belong to the personal roster
                // (since we have already added the user to the answer)
638 639
                boolean isRosterItem = rosterItems.containsKey(jid.toBareJID());
                if (!isRosterItem && !userJID.equals(jid)) {
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
                    List<Group> groups = sharedGroupUsers.get(jid);
                    if (groups == null) {
                        groups = new ArrayList<Group>();
                        sharedGroupUsers.put(jid, groups);
                    }
                    groups.add(group);
                }
            }
        }
        return sharedGroupUsers;
    }

    private void broadcast(org.xmpp.packet.Roster roster) {
        JID recipient = server.createJID(username, null);
        roster.setTo(recipient);
        if (sessionManager == null) {
            sessionManager = SessionManager.getInstance();
        }
658
        sessionManager.userBroadcast(username, roster);
659 660 661 662 663 664 665 666 667 668 669 670
    }

    /**
     * Broadcasts the RosterItem to all the connected resources of this user. Due to performance
     * optimizations and due to some clients errors that are showing items with subscription status
     * FROM we added a flag that indicates if a roster items that exists only because of a shared
     * group with subscription status FROM will not be sent.
     *
     * @param item     the item to broadcast.
     * @param optimize true indicates that items that exists only because of a shared
     *                 group with subscription status FROM will not be sent
     */
671
    public void broadcast(RosterItem item, boolean optimize) {
672 673 674 675 676 677 678
        // Do not broadcast items with status FROM that exist only because of shared groups
        if (optimize && item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
            return;
        }
        // Set the groups to broadcast (include personal and shared groups)
        List<String> groups = new ArrayList<String>(item.getGroups());
        for (Group sharedGroup : item.getSharedGroups()) {
Gaston Dombiak's avatar
Gaston Dombiak committed
679 680 681 682
            String displayName = sharedGroup.getProperties().get("sharedRoster.displayName");
            if (displayName != null) {
                groups.add(displayName);
            }
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
        }

        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
        roster.setType(IQ.Type.set);
        roster.addItem(item.getJid(), item.getNickname(),
                getAskStatus(item.getAskStatus()),
                org.xmpp.packet.Roster.Subscription.valueOf(item.getSubStatus().getName()),
                groups);
        broadcast(roster);
    }

    /**
     * Sends a presence probe to the probee for each connected resource of this user.
     */
    private void probePresence(JID probee) {
        for (ClientSession session : sessionManager.getSessions(username)) {
            presenceManager.probePresence(session.getAddress(), probee);
        }
    }

    public int getCachedSize() {
        // Approximate the size of the object in bytes by calculating the size
        // of each field.
        int size = 0;
        size += CacheSizes.sizeOfObject();                           // overhead of object
        size += CacheSizes.sizeOfCollection(rosterItems.values());   // roster item cache
        size += CacheSizes.sizeOfString(username);                   // username
        return size;
    }

    /**
     * Update the roster since a group user has been added to a shared group. Create a new
     * RosterItem if the there doesn't exist an item for the added user. The new RosterItem won't be
     * saved to the backend store unless the user explicitly subscribes to the contact's presence,
     * renames the contact in his roster or adds the item to a personal group. Otherwise the shared
     * group will be added to the shared groups lists. In any case an update broadcast will be sent
     * to all the users logged resources.
     *
     * @param group the shared group where the user was added.
     * @param addedUser the contact to update in the roster.
     */
    void addSharedUser(Group group, JID addedUser) {
        boolean newItem = false;
        RosterItem item = null;
        try {
            // Get the RosterItem for the *local* user to add
            item = getRosterItem(addedUser);
            // Do nothing if the item already includes the shared group
            if (item.getSharedGroups().contains(group)) {
                return;
            }
            newItem = false;
        }
        catch (UserNotFoundException e) {
            try {
                // Create a new RosterItem for this new user
739
                String nickname = UserNameManager.getUserName(addedUser);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 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
                item =
                        new RosterItem(addedUser, RosterItem.SUB_BOTH, RosterItem.ASK_NONE,
                                RosterItem.RECV_NONE, nickname, null);
                // Add the new item to the list of items
                rosterItems.put(item.getJid().toBareJID(), item);
                newItem = true;
            }
            catch (UserNotFoundException ex) {
                Log.error("Group (" + group.getName() + ") includes non-existent username (" +
                        addedUser +
                        ")");
            }
        }

        // If an item already exists then take note of the old subscription status
        RosterItem.SubType prevSubscription = null;
        if (!newItem) {
            prevSubscription = item.getSubStatus();
        }

        // Update the subscription of the item **based on the item groups**
        Collection<Group> userGroups = GroupManager.getInstance().getGroups(getUserJID());
        Collection<Group> sharedGroups = new ArrayList<Group>();
        sharedGroups.addAll(item.getSharedGroups());
        // Add the new group to the list of groups to check
        sharedGroups.add(group);
        // Set subscription type to BOTH if the roster user belongs to a shared group
        // that is mutually visible with a shared group of the new roster item
        if (rosterManager.hasMutualVisibility(getUsername(), userGroups, addedUser, sharedGroups)) {
            item.setSubStatus(RosterItem.SUB_BOTH);
        }
        // Update the subscription status depending on the group membership of the new
        // user and this user
        else if (group.isUser(addedUser) && !group.isUser(getUsername())) {
            item.setSubStatus(RosterItem.SUB_TO);
        }
        else if (!group.isUser(addedUser) && group.isUser(getUsername())) {
            item.setSubStatus(RosterItem.SUB_FROM);
        }

        // Add the shared group to the list of shared groups
        if (item.getSubStatus() != RosterItem.SUB_FROM) {
            item.addSharedGroup(group);
        }
        else {
            item.addInvisibleSharedGroup(group);
        }

        // If the item already exists then check if the subscription status should be
        // changed to BOTH based on the old and new subscription status
        if (prevSubscription != null) {
            if (prevSubscription == RosterItem.SUB_TO &&
                    item.getSubStatus() == RosterItem.SUB_FROM) {
                item.setSubStatus(RosterItem.SUB_BOTH);
            }
            else if (prevSubscription == RosterItem.SUB_FROM &&
                    item.getSubStatus() == RosterItem.SUB_TO) {
                item.setSubStatus(RosterItem.SUB_BOTH);
            }
        }

801 802 803 804
        // Optimization: Check if we do not need to keep the item in memory
        if (item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
            // Remove from memory and do nothing else
            rosterItems.remove(item.getJid().toBareJID());
805
            // Cache information about shared contacts with subscription status FROM
806
            implicitFrom.put(item.getJid().toBareJID(), item.getInvisibleSharedGroupsNames());
807 808
        }
        else {
809 810
            // Remove from list of shared contacts with status FROM (if any)
            implicitFrom.remove(item.getJid().toBareJID());
811 812
            // Ensure that the item is an explicit roster item
            rosterItems.put(item.getJid().toBareJID(), item);
813 814 815 816 817 818 819
            // Brodcast to all the user resources of the updated roster item
            broadcast(item, true);
            // Probe the presence of the new group user
            if (item.getSubStatus() == RosterItem.SUB_BOTH ||
                    item.getSubStatus() == RosterItem.SUB_TO) {
                probePresence(item.getJid());
            }
820
        }
821 822 823 824 825 826 827 828
        if (newItem) {
            // Fire event indicating that a roster item has been added
            RosterEventDispatcher.contactAdded(this, item);
        }
        else {
            // Fire event indicating that a roster item has been updated
            RosterEventDispatcher.contactUpdated(this, item);
        }
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    }

    /**
     * Adds a new contact that belongs to a certain list of groups to the roster. Depending on
     * the contact's groups and this user's groups, the presence subscription of the roster item may
     * vary.
     *
     * @param addedUser the new contact to add to the roster
     * @param groups the groups where the contact is a member
     */
    void addSharedUser(JID addedUser, Collection<Group> groups, Group addedGroup) {
        boolean newItem = false;
        RosterItem item = null;
        try {
            // Get the RosterItem for the *local* user to add
            item = getRosterItem(addedUser);
            newItem = false;
        }
        catch (UserNotFoundException e) {
            try {
                // Create a new RosterItem for this new user
850
                String nickname = UserNameManager.getUserName(addedUser);
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 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
                item =
                        new RosterItem(addedUser, RosterItem.SUB_BOTH, RosterItem.ASK_NONE,
                                RosterItem.RECV_NONE, nickname, null);
                // Add the new item to the list of items
                rosterItems.put(item.getJid().toBareJID(), item);
                newItem = true;
            }
            catch (UserNotFoundException ex) {
                Log.error("Couldn't find a user with username (" + addedUser + ")");
            }
        }
        // Update the subscription of the item **based on the item groups**
        Collection<Group> userGroups = GroupManager.getInstance().getGroups(getUserJID());
        // Set subscription type to BOTH if the roster user belongs to a shared group
        // that is mutually visible with a shared group of the new roster item
        if (rosterManager.hasMutualVisibility(getUsername(), userGroups, addedUser, groups)) {
            item.setSubStatus(RosterItem.SUB_BOTH);
            for (Group group : groups) {
                if (rosterManager.isGroupVisible(group, getUserJID())) {
                    // Add the shared group to the list of shared groups
                    item.addSharedGroup(group);
                }
            }
            // Add to the item the groups of this user that generated a FROM subscription
            // Note: This FROM subscription is overridden by the BOTH subscription but in
            // fact there is a TO-FROM relation between these two users that ends up in a
            // BOTH subscription
            for (Group group : userGroups) {
                if (!group.isUser(addedUser) && rosterManager.isGroupVisible(group, addedUser)) {
                    // Add the shared group to the list of invisible shared groups
                    item.addInvisibleSharedGroup(group);
                }
            }
        }
        else {
            // If an item already exists then take note of the old subscription status
            RosterItem.SubType prevSubscription = null;
            if (!newItem) {
                prevSubscription = item.getSubStatus();
            }

            // Assume by default that the contact has subscribed from the presence of
            // this user
            item.setSubStatus(RosterItem.SUB_FROM);
            // Check if the user may see the new contact in a shared group
            for (Group group : groups) {
                if (rosterManager.isGroupVisible(group, getUserJID())) {
                    // Add the shared group to the list of shared groups
                    item.addSharedGroup(group);
                    item.setSubStatus(RosterItem.SUB_TO);
                }
            }
            if (item.getSubStatus() == RosterItem.SUB_FROM) {
                item.addInvisibleSharedGroup(addedGroup);
            }

            // If the item already exists then check if the subscription status should be
            // changed to BOTH based on the old and new subscription status
            if (prevSubscription != null) {
                if (prevSubscription == RosterItem.SUB_TO &&
                        item.getSubStatus() == RosterItem.SUB_FROM) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
                }
                else if (prevSubscription == RosterItem.SUB_FROM &&
                        item.getSubStatus() == RosterItem.SUB_TO) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
                }
            }
        }
920 921 922 923
        // Optimization: Check if we do not need to keep the item in memory
        if (item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
            // Remove from memory and do nothing else
            rosterItems.remove(item.getJid().toBareJID());
924
            // Cache information about shared contacts with subscription status FROM
925
            implicitFrom.put(item.getJid().toBareJID(), item.getInvisibleSharedGroupsNames());
926 927
        }
        else {
928 929
            // Remove from list of shared contacts with status FROM (if any)
            implicitFrom.remove(item.getJid().toBareJID());
930 931
            // Ensure that the item is an explicit roster item
            rosterItems.put(item.getJid().toBareJID(), item);
932 933 934 935 936 937 938
            // Brodcast to all the user resources of the updated roster item
            broadcast(item, true);
            // Probe the presence of the new group user
            if (item.getSubStatus() == RosterItem.SUB_BOTH ||
                    item.getSubStatus() == RosterItem.SUB_TO) {
                probePresence(item.getJid());
            }
939
        }
940 941 942 943 944 945 946 947
        if (newItem) {
            // Fire event indicating that a roster item has been added
            RosterEventDispatcher.contactAdded(this, item);
        }
        else {
            // Fire event indicating that a roster item has been updated
            RosterEventDispatcher.contactUpdated(this, item);
        }
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    }

    /**
     * Update the roster since a group user has been deleted from a shared group. If the RosterItem
     * (of the deleted contact) exists only because of of the sahred group then the RosterItem will
     * be deleted physically from the backend store. Otherwise the shared group will be removed from
     * the shared groups lists. In any case an update broadcast will be sent to all the users
     * logged resources.
     *
     * @param sharedGroup the shared group from where the user was deleted.
     * @param deletedUser the contact to update in the roster.
     */
    void deleteSharedUser(Group sharedGroup, JID deletedUser) {
        try {
            // Get the RosterItem for the *local* user to remove
            RosterItem item = getRosterItem(deletedUser);
            int groupSize = item.getSharedGroups().size() + item.getInvisibleSharedGroups().size();
            if (item.isOnlyShared() && groupSize == 1) {
                // Do nothing if the existing shared group is not the sharedGroup to remove
967 968
                if (!item.getSharedGroups().contains(sharedGroup) &&
                        !item.getInvisibleSharedGroups().contains(sharedGroup)) {
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                    return;
                }
                // Delete the roster item from the roster since it exists only because of this
                // group which is being removed
                deleteRosterItem(deletedUser, false);
            }
            else {
                // Remove the removed shared group from the list of shared groups
                item.removeSharedGroup(sharedGroup);
                // Update the subscription of the item based on the remaining groups
                if (item.isOnlyShared()) {
                    Collection<Group> userGroups =
                            GroupManager.getInstance().getGroups(getUserJID());
                    Collection<Group> sharedGroups = new ArrayList<Group>();
                    sharedGroups.addAll(item.getSharedGroups());
                    // Set subscription type to BOTH if the roster user belongs to a shared group
                    // that is mutually visible with a shared group of the new roster item
                    if (rosterManager.hasMutualVisibility(getUsername(), userGroups, deletedUser,
                            sharedGroups)) {
                        item.setSubStatus(RosterItem.SUB_BOTH);
                    }
                    else if (item.getSharedGroups().isEmpty() &&
                            !item.getInvisibleSharedGroups().isEmpty()) {
                        item.setSubStatus(RosterItem.SUB_FROM);
                    }
                    else {
                        item.setSubStatus(RosterItem.SUB_TO);
                    }
                }
                // Brodcast to all the user resources of the updated roster item
                broadcast(item, false);
            }
        }
        catch (SharedGroupException e) {
            // Do nothing. Checkings are disabled so this exception should never happen.
        }
        catch (UserNotFoundException e) {
            // Do nothing since the contact does not exist in the user's roster. (strange case!)
        }
    }

1010
    void deleteSharedUser(JID deletedUser, Group deletedGroup) {
1011 1012 1013 1014 1015 1016 1017 1018
        try {
            // Get the RosterItem for the *local* user to remove
            RosterItem item = getRosterItem(deletedUser);
            int groupSize = item.getSharedGroups().size() + item.getInvisibleSharedGroups().size();
            if (item.isOnlyShared() && groupSize == 1 &&
                    // Do not delete the item if deletedUser belongs to a public group since the
                    // subcription status will change
                    !(deletedGroup.isUser(deletedUser) &&
Gaston Dombiak's avatar
Gaston Dombiak committed
1019
                    RosterManager.isPublicSharedGroup(deletedGroup))) {
1020 1021 1022 1023 1024 1025 1026 1027
                // Delete the roster item from the roster since it exists only because of this
                // group which is being removed
                deleteRosterItem(deletedUser, false);
            }
            else {
                // Remove the shared group from the item if deletedUser does not belong to a
                // public group
                if (!(deletedGroup.isUser(deletedUser) &&
Gaston Dombiak's avatar
Gaston Dombiak committed
1028
                        RosterManager.isPublicSharedGroup(deletedGroup))) {
1029 1030
                    item.removeSharedGroup(deletedGroup);
                }
1031 1032
                // Get the groups of the deleted user
                Collection<Group> groups = GroupManager.getInstance().getGroups(deletedUser);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                // Remove all invalid shared groups from the roster item
                for (Group group : groups) {
                    if (!rosterManager.isGroupVisible(group, getUserJID())) {
                        // Remove the shared group from the list of shared groups
                        item.removeSharedGroup(group);
                    }
                }

                // Update the subscription of the item **based on the item groups**
                if (item.isOnlyShared()) {
                    Collection<Group> userGroups =
1044
                            GroupManager.getInstance().getGroups(getUserJID());
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
                    // Set subscription type to BOTH if the roster user belongs to a shared group
                    // that is mutually visible with a shared group of the new roster item
                    if (rosterManager
                            .hasMutualVisibility(getUsername(), userGroups, deletedUser, groups)) {
                        item.setSubStatus(RosterItem.SUB_BOTH);
                    }
                    else {
                        // Assume by default that the contact has subscribed from the presence of
                        // this user
                        item.setSubStatus(RosterItem.SUB_FROM);
                        // Check if the user may see the new contact in a shared group
                        for (Group group : groups) {
                            if (rosterManager.isGroupVisible(group, getUserJID())) {
                                item.setSubStatus(RosterItem.SUB_TO);
                            }
                        }
                    }
                }
                // Brodcast to all the user resources of the updated roster item
                broadcast(item, false);
            }
        }
        catch (SharedGroupException e) {
            // Do nothing. Checkings are disabled so this exception should never happen.
        }
        catch (UserNotFoundException e) {
            // Do nothing since the contact does not exist in the user's roster. (strange case!)
        }
    }

    /**
     * A shared group of the user has been renamed. Update the existing roster items with the new
     * name of the shared group and make a roster push for all the available resources.
     *
     * @param users group users of the renamed group.
     */
    void shareGroupRenamed(Collection<JID> users) {
        JID userJID = getUserJID();
        for (JID user : users) {
            if (userJID.equals(user)) {
                continue;
            }
1087
            RosterItem item;
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
            try {
                // Get the RosterItem for the *local* user to add
                item = getRosterItem(user);
                // Brodcast to all the user resources of the updated roster item
                broadcast(item, true);
            }
            catch (UserNotFoundException e) {
                // Do nothing since the contact does not exist in the user's roster. (strange case!)
            }
        }
    }

    private JID getUserJID() {
        return XMPPServer.getInstance().createJID(getUsername(), null);
    }
Gaston Dombiak's avatar
Gaston Dombiak committed
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

    public void writeExternal(ObjectOutput out) throws IOException {
        ExternalizableUtil.getInstance().writeSafeUTF(out, username);
        ExternalizableUtil.getInstance().writeExternalizableMap(out, rosterItems);
        ExternalizableUtil.getInstance().writeStringsMap(out, implicitFrom);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        presenceManager = XMPPServer.getInstance().getPresenceManager();
        rosterManager = XMPPServer.getInstance().getRosterManager();
        sessionManager = SessionManager.getInstance();
        rosterItemProvider =  RosterItemProvider.getInstance();
        routingTable = XMPPServer.getInstance().getRoutingTable();

        username = ExternalizableUtil.getInstance().readSafeUTF(in);
        ExternalizableUtil.getInstance().readExternalizableMap(in, rosterItems, getClass().getClassLoader());
        ExternalizableUtil.getInstance().readStringsMap(in, implicitFrom);
    }
1121
}