Java Code Examples for org.jivesoftware.openfire.session.Session

The following examples show how to use org.jivesoftware.openfire.session.Session. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openfire-ofmeet-plugin   Source File: OfMeetPlugin.java    License: Apache License 2.0 6 votes vote down vote up
public void sessionDestroyed(Session session)
{
    Log.debug("OfMeet Plugin -  sessionDestroyed "+ session.getAddress().toString() + "\n" + ((ClientSession) session).getPresence().toXML());

    boolean skypeAvailable = XMPPServer.getInstance().getPluginManager().getPlugin("ofskype") != null;

    if (OfMeetAzure.skypeids.containsKey(session.getAddress().getNode()))
    {
        String sipuri = OfMeetAzure.skypeids.remove(session.getAddress().getNode());

        IQ iq = new IQ(IQ.Type.set);
        iq.setFrom(session.getAddress());
        iq.setTo(XMPPServer.getInstance().getServerInfo().getXMPPDomain());

        Element child = iq.setChildElement("request", "http://igniterealtime.org/protocol/ofskype");
        child.setText("{'action':'stop_skype_user', 'sipuri':'" + sipuri + "'}");
        XMPPServer.getInstance().getIQRouter().route(iq);

        Log.info("OfMeet Plugin - closing skype session " + sipuri);
    }
}
 
Example 2
Source Project: openfire-ofmeet-plugin   Source File: SipComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the user SIP presence to Unregistered if his jabber account is disconnected.
 *
 * @param session the destroyed session
 */
public void sessionDestroyed(Session session) {

    String username = session.getAddress().toBareJID().split("@")[0];

    SipAccount sipAccount = SipAccountDAO.getAccountByUser(username);
    if (sipAccount != null) {
        try {
            sipAccount.setStatus(SipRegisterStatus.Unregistered);
            SipAccountDAO.update(sipAccount);
        }
        catch (SQLException e) {
            Log.error(e.getMessage(), e);
        }
    }

}
 
Example 3
Source Project: Openfire-GCM   Source File: GcmPlugin.java    License: Apache License 2.0 6 votes vote down vote up
public void interceptPacket(Packet packet, Session session,
		boolean incoming, boolean processed) throws PacketRejectedException {

	if (processed) {
		return;
	}
	if (!incoming) {
		return;
	}

	if (packet instanceof Message) {
		Message msg = (Message) packet;
		process(msg);
	}

}
 
Example 4
Source Project: Openfire   Source File: PacketCopier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {
    // Queue intercepted packet only if there are subscribers interested
    if (!subscribers.isEmpty()) {
        boolean queue = false;
        Class packetClass = packet.getClass();
        for (Subscription subscription : subscribers.values()) {
            if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                queue = true;
            }
            else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                queue = true;
            }
            else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                queue = true;
            }
        }
        if (queue) {
            // Queue packet with extra information and let the background thread process it
            packetQueue.add(new InterceptedPacket(packet, incoming, processed));
        }
    }
}
 
Example 5
Source Project: Openfire   Source File: AuditorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void audit(Packet packet, Session session) {
    if (auditManager.isEnabled()) {
        if (packet instanceof Message) {
            if (auditManager.isAuditMessage()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof Presence) {
            if (auditManager.isAuditPresence()) {
                writePacket(packet, session);
            }
        }
        else if (packet instanceof IQ) {
            if (auditManager.isAuditIQ()) {
                writePacket(packet, session);
            }
        }
    }
}
 
Example 6
Source Project: Openfire   Source File: ServerSessionEventDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Dispatches an event to all listeners.
 *
 * @param session the session.
 * @param eventType the event type.
 */
public static void dispatchEvent(Session session, EventType eventType) {
    for (ServerSessionEventListener listener : listeners) {
        try {
            switch (eventType) {
                case session_created: {
                    listener.sessionCreated(session);
                    break;
                }
                case session_destroyed: {
                    listener.sessionDestroyed(session);
                    break;
                }
                default:
                    break;
            }
        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
}
 
Example 7
Source Project: Openfire   Source File: IQDiscoItemsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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);
        // If the requesting entity is subscribed to the account's presence then
        // 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();
    }
}
 
