Refactoring Stun4j

This commit is contained in:
emcho 2010-01-31 13:00:28 +00:00
parent a7d1a7fdc9
commit dde2553222
16 changed files with 336 additions and 729 deletions

View File

@ -1,119 +0,0 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j;
/**
* The class is used to represent an [address]:[port] couple where the Stun4J
* stack is to listen for incoming messages. We need such a class so that we
* could identify and manage (add, remove, etc.) DatagramListeners.
*
* @author Emil Ivov
*/
public class NetAccessPointDescriptor
{
/**
* The address string representing the host (interface) where the stack
* should bind.
*/
protected TransportAddress stunAddr = null;
/**
* Creates a net access point that will bind to the specified address.
*
* @param address a valid Stun Address.
*/
public NetAccessPointDescriptor(TransportAddress address)
{
stunAddr = address;
}
/**
* Attempts to automatically detect the address of local host and binds
* on the specified port.
*
* @param port the port where to bind.
*/
/* public NetAccessPointDescriptor(int port)
{
stunAddr = new StunAddress(port);
}
*/
/**
* Compares this object against the specified object. The result is true if
* and only if the argument is not null and it represents the same address
* as this object.
*
* Two instances of InetSocketAddress represent the same address if both the
* InetAddresses (or hostnames if it is unresolved) and port numbers are
* equal. If both addresses are unresolved, then the hostname & the port
* number are compared.
*
* @param obj the object to compare against.
* @return true if the objects are the same; false otherwise.
*/
public final boolean equals(Object obj)
{
if(obj == null
|| !(obj instanceof NetAccessPointDescriptor))
return false;
if (obj == this)
return true;
return stunAddr.equals( ((NetAccessPointDescriptor)obj).stunAddr );
}
/**
* Returns the socket address wrapped by this class.
* @return an InetSocketAddress instance.
*/
public TransportAddress getAddress()
{
return stunAddr;
}
/**
* Clones the NetAccessPointDescriptor.
*
* @return a copy of this NetAccessPointDescriptor.
*/
public Object clone()
{
NetAccessPointDescriptor napd = new NetAccessPointDescriptor(stunAddr);
return napd;
}
/**
* Returns the hashcode of this NetAccessPointDescriptor so that it could
* be used as a key in hashtables.
*
* @return the hashcode of this NetAccessPointDescriptor
*/
public int hashCode(){
//we could actually simply return the hashcode of the socket address
//since it identifies us more or less uniquely
return stunAddr.getSocketAddress().hashCode();
}
/**
* Returns a string representation of this NetAccessPointDescriptor.
*
* @return a string representation of the object.
*/
public String toString()
{
return "StunAddress=" + ( (stunAddr==null)? "null":stunAddr.toString());
}
}

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j;
@ -40,27 +40,27 @@ public class StunMessageEvent
/**
* Constructs a StunMessageEvent according to the specified message.
* @param source the access point that received the message
* @param sourceAddress the access point that received the message
* @param message the message itself
* @param remoteAddress the address that sent the message
*/
public StunMessageEvent(NetAccessPointDescriptor source,
Message message,
TransportAddress remoteAddress)
public StunMessageEvent(TransportAddress sourceAddress,
Message message,
TransportAddress remoteAddress)
{
super(source);
super(sourceAddress);
this.message = message;
this.remoteAddress = remoteAddress;
}
/**
* Returns a NetAccessPointDescriptor referencing the access point where the
* message was received.
* Returns a <tt>TransportAddress</tt> referencing the access point where
* the message was received.
* @return a descriptor of the access point where the message arrived.
*/
public NetAccessPointDescriptor getSourceAccessPoint()
public TransportAddress getLocalAddress()
{
return (NetAccessPointDescriptor)getSource();
return (TransportAddress)getSource();
}
/**

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j;
@ -29,34 +29,14 @@ public class TransportAddress
*/
private final Transport transport;
/**
* Creates an address instance address from an IP address and a port number
* and UDP transport.
* <p>
* A valid port value is between 0 and 65535.
* A port number of <code>zero</code> will let the system pick up an
* ephemeral port in a <code>bind</code> operation.
* <P>
* A <code>null</code> address will assign the <i>wildcard</i> address.
* <p>
* @param hostname The IP address
* @param port The port number
* @throws IllegalArgumentException if the port parameter is outside the
* specified range of valid port values.
*/
public TransportAddress(String hostname, int port)
{
this(hostname, port, Transport.UDP);
}
/**
* Creates an address instance address from an IP address and a port number.
* <p>
* A valid port value is between 0 and 65535.
* A port number of <code>zero</code> will let the system pick up an
* ephemeral port in a <code>bind</code> operation.
* A port number of <tt>zero</tt> will let the system pick up an
* ephemeral port in a <tt>bind</tt> operation.
* <P>
* A <code>null</code> address will assign the <i>wildcard</i> address.
* A <tt>null</tt> address will assign the <i>wildcard</i> address.
* <p>
* @param hostname The IP address
* @param port The port number
@ -67,7 +47,7 @@ public class TransportAddress
public TransportAddress(String hostname, int port, Transport transport)
{
socketAddress = new InetSocketAddress(hostname, port);
this.transport = Transport.UDP;
this.transport = transport;
}
/**
@ -75,18 +55,20 @@ public class TransportAddress
* address and a port number.
* <p>
* A valid port value is between 0 and 65535.
* A port number of <code>zero</code> will let the system pick up an
* ephemeral port in a <code>bind</code> operation.
* A port number of <tt>zero</tt> will let the system pick up an
* ephemeral port in a <tt>bind</tt> operation.
* <P>
* A <code>null</code> address will assign the <i>wildcard</i> address.
* A <tt>null</tt> address will assign the <i>wildcard</i> address.
* <p>
* @param ipAddress The IP address
* @param port The port number
* @param transport The <tt>Transport</tt> to use with this address.
*
* @throws IllegalArgumentException if the port parameter is outside the
* specified range of valid port values or if ipAddress is not a valid ip
* specified range of valid port values or if ipAddress is not a valid IP
* address.
*/
public TransportAddress(byte[] ipAddress, int port)
public TransportAddress(byte[] ipAddress, int port, Transport transport)
{
try
@ -104,7 +86,7 @@ public class TransportAddress
port);
}
transport = Transport.UDP;
this.transport = transport;
}
@ -114,41 +96,22 @@ public class TransportAddress
* An attempt will be made to resolve the hostname into an InetAddress.
* If that attempt fails, the address will be flagged as <I>unresolved</I>.
* <p>
* A valid port value is between 0 and 65535.
* A port number of <code>zero</code> will let the system pick up an
* ephemeral port in a <code>bind</code> operation.
* <P>
* @param address the address itself
* @param port the port number
* A valid port value is between 0 and 65535. A port number of zero will
* let the system pick up an ephemeral port in a <tt>bind</tt> operation.
* <p>
* @param address the address itself
* @param port the port number
* @param transport the transport to use with this address.
*
* @throws IllegalArgumentException if the port parameter is outside the
* range of valid port values, or if the hostname parmeter is <TT>null</TT>.
*/
public TransportAddress(InetAddress address, int port)
public TransportAddress(InetAddress address, int port, Transport transport)
{
socketAddress = new InetSocketAddress(address, port);
transport = Transport.UDP;
this.transport = transport;
}
/**
* Creates an address instance from the localhost amd a port number.
* <p>
* Addresses created with this constructor should be used cautiously as
* they won't be trated as equal to address created from the localhost
* address even though the represent the same thing. In other words - use
* this constructor only if you're not going to compare the resulting
* instance with other addresses.
*
* @param port the port number
* @throws IllegalArgumentException if the port parameter is outside the
* range of valid port values, or if the hostname parmeter is <TT>null</TT>.
*/
public TransportAddress(int port)
{
socketAddress = new InetSocketAddress(port);
transport = Transport.UDP;
}
/**
* Returns the raw IP address of this Address object. The result is in
* network byte order: the highest order byte of the address is in
@ -163,7 +126,7 @@ public class TransportAddress
}
/**
* Returns the port number or 0 if the addres has not been initialized.
* Returns the port number or 0 if the address has not been initialized.
* @return the port number.
*/
public int getPort()

