FileTransferProxy.java 12.9 KB
Newer Older
1
/**
2 3 4
 * $RCSfile$
 * $Revision: 1217 $
 * $Date: 2005-04-11 18:11:06 -0300 (Mon, 11 Apr 2005) $
5 6
 *
 * Copyright (C) 1999-2006 Jive Software. All rights reserved.
7 8 9 10 11
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

12
package org.jivesoftware.wildfire.filetransfer.proxy;
13 14 15 16 17

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
18 19
import org.jivesoftware.util.PropertyEventDispatcher;
import org.jivesoftware.util.PropertyEventListener;
20 21 22
import org.jivesoftware.wildfire.*;
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.container.BasicModule;
Gaston Dombiak's avatar
Gaston Dombiak committed
23 24 25 26 27
import org.jivesoftware.wildfire.disco.DiscoInfoProvider;
import org.jivesoftware.wildfire.disco.DiscoItemsProvider;
import org.jivesoftware.wildfire.disco.DiscoServerItem;
import org.jivesoftware.wildfire.disco.ServerItemsProvider;
import org.jivesoftware.wildfire.filetransfer.FileTransferManager;
28 29 30 31 32 33 34 35
import org.jivesoftware.wildfire.forms.spi.XDataFormImpl;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;

import java.net.InetAddress;
import java.net.UnknownHostException;
36
import java.util.*;
37 38 39 40 41 42 43 44 45 46 47

/**
 * Manages the transfering of files between two remote entities on the jabber network.
 * This class acts independtly as a Jabber component from the rest of the server, according to
 * the Jabber <a href="http://www.jabber.org/jeps/jep-0065.html">SOCKS5 bytestreams protocol</a>.
 *
 * @author Alexander Wenckus
 */
public class FileTransferProxy extends BasicModule
        implements ServerItemsProvider, DiscoInfoProvider, DiscoItemsProvider,
        RoutableChannelHandler {
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    /**
     * The JiveProperty relating to whether or not the file treansfer proxy is enabled.
     */
    public static final String JIVEPROPERTY_PROXY_ENABLED = "xmpp.proxy.enabled";

    /**
     * The JiveProperty relating to the port the proxy is operating on. Changing this value requires a restart of the
     * proxy.
     */
    public static final String JIVEPROPERTY_PORT = "xmpp.proxy.port";

    /**
     * Whether or not the file transfer proxy is enabled by default.
     */
    public static final boolean DEFAULT_IS_PROXY_ENABLED = true;

    /**
     * The default port of the file transfer proxy
     */
    public static final int DEFAULT_PORT = 7777;

69 70 71 72 73 74 75
    private String proxyServiceName;

    private IQHandlerInfo info;
    private RoutingTable routingTable;
    private PacketRouter router;
    private String proxyIP;
    private ProxyConnectionManager connectionManager;
76

77
    private InetAddress bindInterface;
78 79 80 81 82


    public FileTransferProxy() {
        super("SOCKS5 file transfer proxy");

83 84
        info = new IQHandlerInfo("query", FileTransferManager.NAMESPACE_BYTESTREAMS);

85
        PropertyEventDispatcher.addListener(new FileTransferPropertyListener());
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    }

    public boolean handleIQ(IQ packet) throws UnauthorizedException {
        Element childElement = packet.getChildElement();
        String namespace = null;

        // ignore errors
        if (packet.getType() == IQ.Type.error) {
            return true;
        }
        if (childElement != null) {
            namespace = childElement.getNamespaceURI();
        }

        if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
101 102 103
            IQ reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(packet);
            router.route(reply);
            return true;
104 105
        }
        else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
106 107 108 109
            // a component
            IQ reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(packet);
            router.route(reply);
            return true;
110
        }
