STUNService.java 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/**
 * $RCSfile$
 * $Revision: 3144 $
 * $Date: 2005-12-01 14:20:11 -0300 (Thu, 01 Dec 2005) $
 *
 * Copyright (C) 2004 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.wildfire.stun;

import de.javawi.jstun.test.demo.StunServer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.*;
import org.jivesoftware.wildfire.auth.UnauthorizedException;
import org.jivesoftware.wildfire.container.BasicModule;
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.forms.spi.XDataFormImpl;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
Gaston Dombiak's avatar
Gaston Dombiak committed
30 31 32 33 34

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
Thiago Camargo's avatar
Thiago Camargo committed
35
import java.util.*;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

/**
 * STUN Server and Service Module
 * Provides especial Address discovery for p2p sessions to be used for media transmission and receiving of UDP packets.
 * Especialy used for behind NAT users to ensure connectivity between parties.
 *
 * @author Thiago Camargo
 */
public class STUNService extends BasicModule implements ServerItemsProvider, RoutableChannelHandler, DiscoInfoProvider, DiscoItemsProvider {

    private String serviceName;
    private RoutingTable routingTable;
    private PacketRouter router;

    private StunServer stunServer = null;
    private String name = "stun";
    private boolean enabled = false;

    private String primaryAddress;
    private String secondaryAddress;
    private int primaryPort = 3478;
Thiago Camargo's avatar
Thiago Camargo committed
57
    private int secondaryPort = 3479;
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 87 88 89 90 91 92 93 94

    public static final String NAMESPACE = "google:jingleinfo";

    /**
     * Constructs a new STUN Service
     */
    public STUNService() {
        super("STUN Service");
    }

    /**
     * Load config using JiveGlobals
     */
    private void loadSTUNConfig() {
        primaryAddress = JiveGlobals.getProperty("stun.address.primary");
        secondaryAddress = JiveGlobals.getProperty("stun.address.secondary");

        if (primaryAddress == null || primaryAddress.equals(""))
            primaryAddress = JiveGlobals.getProperty("xmpp.domain",
                    JiveGlobals.getProperty("network.interface", "localhost"));

        if (secondaryAddress == null || secondaryAddress.equals(""))
            secondaryAddress = "127.0.0.1";

        try {
            primaryPort = Integer.valueOf(JiveGlobals.getProperty("stun.port.primary"));
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }
        try {
            secondaryPort = Integer.valueOf(JiveGlobals.getProperty("stun.port.secondary"));
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }

Thiago Camargo's avatar
Thiago Camargo committed
95
        this.enabled = JiveGlobals.getProperty("stun.enabled") == null || Boolean.parseBoolean(JiveGlobals.getProperty("stun.enabled"));
Thiago Camargo's avatar
Thiago Camargo committed
96

97 98 99 100 101 102 103 104 105 106 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
    }

    public void destroy() {
        super.destroy();
        stunServer = null;
    }

    public void initialize(XMPPServer server) {
        super.initialize(server);
        routingTable = server.getRoutingTable();
        router = server.getPacketRouter();
        loadSTUNConfig();
    }

    public void start() {
        if (isEnabled()) {
            startServer();
        } else {
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeServerItemsProvider(this);
        }
    }

    public void startServer() {
        try {

            InetAddress primary = InetAddress.getByName(primaryAddress);
            InetAddress secondary = InetAddress.getByName(secondaryAddress);

            if (primary != null && secondary != null) {

                stunServer = new StunServer(primaryPort, primary, secondaryPort, secondary);
                serviceName = JiveGlobals.getProperty("stun.serviceName", name);
                serviceName = serviceName == null ? name : serviceName.equals("") ? name : serviceName;

                stunServer.start();

            } else
                setEnabled(false);

        } catch (SocketException e) {
137
            Log.error("Disabling STUN server", e);
138 139
            setEnabled(false);
        } catch (UnknownHostException e) {
140
            Log.error("Disabling STUN server", e);
141 142 143 144 145 146 147 148 149 150 151 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 189 190 191 192 193 194 195 196 197 198
            setEnabled(false);
        }

        if (stunServer != null) {
            routingTable.addRoute(getAddress(), this);
            XMPPServer server = XMPPServer.getInstance();
            server.getIQDiscoItemsHandler().addServerItemsProvider(this);
        }
    }

    public void stop() {
        super.stop();
        this.enabled = false;
        if (stunServer != null)
            stunServer.stop();
        stunServer = null;
        XMPPServer.getInstance().getIQDiscoItemsHandler()
                .removeComponentItem(getAddress().toString());
        if (routingTable != null)
            routingTable.removeRoute(getAddress());
    }

