FileTransferProxy.java 11.5 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 18
 *
 * 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;
import org.jivesoftware.wildfire.*;
19 20 21 22
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;
23 24
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.container.BasicModule;
25
import org.jivesoftware.wildfire.disco.*;
26 27 28 29 30 31 32 33
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;
34
import java.util.*;
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

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

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

    private String proxyServiceName;

    private IQHandlerInfo info;
    private RoutingTable routingTable;
    private PacketRouter router;
    private String proxyIP;
    private ProxyConnectionManager connectionManager;
56
    private FileTransferManager transferManager;
57 58 59 60 61 62


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

        info = new IQHandlerInfo("query", NAMESPACE);
63
        InterceptorManager.getInstance().addInterceptor(new FileTransferInterceptor());
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    }

    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
            }
        }
        else if (NAMESPACE.equals(namespace)) {
            if (packet.getType() == IQ.Type.get) {
                IQ reply = IQ.createResultIQ(packet);
102 103
                Element newChild = reply.setChildElement("query", NAMESPACE);
                Element response = newChild.addElement("streamhost");
104 105
                response.addAttribute("jid", getServiceDomain());
                response.addAttribute("host", proxyIP);
106
                response.addAttribute("port", String.valueOf(connectionManager.getProxyPort()));
107 108 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 144 145 146 147 148 149 150
                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
        try {
            proxyIP = JiveGlobals.getProperty("xmpp.proxy.externalip",
                    InetAddress.getLocalHost().getHostAddress());
        }
        catch (UnknownHostException e) {
            Log.error("Couldn't discover local host", e);
        }
151 152 153
        transferManager = getFileTransferManager();
        connectionManager = new ProxyConnectionManager(transferManager);
    }
154

155 156
    private FileTransferManager getFileTransferManager() {
        return new DefaultFileTransferManager();
157 158 159 160 161
    }

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

162 163 164
        if (isEnabled()) {
            connectionManager.processConnections(getProxyPort());
            routingTable.addRoute(getAddress(), this);
165 166
            XMPPServer server = XMPPServer.getInstance();

167
            server.getIQDiscoItemsHandler().addServerItemsProvider(this);
168 169
        }
        else {
170
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeServerItemsProvider(this);
171
        }
172 173 174 175 176
    }

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

177 178
        XMPPServer.getInstance().getIQDiscoItemsHandler()
                .removeComponentItem(getAddress().toString());
179
        routingTable.removeRoute(getAddress());
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        connectionManager.disable();
    }

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

        connectionManager.shutdown();
    }

    public void setEnabled(boolean isEnabled) {
        JiveGlobals.setProperty("xmpp.proxy.enabled", Boolean.toString(isEnabled));
        if (isEnabled) {
            start();
        }
        else {
            stop();
        }
    }

    public boolean isEnabled() {
        return connectionManager.isRunning() ||
                JiveGlobals.getBooleanProperty("xmpp.proxy.enabled", true);
    }

    public void setProxyPort(int port) {
        JiveGlobals.setProperty("xmpp.proxy.port", Integer.toString(port));
    }

    public int getProxyPort() {
        return JiveGlobals.getIntProperty("xmpp.proxy.port", 7777);
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    }

    /**
     * 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
227
    public Iterator<DiscoServerItem> getItems() {
228
        List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
229
        if(!isEnabled()) {
230
            return items.iterator();
231
        }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

        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) {
        return Arrays.asList(new String[]{NAMESPACE, "http://jabber.org/protocol/disco#info"})
                .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
289
        return new ArrayList<Element>().iterator();
290 291 292 293 294 295
    }

    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
296
                // Do nothing
297 298 299 300 301 302 303 304 305
            }
            else {
                IQ reply = IQ.createResultIQ((IQ) packet);
                reply.setChildElement(((IQ) packet).getChildElement().createCopy());
                reply.setError(PacketError.Condition.feature_not_implemented);
                router.route(reply);
            }
        }
    }
306 307 308 309 310 311 312 313 314 315 316

    /**
     * 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
317 318 319
                if(childElement == null) {
                    return;
                }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
                String namespace = childElement.getNamespaceURI();
                if ("http://jabber.org/protocol/si".equals(namespace)) {
                    // 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();
                        }
                    }
                }
            }
        }
    }
335
}