Search in sources :

Example 11 with Session

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

the class IQDiscoItemsHandler method getUserItems.

@Override
public Iterator<Element> getUserItems(String name, JID senderJID) {
    List<Element> answer = new ArrayList<>();
    try {
        User user = UserManager.getInstance().getUser(name);
        RosterItem item = user.getRoster().getRosterItem(senderJID);
        // answer the user's "available resources"
        if (item.getSubStatus() == RosterItem.SUB_FROM || item.getSubStatus() == RosterItem.SUB_BOTH) {
            for (Session session : SessionManager.getInstance().getSessions(name)) {
                Element element = DocumentHelper.createElement("item");
                element.addAttribute("jid", session.getAddress().toString());
                answer.add(element);
            }
        }
        return answer.iterator();
    } catch (UserNotFoundException e) {
        return answer.iterator();
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) RosterItem(org.jivesoftware.openfire.roster.RosterItem) User(org.jivesoftware.openfire.user.User) DefaultElement(org.dom4j.tree.DefaultElement) Element(org.dom4j.Element) Session(org.jivesoftware.openfire.session.Session)

Example 12 with Session

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

the class RemoteServerManager method blockAccess.

/**
 * Blocks a remote server from connecting to the local server. If the remote server was
 * connected when the permission was revoked then the connection of the entity will be closed.
 *
 * @param domain the domain of the remote server that is not allowed to connect.
 */
public static void blockAccess(String domain) {
    // Remove any previous configuration for this remote server
    deleteConfiguration(domain);
    // Update the database with the new revoked permission
    RemoteServerConfiguration config = new RemoteServerConfiguration(domain);
    config.setPermission(Permission.blocked);
    addConfiguration(config);
    // Check if the remote server was connected and proceed to close the connection
    for (Session session : SessionManager.getInstance().getIncomingServerSessions(domain)) {
        Log.debug("Closing session for domain '{}' as the domain is being blocked. Affected session: {}", domain, session);
        session.close();
    }
    // Can't just lookup a single remote server anymore, so check them all.
    for (DomainPair domainPair : SessionManager.getInstance().getOutgoingDomainPairs()) {
        if (domainPair.getRemote().equals(domain)) {
            Session session = SessionManager.getInstance().getOutgoingServerSession(domainPair);
            Log.debug("Closing (domain-pair) session for domain '{}' as the domain is being blocked. Affected session: {}", domain, session);
            session.close();
        }
    }
}
Also used : DomainPair(org.jivesoftware.openfire.session.DomainPair) Session(org.jivesoftware.openfire.session.Session)

Example 13 with Session

use of org.jivesoftware.openfire.session.Session 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
        // If there's a listener for this result at all, then it's likely that that listener had been registered
        // on this cluster node. For efficiency, try the local cluster node before triggering tasks in the rest
        // of the cluster.
        IQResultListener iqResultListener = resultListeners.remove(packet.getID());
        if (iqResultListener != null) {
            resultTimeout.remove(packet.getID());
            resultPending.remove(packet.getID());
            try {
                iqResultListener.receivedAnswer(packet);
            } catch (Exception e) {
                Log.error("Error processing answer of remote entity. Answer: " + packet.toXML(), e);
            }
            return;
        } else if (ClusterManager.isClusteringStarted()) {
            // Only do lookups in the cluster, after it's determined that the local node cannot process the result.
            // remove it, to reduce the risk of this packet being sent back and forth.
            final NodeID nodeID = resultPending.remove(packet.getID());
            if (nodeID != null && !XMPPServer.getInstance().getNodeID().equals(nodeID)) {
                CacheFactory.doClusterTask(new IQResultListenerTask(packet), nodeID.toByteArray());
                return;
            }
        }
    }
    try {
        // they are not allowed in s2s traffic.
        if (packet.getFrom() == null && !XMPPServer.getInstance().isLocal(recipientJID)) {
            // Stanzas that originate from clients _always_ have a 'from' attribute (as that attribute value is set/
            // overwritten by Openfire upon receiving the stanza, to prevent abuse where a user tries to impersonate
            // someone else). That means that, if we're processing a stanza without a 'from' attribute, that the
            // stanza is very likely to originate from Openfire's code. If we have code that generates a stanza
            // without a 'from' address but addressed to a remote domain, this simply is a bug that we should very
            // verbosely warn about.
            Log.error("Unable to process a stanza that has no 'from' attribute, addressed to a remote entity. Stanza is being dropped: {}", packet.toXML());
            return;
        }
        if (recipientJID != null && (routingTable.hasComponentRoute(recipientJID) || (packet.getFrom() != null && routingTable.hasServerRoute(new DomainPair(packet.getFrom().getDomain(), recipientJID.getDomain()))))) {
            // 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, false)) {
                    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, false) && 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 : IQHandler(org.jivesoftware.openfire.handler.IQHandler) Element(org.dom4j.Element) PrivacyList(org.jivesoftware.openfire.privacy.PrivacyList) PacketRejectedException(org.jivesoftware.openfire.interceptor.PacketRejectedException) IQResultListener(org.xmpp.component.IQResultListener) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) DomainPair(org.jivesoftware.openfire.session.DomainPair) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) NodeID(org.jivesoftware.openfire.cluster.NodeID) IQResultListenerTask(org.jivesoftware.openfire.cluster.IQResultListenerTask) LocalClientSession(org.jivesoftware.openfire.session.LocalClientSession) ClientSession(org.jivesoftware.openfire.session.ClientSession) Session(org.jivesoftware.openfire.session.Session)

