Refactoring Stun4j

This commit is contained in:
emcho 2010-01-31 12:59:59 +00:00
parent 33ed858355
commit a7d1a7fdc9
11 changed files with 184 additions and 286 deletions

View File

@ -6,11 +6,9 @@
*/ */
package org.ice4j; package org.ice4j;
import java.util.EventObject; import java.util.*;
import java.net.InetSocketAddress;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*;
/** /**
@ -20,12 +18,8 @@ import org.ice4j.stack.*;
* as well as the Descriptor of the NetAccessPoint that received it (In case the * as well as the Descriptor of the NetAccessPoint that received it (In case the
* stack is used on more than one ports/addresses). * stack is used on more than one ports/addresses).
* *
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
public class StunMessageEvent public class StunMessageEvent
extends EventObject extends EventObject
{ {
@ -37,12 +31,12 @@ public class StunMessageEvent
/** /**
* The message itself. * The message itself.
*/ */
private Message message = null; private Message message = null;
/** /**
* The sending address. * The sending address.
*/ */
private TransportAddress remoteAddress = null; private TransportAddress remoteAddress = null;
/** /**
* Constructs a StunMessageEvent according to the specified message. * Constructs a StunMessageEvent according to the specified message.

View File

@ -8,6 +8,8 @@
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.stack.*;
import org.ice4j.stunclient.*;
/** /**
* A <tt>StunCandidateHarvester</tt> gathers STUN <tt>Candidate</tt>s for a * A <tt>StunCandidateHarvester</tt> gathers STUN <tt>Candidate</tt>s for a
@ -28,5 +30,8 @@ public class StunCandidateHarvester
public void harvest(Component component) public void harvest(Component component)
{ {
//todo implement //todo implement
StunClient client = new StunClient(stack);
} }
} }

View File

@ -13,10 +13,7 @@ import org.ice4j.*;
* NetAccessManager (and more precisely - MessageProcessors). This is our * NetAccessManager (and more precisely - MessageProcessors). This is our
* way of keeping scalable network and stun layers. * way of keeping scalable network and stun layers.
* *
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
interface MessageEventHandler interface MessageEventHandler

View File

@ -12,26 +12,43 @@ import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
/** /**
* The class is used to parse and dispatch incoming messages in a multithreaded * The class is used to parse and dispatch incoming messages in a multi-thread
* manner. * manner.
* *
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
class MessageProcessor class MessageProcessor
implements Runnable implements Runnable
{ {
private static final Logger logger = /**
Logger.getLogger(MessageProcessor.class.getName()); * Our class logger.
*/
private static final Logger logger
= Logger.getLogger(MessageProcessor.class.getName());
/**
* The queue where we store incoming messages until they are collected.
*/
private MessageQueue messageQueue = null; private MessageQueue messageQueue = null;
/**
* The listener that will be retrieving <tt>MessageEvent</tt>s
*/
private MessageEventHandler messageHandler = null; private MessageEventHandler messageHandler = null;
/**
* The listener that will be collecting error notifications.
*/
private ErrorHandler errorHandler = null; private ErrorHandler errorHandler = null;
private boolean isRunning = false; /**
* The flag that indicates whether we are still running.
*/
private boolean isRunning = false;
/**
* A reference to the thread that we use to execute ourselves.
*/
private Thread runningThread = null; private Thread runningThread = null;
/** /**
@ -62,10 +79,8 @@ class MessageProcessor
throw new IllegalArgumentException( throw new IllegalArgumentException(
"The error handler may not be " + null); "The error handler may not be " + null);
this.messageQueue = queue; this.messageQueue = queue;
this.messageHandler = messageHandler; this.messageHandler = messageHandler;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
@ -74,8 +89,8 @@ class MessageProcessor
*/ */
public void run() public void run()
{ {
//add an extra try/catch block that handles uncatched errors and helps avoid //add an extra try/catch block that handles uncatched errors and helps
//having dead threads in our pools. //avoid having dead threads in our pools.
try try
{ {
while (isRunning) while (isRunning)
@ -89,8 +104,7 @@ class MessageProcessor
{ {
if(isRunning()) if(isRunning())
logger.log(Level.WARNING, logger.log(Level.WARNING,
"A net access point has gone useless:", "A net access point has gone useless:", ex);
ex);
//nothing to do here since we test whether we are running //nothing to do here since we test whether we are running
//just beneath ... //just beneath ...
} }
@ -106,10 +120,10 @@ class MessageProcessor
Message stunMessage = null; Message stunMessage = null;
try try
{ {
stunMessage = stunMessage
Message.decode(rawMessage.getBytes(), = Message.decode(rawMessage.getBytes(),
(char) 0, (char) 0,
(char) rawMessage.getMessageLength()); (char) rawMessage.getMessageLength());
} }
catch (StunException ex) catch (StunException ex)
{ {

View File

@ -7,10 +7,9 @@
package org.ice4j.stack; package org.ice4j.stack;
import java.util.Hashtable;
import java.io.*; import java.io.*;
import java.net.*;
import java.util.*; import java.util.*;
import java.net.DatagramSocket;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -22,32 +21,34 @@ import org.ice4j.message.*;
* Instances that operate with the NetAccessManager are only supposed to * Instances that operate with the NetAccessManager are only supposed to
* understand STUN talk and shouldn't be aware of datagrams sockets, and etc. * understand STUN talk and shouldn't be aware of datagrams sockets, and etc.
* *
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
class NetAccessManager class NetAccessManager
implements ErrorHandler implements ErrorHandler
{ {
/**
* Our class logger
*/
private static final Logger logger = private static final Logger logger =
Logger.getLogger(NetAccessManager.class.getName()); Logger.getLogger(NetAccessManager.class.getName());
/** /**
* All access points currently in use. The table maps NetAccessPointDescriptor-s * All access points currently in use. The table maps
* to NetAccessPoint-s * <tt>NetAccessPointDescriptor</tt>s to <tt>NetAccessPoint</tt>s
*/ */
private Hashtable<NetAccessPointDescriptor, NetAccessPoint> netAccessPoints = new Hashtable<NetAccessPointDescriptor, NetAccessPoint>(); private Hashtable<NetAccessPointDescriptor, NetAccessPoint> netAccessPoints
= new Hashtable<NetAccessPointDescriptor, NetAccessPoint>();
/** /**
* A synchronized FIFO where incoming messages are stocked for processing. * A synchronized FIFO where incoming messages are stocked for processing.
*/ */
private MessageQueue messageQueue = new MessageQueue(); private MessageQueue messageQueue = new MessageQueue();
/** /**
* A thread pool of message processors. * A thread pool of message processors.
*/ */
private Vector<MessageProcessor> messageProcessors = new Vector<MessageProcessor>(); private Vector<MessageProcessor> messageProcessors
= new Vector<MessageProcessor>();
/** /**
* The instance that should be notified whan an incoming message has been * The instance that should be notified whan an incoming message has been
@ -81,7 +82,6 @@ class NetAccessManager
messageEventHandler = evtHandler; messageEventHandler = evtHandler;
} }
//------------------------ error handling -------------------------------------
/** /**
* A civilized way of not caring! * A civilized way of not caring!
* @param message a description of the error * @param message a description of the error
@ -96,7 +96,7 @@ class NetAccessManager
} }
/** /**
* Clears the faulty thread and tries to repair the damage and instanciate * Clears the faulty thread and tries to repair the damage and instantiate
* a replacement. * a replacement.
* *
* @param callingThread the thread where the error occurred. * @param callingThread the thread where the error occurred.
@ -124,7 +124,8 @@ class NetAccessManager
{ {
//make sure nothing's left and notify user //make sure nothing's left and notify user
removeNetAccessPoint(ap.getDescriptor()); removeNetAccessPoint(ap.getDescriptor());
logger.log(Level.WARNING, "Failed to relaunch accesspoint:" + ap, logger.log(Level.WARNING, "Failed to relaunch accesspoint:"
+ ap,
ex); ex);
} }
} }
@ -160,7 +161,8 @@ class NetAccessManager
if(netAccessPoints.containsKey(apDescriptor)) if(netAccessPoints.containsKey(apDescriptor))
return; return;
NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this); NetAccessPoint ap
= new NetAccessPoint(apDescriptor, messageQueue, this);
netAccessPoints.put(apDescriptor, ap); netAccessPoints.put(apDescriptor, ap);
ap.start(); ap.start();
} }
@ -181,13 +183,17 @@ class NetAccessManager
{ {
//no null check - let it through a null pointer exception //no null check - let it through a null pointer exception
TransportAddress address = new TransportAddress(socket.getLocalAddress(), socket.getLocalPort()); TransportAddress address = new TransportAddress(
NetAccessPointDescriptor apDescriptor = new NetAccessPointDescriptor(address); socket.getLocalAddress(), socket.getLocalPort());
NetAccessPointDescriptor apDescriptor
= new NetAccessPointDescriptor(address);
if(netAccessPoints.containsKey(apDescriptor)) if(netAccessPoints.containsKey(apDescriptor))
return apDescriptor; return apDescriptor;
NetAccessPoint ap = new NetAccessPoint(apDescriptor, messageQueue, this); NetAccessPoint ap
= new NetAccessPoint(apDescriptor, messageQueue, this);
//call the useExternalSocket method to avoid closing the socket when //call the useExternalSocket method to avoid closing the socket when
//removing the accesspoint. Bug Report - Dave Stuart - SipQuest //removing the accesspoint. Bug Report - Dave Stuart - SipQuest
ap.useExternalSocket(socket); ap.useExternalSocket(socket);
@ -245,8 +251,8 @@ class NetAccessManager
} }
/** /**
* @throws StunException INVALID_ARGUMENT if threadPoolSize is not a * Fills the thread pool with the initially specified number of message
* valid size. * processors.
*/ */
private void initThreadPool() private void initThreadPool()
{ {
@ -258,7 +264,7 @@ class NetAccessManager
/** /**
* Starts all message processors * Starts all message processors
* *
* @param newSize the new thread poolsize * @param newSize the new thread pool size
*/ */
private void fillUpThreadPool(int newSize) private void fillUpThreadPool(int newSize)
{ {
@ -307,7 +313,7 @@ class NetAccessManager
*/ */
void sendMessage(Message stunMessage, void sendMessage(Message stunMessage,
NetAccessPointDescriptor apDescriptor, NetAccessPointDescriptor apDescriptor,
TransportAddress address) TransportAddress address)
throws IOException, IllegalArgumentException, StunException throws IOException, IllegalArgumentException, StunException
{ {
byte[] bytes = stunMessage.encode(); byte[] bytes = stunMessage.encode();

View File

@ -6,8 +6,7 @@
*/ */
package org.ice4j.stack; package org.ice4j.stack;
import java.util.*; import java.io.*;
import java.io.IOException;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
@ -19,27 +18,25 @@ import org.ice4j.*;
* messages to the MessageProcessor as well as sending datagrams to the STUN server * messages to the MessageProcessor as well as sending datagrams to the STUN server
* specified by the original NetAccessPointDescriptor. * specified by the original NetAccessPointDescriptor.
* *
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
class NetAccessPoint class NetAccessPoint
implements Runnable implements Runnable
{ {
/**
* Our class logger.
*/
private static final Logger logger = private static final Logger logger =
Logger.getLogger(NetAccessPoint.class.getName()); Logger.getLogger(NetAccessPoint.class.getName());
/**
* Creates a new access point.
*/
NetAccessPoint() NetAccessPoint()
{ {
} }
/**
* Max datagram size.
*/
private static final int MAX_DATAGRAM_SIZE = 8 * 1024;
/** /**
* The message queue is where incoming messages are added. * The message queue is where incoming messages are added.
*/ */
@ -50,32 +47,16 @@ class NetAccessPoint
*/ */
protected DatagramSocket sock; protected DatagramSocket sock;
/**
* Indicates whether the access point is using a socket that was created
* by someone else. The variable is set to true when the AP's socket is
* set using the <code>useExternalSocket()</code> method and is consulted
* inside the stop method. When its value is true, the AP's socket is not
* closed when <code>stop()</code>ing the AP.
*
* This variable is part of bug fix reported by Dave Stuart - SipQuest
*/
private boolean isUsingExternalSocket = false;
/** /**
* A flag that is set to false to exit the message processor. * A flag that is set to false to exit the message processor.
*/ */
private boolean isRunning; private boolean isRunning;
/**
* The descriptor used to create this access point.
*/
private NetAccessPointDescriptor apDescriptor = null;
/** /**
* The instance to be notified if errors occur in the network listening * The instance to be notified if errors occur in the network listening
* thread. * thread.
*/ */
private ErrorHandler errorHandler = null; private ErrorHandler errorHandler = null;
/** /**
* Used for locking socket operations * Used for locking socket operations
@ -84,15 +65,16 @@ class NetAccessPoint
/** /**
* Creates a network access point. * Creates a network access point.
* @param apDescriptor the address and port where to bind. * @param socket the socket that this access point is supposed to use for
* communication.
* @param messageQueue the FIFO list where incoming messages should be queued * @param messageQueue the FIFO list where incoming messages should be queued
* @param errorHandler the instance to notify when errors occur. * @param errorHandler the instance to notify when errors occur.
*/ */
NetAccessPoint(NetAccessPointDescriptor apDescriptor, protected NetAccessPoint(DatagramSocket socket,
MessageQueue messageQueue, MessageQueue messageQueue,
ErrorHandler errorHandler) ErrorHandler errorHandler)
{ {
this.apDescriptor = apDescriptor; this.sock = socket;
this.messageQueue = messageQueue; this.messageQueue = messageQueue;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
@ -106,19 +88,8 @@ class NetAccessPoint
void start() void start()
throws IOException throws IOException
{ {
synchronized(socketLock){ synchronized(socketLock)
{
//do not create the socket earlier as someone might want to set an
// existing one was != null fixed (Ranga)
if (sock == null)
{
this.sock = new DatagramSocket(getDescriptor().getAddress().
getSocketAddress());
this.isUsingExternalSocket = false;
logger.info("Bound a socket on ap: " + toString());
}
sock.setReceiveBufferSize(MAX_DATAGRAM_SIZE);
this.isRunning = true; this.isRunning = true;
Thread thread = new Thread(this); Thread thread = new Thread(this);
thread.start(); thread.start();
@ -126,13 +97,14 @@ class NetAccessPoint
} }
/** /**
* Returns the NetAccessPointDescriptor that contains the port and address * Returns the <tt>DatagramSocket</tt> that contains the port and address
* associated with this accesspoint. * associated with this access point.
* @return the NetAccessPointDescriptor associated with this AP. *
* @return the <tt>DatagramSocket</tt> associated with this AP.
*/ */
NetAccessPointDescriptor getDescriptor() protected DatagramSocket getSocket()
{ {
return apDescriptor; return sock;
} }
/** /**
@ -149,6 +121,11 @@ class NetAccessPoint
DatagramPacket packet = new DatagramPacket(message, bufsize); DatagramPacket packet = new DatagramPacket(message, bufsize);
sock.receive(packet); sock.receive(packet);
//get lost if we are no longer running.
if(!isRunning)
return;
logger.finest("received datagram"); logger.finest("received datagram");
RawMessage rawMessage = new RawMessage( message, RawMessage rawMessage = new RawMessage( message,
@ -172,10 +149,9 @@ class NetAccessPoint
+ "receive a message.", + "receive a message.",
ex); ex);
} }
else
{ {
//The exception was most probably caused by calling this.stop() //The exception was most probably caused by calling
// .... //this.stop() ....
} }
} }
catch (IOException ex) catch (IOException ex)
@ -200,101 +176,31 @@ class NetAccessPoint
} }
} }
/** /**
* Shut down the access point. Close the socket for recieving * Makes the access point stop listening on its socket.
* incoming messages. The method won't close the socket if it was created
* outside the stack (Bug Report - Dave Stuart - SipQuest). It also seems
* that sometimes sockets don't immdeiately free their port and trying
* to bind to that port immediately after gets us an exception. We therefore
* null the socket, wait for 200 miliseconds and call the garbage collector
* this seems to be working fine but is not what one could call neat
* behaviour, so if you'd like to disable it - set the
* org.ice4j.stack.HARD_SOCK_CLOSE property to anything different from
* true. If you'd want us to wait more or less - set
* org.ice4j.stack.WAIT_FOR_SOCK_CLOSE to the appropriate number of
* miliseconds.
* *
*/ */
synchronized void stop() synchronized void stop()
{ {
this.isRunning = false; this.isRunning = false;
//avoid a needless null pointer exception
if (sock != null
&& isUsingExternalSocket == false)
{
synchronized (socketLock)
{
sock.close();
logger.info("Closed socket on ap " + toString());
sock = null;
String hardSocketClose =
System.getProperty("org.ice4j.stack.HARD_SOCK_CLOSE");
//sometimes sockts stay open even after closing them. make sure
//this doesn't happen here. (unless the user doesn't want us to)
if (hardSocketClose == null
|| hardSocketClose.equalsIgnoreCase("true"))
{
int waitForSockClose = 200;
try
{
String waitForSockCloseStr =
System.getProperty(
"org.ice4j.stack.WAIT_FOR_SOCK_CLOSE");
if (waitForSockCloseStr != null &&
waitForSockCloseStr.length() > 0){
waitForSockClose =
Integer.parseInt(System.getProperty(
waitForSockCloseStr));
}
}
catch (Throwable t)
{
logger.log(
Level.WARNING,
"Failed to parse wait_for_sock_close prop", t);
if (waitForSockClose < 0)
{
waitForSockClose = 200;
}
}
//wait
try
{
wait(waitForSockClose);
}
catch (InterruptedException t)
{
logger.warning("Interrupted waiting for sock close.");
}
System.gc();
}
}
}
} }
/** /**
* Sends message through this access point's socket. * Sends message through this access point's socket.
*
* @param message the bytes to send. * @param message the bytes to send.
* @param address message destination. * @param address message destination.
*
* @throws IOException if an exception occurs while sending the message. * @throws IOException if an exception occurs while sending the message.
*/ */
void sendMessage(byte[] message, TransportAddress address) void sendMessage(byte[] message, TransportAddress address)
throws IOException throws IOException
{ {
DatagramPacket datagramPacket = new DatagramPacket( DatagramPacket datagramPacket = new DatagramPacket(
message, message, 0, message.length, address.getSocketAddress());
0,
message.length, synchronized(socketLock)
address.getSocketAddress()); {
synchronized(socketLock){
sock.send(datagramPacket); sock.send(datagramPacket);
} }
} }
@ -313,8 +219,9 @@ class NetAccessPoint
} }
/** /**
* Sets a socket for the access point to use. This socket will not be closed * Sets a socket for the access point to use. This socket will not be
* when the AP is <code>stop()</code>ed (Bug Report - Dave Stuart - SipQuest). * closed when the AP is <tt>stop()</tt>ed (Bug Report - Dave Stuart).
*
* @param socket the socket that the AP should use. * @param socket the socket that the AP should use.
*/ */
void useExternalSocket(DatagramSocket socket) void useExternalSocket(DatagramSocket socket)

View File

@ -15,11 +15,7 @@ import org.ice4j.*;
* of the host that sent it and the address and port where it was received * of the host that sent it and the address and port where it was received
* (locally). * (locally).
* *
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
*
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
class RawMessage class RawMessage
{ {
@ -31,34 +27,29 @@ class RawMessage
/** /**
* The length of the message. * The length of the message.
*/ */
private int messageLength = -1; private int messageLength = -1;
/** /**
* The addres and port where the message was sent from. * The address and port where the message was sent from.
*/ */
private InetSocketAddress remoteAddress = null; private InetSocketAddress remoteAddress = null;
/**
* The descriptor of the net access point that received the message.
*/
private NetAccessPointDescriptor receivingAccessPoint = null;
/** /**
* Constructs a raw message with the specified field values. All parameters * Constructs a raw message with the specified field values. All parameters
* are cloned before being assigned to class members. * are cloned before being assigned to class members.
* *
* @param messageBytes the message itself. * @param messageBytes the message itself.
* @param remoteAddress the address where the message came from. * @param messageLength the number of bytes currently stored in the
* @param remotePort the port where the message came from. * <tt>messageBytes</tt> array.
* @param netApDescriptor the access point the received the message.s * @param remoteAddress the address where the message came from.
* @param remotePort the port where the message came from.
* *
* @throws NullPointerException if one or more of the parameters were null. * @throws NullPointerException if one or more of the parameters were null.
*/ */
RawMessage(byte[] messageBytes, RawMessage(byte[] messageBytes,
int messageLength, InetAddress remoteAddress,
InetAddress remoteAddress, int messageLength,
int remotePort, int remotePort)
NetAccessPointDescriptor netApDescriptor)
{ {
//... don't do a null check - let it throw an NP exception //... don't do a null check - let it throw an NP exception
@ -68,8 +59,6 @@ class RawMessage
0, messageBytes.length); 0, messageBytes.length);
this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort); this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort);
this.receivingAccessPoint =
(NetAccessPointDescriptor)netApDescriptor.clone();
} }
/** /**
@ -92,7 +81,6 @@ class RawMessage
return messageLength; return messageLength;
} }
/** /**
* Returns the address and port of the host that sent the message * Returns the address and port of the host that sent the message
* @return the [address]:[port] pair that sent the message. * @return the [address]:[port] pair that sent the message.
@ -101,13 +89,4 @@ class RawMessage
{ {
return this.remoteAddress; return this.remoteAddress;
} }
/**
* Returns a descriptor of the access point that received the message.
* @return a descriptor of the access point that received the message.
*/
NetAccessPointDescriptor getNetAccessPoint()
{
return this.receivingAccessPoint;
}
} }

View File

@ -1,4 +1,3 @@
/* /*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
@ -7,9 +6,9 @@
*/ */
package org.ice4j.stack; package org.ice4j.stack;
import java.io.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import java.io.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
@ -20,40 +19,40 @@ import org.ice4j.message.*;
* responses. In the Stun4J implementation it is the transaction layer that * responses. In the Stun4J implementation it is the transaction layer that
* ensures reliable delivery. * ensures reliable delivery.
* *
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
public class StunProvider public class StunProvider
implements MessageEventHandler implements MessageEventHandler
{ {
/**
* Our class logger.
*/
private static final Logger logger = private static final Logger logger =
Logger.getLogger(StunProvider.class.getName()); Logger.getLogger(StunProvider.class.getName());
/** /**
* Stores active client transactions mapped against TransactionID-s. * Stores active client transactions mapped against TransactionID-s.
*/ */
private Hashtable<TransactionID, StunClientTransaction> clientTransactions = new Hashtable<TransactionID, StunClientTransaction>(); private Hashtable<TransactionID, StunClientTransaction> clientTransactions
= new Hashtable<TransactionID, StunClientTransaction>();
/** /**
* Currently open server transactions. The vector contains transaction ids * Currently open server transactions. The vector contains transaction ids
* for transactions corresponding to all non-answered received requests. * for transactions corresponding to all non-answered received requests.
*/ */
private Hashtable<TransactionID, StunServerTransaction> serverTransactions = new Hashtable<TransactionID, StunServerTransaction>(); private Hashtable<TransactionID, StunServerTransaction> serverTransactions
= new Hashtable<TransactionID, StunServerTransaction>();
/** /**
* The stack that created us. * The stack that created us.
*/ */
private StunStack stunStack = null; private StunStack stunStack = null;
/** /**
* A dispatcher for incoming requests event; * A dispatcher for incoming requests event;
*/ */
private EventDispatcher eventDispatcher = new EventDispatcher(); private EventDispatcher eventDispatcher = new EventDispatcher();
//------------------ public interface //------------------ public interface
/** /**
@ -88,10 +87,7 @@ public class StunProvider
throws StunException, IOException, IllegalArgumentException throws StunException, IOException, IllegalArgumentException
{ {
StunClientTransaction clientTransaction StunClientTransaction clientTransaction
= new StunClientTransaction(this, = new StunClientTransaction(this, request, sendTo, sendThrough,
request,
sendTo,
sendThrough,
collector); collector);
clientTransactions.put(clientTransaction.getTransactionID(), clientTransactions.put(clientTransaction.getTransactionID(),
@ -120,7 +116,7 @@ public class StunProvider
public void sendResponse(byte[] transactionID, public void sendResponse(byte[] transactionID,
Response response, Response response,
NetAccessPointDescriptor sendThrough, NetAccessPointDescriptor sendThrough,
TransportAddress sendTo) TransportAddress sendTo)
throws StunException, throws StunException,
IOException, IOException,
IllegalArgumentException IllegalArgumentException
@ -129,13 +125,15 @@ public class StunProvider
StunServerTransaction sTran = StunServerTransaction sTran =
serverTransactions.get(tid); serverTransactions.get(tid);
if(sTran == null || sTran.isReransmitting()){ if(sTran == null || sTran.isReransmitting())
{
throw new StunException(StunException.TRANSACTION_DOES_NOT_EXIST, throw new StunException(StunException.TRANSACTION_DOES_NOT_EXIST,
"The transaction specified in the response " "The transaction specified in the response "
+ "object does not exist or has already " + "object does not exist or has already "
+ "transmitted a response."); + "transmitted a response.");
} }
else{ else
{
sTran.sendResponse(response, sendThrough, sendTo); sTran.sendResponse(response, sendThrough, sendTo);
} }
@ -179,8 +177,6 @@ public class StunProvider
eventDispatcher.addRequestListener(apDescriptor, listener); eventDispatcher.addRequestListener(apDescriptor, listener);
} }
//------------- stack internals ------------------------------------------------ //------------- stack internals ------------------------------------------------
/** /**
* Returns the currently active instance of NetAccessManager. Used by client * Returns the currently active instance of NetAccessManager. Used by client
@ -235,7 +231,8 @@ public class StunProvider
createTransactionID(msg.getTransactionID()); createTransactionID(msg.getTransactionID());
StunServerTransaction sTran = serverTransactions.get(serverTid); StunServerTransaction sTran = serverTransactions.get(serverTid);
if( sTran != null){ if( sTran != null)
{
//requests from this transaction have already been seen //requests from this transaction have already been seen
//retransmit the response if there was any //retransmit the response if there was any
@ -255,10 +252,14 @@ public class StunProvider
String propagate = System.getProperty( String propagate = System.getProperty(
"org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS"); "org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS");
if(propagate == null || !propagate.trim().equalsIgnoreCase("true")) if(propagate == null
|| !propagate.trim().equalsIgnoreCase("true"))
{
return; return;
}
} }
else{ else
{
logger.finest("exising transaction not found"); logger.finest("exising transaction not found");
sTran = sTran =
new StunServerTransaction(this, serverTid); new StunServerTransaction(this, serverTid);
@ -266,13 +267,14 @@ public class StunProvider
serverTransactions.put(serverTid, sTran); serverTransactions.put(serverTid, sTran);
sTran.start(); sTran.start();
} }
eventDispatcher.fireMessageEvent(event); eventDispatcher.fireMessageEvent(event);
} }
//response //response
else if(msg instanceof Response) else if(msg instanceof Response)
{ {
TransactionID tid = TransactionID. TransactionID tid
createTransactionID(msg.getTransactionID()); = TransactionID.createTransactionID(msg.getTransactionID());
StunClientTransaction tran = StunClientTransaction tran =
clientTransactions.remove(tid); clientTransactions.remove(tid);
@ -284,9 +286,11 @@ public class StunProvider
else else
{ {
//do nothing - just drop the phantom response. //do nothing - just drop the phantom response.
logger.fine("Dropped response - no matching client tran found."); logger.fine("Dropped response - "
+ "no matching client tran found.");
logger.fine("response tid was - " + tid.toString()); logger.fine("response tid was - " + tid.toString());
logger.fine("all tids in stock were" + clientTransactions.toString()); logger.fine("all tids in stock were"
+ clientTransactions.toString());
} }
} }
@ -299,8 +303,9 @@ public class StunProvider
{ {
eventDispatcher.removeAllListeners(); eventDispatcher.removeAllListeners();
Enumeration tids = clientTransactions.keys(); Enumeration<TransactionID> tids = clientTransactions.keys();
while (tids.hasMoreElements()) { while (tids.hasMoreElements())
{
TransactionID item = (TransactionID)tids.nextElement(); TransactionID item = (TransactionID)tids.nextElement();
StunClientTransaction tran = clientTransactions.remove(item); StunClientTransaction tran = clientTransactions.remove(item);
if(tran != null) if(tran != null)
@ -309,10 +314,10 @@ public class StunProvider
} }
tids = serverTransactions.keys(); tids = serverTransactions.keys();
while (tids.hasMoreElements()) { while (tids.hasMoreElements())
{
TransactionID item = (TransactionID)tids.nextElement(); TransactionID item = (TransactionID)tids.nextElement();
StunServerTransaction tran = StunServerTransaction tran = serverTransactions.remove(item);
serverTransactions.remove(item);
if(tran != null) if(tran != null)
tran.expire(); tran.expire();

View File

@ -38,6 +38,9 @@ public class StunStack
*/ */
public static final int DEFAULT_THREAD_POOL_SIZE = 3; public static final int DEFAULT_THREAD_POOL_SIZE = 3;
/**
* This stack's provider.
*/
private StunProvider stunProvider = null; private StunProvider stunProvider = null;
/** /**
@ -54,17 +57,14 @@ public class StunStack
return stackInstance; return stackInstance;
} }
//----------------------- PUBLIC INTERFACE ---------------------------------
/** /**
* Sets the number of Message processors running in the same time. * Sets the number of Message processors running in the same time.
* *
* @param threadPoolSize the number of message process threads to run. * @param threadPoolSize the number of message process threads to run.
* @throws StunException * @throws IllegalArgumentException if threadPoolSize is not a valid size.
*/ */
public void setThreadPoolSize(int threadPoolSize) public void setThreadPoolSize(int threadPoolSize)
throws StunException throws IllegalArgumentException
{ {
netAccessManager.setThreadPoolSize(threadPoolSize); netAccessManager.setThreadPoolSize(threadPoolSize);
} }
@ -84,8 +84,8 @@ public class StunStack
} }
/** /**
* Creates and starts the specified Network Access Point based on the specified * Creates and starts the specified Network Access Point based on the
* socket and returns a relevant descriptor. * specified socket and returns a relevant descriptor.
* *
* @param sock The socket that the new access point should represent. * @param sock The socket that the new access point should represent.
* @throws IOException if we fail to setup the socket. * @throws IOException if we fail to setup the socket.
@ -120,7 +120,6 @@ public class StunStack
return stunProvider; return stunProvider;
} }
//-------------------- internal stuff --------------------------------------
/** /**
* Private constructor as we want a singleton pattern. * Private constructor as we want a singleton pattern.
*/ */

View File

@ -6,10 +6,9 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import java.net.DatagramSocket;
import java.io.*; import java.io.*;
import java.util.logging.*;
import java.net.*; import java.net.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
@ -19,18 +18,19 @@ import org.ice4j.stack.*;
/** /**
* The class provides basic means of discovering a public IP address. All it * The class provides basic means of discovering a public IP address. All it
* does is send a binding request through a specified port and return the * does is send a binding request through a specified port and return the
* mapped address it got back or null if there was no reponse. * mapped address it got back or <tt>null</tt> if there was no reponse.
* *
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov * @author Emil Ivov
* @version 0.1
*/ */
public class SimpleAddressDetector public class SimpleAddressDetector
{ {
/**
* Our class logger.
*/
private static final Logger logger private static final Logger logger
= Logger.getLogger(SimpleAddressDetector.class.getName()); = Logger.getLogger(SimpleAddressDetector.class.getName());
/** /**
* The stack to use for STUN communication. * The stack to use for STUN communication.
*/ */
@ -47,7 +47,7 @@ public class SimpleAddressDetector
private TransportAddress serverAddress = null; private TransportAddress serverAddress = null;
/** /**
* A utility used to flatten the multithreaded architecture of the Stack * A utility used to flatten the multi-threaded architecture of the Stack
* and execute the discovery process in a synchronized manner * and execute the discovery process in a synchronized manner
*/ */
private BlockingRequestSender requestSender = null; private BlockingRequestSender requestSender = null;
@ -98,9 +98,12 @@ public class SimpleAddressDetector
/** /**
* Creates a listening point from the following address and attempts to * Creates a listening point from the following address and attempts to
* discover how it is mapped so that using inside the application is possible. * discover how it is mapped so that using inside the application is
* possible.
*
* @param address the [address]:[port] pair where ther request should be * @param address the [address]:[port] pair where ther request should be
* sent from. * sent from.
*
* @return a StunAddress object containing the mapped address or null if * @return a StunAddress object containing the mapped address or null if
* discovery failed. * discovery failed.
* @throws IOException if <tt>address</tt> is already bound. * @throws IOException if <tt>address</tt> is already bound.
@ -153,7 +156,9 @@ public class SimpleAddressDetector
} }
/* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */ /* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */
XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res.getAttribute(Attribute.XOR_MAPPED_ADDRESS); XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res
.getAttribute(Attribute.XOR_MAPPED_ADDRESS);
if(xorAtt != null) if(xorAtt != null)
{ {
byte xoring[] = new byte[16]; byte xoring[] = new byte[16];
@ -219,7 +224,8 @@ public class SimpleAddressDetector
} }
/* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */ /* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */
XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res.getAttribute(Attribute.XOR_MAPPED_ADDRESS); XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res
.getAttribute(Attribute.XOR_MAPPED_ADDRESS);
if(xorAtt != null) if(xorAtt != null)
{ {
byte xoring[] = new byte[16]; byte xoring[] = new byte[16];
@ -250,20 +256,4 @@ public class SimpleAddressDetector
{ {
return getMappingFor(new TransportAddress(port)); return getMappingFor(new TransportAddress(port));
} }
/*
public static void main(String[] args)
throws Exception
{
SimpleAddressDetector detector = new SimpleAddressDetector(
new StunAddress("stun01.sipphone.com", 3478));
detector.start();
StunAddress mappedAddr = detector.getMappingFor(5060);
System.out.println("address is " + mappedAddr);
detector.shutDown();
}
*/
} }

View File

@ -17,8 +17,6 @@ import org.ice4j.stunclient.*;
* and receive responses * and receive responses
* *
* @author Namal Senarathne * @author Namal Senarathne
*
* TODO : The constructor must have a reference to ICE Agent
*/ */
public class StunClient public class StunClient
implements ResponseCollector implements ResponseCollector
@ -44,6 +42,10 @@ public class StunClient
*/ */
private HashMap<byte[], Request> requestMap = new HashMap<byte[], Request>(); private HashMap<byte[], Request> requestMap = new HashMap<byte[], Request>();
/**
* Creates a new Instance of the ST
* @param stunStack
*/
public StunClient(StunStack stunStack) public StunClient(StunStack stunStack)
{ {
this.stunStack = stunStack; this.stunStack = stunStack;