Example 8
Source Project: Openfire   Source File: SASLAuthentication.java    License: Apache License 2.0 6 votes vote down vote up
private static void sendElement(Session session, String element, byte[] data) {
    StringBuilder reply = new StringBuilder(250);
    reply.append("<");
    reply.append(element);
    reply.append(" xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"");
    if (data != null) {
        reply.append(">");
        String data_b64 = StringUtils.encodeBase64(data).trim();
        if ("".equals(data_b64)) {
            data_b64 = "=";
        }
        reply.append(data_b64);
        reply.append("</");
        reply.append(element);
        reply.append(">");
    } else {
        reply.append("/>");
    }
    session.deliverRawText(reply.toString());
}
 
Example 9
Source Project: Openfire   Source File: StanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * After compression was successful we should open a new stream and offer
 * new stream features such as resource binding and session establishment. Notice that
 * resource binding and session establishment should only be offered to clients (i.e. not
 * to servers or external components)
 */
private void compressionSuccessful() {
    StringBuilder sb = new StringBuilder(340);
    sb.append(getStreamHeader());
    sb.append("<stream:features>");
    // Include SASL mechanisms only if client has not been authenticated
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Include available SASL Mechanisms
        sb.append(SASLAuthentication.getSASLMechanisms(session));
    }
    // Include specific features such as resource binding and session establishment
    // for client sessions
    String specificFeatures = session.getAvailableStreamFeatures();
    if (specificFeatures != null) {
        sb.append(specificFeatures);
    }
    sb.append("</stream:features>");
    connection.deliverRawText(sb.toString());
}
 
Example 10
Source Project: Openfire   Source File: StanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
private String getStreamHeader() {
    StringBuilder sb = new StringBuilder(200);
    sb.append("<?xml version='1.0' encoding='");
    sb.append(CHARSET);
    sb.append("'?>");
    if (connection.isFlashClient()) {
        sb.append("<flash:stream xmlns:flash=\"http://www.jabber.com/streams/flash\" ");
    }
    else {
        sb.append("<stream:stream ");
    }
    sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"");
    sb.append(getNamespace());
    sb.append("\" from=\"");
    sb.append(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
    sb.append("\" id=\"");
    sb.append(session.getStreamID());
    sb.append("\" xml:lang=\"");
    sb.append(session.getLanguage().toLanguageTag());
    sb.append("\" version=\"");
    sb.append(Session.MAJOR_VERSION).append('.').append(Session.MINOR_VERSION);
    sb.append("\">");
    return sb.toString();
}
 
Example 11
Source Project: Openfire   Source File: SocketReadingMode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * After compression was successful we should open a new stream and offer
 * new stream features such as resource binding and session establishment. Notice that
 * resource binding and session establishment should only be offered to clients (i.e. not
 * to servers or external components)
 */
protected void compressionSuccessful() throws XmlPullParserException, IOException
{
    StringBuilder sb = new StringBuilder(340);
    sb.append(geStreamHeader());
    sb.append("<stream:features>");
    // Include SASL mechanisms only if client has not been authenticated
    if (socketReader.session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Include available SASL Mechanisms
        sb.append(SASLAuthentication.getSASLMechanisms(socketReader.session));
    }
    // Include specific features such as resource binding and session establishment
    // for client sessions
    String specificFeatures = socketReader.session.getAvailableStreamFeatures();
    if (specificFeatures != null)
    {
        sb.append(specificFeatures);
    }
    sb.append("</stream:features>");
    socketReader.connection.deliverRawText(sb.toString());
}
 
Example 12
Source Project: Openfire   Source File: MultiplexerStanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void processIQ(final IQ packet) {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        IQ reply = new IQ();
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Process the packet
    packetHandler.handle(packet);
}
 
Example 13
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void processIQ(IQ packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        IQ reply = new IQ();
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Keep track of the component that sent an IQ get/set
    if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
        // Handle subsequent bind packets
        LocalComponentSession componentSession = (LocalComponentSession) session;
        // Get the external component of this session
        LocalComponentSession.LocalExternalComponent component =
                (LocalComponentSession.LocalExternalComponent) componentSession.getExternalComponent();
        component.track(packet);
    }
    super.processIQ(packet);
}
 
Example 14
Source Project: Openfire   Source File: ExternalComponentManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Blocks an external component from connecting to the local server. If the component was
 * connected when the permission was revoked then the connection of the entity will be closed.
 *
 * @param subdomain the subdomain of the external component that is not allowed to connect.
 * @throws ModificationNotAllowedException if the operation was denied.
 */
public static void blockAccess(String subdomain) throws ModificationNotAllowedException {
    // Alert listeners about this event
    for (ExternalComponentManagerListener listener : listeners) {
        try {
            listener.componentBlocked(subdomain);
        } catch (Exception e) {
            Log.warn("An exception occurred while dispatching a 'componentBlocked' event!", e);
        }
    }
    // Remove any previous configuration for this external component
    deleteConfigurationFromDB(getConfiguration(subdomain, false));
    // Update the database with the new revoked permission
    ExternalComponentConfiguration config = new ExternalComponentConfiguration(subdomain, false, Permission.blocked, null);
    addConfiguration(config);
    // Check if the component was connected and proceed to close the connection
    String domain = subdomain + "." + XMPPServer.getInstance().getServerInfo().getXMPPDomain();
    Session session = SessionManager.getInstance().getComponentSession(domain);
    if (session != null) {
        Log.debug( "Closing session for external component '{}' as the domain is being blocked. Affected session: {}", domain, session );
        session.close();
    }
}
 