View File

@ -1,9 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -15,7 +14,7 @@ import org.ice4j.*;
/**
* This is a utility class used for dispatching incoming request events. We use
* this class mainly (and probably solely) for its ability to handle listener
* proxies (i.e. listeners interested in requests recevied on a particular
* proxies (i.e. listeners interested in requests received on a particular
* NetAccessPoint only).
*
* @author Emil Ivov
@ -32,10 +31,11 @@ public class EventDispatcher
* Hashtable for managing property change listeners registered for specific
* properties. Maps property names to PropertyChangeSupport objects.
*/
private Hashtable<NetAccessPointDescriptor, EventDispatcher> requestListenersChildren = null;
private Hashtable<TransportAddress, EventDispatcher>
requestListenersChildren = null;
/**
* Constructs an <code>EventDispatcher</code> object.
* Constructs an <tt>EventDispatcher</tt> object.
*/
public EventDispatcher()
{
@ -63,23 +63,23 @@ public class EventDispatcher
* will be invoked only when a call on fireRequestReceived is issued for
* that specific NetAccessPoint.
*
* @param descriptor The NETAP descriptor that we're interested in.
* @param localAddr The NETAP descriptor that we're interested in.
* @param listener The ConfigurationChangeListener to be added
*/
public synchronized void addRequestListener(
NetAccessPointDescriptor descriptor,
RequestListener listener)
public synchronized void addRequestListener( TransportAddress localAddr,
RequestListener listener)
{
if (requestListenersChildren == null)
{
requestListenersChildren = new Hashtable<NetAccessPointDescriptor, EventDispatcher>();
requestListenersChildren
= new Hashtable<TransportAddress, EventDispatcher>();
}
EventDispatcher child = requestListenersChildren.get(descriptor);
EventDispatcher child = requestListenersChildren.get(localAddr);
if (child == null)
{
child = new EventDispatcher();
requestListenersChildren.put(descriptor, child);
requestListenersChildren.put(localAddr, child);
}
child.addRequestListener(listener);
}
@ -87,7 +87,7 @@ public class EventDispatcher
/**
* Remove a RquestListener from the listener list.
* This removes a RequestListener that was registered
* for all NetAccessPoints and would not remove lsiteners registered for
* for all NetAccessPoints and would not remove listeners registered for
* specific NetAccessPointDescriptors.
*
* @param listener The RequestListener to be removed
@ -108,18 +108,17 @@ public class EventDispatcher
* would only remove the listener for the specified NetAccessPointDescriptor
* and would not remove it if it was also registered as a wildcard listener.
*
* @param apDescriptor The NetAPDescriptor that was listened on.
* @param localAddr The NetAPDescriptor that was listened on.
* @param listener The RequestListener to be removed
*/
public synchronized void removeRequestListener(
NetAccessPointDescriptor apDescriptor,
RequestListener listener)
public synchronized void removeRequestListener(TransportAddress localAddr,
RequestListener listener)
{
if (requestListenersChildren == null)
{
return;
}
EventDispatcher child = requestListenersChildren.get( apDescriptor );
EventDispatcher child = requestListenersChildren.get( localAddr );
if (child == null)
{
@ -136,15 +135,17 @@ public class EventDispatcher
*/
public void fireMessageEvent(StunMessageEvent evt)
{
NetAccessPointDescriptor apDescriptor = evt.getSourceAccessPoint();
TransportAddress localAddr = evt.getLocalAddress();
if (requestListeners != null)
{
Iterator iterator = null;
List<RequestListener> listenersCopy = null;
synchronized(requestListeners)
{
iterator = new ArrayList<RequestListener>(requestListeners).iterator();
listenersCopy
= new ArrayList<RequestListener>(requestListeners);
}
Iterator<RequestListener> iterator = listenersCopy.iterator();
while (iterator.hasNext())
{
RequestListener target =
@ -153,16 +154,14 @@ public class EventDispatcher
}
}
if (requestListenersChildren != null && apDescriptor != null)
if (requestListenersChildren != null && localAddr != null)
{
EventDispatcher child
= requestListenersChildren.get(apDescriptor);
apDescriptor.getAddress().toString();
EventDispatcher child = requestListenersChildren.get(localAddr);
if (child != null)
{
child.fireMessageEvent(evt);
}
if (child != null)
{
child.fireMessageEvent(evt);
}
}
}
@ -170,21 +169,21 @@ public class EventDispatcher
* Check if there are any listeners for a specific NetAccessPointDescriptor.
* (Generic listeners count as well)
*
* @param apDescriptor the NetAccessPointDescriptor.
* @param localAddr the NetAccessPointDescriptor.
* @return true if there are one or more listeners for the specified
* NetAccessPointDescriptor
*/
public synchronized boolean hasRequestListeners(
NetAccessPointDescriptor apDescriptor)
public synchronized boolean hasRequestListeners(TransportAddress localAddr)
{
if(requestListeners != null && !requestListeners.isEmpty())
{
// there is a generic listener
return true;
}
if (requestListenersChildren != null)
{
EventDispatcher child = requestListenersChildren.get(apDescriptor);
EventDispatcher child = requestListenersChildren.get(localAddr);
if (child != null && child.requestListeners != null)
{
return!child.requestListeners.isEmpty();

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -29,27 +29,27 @@ class MessageProcessor
/**
* 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;
/**
* The flag that indicates whether we are still running.
*/
private boolean isRunning = false;
private boolean isRunning = false;
/**
* A reference to the thread that we use to execute ourselves.
*/
private Thread runningThread = null;
private Thread runningThread = null;
/**
* Creates a Message processor.
@ -136,11 +136,9 @@ class MessageProcessor
StunMessageEvent stunMessageEvent =
new StunMessageEvent(
rawMessage.getNetAccessPoint(),
rawMessage.getLocalAddress(),
stunMessage,
new TransportAddress(
rawMessage.getRemoteAddress().getAddress(),
rawMessage.getRemoteAddress().getPort() ));
rawMessage.getRemoteAddress());
messageHandler.handleMessageEvent(stunMessageEvent);
}
}
@ -176,7 +174,7 @@ class MessageProcessor
/**
* Determines whether the processor is still running;
*
* @return true if the processor is still authorised to run, and false
* @return true if the processor is still authorized to run, and false
* otherwise.
*/
boolean isRunning()

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -34,10 +34,10 @@ class NetAccessManager
Logger.getLogger(NetAccessManager.class.getName());
/**
* All access points currently in use. The table maps
* <tt>NetAccessPointDescriptor</tt>s to <tt>NetAccessPoint</tt>s
* <tt>TransportAddress</tt>es to <tt>Connector</tt>s
*/
private Hashtable<NetAccessPointDescriptor, NetAccessPoint> netAccessPoints
= new Hashtable<NetAccessPointDescriptor, NetAccessPoint>();
private Hashtable<TransportAddress, NetAccessPoint> netAccessPoints
= new Hashtable<TransportAddress, NetAccessPoint>();
/**
* A synchronized FIFO where incoming messages are stocked for processing.
@ -96,8 +96,7 @@ class NetAccessManager
}
/**
* Clears the faulty thread and tries to repair the damage and instantiate
* a replacement.
* Clears the faulty thread and reports the problem.
*
* @param callingThread the thread where the error occurred.
* @param message A description of the error
@ -111,23 +110,9 @@ class NetAccessManager
{
NetAccessPoint ap = (NetAccessPoint)callingThread;
//make sure socket is closed
removeNetAccessPoint(ap.getDescriptor());
try
{
logger.log( Level.WARNING, "An access point has unexpectedly "
+"stopped. AP:" + ap.toString(), error);
installNetAccessPoint(ap.getDescriptor());
}
catch (IOException ex)
{
//make sure nothing's left and notify user
removeNetAccessPoint(ap.getDescriptor());
logger.log(Level.WARNING, "Failed to relaunch accesspoint:"
+ ap,
ex);
}
//make sure nothing's left and notify user
removeNetAccessPoint(ap.getListenAddress());
logger.log(Level.WARNING, "Removing connector:"+ ap);
}
else if( callingThread instanceof MessageProcessor )
{
@ -146,72 +131,42 @@ class NetAccessManager
}
}
/**
* Creates and starts a new access point according to the given descriptor.
* If the specified access point has already been installed the method
* has no effect.
*
* @param apDescriptor a description of the access point to create.
* @throws IOException if we fail to bind a datagram socket on the specified
* address and port (NetAccessPointDescriptor)
*/
void installNetAccessPoint(NetAccessPointDescriptor apDescriptor)
throws IOException
{
if(netAccessPoints.containsKey(apDescriptor))
return;
NetAccessPoint ap
= new NetAccessPoint(apDescriptor, messageQueue, this);
netAccessPoints.put(apDescriptor, ap);
ap.start();
}
/**
* Creates and starts a new access point based on the specified socket.
* If the specified access point has already been installed the method
* has no effect.
*
* @param socket the socket that the access point should use.
* @return an access point descriptor to allow further management of the
* newly created access point.
*
* @throws IOException if we fail to setup the socket.
*/
NetAccessPointDescriptor installNetAccessPoint(DatagramSocket socket)
protected void installUdpConnector(DatagramSocket socket)
throws IOException
{
//no null check - let it through a null pointer exception
TransportAddress address = new TransportAddress(
socket.getLocalAddress(), socket.getLocalPort());
NetAccessPointDescriptor apDescriptor
= new NetAccessPointDescriptor(address);
TransportAddress localAddr = new TransportAddress(
socket.getLocalAddress(), socket.getLocalPort(), Transport.UDP);
if(netAccessPoints.containsKey(apDescriptor))
return apDescriptor;
if(netAccessPoints.containsKey(localAddr))
return;
NetAccessPoint ap
= new NetAccessPoint(apDescriptor, messageQueue, this);
NetAccessPoint ap = new NetAccessPoint(socket, messageQueue, this);
//call the useExternalSocket method to avoid closing the socket when
//removing the accesspoint. Bug Report - Dave Stuart - SipQuest
ap.useExternalSocket(socket);
netAccessPoints.put(apDescriptor, ap);
netAccessPoints.put(localAddr, ap);
ap.start();
return apDescriptor;
}
/**
* Stops and deletes the specified access point.
* @param apDescriptor the access point to remove
*
* @param address the address of the connector to remove.
*/
void removeNetAccessPoint(NetAccessPointDescriptor apDescriptor)
protected void removeNetAccessPoint(TransportAddress address)
{
NetAccessPoint ap = netAccessPoints.remove(apDescriptor);
NetAccessPoint ap = netAccessPoints.remove(address);
if(ap != null)
ap.stop();
@ -302,8 +257,8 @@ class NetAccessManager
* Sends the specified stun message through the specified access point.
*
* @param stunMessage the message to send
* @param apDescriptor the access point to use to send the message
* @param address the destination of the message.
* @param srcAddr the access point to use to send the message
* @param remoteAddr the destination of the message.
*
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
@ -311,19 +266,19 @@ class NetAccessManager
* access point that had not been installed,
* @throws StunException if message encoding fails,
*/
void sendMessage(Message stunMessage,
NetAccessPointDescriptor apDescriptor,
TransportAddress address)
void sendMessage(Message stunMessage,
TransportAddress srcAddr,
TransportAddress remoteAddr)
throws IOException, IllegalArgumentException, StunException
{
byte[] bytes = stunMessage.encode();
NetAccessPoint ap = netAccessPoints.get(apDescriptor);
NetAccessPoint ap = netAccessPoints.get(srcAddr);
if(ap == null)
throw new IllegalArgumentException(
"The specified access point had not been installed.");
ap.sendMessage(bytes, address);
ap.sendMessage(bytes, remoteAddr);
}
}

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -30,13 +30,6 @@ class NetAccessPoint
private static final Logger logger =
Logger.getLogger(NetAccessPoint.class.getName());
/**
* Creates a new access point.
*/
NetAccessPoint()
{
}
/**
* The message queue is where incoming messages are added.
*/
@ -45,7 +38,7 @@ class NetAccessPoint
/**
* The socket object that used by this access point to access the network.
*/
protected DatagramSocket sock;
private final DatagramSocket sock;
/**
* A flag that is set to false to exit the message processor.
@ -59,9 +52,9 @@ class NetAccessPoint
private ErrorHandler errorHandler = null;
/**
* Used for locking socket operations
* The address that we are listening to.
*/
private Object socketLock = new Object();
private final TransportAddress listenAddress;
/**
* Creates a network access point.
@ -77,6 +70,8 @@ class NetAccessPoint
this.sock = socket;
this.messageQueue = messageQueue;
this.errorHandler = errorHandler;
this.listenAddress = new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(), Transport.UDP);
}
@ -88,7 +83,7 @@ class NetAccessPoint
void start()
throws IOException
{
synchronized(socketLock)
synchronized(sock)
{
this.isRunning = true;
Thread thread = new Thread(this);
@ -129,8 +124,10 @@ class NetAccessPoint
logger.finest("received datagram");
RawMessage rawMessage = new RawMessage( message,
packet.getLength(), packet.getAddress(), packet.getPort(),
getDescriptor());
packet.getLength(),
new TransportAddress( packet.getAddress(),
packet.getPort(), Transport.UDP),
listenAddress);
messageQueue.add(rawMessage);
}
@ -199,7 +196,7 @@ class NetAccessPoint
DatagramPacket datagramPacket = new DatagramPacket(
message, 0, message.length, address.getSocketAddress());
synchronized(socketLock)
synchronized(sock)
{
sock.send(datagramPacket);
}
@ -212,21 +209,20 @@ class NetAccessPoint
public String toString()
{
return "org.ice4j.stack.AccessPoint@"
+apDescriptor.getAddress()
+ sock.getLocalSocketAddress()
+" status: "
+ (isRunning? "not":"")
+" running";
}
/**
* Sets a socket for the access point to use. This socket will not be
* closed when the AP is <tt>stop()</tt>ed (Bug Report - Dave Stuart).
* Returns the <tt>TransportAddress</tt> that this access point is bound
* on.
*
* @param socket the socket that the AP should use.
* @return the <tt>TransportAddress</tt> associated with this AP.
*/
void useExternalSocket(DatagramSocket socket)
TransportAddress getListenAddress()
{
this.sock = socket;
this.isUsingExternalSocket = true;
return listenAddress;
}
}

View File

@ -1,13 +1,11 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
import java.net.*;
import org.ice4j.*;
/**
@ -32,7 +30,12 @@ class RawMessage
/**
* The address and port where the message was sent from.
*/
private InetSocketAddress remoteAddress = null;
private TransportAddress remoteAddress = null;
/**
* The address that this message was received on.
*/
private TransportAddress localAddress = null;
/**
* Constructs a raw message with the specified field values. All parameters
@ -42,14 +45,15 @@ class RawMessage
* @param messageLength the number of bytes currently stored in the
* <tt>messageBytes</tt> array.
* @param remoteAddress the address where the message came from.
* @param remotePort the port where the message came from.
* @param localAddress the <tt>TransportAddress</tt> that the message was
* received on.
*
* @throws NullPointerException if one or more of the parameters were null.
*/
RawMessage(byte[] messageBytes,
InetAddress remoteAddress,
int messageLength,
int remotePort)
RawMessage(byte[] messageBytes,
int messageLength,
TransportAddress remoteAddress,
TransportAddress localAddress)
{
//... don't do a null check - let it throw an NP exception
@ -58,7 +62,7 @@ class RawMessage
System.arraycopy(messageBytes, 0, this.messageBytes,
0, messageBytes.length);
this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort);
this.remoteAddress = remoteAddress;
}
/**
@ -83,10 +87,21 @@ class RawMessage
/**
* Returns the address and port of the host that sent the message
*
* @return the [address]:[port] pair that sent the message.
*/
InetSocketAddress getRemoteAddress()
public TransportAddress getRemoteAddress()
{
return this.remoteAddress;
}
/**
* Returns the address that this message was received on.
*
* @return the address that this message was received on.
*/
public TransportAddress getLocalAddress()
{
return localAddress;
}
}

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -29,16 +29,16 @@ import org.ice4j.message.*;
* transaction to have failed if no response has been received.
*
*
* <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 Pascal Mogeri (contributed configuration of client transactions).
* @version 0.1
*/
class StunClientTransaction
implements Runnable
{
/**
* Our class logger.
*/
private static final Logger logger =
Logger.getLogger(StunClientTransaction.class.getName());
@ -88,51 +88,45 @@ class StunClientTransaction
/**
* How much did we wait after our last retransmission.
*/
private int nextWaitInterval = originalWaitInterval;
private int nextWaitInterval = originalWaitInterval;
/**
* The StunProvider that created us.
*/
private StunProvider providerCallback = null;
private StunProvider providerCallback = null;
/**
* The request that we are retransmitting.
*/
private Request request = null;
private Request request = null;
/**
* The destination of the request.
*/
private TransportAddress requestDestination= null;
private TransportAddress requestDestination= null;
/**
* The id of the transaction.
*/
private TransactionID transactionID = null;
private TransactionID transactionID = null;
/**
* The NetAccessPoint through which the original request was sent an where
* we are supposed to be retransmitting.
* The <tt>TransportAddress</tt> through which the original request was sent
* and that we are supposed to be retransmitting through.
*/
private NetAccessPointDescriptor apDescriptor = null;
private TransportAddress localAddress = null;
/**
* The instance to notify when a response has been received in the current
* transaction or when it has timed out.
*/
private ResponseCollector responseCollector = null;
private ResponseCollector responseCollector = null;
/**
* Specifies whether the transaction is active or not.
* Determines whether the transaction is active or not.
*/
private boolean cancelled = false;
/**
* The date (in millis) when the next retransmission should follow.
*/
private long nextRetransmissionDate = -1;
/**
* The thread that this transaction runs in.
*/
@ -143,20 +137,20 @@ class StunClientTransaction
* @param providerCallback the provider that created us.
* @param request the request that we are living for.
* @param requestDestination the destination of the request.
* @param apDescriptor the access point through which we are supposed to
* @param localAddress the local <tt>TransportAddress</tt> this transaction
* will be communication through.
* @param responseCollector the instance that should receive this request's
* response.
* retransmit.
* response retransmit.
*/
public StunClientTransaction(StunProvider providerCallback,
Request request,
TransportAddress requestDestination,
NetAccessPointDescriptor apDescriptor,
ResponseCollector responseCollector)
public StunClientTransaction(StunProvider providerCallback,
Request request,
TransportAddress requestDestination,
TransportAddress localAddress,
ResponseCollector responseCollector)
{
this.providerCallback = providerCallback;
this.request = request;
this.apDescriptor = apDescriptor;
this.localAddress = localAddress;
this.responseCollector = responseCollector;
this.requestDestination = requestDestination;
@ -267,7 +261,7 @@ class StunClientTransaction
}
providerCallback.getNetAccessManager().sendMessage(
this.request,
apDescriptor,
localAddress,
requestDestination);
}

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
@ -69,7 +69,7 @@ public class StunProvider
* registers the specified ResponseCollector for later notification.
* @param request the request to send
* @param sendTo the destination address of the request.
* @param sendThrough the access point to use when sending the request
* @param sendThrough the local address to use when sending the request
* @param collector the instance to notify when a response arrives or the
* the transaction timeouts
*
@ -80,10 +80,10 @@ public class StunProvider
* @throws StunException if message encoding fails,
*
*/
public void sendRequest( Request request,
TransportAddress sendTo,
NetAccessPointDescriptor sendThrough,
ResponseCollector collector )
public void sendRequest( Request request,
TransportAddress sendTo,
TransportAddress sendThrough,
ResponseCollector collector )
throws StunException, IOException, IllegalArgumentException
{
StunClientTransaction clientTransaction
@ -103,7 +103,7 @@ public class StunProvider
* have the id in the response object, but I am bringing out as an extra
* parameter as the user might otherwise forget to explicitly set it.
* @param response the message to send.
* @param sendThrough the access point to use when sending the message.
* @param sendThrough the local address to use when sending the message.
* @param sendTo the destination of the message.
*
* @throws IOException if an error occurs while sending message bytes
@ -113,10 +113,10 @@ public class StunProvider
* @throws StunException if message encoding fails,
*/
public void sendResponse(byte[] transactionID,
Response response,
NetAccessPointDescriptor sendThrough,
TransportAddress sendTo)
public void sendResponse(byte[] transactionID,
Response response,
TransportAddress sendThrough,
TransportAddress sendTo)
throws StunException,
IOException,
IllegalArgumentException
@ -166,15 +166,18 @@ public class StunProvider
* The listener will be invoked only when a request event is received on
* that specific property.
*
* @param apDescriptor The descriptor of the NetAccessPoint to listen on.
* @param listener The ConfigurationChangeListener to be added
* @param localAddress The local <tt>TransportAddress</tt> that we would
* like to listen on.
* @param listener The ConfigurationChangeListener to be added
*/
public synchronized void addRequestListener(
NetAccessPointDescriptor apDescriptor,
RequestListener listener)
public void addRequestListener( TransportAddress localAddress,
RequestListener listener)
{
eventDispatcher.addRequestListener(apDescriptor, listener);
synchronized(eventDispatcher)
{
eventDispatcher.addRequestListener(localAddress, listener);
}
}
//------------- stack internals ------------------------------------------------
@ -219,7 +222,7 @@ public class StunProvider
if(logger.isLoggable(Level.FINEST))
logger.finest("Received a message on NetAP"
+ event.getSourceAccessPoint()
+ event.getLocalAddress()
+ " of type:"
+ (int)msg.getMessageType());

View File

@ -1,12 +1,11 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
import java.util.TimerTask;
import java.io.*;
import org.ice4j.*;
@ -31,10 +30,7 @@ import org.ice4j.message.*;
* response that was saved for the original request, and not let any
* retransmissions go through to the user application.
*
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
class StunServerTransaction
@ -48,7 +44,7 @@ class StunServerTransaction
/**
* The StunProvider that created us.
*/
private StunProvider providerCallback = null;
private StunProvider providerCallback = null;
/**
* The source of the transaction request.
@ -61,17 +57,17 @@ class StunServerTransaction
private Response response = null;
/**
* The ap descriptor used when sending the response
* The <tt>TransportAddress</tt> we use when sending responses
*/
private NetAccessPointDescriptor apDescriptor = null;
private TransportAddress localAddress = null;
/**
* The id of the transaction.
*/
private TransactionID transactionID = null;
private TransactionID transactionID = null;
/**
* The date (in millis) when the next retransmission should follow.
* The date (in milliseconds) when the next retransmission should follow.
*/
private long expirationDate = -1;
@ -140,7 +136,7 @@ class StunServerTransaction
* the transaction's state to retransmitting.
*
* @param response the response to send the transaction to.
* @param sendThrough the NetAccessPoint through which the response is to
* @param sendThrough the local address through which the response is to
* be sent
* @param sendTo the destination of the response.
*
@ -150,9 +146,9 @@ class StunServerTransaction
* access point that had not been installed,
* @throws StunException if message encoding fails,
*/
void sendResponse(Response response,
NetAccessPointDescriptor sendThrough,
TransportAddress sendTo)
public void sendResponse(Response response,
TransportAddress sendThrough,
TransportAddress sendTo)
throws StunException,
IOException,
IllegalArgumentException
@ -162,7 +158,7 @@ class StunServerTransaction
//the transaction id might already have been set, but its our job
//to make sure of that
response.setTransactionID(this.transactionID.getTransactionID());
this.apDescriptor = sendThrough;
this.localAddress = sendThrough;
this.responseDestination = sendTo;
}
@ -180,7 +176,7 @@ class StunServerTransaction
* access point that had not been installed,
* @throws StunException if message encoding fails,
*/
void retransmitResponse()
private void retransmitResponse()
throws StunException,
IOException,
IllegalArgumentException
@ -191,15 +187,15 @@ class StunServerTransaction
return;
providerCallback.getNetAccessManager().sendMessage(response,
apDescriptor,
localAddress,
responseDestination);
}
/**
* Waits until next retransmission is due or until the transaction is
* cancelled (whichever comes first).
* canceled (whichever comes first).
*/
synchronized void waitNextScheduledDate()
private synchronized void waitNextScheduledDate()
{
long current = System.currentTimeMillis();
while(expirationDate - current > 0)
@ -221,9 +217,10 @@ class StunServerTransaction
/**
* Sets the expiration date for this server transaction.
* @param timeout the number of millis to wait before expiration.
*
* @param timeout the number of milliseconds to wait before expiration.
*/
void schedule(long timeout)
private void schedule(long timeout)
{
this.expirationDate = System.currentTimeMillis() + timeout;
}
@ -232,7 +229,7 @@ class StunServerTransaction
* Cancels the transaction. Once this method is called the transaction is
* considered terminated and will stop retransmissions.
*/
synchronized void expire()
public synchronized void expire()
{
this.expired = true;
notifyAll();
@ -244,7 +241,7 @@ class StunServerTransaction
*
* @return the ID of the transaction.
*/
TransactionID getTransactionID()
public TransactionID getTransactionID()
{
return this.transactionID;
}
@ -252,9 +249,11 @@ class StunServerTransaction
/**
* Specifies whether this server transaction is in the retransmitting state.
* Or in other words - has it already sent a first response or not?
* @return boolean
*
* @return <tt>true</tt> if this transaction is still retransmitting and
* false <tt>otherwise</tt>
*/
boolean isReransmitting()
public boolean isReransmitting()
{
return isRetransmitting;
}

View File

@ -1,25 +1,21 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stack;
import java.net.DatagramSocket;
import java.io.*;
import java.net.*;
import org.ice4j.*;
import org.ice4j.message.*;
/**
* The entry point to the Stun4J stack. The class is used to start, stop and
* configure the stack.
*
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
public class StunStack
{
@ -69,49 +65,35 @@ public class StunStack
netAccessManager.setThreadPoolSize(threadPoolSize);
}
/**
* Creates and starts the specified Network Access Point.
*
* @param apDescriptor A descriptor containing the address and port of the
* STUN server that the newly created access point will communicate with.
* @throws IOException if we fail to bind a datagram socket on the specified
* address and port (NetAccessPointDescriptor)
*/
public void installNetAccessPoint(NetAccessPointDescriptor apDescriptor)
throws IOException
{
netAccessManager.installNetAccessPoint(apDescriptor);
}
/**
* Creates and starts the specified Network Access Point based on the
* specified socket and returns a relevant descriptor.
*
* @param sock The socket that the new access point should represent.
* @throws IOException if we fail to setup the socket.
* @return a descriptor of the newly created access point.
*/
public NetAccessPointDescriptor installNetAccessPoint(DatagramSocket sock)
public void installNetAccessPoint(DatagramSocket sock)
throws IOException
{
return netAccessManager.installNetAccessPoint(sock);
netAccessManager.installUdpConnector(sock);
}
/**
* Stops and deletes the specified access point.
* @param apDescriptor the access point to remove
* Stops and deletes the connector listening on the specified local address.
*
* @param localAddr the access point to remove
*/
public void removeNetAccessPoint(NetAccessPointDescriptor apDescriptor)
public void removeNetAccessPoint(TransportAddress localAddr)
{
netAccessManager.removeNetAccessPoint(apDescriptor);
netAccessManager.removeNetAccessPoint(localAddr);
}
/**
* Returns a StunProvider instance to be used for sending and receiving
* mesages.
* messages.
*
* @return an instance of StunProvider
*/

View File

@ -1,26 +1,26 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import java.util.logging.*;
import java.io.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* A utility used to flatten the multithreaded architecture of the Stack
* A utility used to flatten the multi-thread architecture of the Stack
* and execute the discovery process in a synchronized manner. Roughly what
* happens here is:
*
* <code>
* ApplicationThread:
* sendMessage()
* wait();
* wait();
*
* StackThread:
* processMessage/Timeout()
@ -28,32 +28,57 @@ import org.ice4j.stack.*;
* saveMessage();
* notify();
* }
*</code>
*
*
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
class BlockingRequestSender
implements ResponseCollector
{
private static final Logger logger =
Logger.getLogger(BlockingRequestSender.class.getName());
/**
* Our class logger
*/
private static final Logger logger
= Logger.getLogger(BlockingRequestSender.class.getName());
private StunProvider stunProvider = null;
private NetAccessPointDescriptor apDescriptor = null;
/**
* The provider that we are using to send requests through.
*/
private StunProvider stunProvider = null;
StunMessageEvent responseEvent = null;
/**
* The transport address that we are bound on.
*/
private TransportAddress localAddress = null;
/**
* The <tt>StunMessageEvent</tt> that contains the response matching our
* request.
*/
private StunMessageEvent responseEvent = null;
/**
* Determines whether this request sender has comleted its coarse.
*/
private boolean ended = false;
private Object sendLock = new Object();
BlockingRequestSender(StunProvider stunProvider,
NetAccessPointDescriptor apDescriptor)
/**
* A lock object that we are using to synchronize sending.
*/
private Object sendLock = new Object();
/**
* Creates a new request sender.
* @param stunProvider the provider that the sender should send requests
* through.
* @param localAddress the <tt>TransportAddress</tt> that requests should be
* leaving from.
*/
BlockingRequestSender(StunProvider stunProvider,
TransportAddress localAddress)
{
this.stunProvider = stunProvider;
this.apDescriptor = apDescriptor;
this.localAddress = localAddress;
}
/**
@ -71,7 +96,7 @@ class BlockingRequestSender
}
/**
* Notifies the discoverer thread when a message has timeouted so that
* Notifies the discoverer thread when a message has timeout-ed so that
* it may resume and consider it as unanswered.
*/
public synchronized void processTimeout()
@ -85,7 +110,7 @@ class BlockingRequestSender
/**
* Sends the specified request and blocks until a response has been
* received or the request transaction has timed out.
* @param request the reuqest to send
* @param request the request to send
* @param serverAddress the request destination address
* @return the event encapsulating the response or null if no response
* has been received.
@ -97,13 +122,13 @@ class BlockingRequestSender
* @throws StunException if message encoding fails,
*/
public synchronized StunMessageEvent sendRequestAndWaitForResponse(
Request request,
TransportAddress serverAddress)
Request request,
TransportAddress serverAddress)
throws StunException,
IOException
{
synchronized(sendLock){
stunProvider.sendRequest(request, serverAddress, apDescriptor,
stunProvider.sendRequest(request, serverAddress, localAddress,
BlockingRequestSender.this);
}

View File

@ -1,15 +1,14 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import java.net.*;
import java.util.logging.*;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
@ -85,6 +84,9 @@ import org.ice4j.stack.*;
public class NetworkConfigurationDiscoveryProcess
{
/**
* Our class logger.
*/
private static final Logger logger =
Logger.getLogger(NetworkConfigurationDiscoveryProcess.class.getName());
/**
@ -96,52 +98,46 @@ public class NetworkConfigurationDiscoveryProcess
/**
* The stack to use for STUN communication.
*/
private StunStack stunStack = null;
private StunStack stunStack = null;
/**
* The provider to send our messages through
*/
private StunProvider stunProvider = null;
private StunProvider stunProvider = null;
/**
* The point where we'll be listening.
*/
private NetAccessPointDescriptor apDescriptor = null;
private TransportAddress localAddress = null;
/**
* The address of the stun server
*/
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 thread architecture of the Stack
* and execute the discovery process in a synchronized manner
*/
private BlockingRequestSender requestSender = null;
private BlockingRequestSender requestSender = null;
/**
* The <tt>DatagramSocket</tt> that we are going to be running the
* discovery process through.
*/
private DatagramSocket sock = null;
/**
* Creates a StunAddressDiscoverer. In order to use it one must start the
* discoverer.
* @param localAddress the address where the stach should bind.
*
* @param localAddress the address where the stack should bind.
* @param serverAddress the address of the server to interrogate.
*/
public NetworkConfigurationDiscoveryProcess(TransportAddress localAddress,
TransportAddress serverAddress)
TransportAddress serverAddress)
{
apDescriptor = new NetAccessPointDescriptor(localAddress);
this.serverAddress = serverAddress;
}
/**
* Creates a StunAddressDiscoverer. In order to use it one must start the
* discoverer.
* @param apDescriptor the address where the stach should bind.
* @param serverAddress the address of the server to interrogate.
*/
public NetworkConfigurationDiscoveryProcess(NetAccessPointDescriptor apDescriptor,
TransportAddress serverAddress)
{
this.apDescriptor = apDescriptor;
this.localAddress = localAddress;
this.serverAddress = serverAddress;
}
@ -154,7 +150,7 @@ public class NetworkConfigurationDiscoveryProcess
{
stunStack = null;
stunProvider = null;
apDescriptor = null;
localAddress = null;
requestSender = null;
this.started = false;
@ -171,11 +167,13 @@ public class NetworkConfigurationDiscoveryProcess
{
stunStack = StunStack.getInstance();
stunStack.installNetAccessPoint(apDescriptor);
DatagramSocket sock
= new DatagramSocket(localAddress.getSocketAddress());
stunStack.installNetAccessPoint(sock);
stunProvider = stunStack.getProvider();
requestSender = new BlockingRequestSender(stunProvider, apDescriptor);
requestSender = new BlockingRequestSender(stunProvider, localAddress);
started = true;
}
@ -228,7 +226,7 @@ public class NetworkConfigurationDiscoveryProcess
+ ", name=" + backupServerAddress.getHostAddress());
report.setPublicAddress(mappedAddress);
if (mappedAddress.equals(apDescriptor.getAddress()))
if (mappedAddress.equals(localAddress))
{
evt = doTestII(serverAddress);
if (evt == null)
@ -260,7 +258,8 @@ public class NetworkConfigurationDiscoveryProcess
}
TransportAddress mappedAddress2 =
((MappedAddressAttribute)evt.getMessage().
getAttribute(Attribute.MAPPED_ADDRESS)).getAddress();
getAttribute(Attribute.MAPPED_ADDRESS))
.getAddress();
if(mappedAddress.equals(mappedAddress2))
{
evt = doTestIII(serverAddress);
@ -322,7 +321,8 @@ public class NetworkConfigurationDiscoveryProcess
changeRequest.setChangePortFlag(false);
*/
/* add a change request attribute */
ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute();
ChangeRequestAttribute changeRequest
= AttributeFactory.createChangeRequestAttribute();
changeRequest.setChangeIpFlag(false);
changeRequest.setChangePortFlag(false);
request.addAttribute(changeRequest);
@ -367,7 +367,9 @@ public class NetworkConfigurationDiscoveryProcess
{
Request request = MessageFactory.createBindingRequest();
/* ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */
/* ChangeRequestAttribute changeRequest
* = (ChangeRequestAttribute)request
* .getAttribute(Attribute.CHANGE_REQUEST); */
/* add a change request attribute */
ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute();
changeRequest.setChangeIpFlag(true);

View File

@ -1,8 +1,8 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.stunclient;

View File

@ -1,205 +0,0 @@
package org.ice4j.stunclient;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
import org.ice4j.stunclient.*;
/**
* The interface given to the ICE agent to send STUN requests
* and receive responses
*
* @author Namal Senarathne
*/
public class StunClient
implements ResponseCollector
{
private final Logger logger =
Logger.getLogger(StunClient.class.getName());
/**
* The STUN stack
*/
private StunStack stunStack = null;
/**
* The Stun Provider from the stack
*/
private StunProvider stunProvider = null;
/**
* The HashMap used to store the sent requests and correlate between
* the responses and the requests.
* This data structure is used only when sendStunRequest message is invoked
*/
private HashMap<byte[], Request> requestMap = new HashMap<byte[], Request>();
/**
* Creates a new Instance of the ST
* @param stunStack
*/
public StunClient(StunStack stunStack)
{
this.stunStack = stunStack;
stunProvider = stunStack.getProvider();
}
//------------------ Implemented methods of the ResponseCollector interface -------------
/**
* This callBack method is called in a separate thread to process
* incomming response
*/
public void processResponse(StunMessageEvent response) {
// TODO Auto-generated method stub
Message responseMsg = response.getMessage(); /* retrieving the response message */
byte[] tid = responseMsg.getTransactionID(); /* retrieving the Transaction ID */
synchronized(requestMap)
{
if(requestMap.containsKey(tid))
{
// TODO : process the response
requestMap.remove(tid);
// TODO : additional processing ; set done status for the candidate pair
}
}
MappedAddressAttribute mappedAttribute =
(MappedAddressAttribute)responseMsg.getAttribute(Attribute.MAPPED_ADDRESS);
if(mappedAttribute != null)
{
TransportAddress mappedAddr = mappedAttribute.getAddress();
System.out.println("The mapped address : " + mappedAddr.getHostAddress() +
" : " + (int)mappedAddr.getPort());
}
}
/**
*
*/
public void processTimeout() {
// TODO Auto-generated method stub
// How can you recognize which request (TransactionID) timed-out
// ignore it at the moment
}
//-------------------- Public interface ---------------------------------------
// TODO : move them up
private boolean ended = false;
private Object sendLock = new Object();
/**
* Determines the public IP of the specified Transport address in a blocking manner
*/
public TransportAddress determineAddress(TransportAddress localAddress,
TransportAddress serverAddress)
throws StunException, IOException
{
NetAccessPointDescriptor apDescriptor
= new NetAccessPointDescriptor(localAddress);
Request request = MessageFactory.createBindingRequest();
stunStack.installNetAccessPoint(apDescriptor);
synchronized (sendLock)
{
try
{
stunProvider.sendRequest(request, serverAddress,
apDescriptor, this);
}
catch(Exception e)
{
logger.warning("Cannot determine mapped address for " + localAddress);
}
}
ended = false;
return null;
}
/**
* Determines the NAT type
*/
public TransportAddress determineAddress(NetAccessPointDescriptor apDescriptor,
TransportAddress serverAddress)
{
return null;
}
/**
* TODO : modify the signature of the method
*
* @param request The stun Request object
* @param sendTo The address of the server
* @param apDescriptor The NetAccessPointDescriptor
* @param collector The response collector
*/
public void sendStunRequest(Request request,
TransportAddress sendTo,
NetAccessPointDescriptor apDescriptor, // apDescriptor must be installed in the stack
ResponseCollector collector)
throws StunException, IOException, IllegalArgumentException
{
logger.log(Level.INFO, "Sending the request ... ");
try
{
stunProvider.sendRequest(request, sendTo, apDescriptor, collector);
synchronized (requestMap) {
requestMap.put(request.getTransactionID(), request);
}
}
catch(StunException ex)
{
logger.log(Level.SEVERE, "StunException occurred..", ex);
throw new StunException();
}
catch(IOException ex)
{
logger.log(Level.SEVERE, "IOException occurred", ex);
throw new StunException();
}
catch(IllegalArgumentException ex)
{
logger.log(Level.SEVERE, "IllegalArgumentException occurred", ex);
throw new StunException();
}
}
/*public static void main(String[] args) throws IOException, IllegalArgumentException, StunException
{
StunStack stunStack = StunStack.getInstance();
NetAccessPointDescriptor apDescriptor =
new NetAccessPointDescriptor(new TransportAddress("localhost", 5009));
stunStack.installNetAccessPoint(apDescriptor);
StunClient stunClient = new StunClient(stunStack);
// create the Stun Request message
Request request = MessageFactory.createBindingRequest();
TransportAddress serverAddress = new TransportAddress("localhost", 4006);
stunClient.sendStunRequest(request, serverAddress, apDescriptor, stunClient);
}*/
}