Example 14 with Session

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

the class PresenceRouter method handle.

private void handle(Presence packet) {
    JID recipientJID = packet.getTo();
    JID senderJID = packet.getFrom();
    // Check if the packet was sent to the server hostname
    if (recipientJID != null && recipientJID.getNode() == null && recipientJID.getResource() == null && serverName.equals(recipientJID.getDomain())) {
        if (packet.getElement().element("addresses") != null) {
            // Presence includes multicast processing instructions. Ask the multicastRouter
            // to route this packet
            multicastRouter.route(packet);
            return;
        }
    }
    try {
        // Presences sent between components are just routed to the component
        if (recipientJID != null && !XMPPServer.getInstance().isLocal(recipientJID) && !XMPPServer.getInstance().isLocal(senderJID)) {
            // Route the packet
            routingTable.routePacket(recipientJID, packet, false);
            return;
        }
        Presence.Type type = packet.getType();
        // Presence updates (null is 'available')
        if (type == null || Presence.Type.unavailable == type) {
            // check for local server target
            if (recipientJID == null || recipientJID.getDomain() == null || "".equals(recipientJID.getDomain()) || (recipientJID.getNode() == null && recipientJID.getResource() == null) && serverName.equals(recipientJID.getDomain())) {
                entityCapsManager.process(packet);
                updateHandler.process(packet);
            } else {
                // Trigger events for presences of remote users
                if (senderJID != null && !serverName.equals(senderJID.getDomain()) && !routingTable.hasComponentRoute(senderJID)) {
                    entityCapsManager.process(packet);
                }
                // Check that sender session is still active (let unavailable presence go through)
                Session session = sessionManager.getSession(packet.getFrom());
                if (session != null && session.getStatus() == Session.STATUS_CLOSED && type == null) {
                    Log.warn("Rejected available presence: " + packet + " - " + session);
                    return;
                }
                // Broadcast it to all connected resources
                for (JID jid : routingTable.getRoutes(recipientJID, senderJID)) {
                    // Register the sent directed presence
                    updateHandler.directedPresenceSent(packet, jid, recipientJID.toString());
                    // Route the packet
                    routingTable.routePacket(jid, packet, false);
                }
            }
        } else if (// presence subscriptions
        Presence.Type.subscribe == type || Presence.Type.unsubscribe == type || Presence.Type.subscribed == type || Presence.Type.unsubscribed == type) {
            subscribeHandler.process(packet);
        } else if (Presence.Type.probe == type) {
            // Handle a presence probe sent by a remote server
            if (!XMPPServer.getInstance().isLocal(recipientJID)) {
                routingTable.routePacket(recipientJID, packet, false);
            } else {
                // Handle probe to a local user
                presenceManager.handleProbe(packet);
            }
        } else {
            // It's an unknown or ERROR type, just deliver it because there's nothing
            // else to do with it
            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) {
            Log.debug("Closing session of '{}': {}", packet.getFrom(), session);
            session.close();
        }
    }
}
Also used : PacketRejectedException(org.jivesoftware.openfire.interceptor.PacketRejectedException) ClientSession(org.jivesoftware.openfire.session.ClientSession) Session(org.jivesoftware.openfire.session.Session)

