MediaProxyService.java 16.1 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4
/**
 * $Revision$
 * $Date$
 *
5
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
6 7
 *
 * This software is published under the terms of the GNU Public License (GPL),
8 9
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
Matt Tucker's avatar
Matt Tucker committed
10 11
 */

12
package org.jivesoftware.openfire.mediaproxy;
13

14 15 16 17 18 19 20 21
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

22 23 24
import org.dom4j.Attribute;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
25 26 27 28 29 30
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.PacketRouter;
import org.jivesoftware.openfire.RoutableChannelHandler;
import org.jivesoftware.openfire.RoutingTable;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
31 32
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.container.BasicModule;
33 34 35 36 37
import org.jivesoftware.openfire.disco.DiscoInfoProvider;
import org.jivesoftware.openfire.disco.DiscoItem;
import org.jivesoftware.openfire.disco.DiscoItemsProvider;
import org.jivesoftware.openfire.disco.DiscoServerItem;
import org.jivesoftware.openfire.disco.ServerItemsProvider;
Gaston Dombiak's avatar
Gaston Dombiak committed
38 39
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
40
import org.xmpp.forms.DataForm;
41 42 43 44 45 46
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;

/**
Matt Tucker's avatar
Matt Tucker committed
47 48 49
 * A proxy service for UDP traffic such as RTP. It provides Jingle transport candidates
 * to be used for media transmission. The media proxy is especially useful for users
 * behind NAT devices or firewalls that prevent peer to peer communication..
50 51 52
 *
 * @author Thiago Camargo
 */
53 54
public class MediaProxyService extends BasicModule
        implements ServerItemsProvider, RoutableChannelHandler, DiscoInfoProvider, DiscoItemsProvider {
55 56 57 58

    private String serviceName;
    private RoutingTable routingTable;
    private PacketRouter router;
Thiago Camargo's avatar
Thiago Camargo committed
59 60
    private Echo echo = null;
    private int echoPort = 10020;
61
    private SessionManager sessionManager = null;
62 63

    private MediaProxy mediaProxy = null;
64
    private boolean enabled = true;
65 66 67 68

    public static final String NAMESPACE = "http://www.jivesoftware.com/protocol/rtpbridge";

    /**
Thiago Camargo's avatar
Thiago Camargo committed
69
     * Constructs a new MediaProxyService.
70 71 72 73 74 75 76 77
     */
    public MediaProxyService() {
        super("Media Proxy Service");
    }

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

78
        sessionManager = server.getSessionManager();
79 80 81
        // In some cases, the domain name of the server may not be the actual address of the machine
        // (ie, when using DNS SRV records). In that case, the "mediaproxy.externalip" property should be
        // set to the IP address of the actual server where the media proxy is listening.
82
        String ipAddress = JiveGlobals.getProperty("mediaproxy.externalip", server.getServerInfo().getXMPPDomain());
83
        mediaProxy = new MediaProxy(ipAddress);
84 85 86 87

        String defaultName = "rtpbridge";
        serviceName = JiveGlobals.getProperty("mediaproxy.serviceName", defaultName);
        serviceName = serviceName.equals("") ? defaultName : serviceName;
88

Thiago Camargo's avatar
Thiago Camargo committed
89 90
        echoPort = JiveGlobals.getIntProperty("mediaproxy.echoPort", echoPort);

91 92 93
        routingTable = server.getRoutingTable();
        router = server.getPacketRouter();

94
        initMediaProxy();
95 96 97 98
    }

    public void start() {
        if (isEnabled()) {
Thiago Camargo's avatar
Thiago Camargo committed
99 100 101 102 103 104

            try {
                echo = new Echo(echoPort);
                Thread t = new Thread(echo);
                t.start();
            } catch (UnknownHostException e) {
105
                // Ignore
Thiago Camargo's avatar
Thiago Camargo committed
106
            } catch (SocketException e) {
107
                // Ignore
Thiago Camargo's avatar
Thiago Camargo committed
108 109
            }

Gaston Dombiak's avatar
Gaston Dombiak committed
110
            routingTable.addComponentRoute(getAddress(), this);
111
            XMPPServer.getInstance().getIQDiscoItemsHandler().addServerItemsProvider(this);
112
        } else {
113
            if (echo != null) echo.cancel();
114
            XMPPServer.getInstance().getIQDiscoItemsHandler().removeComponentItem(getAddress().toString());
115 116 117 118 119 120
        }
    }

    public void stop() {
        super.stop();
        mediaProxy.stopProxy();
121
        XMPPServer.getInstance().getIQDiscoItemsHandler().removeComponentItem(getAddress().toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
122
        routingTable.removeComponentRoute(getAddress());
123
        if (echo != null) echo.cancel();
124 125 126 127 128 129 130 131 132
    }

    // Component Interface

    public String getName() {
        // Get the name from the plugin.xml file.
        return serviceName;
    }

133
    public Iterator<DiscoItem> getItems(String name, String node, JID senderJID) {
134
        // A proxy server has no items
135
        return new ArrayList<DiscoItem>().iterator();
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    }

    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)) {
159 160 161
            reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(iq);
            router.route(reply);
            return;
162
        } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
