SessionManager.java 62.4 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3170 $
 * $Date: 2005-12-07 14:00:58 -0300 (Wed, 07 Dec 2005) $
 *
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;
13

14
import org.jivesoftware.openfire.audit.AuditStreamIDFactory;
15
import org.jivesoftware.openfire.auth.AuthToken;
16
import org.jivesoftware.openfire.auth.UnauthorizedException;
17 18
import org.jivesoftware.openfire.cluster.ClusterEventListener;
import org.jivesoftware.openfire.cluster.ClusterManager;
19 20 21 22 23 24 25 26 27
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.container.BasicModule;
import org.jivesoftware.openfire.event.SessionEventDispatcher;
import org.jivesoftware.openfire.http.HttpSession;
import org.jivesoftware.openfire.multiplex.ConnectionMultiplexerManager;
import org.jivesoftware.openfire.server.OutgoingSessionPromise;
import org.jivesoftware.openfire.session.*;
import org.jivesoftware.openfire.spi.BasicStreamIDFactory;
import org.jivesoftware.openfire.user.UserManager;
28 29 30
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
31 32 33
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
import org.jivesoftware.util.lock.LockManager;
34 35 36 37 38
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.Presence;

39
import java.net.InetAddress;
40
import java.util.*;
Gaston Dombiak's avatar
Gaston Dombiak committed
41
import java.util.concurrent.atomic.AtomicInteger;
42
import java.util.concurrent.locks.Lock;
43 44 45 46 47 48 49 50

/**
 * Manages the sessions associated with an account. The information
 * maintained by the Session manager is entirely transient and does
 * not need to be preserved between server restarts.
 *
 * @author Derek DeMoro
 */
51
public class SessionManager extends BasicModule implements ClusterEventListener {
52

53 54 55 56
    public static final String COMPONENT_SESSION_CACHE_NAME = "Components Sessions";
    public static final String CM_CACHE_NAME = "Connection Managers Sessions";
    public static final String ISS_CACHE_NAME = "Incoming Server Sessions";

57 58
    public static final int NEVER_KICK = -1;

59
    private XMPPServer server;
60 61 62 63 64 65
    private PacketRouter router;
    private String serverName;
    private JID serverAddress;
    private UserManager userManager;
    private int conflictLimit;

66
    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
67 68
     * Counter of user connections. A connection is counted just after it was created and not
     * after the user became available.
69
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
70 71
    private final AtomicInteger connectionsCounter = new AtomicInteger(0);

72
    /**
73 74
     * Cache (unlimited, never expire) that holds external component sessions.
     * Key: component address, Value: nodeID
75
     */
76
    private Cache<String, byte[]> componentSessionsCache;
77 78

    /**
79 80 81
     * Cache (unlimited, never expire) that holds sessions of connection managers. For each
     * socket connection of the CM to the server there is going to be an entry in the cache.
     * Key: full address of the CM that identifies the socket, Value: nodeID
82
     */
83
    private Cache<String, byte[]> multiplexerSessionsCache;
84 85

    /**
86 87
     * Cache (unlimited, never expire) that holds incoming sessions of remote servers.
     * Key: stream ID that identifies the socket/session, Value: nodeID
88
     */
89
    private Cache<String, byte[]> incomingServerSessionsCache;
90
    /**
91 92 93 94 95
     * Cache (unlimited, never expire) that holds list of incoming sessions
     * originated from the same remote server (domain/subdomain). For instance, jabber.org
     * may have 2 connections to the server running in jivesoftware.com (one socket to
     * jivesoftware.com and the other socket to conference.jivesoftware.com).
     * Key: remote hostname (domain/subdomain), Value: list of stream IDs that identify each socket.
96
     */
97
    private Cache<String, List<String>> hostnameSessionsCache;
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112
    /**
     * Cache (unlimited, never expire) that holds domains, subdomains and virtual
     * hostnames of the remote server that were validated with this server for each
     * incoming server session.
     * Key: stream ID, Value: Domains and subdomains of the remote server that were
     * validated with this server.<p>
     *
     * This same information is stored in {@link LocalIncomingServerSession} but the
     * reason for this duplication is that when running in a cluster other nodes
     * will have access to this clustered cache even in the case of this node going
     * down. 
     */
    private Cache<String, Set<String>> validatedDomainsCache;

113 114 115 116 117
    private ClientSessionListener clientSessionListener = new ClientSessionListener();
    private ComponentSessionListener componentSessionListener = new ComponentSessionListener();
    private IncomingServerSessionListener incomingServerListener = new IncomingServerSessionListener();
    private OutgoingServerSessionListener outgoingServerListener = new OutgoingServerSessionListener();
    private ConnectionMultiplexerSessionListener multiplexerSessionListener = new ConnectionMultiplexerSessionListener();
118 119

    /**
120 121
     * Local session manager responsible for keeping sessions connected to this JVM that are not
     * present in the routing table. 
122
     */
123
    private LocalSessionManager localSessionManager;
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
    /**
     * <p>Session manager must maintain the routing table as sessions are added and
     * removed.</p>
     */
    private RoutingTable routingTable;

    private StreamIDFactory streamIDFactory;

    /**
     * Returns the instance of <CODE>SessionManagerImpl</CODE> being used by the XMPPServer.
     *
     * @return the instance of <CODE>SessionManagerImpl</CODE> being used by the XMPPServer.
     */
    public static SessionManager getInstance() {
        return XMPPServer.getInstance().getSessionManager();
    }

