Commit 59095821 authored by Gaston Dombiak's avatar Gaston Dombiak Committed by gato

External components are now using MINA. JM-1269

git-svn-id: http://svn.igniterealtime.org/svn/repos/openfire/trunk@9912 b35dd754-fafc-0310-a699-88a17e54d16e
parent cde5f965
......@@ -322,9 +322,9 @@ public class SessionManager extends BasicModule implements ClusterEventListener
return session;
}
public LocalComponentSession createComponentSession(JID address, Connection conn) throws UnauthorizedException {
public LocalComponentSession createComponentSession(JID address, Connection conn) {
if (serverName == null) {
throw new UnauthorizedException("Server not initialized");
throw new IllegalStateException("Server not initialized");
}
StreamID id = nextStreamID();
LocalComponentSession session = new LocalComponentSession(serverName, conn, id);
......
/**
* $RCSfile: ComponentSocketReader.java,v $
* $Revision: 3174 $
* $Date: 2005-12-08 17:41:00 -0300 (Thu, 08 Dec 2005) $
* $Revision: $
* $Date: $
*
* Copyright (C) 2007 Jive Software. All rights reserved.
* Copyright (C) 2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
......@@ -12,44 +11,51 @@
package org.jivesoftware.openfire.net;
import org.dom4j.Element;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.PacketRouter;
import org.jivesoftware.openfire.RoutingTable;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.session.ComponentSession;
import org.jivesoftware.openfire.session.LocalComponentSession;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.component.ComponentException;
import org.xmpp.packet.IQ;
import org.xmpp.packet.Message;
import org.xmpp.packet.PacketError;
import java.io.IOException;
import java.net.Socket;
import org.xmpp.packet.Presence;
/**
* A SocketReader specialized for component connections. This reader will be used when the open
* stream contains a jabber:component:accept namespace.
* Handler of XML stanzas sent by external components connected directly to the server. Received packet will
* have their FROM attribute overriden to avoid spoofing.<p>
*
* This is an implementation of the XEP-114. In the future we will add support for XEP-225 now that
* we are using MINA things should be easier. Since we are now using MINA incoming traffic is handled
* by a set of worker threads.
*
* @author Gaston Dombiak
*/
public class ComponentSocketReader extends SocketReader {
public class ComponentStanzaHandler extends StanzaHandler {
public ComponentSocketReader(PacketRouter router, RoutingTable routingTable, String serverName,
Socket socket, SocketConnection connection, boolean useBlockingMode) {
super(router, routingTable, serverName, socket, connection, useBlockingMode);
public ComponentStanzaHandler(PacketRouter router, String serverName, Connection connection) {
super(router, serverName, connection);
}
/**
* Only <tt>bind<tt> packets will be processed by this class to bind more domains
* to existing external components. Any other type of packet is unknown and thus
* rejected generating the connection to be closed.
*
* @param doc the unknown DOM element that was received
* @return false if packet is unknown otherwise true.
*/
protected boolean processUnknowPacket(Element doc) {
// Handle subsequent bind packets
if ("bind".equals(doc.getName())) {
boolean processUnknowPacket(Element doc) throws UnauthorizedException {
String tag = doc.getName();
if ("handshake".equals(tag)) {
// External component is trying to authenticate
if (!((LocalComponentSession) session).authenticate(doc.getStringValue())) {
session.close();
}
return true;
} else if ("error".equals(tag) && "stream".equals(doc.getNamespacePrefix())) {
session.close();
return true;
} else if ("bind".equals(tag)) {
// Handle subsequent bind packets
LocalComponentSession componentSession = (LocalComponentSession) session;
// Get the external component of this session
ComponentSession.ExternalComponent component = componentSession.getExternalComponent();
......@@ -107,29 +113,76 @@ public class ComponentSocketReader extends SocketReader {
}
return true;
}
// This is an unknown packet so return false (and close the connection)
return false;
}
boolean createSession(String namespace) throws UnauthorizedException, XmlPullParserException,
IOException {
if ("jabber:component:accept".equals(namespace)) {
// The connected client is a component so create a ComponentSession
session = LocalComponentSession.createSession(serverName, reader, connection);
return true;
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;
}
return false;
super.processIQ(packet);
}
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);
}
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);
}
void startTLS() throws Exception {
// TODO Finish implementation. We need to get the name of the CM if we want to validate certificates of the CM that requested TLS
connection.startTLS(false, "IMPLEMENT_ME", Connection.ClientAuth.disabled);
}
String getNamespace() {
return "jabber:component:accept";
}
String getName() {
return "Component SR - " + hashCode();
boolean validateHost() {
return false;
}
boolean validateHost() {
boolean validateJIDs() {
return false;
}
boolean createSession(String namespace, String serverName, XmlPullParser xpp, Connection connection)
throws XmlPullParserException {
if (getNamespace().equals(namespace)) {
// The connected client is a connection manager so create a ConnectionMultiplexerSession
session = LocalComponentSession.createSession(serverName, xpp, connection);
return true;
}
return false;
}
}
......@@ -22,12 +22,7 @@ import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.packet.IQ;
import org.xmpp.packet.Message;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;
import org.xmpp.packet.Roster;
import org.xmpp.packet.StreamError;
import org.xmpp.packet.*;
import java.io.IOException;
import java.io.StringReader;
......@@ -69,7 +64,7 @@ public abstract class StanzaHandler {
/**
* Server name for which we are attending clients.
*/
private String serverName;
protected String serverName;
/**
* Router used to route incoming packets to the correct channels.
......
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.nio;
import org.apache.mina.common.IoSession;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.net.ComponentStanzaHandler;
import org.jivesoftware.openfire.net.StanzaHandler;
import org.jivesoftware.util.JiveGlobals;
/**
* ConnectionHandler that knows which subclass of {@link StanzaHandler} should
* be created and how to build and configure a {@link NIOConnection}.
*
* @author Gaston Dombiak
*/
public class ComponentConnectionHandler extends ConnectionHandler {
public ComponentConnectionHandler(String serverName) {
super(serverName);
}
NIOConnection createNIOConnection(IoSession session) {
return new NIOConnection(session, XMPPServer.getInstance().getPacketDeliverer());
}
StanzaHandler createStanzaHandler(NIOConnection connection) {
return new ComponentStanzaHandler(XMPPServer.getInstance().getPacketRouter(), serverName, connection);
}
int getMaxIdleTime() {
return JiveGlobals.getIntProperty("xmpp.component.idle", 6 * 60 * 1000) / 1000;
}
}
......@@ -10,28 +10,23 @@
*/
package org.jivesoftware.openfire.session;
import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.StreamID;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.component.ExternalComponentManager;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.net.SocketConnection;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.component.ComponentException;
import org.xmpp.component.ComponentManager;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.StreamError;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
......@@ -44,6 +39,13 @@ import java.util.List;
public class LocalComponentSession extends LocalSession implements ComponentSession {
private LocalExternalComponent component;
/**
* When using XEP-114 (the old spec) components will include in the TO attribute
* of the intial stream header the domain they would like to have. The requested
* domain is used only after the authentication was successful so we need keep track
* of this information until the handshake is done.
*/
private String defaultSubdomain;
/**
* Returns a newly created session between the server and a component. The session will be
......@@ -53,24 +55,19 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
* the JEP-114 where the domain to bind is sent in the TO attribute of the stream header.
*
* @param serverName the name of the server where the session is connecting to.
* @param reader the reader that is reading the provided XML through the connection.
* @param xpp the parser that is reading the provided XML through the connection.
* @param connection the connection with the component.
* @return a newly created session between the server and a component.
* @throws UnauthorizedException if the connection required security but was not secured.
* @throws XmlPullParserException if there was an XML error while creating the session.
* @throws IOException if an IO error occured while creating the session.
*/
public static LocalComponentSession createSession(String serverName, XMPPPacketReader reader,
SocketConnection connection) throws UnauthorizedException, IOException,
XmlPullParserException
{
XmlPullParser xpp = reader.getXPPParser();
public static LocalComponentSession createSession(String serverName, XmlPullParser xpp, Connection connection)
throws XmlPullParserException {
String domain = xpp.getAttributeValue("", "to");
Boolean allowMultiple = reader.getXPPParser().getAttributeValue("", "allowMultiple") != null;
Boolean allowMultiple = xpp.getAttributeValue("", "allowMultiple") != null;
Log.debug("LocalComponentSession: [ExComp] Starting registration of new external component for domain: " + domain);
Log.debug("LocalComponentSession: [ExComp] Starting registration of new external component for domain: " +
domain);
Writer writer = connection.getWriter();
// Default answer header in case of an error
StringBuilder sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='");
......@@ -88,8 +85,7 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
// Include the bad-format in the response
StreamError error = new StreamError(StreamError.Condition.bad_format);
sb.append(error.toXML());
writer.write(sb.toString());
writer.flush();
connection.deliverRawText(sb.toString());
// Close the underlying connection
connection.close();
return null;
......@@ -105,11 +101,11 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
JID componentJID = new JID(domain);
// Check that an external component for the specified subdomain may connect to this server
if (!ExternalComponentManager.canAccess(subdomain)) {
Log.debug("LocalComponentSession: [ExComp] Component is not allowed to connect with subdomain: " + subdomain);
Log.debug(
"LocalComponentSession: [ExComp] Component is not allowed to connect with subdomain: " + subdomain);
StreamError error = new StreamError(StreamError.Condition.host_unknown);
sb.append(error.toXML());
writer.write(sb.toString());
writer.flush();
connection.deliverRawText(sb.toString());
// Close the underlying connection
connection.close();
return null;
......@@ -121,8 +117,7 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
// Include the internal-server-error in the response
StreamError error = new StreamError(StreamError.Condition.internal_server_error);
sb.append(error.toXML());
writer.write(sb.toString());
writer.flush();
connection.deliverRawText(sb.toString());
// Close the underlying connection
connection.close();
return null;
......@@ -134,8 +129,7 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
// Include the conflict error in the response
StreamError error = new StreamError(StreamError.Condition.conflict);
sb.append(error.toXML());
writer.write(sb.toString());
writer.flush();
connection.deliverRawText(sb.toString());
// Close the underlying connection
connection.close();
return null;
......@@ -161,36 +155,13 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
sb.append("\" id=\"");
sb.append(session.getStreamID().toString());
sb.append("\">");
writer.write(sb.toString());
writer.flush();
// Perform authentication. Wait for the handshake (with the secret key)
Element doc = reader.parseDocument().getRootElement();
String digest = "handshake".equals(doc.getName()) ? doc.getStringValue() : "";
String anticipatedDigest = AuthFactory.createDigest(session.getStreamID().getID(), secretKey);
// Check that the provided handshake (secret key + sessionID) is correct
if (!anticipatedDigest.equalsIgnoreCase(digest)) {
Log.debug("LocalComponentSession: [ExComp] Incorrect handshake for component with domain: " + domain);
// The credentials supplied by the initiator are not valid (answer an error
// and close the connection)
writer.write(new StreamError(StreamError.Condition.not_authorized).toXML());
writer.flush();
// Close the underlying connection
connection.close();
return null;
}
else {
// Component has authenticated fine
session.setStatus(STATUS_AUTHENTICATED);
// Send empty handshake element to acknowledge success
writer.write("<handshake></handshake>");
writer.flush();
// Bind the domain to this component
ExternalComponent component = session.getExternalComponent();
InternalComponentManager.getInstance().addComponent(subdomain, component);
Log.debug("LocalComponentSession: [ExComp] External component was registered SUCCESSFULLY with domain: " + domain);
return session;
}
connection.deliverRawText(sb.toString());
// Return session although session has not been authentication yet. Until
// it is authenticated traffic will be rejected except for authentication
// requests
session.defaultSubdomain = subdomain;
return session;
}
catch (Exception e) {
Log.error("An error occured while creating a ComponentSession", e);
......@@ -221,6 +192,56 @@ public class LocalComponentSession extends LocalSession implements ComponentSess
return component;
}
/**
* Authenticate the external component using a digest method. The digest includes the
* stream ID and the secret key of the main domain of the external component. A component
* needs to authenticate just once but it may bind several domains.
*
* @param digest the digest sent in the handshake.
* @return true if the authentication was successful.
*/
public boolean authenticate(String digest) {
// Perform authentication. Wait for the handshake (with the secret key)
String secretKey = ExternalComponentManager.getSecretForComponent(defaultSubdomain);
String anticipatedDigest = AuthFactory.createDigest(getStreamID().getID(), secretKey);
// Check that the provided handshake (secret key + sessionID) is correct
if (!anticipatedDigest.equalsIgnoreCase(digest)) {
Log.debug("LocalComponentSession: [ExComp] Incorrect handshake for component with domain: " +
defaultSubdomain);
// The credentials supplied by the initiator are not valid (answer an error
// and close the connection)
conn.deliverRawText(new StreamError(StreamError.Condition.not_authorized).toXML());
// Close the underlying connection
conn.close();
return false;
}
else {
// Component has authenticated fine
setStatus(STATUS_AUTHENTICATED);
// Send empty handshake element to acknowledge success
conn.deliverRawText("<handshake></handshake>");
// Bind the domain to this component
ExternalComponent component = getExternalComponent();
try {
InternalComponentManager.getInstance().addComponent(defaultSubdomain, component);
Log.debug(
"LocalComponentSession: [ExComp] External component was registered SUCCESSFULLY with domain: " +
defaultSubdomain);
return true;
}
catch (ComponentException e) {
Log.debug("LocalComponentSession: [ExComp] Another component is already using domain: " +
defaultSubdomain);
// The credentials supplied by the initiator are not valid (answer an error
// and close the connection)
conn.deliverRawText(new StreamError(StreamError.Condition.conflict).toXML());
// Close the underlying connection
conn.close();
return false;
}
}
}
/**
* The ExternalComponent acts as a proxy of the remote connected component. Any Packet that is
* sent to this component will be delivered to the real component on the other side of the
......
......@@ -28,6 +28,7 @@ import org.jivesoftware.openfire.container.PluginManagerListener;
import org.jivesoftware.openfire.http.HttpBindManager;
import org.jivesoftware.openfire.net.*;
import org.jivesoftware.openfire.nio.ClientConnectionHandler;
import org.jivesoftware.openfire.nio.ComponentConnectionHandler;
import org.jivesoftware.openfire.nio.MultiplexerConnectionHandler;
import org.jivesoftware.openfire.nio.XMPPCodecFactory;
import org.jivesoftware.util.*;
......@@ -53,7 +54,7 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
private SocketAcceptor socketAcceptor;
private SocketAcceptor sslSocketAcceptor;
private SocketAcceptThread componentSocketThread;
private SocketAcceptor componentAcceptor;
private SocketAcceptThread serverSocketThread;
private SocketAcceptor multiplexerSocketAcceptor;
private ArrayList<ServerPort> ports;
......@@ -83,7 +84,7 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
// Create the port listener for Connections Multiplexers
createConnectionManagerListener();
// Create the port listener for external components
createComponentListener(localIPAddress);
createComponentListener();
// Create the port listener for clients
createClientListeners();
// Create the port listener for secured clients
......@@ -243,23 +244,22 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
}
}
private void createComponentListener(String localIPAddress) {
private void createComponentListener() {
// Start components socket unless it's been disabled.
if (isComponentListenerEnabled()) {
int port = getComponentListenerPort();
try {
componentSocketThread = new SocketAcceptThread(this, new ServerPort(port,
serverName, localIPAddress, false, null, ServerPort.Type.component));
ports.add(componentSocketThread.getServerPort());
componentSocketThread.setDaemon(true);
componentSocketThread.setPriority(Thread.MAX_PRIORITY);
// Create SocketAcceptor with correct number of processors
componentAcceptor = buildSocketAcceptor();
// Customize Executor that will be used by processors to process incoming stanzas
ExecutorThreadModel threadModel = ExecutorThreadModel.getInstance("component");
int eventThreads = JiveGlobals.getIntProperty("xmpp.component.processing.threads", 16);
ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor)threadModel.getExecutor();
eventExecutor.setCorePoolSize(eventThreads + 1);
eventExecutor.setMaximumPoolSize(eventThreads + 1);
eventExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);
}
catch (Exception e) {
System.err.println("Error starting component listener on port " + port + ": " +
e.getMessage());
Log.error(LocaleUtils.getLocalizedString("admin.error.socket-setup"), e);
}
componentAcceptor.getDefaultConfig().setThreadModel(threadModel);
// Add the XMPP codec filter
componentAcceptor.getFilterChain().addFirst("xmpp", new ProtocolCodecFilter(new XMPPCodecFactory()));
}
}
......@@ -268,10 +268,22 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
if (isComponentListenerEnabled()) {
int port = getComponentListenerPort();
try {
componentSocketThread.start();
// Listen on a specific network interface if it has been set.
String interfaceName = JiveGlobals.getXMLProperty("network.interface");
InetAddress bindInterface = null;
if (interfaceName != null) {
if (interfaceName.trim().length() > 0) {
bindInterface = InetAddress.getByName(interfaceName);
}
}
// Start accepting connections
componentAcceptor
.bind(new InetSocketAddress(bindInterface, port), new ComponentConnectionHandler(serverName));
ports.add(new ServerPort(port, serverName, localIPAddress, false, null, ServerPort.Type.component));
List<String> params = new ArrayList<String>();
params.add(Integer.toString(componentSocketThread.getPort()));
params.add(Integer.toString(port));
Log.info(LocaleUtils.getLocalizedString("startup.component", params));
}
catch (Exception e) {
......@@ -283,10 +295,15 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
}
private void stopComponentListener() {
if (componentSocketThread != null) {
componentSocketThread.shutdown();
ports.remove(componentSocketThread.getServerPort());
componentSocketThread = null;
if (componentAcceptor != null) {
componentAcceptor.unbindAll();
for (ServerPort port : ports) {
if (port.isComponentPort()) {
ports.remove(port);
break;
}
}
componentAcceptor = null;
}
}
......@@ -488,12 +505,7 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
public SocketReader createSocketReader(Socket sock, boolean isSecure, ServerPort serverPort,
boolean useBlockingMode) throws IOException {
if (serverPort.isComponentPort()) {
SocketConnection conn = new SocketConnection(deliverer, sock, isSecure);
return new ComponentSocketReader(router, routingTable, serverName, sock, conn,
useBlockingMode);
}
else if (serverPort.isServerPort()) {
if (serverPort.isServerPort()) {
SocketConnection conn = new SocketConnection(deliverer, sock, isSecure);
return new ServerSocketReader(router, routingTable, serverName, sock, conn,
useBlockingMode);
......@@ -578,7 +590,7 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
if (enabled) {
JiveGlobals.setProperty("xmpp.component.socket.active", "true");
// Start the port listener for external components
createComponentListener(localIPAddress);
createComponentListener();
startComponentListener();
}
else {
......@@ -692,7 +704,7 @@ public class ConnectionManagerImpl extends BasicModule implements ConnectionMana
stopComponentListener();
if (isComponentListenerEnabled()) {
// Start the port listener for external components
createComponentListener(localIPAddress);
createComponentListener();
startComponentListener();
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment