Search in sources :

Example 6 with LocalClientSession

use of org.jivesoftware.openfire.session.LocalClientSession in project Openfire by igniterealtime.

the class SessionController method convertToSessionEntities.

/**
	 * Convert to session entities.
	 *
	 * @param clientSessions the client sessions
	 * @return the session entities
	 * @throws ServiceException the service exception
	 */
private SessionEntities convertToSessionEntities(Collection<ClientSession> clientSessions) throws ServiceException {
    List<SessionEntity> sessions = new ArrayList<SessionEntity>();
    SessionEntities sessionEntities = new SessionEntities(sessions);
    for (ClientSession clientSession : clientSessions) {
        SessionEntity session = new SessionEntity();
        session.setSessionId(clientSession.getAddress().toString());
        if (!clientSession.isAnonymousUser()) {
            try {
                session.setUsername(clientSession.getUsername());
            } catch (UserNotFoundException e) {
                throw new ServiceException("Could not get user", "", ExceptionType.USER_NOT_FOUND_EXCEPTION, Response.Status.NOT_FOUND, e);
            }
        } else {
            session.setUsername("Anonymous");
        }
        session.setRessource(clientSession.getAddress().getResource());
        if (clientSession instanceof LocalClientSession) {
            session.setNode("Local");
        } else {
            session.setNode("Remote");
        }
        String status = "";
        if (clientSession.getStatus() == Session.STATUS_CLOSED) {
            status = "Closed";
        } else if (clientSession.getStatus() == Session.STATUS_CONNECTED) {
            status = "Connected";
        } else if (clientSession.getStatus() == Session.STATUS_AUTHENTICATED) {
            status = "Authenticated";
        } else {
            status = "Unkown";
        }
        session.setSessionStatus(status);
        if (clientSession.getPresence() != null) {
            session.setPresenceMessage(clientSession.getPresence().getStatus());
            Presence.Show show = clientSession.getPresence().getShow();
            if (show == Presence.Show.away) {
                session.setPresenceStatus("Away");
            } else if (show == Presence.Show.chat) {
                session.setPresenceStatus("Available to Chat");
            } else if (show == Presence.Show.dnd) {
                session.setPresenceStatus("Do Not Disturb");
            } else if (show == Presence.Show.xa) {
                session.setPresenceStatus("Extended Away");
            } else if (show == null) {
                session.setPresenceStatus("Online");
            } else {
                session.setPresenceStatus("Unknown/Not Recognized");
            }
            session.setPriority(clientSession.getPresence().getPriority());
        }
        try {
            session.setHostAddress(clientSession.getHostAddress());
            session.setHostName(clientSession.getHostName());
        } catch (UnknownHostException e) {
            LOG.error("UnknownHostException", e);
        }
        session.setCreationDate(clientSession.getCreationDate());
        session.setLastActionDate(clientSession.getLastActiveDate());
        session.setSecure(clientSession.isSecure());
        sessions.add(session);
    }
    return sessionEntities;
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ServiceException(org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException) UnknownHostException(java.net.UnknownHostException) SessionEntity(org.jivesoftware.openfire.plugin.rest.entity.SessionEntity) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) ArrayList(java.util.ArrayList) Presence(org.xmpp.packet.Presence) SessionEntities(org.jivesoftware.openfire.plugin.rest.entity.SessionEntities)

Example 7 with LocalClientSession

use of org.jivesoftware.openfire.session.LocalClientSession in project Openfire by igniterealtime.

the class IQRouter method handle.