163 164 165 166
            // a component
            reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(iq);
            router.route(reply);
            return;
167 168
        } else if (NAMESPACE.equals(namespace) && enabled) {

169 170
            Element candidateElement = childElementCopy.element("candidate");
            String sid = childElementCopy.attribute("sid").getValue() + "-" + iq.getFrom();
171

172 173
            if (candidateElement != null) {
                childElementCopy.remove(candidateElement);
174
                Element candidate = childElementCopy.addElement("candidate ");
175
                ProxyCandidate proxyCandidate = mediaProxy.addRelayAgent(sid, iq.getFrom().toString());
176
                Log.debug("MediaProxyService: "+sid);
177 178 179 180 181 182 183 184
                proxyCandidate.start();
                candidate.addAttribute("name", "voicechannel");
                candidate.addAttribute("ip", mediaProxy.getPublicIP());
                candidate.addAttribute("porta", String.valueOf(proxyCandidate.getLocalPortA()));
                candidate.addAttribute("portb", String.valueOf(proxyCandidate.getLocalPortB()));
                candidate.addAttribute("pass", proxyCandidate.getPass());

            } else {
185 186 187
                candidateElement = childElementCopy.element("relay");
                if (candidateElement != null) {
                    MediaProxySession session = mediaProxy.getSession(sid);
188
                    Log.debug("MediaProxyService: "+sid);
189
                    if (session != null) {
190
                        Attribute pass = candidateElement.attribute("pass");
191 192

                        if (pass != null && pass.getValue().trim().equals(session.getPass().trim())) {
193 194 195 196
                            Attribute portA = candidateElement.attribute("porta");
                            Attribute portB = candidateElement.attribute("portb");
                            Attribute hostA = candidateElement.attribute("hosta");
                            Attribute hostB = candidateElement.attribute("hostb");
197 198

                            try {
199 200 201
                                if (hostA != null && portA != null) {
                                    for (int i = 0; i < 2; i++) {
                                        session.sendFromPortA(hostB.getValue(), Integer.parseInt(portB.getValue()));
202 203 204 205 206 207 208 209 210 211 212
                                    }
                                }
                            }
                            catch (Exception e) {
                                Log.error(e);
                            }

                        } else {
                            reply.setError(PacketError.Condition.forbidden);
                        }
                    }
213
                    childElementCopy.remove(candidateElement);
214 215 216 217 218 219
                } else {
                    candidateElement = childElementCopy.element("publicip");
                    if (candidateElement != null) {
                        childElementCopy.remove(candidateElement);
                        Element publicIp = childElementCopy.addElement("publicip");
                        try {
220
                            String ip = sessionManager.getSession(iq.getFrom()).getHostAddress();
221 222 223 224
                            if (ip != null) {
                                publicIp.addAttribute("ip", ip);
                            }
                        } catch (UnknownHostException e) {
Thiago Camargo's avatar
Thiago Camargo committed
225
                            Log.error(e);
226 227 228 229 230 231 232
                        }

                    } else {
                        childElementCopy.remove(candidateElement);
                        reply.setError(PacketError.Condition.forbidden);
                    }

233 234 235 236 237 238 239 240
                }
            }
        } else {
            // Answer an error since the server can't handle the requested namespace
            reply.setError(PacketError.Condition.service_unavailable);
        }

        try {
241
            if (Log.isDebugEnabled()) {
242
                Log.debug("MediaProxyService: RETURNED:" + reply.toXML());
243
            }
244 245 246 247 248 249 250
            router.route(reply);
        }
        catch (Exception e) {
            Log.error(e);
        }
    }

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
    /**
     * Load config using JiveGlobals
     */
    private void initMediaProxy() {
        try {
            long idleTime =
                    Long.valueOf(JiveGlobals.getProperty("mediaproxy.idleTimeout"));
            mediaProxy.setIdleTime(idleTime);
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }
        try {
            long lifetime =
                    Long.valueOf(JiveGlobals.getProperty("mediaproxy.lifetime"));
            mediaProxy.setLifetime(lifetime);
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }
        try {
            int minPort = Integer.valueOf(JiveGlobals.getProperty("mediaproxy.portMin"));
            mediaProxy.setMinPort(minPort);
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }
        try {
            int maxPort = JiveGlobals.getIntProperty("mediaproxy.portMax", mediaProxy.getMaxPort());
            mediaProxy.setMaxPort(maxPort);
        }
        catch (NumberFormatException e) {
            // Do nothing let the default values to be used.
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
285
        this.enabled = JiveGlobals.getBooleanProperty("mediaproxy.enabled");
286 287
    }

288 289 290 291 292 293 294 295
    /**
     * 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() {
296
        return serviceName + "." + XMPPServer.getInstance().getServerInfo().getXMPPDomain();
297 298 299 300 301 302
    }

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

303 304 305 306 307 308 309 310 311 312 313 314 315
    public Iterator<DiscoServerItem> getItems()
	{
		List<DiscoServerItem> items = new ArrayList<DiscoServerItem>();
		if (!isEnabled())
		{
			return items.iterator();
		}

		final DiscoServerItem item = new DiscoServerItem(new JID(
			getServiceDomain()), "Media Proxy Service", null, null, this, this);
		items.add(item);
		return items.iterator();
	}
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

    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", "Media Proxy Service");
        identity.addAttribute("type", "rtpbridge");

        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();
    }

335
    public DataForm getExtendedInfo(String name, String node, JID senderJID) {
336 337 338 339 340 341 342 343 344 345
        return null;
    }

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

    /**
     * Return the list of active Agents
     *
Thiago Camargo's avatar
Thiago Camargo committed
346
     * @return list of active agents
347
     */
348
    public Collection<MediaProxySession> getAgents() {
Matt Tucker's avatar
Matt Tucker committed
349
        return mediaProxy.getSessions();
350 351 352 353 354 355 356 357 358
    }

    /**
     * Set the keep alive delay of the mediaproxy agents.
     * When an agent stay more then this delay, the agent is destroyed.
     *
     * @param delay time in millis
     */
    public void setKeepAliveDelay(long delay) {
Matt Tucker's avatar
Matt Tucker committed
359
        mediaProxy.setIdleTime(delay);
360 361 362
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
363 364
     * Returns the maximum amount of time (in milleseconds) that a session can
     * be idle before it's closed.
365
     *
Matt Tucker's avatar
Matt Tucker committed
366
     * @return the max idle time in millis.
367
     */
Matt Tucker's avatar
Matt Tucker committed
368
    public long getIdleTime() {
Matt Tucker's avatar
Matt Tucker committed
369
        return mediaProxy.getIdleTime();
370 371 372
    }

    /**
Thiago Camargo's avatar
Thiago Camargo committed
373
     * Set Minimal port value to listen for incoming packets.
374
     *
Thiago Camargo's avatar
Thiago Camargo committed
375
     * @param minPort port value to listen for incoming packets
376 377 378 379 380 381
     */
    public void setMinPort(int minPort) {
        mediaProxy.setMinPort(minPort);
    }

    /**
Thiago Camargo's avatar
Thiago Camargo committed
382
     * Set Maximum port value to listen for incoming packets.
383
     *
Thiago Camargo's avatar
Thiago Camargo committed
384
     * @param maxPort port value to listen for incoming packets
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
     */
    public void setMaxPort(int maxPort) {
        mediaProxy.setMaxPort(maxPort);
    }

    /**
     * Get Minimal port value to listen from incoming packets.
     *
     * @return minPort
     */
    public int getMinPort() {
        return mediaProxy.getMinPort();
    }

    /**
     * Get Maximum port value to listen from incoming packets.
     *
     * @return maxPort
     */
    public int getMaxPort() {
        return mediaProxy.getMaxPort();
    }

    /**
     * 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
420
     * @param enabled boolean value setting enabled or disabled
421 422 423 424
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
        if (isEnabled()) {
425
            start();
426 427 428 429 430 431 432 433 434 435 436
        } else {
            stop();
        }
    }

    /**
     * Stops every running agents
     */
    public void stopAgents() {
        mediaProxy.stopProxy();
    }
437 438 439

    /**
     * Get the Life Time of Sessions
Thiago Camargo's avatar
Thiago Camargo committed
440
     *
441 442
     * @return lifetime in seconds
     */
Thiago Camargo's avatar
Thiago Camargo committed
443
    public long getLifetime() {
444 445 446 447 448
        return mediaProxy.getLifetime();
    }

    /**
     * Set the Life time of Sessions
Thiago Camargo's avatar
Thiago Camargo committed
449
     *
450 451
     * @param lifetime lifetime in seconds
     */
Thiago Camargo's avatar
Thiago Camargo committed
452
    public void setLifetime(long lifetime) {
453 454
        mediaProxy.setLifetime(lifetime);
    }
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

    /**
     * Get the Port used to the UDP Echo Test
     *
     * @return port number
     */
    public int getEchoPort() {
        return echoPort;
    }

    /**
     * Set the Port used to the UDP Echo Test
     *
     * @param echoPort port number
     */
    public void setEchoPort(int echoPort) {
        this.echoPort = echoPort;
    }
473
}