Example 15
Source Project: Openfire   Source File: S2STestService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Logs the status of the session.
 */
private void logSessionStatus() {
    final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain);
    OutgoingServerSession session = XMPPServer.getInstance().getSessionManager().getOutgoingServerSession(pair);
    if (session != null) {
        int connectionStatus = session.getStatus();
        switch(connectionStatus) {
        case Session.STATUS_CONNECTED:
            Log.info("Session is connected.");
            break;
        case Session.STATUS_CLOSED:
            Log.info("Session is closed.");
            break;
        case Session.STATUS_AUTHENTICATED:
            Log.info("Session is authenticated.");
            break;
        }
    } else {
        Log.info("Failed to establish server to server session.");
    }
}
 
Example 16
Source Project: Openfire   Source File: AuditManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) {
    if (!processed) {
        // Ignore packets sent or received by users that are present in the ignore list
        JID from = packet.getFrom();
        JID to = packet.getTo();
        if ((from == null || !ignoreList.contains(from.getNode())) &&
                (to == null || !ignoreList.contains(to.getNode()))) {
            auditor.audit(packet, session);
        }
    }
}
 
Example 17
Source Project: Openfire   Source File: AuditorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public AuditPacket(Packet packet, Session session) {
    element = docFactory.createElement("packet", "http://www.jivesoftware.org");
    creationDate = new Date();
    if (session != null && session.getStreamID() != null) {
        element.addAttribute("streamID", session.getStreamID().toString());
    }
    switch (session == null ? 0 : session.getStatus()) {
        case Session.STATUS_AUTHENTICATED:
            element.addAttribute("status", "auth");
            break;
        case Session.STATUS_CLOSED:
            element.addAttribute("status", "closed");
            break;
        case Session.STATUS_CONNECTED:
            element.addAttribute("status", "connected");
            // This is a workaround. Since we don't want to have an incorrect FROM attribute
            // value we need to clean up the FROM attribute. The FROM attribute will contain
            // an incorrect value since we are setting a fake JID until the user actually
            // authenticates with the server.
            packet.setFrom((String) null);
            break;
        default:
            element.addAttribute("status", "unknown");
            break;
    }
    element.addAttribute("timestamp", auditFormat.format(creationDate));
    element.add(packet.getElement());
}
 
Example 18
Source Project: Openfire   Source File: DefaultFileTransferManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming,
                            boolean processed)
        throws PacketRejectedException
{
    // We only want packets received by the server
    if (!processed && incoming && packet instanceof IQ) {
        IQ iq = (IQ) packet;
        Element childElement = iq.getChildElement();
        if(childElement == null) {
            return;
        }
        String namespace = childElement.getNamespaceURI();
        String profile = childElement.attributeValue("profile");
        // Check that the SI is about file transfer and try creating a file transfer
        if (NAMESPACE_SI.equals(namespace) && NAMESPACE_SI_FILETRANSFER.equals(profile)) {
            // If this is a set, check the feature offer
            if (iq.getType().equals(IQ.Type.set)) {
                JID from = iq.getFrom();
                JID to = iq.getTo();

                FileTransfer transfer = createFileTransfer(from, to, childElement);

                try {
                    if (transfer == null || !acceptIncomingFileTransferRequest(transfer)) {
                        throw new PacketRejectedException();
                    }
                }
                catch (FileTransferRejectedException e) {
                    throw new PacketRejectedException(e);
                }
            }
        }
    }
}
 
Example 19
Source Project: Openfire   Source File: ConnectionMultiplexerManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes an existing client session that was established through a connection manager.
 *
 * @param connectionManagerDomain the connection manager that is handling the connection
 *        of the session.
 * @param streamID the stream ID created by the connection manager for the session.
 */
public void closeClientSession(String connectionManagerDomain, StreamID streamID) {
    Map<StreamID, LocalClientSession> sessions = sessionsByManager.get(connectionManagerDomain);
    if (sessions != null) {
        Session session = sessions.remove(streamID);
        if (session != null) {
            Log.debug( "Closing session: {}", session );
            session.close();
        }
    }
}
 
