Search in sources :

Example 26 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 27 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 28 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 29 with ClientSession

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

the class GetServerStats method execute.

@Override
public void execute(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.result);
    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.server_name"));
    field.setVariable("name");
    field.addValue(AdminConsole.getAppName());
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.version"));
    field.setVariable("version");
    field.addValue(AdminConsole.getVersionString());
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.domain_name"));
    field.setVariable("domain");
    field.addValue(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.jvm"));
    field.setVariable("os");
    String vmName = System.getProperty("java.vm.name");
    if (vmName == null) {
        vmName = "";
    } else {
        vmName = " -- " + vmName;
    }
    field.addValue(System.getProperty("java.version") + " " + System.getProperty("java.vendor") + vmName);
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.uptime"));
    field.setVariable("uptime");
    field.addValue(XMPPDateTimeFormat.format(XMPPServer.getInstance().getServerInfo().getLastStarted()));
    DecimalFormat mbFormat = new DecimalFormat("#0.00");
    DecimalFormat percentFormat = new DecimalFormat("#0.0");
    Runtime runtime = Runtime.getRuntime();
    double freeMemory = (double) runtime.freeMemory() / (1024 * 1024);
    double maxMemory = (double) runtime.maxMemory() / (1024 * 1024);
    double totalMemory = (double) runtime.totalMemory() / (1024 * 1024);
    double usedMemory = totalMemory - freeMemory;
    double percentFree = ((maxMemory - usedMemory) / maxMemory) * 100.0;
    double percentUsed = 100 - percentFree;
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.memory"));
    field.setVariable("memory");
    field.addValue(mbFormat.format(usedMemory) + " MB of " + mbFormat.format(maxMemory) + " MB (" + percentFormat.format(percentUsed) + "%) used");
    // Make sure that we are only counting based on bareJIDs and not fullJIDs
    Collection<ClientSession> sessions = SessionManager.getInstance().getSessions();
    Set<String> users = new HashSet<>(sessions.size());
    int availableSessions = 0;
    for (ClientSession session : sessions) {
        if (session.getPresence().isAvailable()) {
            users.add(session.getAddress().toBareJID());
            availableSessions++;
        }
    }
    field = form.addField();
    field.setLabel("Available Users");
    field.setVariable("activeusersnum");
    field.addValue(users.size());
    field = form.addField();
    field.setLabel("Available Users Sessions");
    field.setVariable("sessionsnum");
    field.addValue(availableSessions);
    command.add(form.getElement());
}
Also used : DecimalFormat(java.text.DecimalFormat) ClientSession(org.jivesoftware.openfire.session.ClientSession) DataForm(org.xmpp.forms.DataForm) FormField(org.xmpp.forms.FormField)

Example 30 with ClientSession

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

the class IQPrivacyHandler method declineDefaultList.

/**
     * User has specified that there is no default list that should be used for this user.
     *
     * @param packet IQ packet declining default list for all sessions.
     * @param from sender of the IQ packet.
     * @return acknowledge of success.
     */
private IQ declineDefaultList(IQ packet, JID from) {
    IQ result = IQ.createResultIQ(packet);
    Element childElement = packet.getChildElement().createCopy();
    result.setChildElement(childElement);
    if (sessionManager.getSessionCount(from.getNode()) > 1) {
        // Current default list is being used by more than one session
        result.setError(PacketError.Condition.conflict);
    } else {
        // Get the user session
        ClientSession session = sessionManager.getSession(from);
        // Check if a default list was already defined
        if (session.getDefaultList() != null) {
            // Set the existing default list as non-default
            session.getDefaultList().setDefaultList(false);
            // Update the database with the new list state
            provider.updatePrivacyList(from.getNode(), session.getDefaultList());
            session.setDefaultList(null);
        }
    }
    return result;
}
Also used : Element(org.dom4j.Element) ClientSession(org.jivesoftware.openfire.session.ClientSession) IQ(org.xmpp.packet.IQ)

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