diff --git a/src/org/ice4j/BaseStunMessageEvent.java b/src/org/ice4j/BaseStunMessageEvent.java index 91136fb..b66aca0 100644 --- a/src/org/ice4j/BaseStunMessageEvent.java +++ b/src/org/ice4j/BaseStunMessageEvent.java @@ -15,7 +15,7 @@ import org.ice4j.stack.*; * Represents an EventObject which notifies of an event associated with * a specific STUN Message. * - * @author Lubomir Marinov + * @author Lyubomir Marinov */ public class BaseStunMessageEvent extends EventObject @@ -30,6 +30,11 @@ public class BaseStunMessageEvent */ private final Message message; + /** + * The StunStack 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 BaseStunMessageEvent associated with a * specific STUN Message. * + * @param stunStack the StunStack to be associated with the new + * instance * @param sourceAddress the TransportAddress which is to be * reported as the source of the new event * @param message the STUN Message 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 StunStack associated with this instance. + * + * @return the StunStack associated with this instance + */ + public StunStack getStunStack() + { + return stunStack; + } + /** * Gets the ID of the transaction related to the STUN Message * 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; } diff --git a/src/org/ice4j/StunFailureEvent.java b/src/org/ice4j/StunFailureEvent.java index fd9bc30..0dd67e6 100644 --- a/src/org/ice4j/StunFailureEvent.java +++ b/src/org/ice4j/StunFailureEvent.java @@ -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 StunFailureEvent according to the specified * message. - * + * + * @param stunStack the StunStack 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 Exception that caused this failure or * null if there's no Exception 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; } diff --git a/src/org/ice4j/StunMessageEvent.java b/src/org/ice4j/StunMessageEvent.java index aa060af..5a24420 100644 --- a/src/org/ice4j/StunMessageEvent.java +++ b/src/org/ice4j/StunMessageEvent.java @@ -34,13 +34,18 @@ public class StunMessageEvent /** * Constructs a StunMessageEvent according to the specified message. * + * @param stunStack the StunStack 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; } diff --git a/src/org/ice4j/StunResponseEvent.java b/src/org/ice4j/StunResponseEvent.java index 101ee3e..8c86c59 100644 --- a/src/org/ice4j/StunResponseEvent.java +++ b/src/org/ice4j/StunResponseEvent.java @@ -34,18 +34,22 @@ public class StunResponseEvent /** * Creates a new instance of this event. * + * @param stunStack the StunStack 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); } diff --git a/src/org/ice4j/StunTimeoutEvent.java b/src/org/ice4j/StunTimeoutEvent.java index 794d6eb..0dfc895 100644 --- a/src/org/ice4j/StunTimeoutEvent.java +++ b/src/org/ice4j/StunTimeoutEvent.java @@ -27,16 +27,21 @@ public class StunTimeoutEvent * Constructs a StunTimeoutEvent according to the specified * message. * + * @param stunStack the StunStack 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); } /** diff --git a/src/org/ice4j/attribute/ContentDependentAttribute.java b/src/org/ice4j/attribute/ContentDependentAttribute.java index ed739e8..f63282b 100644 --- a/src/org/ice4j/attribute/ContentDependentAttribute.java +++ b/src/org/ice4j/attribute/ContentDependentAttribute.java @@ -6,6 +6,8 @@ */ package org.ice4j.attribute; +import org.ice4j.stack.*; + /** * ContentDependentAttributes have a value that depend on the content * of the message. The {@link MessageIntegrityAttribute} and {@link @@ -13,6 +15,7 @@ package org.ice4j.attribute; *

* Rather than encoding them via the standard {@link Attribute#encode()} method, * the stack would use the one from this interface. + *

* * @author Emil Ivov */ @@ -21,6 +24,8 @@ public interface ContentDependentAttribute /** * Returns a binary representation of this attribute. * + * @param stunStack the StunStack in the context of which the + * request to encode this ContentDependentAttribute is being made * @param content the content of the message that this attribute will be * transported in * @param offset the content-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 content. */ - public byte[] encode(byte[] content, int offset, int length); + public byte[] encode( + StunStack stunStack, + byte[] content, int offset, int length); } diff --git a/src/org/ice4j/attribute/FingerprintAttribute.java b/src/org/ice4j/attribute/FingerprintAttribute.java index 4d4bbca..14f5e6e 100644 --- a/src/org/ice4j/attribute/FingerprintAttribute.java +++ b/src/org/ice4j/attribute/FingerprintAttribute.java @@ -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 StunStack in the context of which the + * request to encode this ContentDependentAttribute is being made * @param content the content of the message that this attribute will be * transported in * @param offset the content-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 content. */ - 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()]; diff --git a/src/org/ice4j/attribute/MessageIntegrityAttribute.java b/src/org/ice4j/attribute/MessageIntegrityAttribute.java index 3a2743b..dcdfa89 100644 --- a/src/org/ice4j/attribute/MessageIntegrityAttribute.java +++ b/src/org/ice4j/attribute/MessageIntegrityAttribute.java @@ -228,6 +228,8 @@ public class MessageIntegrityAttribute /** * Returns a binary representation of this attribute. * + * @param stunStack the StunStack in the context of which the + * request to encode this ContentDependentAttribute is being made * @param content the content of the message that this attribute will be * transported in * @param offset the content-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 content. */ - 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); diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java index c6b88ba..2bd821b 100644 --- a/src/org/ice4j/ice/Agent.java +++ b/src/org/ice4j/ice/Agent.java @@ -30,6 +30,7 @@ import org.ice4j.stack.*; *