Example 20
Source Project: Openfire   Source File: ConnectionMultiplexerManager.java    License: Apache License 2.0 5 votes vote down vote up
private void removeSession(Session session) {
    // Remove trace indicating that a connection manager is hosting a connection
    StreamID streamID = session.getStreamID();
    String connectionManagerDomain = streamIDs.remove(streamID);
    // Remove trace indicating that a connection manager is hosting a session
    if (connectionManagerDomain != null) {
        Map<StreamID, LocalClientSession> sessions = sessionsByManager.get(connectionManagerDomain);
        if (sessions != null) {
            sessions.remove(streamID);
        }
    }
}
 
Example 21
Source Project: Openfire   Source File: SessionEventDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Dispatches an event to all listeners.
 *
 * @param session the session.
 * @param eventType the event type.
 */
public static void dispatchEvent(Session session, EventType eventType) {
    for (SessionEventListener listener : listeners) {
        try {
            switch (eventType) {
                case session_created: {
                    listener.sessionCreated(session);
                    break;
                }
                case session_destroyed: {
                    listener.sessionDestroyed(session);
                    break;
                }
                case anonymous_session_created: {
                  listener.anonymousSessionCreated(session);
                  break;
                }
                case anonymous_session_destroyed: {
                  listener.anonymousSessionDestroyed(session);
                  break;
                }
                case resource_bound: {
                  listener.resourceBound(session);
                  break;
                }
                default:
                    break;
            }
        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
}
 
Example 22
Source Project: Openfire   Source File: SocketReadingMode.java    License: Apache License 2.0 5 votes vote down vote up
private String geStreamHeader() {
    StringBuilder sb = new StringBuilder(200);
    sb.append("<?xml version='1.0' encoding='");
    sb.append(CHARSET);
    sb.append("'?>");
    if (socketReader.connection.isFlashClient()) {
        sb.append("<flash:stream xmlns:flash=\"http://www.jabber.com/streams/flash\" ");
    } else {
        sb.append("<stream:stream ");
    }
    sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"");
    sb.append(socketReader.getNamespace()).append('\"');
    if (socketReader.getExtraNamespaces() != null) {
        sb.append(' ');
        sb.append(socketReader.getExtraNamespaces());
    }
    sb.append(" from=\"");
    sb.append(socketReader.session.getServerName());
    sb.append("\" id=\"");
    sb.append(socketReader.session.getStreamID().toString());
    sb.append("\" xml:lang=\"");
    sb.append(socketReader.session.getLanguage().toLanguageTag());
    sb.append("\" version=\"");
    sb.append(Session.MAJOR_VERSION).append('.').append(Session.MINOR_VERSION);
    sb.append("\">");
    return sb.toString();
}
 
Example 23
Source Project: Openfire   Source File: MultiplexerStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process stanza sent by a client that is connected to a connection manager. The
 * original stanza is wrapped in the route element. Only a single stanza must be
 * wrapped in the route element.
 *
 * @param packet the route element.
 */
private void processRoute(final Route packet) {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Route reply = new Route(packet.getStreamID());
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    // Process the packet
    packetHandler.route(packet);
}
 
Example 24
Source Project: Openfire   Source File: SocketConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Normal connection close will attempt to write the stream end tag. Otherwise this method
 * forces the connection closed immediately. This method will be called from {@link SocketSendingTracker} 
 * when sending data over the socket has taken a long time and we need to close the socket, discard
 * the connection and its session.
 */
private void close(boolean force) {
    if (state.compareAndSet(State.OPEN, State.CLOSED)) {
        
        if (session != null) {
            session.setStatus(Session.STATUS_CLOSED);
        }

        if (!force) {
            boolean allowedToWrite = false;
            try {
                requestWriting();
                allowedToWrite = true;
                // Register that we started sending data on the connection
                writeStarted();
                writer.write("</stream:stream>");
                if (flashClient) {
                    writer.write('\0');
                }
                writer.flush();
            }
            catch (Exception e) {
                Log.debug("Failed to deliver stream close tag: " + e.getMessage());
            }
            
            // Register that we finished sending data on the connection
            writeFinished();
            if (allowedToWrite) {
                releaseWriting();
            }
        }
            
        closeConnection();
        notifyCloseListeners();
        listeners.clear();
    }
}
 
Example 25
Source Project: Openfire   Source File: VirtualConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes the session, the virtual connection and notifies listeners that the connection
 * has been closed.
 */
@Override
public void close() {
    if (state.compareAndSet(State.OPEN, State.CLOSED)) {
        
        if (session != null) {
            session.setStatus(Session.STATUS_CLOSED);
        }

        // See OF-1596
        // The notification will trigger some shutdown procedures that, amongst other things,
        // check what type of session (eg: anonymous) is being closed. This check depends on the
        // session still being available.
        //
        // For that reason, it's important to first notify the listeners, and then close the
        // session - not the other way around.
        //
        // This fixes a very visible bug where MUC users would remain in the MUC room long after
        // their session was closed. Effectively, the bug prevents the MUC room from getting a
        // presence update to notify it that the user logged off.
        notifyCloseListeners();
        listeners.clear();

        try {
            closeVirtualConnection();
        } catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error.close") + "\n" + toString(), e);
        }
    }
}
 
