Uses StunStack on a per-Agent basis.

This commit is contained in:
lubomir.marinov 2010-09-12 13:17:06 +00:00
parent 3d4de0f547
commit 5f4c05d699
35 changed files with 601 additions and 319 deletions

View File

@ -15,7 +15,7 @@ import org.ice4j.stack.*;
* Represents an <tt>EventObject</tt> which notifies of an event associated with
* a specific STUN <tt>Message</tt>.
*
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class BaseStunMessageEvent
extends EventObject
@ -30,6 +30,11 @@ public class BaseStunMessageEvent
*/
private final Message message;
/**
* The <tt>StunStack</tt> associated with this instance.
*/
private final StunStack stunStack;
/**
* The ID of the transaction related to {@link #message}.
*/
@ -39,14 +44,20 @@ public class BaseStunMessageEvent
* Initializes a new <tt>BaseStunMessageEvent</tt> associated with a
* specific STUN <tt>Message</tt>.
*
* @param stunStack the <tt>StunStack</tt> to be associated with the new
* instance
* @param sourceAddress the <tt>TransportAddress</tt> which is to be
* reported as the source of the new event
* @param message the STUN <tt>Message</tt> associated with the new event
*/
public BaseStunMessageEvent(TransportAddress sourceAddress, Message message)
public BaseStunMessageEvent(
StunStack stunStack,
TransportAddress sourceAddress,
Message message)
{
super(sourceAddress);
this.stunStack = stunStack;
this.message = message;
}
@ -70,6 +81,16 @@ public class BaseStunMessageEvent
return (TransportAddress) getSource();
}
/**
* Gets the <tt>StunStack</tt> associated with this instance.
*
* @return the <tt>StunStack</tt> associated with this instance
*/
public StunStack getStunStack()
{
return stunStack;
}
/**
* Gets the ID of the transaction related to the STUN <tt>Message</tt>
* associated with this event.
@ -80,9 +101,12 @@ public class BaseStunMessageEvent
public TransactionID getTransactionID()
{
if (transactionID == null)
{
transactionID
= TransactionID
.createTransactionID(getMessage().getTransactionID());
= TransactionID.createTransactionID(
getStunStack(),
getMessage().getTransactionID());
}
return transactionID;
}

View File

@ -7,6 +7,7 @@
package org.ice4j;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* The class is used to dispatch events that occur when a STUN transaction
@ -31,18 +32,22 @@ public class StunFailureEvent
/**
* Constructs a <tt>StunFailureEvent</tt> according to the specified
* message.
*
*
* @param stunStack the <tt>StunStack</tt> to be associated with the new
* instance
* @param message the message itself
* @param localAddress the local address that the message was sent from.
* @param cause the <tt>Exception</tt> that caused this failure or
* <tt>null</tt> if there's no <tt>Exception</tt> associated with this
* failure
*/
public StunFailureEvent(Message message,
TransportAddress localAddress,
Throwable cause)
public StunFailureEvent(
StunStack stunStack,
Message message,
TransportAddress localAddress,
Throwable cause)
{
super(localAddress, message);
super(stunStack, localAddress, message);
this.cause = cause;
}

View File

@ -34,13 +34,18 @@ public class StunMessageEvent
/**
* Constructs a StunMessageEvent according to the specified message.
*
* @param stunStack the <tt>StunStack</tt> to be associated with the new
* instance
* @param rawMessage the crude message we got off the wire.
* @param parsedMessage the message itself
*/
public StunMessageEvent(RawMessage rawMessage,
Message parsedMessage)
public StunMessageEvent(
StunStack stunStack,
RawMessage rawMessage,
Message parsedMessage)
{
super(rawMessage.getLocalAddress(), parsedMessage);
super(stunStack, rawMessage.getLocalAddress(), parsedMessage);
this.rawMessage = rawMessage;
}

View File

@ -34,18 +34,22 @@ public class StunResponseEvent
/**
* Creates a new instance of this event.
*
* @param stunStack the <tt>StunStack</tt> to be associated with the new
* instance
* @param rawMessage the crude message we got off the wire.
* @param response the STUN {@link Response} that we've just received.
* @param request the message itself
* @param transactionID a reference to the exact {@link TransactionID}
* instance that represents the corresponding client transaction.
*/
public StunResponseEvent(RawMessage rawMessage,
Response response,
Request request,
TransactionID transactionID)
public StunResponseEvent(
StunStack stunStack,
RawMessage rawMessage,
Response response,
Request request,
TransactionID transactionID)
{
super(rawMessage, response);
super(stunStack, rawMessage, response);
this.request = request;
super.setTransactionID(transactionID);
}

View File

@ -27,16 +27,21 @@ public class StunTimeoutEvent
* Constructs a <tt>StunTimeoutEvent</tt> according to the specified
* message.
*
* @param stunStack the <tt>StunStack</tt> to be associated with the new
* instance
* @param message the message itself
* @param localAddress the local address that the message was sent from.
* @param transactionID the ID of the associated with this event.
*/
public StunTimeoutEvent(Message message,
TransportAddress localAddress,
TransactionID transactionID)
public StunTimeoutEvent(
StunStack stunStack,
Message message,
TransportAddress localAddress,
TransactionID transactionID)
{
super(localAddress, message);
super.setTransactionID(transactionID);
super(stunStack, localAddress, message);
setTransactionID(transactionID);
}
/**

View File

@ -6,6 +6,8 @@
*/
package org.ice4j.attribute;
import org.ice4j.stack.*;
/**
* <tt>ContentDependentAttribute</tt>s have a value that depend on the content
* of the message. The {@link MessageIntegrityAttribute} and {@link
@ -13,6 +15,7 @@ package org.ice4j.attribute;
* <p>
* Rather than encoding them via the standard {@link Attribute#encode()} method,
* the stack would use the one from this interface.
* </p>
*
* @author Emil Ivov
*/
@ -21,6 +24,8 @@ public interface ContentDependentAttribute
/**
* Returns a binary representation of this attribute.
*
* @param stunStack the <tt>StunStack</tt> in the context of which the
* request to encode this <tt>ContentDependentAttribute</tt> is being made
* @param content the content of the message that this attribute will be
* transported in
* @param offset the <tt>content</tt>-related offset where the actual
@ -30,5 +35,7 @@ public interface ContentDependentAttribute
* @return a binary representation of this attribute valid for the message
* with the specified <tt>content</tt>.
*/
public byte[] encode(byte[] content, int offset, int length);
public byte[] encode(
StunStack stunStack,
byte[] content, int offset, int length);
}

View File