    public SessionManager() {
        super("Session Manager");
        if (JiveGlobals.getBooleanProperty("xmpp.audit.active")) {
            streamIDFactory = new AuditStreamIDFactory();
        }
        else {
            streamIDFactory = new BasicStreamIDFactory();
        }
149
        localSessionManager = new LocalSessionManager();
Matt Tucker's avatar
Matt Tucker committed
150
        conflictLimit = JiveGlobals.getIntProperty("xmpp.session.conflict-limit", 0);
151 152
    }

153
    /**
154 155 156 157
     * Returns the session originated from the specified address or <tt>null</tt> if none was
     * found. The specified address MUST contain a resource that uniquely identifies the session.
     *
     * A single connection manager should connect to the same node.
158
     *
159
     * @param address the address of the connection manager (including resource that identifies specific socket)
160 161 162
     * @return the session originated from the specified address.
     */
    public ConnectionMultiplexerSession getConnectionMultiplexerSession(JID address) {
163 164 165 166 167 168 169 170
        // Search in the list of CMs connected to this JVM
        LocalConnectionMultiplexerSession session =
                localSessionManager.getConnnectionManagerSessions().get(address.toString());
        if (session == null && server.getRemoteSessionLocator() != null) {
            // Search in the list of CMs connected to other cluster members
            byte[] nodeID = multiplexerSessionsCache.get(address.toString());
            if (nodeID != null) {
                return server.getRemoteSessionLocator().getConnectionMultiplexerSession(nodeID, address);
171 172
            }
        }
173
        return null;
174 175
    }

176 177 178 179 180 181
    /**
     * Returns all sessions originated from connection managers.
     *
     * @return all sessions originated from connection managers.
     */
    public List<ConnectionMultiplexerSession> getConnectionMultiplexerSessions() {
182 183 184 185 186 187 188
        List<ConnectionMultiplexerSession> sessions = new ArrayList<ConnectionMultiplexerSession>();
        // Add sessions of CMs connected to this JVM
        sessions.addAll(localSessionManager.getConnnectionManagerSessions().values());
        // Add sessions of CMs connected to other cluster nodes
        RemoteSessionLocator locator = server.getRemoteSessionLocator();
        if (locator != null) {
            for (Map.Entry<String, byte[]> entry : multiplexerSessionsCache.entrySet()) {
189
                if (!server.getNodeID().equals(entry.getValue())) {
190 191 192
                    sessions.add(locator.getConnectionMultiplexerSession(entry.getValue(), new JID(entry.getKey())));
                }
            }
193
        }
194
        return sessions;
195 196
    }

197 198 199 200 201 202 203 204 205 206
    /**
     * Returns a collection with all the sessions originated from the connection manager
     * whose domain matches the specified domain. If there is no connection manager with
     * the specified domain then an empty list is going to be returned.
     *
     * @param domain the domain of the connection manager.
     * @return a collection with all the sessions originated from the connection manager
     *         whose domain matches the specified domain.
     */
    public List<ConnectionMultiplexerSession> getConnectionMultiplexerSessions(String domain) {
207 208 209 210 211 212 213
        List<ConnectionMultiplexerSession> sessions = new ArrayList<ConnectionMultiplexerSession>();
        // Add sessions of CMs connected to this JVM
        for (String address : localSessionManager.getConnnectionManagerSessions().keySet()) {
            JID jid = new JID(address);
            if (domain.equals(jid.getDomain())) {
                sessions.add(localSessionManager.getConnnectionManagerSessions().get(address));
            }
214
        }
215 216 217 218
        // Add sessions of CMs connected to other cluster nodes
        RemoteSessionLocator locator = server.getRemoteSessionLocator();
        if (locator != null) {
            for (Map.Entry<String, byte[]> entry : multiplexerSessionsCache.entrySet()) {
219
                if (!server.getNodeID().equals(entry.getValue())) {
220 221 222 223 224 225 226
                    JID jid = new JID(entry.getKey());
                    if (domain.equals(jid.getDomain())) {
                        sessions.add(
                                locator.getConnectionMultiplexerSession(entry.getValue(), new JID(entry.getKey())));
                    }
                }
            }
227
        }
228
        return sessions;
229 230
    }

231 232 233 234 235 236 237
    /**
     * Creates a new <tt>ConnectionMultiplexerSession</tt>.
     *
     * @param conn the connection to create the session from.
     * @param address the JID (may include a resource) of the connection manager's session. 
     * @return a newly created session.
     */
238
    public LocalConnectionMultiplexerSession createMultiplexerSession(Connection conn, JID address) {
239
        if (serverName == null) {
240
            throw new IllegalStateException("Server not initialized");
241 242
        }
        StreamID id = nextStreamID();
243
        LocalConnectionMultiplexerSession session = new LocalConnectionMultiplexerSession(serverName, conn, id);
244 245 246 247 248 249
        conn.init(session);
        // Register to receive close notification on this session so we can
        // figure out when users that were using this connection manager may become unavailable
        conn.registerCloseListener(multiplexerSessionListener, session);

        // Add to connection multiplexer session.
250 251 252
        boolean firstConnection = getConnectionMultiplexerSessions(address.getDomain()).isEmpty();
        localSessionManager.getConnnectionManagerSessions().put(address.toString(), session);
        // Keep track of the cluster node hosting the new CM connection
253
        multiplexerSessionsCache.put(address.toString(), server.getNodeID().toByteArray());
254 255 256 257
        if (firstConnection) {
            // Notify ConnectionMultiplexerManager that a new connection manager
            // is available
            ConnectionMultiplexerManager.getInstance().multiplexerAvailable(address.getDomain());
258 259 260 261
        }
        return session;
    }

262 263 264 265 266 267 268 269 270 271
    /**
     * Returns a randomly created ID to be used in a stream element.
     *
     * @return a randomly created ID to be used in a stream element.
     */
    public StreamID nextStreamID() {
        return streamIDFactory.createStreamID();
    }

    /**
272 273
     * Creates a new <tt>ClientSession</tt>. The new Client session will have a newly created
     * stream ID.
274 275 276 277
     *
     * @param conn the connection to create the session from.
     * @return a newly created session.
     */
278
    public LocalClientSession createClientSession(Connection conn) {
279 280 281 282 283 284 285 286 287 288
        return createClientSession(conn, nextStreamID());
    }

    /**
     * Creates a new <tt>ClientSession</tt> with the specified streamID.
     *
     * @param conn the connection to create the session from.
     * @param id the streamID to use for the new session.
     * @return a newly created session.
     */
289
    public LocalClientSession createClientSession(Connection conn, StreamID id) {
290
        if (serverName == null) {
291
            throw new IllegalStateException("Server not initialized");
292
        }
293
        LocalClientSession session = new LocalClientSession(serverName, conn, id);
294 295 296 297 298 299 300
        conn.init(session);
        // Register to receive close notification on this session so we can
        // remove  and also send an unavailable presence if it wasn't
        // sent before
        conn.registerCloseListener(clientSessionListener, session);

        // Add to pre-authenticated sessions.
301
        localSessionManager.getPreAuthenticatedSessions().put(session.getAddress().getResource(), session);
302
        // Increment the counter of user sessions
Gaston Dombiak's avatar
Gaston Dombiak committed
303
        connectionsCounter.incrementAndGet();
304 305 306
        return session;
    }

307
    public HttpSession createClientHttpSession(long rid, InetAddress address, StreamID id)
Alex Wenckus's avatar
Alex Wenckus committed
308 309 310 311 312
            throws UnauthorizedException
    {
        if (serverName == null) {
            throw new UnauthorizedException("Server not initialized");
        }
313
        PacketDeliverer backupDeliverer = server.getPacketDeliverer();
314
        HttpSession session = new HttpSession(backupDeliverer, serverName, address, id, rid);
Alex Wenckus's avatar
Alex Wenckus committed
315 316 317
        Connection conn = session.getConnection();
        conn.init(session);
        conn.registerCloseListener(clientSessionListener, session);
318
        localSessionManager.getPreAuthenticatedSessions().put(session.getAddress().getResource(), session);
Gaston Dombiak's avatar
Gaston Dombiak committed
319
        connectionsCounter.incrementAndGet();
Alex Wenckus's avatar
Alex Wenckus committed
320 321 322
        return session;
    }

323
    public LocalComponentSession createComponentSession(JID address, Connection conn) throws UnauthorizedException {
324 325 326 327
        if (serverName == null) {
            throw new UnauthorizedException("Server not initialized");
        }
        StreamID id = nextStreamID();
328
        LocalComponentSession session = new LocalComponentSession(serverName, conn, id);
329 330 331 332
        conn.init(session);
        // Register to receive close notification on this session so we can
        // remove the external component from the list of components
        conn.registerCloseListener(componentSessionListener, session);
333 334
        // Set the bind address as the address of the session
        session.setAddress(address);
335 336

        // Add to component session.
337 338
        localSessionManager.getComponentsSessions().add(session);
        // Keep track of the cluster node hosting the new external component
339
        componentSessionsCache.put(address.toString(), server.getNodeID().toByteArray());
340 341 342 343 344 345 346 347 348 349 350 351
        return session;
    }