Example 26
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processPresence(Presence packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Presence reply = new Presence();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processPresence(packet);
}
 
Example 27
Source Project: Openfire   Source File: ComponentStanzaHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void processMessage(Message packet) throws UnauthorizedException {
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        // Session is not authenticated so return error
        Message reply = new Message();
        reply.setID(packet.getID());
        reply.setTo(packet.getFrom());
        reply.setFrom(packet.getTo());
        reply.setError(PacketError.Condition.not_authorized);
        session.process(reply);
        return;
    }
    super.processMessage(packet);
}
 
Example 28
Source Project: Openfire   Source File: Channel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Enqueus a message to be handled by this channel. After the ChannelHandler is done
 * processing the message, it will be sent to the next channel. Messages with a higher
 * priority will be handled first.
 *
 * @param packet an XMPP packet to add to the channel for processing.
 */
public void add( final T packet )
{
    Runnable r = new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                channelHandler.process( packet );
            }
            catch ( Exception e )
            {
                Log.error( LocaleUtils.getLocalizedString( "admin.error" ), e );

                try
                {
                    Session session = SessionManager.getInstance().getSession( packet.getFrom() );
                    if ( session != null )
                    {
                        Log.debug( "Closing session of '{}': {}", packet.getFrom(), session );
                        session.close();
                    }
                }
                catch ( Exception e1 )
                {
                    Log.error( "Unexpected exception while trying to close session of '{}'.", packet.getFrom(), e1 );
                }
            }
        }
    };
    executor.execute(r);
}
 
Example 29
Source Project: Openfire   Source File: S2STestService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return A String representation of the certificate chain for the connection to the domain under test.
 */
private String getCertificates() {
    final DomainPair pair = new DomainPair(XMPPServer.getInstance().getServerInfo().getXMPPDomain(), domain);
    Session session = XMPPServer.getInstance().getSessionManager().getOutgoingServerSession(pair);
    StringBuilder certs = new StringBuilder();
    if (session != null) {
        Log.info("Successfully negotiated TLS connection.");
        Certificate[] certificates = session.getPeerCertificates();
        for (Certificate certificate : certificates) {
            X509Certificate x509cert = (X509Certificate) certificate;
            certs.append("--\nSubject: ");
            certs.append(x509cert.getSubjectDN());

            List<String> subjectAltNames = new SANCertificateIdentityMapping().mapIdentity(x509cert);
            if (!subjectAltNames.isEmpty()) {
                certs.append("\nSubject Alternative Names: ");
                for (String subjectAltName : subjectAltNames) {
                    certs.append("\n  ");
                    certs.append(subjectAltName);
                }
            }

            certs.append("\nNot Before: ");
            certs.append(x509cert.getNotBefore());
            certs.append("\nNot After: ");
            certs.append(x509cert.getNotAfter());
            certs.append("\n\n-----BEGIN CERTIFICATE-----\n");
            certs.append(DatatypeConverter.printBase64Binary(
                    certificate.getPublicKey().getEncoded()).replaceAll("(.{64})", "$1\n"));
            certs.append("\n-----END CERTIFICATE-----\n\n");
        }
    }
    return certs.toString();
}
 
Example 30
Source Project: Openfire   Source File: S2STestService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Keeps a log of the XMPP traffic, releasing the wait lock on response received.
 */
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {

    if (ping.getTo() == null || packet.getFrom() == null || packet.getTo() == null) {
        return;
    }

    if (!processed
            && (ping.getTo().getDomain().equals(packet.getFrom().getDomain()) || ping.getTo().getDomain().equals(packet.getTo().getDomain()))) {

        // Log all traffic to and from the domain.
        xml.append(packet.toXML());
        xml.append('\n');

        // If we've received our IQ response, stop the test.
        if ( packet instanceof IQ )
        {
            final IQ iq = (IQ) packet;
            if ( iq.isResponse() && ping.getID().equals( iq.getID() ) && ping.getTo().equals( iq.getFrom() ) ) {
                Log.info("Successful server to server response received.");
                waitUntil.release();
            }
        }
    }
}