111
        else if (FileTransferManager.NAMESPACE_BYTESTREAMS.equals(namespace)) {
112 113
            if (packet.getType() == IQ.Type.get) {
                IQ reply = IQ.createResultIQ(packet);
114 115
                Element newChild = reply.setChildElement("query",
                        FileTransferManager.NAMESPACE_BYTESTREAMS);
116
                Element response = newChild.addElement("streamhost");
117 118
                response.addAttribute("jid", getServiceDomain());
                response.addAttribute("host", proxyIP);
119
                response.addAttribute("port", String.valueOf(connectionManager.getProxyPort()));
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
                router.route(reply);
                return true;
            }
            else if (packet.getType() == IQ.Type.set && childElement != null) {
                String sid = childElement.attributeValue("sid");
                JID from = packet.getFrom();
                JID to = new JID(childElement.elementTextTrim("activate"));

                IQ reply = IQ.createResultIQ(packet);
                try {
                    connectionManager.activate(from, to, sid);
                }
                catch (IllegalArgumentException ie) {
                    Log.error("Error activating connection", ie);
                    reply.setType(IQ.Type.error);
                    reply.setError(new PacketError(PacketError.Condition.not_allowed));
                }

                router.route(reply);
                return true;
            }
        }
        return false;
    }

    public IQHandlerInfo getInfo() {
        return info;
    }

    public void initialize(XMPPServer server) {
        super.initialize(server);

        proxyServiceName = JiveGlobals.getProperty("xmpp.proxy.service", "proxy");
        routingTable = server.getRoutingTable();
        router = server.getPacketRouter();

        // Load the external IP and port information
157 158 159 160 161 162 163 164 165 166 167 168 169
        String interfaceName = JiveGlobals.getXMLProperty("network.interface");
        bindInterface = null;
        if (interfaceName != null) {
            if (interfaceName.trim().length() > 0) {
                try {
                    bindInterface = InetAddress.getByName(interfaceName);
                }
                catch (UnknownHostException e) {
                    Log.error("Error binding to network.interface", e);
                }
            }
        }

170 171
        try {
            proxyIP = JiveGlobals.getProperty("xmpp.proxy.externalip",
172 173
                    (bindInterface != null ? bindInterface.getHostAddress()
                            : InetAddress.getLocalHost().getHostAddress()));
174 175 176 177
        }
        catch (UnknownHostException e) {
            Log.error("Couldn't discover local host", e);
        }
178 179
        
        connectionManager = new ProxyConnectionManager(getFileTransferManager(server));
180
    }
181

182 183
    private FileTransferManager getFileTransferManager(XMPPServer server) {
        return server.getFileTransferManager();
184 185 186 187 188
    }

    public void start() {
        super.start();

189
        if (isEnabled()) {
190
            startProxy();
191 192
        }
        else {
193
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeServerItemsProvider(this);
194
        }
195 196
    }

197
    private void startProxy() {
198
        connectionManager.processConnections(bindInterface, getProxyPort());
199 200 201 202 203 204
        routingTable.addRoute(getAddress(), this);
        XMPPServer server = XMPPServer.getInstance();

        server.getIQDiscoItemsHandler().addServerItemsProvider(this);
    }

205 206 207
    public void stop() {
        super.stop();

208 209
        XMPPServer.getInstance().getIQDiscoItemsHandler()
                .removeComponentItem(getAddress().toString());
210
        routingTable.removeRoute(getAddress());
211 212 213 214 215 216 217 218 219
        connectionManager.disable();
    }

    public void destroy() {
        super.destroy();

        connectionManager.shutdown();
    }

220
    public void enableFileTransferProxy(boolean isEnabled) {
221 222
        JiveGlobals.setProperty(FileTransferProxy.JIVEPROPERTY_PROXY_ENABLED,
                Boolean.toString(isEnabled));
223 224 225
    }

    private void setEnabled(boolean isEnabled) {
226
        if (isEnabled) {
227
            startProxy();
228 229 230 231 232 233
        }
        else {
            stop();
        }
    }

234 235 236 237 238 239 240 241 242 243 244
    /**
     * Returns true if the file transfer proxy is currently enabled and false if it is not.
     *
     * @return Returns true if the file transfer proxy is currently enabled and false if it is not.
     */
    public boolean isProxyEnabled() {
        return connectionManager.isRunning() &&
                JiveGlobals.getBooleanProperty(JIVEPROPERTY_PROXY_ENABLED, DEFAULT_IS_PROXY_ENABLED);
    }

    private boolean isEnabled() {
245
        return JiveGlobals.getBooleanProperty(JIVEPROPERTY_PROXY_ENABLED, DEFAULT_IS_PROXY_ENABLED);
246 247
    }