private void handle(IQ packet) {
    JID recipientJID = packet.getTo();
    // Check if the packet was sent to the server hostname
    if (recipientJID != null && recipientJID.getNode() == null && recipientJID.getResource() == null && serverName.equals(recipientJID.getDomain())) {
        Element childElement = packet.getChildElement();
        if (childElement != null && childElement.element("addresses") != null) {
            // Packet includes multicast processing instructions. Ask the multicastRouter
            // to route this packet
            multicastRouter.route(packet);
            return;
        }
    }
    if (packet.getID() != null && (IQ.Type.result == packet.getType() || IQ.Type.error == packet.getType())) {
        // The server got an answer to an IQ packet that was sent from the server
        IQResultListener iqResultListener = resultListeners.remove(packet.getID());
        if (iqResultListener != null) {
            resultTimeout.remove(packet.getID());
            if (iqResultListener != null) {
                try {
                    iqResultListener.receivedAnswer(packet);
                } catch (Exception e) {
                    Log.error("Error processing answer of remote entity. Answer: " + packet.toXML(), e);
                }
                return;
            }
        }
    }
    try {
        // Check for registered components, services or remote servers
        if (recipientJID != null && (routingTable.hasComponentRoute(recipientJID) || routingTable.hasServerRoute(recipientJID))) {
            // A component/service/remote server was found that can handle the Packet
            routingTable.routePacket(recipientJID, packet, false);
            return;
        }
        if (isLocalServer(recipientJID)) {
            // Let the server handle the Packet
            Element childElement = packet.getChildElement();
            String namespace = null;
            if (childElement != null) {
                namespace = childElement.getNamespaceURI();
            }
            if (namespace == null) {
                if (packet.getType() != IQ.Type.result && packet.getType() != IQ.Type.error) {
                    // Do nothing. We can't handle queries outside of a valid namespace
                    Log.warn("Unknown packet " + packet.toXML());
                }
            } else {
                // Check if communication to local users is allowed
                if (recipientJID != null && userManager.isRegisteredUser(recipientJID.getNode())) {
                    PrivacyList list = PrivacyListManager.getInstance().getDefaultPrivacyList(recipientJID.getNode());
                    if (list != null && list.shouldBlockPacket(packet)) {
                        // Communication is blocked
                        if (IQ.Type.set == packet.getType() || IQ.Type.get == packet.getType()) {
                            // Answer that the service is unavailable
                            sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                        }
                        return;
                    }
                }
                IQHandler handler = getHandler(namespace);
                if (handler == null) {
                    if (recipientJID == null) {
                        // Answer an error since the server can't handle the requested namespace
                        sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                    } else if (recipientJID.getNode() == null || "".equals(recipientJID.getNode())) {
                        // Answer an error if JID is of the form <domain>
                        sendErrorPacket(packet, PacketError.Condition.feature_not_implemented);
                    } else {
                        // JID is of the form <node@domain>
                        // Answer an error since the server can't handle packets sent to a node
                        sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                    }
                } else {
                    handler.process(packet);
                }
            }
        } else {
            // If the user account identified by the 'to' attribute does not exist, how the stanza is processed depends on the stanza type.
            if (recipientJID != null && recipientJID.getNode() != null && serverName.equals(recipientJID.getDomain()) && !userManager.isRegisteredUser(recipientJID.getNode()) && sessionManager.getSession(recipientJID) == null && (IQ.Type.set == packet.getType() || IQ.Type.get == packet.getType())) {
                // For an IQ stanza, the server MUST return a <service-unavailable/> stanza error to the sender.
                sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                return;
            }
            ClientSession session = sessionManager.getSession(packet.getFrom());
            boolean isAcceptable = true;
            if (session instanceof LocalClientSession) {
                // Check if we could process IQ stanzas from the recipient.
                // If not, return a not-acceptable error as per XEP-0016:
                // If the user attempts to send an outbound stanza to a contact and that stanza type is blocked, the user's server MUST NOT route the stanza to the contact but instead MUST return a <not-acceptable/> error
                IQ dummyIQ = packet.createCopy();
                dummyIQ.setFrom(packet.getTo());
                dummyIQ.setTo(packet.getFrom());
                if (!((LocalClientSession) session).canProcess(dummyIQ)) {
                    packet.setTo(session.getAddress());
                    packet.setFrom((JID) null);
                    packet.setError(PacketError.Condition.not_acceptable);
                    session.process(packet);
                    isAcceptable = false;
                }
            }
            if (isAcceptable) {
                // JID is of the form <node@domain/resource> or belongs to a remote server
                // or to an uninstalled component
                routingTable.routePacket(recipientJID, packet, false);
            }
        }
    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.routing"), e);
        Session session = sessionManager.getSession(packet.getFrom());
        if (session != null) {
            IQ reply = IQ.createResultIQ(packet);
            reply.setError(PacketError.Condition.internal_server_error);
            session.process(reply);
        }
    }
}
Also used : IQResultListener(org.xmpp.component.IQResultListener) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) IQHandler(org.jivesoftware.openfire.handler.IQHandler) Element(org.dom4j.Element) PrivacyList(org.jivesoftware.openfire.privacy.PrivacyList) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) PacketRejectedException(org.jivesoftware.openfire.interceptor.PacketRejectedException) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) Session(org.jivesoftware.openfire.session.Session)

Example 8 with LocalClientSession

use of org.jivesoftware.openfire.session.LocalClientSession in project Openfire by igniterealtime.

the class SessionManager method changePriority.

/**
     * Change the priority of a session, that was already available, associated with the sender.
     *
     * @param session   The session whose presence priority has been modified
     * @param oldPriority The old priority for the session
     */
public void changePriority(LocalClientSession session, int oldPriority) {
    if (session.getAuthToken().isAnonymous()) {
        // Do nothing if the session belongs to an anonymous user
        return;
    }
    int newPriority = session.getPresence().getPriority();
    if (newPriority < 0 || oldPriority >= 0) {
        // Do nothing if new presence priority is not positive and old presence negative
        return;
    }
    // Check presence's priority of other available resources
    JID searchJID = session.getAddress().asBareJID();
    for (JID address : routingTable.getRoutes(searchJID, null)) {
        if (address.equals(session.getAddress())) {
            continue;
        }
        ClientSession otherSession = routingTable.getClientRoute(address);
        if (otherSession.getPresence().getPriority() >= 0) {
            return;
        }
    }
    // 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);
        }
    }
}
Also used : JID(org.xmpp.packet.JID) Message(org.xmpp.packet.Message) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession)

Example 9 with LocalClientSession

use of org.jivesoftware.openfire.session.LocalClientSession in project Openfire by igniterealtime.