    /**
     * Creates a session for a remote server. The session should be created only after the
     * remote server has been authenticated either using "server dialback" or SASL.
     *
     * @param conn the connection to the remote server.
     * @param id the stream ID used in the stream element when authenticating the server.
     * @return the newly created {@link IncomingServerSession}.
     * @throws UnauthorizedException if the local server has not been initialized yet.
     */
352
    public LocalIncomingServerSession createIncomingServerSession(Connection conn, StreamID id)
353 354 355 356
            throws UnauthorizedException {
        if (serverName == null) {
            throw new UnauthorizedException("Server not initialized");
        }
357
        LocalIncomingServerSession session = new LocalIncomingServerSession(serverName, conn, id);
358 359 360 361 362 363 364 365 366 367 368 369 370 371
        conn.init(session);
        // Register to receive close notification on this session so we can
        // remove its route from the sessions set
        conn.registerCloseListener(incomingServerListener, session);

        return session;
    }

    /**
     * Notification message that a new OutgoingServerSession has been created. Register a listener
     * that will react when the connection gets closed.
     *
     * @param session the newly created OutgoingServerSession.
     */
372
    public void outgoingServerSessionCreated(LocalOutgoingServerSession session) {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        // Register to receive close notification on this session so we can
        // remove its route from the sessions set
        session.getConnection().registerCloseListener(outgoingServerListener, session);
    }

    /**
     * Registers that a server session originated by a remote server is hosting a given hostname.
     * Notice that the remote server may be hosting several subdomains as well as virtual hosts so
     * the same IncomingServerSession may be associated with many keys. If the remote server
     * creates many sessions to this server (eg. one for each subdomain) then associate all
     * the sessions with the originating server that created all the sessions.
     *
     * @param hostname the hostname that is being served by the remote server.
     * @param session the incoming server session to the remote server.
     */
388 389
    public void registerIncomingServerSession(String hostname, LocalIncomingServerSession session) {
        // Keep local track of the incoming server session connected to this JVM
390 391
        String streamID = session.getStreamID().getID();
        localSessionManager.addIncomingServerSessions(streamID, session);
392
        // Keep track of the nodeID hosting the incoming server session
393
        incomingServerSessionsCache.put(streamID, server.getNodeID().toByteArray());
394 395 396 397 398 399 400
        // Update list of sockets/sessions coming from the same remote hostname
        Lock lock = LockManager.getLock(hostname);
        try {
            lock.lock();
            List<String> streamIDs = hostnameSessionsCache.get(hostname);
            if (streamIDs == null) {
                streamIDs = new ArrayList<String>();
401
            }
402
            streamIDs.add(streamID);
403 404 405 406
            hostnameSessionsCache.put(hostname, streamIDs);
        }
        finally {
            lock.unlock();
407
        }
408 409
        // Add to clustered cache
        lock = LockManager.getLock(streamID);
410 411
        try {
            lock.lock();
412 413 414 415 416 417 418
            Set<String> validatedDomains = validatedDomainsCache.get(streamID);
            if (validatedDomains == null) {
                validatedDomains = new HashSet<String>();
            }
            boolean added = validatedDomains.add(hostname);
            if (added) {
                validatedDomainsCache.put(streamID, validatedDomains);
419
            }
420 421
        } finally {
            lock.unlock();
422 423 424 425 426 427 428 429 430
        }
    }