@ -9,6 +9,7 @@ package org.ice4j.attribute;
import java.util.zip.*;
import org.ice4j.*;
import org.ice4j.stack.*;
/**
* The FINGERPRINT attribute is used to distinguish STUN packets from packets
@ -145,6 +146,8 @@ public class FingerprintAttribute
/**
* Returns a binary representation of this attribute.
*
* @param stunStack the <tt>StunStack</tt> in the context of which the
* request to encode this <tt>ContentDependentAttribute</tt> is being made
* @param content the content of the message that this attribute will be
* transported in
* @param offset the <tt>content</tt>-related offset where the actual
@ -154,7 +157,9 @@ public class FingerprintAttribute
* @return a binary representation of this attribute valid for the message
* with the specified <tt>content</tt>.
*/
public byte[] encode(byte[] content, int offset, int length)
public byte[] encode(
StunStack stunStack,
byte[] content, int offset, int length)
{
char type = getAttributeType();
byte binValue[] = new byte[HEADER_LENGTH + getDataLength()];

View File

@ -228,6 +228,8 @@ public class MessageIntegrityAttribute
/**
* Returns a binary representation of this attribute.
*
* @param stunStack the <tt>StunStack</tt> in the context of which the
* request to encode this <tt>ContentDependentAttribute</tt> is being made
* @param content the content of the message that this attribute will be
* transported in
* @param offset the <tt>content</tt>-related offset where the actual
@ -237,7 +239,9 @@ public class MessageIntegrityAttribute
* @return a binary representation of this attribute valid for the message
* with the specified <tt>content</tt>.
*/
public byte[] encode(byte[] content, int offset, int length)
public byte[] encode(
StunStack stunStack,
byte[] content, int offset, int length)
{
char type = getAttributeType();
byte binValue[] = new byte[HEADER_LENGTH + getDataLength()];
@ -250,8 +254,7 @@ public class MessageIntegrityAttribute
binValue[2] = (byte)(getDataLength()>>8);
binValue[3] = (byte)(getDataLength()&0x00FF);
byte[] key = StunStack.getInstance().getCredentialsManager()
.getRemoteKey(username);
byte[] key = stunStack.getCredentialsManager().getRemoteKey(username);
//now calculate the HMAC-SHA1
this.hmacSha1Content = calculateHmacSha1(content, offset, length, key);

View File

@ -30,6 +30,7 @@ import org.ice4j.stack.*;
* <p>
*
* @author Emil Ivov
* @author Lyubomir Marinov
*/
public class Agent
{
@ -189,13 +190,18 @@ public class Agent
private final List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>();
/**
* The <tt>StunStack</tt> used by this <tt>Agent</tt>.
*/
private StunStack stunStack;
/**
* The thread that we use for moving from COMPLETED into a TERMINATED state.
*/
private TerminationThread terminationThread;
/**
* Creates an empty <tt>Agent</tt> with no streams, and no address
* Initializes an empty <tt>Agent</tt> with no streams, and no address.
*/
public Agent()
{
@ -207,14 +213,12 @@ public class Agent
tieBreaker = Math.abs(random.nextLong());
//add the software attribute to all messages
String sware = StackProperties.getString(StackProperties.SOFTWARE);
if( sware == null)
if (StackProperties.getString(StackProperties.SOFTWARE) == null)
System.setProperty(StackProperties.SOFTWARE, "ice4j.org");
//add the FINGERPRINT attribute to all messages.
System.setProperty(StackProperties.ALWAYS_SIGN, "true");
nominator = new DefaultNominator(this);
}
@ -717,6 +721,18 @@ public class Agent
}
}
/**
* Gets the <tt>StunStack</tt> used by this <tt>Agent</tt>.
*
* @return the <tt>StunStack</tt> used by this <tt>Agent</tt>
*/
public synchronized StunStack getStunStack()
{
if (stunStack == null)
stunStack = new StunStack();
return stunStack;
}
/**
* Returns the number of {@link CheckList}s that are currently active.
*
@ -1036,7 +1052,7 @@ public class Agent
TransactionID checkTransaction
= knownPair.getConnectivityCheckTransaction();
StunStack.getInstance().cancelTransaction(checkTransaction);
getStunStack().cancelTransaction(checkTransaction);
}
}
else

View File

@ -24,7 +24,7 @@ import org.ice4j.*;
* </p>
*
* @author Emil Ivov
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public abstract class Candidate
{
@ -80,7 +80,7 @@ public abstract class Candidate
* The component that this candidate was created for. Every candidate is
* always associated with a specific component for which it is a candidate.
*/
private Component parentComponent = null;
private final Component parentComponent;
/**
* The address of the STUN server that was used to obtain this

View File

@ -20,7 +20,7 @@ import org.ice4j.stack.*;
* will be handling their responses or lack thereof.
*
* @author Emil Ivov
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
class ConnectivityCheckClient
implements ResponseCollector
@ -38,9 +38,9 @@ class ConnectivityCheckClient
private final Agent parentAgent;
/**
* The stun stack that we will use for connectivity checks.
* The <tt>StunStack</tt> that we will use for connectivity checks.
*/
private static final StunStack stunStack = StunStack.getInstance();
private final StunStack stunStack;
/**
* The {@link PaceMaker}s that are currently running checks in this client.
@ -57,6 +57,8 @@ class ConnectivityCheckClient
public ConnectivityCheckClient(Agent parentAgent)
{
this.parentAgent = parentAgent;
stunStack = this.parentAgent.getStunStack();
}
/**
@ -160,7 +162,8 @@ class ConnectivityCheckClient
try
{
tran
= stunStack.sendRequest(request,
= stunStack.sendRequest(
request,
candidatePair
.getRemoteCandidate().getTransportAddress(),
localCandidate.getTransportAddress(),

View File

@ -37,9 +37,9 @@ class ConnectivityCheckServer
private final Agent parentAgent;
/**
* The stun stack that we will use for connectivity checks.
* The <tt>StunStack </tt> that we will use for connectivity checks.
*/
private StunStack stunStack = StunStack.getInstance();
private final StunStack stunStack;
/**
* Creates a new <tt>ConnectivityCheckServer</tt> setting
@ -51,6 +51,8 @@ class ConnectivityCheckServer
public ConnectivityCheckServer(Agent parentAgent)
{
this.parentAgent = parentAgent;
stunStack = this.parentAgent.getStunStack();
stunStack.addRequestListener(this);
stunStack.getCredentialsManager().registerAuthority(this);
}
@ -207,10 +209,11 @@ class ConnectivityCheckServer
try
{
StunStack.getInstance().sendResponse(
evt.getTransactionID().getBytes(),
response, evt.getLocalAddress(),
evt.getRemoteAddress());
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
@ -266,10 +269,11 @@ class ConnectivityCheckServer
try
{
StunStack.getInstance().sendResponse(
evt.getTransactionID().getBytes(),
response, evt.getLocalAddress(),
evt.getRemoteAddress());
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
@ -366,6 +370,6 @@ class ConnectivityCheckServer
*/
public void stop()
{
StunStack.getInstance().removeRequestListener(this);
stunStack.removeRequestListener(this);
}
}

View File

