FileTransferProxy.java 13 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
import org.jivesoftware.wildfire.*;
21
import org.jivesoftware.wildfire.filetransfer.FileTransferManager;
22 23
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.container.BasicModule;
24
import org.jivesoftware.wildfire.disco.*;
25 26 27 28 29 30 31 32
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;
33
import java.util.*;
34 35 36 37 38 39 40 41 42 43 44

/**
 * 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 {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * 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;

66 67 68 69 70 71 72
    private String proxyServiceName;

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

74
    private InetAddress bindInterface;
75 76 77 78 79


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

80 81
        info = new IQHandlerInfo("query", FileTransferManager.NAMESPACE_BYTESTREAMS);

82
        PropertyEventDispatcher.addListener(new FileTransferPropertyListener());
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }

    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)) {
            try {
                IQ reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(packet);
                router.route(reply);
                return true;
            }
            catch (UnauthorizedException e) {
                // Do nothing. This error should never happen
            }
        }
        else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
            try {
                // a component
                IQ reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(packet);
                router.route(reply);
                return true;
            }
            catch (UnauthorizedException e) {
                // Do nothing. This error should never happen
            }
        }
118
        else if (FileTransferManager.NAMESPACE_BYTESTREAMS.equals(namespace)) {
119 120
            if (packet.getType() == IQ.Type.get) {
                IQ reply = IQ.createResultIQ(packet);
121 122
                Element newChild = reply.setChildElement("query",
                        FileTransferManager.NAMESPACE_BYTESTREAMS);
123
                Element response = newChild.addElement("streamhost");
124 125
                response.addAttribute("jid", getServiceDomain());
                response.addAttribute("host", proxyIP);
126
                response.addAttribute("port", String.valueOf(connectionManager.getProxyPort()));
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 157 158 159 160 161 162 163
                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
164 165 166 167 168 169 170 171 172 173 174 175 176
        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);
                }
            }
        }

177 178
        try {
            proxyIP = JiveGlobals.getProperty("xmpp.proxy.externalip",
179 180
                    (bindInterface != null ? bindInterface.getHostAddress()
                            : InetAddress.getLocalHost().getHostAddress()));
181 182 183 184
        }
        catch (UnknownHostException e) {
            Log.error("Couldn't discover local host", e);
        }
185 186
        
        connectionManager = new ProxyConnectionManager(getFileTransferManager(server));
187
    }
188

189 190
    private FileTransferManager getFileTransferManager(XMPPServer server) {
        return server.getFileTransferManager();
191 192 193 194 195
    }

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

196
        if (isEnabled()) {
197
            startProxy();
198 199
        }
        else {
200
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeServerItemsProvider(this);
201
        }
202 203
    }

204
    private void startProxy() {
205
        connectionManager.processConnections(bindInterface, getProxyPort());
206 207 208 209 210 211
        routingTable.addRoute(getAddress(), this);
        XMPPServer server = XMPPServer.getInstance();

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

212 213 214
    public void stop() {
        super.stop();

215 216
        XMPPServer.getInstance().getIQDiscoItemsHandler()
                .removeComponentItem(getAddress().toString());
217
        routingTable.removeRoute(getAddress());
218 219 220 221 222 223 224 225 226
        connectionManager.disable();
    }

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

        connectionManager.shutdown();
    }

227
    public void enableFileTransferProxy(boolean isEnabled) {
228 229
        JiveGlobals.setProperty(FileTransferProxy.JIVEPROPERTY_PROXY_ENABLED,
                Boolean.toString(isEnabled));
230 231 232
    }

    private void setEnabled(boolean isEnabled) {
233
        if (isEnabled) {
234
            startProxy();
235 236 237 238 239 240
        }
        else {
            stop();
        }
    }

241 242 243 244 245 246 247 248 249 250 251
    /**
     * 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() {
252
        return JiveGlobals.getBooleanProperty(JIVEPROPERTY_PROXY_ENABLED, DEFAULT_IS_PROXY_ENABLED);
253 254
    }

255 256 257 258 259
    /**
     * Sets the port that the proxy operates on. This requires a restart of the file transfer proxy.
     *
     * @param port The port.
     */
260
    public void setProxyPort(int port) {
261
        JiveGlobals.setProperty(JIVEPROPERTY_PORT, Integer.toString(port));
262 263
    }

264 265 266 267 268
    /**
     * Returns the port that the file transfer proxy is opertating on.
     *
     * @return Returns the port that the file transfer proxy is opertating on.
     */
269
    public int getProxyPort() {
270
        return JiveGlobals.getIntProperty(JIVEPROPERTY_PORT, DEFAULT_PORT);
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    }

    /**
     * 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
288
    public Iterator<DiscoServerItem> getItems() {
289
        List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
290
        if(!isEnabled()) {
291
            return items.iterator();
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 329 330 331 332 333 334 335

        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) {
336 337
        return Arrays.asList(FileTransferManager.NAMESPACE_BYTESTREAMS,
                "http://jabber.org/protocol/disco#info").iterator();
338 339 340 341 342 343 344 345 346 347 348 349
    }

    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
350
        return new ArrayList<Element>().iterator();
351 352 353 354 355 356
    }

    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
357
                // Do nothing
358 359 360 361 362 363 364 365 366
            }
            else {
                IQ reply = IQ.createResultIQ((IQ) packet);
                reply.setChildElement(((IQ) packet).getChildElement().createCopy());
                reply.setError(PacketError.Condition.feature_not_implemented);
                router.route(reply);
            }
        }
    }
367

368 369 370 371
    private class FileTransferPropertyListener implements PropertyEventListener {
        public void propertySet(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
                Object value = params.get("value");
372 373
                boolean isEnabled = (value != null ? Boolean.parseBoolean(value.toString()) :
                        DEFAULT_IS_PROXY_ENABLED);
374
                setEnabled(isEnabled);
375 376 377 378 379
            }
        }

        public void propertyDeleted(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
380
                setEnabled(DEFAULT_IS_PROXY_ENABLED);
381 382 383 384 385 386 387 388 389
            }
        }

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

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