    /**
     * Unregisters the specified remote server session originiated by the specified remote server.
     *
     * @param hostname the hostname that is being served by the remote server.
     * @param session the session to unregiser.
     */
431
    public void unregisterIncomingServerSession(String hostname, IncomingServerSession session) {
432
        // Remove local track of the incoming server session connected to this JVM
433 434
        String streamID = session.getStreamID().getID();
        localSessionManager.removeIncomingServerSessions(streamID);
435
        // Remove track of the nodeID hosting the incoming server session
436
        incomingServerSessionsCache.remove(streamID);
437

438 439 440 441 442 443
        // Remove from list of sockets/sessions coming from the remote hostname
        Lock lock = LockManager.getLock(hostname);
        try {
            lock.lock();
            List<String> streamIDs = hostnameSessionsCache.get(hostname);
            if (streamIDs != null) {
444
                streamIDs.remove(streamID);
445 446 447 448 449
                if (streamIDs.isEmpty()) {
                    hostnameSessionsCache.remove(hostname);
                }
                else {
                    hostnameSessionsCache.put(hostname, streamIDs);
450
                }
451 452
            }
        }
453 454 455
        finally {
            lock.unlock();
        }
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        // Remove from clustered cache
        lock = LockManager.getLock(streamID);
        try {
            lock.lock();
            Set<String> validatedDomains = validatedDomainsCache.get(streamID);
            if (validatedDomains == null) {
                validatedDomains = new HashSet<String>();
            }
            validatedDomains.remove(hostname);
            if (!validatedDomains.isEmpty()) {
                validatedDomainsCache.put(streamID, validatedDomains);
            }
            else {
                validatedDomainsCache.remove(streamID);
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Returns a collection with all the domains, subdomains and virtual hosts that where
     * validated. The remote server is allowed to send packets from any of these domains,
     * subdomains and virtual hosts.<p>
     *
     * Content is stored in a clustered cache so that even in the case of the node hosting
     * the sessions is lost we can still have access to this info to be able to perform
     * proper clean up logic.
     *
     * @param streamID id that uniquely identifies the session.
     * @return domains, subdomains and virtual hosts that where validated.
     */
    public Collection<String> getValidatedDomains(String streamID) {
        Lock lock = LockManager.getLock(streamID);
        try {
            lock.lock();
            Set<String> validatedDomains = validatedDomainsCache.get(streamID);
            if (validatedDomains == null) {
                return Collections.emptyList();
            }
            return Collections.unmodifiableCollection(validatedDomains);
        } finally {
            lock.unlock();
        }
500 501 502
    }

    /**
503 504
     * Add a new session to be managed. The session has been authenticated and resource
     * binding has been done.
505 506
     *
     * @param session the session that was authenticated.
507
     */
508
    public void addSession(LocalClientSession session) {
509
        // Remove the pre-Authenticated session but remember to use the temporary ID as the key
510
        localSessionManager.getPreAuthenticatedSessions().remove(session.getStreamID().toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
511
        // Add session to the routing table (routing table will know session is not available yet)
512
        routingTable.addClientRoute(session.getAddress(), session);
513 514 515
        SessionEventDispatcher.EventType event = session.getAuthToken().isAnonymous() ?
                SessionEventDispatcher.EventType.anonymous_session_created :
                SessionEventDispatcher.EventType.session_created;
516
        // Fire session created event.
517
        SessionEventDispatcher.dispatchEvent(session, event);
518 519 520 521 522 523 524 525 526 527
    }

    /**
     * Notification message sent when a client sent an available presence for the session. Making
     * the session available means that the session is now eligible for receiving messages from
     * other clients. Sessions whose presence is not available may only receive packets (IQ packets)
     * from the server. Therefore, an unavailable session remains invisible to other clients.
     *
     * @param session the session that receieved an available presence.
     */
528 529
    public void sessionAvailable(LocalClientSession session) {
        if (session.getAuthToken().isAnonymous()) {
530 531
            // Anonymous session always have resources so we only need to add one route. That is
            // the route to the anonymous session
Gaston Dombiak's avatar
Gaston Dombiak committed
532
            routingTable.addClientRoute(session.getAddress(), session);
533 534 535
        }
        else {
            // A non-anonymous session is now available
536 537 538 539
            // Add route to the new session
            routingTable.addClientRoute(session.getAddress(), session);
            // Broadcast presence between the user's resources
            broadcastPresenceOfOtherResource(session);
540 541 542 543
        }
    }

    /**
544
     * Sends the presences of other connected resources to the resource that just connected.
545
     * 
546
     * @param session the newly created session.
547
     */
548
    private void broadcastPresenceOfOtherResource(LocalClientSession session) {
549
        Presence presence;
550 551 552 553 554 555
        // Get list of sessions of the same user
        JID searchJID = new JID(session.getAddress().getNode(), session.getAddress().getDomain(), null);
        List<JID> addresses = routingTable.getRoutes(searchJID);
        for (JID address : addresses) {
            if (address.equals(session.getAddress())) {
                continue;
556
            }
557 558 559 560 561 562
            // Send the presence of an existing session to the session that has just changed
            // the presence
            ClientSession userSession = routingTable.getClientRoute(address);
            presence = userSession.getPresence().createCopy();
            presence.setTo(session.getAddress());
            session.process(presence);
563 564 565 566 567 568 569 570
        }
    }

    /**
     * Broadcasts presence updates from the originating user's resource to any of the user's
     * existing available resources (if any).
     *
     * @param originatingResource the full JID of the session that sent the presence update.
Matt Tucker's avatar
Matt Tucker committed
571
     * @param presence the presence.
572 573
     */
    public void broadcastPresenceToOtherResources(JID originatingResource, Presence presence) {
574 575 576 577 578 579
        // Get list of sessions of the same user
        JID searchJID = new JID(originatingResource.getNode(), originatingResource.getDomain(), null);
        List<JID> addresses = routingTable.getRoutes(searchJID);
        for (JID address : addresses) {
            if (address.equals(originatingResource)) {
                continue;
580
            }
581 582 583
            // Send the presence of the session whose presence has changed to
            // this other user's session
            presence.setTo(address);
Gaston Dombiak's avatar
Gaston Dombiak committed
584
            routingTable.routePacket(address, presence, false);
585 586 587 588 589 590 591 592 593 594
        }
    }

    /**
     * Notification message sent when a client sent an unavailable presence for the session. Making
     * the session unavailable means that the session is not eligible for receiving messages from
     * other clients.
     *
     * @param session the session that receieved an unavailable presence.
     */
595
    public void sessionUnavailable(LocalClientSession session) {
596 597
        if (session.getAddress() != null && routingTable != null &&
                session.getAddress().toBareJID().trim().length() != 0) {
Gaston Dombiak's avatar
Gaston Dombiak committed
598 599
            // Update route to unavailable session (anonymous or not)
            routingTable.addClientRoute(session.getAddress(), session);
600 601 602 603 604 605
        }
    }

    /**
     * Change the priority of a session, that was already available, associated with the sender.
     *
606 607
     * @param session   The session whose presence priority has been modified
     * @param oldPriority The old priority for the session
608
     */
609 610
    public void changePriority(LocalClientSession session, int oldPriority) {
        if (session.getAuthToken().isAnonymous()) {
611
            // Do nothing if the session belongs to an anonymous user
612 613
            return;
        }
614
        int newPriority = session.getPresence().getPriority();
615
        if (newPriority < 0 || oldPriority >= 0) {
616
            // Do nothing if new presence priority is not positive and old presence negative
617 618
            return;
        }
619

620 621 622 623 624
        // Check presence's priority of other available resources
        JID searchJID = new JID(session.getAddress().toBareJID());
        for (JID address : routingTable.getRoutes(searchJID)) {
            if (address.equals(session.getAddress())) {
                continue;
625
            }
626 627 628
            ClientSession otherSession = routingTable.getClientRoute(address);
            if (otherSession.getPresence().getPriority() >= 0) {
                return;
629 630
            }
        }
631 632 633 634 635 636 637 638

        // User sessions had negative presence before this change so deliver messages
        if (session.canFloodOfflineMessages()) {
            OfflineMessageStore messageStore = server.getOfflineMessageStore();
            Collection<OfflineMessage> messages = messageStore.getMessages(session.getAuthToken().getUsername(), true);
            for (Message message : messages) {
                session.process(message);
            }
639 640 641
        }
    }

642 643
    public boolean isAnonymousRoute(String username) {
        // JID's node and resource are the same for anonymous sessions
Gaston Dombiak's avatar
Gaston Dombiak committed
644
        return isAnonymousRoute(new JID(username, serverName, username, true));
645 646 647 648 649
    }

    public boolean isAnonymousRoute(JID address) {
        // JID's node and resource are the same for anonymous sessions
        return routingTable.isAnonymousRoute(address);
650 651
    }

652 653
    public boolean isActiveRoute(String username, String resource) {
        boolean hasRoute = false;
654 655 656 657
        Session session = routingTable.getClientRoute(new JID(username, serverName, resource));
        // Makes sure the session is still active
        if (session != null && !session.isClosed()) {
            hasRoute = session.validate();
658 659 660 661 662 663
        }

        return hasRoute;
    }

    /**
664 665 666
     * Returns the session responsible for this JID data. The returned Session may have never sent
     * an available presence (thus not have a route) or could be a Session that hasn't
     * authenticated yet (i.e. preAuthenticatedSessions).
667 668 669 670 671
     *
     * @param from the sender of the packet.
     * @return the <code>Session</code> associated with the JID.
     */
    public ClientSession getSession(JID from) {
672
        // Return null if the JID is null or belongs to a foreign server. If the server is
673
        // shutting down then serverName will be null so answer null too in this case.
674
        if (from == null || serverName == null || !serverName.equals(from.getDomain())) {
675 676 677 678
            return null;
        }

        // Initially Check preAuthenticated Sessions
679 680
        if (from.getResource() != null) {
            ClientSession session = localSessionManager.getPreAuthenticatedSessions().get(from.getResource());
681
            if (session != null) {
682 683
                return session;
            }
684 685
        }

686
        if (from.getResource() == null || from.getNode() == null) {
687 688
            return null;
        }
689

690
        return routingTable.getClientRoute(from);
691 692
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
693
    /**
694 695
     * Returns a list that contains all authenticated client sessions connected to the server.
     * The list contains sessions of anonymous and non-anonymous users.
Gaston Dombiak's avatar
Gaston Dombiak committed
696 697 698
     *
     * @return a list that contains all client sessions connected to the server.
     */
699
    public Collection<ClientSession> getSessions() {
700
        return routingTable.getClientsRoutes(false);
701 702 703 704 705 706
    }


    public Collection<ClientSession> getSessions(SessionResultFilter filter) {
        List<ClientSession> results = new ArrayList<ClientSession>();
        if (filter != null) {
707 708
            // Grab all the matching sessions
            results.addAll(getSessions());
709 710 711 712 713 714 715

            // Now we have a copy of the references so we can spend some time
            // doing the rest of the filtering without locking out session access
            // so let's iterate and filter each session one by one
            List<ClientSession> filteredResults = new ArrayList<ClientSession>();
            for (ClientSession session : results) {
                // Now filter on creation date if needed
716
                filteredResults.add(session);
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
            }

            // Sort list.
            Collections.sort(filteredResults, filter.getSortComparator());

            int maxResults = filter.getNumResults();
            if (maxResults == SessionResultFilter.NO_RESULT_LIMIT) {
                maxResults = filteredResults.size();
            }

            // Now generate the final list. I believe it's faster to to build up a new
            // list than it is to remove items from head and tail of the sorted tree
            List<ClientSession> finalResults = new ArrayList<ClientSession>();
            int startIndex = filter.getStartIndex();
            Iterator<ClientSession> sortedIter = filteredResults.iterator();
            for (int i = 0; sortedIter.hasNext() && finalResults.size() < maxResults; i++) {
                ClientSession result = sortedIter.next();
                if (i >= startIndex) {
                    finalResults.add(result);
                }
            }
            return finalResults;
        }
        return results;
    }

743 744 745 746 747 748 749 750 751 752
    /**
     * Returns the incoming server session hosted by this JVM that matches the specified stream ID.
     *
     * @param streamID the stream ID that identifies the incoming server session hosted by this JVM.
     * @return the incoming server session hosted by this JVM or null if none was found.
     */
    public LocalIncomingServerSession getIncomingServerSession(String streamID) {
        return localSessionManager.getIncomingServerSession(streamID);
    }

753 754 755 756 757 758 759 760 761
    /**
     * Returns the list of sessions that were originated by a remote server. The list will be
     * ordered chronologically.  IncomingServerSession can only receive packets from the remote
     * server but are not capable of sending packets to the remote server.
     *
     * @param hostname the name of the remote server.
     * @return the sessions that were originated by a remote server.
     */
    public List<IncomingServerSession> getIncomingServerSessions(String hostname) {
762 763 764 765 766 767 768 769 770 771 772 773
        List<String> streamIDs;
        // Get list of sockets/sessions coming from the remote hostname
        Lock lock = LockManager.getLock(hostname);
        try {
            lock.lock();
            streamIDs = hostnameSessionsCache.get(hostname);
        }
        finally {
            lock.unlock();
        }

        if (streamIDs == null) {
774 775 776
            return Collections.emptyList();
        }
        else {
777 778 779 780
            // Collect the sessions associated to the found stream IDs
            List<IncomingServerSession> sessions = new ArrayList<IncomingServerSession>();
            for (String streamID : streamIDs) {
                // Search in local hosted sessions
781
                IncomingServerSession session = localSessionManager.getIncomingServerSession(streamID);
782 783 784 785 786 787 788 789 790 791 792 793 794
                RemoteSessionLocator locator = server.getRemoteSessionLocator();
                if (session == null && locator != null) {
                    // Get the node hosting this session
                    byte[] nodeID = incomingServerSessionsCache.get(streamID);
                    if (nodeID != null) {
                        session = locator.getIncomingServerSession(nodeID, streamID);
                    }
                }
                if (session != null) {
                    sessions.add(session);
                }
            }
            return sessions;
795 796 797 798 799 800 801 802 803 804 805 806
        }
    }

    /**
     * Returns a session that was originated from this server to a remote server.
     * OutgoingServerSession an only send packets to the remote server but are not capable of
     * receiving packets from the remote server.
     *
     * @param hostname the name of the remote server.
     * @return a session that was originated from this server to a remote server.
     */
    public OutgoingServerSession getOutgoingServerSession(String hostname) {
807
        return routingTable.getServerRoute(new JID(null, hostname, null, true));
808 809 810 811 812
    }

    public Collection<ClientSession> getSessions(String username) {
        List<ClientSession> sessionList = new ArrayList<ClientSession>();
        if (username != null) {
813 814 815 816
            List<JID> addresses = routingTable.getRoutes(new JID(username, serverName, null, true));
            for (JID address : addresses) {
                sessionList.add(routingTable.getClientRoute(address));
            }
817 818 819 820
        }
        return sessionList;
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
821
    /**
822 823
     * Returns number of client sessions that are connected to the server. Sessions that
     * are authenticated and not authenticated will be included
Gaston Dombiak's avatar
Gaston Dombiak committed
824
     *
Gaston Dombiak's avatar
Gaston Dombiak committed
825
     * @param onlyLocal true if only sessions connected to this JVM will be considered. Otherwise count cluster wise.
Gaston Dombiak's avatar
Gaston Dombiak committed
826 827
     * @return number of client sessions that are connected to the server.
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
828 829
    public int getConnectionsCount(boolean onlyLocal) {
        int total = connectionsCounter.get();
830 831 832 833 834 835 836 837
        if (!onlyLocal) {
            Collection<Object> results =
                    CacheFactory.doSynchronousClusterTask(new GetSessionsCountTask(false), false);
            for (Object result : results) {
                if (result == null) {
                    continue;
                }
                total = total + (Integer) result;
Gaston Dombiak's avatar
Gaston Dombiak committed
838 839 840
            }
        }
        return total;
841 842 843
    }

    /**
844 845
     * Returns number of client sessions that are authenticated with the server. This includes
     * anonymous and non-anoymous users.
846
     *
Gaston Dombiak's avatar
Gaston Dombiak committed
847
     * @param onlyLocal true if only sessions connected to this JVM will be considered. Otherwise count cluster wise.
848
     * @return number of client sessions that are authenticated with the server.
849
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
850
    public int getUserSessionsCount(boolean onlyLocal) {
851 852 853 854 855 856 857 858 859
        int total = routingTable.getClientsRoutes(true).size();
        if (!onlyLocal) {
            Collection<Object> results =
                    CacheFactory.doSynchronousClusterTask(new GetSessionsCountTask(true), false);
            for (Object result : results) {
                if (result == null) {
                    continue;
                }
                total = total + (Integer) result;
Gaston Dombiak's avatar
Gaston Dombiak committed
860 861 862
            }
        }
        return total;
863 864
    }

865 866 867
    /**
     * Returns the number of sessions for a user that are available. For the count
     * of all sessions for the user, including sessions that are just starting
868
     * or closed, see {@see #getConnectionsCount(String)}.
869 870 871 872 873
     *
     * @param username the user.
     * @return number of available sessions for a user.
     */
    public int getActiveSessionCount(String username) {
Gaston Dombiak's avatar
Gaston Dombiak committed
874
        return routingTable.getRoutes(new JID(username, serverName, null, true)).size();
875 876
    }

877
    public int getSessionCount(String username) {
878
        // TODO Count ALL sessions not only available
Gaston Dombiak's avatar
Gaston Dombiak committed
879
        return routingTable.getRoutes(new JID(username, serverName, null, true)).size();
880 881 882 883 884 885 886 887
    }

    /**
     * Returns a collection with the established sessions from external components.
     *
     * @return a collection with the established sessions from external components.
     */
    public Collection<ComponentSession> getComponentSessions() {
888 889 890 891 892 893 894
        List<ComponentSession> sessions = new ArrayList<ComponentSession>();
        // Add sessions of external components connected to this JVM
        sessions.addAll(localSessionManager.getComponentsSessions());
        // Add sessions of external components connected to other cluster nodes
        RemoteSessionLocator locator = server.getRemoteSessionLocator();
        if (locator != null) {
            for (Map.Entry<String, byte[]> entry : componentSessionsCache.entrySet()) {
895
                if (!server.getNodeID().equals(entry.getValue())) {
896 897 898 899 900
                    sessions.add(locator.getComponentSession(entry.getValue(), new JID(entry.getKey())));
                }
            }
        }
        return sessions;
901 902 903 904 905 906 907 908 909
    }

    /**
     * Returns the session of the component whose domain matches the specified domain.
     *
     * @param domain the domain of the component session to look for.
     * @return the session of the component whose domain matches the specified domain.
     */
    public ComponentSession getComponentSession(String domain) {
910 911
        // Search in the external components connected to this JVM
        for (ComponentSession session : localSessionManager.getComponentsSessions()) {
912 913 914 915
            if (domain.equals(session.getAddress().getDomain())) {
                return session;
            }
        }
916 917 918 919 920 921 922 923
        // Search in the external components connected to other cluster nodes
        RemoteSessionLocator locator = server.getRemoteSessionLocator();
        if (locator != null) {
            byte[] nodeID = componentSessionsCache.get(domain);
            if (nodeID != null) {
                return locator.getComponentSession(nodeID, new JID(domain));
            }
        }
924 925 926 927 928 929 930 931 932 933 934
        return null;
    }

    /**
     * Returns a collection with the hostnames of the remote servers that currently have an
     * incoming server connection to this server.
     *
     * @return a collection with the hostnames of the remote servers that currently have an
     *         incoming server connection to this server.
     */
    public Collection<String> getIncomingServers() {
935
        return hostnameSessionsCache.keySet();
936 937 938 939 940 941 942 943 944 945
    }

    /**
     * Returns a collection with the hostnames of the remote servers that currently may receive
     * packets sent from this server.
     *
     * @return a collection with the hostnames of the remote servers that currently may receive
     *         packets sent from this server.
     */
    public Collection<String> getOutgoingServers() {
946
        return routingTable.getServerHostnames();
947 948 949 950 951 952
    }

    /**
     * Broadcasts the given data to all connected sessions. Excellent
     * for server administration messages.
     *
Matt Tucker's avatar
Matt Tucker committed
953
     * @param packet the packet to be broadcast.
954
     */
955
    public void broadcast(Message packet) {
956
        routingTable.broadcastPacket(packet, false);
957 958 959 960 961 962 963
    }

    /**
     * Broadcasts the given data to all connected sessions for a particular
     * user. Excellent for updating all connected resources for users such as
     * roster pushes.
     *
Matt Tucker's avatar
Matt Tucker committed
964 965 966
     * @param username the user to send the boradcast to.
     * @param packet the packet to be broadcast.
     * @throws PacketException if a packet exception occurs.
967
     */
968 969 970
    public void userBroadcast(String username, Packet packet) throws PacketException {
        // TODO broadcast to ALL sessions of the user and not only available
        for (JID address : routingTable.getRoutes(new JID(username, serverName, null))) {
971
            packet.setTo(address);
Gaston Dombiak's avatar
Gaston Dombiak committed
972
            routingTable.routePacket(address, packet, true);
973 974 975 976 977 978 979
        }
    }

    /**
     * Removes a session.
     *
     * @param session the session.
980
     * @return true if the requested session was successfully removed.
981
     */
982
    public boolean removeSession(LocalClientSession session) {
983 984 985
        // Do nothing if session is null or if the server is shutting down. Note: When the server
        // is shutting down the serverName will be null.
        if (session == null || serverName == null) {
986
            return false;
987
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
988

989 990 991
        AuthToken authToken = session.getAuthToken();
        // Consider session anonymous (for this matter) if we are closing a session that never authenticated
        boolean anonymous = authToken == null || authToken.isAnonymous();
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        return removeSession(session, session.getAddress(), anonymous, false);
    }

    /**
     * Removes a session.
     *
     * @param session the session or null when session is derived from fullJID.
     * @param fullJID the address of the session.
     * @param anonymous true if the authenticated user is anonymous.
     * @param forceUnavailable true if an unavailable presence must be created and routed.
     * @return true if the requested session was successfully removed.
     */
    public boolean removeSession(ClientSession session, JID fullJID, boolean anonymous, boolean forceUnavailable) {
        // Do nothing if server is shutting down. Note: When the server
        // is shutting down the serverName will be null.
        if (serverName == null) {
            return false;
        }

        if (session == null) {
            session = getSession(fullJID);
        }

        // Remove route to the removed session (anonymous or not)
        boolean removed = routingTable.removeClientRoute(fullJID);
Gaston Dombiak's avatar
Gaston Dombiak committed
1017

1018
        if (removed) {
1019
            // Fire session event.
1020 1021 1022 1023 1024 1025 1026
            if (anonymous) {
                SessionEventDispatcher
                        .dispatchEvent(session, SessionEventDispatcher.EventType.anonymous_session_destroyed);
            }
            else {
                SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.session_destroyed);

1027 1028
            }
        }
1029

1030
        // Remove the session from the pre-Authenticated sessions list (if present)
1031
        boolean preauth_removed =
1032
                localSessionManager.getPreAuthenticatedSessions().remove(fullJID.getResource()) != null;
1033
        // If the user is still available then send an unavailable presence
1034
        if (forceUnavailable || session.getPresence().isAvailable()) {
1035
            Presence offline = new Presence();
1036
            offline.setFrom(fullJID);
Gaston Dombiak's avatar
Gaston Dombiak committed
1037
            offline.setTo(new JID(null, serverName, null, true));
1038 1039 1040
            offline.setType(Presence.Type.unavailable);
            router.route(offline);
        }
1041
        if (removed || preauth_removed) {
1042
            // Decrement the counter of user sessions
Gaston Dombiak's avatar
Gaston Dombiak committed
1043
            connectionsCounter.decrementAndGet();
1044 1045 1046
            return true;
        }
        return false;
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    }

    public int getConflictKickLimit() {
        return conflictLimit;
    }

    /**
     * Returns the temporary keys used by the sessions that has not been authenticated yet. This
     * is an utility method useful for debugging situations.
     *
     * @return the temporary keys used by the sessions that has not been authenticated yet.
     */
    public Collection<String> getPreAuthenticatedKeys() {
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        return localSessionManager.getPreAuthenticatedSessions().keySet();
    }

    /**
     * Returns true if the specified address belongs to a preauthenticated session. Preauthenticated
     * sessions are only available to the local cluster node when running inside of a cluster.
     *
     * @param address the address of the session.
     * @return true if the specified address belongs to a preauthenticated session.
     */
    public boolean isPreAuthenticatedSession(JID address) {
        return serverName.equals(address.getDomain()) &&
                localSessionManager.getPreAuthenticatedSessions().containsKey(address.getResource());
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    }

    public void setConflictKickLimit(int limit) {
        conflictLimit = limit;
        JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
    }

    private class ClientSessionListener implements ConnectionCloseListener {
        /**
         * Handle a session that just closed.
         *
         * @param handback The session that just closed
         */
        public void onConnectionClose(Object handback) {
            try {
1088
                LocalClientSession session = (LocalClientSession) handback;
1089
                try {
1090
                    if ((session.getPresence().isAvailable() || !session.wasAvailable()) &&
1091
                            routingTable.hasClientRoute(session.getAddress())) {
1092 1093 1094 1095 1096 1097
                        // Send an unavailable presence to the user's subscribers
                        // Note: This gives us a chance to send an unavailable presence to the
                        // entities that the user sent directed presences
                        Presence presence = new Presence();
                        presence.setType(Presence.Type.unavailable);
                        presence.setFrom(session.getAddress());
1098
                        router.route(presence);
1099 1100 1101 1102
                    }
                }
                finally {
                    // Remove the session
1103
                    removeSession(session);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                }
            }
            catch (Exception e) {
                // Can't do anything about this problem...
                Log.error(LocaleUtils.getLocalizedString("admin.error.close"), e);
            }
        }
    }

    private class ComponentSessionListener implements ConnectionCloseListener {
        /**
         * Handle a session that just closed.
         *
         * @param handback The session that just closed
         */
        public void onConnectionClose(Object handback) {
1120
            LocalComponentSession session = (LocalComponentSession)handback;
1121
            try {
1122 1123 1124 1125 1126
                // Unbind registered domains for this external component
                for (String domain : session.getExternalComponent().getSubdomains()) {
                    String subdomain = domain.substring(0, domain.indexOf(serverName) - 1);
                    InternalComponentManager.getInstance().removeComponent(subdomain);
                }
1127 1128 1129 1130 1131 1132 1133
            }
            catch (Exception e) {
                // Can't do anything about this problem...
                Log.error(LocaleUtils.getLocalizedString("admin.error.close"), e);
            }
            finally {
                // Remove the session
1134 1135 1136
                localSessionManager.getComponentsSessions().remove(session);
                // Remove track of the cluster node hosting the external component
                componentSessionsCache.remove(session.getAddress().toString());
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
            }
        }
    }

    private class IncomingServerSessionListener implements ConnectionCloseListener {
        /**
         * Handle a session that just closed.
         *
         * @param handback The session that just closed
         */
        public void onConnectionClose(Object handback) {
            IncomingServerSession session = (IncomingServerSession)handback;
            // Remove all the hostnames that were registered for this server session
            for (String hostname : session.getValidatedDomains()) {
                unregisterIncomingServerSession(hostname, session);
            }
        }
    }

    private class OutgoingServerSessionListener implements ConnectionCloseListener {
        /**
         * Handle a session that just closed.
         *
         * @param handback The session that just closed
         */
        public void onConnectionClose(Object handback) {
            OutgoingServerSession session = (OutgoingServerSession)handback;
            // Remove all the hostnames that were registered for this server session
            for (String hostname : session.getHostnames()) {
                // Remove the route to the session using the hostname
1167
                server.getRoutingTable().removeServerRoute(new JID(hostname));
1168 1169 1170 1171
            }
        }
    }

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    private class ConnectionMultiplexerSessionListener implements ConnectionCloseListener {
        /**
         * Handle a session that just closed.
         *
         * @param handback The session that just closed
         */
        public void onConnectionClose(Object handback) {
            ConnectionMultiplexerSession session = (ConnectionMultiplexerSession)handback;
            // Remove all the hostnames that were registered for this server session
            String domain = session.getAddress().getDomain();
1182 1183 1184 1185 1186 1187 1188
            localSessionManager.getConnnectionManagerSessions().remove(session.getAddress().toString());
            // Remove track of the cluster node hosting the CM connection
            multiplexerSessionsCache.remove(session.getAddress().toString());
            if (getConnectionMultiplexerSessions(domain).isEmpty()) {
                // Terminate ClientSessions originated from this connection manager
                // that are still active since the connection manager has gone down
                ConnectionMultiplexerManager.getInstance().multiplexerUnavailable(domain);
1189 1190 1191 1192
            }
        }
    }

1193 1194
    public void initialize(XMPPServer server) {
        super.initialize(server);
1195
        this.server = server;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        router = server.getPacketRouter();
        userManager = server.getUserManager();
        routingTable = server.getRoutingTable();
        serverName = server.getServerInfo().getName();
        serverAddress = new JID(serverName);

        if (JiveGlobals.getBooleanProperty("xmpp.audit.active")) {
            streamIDFactory = new AuditStreamIDFactory();
        }
        else {
            streamIDFactory = new BasicStreamIDFactory();
        }

        String conflictLimitProp = JiveGlobals.getProperty("xmpp.session.conflict-limit");
        if (conflictLimitProp == null) {
            conflictLimit = 0;
            JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
        }
        else {
            try {
                conflictLimit = Integer.parseInt(conflictLimitProp);
            }
            catch (NumberFormatException e) {
                conflictLimit = 0;
                JiveGlobals.setProperty("xmpp.session.conflict-limit", Integer.toString(conflictLimit));
            }
        }
1223 1224

        // Initialize caches.
1225 1226 1227
        componentSessionsCache = CacheFactory.createCache(COMPONENT_SESSION_CACHE_NAME);
        multiplexerSessionsCache = CacheFactory.createCache(CM_CACHE_NAME);
        incomingServerSessionsCache = CacheFactory.createCache(ISS_CACHE_NAME);
1228
        hostnameSessionsCache = CacheFactory.createCache("Sessions by Hostname");
1229 1230 1231
        validatedDomainsCache = CacheFactory.createCache("Validated Domains");
        // Listen to cluster events
        ClusterManager.addListener(this);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    }


    /**
     * Sends a message with a given subject and body to all the active user sessions in the server.
     *
     * @param subject the subject to broadcast.
     * @param body    the body to broadcast.
     */
    public void sendServerMessage(String subject, String body) {
        sendServerMessage(null, subject, body);
    }

    /**
     * Sends a message with a given subject and body to one or more user sessions related to the
     * specified address. If address is null or the address's node is null then the message will be
     * sent to all the user sessions. But if the address includes a node but no resource then
     * the message will be sent to all the user sessions of the requeted user (defined by the node).
     * Finally, if the address is a full JID then the message will be sent to the session associated
     * to the full JID. If no session is found then the message is not sent.
     *
     * @param address the address that defines the sessions that will receive the message.
     * @param subject the subject to broadcast.
     * @param body    the body to broadcast.
     */
    public void sendServerMessage(JID address, String subject, String body) {
        Message packet = createServerMessage(subject, body);
1259 1260 1261 1262 1263
        if (address == null || address.getNode() == null || !userManager.isRegisteredUser(address)) {
            broadcast(packet);
        }
        else if (address.getResource() == null || address.getResource().length() < 1) {
            userBroadcast(address.getNode(), packet);
1264
        }
1265
        else {
Gaston Dombiak's avatar
Gaston Dombiak committed
1266
            routingTable.routePacket(address, packet, true);
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        }
    }

    private Message createServerMessage(String subject, String body) {
        Message message = new Message();
        message.setFrom(serverAddress);
        if (subject != null) {
            message.setSubject(subject);
        }
        message.setBody(body);
        return message;
    }

1280 1281 1282 1283 1284
    public void start() throws IllegalStateException {
        super.start();
        localSessionManager.start();
    }

1285 1286 1287 1288 1289 1290 1291
    public void stop() {
        Log.debug("Stopping server");
        // Stop threads that are sending packets to remote servers
        OutgoingSessionPromise.getInstance().shutdown();
        if (JiveGlobals.getBooleanProperty("shutdownMessage.enabled")) {
            sendServerMessage(null, LocaleUtils.getLocalizedString("admin.shutdown.now"));
        }
1292
        localSessionManager.stop();
1293
        serverName = null;
1294 1295
    }

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    /**
     * Returns true if remote servers are allowed to have more than one connection to this
     * server. Having more than one connection may improve number of packets that can be
     * transfered per second. This setting only used by the server dialback mehod.<p>
     *
     * It is highly recommended that {@link #getServerSessionTimeout()} is enabled so that
     * dead connections to this server can be easily discarded.
     *
     * @return true if remote servers are allowed to have more than one connection to this
     *         server.
     */
    public boolean isMultipleServerConnectionsAllowed() {
        return JiveGlobals.getBooleanProperty("xmpp.server.session.allowmultiple", true);
    }

    /**
     * Sets if remote servers are allowed to have more than one connection to this
     * server. Having more than one connection may improve number of packets that can be
     * transfered per second. This setting only used by the server dialback mehod.<p>
     *
     * It is highly recommended that {@link #getServerSessionTimeout()} is enabled so that
     * dead connections to this server can be easily discarded.
     *
     * @param allowed true if remote servers are allowed to have more than one connection to this
     *        server.
     */
    public void setMultipleServerConnectionsAllowed(boolean allowed) {
        JiveGlobals.setProperty("xmpp.server.session.allowmultiple", Boolean.toString(allowed));
        if (allowed && JiveGlobals.getIntProperty("xmpp.server.session.idle", 10 * 60 * 1000) <= 0)
        {
            Log.warn("Allowing multiple S2S connections for each domain, without setting a " +
                    "maximum idle timeout for these connections, is unrecommended! Either " +
                    "set xmpp.server.session.allowmultiple to 'false' or change " +
                    "xmpp.server.session.idle to a (large) positive value.");
        }
    }

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
    /******************************************************
     * Clean up code
     *****************************************************/
    /**
     * Sets the number of milliseconds to elapse between clearing of idle server sessions.
     *
     * @param timeout the number of milliseconds to elapse between clearings.
     */
    public void setServerSessionTimeout(int timeout) {
        if (getServerSessionTimeout() == timeout) {
            return;
        }
        // Set the new property value
        JiveGlobals.setProperty("xmpp.server.session.timeout", Integer.toString(timeout));
    }

    /**
     * Returns the number of milliseconds to elapse between clearing of idle server sessions.
     *
     * @return the number of milliseconds to elapse between clearing of idle server sessions.
     */
    public int getServerSessionTimeout() {
        return JiveGlobals.getIntProperty("xmpp.server.session.timeout", 5 * 60 * 1000);
    }

    public void setServerSessionIdleTime(int idleTime) {
        if (getServerSessionIdleTime() == idleTime) {
            return;
        }
        // Set the new property value
        JiveGlobals.setProperty("xmpp.server.session.idle", Integer.toString(idleTime));
1364

1365 1366 1367 1368 1369 1370 1371
        if (idleTime <= 0 && isMultipleServerConnectionsAllowed() )
        {
            Log.warn("Allowing multiple S2S connections for each domain, without setting a " +
                "maximum idle timeout for these connections, is unrecommended! Either " +
                "set xmpp.server.session.allowmultiple to 'false' or change " +
                "xmpp.server.session.idle to a (large) positive value.");
        }
1372 1373 1374 1375 1376 1377
    }

    public int getServerSessionIdleTime() {
        return JiveGlobals.getIntProperty("xmpp.server.session.idle", 10 * 60 * 1000);
    }

1378
    public void joinedCluster() {
1379 1380 1381
        restoreCacheContent();
    }

1382 1383
    public void joinedCluster(byte[] nodeID) {
        // Do nothing
1384 1385 1386 1387 1388 1389 1390 1391 1392
    }

    public void leftCluster() {
        if (!XMPPServer.getInstance().isShuttingDown()) {
            // Add local sessions to caches
            restoreCacheContent();
        }
    }

1393 1394 1395 1396
    public void leftCluster(byte[] nodeID) {
        // Do nothing
    }

1397 1398 1399 1400 1401 1402 1403
    public void markedAsSeniorClusterMember() {
        // Do nothing
    }

    private void restoreCacheContent() {
        // Add external component sessions hosted locally to the cache (using new nodeID)
        for (Session session : localSessionManager.getComponentsSessions()) {
1404
            componentSessionsCache.put(session.getAddress().toString(), server.getNodeID().toByteArray());
1405 1406 1407 1408
        }

        // Add connection multiplexer sessions hosted locally to the cache (using new nodeID)
        for (String address : localSessionManager.getConnnectionManagerSessions().keySet()) {
1409
            multiplexerSessionsCache.put(address, server.getNodeID().toByteArray());
1410 1411 1412 1413 1414
        }

        // Add incoming server sessions hosted locally to the cache (using new nodeID)
        for (LocalIncomingServerSession session : localSessionManager.getIncomingServerSessions()) {
            String streamID = session.getStreamID().getID();
1415
            incomingServerSessionsCache.put(streamID, server.getNodeID().toByteArray());
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
            for (String hostname : session.getValidatedDomains()) {
                // Update list of sockets/sessions coming from the same remote hostname
                Lock lock = LockManager.getLock(hostname);
                try {
                    lock.lock();
                    List<String> streamIDs = hostnameSessionsCache.get(hostname);
                    if (streamIDs == null) {
                        streamIDs = new ArrayList<String>();
                    }
                    streamIDs.add(streamID);
                    hostnameSessionsCache.put(hostname, streamIDs);
                }
                finally {
                    lock.unlock();
                }
                // Add to clustered cache
                lock = LockManager.getLock(streamID);
                try {
                    lock.lock();
                    Set<String> validatedDomains = validatedDomainsCache.get(streamID);
                    if (validatedDomains == null) {
                        validatedDomains = new HashSet<String>();
                    }
                    boolean added = validatedDomains.add(hostname);
                    if (added) {
                        validatedDomainsCache.put(streamID, validatedDomains);
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }
1449
}