FileTransferProxy.java 16.8 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 12 13 14 15 16 17
 *
 * 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.wildfire.filetransfer;

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 22 23 24
import org.jivesoftware.wildfire.filetransfer.spi.DefaultFileTransferManager;
import org.jivesoftware.wildfire.interceptor.InterceptorManager;
import org.jivesoftware.wildfire.interceptor.PacketInterceptor;
import org.jivesoftware.wildfire.interceptor.PacketRejectedException;
25 26
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.container.BasicModule;
27
import org.jivesoftware.wildfire.disco.*;
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    /**
     * The JiveProperty relating to whether or not file transfer is currently enabled. If file transfer is disabled
     * all known file transfer related packets are blocked, it also goes with out saying that the file transfer proxy
     * is then disabled.
     */
    public static final String JIVEPROPERTY_FILE_TRANSFER_ENABLED = "xmpp.filetransfer.enabled";

    /**
     * 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;

    /**
     * Whether or not the file transfer is enabled.
     */
    public static final boolean DEFAULT_IS_FILE_TRANSFER_ENABLED = true;

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

    private static final String NAMESPACE_BYTESTREAMS = "http://jabber.org/protocol/bytestreams";

    /**
     * Stream Initiation, SI, namespace
     */
    private static final String NAMESPACE_SI = "http://jabber.org/protocol/si";
87

88 89
    private static final List<String> FILETRANSFER_NAMESPACES
            = Arrays.asList(NAMESPACE_BYTESTREAMS, NAMESPACE_SI);
90 91 92 93 94 95 96 97

    private String proxyServiceName;

    private IQHandlerInfo info;
    private RoutingTable routingTable;
    private PacketRouter router;
    private String proxyIP;
    private ProxyConnectionManager connectionManager;
98
    private FileTransferManager transferManager;
99
    private boolean isFileTransferEnabled;
100
    private InetAddress bindInterface;
101 102 103 104 105


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

106
        info = new IQHandlerInfo("query", NAMESPACE_BYTESTREAMS);
107
        InterceptorManager.getInstance().addInterceptor(new FileTransferInterceptor());
108
        PropertyEventDispatcher.addListener(new FileTransferPropertyListener());
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    }

    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
            }
        }
144
        else if (NAMESPACE_BYTESTREAMS.equals(namespace)) {
145 146
            if (packet.getType() == IQ.Type.get) {
                IQ reply = IQ.createResultIQ(packet);
147
                Element newChild = reply.setChildElement("query", NAMESPACE_BYTESTREAMS);
148
                Element response = newChild.addElement("streamhost");
149 150
                response.addAttribute("jid", getServiceDomain());
                response.addAttribute("host", proxyIP);
151
                response.addAttribute("port", String.valueOf(connectionManager.getProxyPort()));
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
                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
189 190 191 192 193 194 195 196 197 198 199 200 201
        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);
                }
            }
        }

202 203
        try {
            proxyIP = JiveGlobals.getProperty("xmpp.proxy.externalip",
204 205
                    (bindInterface != null ? bindInterface.getHostAddress()
                            : InetAddress.getLocalHost().getHostAddress()));
206 207 208 209
        }
        catch (UnknownHostException e) {
            Log.error("Couldn't discover local host", e);
        }
210

211 212
        transferManager = getFileTransferManager();
        connectionManager = new ProxyConnectionManager(transferManager);
213
        isFileTransferEnabled = isFileTransferEnabled();
214
    }
215

216 217
    private FileTransferManager getFileTransferManager() {
        return new DefaultFileTransferManager();
218 219 220 221 222
    }

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

223
        if (isEnabled()) {
224
            startProxy();
225 226
        }
        else {
227
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeServerItemsProvider(this);
228
        }
229 230
    }

231
    private void startProxy() {
232
        connectionManager.processConnections(bindInterface, getProxyPort());
233 234 235 236 237 238
        routingTable.addRoute(getAddress(), this);
        XMPPServer server = XMPPServer.getInstance();

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

239 240 241
    public void stop() {
        super.stop();

242 243
        XMPPServer.getInstance().getIQDiscoItemsHandler()
                .removeComponentItem(getAddress().toString());
244
        routingTable.removeRoute(getAddress());
245 246 247 248 249 250 251 252 253
        connectionManager.disable();
    }

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

        connectionManager.shutdown();
    }