* * @author Emil Ivov + * @author Lyubomir Marinov */ public class Agent { @@ -189,13 +190,18 @@ public class Agent private final List stateListeners = new LinkedList(); + /** + * The StunStack used by this Agent. + */ + private StunStack stunStack; + /** * The thread that we use for moving from COMPLETED into a TERMINATED state. */ private TerminationThread terminationThread; /** - * Creates an empty Agent with no streams, and no address + * Initializes an empty Agent 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 StunStack used by this Agent. + * + * @return the StunStack used by this Agent + */ + 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 diff --git a/src/org/ice4j/ice/Candidate.java b/src/org/ice4j/ice/Candidate.java index b62e279..1cd14df 100644 --- a/src/org/ice4j/ice/Candidate.java +++ b/src/org/ice4j/ice/Candidate.java @@ -24,7 +24,7 @@ import org.ice4j.*; *

* * @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 diff --git a/src/org/ice4j/ice/ConnectivityCheckClient.java b/src/org/ice4j/ice/ConnectivityCheckClient.java index d9e422e..3419baa 100644 --- a/src/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/org/ice4j/ice/ConnectivityCheckClient.java @@ -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 StunStack 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(), diff --git a/src/org/ice4j/ice/ConnectivityCheckServer.java b/src/org/ice4j/ice/ConnectivityCheckServer.java index beca343..7024f7c 100644 --- a/src/org/ice4j/ice/ConnectivityCheckServer.java +++ b/src/org/ice4j/ice/ConnectivityCheckServer.java @@ -37,9 +37,9 @@ class ConnectivityCheckServer private final Agent parentAgent; /** - * The stun stack that we will use for connectivity checks. + * The StunStack that we will use for connectivity checks. */ - private StunStack stunStack = StunStack.getInstance(); + private final StunStack stunStack; /** * Creates a new ConnectivityCheckServer 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); } } diff --git a/src/org/ice4j/ice/LocalCandidate.java b/src/org/ice4j/ice/LocalCandidate.java index 511a548..e0ec25d 100644 --- a/src/org/ice4j/ice/LocalCandidate.java +++ b/src/org/ice4j/ice/LocalCandidate.java @@ -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 StunStack associated with this Candidate. + * + * @return the StunStack associated with this Candidate + */ + public StunStack getStunStack() + { + return + getParentComponent() + .getParentStream() + .getParentAgent() + .getStunStack(); + } + /** * Creates a new StunDatagramPacketFilter which is to capture STUN * messages and make them available to the DatagramSocket 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 diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index 77dd908..2b7c115 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -15,7 +15,6 @@ import java.util.logging.*; import org.ice4j.*; import org.ice4j.ice.*; import org.ice4j.socket.*; -import org.ice4j.stack.*; /** * A HostCandidateHarvester gathers host Candidates 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); } } diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java index e92850a..69c7802 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java @@ -23,7 +23,7 @@ import org.ice4j.stack.*; * HostCandidate performed by a specific * StunCandidateHarvester. * - * @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) { diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java index 808e399..d220fd4 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -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 StunSTack 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 StunStack used by this CandidateHarvester for + * the purposes of STUN communication. It is guaranteed to be available only + * during the execution of {@link CandidateHarvester#harvest(Component)}. + * + * @return the StunStack used by this CandidateHarvester + * for the purposes of STUN communication + * @see CandidateHarvester#harvest(Component) + */ + public StunStack getStunStack() + { + return stunStack; + } + /** * Gathers STUN candidates for all host Candidates that are already * present in the specified component. 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); diff --git a/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java b/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java index 26dc721..e33b727 100644 --- a/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/TurnCandidateHarvest.java @@ -22,7 +22,7 @@ import org.ice4j.stack.*; * HostCandidate performed by a specific * TurnCandidateHarvester. * - * @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); diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index 418524d..6b5e2c5 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -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 Logger used by the Message - * class and its instances for logging output. + * The Logger used by the Message 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 StunStack in the context of which the + * request to encode this Message 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 ILLEGAL_ARGUMENT 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 binMessage. * @param msgLen the number of message bytes in binMessage. * - * @throws StunException if there's something in the - * attribute that caused us to discard the whole message (e.g. an - * invalid checksum - * or username) + * @throws StunException if there's something in the attribute that + * caused us to discard the whole message (e.g. an invalid checksum or + * username) */ private static void performAttributeSpecificActions(Attribute attribute, byte[] binMessage, diff --git a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java index 01aa0f4..0ff7111 100644 --- a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java +++ b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java @@ -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 diff --git a/src/org/ice4j/stack/MessageProcessor.java b/src/org/ice4j/stack/MessageProcessor.java index 18b4a35..555e8bc 100644 --- a/src/org/ice4j/stack/MessageProcessor.java +++ b/src/org/ice4j/stack/MessageProcessor.java @@ -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 MessageEvents */ - private MessageEventHandler messageHandler = null; + private final MessageEventHandler messageEventHandler; /** - * The listener that will be collecting error notifications. + * The NetAccessManager 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 MessageQueue where we'll be storing incoming - * messages. - * @param messageHandler MessageEventHandler - * @param errorHandler the ErrorHandler that should handle - * exceptions in this processor - * - * @throws IllegalArgumentException if either of the parameters is null. + * @param netAccessManager the NetAccessManager which is creating + * the new instance, is going to be its owner, specifies the + * MessageQueue which is to store incoming messages, specifies the + * MessageEventHandler and represents the ErrorHandler to + * handle exceptions in the new instance + * @throws IllegalArgumentException if any of the mentioned properties of + * netAccessManager are null */ - 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) diff --git a/src/org/ice4j/stack/NetAccessManager.java b/src/org/ice4j/stack/NetAccessManager.java index f553110..41c9257 100644 --- a/src/org/ice4j/stack/NetAccessManager.java +++ b/src/org/ice4j/stack/NetAccessManager.java @@ -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 StunStack 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 StunStack 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 MessageEventHandler of this NetAccessManager + * which is to be notified when incoming messages have been processed and + * are ready for delivery. + * + * @return the MessageEventHandler of this + * NetAccessManager 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 MessageQueue of this NetAccessManager in which + * incoming messages are stocked for processing. + * + * @return the MessageQueue of this NetAccessManager in + * which incoming messages are stocked for processing + */ + MessageQueue getMessageQueue() + { + return messageQueue; + } + + /** + * Gets the StunStack which has created this instance and is its + * owner. + * + * @return the StunStack 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) diff --git a/src/org/ice4j/stack/StunClientTransaction.java b/src/org/ice4j/stack/StunClientTransaction.java index 9ba949d..a6449ff 100644 --- a/src/org/ice4j/stack/StunClientTransaction.java +++ b/src/org/ice4j/stack/StunClientTransaction.java @@ -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())); } /** diff --git a/src/org/ice4j/stack/StunServerTransaction.java b/src/org/ice4j/stack/StunServerTransaction.java index 448fd2b..e35c0cc 100644 --- a/src/org/ice4j/stack/StunServerTransaction.java +++ b/src/org/ice4j/stack/StunServerTransaction.java @@ -204,9 +204,10 @@ class StunServerTransaction if(expired || !isRetransmitting) return; - stackCallback.getNetAccessManager().sendMessage(response, - localSendingAddress, - responseDestination); + stackCallback.getNetAccessManager().sendMessage( + response, + localSendingAddress, + responseDestination); } /** diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 20f9c5a..095b0ee 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -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 Logger used by the StunStack class and its + * instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(StunStack.class.getName()); + + /** + * The indicator which determines whether + * Mac.getInstance(MessageIntegrityAttribute.HMAC_SHA1_ALGORITHM) + * 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 StunStack 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 true if username contains a valid username; * false, 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); } } diff --git a/src/org/ice4j/stack/TransactionID.java b/src/org/ice4j/stack/TransactionID.java index f331168..33d090d 100644 --- a/src/org/ice4j/stack/TransactionID.java +++ b/src/org/ice4j/stack/TransactionID.java @@ -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 StunStack in the context of which the + * request to create a TransactionID is being made * @param transactionID the value of the ID. * * @return a reference to the (possibly already existing) * TransactionID corresponding to the value of * transactionID */ - 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(); diff --git a/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java index c88ab81..ebd1b5d 100644 --- a/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java +++ b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java @@ -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 StunStack used by this instance for the purposes of STUN + * communication. + */ + private final StunStack stunStack; + + /** + * Initializes a StunAddressDiscoverer with a specific + * StunStack. In order to use it one must first start it. * + * @param stunStack the StunStack 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); diff --git a/src/org/ice4j/stunclient/SimpleAddressDetector.java b/src/org/ice4j/stunclient/SimpleAddressDetector.java index 5d8f81a..3e5776e 100644 --- a/src/org/ice4j/stunclient/SimpleAddressDetector.java +++ b/src/org/ice4j/stunclient/SimpleAddressDetector.java @@ -83,7 +83,7 @@ public class SimpleAddressDetector */ public void start() { - stunStack = StunStack.getInstance(); + stunStack = new StunStack(); } diff --git a/test/org/ice4j/MessageEventDispatchingTest.java b/test/org/ice4j/MessageEventDispatchingTest.java index 1fc91bc..db81262 100644 --- a/test/org/ice4j/MessageEventDispatchingTest.java +++ b/test/org/ice4j/MessageEventDispatchingTest.java @@ -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); diff --git a/test/org/ice4j/TransactionSupportTests.java b/test/org/ice4j/TransactionSupportTests.java index 19b137f..615a917 100644 --- a/test/org/ice4j/TransactionSupportTests.java +++ b/test/org/ice4j/TransactionSupportTests.java @@ -46,6 +46,11 @@ public class TransactionSupportTests extends TestCase */ DatagramSocket serverSock = null; + /** + * The StunStack used by this TransactionSupportTests. + */ + 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); diff --git a/test/org/ice4j/message/MessageTest.java b/test/org/ice4j/message/MessageTest.java index 8c16bda..6b03902 100644 --- a/test/org/ice4j/message/MessageTest.java +++ b/test/org/ice4j/message/MessageTest.java @@ -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 StunStack used by this MessageTest. + */ + 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 ) ); diff --git a/test/org/ice4j/stack/ShallowStackTest.java b/test/org/ice4j/stack/ShallowStackTest.java index 5a4d3a2..b313ee8 100644 --- a/test/org/ice4j/stack/ShallowStackTest.java +++ b/test/org/ice4j/stack/ShallowStackTest.java @@ -21,12 +21,19 @@ import org.ice4j.socket.*; * * @author Emil Ivov */ -public class ShallowStackTest extends TestCase { +public class ShallowStackTest extends TestCase +{ + /** + * The Logger used by the ShallowStackTest 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 StunStack used by this ShallowStackTest + */ + 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)); } diff --git a/test/org/ice4j/stunclient/ResponseSequenceServer.java b/test/org/ice4j/stunclient/ResponseSequenceServer.java index b234bae..ed4913a 100644 --- a/test/org/ice4j/stunclient/ResponseSequenceServer.java +++ b/test/org/ice4j/stunclient/ResponseSequenceServer.java @@ -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 Logger used by the ResponseSequenceServer 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 messageSequence = new Vector(); - private StunStack stunStack = null; + /** + * The StunStack 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 ResponseSequenceServer instance with a + * specific StunStack to be used for the purposes of STUN + * communication. + * + * @param stunStack the StunStack 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; } /** diff --git a/test/org/ice4j/stunclient/StunAddressDiscovererTest.java b/test/org/ice4j/stunclient/StunAddressDiscovererTest.java index 399206e..061609b 100644 --- a/test/org/ice4j/stunclient/StunAddressDiscovererTest.java +++ b/test/org/ice4j/stunclient/StunAddressDiscovererTest.java @@ -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. * *

Company: Net Research Team, Louis Pasteur University

@@ -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? ). diff --git a/test/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java b/test/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java index 72a0401..a57150f 100644 --- a/test/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java +++ b/test/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java @@ -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. * *

Company: Net Research Team, Louis Pasteur University

@@ -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(); diff --git a/test/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java b/test/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java index aa794f7..7c1f392 100644 --- a/test/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java +++ b/test/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java @@ -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();