248 249 250 251 252
    /**
     * Sets the port that the proxy operates on. This requires a restart of the file transfer proxy.
     *
     * @param port The port.
     */
253
    public void setProxyPort(int port) {
254
        JiveGlobals.setProperty(JIVEPROPERTY_PORT, Integer.toString(port));
255 256
    }

257 258 259 260 261
    /**
     * Returns the port that the file transfer proxy is opertating on.
     *
     * @return Returns the port that the file transfer proxy is opertating on.
     */
262
    public int getProxyPort() {
263
        return JiveGlobals.getIntProperty(JIVEPROPERTY_PORT, DEFAULT_PORT);
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    }

    /**
     * Returns the fully-qualifed domain name of this chat service.
     * The domain is composed by the service name and the
     * name of the XMPP server where the service is running.
     *
     * @return the file transfer server domain (service name + host name).
     */
    public String getServiceDomain() {
        return proxyServiceName + "." + XMPPServer.getInstance().getServerInfo().getName();
    }

    public JID getAddress() {
        return new JID(null, getServiceDomain(), null);
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
281
    public Iterator<DiscoServerItem> getItems() {
282
        List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
283
        if(!isEnabled()) {
284
            return items.iterator();
285
        }
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

        items.add(new DiscoServerItem() {
            public String getJID() {
                return getServiceDomain();
            }

            public String getName() {
                return "Socks 5 Bytestreams Proxy";
            }

            public String getAction() {
                return null;
            }

            public String getNode() {
                return null;
            }

            public DiscoInfoProvider getDiscoInfoProvider() {
                return FileTransferProxy.this;
            }

            public DiscoItemsProvider getDiscoItemsProvider() {
                return FileTransferProxy.this;
            }
        });
        return items.iterator();
    }

    public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
        List<Element> identities = new ArrayList<Element>();
        // Answer the identity of the proxy
        Element identity = DocumentHelper.createElement("identity");
        identity.addAttribute("category", "proxy");
        identity.addAttribute("name", "SOCKS5 Bytestreams Service");
        identity.addAttribute("type", "bytestreams");

        identities.add(identity);

        return identities.iterator();
    }

    public Iterator<String> getFeatures(String name, String node, JID senderJID) {
329 330
        return Arrays.asList(FileTransferManager.NAMESPACE_BYTESTREAMS,
                "http://jabber.org/protocol/disco#info").iterator();
331 332 333 334 335 336 337 338 339 340 341 342
    }

    public XDataFormImpl getExtendedInfo(String name, String node, JID senderJID) {
        return null;
    }

    public boolean hasInfo(String name, String node, JID senderJID) {
        return true;
    }

    public Iterator<Element> getItems(String name, String node, JID senderJID) {
        // A proxy server has no items
343
        return new ArrayList<Element>().iterator();
344 345 346 347 348 349
    }

    public void process(Packet packet) throws UnauthorizedException, PacketException {
        // Check if the packet is a disco request or a packet with namespace iq:register
        if (packet instanceof IQ) {
            if (handleIQ((IQ) packet)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
350
                // Do nothing
351 352 353 354 355 356 357 358 359
            }
            else {
                IQ reply = IQ.createResultIQ((IQ) packet);
                reply.setChildElement(((IQ) packet).getChildElement().createCopy());
                reply.setError(PacketError.Condition.feature_not_implemented);
                router.route(reply);
            }
        }
    }
360

361 362 363 364
    private class FileTransferPropertyListener implements PropertyEventListener {
        public void propertySet(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
                Object value = params.get("value");
365 366
                boolean isEnabled = (value != null ? Boolean.parseBoolean(value.toString()) :
                        DEFAULT_IS_PROXY_ENABLED);
367
                setEnabled(isEnabled);
368 369 370 371 372
            }
        }

        public void propertyDeleted(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
373
                setEnabled(DEFAULT_IS_PROXY_ENABLED);
374 375 376 377 378 379 380 381 382
            }
        }

        public void xmlPropertySet(String property, Map params) {
        }

        public void xmlPropertyDeleted(String property, Map params) {
        }
    }
383
}