254 255 256 257 258 259 260 261 262
    public void enableFileTransfer(boolean isEnabled) {
        JiveGlobals.setProperty(JIVEPROPERTY_FILE_TRANSFER_ENABLED, Boolean.toString(isEnabled));
    }

    public void enableFileTransferProxy(boolean isEnabled) {
        JiveGlobals.setProperty(FileTransferProxy.JIVEPROPERTY_PROXY_ENABLED, Boolean.toString(isEnabled));
    }

    private void setEnabled(boolean isEnabled) {
263
        if (isEnabled) {
264
            startProxy();
265 266 267 268 269 270
        }
        else {
            stop();
        }
    }

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    private void setEnabledFileTransfer(boolean isEnabled) {
        isFileTransferEnabled = isEnabled;
        setEnabled(isEnabled && JiveGlobals.getBooleanProperty(JIVEPROPERTY_PROXY_ENABLED, DEFAULT_IS_PROXY_ENABLED));
    }

    public boolean isFileTransferEnabled() {
        return JiveGlobals.getBooleanProperty(JIVEPROPERTY_FILE_TRANSFER_ENABLED, DEFAULT_IS_FILE_TRANSFER_ENABLED);
    }

    /**
     * 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() {
        return isFileTransferEnabled() && (connectionManager.isRunning() ||
                JiveGlobals.getBooleanProperty(JIVEPROPERTY_PROXY_ENABLED, DEFAULT_IS_PROXY_ENABLED));
293 294
    }

295 296 297 298 299
    /**
     * Sets the port that the proxy operates on. This requires a restart of the file transfer proxy.
     *
     * @param port The port.
     */
300
    public void setProxyPort(int port) {
301
        JiveGlobals.setProperty(JIVEPROPERTY_PORT, Integer.toString(port));
302 303
    }

304 305 306 307 308
    /**
     * Returns the port that the file transfer proxy is opertating on.
     *
     * @return Returns the port that the file transfer proxy is opertating on.
     */
309
    public int getProxyPort() {
310
        return JiveGlobals.getIntProperty(JIVEPROPERTY_PORT, DEFAULT_PORT);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    }

    /**
     * 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
328
    public Iterator<DiscoServerItem> getItems() {
329
        List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
330
        if(!isEnabled()) {
331
            return items.iterator();
332
        }
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        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) {
376
        return Arrays.asList(NAMESPACE_BYTESTREAMS, "http://jabber.org/protocol/disco#info")
377 378 379 380 381 382 383 384 385 386 387 388 389
                .iterator();
    }

    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
390
        return new ArrayList<Element>().iterator();
391 392 393 394 395 396
    }

    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
397
                // Do nothing
398 399 400 401 402 403 404 405 406
            }
            else {
                IQ reply = IQ.createResultIQ((IQ) packet);
                reply.setChildElement(((IQ) packet).getChildElement().createCopy());
                reply.setError(PacketError.Condition.feature_not_implemented);
                router.route(reply);
            }
        }
    }
407 408 409 410 411 412 413 414 415 416 417

    /**
     * Interceptor to grab and validate file transfer meta information.
     */
    private class FileTransferInterceptor implements PacketInterceptor {
        public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
                throws PacketRejectedException {
            // We only want packets recieved by the server
            if (!processed && incoming && packet instanceof IQ) {
                IQ iq = (IQ) packet;
                Element childElement = iq.getChildElement();
Alex Wenckus's avatar
Alex Wenckus committed
418 419 420
                if(childElement == null) {
                    return;
                }
421

422
                String namespace = childElement.getNamespaceURI();
423 424 425 426 427
                if(!isFileTransferEnabled && FILETRANSFER_NAMESPACES.contains(namespace)) {
                    throw new PacketRejectedException("File Transfer Disabled");
                }

                if (NAMESPACE_SI.equals(namespace)) {
428 429 430 431 432 433 434 435 436 437 438 439 440
                    // If this is a set, check the feature offer
                    if (iq.getType().equals(IQ.Type.set)) {
                        JID from = iq.getFrom();
                        JID to = iq.getTo();
                        String packetID = iq.getID();
                        if (!transferManager.acceptIncomingFileTransferRequest(packetID, from, to, childElement)) {
                            throw new PacketRejectedException();
                        }
                    }
                }
            }
        }
    }
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

    private class FileTransferPropertyListener implements PropertyEventListener {
        public void propertySet(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
                Object value = params.get("value");
                boolean isEnabled = (value != null ? Boolean.parseBoolean(value.toString()) : DEFAULT_IS_PROXY_ENABLED);
                setEnabled(isEnabled && isFileTransferEnabled());
            }
            else if(JIVEPROPERTY_FILE_TRANSFER_ENABLED.equalsIgnoreCase(property)) {
                Object value = params.get("value");
                boolean isEnabled = (value != null ? Boolean.parseBoolean(value.toString())
                        : DEFAULT_IS_FILE_TRANSFER_ENABLED);
                setEnabledFileTransfer(isEnabled);
            }
        }

        public void propertyDeleted(String property, Map params) {
            if(JIVEPROPERTY_PROXY_ENABLED.equalsIgnoreCase(property)) {
                setEnabled(DEFAULT_IS_PROXY_ENABLED && isFileTransferEnabled());
            }
            else if(JIVEPROPERTY_FILE_TRANSFER_ENABLED.equalsIgnoreCase(property)){
                setEnabledFileTransfer(DEFAULT_IS_FILE_TRANSFER_ENABLED);
            }
        }

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

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