    public String getName() {
        return serviceName;
    }

    public Iterator<Element> getItems(String name, String node, JID senderJID) {
        List<Element> identities = new ArrayList<Element>();
        // Answer the identity of the proxy
        Element identity = DocumentHelper.createElement("item");
        identity.addAttribute("jid", getServiceDomain());
        identity.addAttribute("name", "STUN Service");
        identities.add(identity);

        return identities.iterator();
    }

    public void process(Packet packet) throws UnauthorizedException, PacketException {
        // Check if user is allowed to send packet to this service
        if (packet instanceof IQ) {
            // Handle disco packets
            IQ iq = (IQ) packet;
            // Ignore IQs of type ERROR or RESULT
            if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) {
                return;
            }
            processIQ(iq);
        }
    }

    private void processIQ(IQ iq) {
        IQ reply = IQ.createResultIQ(iq);
        Element childElement = iq.getChildElement();
        String namespace = childElement.getNamespaceURI();
        Element childElementCopy = iq.getChildElement().createCopy();
        reply.setChildElement(childElementCopy);

        if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
199 200 201
            reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(iq);
            router.route(reply);
            return;
202
        } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
203 204 205 206
            // a component
            reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(iq);
            router.route(reply);
            return;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 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 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
        } else if (NAMESPACE.equals(namespace)) {

            Element stun = childElementCopy.addElement("stun");
            Element server = stun.addElement("server");
            server.addAttribute("host", primaryAddress);
            server.addAttribute("udp", String.valueOf(primaryPort));

        } else {
            // Answer an error since the server can't handle the requested namespace
            reply.setError(PacketError.Condition.service_unavailable);
        }

        try {
            Log.debug("RETURNED:" + reply.toXML());
            router.route(reply);
        }

        catch (Exception e) {
            Log.error(e);
        }
    }

    /**
     * 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 serviceName + "." + XMPPServer.getInstance().getServerInfo().getName();
    }

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

    public Iterator<DiscoServerItem> getItems() {
        List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
        if (!isEnabled()) {
            return items.iterator();
        }

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

            public String getName() {
                return "STUN Service";
            }

            public String getAction() {
                return null;
            }

            public String getNode() {
                return null;
            }

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

            public DiscoItemsProvider getDiscoItemsProvider() {
                return STUNService.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", "STUN Service");
        identity.addAttribute("type", "stun");
        identities.add(identity);

        return identities.iterator();
    }

    public Iterator<String> getFeatures(String name, String node, JID senderJID) {
        return Arrays.asList(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;
    }

    /**
     * Get if the service is enabled.
     *
     * @return enabled
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Set the service enable status.
     *
Thiago Camargo's avatar
Thiago Camargo committed
315
     * @param enabled boolean to enable or disable
316 317 318 319 320 321 322 323 324 325 326 327 328
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
        if (isEnabled()) {
            startServer();
        } else {
            stop();
        }
    }

    /**
     * Get the secondary Port used by the STUN server
     *
Thiago Camargo's avatar
Thiago Camargo committed
329
     * @return secondary Port used by the STUN server
330 331 332 333 334 335 336 337
     */
    public int getSecondaryPort() {
        return secondaryPort;
    }

    /**
     * Get the primary Port used by the STUN server
     *
Thiago Camargo's avatar
Thiago Camargo committed
338
     * @return primary Port used by the STUN server
339 340 341 342 343 344 345 346
     */
    public int getPrimaryPort() {
        return primaryPort;
    }

    /**
     * Get the secondary Address used by the STUN server
     *
Thiago Camargo's avatar
Thiago Camargo committed
347
     * @return secondary Address used by the STUN server
348 349 350 351 352 353 354 355
     */
    public String getSecondaryAddress() {
        return secondaryAddress;
    }

    /**
     * Get the primary Address used by the STUN server
     *
Thiago Camargo's avatar
Thiago Camargo committed
356
     * @return primary Address used by the STUN server
357 358 359 360 361
     */
    public String getPrimaryAddress() {
        return primaryAddress;
    }

Thiago Camargo's avatar
Thiago Camargo committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    public List<InetAddress> getAddresses() {
        List<InetAddress> list = new ArrayList<InetAddress>();
        try {
            Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
            while (ifaces.hasMoreElements()) {
                NetworkInterface iface = ifaces.nextElement();
                Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
                while (iaddresses.hasMoreElements()) {
                    InetAddress iaddress = iaddresses.nextElement();
                    if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress()) {
                        list.add(iaddress);
                    }
                }
            }
        } catch (Exception e) {
        }
        return list;
    }
380
}