the class IQBindHandler method handleIQ.

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    LocalClientSession session = (LocalClientSession) sessionManager.getSession(packet.getFrom());
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during resource binding. Session not found in " + sessionManager.getPreAuthenticatedKeys() + " for key " + packet.getFrom());
        // This error packet will probably won't make it through
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    IQ reply = IQ.createResultIQ(packet);
    Element child = reply.setChildElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
    // Check if the client specified a desired resource
    String resource = packet.getChildElement().elementTextTrim("resource");
    if (resource == null || resource.length() == 0) {
        // None was defined so use the random generated resource
        resource = session.getAddress().getResource();
    } else {
        // Check that the desired resource is valid
        try {
            resource = JID.resourceprep(resource);
        } catch (StringprepException e) {
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.jid_malformed);
            // Send the error directly since a route does not exist at this point.
            session.process(reply);
            return null;
        }
    }
    // Get the token that was generated during the SASL authentication
    AuthToken authToken = session.getAuthToken();
    if (authToken == null) {
        // User must be authenticated before binding a resource
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.not_authorized);
        // Send the error directly since a route does not exist at this point.
        session.process(reply);
        return reply;
    }
    if (authToken.isAnonymous()) {
        // User used ANONYMOUS SASL so initialize the session as an anonymous login
        session.setAnonymousAuth();
    } else {
        String username = authToken.getUsername().toLowerCase();
        // If a session already exists with the requested JID, then check to see
        // if we should kick it off or refuse the new connection
        ClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true));
        if (oldSession != null) {
            try {
                int conflictLimit = sessionManager.getConflictKickLimit();
                if (conflictLimit == SessionManager.NEVER_KICK) {
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.conflict);
                    // Send the error directly since a route does not exist at this point.
                    session.process(reply);
                    return null;
                }
                int conflictCount = oldSession.incrementConflictCount();
                if (conflictCount > conflictLimit) {
                    // Kick out the old connection that is conflicting with the new one
                    StreamError error = new StreamError(StreamError.Condition.conflict);
                    oldSession.deliverRawText(error.toXML());
                    oldSession.close();
                } else {
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.conflict);
                    // Send the error directly since a route does not exist at this point.
                    session.process(reply);
                    return null;
                }
            } catch (Exception e) {
                Log.error("Error during login", e);
            }
        }
        // If the connection was not refused due to conflict, log the user in
        session.setAuthToken(authToken, resource);
    }
    child.addElement("jid").setText(session.getAddress().toString());
    // Send the response directly since a route does not exist at this point.
    session.process(reply);
    // After the client has been informed, inform all listeners as well.
    SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.resource_bound);
    return null;
}
Also used : LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) StringprepException(gnu.inet.encoding.StringprepException) StreamError(org.xmpp.packet.StreamError) JID(org.xmpp.packet.JID) Element(org.dom4j.Element) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) IQ(org.xmpp.packet.IQ) AuthToken(org.jivesoftware.openfire.auth.AuthToken) StringprepException(gnu.inet.encoding.StringprepException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException)

Example 10 with LocalClientSession

use of org.jivesoftware.openfire.session.LocalClientSession in project Openfire by igniterealtime.

the class ConnectionMultiplexerManager method multiplexerUnavailable.

/**
     * A connection manager has gone unavailable. Close client sessions that were established
     * to the specified connection manager.
     *
     * @param connectionManagerName the connection manager that is no longer available.
     */
public void multiplexerUnavailable(String connectionManagerName) {
    // Remove the connection manager and the hosted sessions
    Map<StreamID, LocalClientSession> sessions = sessionsByManager.remove(connectionManagerName);
    if (sessions != null) {
        for (StreamID streamID : sessions.keySet()) {
            // Remove inverse track of connection manager hosting streamIDs
            streamIDs.remove(streamID);
            // Close the session
            sessions.get(streamID).close();
        }
    }
}
Also used : LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) StreamID(org.jivesoftware.openfire.StreamID)

Aggregations

LocalClientSession (org.jivesoftware.openfire.session.LocalClientSession)14 ClientSession (org.jivesoftware.openfire.session.ClientSession)7 JID (org.xmpp.packet.JID)6 Element (org.dom4j.Element)4 StreamID (org.jivesoftware.openfire.StreamID)4 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)3 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)3 IQ (org.xmpp.packet.IQ)3 StringprepException (gnu.inet.encoding.StringprepException)2 UnknownHostException (java.net.UnknownHostException)2 AuthToken (org.jivesoftware.openfire.auth.AuthToken)2 ConnectionException (org.jivesoftware.openfire.auth.ConnectionException)2 InternalUnauthenticatedException (org.jivesoftware.openfire.auth.InternalUnauthenticatedException)2 PacketRejectedException (org.jivesoftware.openfire.interceptor.PacketRejectedException)2 Message (org.xmpp.packet.Message)2 Presence (org.xmpp.packet.Presence)2 StreamError (org.xmpp.packet.StreamError)2 ArrayList (java.util.ArrayList)1 Connection (org.jivesoftware.openfire.Connection)1 PacketException (org.jivesoftware.openfire.PacketException)1