@ -19,7 +19,7 @@ import org.ice4j.stack.*;
* and are then included in outgoing offers or answers.
*
* @author Emil Ivov
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public abstract class LocalCandidate
extends Candidate
@ -114,6 +114,20 @@ public abstract class LocalCandidate
return stunSocket;
}
/**
* Gets the <tt>StunStack</tt> associated with this <tt>Candidate</tt>.
*
* @return the <tt>StunStack</tt> associated with this <tt>Candidate</tt>
*/
public StunStack getStunStack()
{
return
getParentComponent()
.getParentStream()
.getParentAgent()
.getStunStack();
}
/**
* Creates a new <tt>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned
@ -151,7 +165,7 @@ public abstract class LocalCandidate
|| (base.getSocket() != socket))
{
//remove our socket from the stack.
StunStack.getInstance().removeSocket(getTransportAddress());
getStunStack().removeSocket(getTransportAddress());
/*
* Allow this LocalCandiate implementation to not create a

View File

@ -15,7 +15,6 @@ import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
/**
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a
@ -242,6 +241,7 @@ public class HostCandidateHarvester
private void createAndRegisterStunSocket(HostCandidate candidate)
{
DatagramSocket stunSocket = candidate.getStunSocket(null);
StunStack.getInstance().addSocket(stunSocket);
candidate.getStunStack().addSocket(stunSocket);
}
}

View File

@ -23,7 +23,7 @@ import org.ice4j.stack.*;
* <tt>HostCandidate</tt> performed by a specific
* <tt>StunCandidateHarvester</tt>.
*
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class StunCandidateHarvest
extends AbstractResponseCollector
@ -226,8 +226,10 @@ public class StunCandidateHarvest
if (((response == null) || !response.isSuccessResponse())
&& (longTermCredentialSession != null))
{
harvester.stunStack.getCredentialsManager().unregisterAuthority(
longTermCredentialSession);
harvester
.getStunStack()
.getCredentialsManager()
.unregisterAuthority(longTermCredentialSession);
longTermCredentialSession = null;
}
}
@ -492,7 +494,7 @@ public class StunCandidateHarvest
longTermCredential,
realm);
harvester
.stunStack
.getStunStack()
.getCredentialsManager()
.registerAuthority(longTermCredentialSession);
}
@ -560,6 +562,7 @@ public class StunCandidateHarvest
= (retryRequestTransactionIDAsBytes == null)
? TransactionID.createNewTransactionID()
: TransactionID.createTransactionID(
harvester.getStunStack(),
retryRequestTransactionIDAsBytes);
retryRequestTransactionID.setApplicationData(
applicationData);
@ -785,7 +788,7 @@ public class StunCandidateHarvest
*/
if (usernameAttribute == null)
return;
if (!harvester.stunStack.validateMessageIntegrity(
if (!harvester.getStunStack().validateMessageIntegrity(
messageIntegrityAttribute,
LongTermCredential.toString(
usernameAttribute.getUsername()),
@ -1168,7 +1171,7 @@ public class StunCandidateHarvest
if (!firstRequest && (longTermCredentialSession != null))
longTermCredentialSession.addAttributes(request);
StunStack stunStack = harvester.stunStack;
StunStack stunStack = harvester.getStunStack();
TransportAddress stunServer = harvester.stunServer;
TransportAddress hostCandidateTransportAddress
= hostCandidate.getTransportAddress();
@ -1180,7 +1183,9 @@ public class StunCandidateHarvest
transactionID
= (transactionIDAsBytes == null)
? TransactionID.createNewTransactionID()
: TransactionID.createTransactionID(transactionIDAsBytes);
: TransactionID.createTransactionID(
harvester.getStunStack(),
transactionIDAsBytes);
}
synchronized (requests)
{

View File

@ -21,7 +21,7 @@ import org.ice4j.stack.*;
* Traversal Utilities for NAT (STUN)" only.
*
* @author Emil Ivov
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class StunCandidateHarvester
implements CandidateHarvester
@ -61,9 +61,10 @@ public class StunCandidateHarvester
public final TransportAddress stunServer;
/**
* The stack to use for STUN communication.
* The <tt>StunSTack</tt> used by this instance for the purposes of STUN
* communication.
*/
public final StunStack stunStack = StunStack.getInstance();
private StunStack stunStack;
/**
* Creates a new STUN harvester that will be running against the specified
@ -186,6 +187,20 @@ public class StunCandidateHarvester
return shortTermCredentialUsername;
}
/**
* Gets the <tt>StunStack</tt> used by this <tt>CandidateHarvester</tt> for
* the purposes of STUN communication. It is guaranteed to be available only
* during the execution of {@link CandidateHarvester#harvest(Component)}.
*
* @return the <tt>StunStack</tt> used by this <tt>CandidateHarvester</tt>
* for the purposes of STUN communication
* @see CandidateHarvester#harvest(Component)
*/
public StunStack getStunStack()
{
return stunStack;
}
/**
* Gathers STUN candidates for all host <tt>Candidate</tt>s that are already
* present in the specified <tt>component</tt>. This method relies on the
@ -197,6 +212,8 @@ public class StunCandidateHarvester
*/
public void harvest(Component component)
{
stunStack = component.getParentStream().getParentAgent().getStunStack();
for (Candidate cand : component.getLocalCandidates())
if (cand instanceof HostCandidate)
startResolvingCandidate((HostCandidate) cand);

View File

@ -22,7 +22,7 @@ import org.ice4j.stack.*;
* <tt>HostCandidate</tt> performed by a specific
* <tt>TurnCandidateHarvester</tt>.
*
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class TurnCandidateHarvest
extends StunCandidateHarvest
@ -245,7 +245,7 @@ public class TurnCandidateHarvest
* (application-purposed) socket of the RelayedCandidate and
* will not add it to the StunStack so we have to do it.
*/
harvester.stunStack.addSocket(
harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null));
addCandidate(relayedCandidate);

View File

@ -22,16 +22,16 @@ import org.ice4j.stack.*;
*
* @author Emil Ivov
* @author Sebastien Vincent
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public abstract class Message
{
/**
* The <tt>Logger</tt> used by the <tt>Message</tt>
* class and its instances for logging output.
* The <tt>Logger</tt> used by the <tt>Message</tt> class and its instances
* for logging output.
*/
private static final Logger logger = Logger.getLogger(Message.class
.getName());
private static final Logger logger
= Logger.getLogger(Message.class.getName());
/* general declaration */
public static final char STUN_REQUEST = 0x0000;
@ -561,12 +561,14 @@ public abstract class Message
/**
* Returns a binary representation of this message.
*
* @param stunStack the <tt>StunStack</tt> in the context of which the
* request to encode this <tt>Message</tt> is being made
* @return a binary representation of this message.
*
* @throws IllegalStateException if the message does not have all
* required attributes.
*/
public byte[] encode()
public byte[] encode(StunStack stunStack)
throws IllegalStateException
{
prepareForEncoding();
@ -622,8 +624,8 @@ public abstract class Message
binMsg[messageLengthOffset + 1]
= (byte)(dataLengthForContentDependentAttribute & 0xFF);
binAtt
= ((ContentDependentAttribute)attribute).encode(
binMsg, 0, offset);
= ((ContentDependentAttribute)attribute)
.encode(stunStack, binMsg, 0, offset);
}
else
{
@ -695,8 +697,8 @@ public abstract class Message
* @param arrayLen the length of the message
* @return a Message object constructed from the binMessage array
*
* @throws StunException ILLEGAL_ARGUMENT if one or more of the arguments
* have invalid values.
* @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the
* arguments have invalid values.
*/
public static Message decode(byte binMessage[], char offset, char arrayLen)
throws StunException
@ -790,10 +792,9 @@ public abstract class Message
* @param offset the index where data starts in <tt>binMessage</tt>.
* @param msgLen the number of message bytes in <tt>binMessage</tt>.
*
* @throws StunException if there's something in the
* <tt>attribute</tt> that caused us to discard the whole message (e.g. an
* invalid checksum
* or username)
* @throws StunException if there's something in the <tt>attribute</tt> that
* caused us to discard the whole message (e.g. an invalid checksum or
* username)
*/
private static void performAttributeSpecificActions(Attribute attribute,
byte[] binMessage,

View File

@ -28,7 +28,7 @@ import org.ice4j.stack.*;
* Allocation on a TURN server and implements sends and receives through it
* using TURN messages to and from that TURN server.
*
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class RelayedCandidateDatagramSocket
extends DatagramSocket
@ -191,9 +191,13 @@ public class RelayedCandidateDatagramSocket
this.relayedCandidate = relayedCandidate;
this.turnCandidateHarvest = turnCandidateHarvest;
this.turnCandidateHarvest.harvester.stunStack.addIndicationListener(
this.turnCandidateHarvest.hostCandidate.getTransportAddress(),
this);
this.turnCandidateHarvest
.harvester
.getStunStack()
.addIndicationListener(
this.turnCandidateHarvest.hostCandidate
.getTransportAddress(),
this);
DatagramSocket hostSocket
= this.turnCandidateHarvest.hostCandidate.getSocket();
@ -330,7 +334,7 @@ public class RelayedCandidateDatagramSocket
{
packetsToSend.notifyAll();
}
turnCandidateHarvest.harvester.stunStack.removeIndicationListener(
turnCandidateHarvest.harvester.getStunStack().removeIndicationListener(
turnCandidateHarvest.hostCandidate.getTransportAddress(),
this);
turnCandidateHarvest.close(this);
@ -1449,7 +1453,7 @@ public class RelayedCandidateDatagramSocket
transactionID);
sendIndication.setTransactionID(transactionID);
turnCandidateHarvest.harvester.stunStack.sendIndication(
turnCandidateHarvest.harvester.getStunStack().sendIndication(
sendIndication,
turnCandidateHarvest.harvester.stunServer,
turnCandidateHarvest

View File

@ -26,20 +26,26 @@ class MessageProcessor
private static final Logger logger
= Logger.getLogger(MessageProcessor.class.getName());
/**
* The listener that will be collecting error notifications.
*/
private final ErrorHandler errorHandler;
/**
* The queue where we store incoming messages until they are collected.
*/
private MessageQueue messageQueue = null;
private final MessageQueue messageQueue;
/**
* The listener that will be retrieving <tt>MessageEvent</tt>s
*/
private MessageEventHandler messageHandler = null;
private final MessageEventHandler messageEventHandler;
/**
* The listener that will be collecting error notifications.
* The <tt>NetAccessManager</tt> which has created this instance and which
* is its owner.
*/
private ErrorHandler errorHandler = null;
private final NetAccessManager netAccessManager;
/**
* The flag that indicates whether we are still running.
@ -54,34 +60,41 @@ class MessageProcessor
/**
* Creates a Message processor.
*
* @param queue the <tt>MessageQueue</tt> where we'll be storing incoming
* messages.
* @param messageHandler MessageEventHandler
* @param errorHandler the <tt>ErrorHandler</tt> that should handle
* exceptions in this processor
*
* @throws IllegalArgumentException if either of the parameters is null.
* @param netAccessManager the <tt>NetAccessManager</tt> which is creating
* the new instance, is going to be its owner, specifies the
* <tt>MessageQueue</tt> which is to store incoming messages, specifies the
* <tt>MessageEventHandler</tt> and represents the <tt>ErrorHandler</tt> to
* handle exceptions in the new instance
* @throws IllegalArgumentException if any of the mentioned properties of
* <tt>netAccessManager</tt> are <tt>null</tt>
*/
MessageProcessor(MessageQueue queue,
MessageEventHandler messageHandler,
ErrorHandler errorHandler)
MessageProcessor(NetAccessManager netAccessManager)
throws IllegalArgumentException
{
if(queue == null)
throw new IllegalArgumentException(
"The message queue may not be " + null);
if (netAccessManager == null)
throw new NullPointerException("netAccessManager");
if(messageHandler == null)
MessageQueue messageQueue = netAccessManager.getMessageQueue();
if (messageQueue == null)
{
throw new IllegalArgumentException(
"The message handler may not be " + null);
"The message queue may not be null");
}
if(errorHandler == null)
MessageEventHandler messageEventHandler
= netAccessManager.getMessageEventHandler();
if(messageEventHandler == null)
{
throw new IllegalArgumentException(
"The error handler may not be " + null);
"The message event handler may not be null");
}
this.messageQueue = queue;
this.messageHandler = messageHandler;
this.errorHandler = errorHandler;
this.netAccessManager = netAccessManager;
this.messageQueue = messageQueue;
this.messageEventHandler = messageEventHandler;
this.errorHandler = netAccessManager;
}
/**
@ -93,9 +106,12 @@ class MessageProcessor
//avoid having dead threads in our pools.
try
{
StunStack stunStack = netAccessManager.getStunStack();
while (running)
{
RawMessage rawMessage;
try
{
rawMessage = messageQueue.remove();
@ -127,18 +143,19 @@ class MessageProcessor
}
catch (StunException ex)
{
errorHandler.handleError("Failed to decode a stun message!",
ex);
errorHandler.handleError(
"Failed to decode a stun message!",
ex);
continue; //let this one go and for better luck next time.
}
logger.finest("Dispatching a StunMessageEvent.");
StunMessageEvent stunMessageEvent =
new StunMessageEvent(rawMessage, stunMessage);
StunMessageEvent stunMessageEvent
= new StunMessageEvent(stunStack, rawMessage, stunMessage);
messageHandler.handleMessageEvent(stunMessageEvent);
messageEventHandler.handleMessageEvent(stunMessageEvent);
}
}
catch(Throwable err)

View File

@ -29,8 +29,8 @@ class NetAccessManager
/**
* Our class logger
*/
private static final Logger logger =
Logger.getLogger(NetAccessManager.class.getName());
private static final Logger logger
= Logger.getLogger(NetAccessManager.class.getName());
/**
* All access points currently in use. The table maps
@ -54,32 +54,70 @@ class NetAccessManager
* The instance that should be notified when an incoming message has been
* processed and ready for delivery
*/
private MessageEventHandler messageEventHandler = null;
private final MessageEventHandler messageEventHandler;
/**
* The size of the thread pool to start with.
*/
private int initialThreadPoolSize = StunStack.DEFAULT_THREAD_POOL_SIZE;
/**
* The <tt>StunStack</tt> which has created this instance, is its owner and
* is the handler that incoming message requests should be passed to.
*/
private final StunStack stunStack;
/**
* Constructs a NetAccessManager.
*
* @param evtHandler the handler that incoming message requests should be
* passed to.
* @param stunStack the <tt>StunStack</tt> which is creating the new
* instance, is going to be its owner and is the handler that incoming
* message requests should be passed to
*/
NetAccessManager(MessageEventHandler evtHandler)
NetAccessManager(StunStack stunStack)
{
setEventHandler(evtHandler);
this.stunStack = stunStack;
this.messageEventHandler = stunStack;
initThreadPool();
}
/**
* Sets the instance to notify for incoming message events.
* @param evtHandler the entity that will handle incoming messages.
* Gets the <tt>MessageEventHandler</tt> of this <tt>NetAccessManager</tt>
* which is to be notified when incoming messages have been processed and
* are ready for delivery.
*
* @return the <tt>MessageEventHandler</tt> of this
* <tt>NetAccessManager</tt> which is to be notified when incoming messages
* have been processed and are ready for delivery
*/
void setEventHandler(MessageEventHandler evtHandler)
MessageEventHandler getMessageEventHandler()
{
messageEventHandler = evtHandler;
return messageEventHandler;
}
/**
* Gets the <tt>MessageQueue</tt> of this <tt>NetAccessManager</tt> in which
* incoming messages are stocked for processing.
*
* @return the <tt>MessageQueue</tt> of this <tt>NetAccessManager</tt> in
* which incoming messages are stocked for processing
*/
MessageQueue getMessageQueue()
{
return messageQueue;
}
/**
* Gets the <tt>StunStack</tt> which has created this instance and is its
* owner.
*
* @return the <tt>StunStack</tt> which has created this instance and is its
* owner
*/
StunStack getStunStack()
{
return stunStack;
}
/**
@ -127,7 +165,7 @@ class NetAccessManager
mp.stop();
messageProcessors.remove(mp);
mp = new MessageProcessor(messageQueue, messageEventHandler, this);
mp = new MessageProcessor(this);
mp.start();
logger.fine("A message processor has been relaunched because "
+"of an error.");
@ -227,11 +265,9 @@ class NetAccessManager
for (int i = messageProcessors.size(); i < newSize; i++)
{
MessageProcessor mp = new MessageProcessor(messageQueue,
messageEventHandler,
this);
messageProcessors.add(mp);
MessageProcessor mp = new MessageProcessor(this);
messageProcessors.add(mp);
mp.start();
}
}
@ -263,12 +299,13 @@ class NetAccessManager
* @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed,
*/
void sendMessage(Message stunMessage,
TransportAddress srcAddr,
TransportAddress remoteAddr)
void sendMessage(
Message stunMessage,
TransportAddress srcAddr,
TransportAddress remoteAddr)
throws IOException, IllegalArgumentException
{
byte[] bytes = stunMessage.encode();
byte[] bytes = stunMessage.encode(stunStack);
Connector ap = netAccessPoints.get(srcAddr);
if (ap == null)

View File

@ -254,6 +254,7 @@ class StunClientTransaction
stackCallback.removeClientTransaction(this);
responseCollector.processTimeout(
new StunTimeoutEvent(
stackCallback,
this.request, getLocalAddress(), transactionID));
}
}
@ -294,7 +295,9 @@ class StunClientTransaction
}
stackCallback.getNetAccessManager().sendMessage(
this.request, localAddress, requestDestination);
this.request,
localAddress,
requestDestination);
}
/**
@ -359,9 +362,12 @@ class StunClientTransaction
if( !Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE) )
this.cancel();
this.responseCollector.processResponse(new StunResponseEvent(
evt.getRawMessage(), (Response)evt.getMessage(),
this.request, getTransactionID()));
this.responseCollector.processResponse(
new StunResponseEvent(
stackCallback,
evt.getRawMessage(),
(Response) evt.getMessage(),
this.request, getTransactionID()));
}
/**

View File

@ -204,9 +204,10 @@ class StunServerTransaction
if(expired || !isRetransmitting)
return;
stackCallback.getNetAccessManager().sendMessage(response,
localSendingAddress,
responseDestination);
stackCallback.getNetAccessManager().sendMessage(
response,
localSendingAddress,
responseDestination);
}
/**

View File

@ -24,26 +24,38 @@ import org.ice4j.security.*;
* configure the stack.
*
* @author Emil Ivov
* @author Lubomir Marinov
* @author Lyubomir Marinov
*/
public class StunStack
implements MessageEventHandler
{
/**
* We shouldn't need more than one stack in the same application.
*/
private static StunStack stackInstance = null;
/**
* Our network gateway.
*/
private NetAccessManager netAccessManager = null;
/**
* The number of threads to split our flow in.
*/
public static final int DEFAULT_THREAD_POOL_SIZE = 3;
/**
* The <tt>Logger</tt> used by the <tt>StunStack</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(StunStack.class.getName());
/**
* The indicator which determines whether
* <code>Mac.getInstance(MessageIntegrityAttribute.HMAC_SHA1_ALGORITHM)</code>
* has been called.
*
* @see #StunStack()
*/
private static Mac mac;
/**
* Our network gateway.
*/
private NetAccessManager netAccessManager = null;
/**
* The {@link CredentialsManager} that we are using for retrieving
* passwords.
@ -51,12 +63,6 @@ public class StunStack
private final CredentialsManager credentialsManager
= new CredentialsManager();
/**
* Our class logger.
*/
private static final Logger logger =
Logger.getLogger(StunStack.class.getName());
/**
* Stores active client transactions mapped against TransactionID-s.
*/
@ -77,34 +83,6 @@ public class StunStack
*/
private final EventDispatcher eventDispatcher = new EventDispatcher();
/**
* Returns a reference to the singleton StunStack instance. If the stack
* had not yet been initialized, a new instance will be created.
*
* @return a reference to the StunStack.
*/
public static synchronized StunStack getInstance()
{
if (stackInstance == null)
{
//the Mac instantiation used in MessageIntegrityAttribute could
//take several hundred milliseconds so we don't want it instantiated
//only after we get a response because the delay may cause the
//transaction to fail.
try
{
Mac.getInstance(MessageIntegrityAttribute.HMAC_SHA1_ALGORITHM);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
stackInstance = new StunStack();
}
return stackInstance;
}
/**
* Sets the number of Message processors running in the same time.
*
@ -265,10 +243,32 @@ public class StunStack
}
/**
* Private constructor as we want a singleton pattern.
* Initializes a new <tt>StunStack</tt> instance.
*/
private StunStack()
public StunStack()
{
/*
* The Mac instantiation used in MessageIntegrityAttribute could take
* several hundred milliseconds so we don't want it instantiated only
* after we get a response because the delay may cause the transaction
* to fail.
*/
synchronized (StunStack.class)
{
if (mac == null)
{
try
{
mac
= Mac.getInstance(
MessageIntegrityAttribute.HMAC_SHA1_ALGORITHM);
}
catch (NoSuchAlgorithmException nsaex)
{
nsaex.printStackTrace();
}
}
}
netAccessManager = new NetAccessManager(this);
}
@ -453,9 +453,9 @@ public class StunStack
IOException,
IllegalArgumentException
{
TransactionID tid = TransactionID.createTransactionID(transactionID);
StunServerTransaction sTran =
serverTransactions.get(tid);
TransactionID tid
= TransactionID.createTransactionID(this, transactionID);
StunServerTransaction sTran = serverTransactions.get(tid);
if(sTran == null)
{
@ -1012,7 +1012,7 @@ public class StunStack
* @return <tt>true</tt> if <tt>username</tt> contains a valid username;
* <tt>false</tt>, otherwise
*/
private static boolean validateUsername(String username)
private boolean validateUsername(String username)
{
int colon = username.indexOf(":");
@ -1028,7 +1028,6 @@ public class StunStack
String lfrag = username.substring(0, colon);
return StunStack.getInstance()
.getCredentialsManager().checkLocalUserName(lfrag);
return getCredentialsManager().checkLocalUserName(lfrag);
}
}

View File

@ -84,24 +84,28 @@ public class TransactionID
* to that transaction's instance so that we could use it to for storing
* application data.
*
* @param stunStack the <tt>StunStack</tt> in the context of which the
* request to create a <tt>TransactionID</tt> is being made
* @param transactionID the value of the ID.
*
* @return a reference to the (possibly already existing)
* <tt>TransactionID</tt> corresponding to the value of
* <tt>transactionID</tt>
*/
public static TransactionID createTransactionID(byte[] transactionID)
public static TransactionID createTransactionID(
StunStack stunStack,
byte[] transactionID)
{
//first check whether we can find a client or a server tran with the
//specified id.
StunClientTransaction cliTran = StunStack.getInstance()
.getClientTransaction(transactionID);
StunClientTransaction cliTran
= stunStack.getClientTransaction(transactionID);
if(cliTran != null)
return cliTran.getTransactionID();
StunServerTransaction serTran = StunStack.getInstance()
.getServerTransaction(transactionID);
StunServerTransaction serTran
= stunStack.getServerTransaction(transactionID);
if(serTran != null)
return serTran.getTransactionID();

View File

@ -80,7 +80,6 @@ import org.ice4j.stack.*;
*
* @author Emil Ivov
*/
public class NetworkConfigurationDiscoveryProcess
{
/**
@ -94,11 +93,6 @@ public class NetworkConfigurationDiscoveryProcess
*/
private boolean started = false;
/**
* The stack to use for STUN communication.
*/
private StunStack stunStack = null;
/**
* The point where we'll be listening.
*/
@ -122,18 +116,29 @@ public class NetworkConfigurationDiscoveryProcess
private DatagramSocket sock = null;
/**
* Creates a StunAddressDiscoverer. In order to use it one must start the
* discoverer.
* The <tt>StunStack</tt> used by this instance for the purposes of STUN
* communication.
*/
private final StunStack stunStack;
/**
* Initializes a <tt>StunAddressDiscoverer</tt> with a specific
* <tt>StunStack</tt>. In order to use it one must first start it.
*
* @param stunStack the <tt>StunStack</tt> to be used by the new instance
* @param localAddress the address where the stack should bind.
* @param serverAddress the address of the server to interrogate.
*/
public NetworkConfigurationDiscoveryProcess(TransportAddress localAddress,
TransportAddress serverAddress)
public NetworkConfigurationDiscoveryProcess(
StunStack stunStack,
TransportAddress localAddress, TransportAddress serverAddress)
{
if (stunStack == null)
throw new NullPointerException("stunStack");
this.stunStack = stunStack;
this.localAddress = localAddress;
this.serverAddress = serverAddress;
}
/**
@ -146,12 +151,10 @@ public class NetworkConfigurationDiscoveryProcess
sock.close();
sock = null;
stunStack = null;
localAddress = null;
requestSender = null;
this.started = false;
}
/**
@ -162,8 +165,6 @@ public class NetworkConfigurationDiscoveryProcess
public void start()
throws IOException, StunException
{
stunStack = StunStack.getInstance();
sock = new SafeCloseDatagramSocket(localAddress);
stunStack.addSocket(sock);

View File

@ -83,7 +83,7 @@ public class SimpleAddressDetector
*/
public void start()
{
stunStack = StunStack.getInstance();
stunStack = new StunStack();
}

View File

@ -89,7 +89,7 @@ public class MessageEventDispatchingTest extends TestCase
{
super.setUp();
stunStack = StunStack.getInstance();
stunStack = new StunStack();
clientSock = new SafeCloseDatagramSocket(clientAddress);
serverSock = new SafeCloseDatagramSocket(serverAddress);

View File

@ -46,6 +46,11 @@ public class TransactionSupportTests extends TestCase
*/
DatagramSocket serverSock = null;
/**
* The <tt>StunStack</tt> used by this <tt>TransactionSupportTests</tt>.
*/
private StunStack stunStack;
/**
* The request we send in this test.
*/
@ -79,8 +84,9 @@ public class TransactionSupportTests extends TestCase
clientSock = new SafeCloseDatagramSocket(clientAddress);
serverSock = new SafeCloseDatagramSocket(serverAddress);
StunStack.getInstance().addSocket(clientSock);
StunStack.getInstance().addSocket(serverSock);
stunStack = new StunStack();
stunStack.addSocket(clientSock);
stunStack.addSocket(serverSock);
bindingRequest = MessageFactory.createBindingRequest();
bindingResponse = MessageFactory.create3482BindingResponse(
@ -89,16 +95,21 @@ public class TransactionSupportTests extends TestCase
requestCollector = new PlainRequestCollector();
responseCollector = new PlainResponseCollector();
System.setProperty(StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"false");
System.setProperty(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"false");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"");
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER,
"");
System.setProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER,
"");
System.setProperty(
StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"false");
System.setProperty(
StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"false");
System.setProperty(
StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"");
System.setProperty(
StackProperties.MAX_CTRAN_RETRANS_TIMER,
"");
System.setProperty(
StackProperties.FIRST_CTRAN_RETRANS_AFTER,
"");
}
/**
@ -109,8 +120,8 @@ public class TransactionSupportTests extends TestCase
protected void tearDown()
throws Exception
{
StunStack.getInstance().removeSocket(clientAddress);
StunStack.getInstance().removeSocket(serverAddress);
stunStack.removeSocket(clientAddress);
stunStack.removeSocket(serverAddress);
clientSock.close();
serverSock.close();
@ -118,16 +129,21 @@ public class TransactionSupportTests extends TestCase
requestCollector = null;
responseCollector = null;
System.setProperty(StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"false");
System.setProperty(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"false");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"");
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER,
"");
System.setProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER,
"");
System.setProperty(
StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"false");
System.setProperty(
StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"false");
System.setProperty(
StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"");
System.setProperty(
StackProperties.MAX_CTRAN_RETRANS_TIMER,
"");
System.setProperty(
StackProperties.FIRST_CTRAN_RETRANS_AFTER,
"");
super.tearDown();
}
@ -151,11 +167,13 @@ public class TransactionSupportTests extends TestCase
System.setProperty(StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"true");
StunStack.getInstance()
.addRequestListener(serverAddress, requestCollector);
stunStack.addRequestListener(serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for retransmissions
Thread.sleep(1000);
@ -198,11 +216,13 @@ public class TransactionSupportTests extends TestCase
StackProperties.MAX_CTRAN_RETRANSMISSIONS);
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
//prepare to listen
StunStack.getInstance().addRequestListener(
serverAddress, requestCollector);
stunStack.addRequestListener(serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for retransmissions
Thread.sleep(1000);
@ -240,14 +260,16 @@ public class TransactionSupportTests extends TestCase
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "100");
//prepare to listen
System.setProperty(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"true");
StunStack.getInstance().addRequestListener(
serverAddress, requestCollector);
System.setProperty(
StackProperties.KEEP_CRANS_AFTER_A_RESPONSE,
"true");
stunStack.addRequestListener(serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(
bindingRequest, serverAddress,
clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for the message to arrive
requestCollector.waitForRequest();
@ -258,8 +280,12 @@ public class TransactionSupportTests extends TestCase
StunMessageEvent evt = reqs.get(0);
byte[] tid = evt.getMessage().getTransactionID();
StunStack.getInstance().sendResponse(
tid, bindingResponse, serverAddress, clientAddress);
stunStack.sendResponse(
tid,
bindingResponse,
serverAddress,
clientAddress);
//wait for retransmissions
Thread.sleep(500);
@ -287,11 +313,13 @@ public class TransactionSupportTests extends TestCase
*/
public void testUniqueIDs() throws Exception
{
StunStack.getInstance().addRequestListener(
serverAddress, requestCollector);
stunStack.addRequestListener(serverAddress, requestCollector);
//send req 1
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for retransmissions
requestCollector.waitForRequest();
@ -303,12 +331,19 @@ public class TransactionSupportTests extends TestCase
//send a response to make the other guy shut up
byte[] tid = evt1.getMessage().getTransactionID();
StunStack.getInstance().sendResponse(tid,
bindingResponse, serverAddress, clientAddress);
stunStack.sendResponse(
tid,
bindingResponse,
serverAddress,
clientAddress);
//send req 2
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for retransmissions
Thread.sleep(1000);
@ -336,16 +371,19 @@ public class TransactionSupportTests extends TestCase
{
//MAX_RETRANSMISSIONS
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"2");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
//make sure we see retransmissions so that we may count them
System.setProperty(StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"true");
StunStack.getInstance().addRequestListener(
System.setProperty(
StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"true");
stunStack.addRequestListener(
serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(
bindingRequest, serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait for retransmissions
Thread.sleep(1600);
@ -373,16 +411,18 @@ public class TransactionSupportTests extends TestCase
throws Exception
{
//MAX_RETRANSMISSIONS
System.setProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER,
"50");
System.setProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER, "50");
//make sure we see retransmissions so that we may count them
System.setProperty(StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"true");
StunStack.getInstance().addRequestListener(
serverAddress, requestCollector);
System.setProperty(
StackProperties.PROPAGATE_RECEIVED_RETRANSMISSIONS,
"true");
stunStack.addRequestListener(serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait a while
requestCollector.waitForRequest();
@ -421,11 +461,13 @@ public class TransactionSupportTests extends TestCase
"true");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS,
"11");
StunStack.getInstance()
.addRequestListener(serverAddress, requestCollector);
stunStack.addRequestListener(serverAddress, requestCollector);
//send
StunStack.getInstance().sendRequest(bindingRequest,
serverAddress, clientAddress, responseCollector);
stunStack.sendRequest(
bindingRequest,
serverAddress,
clientAddress,
responseCollector);
//wait a while
Thread.sleep(1200);

View File

@ -12,6 +12,7 @@ import junit.framework.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.stack.*;
public class MessageTest extends TestCase {
private Message bindingRequest = null;
@ -25,11 +26,18 @@ public class MessageTest extends TestCase {
private MsgFixture msgFixture;
/**
* The <tt>StunStack</tt> used by this <tt>MessageTest</tt>.
*/
private StunStack stunStack;
protected void setUp() throws Exception {
super.setUp();
msgFixture = new MsgFixture();
msgFixture.setUp();
stunStack = new StunStack();
//binding request
bindingRequest = new Request();
@ -78,9 +86,11 @@ public class MessageTest extends TestCase {
changeRequest = null;
changeRequest = null;
msgFixture.tearDown();
stunStack = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
@ -130,14 +140,14 @@ public class MessageTest extends TestCase {
//Binding Request
byte[] expectedReturn = msgFixture.bindingRequest;
byte[] actualReturn = bindingRequest.encode();
byte[] actualReturn = bindingRequest.encode(stunStack);
assertTrue("A binding request was not properly encoded",
Arrays.equals( expectedReturn, actualReturn ) );
//Binding Response
expectedReturn = msgFixture.bindingResponse;
actualReturn = bindingResponse.encode();
actualReturn = bindingResponse.encode(stunStack);
assertTrue("A binding response was not properly encoded",
Arrays.equals( expectedReturn, actualReturn ) );

View File

@ -21,12 +21,19 @@ import org.ice4j.socket.*;
*
* @author Emil Ivov
*/
public class ShallowStackTest extends TestCase {
public class ShallowStackTest extends TestCase
{
/**
* The <tt>Logger</tt> used by the <tt>ShallowStackTest<tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(ShallowStackTest.class.getName());
private static final Logger logger =
Logger.getLogger(ShallowStackTest.class.getName());
private StunStack stunStack = null;
/**
* The <tt>StunStack</tt> used by this <tt>ShallowStackTest</tt>
*/
private StunStack stunStack;
private MsgFixture msgFixture = null;
private TransportAddress dummyServerAddress = null;
@ -57,6 +64,7 @@ public class ShallowStackTest extends TestCase {
throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
msgFixture.setUp();
//Addresses
@ -66,7 +74,7 @@ public class ShallowStackTest extends TestCase {
"127.0.0.1", 5004, Transport.UDP);
//init the stack
stunStack = StunStack.getInstance();
stunStack = new StunStack();
//access point
localSock = new SafeCloseDatagramSocket(localAddress);
@ -177,7 +185,7 @@ public class ShallowStackTest extends TestCase {
assertNotNull("No request has been received", collectedRequest);
byte expectedReturn[] = msgFixture.bindingRequest2;
byte actualReturn[] = collectedRequest.encode();
byte actualReturn[] = collectedRequest.encode(stunStack);
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
}
@ -208,7 +216,7 @@ public class ShallowStackTest extends TestCase {
Request collectedRequest = requestCollector.collectedRequest;
byte expectedReturn[] = msgFixture.bindingRequest;
byte actualReturn[] = collectedRequest.encode();
byte actualReturn[] = collectedRequest.encode(stunStack);
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
@ -291,7 +299,7 @@ public class ShallowStackTest extends TestCase {
Response collectedResponse = collector.collectedResponse;
byte expectedReturn[] = response;
byte actualReturn[] = collectedResponse.encode();
byte actualReturn[] = collectedResponse.encode(stunStack);
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
}

View File

@ -21,26 +21,46 @@ import org.ice4j.stack.*;
* sequences of responses. It may be used to test whether a STUN client
* behaves correctly in different use cases.
*
*
* @author Emil Ivov
*/
public class ResponseSequenceServer
implements RequestListener
{
private static final Logger logger =
Logger.getLogger(ResponseSequenceServer.class.getName());
/**
* The <tt>Logger</tt> used by the <tt>ResponseSequenceServer</tt> class and
* its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(ResponseSequenceServer.class.getName());
/**
* The sequence of responses to send.
*/
private Vector<Object> messageSequence = new Vector<Object>();
private StunStack stunStack = null;
/**
* The <tt>StunStack</tt> used by this instance for the purposes of STUN
* communication.
*/
private final StunStack stunStack;
private TransportAddress serverAddress = null;
private DatagramSocket localSocket = null;
public ResponseSequenceServer(TransportAddress bindAddress)
/**
* Initializes a new <tt>ResponseSequenceServer</tt> instance with a
* specific <tt>StunStack</tt> to be used for the purposes of STUN
* communication.
*
* @param stunStack the <tt>StunStack</tt> to be used by the new instance
* for the purposes of STUN communication
* @param bindAddress
*/
public ResponseSequenceServer(
StunStack stunStack,
TransportAddress bindAddress)
{
this.stunStack = stunStack;
this.serverAddress = bindAddress;
}
@ -52,8 +72,6 @@ public class ResponseSequenceServer
public void start()
throws IOException, StunException
{
stunStack = StunStack.getInstance();
localSocket = new SafeCloseDatagramSocket(serverAddress);
stunStack.addSocket(localSocket);
@ -69,8 +87,6 @@ public class ResponseSequenceServer
stunStack.removeSocket(serverAddress);
messageSequence.removeAllElements();
localSocket.close();
stunStack = null;
}
/**

View File

@ -10,12 +10,13 @@ import junit.framework.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun
* operation for scenarios of some basic types of firewalls. The purpose of
* these tests is to make sure that transaction retransmissions and rereceptions
* are handled transparently by the stack, as well as verify overal protocol
* are handled transparently by the stack, as well as verify overall protocol
* operations for IPv4/IPv6 and mixed environments.
*
* <p>Company: Net Research Team, Louis Pasteur University</p>
@ -51,10 +52,14 @@ public class StunAddressDiscovererTest
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "100");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
responseServer = new ResponseSequenceServer(responseServerAddress);
StunStack stunStack = new StunStack();
responseServer
= new ResponseSequenceServer(stunStack, responseServerAddress);
stunAddressDiscoverer
= new NetworkConfigurationDiscoveryProcess(discovererAddress,
responseServerAddress);
= new NetworkConfigurationDiscoveryProcess(
stunStack,
discovererAddress, responseServerAddress);
stunAddressDiscoverer.start();
responseServer.start();
@ -72,7 +77,7 @@ public class StunAddressDiscovererTest
}
/**
* Performs a test where no responces are given the stun client so that
* Performs a test where no responses are given the stun client so that
* it concludes it's in a network where UDP is blocked.
*
* @throws Exception if anything goes wrong ( surprised? ).

View File

@ -10,6 +10,7 @@ import junit.framework.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* Makes basic stun tests for cases where local network addresses and the public
@ -20,7 +21,7 @@ import org.ice4j.message.*;
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun
* operation for scenarios of some basic types of firewalls. The purpose of
* these tests is to make sure that transaction retransmissions and rereceptions
* are handled transparently by the stack, as well as verify overal protocol
* are handled transparently by the stack, as well as verify overall protocol
* operations for IPv4/IPv6 and mixed environments.
*
* <p>Company: Net Research Team, Louis Pasteur University</p>
@ -66,14 +67,22 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase {
throws Exception
{
super.setUp();
StunStack stunStack = new StunStack();
responseServer_v6
= new ResponseSequenceServer(responseServerAddress_v6);
= new ResponseSequenceServer(stunStack, responseServerAddress_v6);
responseServer_v4
= new ResponseSequenceServer(responseServerAddress_v4);
stunAddressDiscoverer_v6 = new NetworkConfigurationDiscoveryProcess(
discovererAddress_v6, responseServerAddress_v6);
stunAddressDiscoverer_v4 = new NetworkConfigurationDiscoveryProcess(
discovererAddress_v4, responseServerAddress_v4);
= new ResponseSequenceServer(stunStack, responseServerAddress_v4);
stunAddressDiscoverer_v6
= new NetworkConfigurationDiscoveryProcess(
stunStack,
discovererAddress_v6, responseServerAddress_v6);
stunAddressDiscoverer_v4
= new NetworkConfigurationDiscoveryProcess(
stunStack,
discovererAddress_v4, responseServerAddress_v4);
stunAddressDiscoverer_v6.start();
stunAddressDiscoverer_v4.start();

View File

@ -10,6 +10,7 @@ import junit.framework.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun
@ -44,11 +45,15 @@ public class StunAddressDiscovererTest_v6 extends TestCase {
protected void setUp() throws Exception
{
super.setUp();
responseServer = new ResponseSequenceServer(responseServerAddress);
StunStack stunStack = new StunStack();
responseServer
= new ResponseSequenceServer(stunStack, responseServerAddress);
stunAddressDiscoverer
= new NetworkConfigurationDiscoveryProcess(
discovererAddress,
responseServerAddress);
stunStack,
discovererAddress, responseServerAddress);
stunAddressDiscoverer.start();
responseServer.start();