Example 15 with Session

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

the class S2STestService method run.

/**
 * Run a test against the domain.
 * @return K-V pairs of debug information.
 * @throws Exception On error.
 */
public Map<String, String> run() throws Exception {
    waitUntil = new Semaphore(0);
    Map<String, String> results = new HashMap<>();
    final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain);
    // Tear down existing routes.
    final SessionManager sessionManager = SessionManager.getInstance();
    for (final Session incomingServerSession : sessionManager.getIncomingServerSessions(domain)) {
        incomingServerSession.close();
    }
    final Session outgoingServerSession = sessionManager.getOutgoingServerSession(pair);
    if (outgoingServerSession != null) {
        outgoingServerSession.close();
    }
    final IQ pingRequest = new IQ(Type.get);
    pingRequest.setChildElement("ping", IQPingHandler.NAMESPACE);
    pingRequest.setFrom(pair.getLocal());
    pingRequest.setTo(domain);
    // Intercept logging.
    final Writer logs = new StringWriter();
    final String appenderName = addAppender(logs);
    // Intercept packets.
    final PacketInterceptor interceptor = new S2SInterceptor(pingRequest);
    InterceptorManager.getInstance().addInterceptor(interceptor);
    // Send ping.
    try {
        Log.info("Sending server to server ping request to " + domain);
        XMPPServer.getInstance().getIQRouter().route(pingRequest);
        // Wait for success or exceed socket timeout.
        waitUntil.tryAcquire(RemoteServerManager.getSocketTimeout(), TimeUnit.MILLISECONDS);
        // Check on the connection status.
        logSessionStatus();
        // Prepare response.
        results.put("certs", getCertificates());
        results.put("stanzas", interceptor.toString());
        results.put("logs", logs.toString());
        return results;
    } finally {
        // Cleanup
        InterceptorManager.getInstance().removeInterceptor(interceptor);
        removeAppender(appenderName);
    }
}
Also used : StringWriter(java.io.StringWriter) DomainPair(org.jivesoftware.openfire.session.DomainPair) SessionManager(org.jivesoftware.openfire.SessionManager) IQ(org.xmpp.packet.IQ) Semaphore(java.util.concurrent.Semaphore) PacketInterceptor(org.jivesoftware.openfire.interceptor.PacketInterceptor) StringWriter(java.io.StringWriter) Writer(java.io.Writer) OutgoingServerSession(org.jivesoftware.openfire.session.OutgoingServerSession) Session(org.jivesoftware.openfire.session.Session)

Aggregations

Session (org.jivesoftware.openfire.session.Session)18 Element (org.dom4j.Element)5 DomainPair (org.jivesoftware.openfire.session.DomainPair)5 IQ (org.xmpp.packet.IQ)5 PacketInterceptor (org.jivesoftware.openfire.interceptor.PacketInterceptor)4 ClientSession (org.jivesoftware.openfire.session.ClientSession)4 PacketRejectedException (org.jivesoftware.openfire.interceptor.PacketRejectedException)3 LocalClientSession (org.jivesoftware.openfire.session.LocalClientSession)3 OutgoingServerSession (org.jivesoftware.openfire.session.OutgoingServerSession)3 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)3 Packet (org.xmpp.packet.Packet)3 Iterator (java.util.Iterator)2 Locale (java.util.Locale)2 Lock (java.util.concurrent.locks.Lock)2 DefaultElement (org.dom4j.tree.DefaultElement)2 PacketException (org.jivesoftware.openfire.PacketException)2 SessionManager (org.jivesoftware.openfire.SessionManager)2 MUCRoom (org.jivesoftware.openfire.muc.MUCRoom)2 ComponentSession (org.jivesoftware.openfire.session.ComponentSession)2 ConnectionMultiplexerSession (org.jivesoftware.openfire.session.ConnectionMultiplexerSession)2