LocalMUCUser.java 29.6 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3084 $
 * $Date: 2005-11-15 23:51:41 -0300 (Tue, 15 Nov 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
19 20 21 22
 */

package org.jivesoftware.openfire.muc.spi;

23 24 25 26 27 28 29 30
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

31 32 33 34
import org.dom4j.Element;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.PacketRouter;
import org.jivesoftware.openfire.auth.UnauthorizedException;
35 36 37 38 39 40 41 42 43 44 45 46 47
import org.jivesoftware.openfire.muc.CannotBeInvitedException;
import org.jivesoftware.openfire.muc.ConflictException;
import org.jivesoftware.openfire.muc.ForbiddenException;
import org.jivesoftware.openfire.muc.HistoryRequest;
import org.jivesoftware.openfire.muc.MUCRole;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.MUCUser;
import org.jivesoftware.openfire.muc.MultiUserChatService;
import org.jivesoftware.openfire.muc.NotAcceptableException;
import org.jivesoftware.openfire.muc.NotAllowedException;
import org.jivesoftware.openfire.muc.RegistrationRequiredException;
import org.jivesoftware.openfire.muc.RoomLockedException;
import org.jivesoftware.openfire.muc.ServiceUnavailableException;
48 49 50
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.NotFoundException;
51 52 53 54 55 56 57 58
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

/**
 * Representation of users interacting with the chat service. A user
 * may join serveral rooms hosted by the chat service. That means that
 * we are going to have an instance of this class for the user and several
 * MUCRoles for each joined room.<p>
 *
 * This room occupant is being hosted by this JVM. When the room occupant
 * is hosted by another cluster node then an instance of {@link RemoteMUCRole}
 * will be used instead.
 * 
 * @author Gaston Dombiak
 */
public class LocalMUCUser implements MUCUser {

74
    private static final Logger Log = LoggerFactory.getLogger(LocalMUCUser.class);
75

76
    /** The chat server this user belongs to. */
77
    private MultiUserChatService server;
78 79 80 81 82

    /** Real system XMPPAddress for the user. */
    private JID realjid;

    /** Table: key roomName.toLowerCase(); value LocalMUCRole. */
83
    private Map<String, LocalMUCRole> roles = new ConcurrentHashMap<>();
84 85 86 87 88 89 90 91 92 93 94 95

    /** Deliver packets to users. */
    private PacketRouter router;

    /**
     * Time of last packet sent.
     */
    private long lastPacketTime;

    /**
     * Create a new chat user.
     * 
96
     * @param chatservice the service the user belongs to.
97 98 99
     * @param packetRouter the router for sending packets from this user.
     * @param jid the real address of the user
     */
100
    LocalMUCUser(MultiUserChatService chatservice, PacketRouter packetRouter, JID jid) {
101 102
        this.realjid = jid;
        this.router = packetRouter;
103
        this.server = chatservice;
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    }

    /**
     * Returns true if the user is currently present in one or more rooms.
     *
     * @return true if the user is currently present in one or more rooms.
     */
    public boolean isJoined() {
        return !roles.isEmpty();
    }

    /**
     * Get all roles for this user.
     *
     * @return Iterator over all roles for this user
     */
    public Collection<LocalMUCRole> getRoles() {
        return Collections.unmodifiableCollection(roles.values());
    }

    /**
     * Adds the role of the user in a particular room.
     *
     * @param roomName The name of the room.
     * @param role The new role of the user.
     */
    public void addRole(String roomName, LocalMUCRole role) {
        roles.put(roomName, role);
    }

    /**
     * Removes the role of the user in a particular room.<p>
     *
     * Note: PREREQUISITE: A lock on this object has already been obtained.
     *
     * @param roomName The name of the room we're being removed
     */
    public void removeRole(String roomName) {
        roles.remove(roomName);
    }

    /**
     * Get time (in milliseconds from System currentTimeMillis()) since last packet.
     *
     * @return The time when the last packet was sent from this user
     */
    public long getLastPacketTime() {
        return lastPacketTime;
    }

    /**
     * Generate a conflict packet to indicate that the nickname being requested/used is already in
     * use by another user.
     * 
     * @param packet the packet to be bounced.
     * @param error the reason why the operation failed.
     */
    private void sendErrorPacket(Packet packet, PacketError.Condition error) {
        if (packet instanceof IQ) {
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement().createCopy());
            reply.setError(error);
            router.route(reply);
        }
        else {
            Packet reply = packet.createCopy();
            reply.setError(error);
            reply.setFrom(packet.getTo());
            reply.setTo(packet.getFrom());
            router.route(reply);
        }
    }

    /**
      * Obtain the address of the user. The address is used by services like the core
      * server packet router to determine if a packet should be sent to the handler.
      * Handlers that are working on behalf of the server should use the generic server
      * hostname address (e.g. server.com).
      *
      * @return the address of the packet handler.
      */
185
    @Override
186 187 188 189
    public JID getAddress() {
        return realjid;
    }

190
    @Override
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    public void process(Packet packet) throws UnauthorizedException, PacketException {
        if (packet instanceof IQ) {
            process((IQ)packet);
        }
        else if (packet instanceof Message) {
            process((Message)packet);
        }
        else if (packet instanceof Presence) {
            process((Presence)packet);
        }
    }

    /**
     * This method does all packet routing in the chat server. Packet routing is actually very
     * simple:
     * 
     * <ul>
     * <li>Discover the room the user is talking to (server packets are dropped)</li>
     * <li>If the room is not registered and this is a presence "available" packet, try to join the
     * room</li>
     * <li>If the room is registered, and presence "unavailable" leave the room</li>
     * <li>Otherwise, rewrite the sender address and send to the room.</li>
     * </ul>
     * 
     * @param packet The packet to route.
     */
    public void process(Message packet) {
        // Ignore messages of type ERROR sent to a room 
        if (Message.Type.error == packet.getType()) {
            return;
        }
        lastPacketTime = System.currentTimeMillis();
        JID recipient = packet.getTo();
        String group = recipient.getNode();
        if (group == null) {
            // Ignore packets to the groupchat server
            // In the future, we'll need to support TYPE_IQ queries to the server for MUC
            Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " "
                    + packet.toString());
        }
        else {
            MUCRole role = roles.get(group);
            if (role == null) {
                if (server.hasChatRoom(group)) {
                    boolean declinedInvitation = false;
                    Element userInfo = null;
                    if (Message.Type.normal == packet.getType()) {
                        // An user that is not an occupant could be declining an invitation
                        userInfo = packet.getChildElement(
                                "x", "http://jabber.org/protocol/muc#user");
                        if (userInfo != null
                                && userInfo.element("decline") != null) {
                            // A user has declined an invitation to a room
                            // WARNING: Potential fraud if someone fakes the "from" of the
                            // message with the JID of a member and sends a "decline"
                            declinedInvitation = true;
                        }
                    }
                    if (declinedInvitation) {
                        Element info = userInfo.element("decline");
                        server.getChatRoom(group).sendInvitationRejection(
                            new JID(info.attributeValue("to")),
                            info.elementTextTrim("reason"),
                            packet.getFrom());
                    }
                    else {
                        // The sender is not an occupant of the room
                        sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                    }
                }
                else {
                    // The sender is not an occupant of a NON-EXISTENT room!!!
                    sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
                }
            }
            else {
                // Check and reject conflicting packets with conflicting roles
                // In other words, another user already has this nickname
                if (!role.getUserAddress().equals(packet.getFrom())) {
                    sendErrorPacket(packet, PacketError.Condition.conflict);
                }
                else {
                    try {
274
                        if (role.getChatRoom().getRoomHistory().isSubjectChangeRequest(packet)) {
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                            // An occupant is trying to change the room's subject
                            role.getChatRoom().changeSubject(packet, role);

                        }
                        else {
                            // An occupant is trying to send a private, send public message,
                            // invite someone to the room or reject an invitation
                            Message.Type type = packet.getType();
                            String resource = packet.getTo().getResource();
                            if (resource == null || resource.trim().length() == 0) {
                                resource = null;
                            }
                            if (resource == null && Message.Type.groupchat == type) {
                                // An occupant is trying to send a public message
                                role.getChatRoom().sendPublicMessage(packet, role);
                            }
                            else if (resource != null
                                    && (Message.Type.chat == type || Message.Type.normal == type)) {
                                // An occupant is trying to send a private message
                                role.getChatRoom().sendPrivatePacket(packet, role);
                            }
                            else if (resource == null && Message.Type.normal == type) {
                                // An occupant could be sending an invitation or declining an
                                // invitation
                                Element userInfo = packet.getChildElement(
                                    "x",
                                    "http://jabber.org/protocol/muc#user");
                                // Real real real UGLY TRICK!!! Will and MUST be solved when
                                // persistence will be added. Replace locking with transactions!
                                LocalMUCRoom room = (LocalMUCRoom) role.getChatRoom();
                                if (userInfo != null && userInfo.element("invite") != null) {
                                    // An occupant is sending invitations

                                    // Try to keep the list of extensions sent together with the
                                    // message invitation. These extensions will be sent to the
                                    // invitees.
311
                                    @SuppressWarnings("unchecked")
312
                                    List<Element> extensions = new ArrayList<>(packet
313 314
                                            .getElement().elements());
                                    extensions.remove(userInfo);
315
                                    
316
                                    // Send invitations to invitees
317 318 319 320
                                    @SuppressWarnings("unchecked")
									Iterator<Element> it = userInfo.elementIterator("invite");
                                    while(it.hasNext()) {
                                        Element info = it.next();
321
                                        JID jid = new JID(info.attributeValue("to"));
322 323 324 325

                                        // Add the user as a member of the room if the room is
                                        // members only
                                        if (room.isMembersOnly()) {
326
                                            room.addMember(jid, null, role);
327 328 329
                                        }

                                        // Send the invitation to the invitee
330
                                        room.sendInvitation(jid,
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                                                info.elementTextTrim("reason"), role, extensions);
                                    }
                                }
                                else if (userInfo != null
                                        && userInfo.element("decline") != null) {
                                    // An occupant has declined an invitation
                                    Element info = userInfo.element("decline");
                                    room.sendInvitationRejection(new JID(info.attributeValue("to")),
                                            info.elementTextTrim("reason"), packet.getFrom());
                                }
                                else {
                                    sendErrorPacket(packet, PacketError.Condition.bad_request);
                                }
                            }
                            else {
                                sendErrorPacket(packet, PacketError.Condition.bad_request);
                            }
                        }
                    }
                    catch (ForbiddenException e) {
                        sendErrorPacket(packet, PacketError.Condition.forbidden);
                    }
                    catch (NotFoundException e) {
354
                        sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
355 356 357 358
                    }
                    catch (ConflictException e) {
                        sendErrorPacket(packet, PacketError.Condition.conflict);
                    }
359 360 361
                    catch (CannotBeInvitedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                    }
362 363 364
                    catch (IllegalArgumentException e) {
                        sendErrorPacket(packet, PacketError.Condition.jid_malformed);
                    }
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
                }
            }
        }
    }

    public void process(IQ packet) {
        lastPacketTime = System.currentTimeMillis();
        JID recipient = packet.getTo();
        String group = recipient.getNode();
        if (group == null) {
            // Ignore packets to the groupchat server
            // In the future, we'll need to support TYPE_IQ queries to the server for MUC
            Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " "
                    + packet.toString());
        }
        else {
            MUCRole role = roles.get(group);
            if (role == null) {
383 384 385 386
                // If a non-occupant sends a disco to an address of the form <room@service/nick>,
                // a MUC service MUST return a <bad-request/> error.
                // http://xmpp.org/extensions/xep-0045.html#disco-occupant
                sendErrorPacket(packet, PacketError.Condition.bad_request);
387
            }
388 389
            else if (IQ.Type.result == packet.getType()
                    || IQ.Type.error == packet.getType()) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                // Only process IQ result packet if it's a private packet sent to another
                // room occupant
                if (packet.getTo().getResource() != null) {
                    try {
                        // User is sending an IQ result packet to another room occupant
                        role.getChatRoom().sendPrivatePacket(packet, role);
                    }
                    catch (NotFoundException e) {
                        // Do nothing. No error will be sent to the sender of the IQ result packet
                    }
                }
            }
            else {
                // Check and reject conflicting packets with conflicting roles
                // In other words, another user already has this nickname
                if (!role.getUserAddress().equals(packet.getFrom())) {
                    sendErrorPacket(packet, PacketError.Condition.conflict);
                }
                else {
                    try {
                        Element query = packet.getElement().element("query");
                        if (query != null &&
                                "http://jabber.org/protocol/muc#owner".equals(query.getNamespaceURI())) {
                            role.getChatRoom().getIQOwnerHandler().handleIQ(packet, role);
                        }
                        else if (query != null &&
                                "http://jabber.org/protocol/muc#admin".equals(query.getNamespaceURI())) {
                            role.getChatRoom().getIQAdminHandler().handleIQ(packet, role);
                        }
                        else {
                            if (packet.getTo().getResource() != null) {
                                // User is sending an IQ packet to another room occupant
                                role.getChatRoom().sendPrivatePacket(packet, role);
                            }
                            else {
                                sendErrorPacket(packet, PacketError.Condition.bad_request);
                            }
                        }
                    }
                    catch (ForbiddenException e) {
                        sendErrorPacket(packet, PacketError.Condition.forbidden);
                    }
                    catch (NotFoundException e) {
                        sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
                    }
                    catch (ConflictException e) {
                        sendErrorPacket(packet, PacketError.Condition.conflict);
                    }
                    catch (NotAllowedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_allowed);
                    }
441 442 443
                    catch (CannotBeInvitedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                    }
444 445
                    catch (Exception e) {
                        sendErrorPacket(packet, PacketError.Condition.internal_server_error);
446
                        Log.error(e.getMessage(), e);
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                    }
                }
            }
        }
    }

    public void process(Presence packet) {
        // Ignore presences of type ERROR sent to a room
        if (Presence.Type.error == packet.getType()) {
            return;
        }
        lastPacketTime = System.currentTimeMillis();
        JID recipient = packet.getTo();
        String group = recipient.getNode();
        if (group != null) {
            MUCRole role = roles.get(group);
463 464 465 466
            Element mucInfo = packet.getChildElement("x",
                    "http://jabber.org/protocol/muc");
            if (role == null || mucInfo != null) {
                // If we're not already in a room (role == null), we either are joining it or it's not
467
                // properly addressed and we drop it silently
468
                // Alternative is that mucInfo is not null, in which case the client thinks it isn't in the room, so we should join anyway.
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                if (recipient.getResource() != null
                        && recipient.getResource().trim().length() > 0) {
                    if (packet.isAvailable()) {
                        try {
                            // Get or create the room
                            MUCRoom room = server.getChatRoom(group, packet.getFrom());
                            // User must support MUC in order to create a room
                            HistoryRequest historyRequest = null;
                            String password = null;
                            // Check for password & requested history if client supports MUC
                            if (mucInfo != null) {
                                password = mucInfo.elementTextTrim("password");
                                if (mucInfo.element("history") != null) {
                                    historyRequest = new HistoryRequest(mucInfo);
                                }
                            }
                            // The user joins the room
                            role = room.joinRoom(recipient.getResource().trim(),
                                    password,
                                    historyRequest,
                                    this,
                                    packet.createCopy());
                            // If the client that created the room is non-MUC compliant then
                            // unlock the room thus creating an "instant" room
                            if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) {
                                room.unlock(role);
                            }
                        }
                        catch (UnauthorizedException e) {
                            sendErrorPacket(packet, PacketError.Condition.not_authorized);
                        }
                        catch (ServiceUnavailableException e) {
                            sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                        }
503
                        catch (UserAlreadyExistsException | ConflictException e) {
504 505 506
                            sendErrorPacket(packet, PacketError.Condition.conflict);
                        }
                        catch (RoomLockedException e) {
507 508
                            // If a user attempts to enter a room while it is "locked" (i.e., before the room creator provides an initial configuration and therefore before the room officially exists), the service MUST refuse entry and return an <item-not-found/> error to the user
                            sendErrorPacket(packet, PacketError.Condition.item_not_found);
509 510 511 512 513 514
                        }
                        catch (ForbiddenException e) {
                            sendErrorPacket(packet, PacketError.Condition.forbidden);
                        }
                        catch (RegistrationRequiredException e) {
                            sendErrorPacket(packet, PacketError.Condition.registration_required);
515
                        } catch (NotAcceptableException e) {
516 517 518 519 520 521 522 523 524 525 526 527 528 529
                            sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                        }
                        catch (NotAllowedException e) {
                            sendErrorPacket(packet, PacketError.Condition.not_allowed);
                        }
                    }
                    else {
                        // TODO: send error message to user (can't send presence to group you
                        // haven't joined)
                    }
                }
                else {
                    if (packet.isAvailable()) {
                        // A resource is required in order to join a room
530 531 532
                        // http://xmpp.org/extensions/xep-0045.html#enter
                        // If the user does not specify a room nickname (note the bare JID on the 'from' address in the following example), the service MUST return a <jid-malformed/> error
                        sendErrorPacket(packet, PacketError.Condition.jid_malformed);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
                    }
                    // TODO: send error message to user (can't send packets to group you haven't
                    // joined)
                }
            }
            else {
                // Check and reject conflicting packets with conflicting roles
                // In other words, another user already has this nickname
                if (!role.getUserAddress().equals(packet.getFrom())) {
                    sendErrorPacket(packet, PacketError.Condition.conflict);
                }
                else {
                    if (Presence.Type.unavailable == packet.getType()) {
                        try {
                            // TODO Consider that different nodes can be creating and processing this presence at the same time (when remote node went down)
                            removeRole(group);
                            role.getChatRoom().leaveRoom(role);
                        }
                        catch (Exception e) {
552
                            Log.error(e.getMessage(), e);
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
                        }
                    }
                    else {
                        try {
                            String resource = (recipient.getResource() == null
                                    || recipient.getResource().trim().length() == 0 ? null
                                    : recipient.getResource().trim());
                            if (resource == null
                                    || role.getNickname().equalsIgnoreCase(resource)) {
                                // Occupant has changed his availability status
                                role.getChatRoom().presenceUpdated(role, packet);
                            }
                            else {
                                // Occupant has changed his nickname. Send two presences
                                // to each room occupant

                                // Check if occupants are allowed to change their nicknames
                                if (!role.getChatRoom().canChangeNickname()) {
                                    sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                                }
                                // Answer a conflic error if the new nickname is taken
                                else if (role.getChatRoom().hasOccupant(resource)) {
                                    sendErrorPacket(packet, PacketError.Condition.conflict);
                                }
                                else {
                                    // Send "unavailable" presence for the old nickname
                                    Presence presence = role.getPresence().createCopy();
                                    // Switch the presence to OFFLINE
                                    presence.setType(Presence.Type.unavailable);
                                    presence.setStatus(null);
                                    // Add the new nickname and status 303 as properties
                                    Element frag = presence.getChildElement("x",
                                            "http://jabber.org/protocol/muc#user");
                                    frag.element("item").addAttribute("nick", resource);
                                    frag.addElement("status").addAttribute("code", "303");
                                    role.getChatRoom().send(presence);

                                    // Send availability presence for the new nickname
                                    String oldNick = role.getNickname();
                                    role.getChatRoom().nicknameChanged(role, packet, oldNick, resource);
                                }
                            }
                        }
                        catch (Exception e) {
                            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                        }
                    }
                }
            }
        }
    }
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((realjid == null) ? 0 : realjid.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LocalMUCUser other = (LocalMUCUser) obj;
		if (realjid == null) {
			if (other.realjid != null)
				return false;
		} else if (!realjid.equals(other.realjid))
			return false;
		return true;
	}
629
}