Search in sources :

Example 41 with ClientSession

use of org.jivesoftware.openfire.session.ClientSession 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 42 with ClientSession

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

the class SessionManager method getSessions.

public Collection<ClientSession> getSessions(SessionResultFilter filter) {
    List<ClientSession> results = new ArrayList<>();
    if (filter != null) {
        // Grab all the matching sessions
        results.addAll(getSessions());
        // 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<>();
        for (ClientSession session : results) {
            // Now filter on creation date if needed
            filteredResults.add(session);
        }
        // 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<>();
        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;
}
Also used : LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) ArrayList(java.util.ArrayList)

Example 43 with ClientSession

use of org.jivesoftware.openfire.session.ClientSession 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 44 with ClientSession

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

the class SparkManager method handleClientVersion.

/**
     * Handles the IQ version reply. If only a given list of clients are allowed to connect
     * then the reply will be analyzed. If the client is not present in the list, no name
     * was responsed or an IQ error was returned (e.g. IQ version not supported) then
     * the client session will be terminated.
     *
     * @param iq the IQ version reply sent by the client.
     */
private void handleClientVersion(IQ iq) {
    final String clientsAllowed = JiveGlobals.getProperty("clients.allowed", "all");
    final boolean disconnectIfNoMatch = !"all".equals(clientsAllowed);
    if ("all".equals(clientsAllowed) || !disconnectIfNoMatch) {
        // There is nothing to do here. Just return.
        return;
    }
    // Get the client session of the user that sent the IQ version response
    ClientSession session = sessionManager.getSession(iq.getFrom());
    if (session == null) {
        // Do nothing if the session no longer exists
        return;
    }
    if (IQ.Type.result == iq.getType()) {
        // Get list of allowed clients to connect
        final List<String> clients = new ArrayList<String>();
        StringTokenizer clientTokens = new StringTokenizer(clientsAllowed, ",");
        while (clientTokens.hasMoreTokens()) {
            clients.add(clientTokens.nextToken().toLowerCase());
        }
        final String otherClientsAllowed = JiveGlobals.getProperty("other.clients.allowed", "");
        clientTokens = new StringTokenizer(otherClientsAllowed, ",");
        while (clientTokens.hasMoreTokens()) {
            clients.add(clientTokens.nextToken().toLowerCase().trim());
        }
        Element child = iq.getChildElement();
        String clientName = child.elementTextTrim("name");
        boolean disconnect = true;
        if (clientName != null) {
            // Check if the client should be disconnected
            for (String c : clients) {
                if (clientName.toLowerCase().contains(c)) {
                    disconnect = false;
                    break;
                }
            }
        } else {
            // Always disconnect clients that didn't provide their name
            disconnect = true;
        }
        if (disconnect) {
            closeSession(session, clientName != null ? clientName : "Unknown");
        }
    } else {
        // If the session is invalid. Close the connection.
        closeSession(session, "Unknown");
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) ClientSession(org.jivesoftware.openfire.session.ClientSession) Element(org.dom4j.Element) ArrayList(java.util.ArrayList)

Example 45 with ClientSession

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

the class ClientSessionTask method run.

public void run() {
    super.run();
    ClientSession session = (ClientSession) getSession();
    if (session instanceof RemoteClientSession) {
        // The session is being hosted by other cluster node so log this unexpected case
        Cache<String, ClientRoute> usersCache = CacheFactory.createCache(RoutingTableImpl.C2S_CACHE_NAME);
        ClientRoute route = usersCache.get(address.toString());
        NodeID nodeID = route.getNodeID();
        Log.warn("Found remote session instead of local session. JID: " + address + " found in Node: " + nodeID.toByteArray() + " and local node is: " + XMPPServer.getInstance().getNodeID().toByteArray());
    }
    if (operation == Operation.isInitialized) {
        if (session instanceof RemoteClientSession) {
            // Something is wrong since the session shoud be local instead of remote
            // Assume some default value
            result = true;
        } else {
            result = session.isInitialized();
        }
    } else if (operation == Operation.incrementConflictCount) {
        if (session instanceof RemoteClientSession) {
            // Something is wrong since the session shoud be local instead of remote
            // Assume some default value
            result = 2;
        } else {
            result = session.incrementConflictCount();
        }
    }
}
Also used : ClientSession(org.jivesoftware.openfire.session.ClientSession) ClientRoute(org.jivesoftware.openfire.spi.ClientRoute) NodeID(org.jivesoftware.openfire.cluster.NodeID)

Aggregations

ClientSession (org.jivesoftware.openfire.session.ClientSession)49 JID (org.xmpp.packet.JID)15 Element (org.dom4j.Element)14 LocalClientSession (org.jivesoftware.openfire.session.LocalClientSession)14 IQ (org.xmpp.packet.IQ)12 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)8 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)7 PrivacyList (org.jivesoftware.openfire.privacy.PrivacyList)7 StreamError (org.xmpp.packet.StreamError)7 DataForm (org.xmpp.forms.DataForm)6 FormField (org.xmpp.forms.FormField)6 Message (org.xmpp.packet.Message)6 Presence (org.xmpp.packet.Presence)6 PacketRejectedException (org.jivesoftware.openfire.interceptor.PacketRejectedException)5 StringprepException (gnu.inet.encoding.StringprepException)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)3 SessionEntities (org.jivesoftware.openfire.plugin.rest.entity.SessionEntities)3 SQLException (java.sql.SQLException)2