Moving project content to trunk as it should have been from the start.

This commit is contained in:
emcho 2010-01-29 11:17:49 +00:00
parent c2bdac23a6
commit a4b67b3334
24 changed files with 4968 additions and 0 deletions

View File

@ -0,0 +1,204 @@
package org.ice4j;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* Test event dispatching for both client and server.
* <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class MessageEventDispatchingTest extends TestCase
{
StunStack stunStack = null;
TransportAddress clientAddress = new TransportAddress("127.0.0.1", 5216);
TransportAddress serverAddress = new TransportAddress("127.0.0.2", 5255);
TransportAddress serverAddress2 = new TransportAddress("127.0.0.2", 5259);
NetAccessPointDescriptor clientAccessPoint = null;
NetAccessPointDescriptor serverAccessPoint = null;
NetAccessPointDescriptor serverAccessPoint2 = null;
Request bindingRequest = null;
Response bindingResponse = null;
PlainRequestCollector requestCollector = null;
PlainResponseCollector responseCollector = null;
protected void setUp() throws Exception
{
super.setUp();
stunStack = StunStack.getInstance();
clientAccessPoint = new NetAccessPointDescriptor(clientAddress);
serverAccessPoint = new NetAccessPointDescriptor(serverAddress);
serverAccessPoint2 = new NetAccessPointDescriptor(serverAddress2);
stunStack.installNetAccessPoint(clientAccessPoint);
stunStack.installNetAccessPoint(serverAccessPoint);
stunStack.installNetAccessPoint(serverAccessPoint2);
bindingRequest = MessageFactory.createBindingRequest();
bindingResponse = MessageFactory.createBindingResponse(
clientAddress, clientAddress, serverAddress);
requestCollector = new PlainRequestCollector();
responseCollector = new PlainResponseCollector();
}
protected void tearDown() throws Exception
{
clientAccessPoint = null;
serverAccessPoint = null;
requestCollector = null;
responseCollector = null;
super.tearDown();
}
/**
* Test timeout events.
*
* @throws Exception upon a stun failure
*/
public void testClientTransactionTimeouts() throws Exception
{
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
Thread.currentThread().sleep(12000);
assertEquals(
"No timeout was produced upon expiration of a client transaction",
responseCollector.receivedResponses.size(), 1);
assertEquals(
"No timeout was produced upon expiration of a client transaction",
responseCollector.receivedResponses.get(0), "timeout");
}
/**
* Test reception of Message events.
*
* @throws java.lang.Exception upon any failure
*/
public void testEventDispatchingUponIncomingRequests() throws Exception
{
//prepare to listen
stunStack.getProvider().addRequestListener(requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(500);
//verify
assertTrue("No MessageEvents have been dispatched",
requestCollector.receivedRequests.size() == 1);
}
/**
* Test that reception of Message events is only received for accesspoints
* that we have been registered for.
*
* @throws java.lang.Exception upon any failure
*/
public void testSelectiveEventDispatchingUponIncomingRequests()
throws Exception
{
//prepare to listen
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
PlainRequestCollector requestCollector2 = new PlainRequestCollector();
stunStack.getProvider().addRequestListener(serverAccessPoint2,
requestCollector2);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress2,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(500);
//verify
assertTrue(
"A MessageEvent was received by a non-interested selective listener",
requestCollector.receivedRequests.size() == 0);
assertTrue(
"No MessageEvents have been dispatched for a selective listener",
requestCollector2.receivedRequests.size() == 1);
}
/**
* Makes sure that we receive response events.
* @throws Exception if we screw up.
*/
public void testServerResponseRetransmissions() throws Exception
{
//prepare to listen
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for the message to arrive
Thread.currentThread().sleep(500);
StunMessageEvent evt = requestCollector.receivedRequests.get(0);
byte[] tid = evt.getMessage().getTransactionID();
stunStack.getProvider().sendResponse(tid,
bindingResponse,
serverAccessPoint,
clientAddress);
//wait for retransmissions
Thread.currentThread().sleep(500);
//verify that we got the response.
assertTrue(
"There were no retransmissions of a binding response",
responseCollector.receivedResponses.size() == 1 );
}
private class PlainRequestCollector implements RequestListener{
public Vector<StunMessageEvent> receivedRequests = new Vector<StunMessageEvent>();
public void requestReceived(StunMessageEvent evt){
receivedRequests.add(evt);
}
}
private class PlainResponseCollector implements ResponseCollector{
public Vector<Object> receivedResponses = new Vector<Object>();
public void processResponse(StunMessageEvent responseEvt)
{
receivedResponses.add(responseEvt);
}
public void processTimeout()
{
receivedResponses.add(new String("timeout"));
}
}
}

View File

@ -0,0 +1,241 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
public class MsgFixture
{
//---------------------- Attributes ---------------------------------------
public static final char ADDRESS_ATTRIBUTE_PORT = 1904;
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS = new byte[]{(byte)130, 79, (byte)156, (byte)137};
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS_V6 =
new byte[]{0x20, 0x01, 0x06, 0x60,
0x47, 0x11, 0x11, 0x01,
0x02, 0x30, 0x05, (byte)0xff,
(byte)0xfe, 0x1a, (byte)0x80, 0x5f};
public byte[] mappedAddress = new byte[]
{0x00, 0x01, 0x00, 0x08, //Type, Length
0x00, 0x01, 0x07, 0x70, //00 Family Port(1904)
(byte)0x82, 0x4f, (byte)0x9c, (byte)0x89 //IP Address 130.79.156.137
};//
public byte[] mappedAddressv6 = new byte[]
{0x00, 0x01, 0x00, 0x14, //Type, Length
0x00, 0x02, 0x07, 0x70, //00 Family Port(1904)
0x20, 0x01, 0x06, 0x60,
0x47, 0x11, 0x11, 0x01,
0x02, 0x30, 0x05, (byte)0xff,
(byte)0xfe, 0x1a, (byte)0x80, 0x5f//IPv6 Address
};
public byte[] unknownOptionalAttribute = new byte[]
{(byte)0x80, 0x38, 0x00, 0x10, //Type, Length
(byte)0x82, 0x4f, (byte)0x9c, (byte)0x89, //random stuff
0x00, 0x01, 0x07, 0x70, //random stuff
0x00, 0x01, 0x07, 0x70, //random stuff
(byte)0x82, 0x4f, (byte)0x9c, (byte)0x89 //random stuff
};//
public char optionalAttributeType = (char)0x8038;
public static final char ADDRESS_ATTRIBUTE_PORT_2 = 3478;
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS_2 = new byte[]{69, 0, (byte)208, 27};
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS_2_V6 =
new byte[]{0x20, 0x01, 0x06, 0x60,
0x47, 0x11, 0x11, 0x01,
0x02, 0x30, 0x55, (byte)0xff,
(byte)0xfe, 0x1a, (byte)0x82, 0x5f};
public static final char ADDRESS_ATTRIBUTE_PORT_3 = 3479;
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS_3 = new byte[]{69, 0, (byte)209, 22};
public static final byte[] ADDRESS_ATTRIBUTE_ADDRESS_3_V6 =
new byte[]{0x20, 0x01, 0x06, 0x60,
0x47, 0x11, 0x11, 0x01,
0x02, 0x30, 0x05, (byte)0xff,
(byte)0xfe, 0x1a, (byte)0x87, 0x5e};
public byte[] sourceAddress = new byte[]
{0x00, 0x04, 0x00, 0x08, //Type Length
0x00, 0x01, 0x0d, (byte)0x96, //00 Family Port(3478)
0x45, 0x00, (byte)0xd0, 0x1b //IP Address 69.0.208.27
};
public byte[] changedAddress = new byte[]
{0x00, 0x05, 0x00, 0x08, //Type Length
0x00, 0x01, 0x0d, (byte)0x97, //00 Family Port(3479)
0x45, 0x00, (byte)0xd1, 0x16 //IP Address 69.0.209.22
};
/**
* Contains three invalid attribute ids. The 3d is repeated to keep an even
* number of reports.
*/
public static final char UNKNOWN_ATTRIBUTES_1ST_ATT = 0x20;
public static final char UNKNOWN_ATTRIBUTES_2ND_ATT = 0x21;
public static final char UNKNOWN_ATTRIBUTES_3D_ATT = 0x22;
public static final char UNKNOWN_ATTRIBUTES_CNT_DEC_TST = 3;
public byte[] unknownAttsDecodeTestValue = new byte[]
{0x00, 0x0a, 0x00, 0x08, //Type Length
0x00, 0x20, 0x00, 0x21,
0x00, 0x22, 0x00, 0x22};
public static final char UNKNOWN_ATTRIBUTES_CNT_ENC_TST = 2;
public byte[] unknownAttsEncodeExpectedResult = new byte[]
{0x00, 0x0a, 0x00, 0x04, //Type Length
0x00, 0x20, 0x00, 0x21};
//--- change request
public static final boolean CHANGE_IP_FLAG_1 = false;
public static final boolean CHANGE_PORT_FLAG_1 = false;
public byte[] chngReqTestValue1 = new byte[]
{0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x00, 0x00};
public static final boolean CHANGE_IP_FLAG_2 = true;
public static final boolean CHANGE_PORT_FLAG_2 = true;
public byte[] chngReqTestValue2 = new byte[]
{0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x00, 0x06};
//--- error code
public static final byte ERROR_CLASS = 4;
public static final byte ERROR_NUMBER = 20;
public static final char ERROR_CODE = 420;
public static final String REASON_PHRASE = "Test error reason phrase.";//odd length!
public byte[] errCodeTestValue = new byte[]
{0x00, 0x09, 0x00, 0x38,
0x00, 0x00, 0x04, 0x14,
0x00, 0x54, 0x00, 0x65,
0x00, 0x73, 0x00, 0x74,
0x00, 0x20, 0x00, 0x65,
0x00, 0x72, 0x00, 0x72,
0x00, 0x6F, 0x00, 0x72,
0x00, 0x20, 0x00, 0x72,
0x00, 0x65, 0x00, 0x61,
0x00, 0x73, 0x00, 0x6F,
0x00, 0x6E, 0x00, 0x20,
0x00, 0x70, 0x00, 0x68,
0x00, 0x72, 0x00, 0x61,
0x00, 0x73, 0x00, 0x65,
0x00, 0x2E, 0x00, 0x20
};
//--------------------------- Messages ----------------------------------------
public static final byte[] TRANSACTION_ID =
new byte[]{
0x05, 0x06, 0x07, 0x08, /* transaction ID */
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16
};
public byte[] bindingRequest = new byte[]
{
0x00, 0x01, 0x00, 0x08, //STUN Msg Type | Msg Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x05, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16,
0x00, 0x03, 0x00, 0x04,//Type(Change Request) Len
0x00, 0x00, 0x00, 0x00 //Don't change neither IP nor port
};
public byte[] bindingRequest2 = new byte[]
{
0x00, 0x01, 0x00, 0x08, //STUN Msg Type | Msg Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x06, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16,
0x00, 0x03, 0x00, 0x04,//Type(Change Request) Len
0x00, 0x00, 0x00, 0x00 //Don't change neither IP nor port
};
public byte[] bindingRequest3 = new byte[]
{
0x00, 0x01, 0x00, 0x08, //STUN Msg Type | Msg Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x07, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16,
0x00, 0x03, 0x00, 0x04,//Type(Change Request) Len
0x00, 0x00, 0x00, 0x00 //Don't change neither IP nor port
};
public byte[] bindingRequest4 = new byte[]
{
0x00, 0x01, 0x00, 0x08, //STUN Msg Type | Msg Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x08, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16,
0x00, 0x03, 0x00, 0x04,//Type(Change Request) Len
0x00, 0x00, 0x00, 0x00 //Don't change neither IP nor port
};
public byte[] bindingResponse = new byte[]
{0x01, 0x01, 0x00, 0x24, //Type Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x05, 0x06, 0x07, 0x08,
0x09, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16,
0x00, 0x01, 0x00, 0x08, //AttType(MappedAddress) AttLength
0x00, 0x01, 0x07, 0x70, //00 Family Port(1904)
(byte)0x82, 0x4f, (byte)0x9c, (byte)0x89, //IP 130.79.156.37
0x00, 0x04, 0x00, 0x08, //AttType(Source Address) AttLen
0x00, 0x01, 0x0d, (byte)0x96, //00 Family Port(3478)
0x45, 0x00, (byte)0xd0, 0x1b, //IP 69.0.208.27
0x00, 0x05, 0x00, 0x08, //AttType(ChangedAddress)
0x00, 0x01, 0x0d, (byte)0x97, //00 Family Port(3479)
0x45, 0x00, (byte)0xd1, 0x16};//IP Address 69.0.209.22
public byte[] bindingErrorResponse = new byte[]
{
0x01, 0x11, 0x00, 0x24, //Type Length
0x21, 0x12, (byte)0xA4, 0x42, //Transaction ID
0x0a, 0x77, 0x6f, 0x64,
0x58, 0x04, (byte) 0xae, 0x46,
(byte)0x85, 0x19, (byte) 0xcc, 0x3c,
0x00, 0x09, 0x00, 0x38,//Error Code Attribute
0x00, 0x00, 0x04, 0x14,//Reason Phrase
0x00, 0x54, 0x00, 0x65,
0x00, 0x73, 0x00, 0x74,
0x00, 0x20, 0x00, 0x65,
0x00, 0x72, 0x00, 0x72,
0x00, 0x6F, 0x00, 0x72,
0x00, 0x20, 0x00, 0x72,
0x00, 0x65, 0x00, 0x61,
0x00, 0x73, 0x00, 0x6F,
0x00, 0x6E, 0x00, 0x20,
0x00, 0x70, 0x00, 0x68,
0x00, 0x72, 0x00, 0x61,
0x00, 0x73, 0x00, 0x65,
0x00, 0x2E, 0x00, 0x20,//unknown attributes
0x00, 0x0a, 0x00, 0x08,//Type Length
0x00, 0x20, 0x00, 0x21,
0x00, 0x22, 0x00, 0x22
};
public MsgFixture()
{
}
public void setUp()
{
}
public void tearDown()
{
}
}

View File

@ -0,0 +1,65 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j;
import junit.framework.*;
public class StunTestSuite
extends TestCase
{
public StunTestSuite(String s)
{
super(s);
}
public static Test suite()
{
TestSuite suite = new TestSuite();
//attributes
suite.addTestSuite(org.ice4j.attribute.
AddressAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.
XorOnlyTest.class);
suite.addTestSuite(org.ice4j.attribute.
AttributeDecoderTest.class);
suite.addTestSuite(org.ice4j.attribute.
ChangeRequestAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.
ErrorCodeAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.
UnknownAttributesAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.
SoftwareAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.
OptionalAttributeAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.UsernameAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.NonceAttributeTest.class);
suite.addTestSuite(org.ice4j.attribute.RealmAttributeTest.class);
//messages
suite.addTestSuite(org.ice4j.message.MessageFactoryTest.class);
suite.addTestSuite(org.ice4j.message.MessageTest.class);
//stack
suite.addTestSuite(org.ice4j.stack.ShallowStackTest.class);
//event dispatching
suite.addTestSuite(org.ice4j.MessageEventDispatchingTest.class);
//transactions
suite.addTestSuite(org.ice4j.TransactionSupportTests.class);
//client
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest.class);
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v6.class);
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v4v6.class);
return suite;
}
}

View File

@ -0,0 +1,403 @@
package org.ice4j;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* Test how client and server behave, how they recognize/adopt messages and
* how they both handle retransmissions (i.e. client transactions should make
* them and server transactions should hide them)
* <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class TransactionSupportTests extends TestCase
{
StunStack stunStack = null;
TransportAddress clientAddress = new TransportAddress("127.0.0.1", 5216);
TransportAddress serverAddress = new TransportAddress("127.0.0.2", 5255);
NetAccessPointDescriptor clientAccessPoint = null;
NetAccessPointDescriptor serverAccessPoint = null;
Request bindingRequest = null;
Response bindingResponse = null;
PlainRequestCollector requestCollector = null;
PlainResponseCollector responseCollector = null;
protected void setUp() throws Exception
{
super.setUp();
stunStack = StunStack.getInstance();
clientAccessPoint = new NetAccessPointDescriptor(clientAddress);
serverAccessPoint = new NetAccessPointDescriptor(serverAddress);
stunStack.installNetAccessPoint(clientAccessPoint);
stunStack.installNetAccessPoint(serverAccessPoint);
bindingRequest = MessageFactory.createBindingRequest();
bindingResponse = MessageFactory.createBindingResponse(
clientAddress, clientAddress, serverAddress);
requestCollector = new PlainRequestCollector();
responseCollector = new PlainResponseCollector();
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"false");
System.setProperty("org.ice4j.KEEP_CLIENT_TRANS_AFTER_A_RESPONSE",
"false");
System.setProperty("org.ice4j.MAX_RETRANSMISSIONS",
"");
System.setProperty("org.ice4j.MAX_WAIT_INTERVAL",
"");
System.setProperty("org.ice4j.ORIGINAL_WAIT_INTERVAL",
"");
}
protected void tearDown() throws Exception
{
clientAccessPoint = null;
serverAccessPoint = null;
requestCollector = null;
responseCollector = null;
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"false");
System.setProperty("org.ice4j.KEEP_CLIENT_TRANS_AFTER_A_RESPONSE",
"false");
System.setProperty("org.ice4j.MAX_RETRANSMISSIONS",
"");
System.setProperty("org.ice4j.MAX_WAIT_INTERVAL",
"");
System.setProperty("org.ice4j.ORIGINAL_WAIT_INTERVAL",
"");
super.tearDown();
}
/**
* Test that requests are retransmitted if no response is received
*
* @throws java.lang.Exception upon any failure
*/
public void testClientRetransmissions() throws Exception
{
//prepare to listen
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"true");
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(12000);
//verify
Vector<StunMessageEvent> reqs = requestCollector.getRequestsForTransaction(bindingRequest.getTransactionID());
assertTrue("No retransmissions of the request have been received",
reqs.size() > 1);
assertTrue("The binding request has not been retransmitted enough!",
reqs.size() >= 7);
}
/**
* Make sure that retransmissions are not seen by the server user and that
* it only gets a single request.
* @throws Exception if anything goes wrong.
*/
public void testServerRetransmissionHiding() throws Exception
{
//prepare to listen
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(12000);
//verify
Vector reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
assertTrue(
"Retransmissions of a binding request were propagated to the server",
reqs.size() <= 1 );
}
/**
* Makes sure that once a request has been answered by the server,
* retransmissions of this request are not propagated to the UA and are
* automatically handled with a retransmission of the last seen response
* @throws Exception if we screw up.
*/
public void testServerResponseRetransmissions() throws Exception
{
//prepare to listen
System.setProperty("org.ice4j.KEEP_CLIENT_TRANS_AFTER_A_RESPONSE",
"true");
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for the message to arrive
Thread.currentThread().sleep(500);
Vector reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
StunMessageEvent evt =
((StunMessageEvent)reqs.get(0));
byte[] tid = evt.getMessage().getTransactionID();
stunStack.getProvider().sendResponse(tid,
bindingResponse,
serverAccessPoint,
clientAddress);
//wait for retransmissions
Thread.currentThread().sleep(12000);
//verify that at least half of the request received a retransmitted resp.
assertTrue(
"There were no retransmissions of a binding response",
responseCollector.receivedResponses.size() < 5 );
}
/**
* A (very) weak test, verifying that transaction IDs are unique.
* @throws Exception in case we feel like it.
*/
public void testUniqueIDs() throws Exception
{
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send req 1
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(500);
Vector reqs1 = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
StunMessageEvent evt1 =
((StunMessageEvent)reqs1.get(0));
//send a response to make the other guy shut up
byte[] tid = evt1.getMessage().getTransactionID();
stunStack.getProvider().sendResponse(tid,
bindingResponse,
serverAccessPoint,
clientAddress);
//send req 2
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(12000);
Vector reqs2 = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
StunMessageEvent evt2 = ((StunMessageEvent)reqs2.get(0));
assertFalse("Consecutive requests were assigned the same transaction id",
Arrays.equals( evt1.getMessage().getTransactionID(),
evt2.getMessage().getTransactionID()));
}
public void testClientTransactionMaxRetransmisssionsConfigurationParameter()
throws Exception
{
//MAX_RETRANSMISSIONS
System.setProperty("org.ice4j.MAX_RETRANSMISSIONS",
"2");
//make sure we see retransmissions so that we may count them
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"true");
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait for retransmissions
Thread.currentThread().sleep(1600);
//verify
Vector reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
assertTrue("No retransmissions of the request have been received",
reqs.size() > 1);
assertEquals(
"The MAX_RETRANSMISSIONS param was not taken into account!",
reqs.size(),
3);
}
public void testMinWaitIntervalConfigurationParameter()
throws Exception
{
//MAX_RETRANSMISSIONS
System.setProperty("org.ice4j.ORIGINAL_WAIT_INTERVAL",
"1000");
//make sure we see retransmissions so that we may count them
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"true");
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
//wait a while
Thread.currentThread().sleep(500);
//verify
Vector reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
assertTrue("A retransmissions of the request was sent too early",
reqs.size() < 2);
//wait for a send
Thread.currentThread().sleep(700);
reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
//verify
assertEquals("A retransmissions of the request was not sent",
2,
reqs.size());
}
public void testMaxWaitIntervalConfigurationParameter()
throws Exception
{
//MAX_RETRANSMISSIONS
System.setProperty("org.ice4j.MAX_WAIT_INTERVAL",
"100");
//make sure we see retransmissions so that we may count them
System.setProperty("org.ice4j.PROPAGATE_RECEIVED_RETRANSMISSIONS",
"true");
System.setProperty("org.ice4j.MAX_RETRANSMISSIONS",
"11");
stunStack.getProvider().addRequestListener(serverAccessPoint,
requestCollector);
//send
stunStack.getProvider().sendRequest(bindingRequest,
serverAddress,
clientAccessPoint,
responseCollector);
// //wait a while
Thread.currentThread().sleep(1095);
//verify
Vector reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
assertEquals("Not all retransmissions were made for the expected period "
+"of time",
11,
reqs.size());
//wait for a send
Thread.currentThread().sleep(1800);
//verify
reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID());
assertEquals("A retransmissions of the request was sent, while not "
+"supposed to",
12,
reqs.size());
}
private class PlainRequestCollector implements RequestListener{
private Vector<StunMessageEvent> receivedRequestsVector = new Vector<StunMessageEvent>();
public void requestReceived(StunMessageEvent evt){
receivedRequestsVector.add(evt);
}
/**
* Only return requests from the specified tran because we might have
* capture others too.
*
* @param tranid the transaction that we'd like to get requests for.
*
* @return a Vector containing all request that we have received and
* that match <tt>tranid</tt>.
*/
public Vector<StunMessageEvent> getRequestsForTransaction(byte[] tranid)
{
Vector<StunMessageEvent> newVec = new Vector<StunMessageEvent>();
Iterator reqsIter = receivedRequestsVector.iterator();
while(reqsIter.hasNext())
{
StunMessageEvent evt = (StunMessageEvent)reqsIter.next();
Message msg = evt.getMessage();
if( Arrays.equals(tranid, msg.getTransactionID()))
newVec.add(evt);
}
return newVec;
}
}
private class PlainResponseCollector implements ResponseCollector{
public Vector<Object> receivedResponses = new Vector<Object>();
public void processResponse(StunMessageEvent responseEvt)
{
receivedResponses.add(responseEvt);
}
public void processTimeout()
{
receivedResponses.add(new String("timeout"));
}
}
/*
public TransactionSupportTests(String name)
{
super(name);
}
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new TransactionSupportTests(
"testMaxWaitIntervalConfigurationParameter"));
return suite;
}
*/
}

View File

@ -0,0 +1,506 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
*
* <p>Title: Stun4J.</p>
* <p>Description: Simple Traversal of UDP Through NAT</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Organisation: <p> Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p> Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
public class AddressAttributeTest extends TestCase {
private AddressAttribute addressAttribute = null;
private MsgFixture msgFixture;
public AddressAttributeTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
addressAttribute = new MappedAddressAttribute();
msgFixture = new MsgFixture();
msgFixture.setUp();
}
protected void tearDown() throws Exception {
addressAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Verify that AddressAttribute descendants have correctly set types and
* names.
*/
public void testAddressAttributeDescendants() {
char expectedType;
char actualType;
String expectedName;
String actualName;
//MAPPED-ADDRESS
addressAttribute = new MappedAddressAttribute();
expectedType = Attribute.MAPPED_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "MAPPED-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("MappedAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("MappedAddressAttribute does not the right name.",
expectedName, actualName);
//SOURCE-ADDRESS
addressAttribute = new SourceAddressAttribute();
expectedType = Attribute.SOURCE_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "SOURCE-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("SourceAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("SourceAddressAttribute does not the right name.",
expectedName, actualName);
//CHANGED-ADDRESS
addressAttribute = new ChangedAddressAttribute();
expectedType = Attribute.CHANGED_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "CHANGED-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("ChangedAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("ChangedAddressAttribute does not the right name.",
expectedName, actualName);
//RESPONSE-ADDRESS
addressAttribute = new ResponseAddressAttribute();
expectedType = Attribute.RESPONSE_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "RESPONSE-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("ResponseAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("ResponseAddressAttribute does not the right name.",
expectedName, actualName);
//REFLECTED-FROM
addressAttribute = new ReflectedFromAttribute();
expectedType = Attribute.REFLECTED_FROM;
actualType = addressAttribute.getAttributeType();
expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName();
assertEquals("ReflectedFromAttribute does not the right type.",
expectedType, actualType);
assertEquals("ReflectedFromAttribute does not the right name.",
expectedName, actualName);
//REFLECTED-FROM
addressAttribute = new ReflectedFromAttribute();
expectedType = Attribute.REFLECTED_FROM;
actualType = addressAttribute.getAttributeType();
expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName();
assertEquals("ReflectedFromAttribute does not the right type.",
expectedType, actualType);
assertEquals("ReflectedFromAttribute does not the right name.",
expectedName, actualName);
//XOR-MAPPED-ADDRESS
addressAttribute = new XorMappedAddressAttribute();
expectedType = Attribute.XOR_MAPPED_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "XOR-MAPPED-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("XorMappedAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("XorMappedAddressAttribute does not the right name.",
expectedName, actualName);
/* ALTERNATE-SERVER */
addressAttribute = new AlternateServerAttribute();
expectedType = Attribute.ALTERNATE_SERVER;
actualType = addressAttribute.getAttributeType();
expectedName = "ALTERNATE-SERVER";
actualName = addressAttribute.getName();
assertEquals("AlternateServerAttribute does not the right type.",
expectedType, actualType);
assertEquals("AlternateAttribute does not the right name.",
expectedName, actualName);
/* XOR-PEER-ADDRESS */
addressAttribute = new XorPeerAddressAttribute();
expectedType = Attribute.XOR_PEER_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "XOR-PEER-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("XorPeerAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("XorPeerAddressAttribute does not the right name.",
expectedName, actualName);
/* XOR-RELAYED-ADDRESS */
addressAttribute = new XorRelayedAddressAttribute();
expectedType = Attribute.XOR_RELAYED_ADDRESS;
actualType = addressAttribute.getAttributeType();
expectedName = "XOR-RELAYED-ADDRESS";
actualName = addressAttribute.getName();
assertEquals("XorRelayedAddressAttribute does not the right type.",
expectedType, actualType);
assertEquals("XorRelayedAddressAttribute does not the right name.",
expectedName, actualName);
}
/**
* Verifies that xorred address-es are properly xor-ed for IPv4 addresses.
*/
public void testXorMappedAddressXoring_v4()
{
XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute();
TransportAddress testAddress =
new TransportAddress("130.79.95.53", 12120);
addressAttribute.setAddress(testAddress);
//do a xor with an id equal to the v4 address itself so that we get 0000..,
TransportAddress xorredAddr =
addressAttribute.applyXor(new byte[]{(byte)130,79,95,53,0,0,0,0,0,0,0,0,0,0,0,0,0});
assertTrue("Xorring the address with itself didn't return 00000...",
Arrays.equals(xorredAddr.getAddressBytes(), new byte[]{0,0,0,0}));
assertTrue("Port was not xorred",
testAddress.getPort() != xorredAddr.getPort());
//Test xor-ing the original with the xored - should get the xor code
addressAttribute.setAddress(testAddress);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
xorredAddr =
addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertTrue("Xorring the original with the xor-ed didn't return the code..",
Arrays.equals(
xorredAddr.getAddressBytes(),
new byte[]{21,22,23,24}));
assertTrue("Port was not xorred",
testAddress.getPort() != 0xFFFF);
//Test double xor-ing - should get the original
addressAttribute.setAddress(testAddress);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
addressAttribute.setAddress(xorredAddr);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
assertEquals("Double xorring didn't give the original ...",
testAddress, xorredAddr);
}
/**
* Verifies that xorred address-es are properly xor-ed for IPv6 addresses.
*/
public void testXorMappedAddressXoring_v6()
{
XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute();
TransportAddress testAddress =
new TransportAddress("2001:660:4701:1001:202:8aff:febe:130b", 12120);
addressAttribute.setAddress(testAddress);
//do a xor with an id equal to the v4 address itself so that we get 0000..,
TransportAddress xorredAddr =
addressAttribute.applyXor(
new byte[]{(byte)0x20, (byte)0x01, (byte)0x06, (byte)0x60,
(byte)0x47, (byte)0x01, (byte)0x10, (byte)0x01,
(byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff,
(byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b});
assertTrue("Xorring the address with itself didn't return 00000...",
Arrays.equals(xorredAddr.getAddressBytes(),
new byte[]{0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0}));
assertTrue("Port was not xorred",
testAddress.getPort() != xorredAddr.getPort());
//Test xor-ing the original with the xored - should get the xor code
addressAttribute.setAddress(testAddress);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
xorredAddr =
addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertTrue("Xorring the original with the xor-ed didn't return the code..",
Arrays.equals(
xorredAddr.getAddressBytes(),
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}));
assertTrue("Port was not xorred",
testAddress.getPort() != 0xFFFF);
//Test double xor-ing - should get the original
addressAttribute.setAddress(testAddress);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
addressAttribute.setAddress(xorredAddr);
xorredAddr =
addressAttribute.applyXor(new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
assertEquals("Double xorring didn't give the original ...",
testAddress, xorredAddr);
}
/**
* Test whetner sample binary arrays are correctly decoded.
* @throws StunException
*/
public void testDecodeAttributeBody() throws StunException {
byte[] attributeValue = msgFixture.mappedAddress;
char offset = Attribute.HEADER_LENGTH;
char length = (char)(attributeValue.length - offset);
addressAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("AddressAttribute.decode() did not properly decode the port field.",
msgFixture.ADDRESS_ATTRIBUTE_PORT,
addressAttribute.getPort());
assertTrue("AddressAttribute.decode() did not properly decode the address field.",
Arrays.equals( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
addressAttribute.getAddressBytes()));
}
/**
* Test whetner sample binary arrays are correctly decoded.
* @throws StunException
*/
public void testDecodeAttributeBodyv6() throws StunException {
byte[] attributeValue = msgFixture.mappedAddressv6;
char offset = Attribute.HEADER_LENGTH;
char length = (char)(attributeValue.length - offset);
addressAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("decode() failed for an IPv6 Addr's port.",
msgFixture.ADDRESS_ATTRIBUTE_PORT,
addressAttribute.getPort());
assertTrue("AddressAttribute.decode() failed for an IPv6 address.",
Arrays.equals( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
addressAttribute.getAddressBytes()));
}
/**
* Test whether attributes are properly encoded.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEncode()
throws StunException
{
byte[] expectedReturn = msgFixture.mappedAddress;
addressAttribute.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
byte[] actualReturn = addressAttribute.encode();
assertTrue("AddressAttribute.encode() did not properly encode a sample attribute",
Arrays.equals( expectedReturn, actualReturn));
}
/**
* Test whether attributes are properly encoded.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEncodev6()
throws StunException
{
byte[] expectedReturn = msgFixture.mappedAddressv6;
addressAttribute.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
byte[] actualReturn = addressAttribute.encode();
assertTrue("An AddressAttribute did not properly encode an IPv6 addr.",
Arrays.equals( expectedReturn, actualReturn));
}
/**
* Tests the equals method against a null, a different and an identical
* object.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEquals()
throws StunException
{
//null test
AddressAttribute target = null;
boolean expectedReturn = false;
boolean actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed against a null target.",
expectedReturn, actualReturn);
//difference test
target = new MappedAddressAttribute();
char port = (char)(msgFixture.ADDRESS_ATTRIBUTE_PORT + 1 );
target.setAddress( new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
port));
addressAttribute.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT ));
expectedReturn = false;
actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed against a different target.",
expectedReturn, actualReturn);
//equality test
target.setAddress( new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT ));
expectedReturn = true;
actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed against an equal target.",
expectedReturn, actualReturn);
//ipv6 equality test
target.setAddress( new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
addressAttribute.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT ));
expectedReturn = true;
actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed for IPv6 addresses.",
expectedReturn, actualReturn);
}
/**
* Tests whether data length is properly calculated.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testGetDataLength()
throws StunException
{
char expectedReturn = 8;//1-padding + 1-family + 2-port + 4-address
addressAttribute.setAddress(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
char actualReturn = addressAttribute.getDataLength();
assertEquals("Datalength is not propoerly calculated",
expectedReturn, actualReturn);
expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address
addressAttribute.setAddress(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
actualReturn = addressAttribute.getDataLength();
assertEquals("Datalength is not propoerly calculated",
expectedReturn, actualReturn);
}
/**
* Tests that the address family is always 1.
*/
public void testGetFamily() {
byte expectedReturn = 1;
addressAttribute.setAddress(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
byte actualReturn = addressAttribute.getFamily();
assertEquals("Address family was not 1 for an IPv4",
expectedReturn, actualReturn);
//ipv6
expectedReturn = 2;
addressAttribute.setAddress(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
actualReturn = addressAttribute.getFamily();
assertEquals("Address family was not 2 for an IPv6 address",
expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,176 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import org.ice4j.*;
import org.ice4j.attribute.*;
import junit.framework.*;
/**
* We have already tested individual decode methods, so our job here
* is to verify that that AttributeDecoder.decode distributes the right way.
*/
public class AttributeDecoderTest extends TestCase {
private AttributeDecoder attributeDecoder = null;
private MsgFixture msgFixture;
private byte[] expectedAttributeValue = null;
public AttributeDecoderTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
attributeDecoder = new AttributeDecoder();
msgFixture = new MsgFixture();
//init a sample body
int offset = Attribute.HEADER_LENGTH;
expectedAttributeValue =
new byte[msgFixture.unknownOptionalAttribute.length - offset];
System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
expectedAttributeValue, 0,
expectedAttributeValue.length);
msgFixture.setUp();
}
protected void tearDown() throws Exception {
attributeDecoder = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
public void testDecodeMappedAddress()
throws StunException
{
//
byte[] bytes = msgFixture.mappedAddress;
char offset = 0;
char length = (char)bytes.length;
//create the message
MappedAddressAttribute expectedReturn = new MappedAddressAttribute();
expectedReturn.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
expectedReturn, actualReturn);
}
public void testDecodeMappedAddress_v6()
throws StunException
{
//
byte[] bytes = msgFixture.mappedAddressv6;
char offset = 0;
char length = (char)bytes.length;
//create the message
MappedAddressAttribute expectedReturn = new MappedAddressAttribute();
expectedReturn.setAddress(
new TransportAddress(msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
msgFixture.ADDRESS_ATTRIBUTE_PORT));
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
expectedReturn, actualReturn);
}
public void testDecodeChangeRequest()
throws StunException
{
//
byte[] bytes = msgFixture.chngReqTestValue1;
char offset = 0;
char length = (char)bytes.length;
//create the message
ChangeRequestAttribute expectedReturn = new ChangeRequestAttribute();
expectedReturn.setChangeIpFlag(msgFixture.CHANGE_IP_FLAG_1);
expectedReturn.setChangePortFlag(msgFixture.CHANGE_PORT_FLAG_1);
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute",
expectedReturn, actualReturn);
}
public void testDecodeErrorCode()
throws StunException
{
//
byte[] bytes = msgFixture.errCodeTestValue;
char offset = 0;
char length = (char)bytes.length;
//create the message
ErrorCodeAttribute expectedReturn = new ErrorCodeAttribute();
expectedReturn.setErrorClass(msgFixture.ERROR_CLASS);
expectedReturn.setErrorNumber(msgFixture.ERROR_NUMBER);
expectedReturn.setReasonPhrase(msgFixture.REASON_PHRASE);
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a ERROR-CODE attribute",
expectedReturn, actualReturn);
}
public void testDecodeUnknownAttributes()
throws StunException
{
//unknown attributes
byte[] bytes = msgFixture.unknownAttsDecodeTestValue;
char offset = 0;
char length = (char)msgFixture.mappedAddress.length;
//create the message
UnknownAttributesAttribute expectedReturn = new UnknownAttributesAttribute();
expectedReturn.addAttributeID(msgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT);
expectedReturn.addAttributeID(msgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
expectedReturn.addAttributeID(msgFixture.UNKNOWN_ATTRIBUTES_3D_ATT);
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a ERROR-CODE attribute",
expectedReturn, actualReturn);
}
public void testDecodeUnknownOptionalAttribute()
throws StunException
{
//unknown attributes
byte[] bytes = msgFixture.unknownOptionalAttribute;
char offset = 0;
char length = (char)msgFixture.mappedAddress.length;
//create the message
OptionalAttribute expectedReturn =
new OptionalAttribute(Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE);
expectedReturn.setBody(expectedAttributeValue, 0,
expectedAttributeValue.length);
Attribute actualReturn = attributeDecoder.decode(bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute",
expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,181 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*;
import org.ice4j.attribute.*;
public class ChangeRequestAttributeTest extends TestCase {
private ChangeRequestAttribute changeRequestAttribute = null;
private MsgFixture binMessagesFixture;
public ChangeRequestAttributeTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
changeRequestAttribute = new ChangeRequestAttribute();
binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
}
protected void tearDown() throws Exception {
changeRequestAttribute = null;
binMessagesFixture.tearDown();
binMessagesFixture = null;
super.tearDown();
}
/**
* Test whether the constructed object has the proper type.
*/
public void testChangeRequestAttribute() {
changeRequestAttribute = new ChangeRequestAttribute();
assertEquals(
"ChangeRequestAttribute did not construct an attribute with the "
+"correct type.",
changeRequestAttribute.getAttributeType(),
Attribute.CHANGE_REQUEST);
}
/**
* Test whether sample binary arrays are properly decoded.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testDecodeAttributeBody()
throws StunException
{
byte[] attributeValue = binMessagesFixture.chngReqTestValue1;
char offset = Attribute.HEADER_LENGTH;
char length = (char)(attributeValue.length - offset);
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
binMessagesFixture.CHANGE_IP_FLAG_1,
changeRequestAttribute.getChangeIpFlag()
);
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
binMessagesFixture.CHANGE_PORT_FLAG_1,
changeRequestAttribute.getChangePortFlag()
);
//2nd sample
attributeValue = binMessagesFixture.chngReqTestValue2;
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
binMessagesFixture.CHANGE_IP_FLAG_2,
changeRequestAttribute.getChangeIpFlag()
);
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
binMessagesFixture.CHANGE_PORT_FLAG_2,
changeRequestAttribute.getChangePortFlag()
);
changeRequestAttribute.getChangePortFlag();
}
/**
* Create sample objects and test whether they encode properly.
*/
public void testEncode() {
byte[] expectedReturn = binMessagesFixture.chngReqTestValue1;
changeRequestAttribute = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(binMessagesFixture.CHANGE_IP_FLAG_1);
changeRequestAttribute.setChangePortFlag(binMessagesFixture.CHANGE_PORT_FLAG_1);
byte[] actualReturn = changeRequestAttribute.encode();
assertTrue("Object did not encode properly.",
Arrays.equals(expectedReturn, actualReturn));
//2nd test
expectedReturn = binMessagesFixture.chngReqTestValue2;
changeRequestAttribute = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(binMessagesFixture.CHANGE_IP_FLAG_2);
changeRequestAttribute.setChangePortFlag(binMessagesFixture.CHANGE_PORT_FLAG_2);
actualReturn = changeRequestAttribute.encode();
assertTrue("Object did not encode properly.",
Arrays.equals(expectedReturn, actualReturn));
}
/**
* Tests the equals method against a null, a different and an identical
* object.
*/
public void testEquals() {
ChangeRequestAttribute target = null;
boolean expectedReturn = false;
//null test
boolean actualReturn = changeRequestAttribute.equals(target);
assertEquals("Null value test failed", expectedReturn, actualReturn);
//test against a different object.
target = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(true);
changeRequestAttribute.setChangePortFlag(false);
target.setChangeIpFlag(false);
target.setChangePortFlag(true);
actualReturn = changeRequestAttribute.equals(target);
assertEquals("Test against a different value failed",
expectedReturn, actualReturn);
//test against an equal value
target = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(true);
changeRequestAttribute.setChangePortFlag(false);
target.setChangeIpFlag(true);
target.setChangePortFlag(false);
expectedReturn = true;
actualReturn = changeRequestAttribute.equals(target);
assertEquals("Test against an equals value failed",
expectedReturn, actualReturn);
}
/**
* Test whether the returned value is always 4.
*/
public void testGetDataLength() {
char expectedReturn = 4; // constant 4 bytes of data
char actualReturn = changeRequestAttribute.getDataLength();
assertEquals("data length returned an invalid value",
expectedReturn, actualReturn);
}
/**
* Test whether we get a relevant name.
*/
public void testGetName() {
String expectedReturn = "CHANGE-REQUEST";
String actualReturn = changeRequestAttribute.getName();
assertEquals("Invalid name", expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,225 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
*
* <p>Title: Stun4J.</p>
* <p>Description: Simple Traversal of UDP Through NAT.</p>
* <p>Copyright: Copyright (c) 2003.</p>
* <p>Organisation: Louis Pasteur University, Strasbourg, France.</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
public class ErrorCodeAttributeTest extends TestCase {
private ErrorCodeAttribute errorCodeAttribute = null;
private MsgFixture msgFixture;
public ErrorCodeAttributeTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
errorCodeAttribute = new ErrorCodeAttribute();
msgFixture = new MsgFixture();
msgFixture.setUp();
}
protected void tearDown() throws Exception {
errorCodeAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Test Attribute type
*/
public void testErrorCodeAttribute()
{
errorCodeAttribute = new ErrorCodeAttribute();
assertEquals("ErrorCodeAttribute() constructed an attribute with an invalid type",
Attribute.ERROR_CODE,
errorCodeAttribute.getAttributeType());
}
/**
* Test whether sample binary arrays are properly decoded.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testDecodeAttributeBody()
throws StunException {
byte[] attributeValue = msgFixture.errCodeTestValue;
char offset = Attribute.HEADER_LENGTH;
char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH);
errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("Error Class was not correctly decoded",
msgFixture.ERROR_CLASS,
errorCodeAttribute.getErrorClass());
assertEquals("Error Number was not correctly decoded",
msgFixture.ERROR_NUMBER,
errorCodeAttribute.getErrorNumber());
assertEquals("Reason phrase was not correctly decoded",
msgFixture.REASON_PHRASE.trim(),
errorCodeAttribute.getReasonPhrase().trim());
}
/**
* Construct and encode a sample object and assert equality with a sample
* binary array.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEncode()
throws StunException
{
byte[] expectedReturn = msgFixture.errCodeTestValue;
errorCodeAttribute.setErrorClass(msgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(msgFixture.ERROR_NUMBER);
errorCodeAttribute.setReasonPhrase(msgFixture.REASON_PHRASE);
byte[] actualReturn = errorCodeAttribute.encode();
assertTrue("encode() did not return the expected binary array.",
Arrays.equals( expectedReturn, actualReturn));
}
/**
* Tests the equals method against a null, a different and an identical
* object.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEquals()
throws StunException
{
//null value test
ErrorCodeAttribute target = null;
boolean expectedReturn = false;
boolean actualReturn = errorCodeAttribute.equals(target);
assertEquals("equals() failed against a null value target.",
expectedReturn, actualReturn);
//different objects
target = new ErrorCodeAttribute();
expectedReturn = false;
target.setErrorClass(msgFixture.ERROR_CLASS);
target.setErrorNumber(msgFixture.ERROR_NUMBER);
errorCodeAttribute.setErrorClass((byte)(msgFixture.ERROR_CLASS+1));
errorCodeAttribute.setErrorNumber((byte)(msgFixture.ERROR_NUMBER+1));
actualReturn = errorCodeAttribute.equals(target);
assertEquals("equals() failed against a not equal target.",
expectedReturn, actualReturn);
//different objects
target = new ErrorCodeAttribute();
errorCodeAttribute = new ErrorCodeAttribute();
expectedReturn = true;
target.setErrorClass(msgFixture.ERROR_CLASS);
target.setErrorNumber(msgFixture.ERROR_NUMBER);
errorCodeAttribute.setErrorClass(msgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(msgFixture.ERROR_NUMBER);
actualReturn = errorCodeAttribute.equals(target);
assertEquals("equals() failed against a not equal target.",
expectedReturn, actualReturn);
}
/**
* Test whether data length is propertly calculated.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testGetDataLength()
throws StunException
{
char expectedReturn =
(char)(msgFixture.errCodeTestValue.length
- Attribute.HEADER_LENGTH);
errorCodeAttribute.setErrorClass(msgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(msgFixture.ERROR_NUMBER);
errorCodeAttribute.setReasonPhrase(msgFixture.REASON_PHRASE);
char actualReturn = errorCodeAttribute.getDataLength();
assertEquals("return value", expectedReturn, actualReturn);
}
/**
* Test whether error code is properly calculated from error class and number
*
* @throws StunException java.lang.Exception if we fail
*/
public void testGetErrorCode()
throws StunException
{
char expectedReturn = (char)(100*msgFixture.ERROR_CLASS
+ msgFixture.ERROR_NUMBER);
errorCodeAttribute.setErrorClass(msgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(msgFixture.ERROR_NUMBER);
char actualReturn = errorCodeAttribute.getErrorCode();
assertEquals("return value", expectedReturn, actualReturn);
}
/**
* Test whether we get a proper name for that attribute.
*/
public void testGetName() {
String expectedReturn = "ERROR-CODE";
String actualReturn = errorCodeAttribute.getName();
assertEquals("return value", expectedReturn, actualReturn);
}
/**
* Test whether error code is properly calculated from error class and number
*
* @throws StunException java.lang.Exception if we fail
*/
public void testSetErrorCode() throws StunException {
char errorCode = (char)(msgFixture.ERROR_CLASS*100 + msgFixture.ERROR_NUMBER);
errorCodeAttribute.setErrorCode(errorCode);
assertEquals("An error class was not properly set after decoding an error code.",
(int)msgFixture.ERROR_CLASS,
(int)errorCodeAttribute.getErrorClass());
assertEquals("An error number was not properly set after decoding an error code.",
(int)msgFixture.ERROR_NUMBER,
(int)errorCodeAttribute.getErrorNumber());
}
}

View File

@ -0,0 +1,134 @@
/*
* Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* Tests the nonce attribute class.
* <p>Organization Network Research Team, Louis Pasteur University</p>
* @author Emil Ivov
* @author Sebastien Vincent
*/
public class NonceAttributeTest extends TestCase
{
private NonceAttribute nonceAttribute = null;
MsgFixture msgFixture = null;
String nonceValue = "0123456789abcdef";
byte[] attributeBinValue = new byte[]{
(byte)(NonceAttribute.NONCE>>8),
(byte)(NonceAttribute.NONCE & 0x00FF),
0, (byte)nonceValue.length(),
'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
protected void setUp() throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
nonceAttribute = new NonceAttribute();
nonceAttribute.setNonce(nonceValue.getBytes());
msgFixture.setUp();
}
protected void tearDown() throws Exception
{
nonceAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Tests decoding of the nonce attribute.
* @throws StunException upon a failure
*/
public void testDecodeAttributeBody() throws StunException
{
char offset = 0;
NonceAttribute decoded = new NonceAttribute();
char length = (char)nonceValue.length();
decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length);
//nonce value
assertEquals( "decode failed", nonceAttribute, decoded);
}
/**
* Tests the encode method
*/
public void testEncode()
{
assertTrue("encode failed",
Arrays.equals(nonceAttribute.encode(),
attributeBinValue));
}
/**
* Test Equals
*/
public void testEquals()
{
NonceAttribute nonceAttribute2 = new NonceAttribute();
nonceAttribute2.setNonce(nonceValue.getBytes());
//test positive equals
assertEquals("testequals failed", nonceAttribute, nonceAttribute2);
//test negative equals
nonceAttribute2 = new NonceAttribute();
nonceAttribute2.setNonce("some other nonce".getBytes());
//test positive equals
assertFalse("testequals failed",
nonceAttribute.equals(nonceAttribute2));
//test null equals
assertFalse("testequals failed",
nonceAttribute.equals(null));
}
/**
* Tests extracting data length
*/
public void testGetDataLength()
{
char expectedReturn = (char)nonceValue.length();
char actualReturn = nonceAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
}
/**
* Tests getting the name
*/
public void testGetName()
{
String expectedReturn = "NONCE";
String actualReturn = nonceAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
}
public void testSetGetNonce()
{
byte[] expectedReturn = nonceValue.getBytes();
NonceAttribute att = new NonceAttribute();
att.setNonce(expectedReturn);
byte[] actualReturn = att.getNonce();
assertTrue("nonce setter or getter failed",
Arrays.equals( expectedReturn,
actualReturn));
}
}

View File

@ -0,0 +1,131 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* @author Emil Ivov
* @version 1.0
*/
public class OptionalAttributeAttributeTest extends TestCase
{
private OptionalAttribute optionalAttribute = null;
private MsgFixture msgFixture = null;
byte[] expectedAttributeValue = null;
protected void setUp() throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
int offset = Attribute.HEADER_LENGTH;
//init a sample body
expectedAttributeValue =
new byte[msgFixture.unknownOptionalAttribute.length - offset];
System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
expectedAttributeValue, 0,
expectedAttributeValue.length);
optionalAttribute = new OptionalAttribute(
msgFixture.optionalAttributeType);
}
protected void tearDown() throws Exception
{
optionalAttribute = null;
expectedAttributeValue = null;
super.tearDown();
}
/**
* Test whetner sample binary arrays are correctly decoded.
* @throws StunException
*/
public void testDecodeAttributeBody() throws StunException {
char offset = Attribute.HEADER_LENGTH;
char length = (char)(msgFixture.unknownOptionalAttribute.length - offset);
optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute,
offset, length);
assertTrue("OptionalAttribute did not decode properly.",
Arrays.equals( expectedAttributeValue,
optionalAttribute.getBody()));
assertEquals("Lenght was not properly decoded", length,
optionalAttribute.getDataLength());
}
/**
* Test whether attributes are properly encoded
*/
public void testEncode()
{
optionalAttribute.setBody(expectedAttributeValue, 0,
expectedAttributeValue.length);
byte[] actualReturn = optionalAttribute.encode();
assertTrue("encode failed",
Arrays.equals( msgFixture.unknownOptionalAttribute, actualReturn) );
}
/**
* Test whether the equals method works ok
*/
public void testEquals()
{
//null comparison
Object obj = null;
boolean expectedReturn = false;
optionalAttribute.setBody( expectedAttributeValue, 0,
expectedAttributeValue.length);
boolean actualReturn = optionalAttribute.equals(obj);
assertEquals("failed null comparison", expectedReturn, actualReturn);
//wrong type comparison
obj = new String("hehe :)");
actualReturn = optionalAttribute.equals(obj);
assertEquals("failed wrong type comparison", expectedReturn,
actualReturn);
//succesful comparison
obj = new OptionalAttribute(msgFixture.optionalAttributeType);
((OptionalAttribute)obj).setBody( expectedAttributeValue, 0,
expectedAttributeValue.length);
expectedReturn = true;
actualReturn = optionalAttribute.equals(obj);
assertEquals("failed null comparison", expectedReturn, actualReturn);
}
public void testGetDataLength()
{
char expectedReturn = (char)expectedAttributeValue.length;
optionalAttribute.setBody( expectedAttributeValue, 0,
expectedAttributeValue.length);
char actualReturn = optionalAttribute.getDataLength();
assertEquals("return value", expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,134 @@
/*
* Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* Tests the realm attribute class.
* <p>Organization Network Research Team, Louis Pasteur University</p>
* @author Emil Ivov
* @author Sebastien Vincent
*/
public class RealmAttributeTest extends TestCase
{
private RealmAttribute realmAttribute = null;
MsgFixture msgFixture = null;
String realmValue = "domain.org";
byte[] attributeBinValue = new byte[]{
(byte)(RealmAttribute.REALM>>8),
(byte)(RealmAttribute.REALM & 0x00FF),
0, (byte)realmValue.length(),
'd', 'o', 'm', 'a', 'i', 'n', '.', 'o', 'r', 'g', 0x00, 0x00};
protected void setUp() throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
realmAttribute = new RealmAttribute();
realmAttribute.setRealm(realmValue.getBytes());
msgFixture.setUp();
}
protected void tearDown() throws Exception
{
realmAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Tests decoding of the realm attribute.
* @throws StunException upon a failure
*/
public void testDecodeAttributeBody() throws StunException
{
char offset = 0;
RealmAttribute decoded = new RealmAttribute();
char length = (char)realmValue.length();
decoded.decodeAttributeBody(realmValue.getBytes(), offset, length);
//realm value
assertEquals( "decode failed", realmAttribute, decoded);
}
/**
* Tests the encode method
*/
public void testEncode()
{
assertTrue("encode failed",
Arrays.equals(realmAttribute.encode(),
attributeBinValue));
}
/**
* Test Equals
*/
public void testEquals()
{
RealmAttribute realmAttribute2 = new RealmAttribute();
realmAttribute2.setRealm(realmValue.getBytes());
//test positive equals
assertEquals("testequals failed", realmAttribute, realmAttribute2);
//test negative equals
realmAttribute2 = new RealmAttribute();
realmAttribute2.setRealm("some other realm".getBytes());
//test positive equals
assertFalse("testequals failed",
realmAttribute.equals(realmAttribute2));
//test null equals
assertFalse("testequals failed",
realmAttribute.equals(null));
}
/**
* Tests extracting data length
*/
public void testGetDataLength()
{
char expectedReturn = (char)realmValue.length();
char actualReturn = realmAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
}
/**
* Tests getting the name
*/
public void testGetName()
{
String expectedReturn = "REALM";
String actualReturn = realmAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
}
public void testSetGetRealm()
{
byte[] expectedReturn = realmValue.getBytes();
RealmAttribute att = new RealmAttribute();
att.setRealm(expectedReturn);
byte[] actualReturn = att.getRealm();
assertTrue("realm setter or getter failed",
Arrays.equals( expectedReturn,
actualReturn));
}
}

View File

@ -0,0 +1,133 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* Tests the software attribute class.
* <p>Organization Network Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class SoftwareAttributeTest extends TestCase
{
private SoftwareAttribute softwareAttribute = null;
MsgFixture msgFixture = null;
String softwareValue = "turnserver.org";
byte[] attributeBinValue = new byte[]{
(byte)(SoftwareAttribute.SOFTWARE>>8),
(byte)(SoftwareAttribute.SOFTWARE & 0x00FF),
0, (byte)softwareValue.length(),
't', 'u', 'r', 'n', 's', 'e', 'r','v', 'e', 'r', '.', 'o', 'r', 'g', 0x00, 0x00};
protected void setUp() throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
softwareAttribute = new SoftwareAttribute();
softwareAttribute.setSoftware(softwareValue.getBytes());
msgFixture.setUp();
}
protected void tearDown() throws Exception
{
softwareAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Tests decoding of the software attribute.
* @throws StunException upon a failure
*/
public void testDecodeAttributeBody() throws StunException
{
char offset = 0;
SoftwareAttribute decoded = new SoftwareAttribute();
char length = (char)softwareValue.length();
decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length);
//software value
assertEquals( "decode failed", softwareAttribute, decoded);
}
/**
* Tests the encode method
*/
public void testEncode()
{
assertTrue("encode failed",
Arrays.equals(softwareAttribute.encode(),
attributeBinValue));
}
/**
* Test Equals
*/
public void testEquals()
{
SoftwareAttribute softwareAttribute2 = new SoftwareAttribute();
softwareAttribute2.setSoftware(softwareValue.getBytes());
//test positive equals
assertEquals("testequals failed", softwareAttribute, softwareAttribute2);
//test negative equals
softwareAttribute2 = new SoftwareAttribute();
softwareAttribute2.setSoftware("some other software".getBytes());
//test positive equals
assertFalse("testequals failed",
softwareAttribute.equals(softwareAttribute2));
//test null equals
assertFalse("testequals failed",
softwareAttribute.equals(null));
}
/**
* Tests extracting data length
*/
public void testGetDataLength()
{
char expectedReturn = (char)softwareValue.length();
char actualReturn = softwareAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
}
/**
* Tests getting the name
*/
public void testGetName()
{
String expectedReturn = "SOFTWARE";
String actualReturn = softwareAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
}
public void testSetGetSoftware()
{
byte[] expectedReturn = softwareValue.getBytes();
SoftwareAttribute att = new SoftwareAttribute();
att.setSoftware(expectedReturn);
byte[] actualReturn = att.getSoftware();
assertTrue("software setter or getter failed",
Arrays.equals( expectedReturn,
actualReturn));
}
}

View File

@ -0,0 +1,271 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
public class UnknownAttributesAttributeTest extends TestCase {
private UnknownAttributesAttribute unknownAttributesAttribute = null;
private MsgFixture binMessagesFixture;
public UnknownAttributesAttributeTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
unknownAttributesAttribute = new UnknownAttributesAttribute();
binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
}
protected void tearDown() throws Exception {
unknownAttributesAttribute = null;
binMessagesFixture.tearDown();
binMessagesFixture = null;
super.tearDown();
}
//-------------------------------- TESTS ---------------------------------------
/**
* Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES)
* type.
*/
public void testUnknownAttributesAttribute() {
unknownAttributesAttribute = new UnknownAttributesAttribute();
assertEquals("UnknownAttributesAttribute() did not properly set the "
+"Attribute's type field!",
(int)Attribute.UNKNOWN_ATTRIBUTES,
(int)unknownAttributesAttribute.getAttributeType()
);
}
/**
* Verify that the passed attribute id is added to the list of attributes
* and that a second addition of the same id would not augment the attribute
* count.
*/
public void testAddAttributeID() {
char attributeID = 0x22; // unknown attribute id
unknownAttributesAttribute.addAttributeID(attributeID);
assertEquals("addAttributeID does not seem to properly add the attribute ID",
(int)attributeID,
(int)unknownAttributesAttribute.getAttribute(0)
);
assertEquals("addAttributeID does not seem to properly add the attribute ID",
1,
unknownAttributesAttribute.getAttributeCount()
);
//add a second one
unknownAttributesAttribute.addAttributeID(attributeID);
assertEquals("Adding a 2nd time the same attributeID should not change "
+"the number of attributes",
1,
unknownAttributesAttribute.getAttributeCount()
);
}
/**
* Tests whether a sample binary array is properly decoded.
* @throws StunException
*/
public void testDecodeAttributeBody() throws StunException {
//a copy of the array in the fixture:
byte[] attributeValue = binMessagesFixture.unknownAttsDecodeTestValue;
unknownAttributesAttribute.decodeAttributeBody(attributeValue,
Attribute.HEADER_LENGTH,
(char)(attributeValue.length
- Attribute.HEADER_LENGTH));
//is every one there?
assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains(
MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT));
assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains(
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT));
assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains(
MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT));
assertEquals("The decoded attribute contained "
+ unknownAttributesAttribute.getAttributeCount()
+ " attribute ids when there were only "
+ (int)MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST
+ " in the original binary array.",
MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST,
unknownAttributesAttribute.getAttributeCount()
);
}
/**
* Creates a new UnknownAttributesAttribute encodes it and assert equality
* with binMessagesFixture.unknownAttsEncodeExpectedResult.
*/
public void testEncode() {
byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult;
unknownAttributesAttribute.addAttributeID(
MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT);
unknownAttributesAttribute.addAttributeID(
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
byte[] actualReturn = unknownAttributesAttribute.encode();
assertTrue("UnknownAttributesAttribute did not encode properly.",
Arrays.equals(actualReturn, expectedReturn));
}
/**
* Tests the equals method against a null, a different and an identical
* object.
*/
public void testEquals() {
UnknownAttributesAttribute target = new UnknownAttributesAttribute();
boolean expectedReturn = false;
boolean actualReturn = unknownAttributesAttribute.equals(null);
assertEquals("Equals failed for a null object",
expectedReturn, actualReturn);
unknownAttributesAttribute.addAttributeID((char)25);
target.addAttributeID((char)25);
unknownAttributesAttribute.addAttributeID((char)26);
actualReturn = unknownAttributesAttribute.equals(target);
assertEquals("Equals failed when comparing different objects.",
expectedReturn, actualReturn);
target.addAttributeID((char)26);
expectedReturn = true;
actualReturn = unknownAttributesAttribute.equals(target);
assertEquals("Equals failed to recognize identical objects.",
expectedReturn, actualReturn);
}
/**
* Tests that getAttribute() return the correct attribute id, preserving
* entry order.
*/
public void testGetAttribute() {
char expectedId1 = 20;
char expectedId2 = 21;
char actualId1;
char actualId2;
unknownAttributesAttribute.addAttributeID(expectedId1);
unknownAttributesAttribute.addAttributeID(expectedId2);
actualId1 = unknownAttributesAttribute.getAttribute(0);
actualId2 = unknownAttributesAttribute.getAttribute(1);
assertEquals("getAttribute() return value mismatch", expectedId1, actualId1);
assertEquals("getAttribute() return value mismatch", expectedId2, actualId2);
}
/**
* Add some attributes and test whether their number is properly calculated.
* Tests duplicate id handling as well.
*/
public void testGetAttributeCount() {
int expectedReturn = 5;
unknownAttributesAttribute.addAttributeID((char)21);
unknownAttributesAttribute.addAttributeID((char)22);
unknownAttributesAttribute.addAttributeID((char)23);
unknownAttributesAttribute.addAttributeID((char)24);
unknownAttributesAttribute.addAttributeID((char)25);
unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored
int actualReturn = unknownAttributesAttribute.getAttributeCount();
assertEquals("getAttributeCount did not return the expected value",
expectedReturn, actualReturn);
}
/**
* Same as testGetAttributeID, only attribute attributes are extracted
* through the getAttributes()'s iterator.
*/
public void testGetAttributes() {
char expectedId1 = 20;
char expectedId2 = 21;
char actualId1;
char actualId2;
unknownAttributesAttribute.addAttributeID(expectedId1);
unknownAttributesAttribute.addAttributeID(expectedId2);
Iterator iterator = unknownAttributesAttribute.getAttributes();
actualId1 = ((Character)iterator.next()).charValue();
actualId2 = ((Character)iterator.next()).charValue();;
assertEquals("getAttributes() return value mismatch", expectedId1, actualId1);
assertEquals("getAttributes() return value mismatch", expectedId2, actualId2);
}
/**
* Adds a fixed number of attributes and checks data length accordingly.
* Test is first performed for an odd number of attributes and then again
* (after adding another attribute id). Both results should be the same.
*/
public void testGetDataLength() {
char expectedReturn = 8;
unknownAttributesAttribute.addAttributeID((char)20);
unknownAttributesAttribute.addAttributeID((char)21);
unknownAttributesAttribute.addAttributeID((char)22);
char actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals("Incorrect testGetDataLength() return value",
expectedReturn, actualReturn);
unknownAttributesAttribute.addAttributeID((char)23);
actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals("Incorrect testGetDataLength() return value",
expectedReturn, actualReturn);
}
/**
* Tests whether getName returns a relevant name.
*/
public void testGetName() {
String expectedReturn = "UNKNOWN-ATTRIBUTES";
String actualReturn = unknownAttributesAttribute.getName();
assertEquals("getName() return", expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,134 @@
/*
* Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* Tests the username attribute class.
* <p>Organization Network Research Team, Louis Pasteur University</p>
* @author Emil Ivov
* @author Sebastien Vincent
*/
public class UsernameAttributeTest extends TestCase
{
private UsernameAttribute usernameAttribute = null;
MsgFixture msgFixture = null;
String usernameValue = "username";
byte[] attributeBinValue = new byte[]{
(byte)(UsernameAttribute.USERNAME>>8),
(byte)(UsernameAttribute.USERNAME & 0x00FF),
0, (byte)usernameValue.length(),
'u', 's', 'e', 'r', 'n', 'a', 'm','e'};
protected void setUp() throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
usernameAttribute = new UsernameAttribute();
usernameAttribute.setUsername(usernameValue.getBytes());
msgFixture.setUp();
}
protected void tearDown() throws Exception
{
usernameAttribute = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Tests decoding of the username attribute.
* @throws StunException upon a failure
*/
public void testDecodeAttributeBody() throws StunException
{
char offset = 0;
UsernameAttribute decoded = new UsernameAttribute();
char length = (char)usernameValue.length();
decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length);
//username value
assertEquals( "decode failed", usernameAttribute, decoded);
}
/**
* Tests the encode method
*/
public void testEncode()
{
assertTrue("encode failed",
Arrays.equals(usernameAttribute.encode(),
attributeBinValue));
}
/**
* Test Equals
*/
public void testEquals()
{
UsernameAttribute usernameAttribute2 = new UsernameAttribute();
usernameAttribute2.setUsername(usernameValue.getBytes());
//test positive equals
assertEquals("testequals failed", usernameAttribute, usernameAttribute2);
//test negative equals
usernameAttribute2 = new UsernameAttribute();
usernameAttribute2.setUsername("some other username".getBytes());
//test positive equals
assertFalse("testequals failed",
usernameAttribute.equals(usernameAttribute2));
//test null equals
assertFalse("testequals failed",
usernameAttribute.equals(null));
}
/**
* Tests extracting data length
*/
public void testGetDataLength()
{
char expectedReturn = (char)usernameValue.length();
char actualReturn = usernameAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
}
/**
* Tests getting the name
*/
public void testGetName()
{
String expectedReturn = "USERNAME";
String actualReturn = usernameAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
}
public void testSetGetUsername()
{
byte[] expectedReturn = usernameValue.getBytes();
UsernameAttribute att = new UsernameAttribute();
att.setUsername(expectedReturn);
byte[] actualReturn = att.getUsername();
assertTrue("username setter or getter failed",
Arrays.equals( expectedReturn,
actualReturn));
}
}

View File

@ -0,0 +1,103 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.attribute;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
/**
* <p>Organization: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class XorOnlyTest extends TestCase
{
private XorOnlyAttribute xorOnly = null;
private MsgFixture msgFixture = null;
protected void setUp() throws Exception
{
super.setUp();
xorOnly = new XorOnlyAttribute();
msgFixture = new MsgFixture();
}
protected void tearDown() throws Exception
{
xorOnly = null;
msgFixture = null;
super.tearDown();
}
/**
* Just makes sure that no exceptions are thrown when calling it as the
* decode method doesn't do anything in the XorOnly att.
* @throws StunException if sth happens
*/
public void testDecodeAttributeBody() throws StunException
{
byte[] attributeValue = new byte[]{};
char offset = 0;
char length = 0;
xorOnly.decodeAttributeBody(attributeValue, offset, length);
}
/**
* Test encoding XorOnly attributes.
*/
public void testEncode()
{
byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8,
Attribute.XOR_ONLY&0x00FF,
0, 0};
byte[] actualReturn = xorOnly.encode();
assertTrue("XorOnly failed to encode",
Arrays.equals( expectedReturn, actualReturn));
}
/**
* Test positive and negative XorOnly.equals() returns
* @throws Exteption if decoding fails
*/
public void testEquals() throws Exception
{
XorOnlyAttribute xor2 = new XorOnlyAttribute();
assertEquals("equals() failes for XorOnly", xorOnly, xor2);
MappedAddressAttribute maatt = new MappedAddressAttribute();
maatt.decodeAttributeBody( msgFixture.mappedAddress,
(char) 0,
(char) msgFixture.mappedAddress.length );
assertFalse("equals failed to see a difference", xorOnly.equals(maatt));
assertFalse("equals failed for null", xorOnly.equals(null));
}
/**
* Makes sure the data langth is 0
*/
public void testGetDataLength()
{
char expectedReturn = 0;
char actualReturn = xorOnly.getDataLength();
assertEquals("data length was not 0", expectedReturn, actualReturn);
}
/**
* Verifies the name (do we really need this?).
*/
public void testGetName()
{
String expectedReturn = "XOR-ONLY";
String actualReturn = xorOnly.getName();
assertEquals("Is name correct", expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,167 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.message;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
import junit.framework.*;
public class MessageFactoryTest extends TestCase {
private MessageFactory messageFactory = null;
private MsgFixture msgFixture;
public MessageFactoryTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
messageFactory = new MessageFactory();
msgFixture = new MsgFixture();
msgFixture.setUp();
}
protected void tearDown() throws Exception {
messageFactory = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
public void testCreateBindingErrorResponse() throws StunException {
char errorCode = 400;
Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
Attribute errorCodeAtt = AttributeFactory.createErrorCodeAttribute(errorCode);
expectedReturn.addAttribute(errorCodeAtt);
Message actualReturn = messageFactory.createBindingErrorResponse(errorCode);
assertEquals("return value", expectedReturn, actualReturn);
}
public void testCreateBindingErrorResponse1() throws StunException {
char errorCode = 400;
String reasonPhrase = "Bad Request";
Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
Attribute errorCodeAtt = AttributeFactory.createErrorCodeAttribute(errorCode, reasonPhrase);
expectedReturn.addAttribute(errorCodeAtt);
Message actualReturn = messageFactory.createBindingErrorResponse(errorCode, reasonPhrase);
assertEquals("Failed to create an error code attribute.", expectedReturn, actualReturn);
}
public void testCreateBindingErrorResponseUnknownAttributes()
throws StunException
{
char errorCode = 420;
char[] unknownAttributes = new char[]{21, 22, 23};
//create a message manually
Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
Attribute errorCodeAtt = AttributeFactory.createErrorCodeAttribute(errorCode);
((ErrorCodeAttribute)errorCodeAtt).setReasonPhrase(ErrorCodeAttribute.getDefaultReasonPhrase(errorCode));
expectedReturn.addAttribute(errorCodeAtt);
UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++) {
unknownAtts.addAttributeID(unknownAttributes[i]);
}
expectedReturn.addAttribute(unknownAtts);
//create the same message using the factory
Message actualReturn = messageFactory.createBindingErrorResponseUnknownAttributes(unknownAttributes);
//compare
assertEquals("return value", expectedReturn, actualReturn);
}
public void testCreateBindingErrorResponseUnknownAttributes1()
throws StunException
{
char errorCode = 420;
String reasonPhrase = "UnknwonAttributes";
char[] unknownAttributes = new char[]{21, 22, 23};
Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
Attribute errorCodeAtt = AttributeFactory.createErrorCodeAttribute(
errorCode, reasonPhrase);
expectedReturn.addAttribute(errorCodeAtt);
UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++)
{
unknownAtts.addAttributeID(unknownAttributes[i]);
}
expectedReturn.addAttribute(unknownAtts);
Message actualReturn = messageFactory.createBindingErrorResponseUnknownAttributes(
reasonPhrase, unknownAttributes);
assertEquals("return value", expectedReturn, actualReturn);
}
public void testCreateBindingRequest() throws StunException {
Request bindingRequest = new Request();
Request expectedReturn = bindingRequest;
bindingRequest.setMessageType(Message.BINDING_REQUEST);
/*
Attribute changeRequest = AttributeFactory.createChangeRequestAttribute(
msgFixture.CHANGE_IP_FLAG_1, msgFixture.CHANGE_PORT_FLAG_1);
bindingRequest.addAttribute(changeRequest);
*/
Request actualReturn = messageFactory.createBindingRequest();
assertEquals("return value", expectedReturn, actualReturn);
}
public void testCreateBindingResponse()
throws StunException
{
Response bindingResponse = new Response();
bindingResponse.setMessageType(Message.BINDING_RESPONSE);
Attribute mappedAddress = AttributeFactory.createMappedAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,msgFixture.ADDRESS_ATTRIBUTE_PORT));
bindingResponse.addAttribute(mappedAddress);
Attribute sourceAddress = AttributeFactory.createSourceAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_2, msgFixture.ADDRESS_ATTRIBUTE_PORT_2));
bindingResponse.addAttribute(sourceAddress);
Attribute changedAddress = AttributeFactory.
createChangedAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3, msgFixture.ADDRESS_ATTRIBUTE_PORT_3));
bindingResponse.addAttribute(changedAddress);
Message expectedReturn = bindingResponse;
Message actualReturn = messageFactory.createBindingResponse(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS, msgFixture.ADDRESS_ATTRIBUTE_PORT),
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_2,msgFixture.ADDRESS_ATTRIBUTE_PORT_2),
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,msgFixture.ADDRESS_ATTRIBUTE_PORT_3));
assertEquals("return value", expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,271 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.message;
import junit.framework.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
public class MessageTest extends TestCase {
private Message bindingRequest = null;
private Message bindingResponse = null;
private Message bindingErrorResponse = null;
private MappedAddressAttribute mappedAddress = null;
private SourceAddressAttribute sourceAddress = null;
private ChangedAddressAttribute changedAddress = null;
private ChangeRequestAttribute changeRequest = null;
private ErrorCodeAttribute errorCodeAttribute = null;
private UnknownAttributesAttribute unknownAttributesAttribute = null;
private MsgFixture msgFixture;
protected void setUp() throws Exception {
super.setUp();
msgFixture = new MsgFixture();
msgFixture.setUp();
//binding request
bindingRequest = new Request();
bindingRequest.setMessageType(Message.BINDING_REQUEST);
changeRequest = AttributeFactory.createChangeRequestAttribute(
msgFixture.CHANGE_IP_FLAG_1, msgFixture.CHANGE_PORT_FLAG_1);
bindingRequest.addAttribute(changeRequest);
bindingRequest.setTransactionID(msgFixture.TRANSACTION_ID);
//binding response
bindingResponse = new Response();
bindingResponse.setMessageType(Message.BINDING_RESPONSE);
mappedAddress = AttributeFactory.createMappedAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS, msgFixture.ADDRESS_ATTRIBUTE_PORT));
bindingResponse.addAttribute(mappedAddress);
sourceAddress = AttributeFactory.createSourceAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_2, msgFixture.ADDRESS_ATTRIBUTE_PORT_2));
bindingResponse.addAttribute(sourceAddress);
changedAddress = AttributeFactory.createChangedAddressAttribute(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,msgFixture.ADDRESS_ATTRIBUTE_PORT_3));
bindingResponse.addAttribute(changedAddress);
bindingResponse.setTransactionID(msgFixture.TRANSACTION_ID);
}
protected void tearDown() throws Exception
{
bindingRequest = null;
bindingResponse = null;
bindingErrorResponse = null;
mappedAddress = null;
sourceAddress = null;
changedAddress = null;
changeRequest = null;
errorCodeAttribute = null;
unknownAttributesAttribute = null;
changeRequest = null;
msgFixture.tearDown();
msgFixture = null;
super.tearDown();
}
/**
* Adds and gets an attribute and test that they are the same then adds a
* another attribute (same typ different value) and veriies that the first
* one is properly replaced.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testAddAndGetAttribute() throws StunException {
Response message = new Response();
message.setMessageType(Message.BINDING_RESPONSE);
message.addAttribute(mappedAddress);
Attribute getResult = null;
getResult = message.getAttribute(mappedAddress.getAttributeType());
assertEquals("Originally added attribute did not match the one retrned "
+"by getAttribute()",
mappedAddress,
getResult);
//do it again
message.addAttribute(sourceAddress);
getResult = message.getAttribute(sourceAddress.getAttributeType());
assertEquals("The second attribute could not be extracted.",
sourceAddress,
getResult);
}
/**
* Decodes a bindingRequest and then a binding response and checks whether
* they match the corresponding objects.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEncode()
throws StunException
{
//Binding Request
byte[] expectedReturn = msgFixture.bindingRequest;
byte[] actualReturn = bindingRequest.encode();
assertTrue("A binding request was not properly encoded",
Arrays.equals( expectedReturn, actualReturn ) );
//Binding Response
expectedReturn = msgFixture.bindingResponse;
actualReturn = bindingResponse.encode();
assertTrue("A binding response was not properly encoded",
Arrays.equals( expectedReturn, actualReturn ) );
}
/**
* Encodes a bindingRequest and then a binding response and checks whether
* they match the corresponding binary arrays.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testDecode()
throws StunException
{
//Binding Request
Message expectedReturn = bindingRequest;
Message actualReturn = Message.decode(msgFixture.bindingRequest,
(char)0,
(char)msgFixture.bindingRequest.length);
assertEquals("A binding request was not properly decoded",
expectedReturn, actualReturn );
//Binding Response
expectedReturn = bindingResponse;
actualReturn = Message.decode(msgFixture.bindingResponse,
(char)0,
(char)msgFixture.bindingResponse.length);
assertEquals("A binding response was not properly decoded",
expectedReturn, actualReturn );
}
/**
* Tests the equals method against a null, a different and an identical
* object.
*
* @throws StunException java.lang.Exception if we fail
*/
public void testEquals()
throws StunException
{
Object target = null;
boolean expectedReturn = false;
boolean actualReturn = bindingRequest.equals(target);
assertEquals("Equals failed against a null target", expectedReturn, actualReturn);
actualReturn = bindingResponse.equals(target);
assertEquals("Equals failed against a null target", expectedReturn, actualReturn);
//different
actualReturn = bindingRequest.equals(bindingResponse);
assertEquals("Equals failed against a different target", expectedReturn, actualReturn);
actualReturn = bindingResponse.equals(bindingRequest);
assertEquals("Equals failed against a different target", expectedReturn, actualReturn);
//same
expectedReturn = true;
//Create a binding request with the same attributes as this.bindingRequest
Request binReqTarget = new Request();
binReqTarget.setMessageType(Message.BINDING_REQUEST);
binReqTarget.addAttribute(changeRequest);
actualReturn = bindingRequest.equals(binReqTarget);
assertEquals("Equals failed against an equal target", expectedReturn, actualReturn);
//Create a binding response with the same attributes as this.bindingRequest
Response binResTarget = new Response();
binResTarget.setMessageType(Message.BINDING_RESPONSE);
binResTarget.addAttribute(mappedAddress);
binResTarget.addAttribute(sourceAddress);
binResTarget.addAttribute(changedAddress);
actualReturn = bindingResponse.equals(binResTarget);
assertEquals("Equals failed against a different target", expectedReturn, actualReturn);
}
/**
* Tests whether attributes are properly counted
*/
public void testGetAttributeCount() {
int expectedReturn = 1;
int actualReturn = bindingRequest.getAttributeCount();
assertEquals("getAttributeCount failed for a bindingRequest",
expectedReturn, actualReturn);
expectedReturn = 3;
actualReturn = bindingResponse.getAttributeCount();
assertEquals("getAttributeCount failed for a bindingRequest",
expectedReturn, actualReturn);
}
/**
* Test whether attributes are properly removed.
*/
public void testRemoveAttribute() {
bindingRequest.removeAttribute(changeRequest.getAttributeType());
assertNull("An attribute was still in the request after being removed",
bindingRequest.getAttribute(changeRequest.getAttributeType()));
//test count
int expectedReturn = 0;
int actualReturn = bindingRequest.getAttributeCount();
assertEquals("Attribute count did not change after removing an attribute",
expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,62 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stack;
import java.net.*;
import java.io.IOException;
public class DatagramCollector
implements Runnable
{
DatagramPacket receivedPacket = null;
DatagramSocket sock = null;
public DatagramCollector()
{
}
public void run()
{
try
{
sock.receive(receivedPacket);
}
catch (IOException ex)
{
receivedPacket = null;
}
}
public void startListening(DatagramSocket sock)
{
this.sock = sock;
receivedPacket = new DatagramPacket(new byte[4096], 4096);
new Thread(this).start();
//give the guy a chance to start
try
{
Thread.sleep(200);
}
catch (InterruptedException ex)
{
}
}
public DatagramPacket collectPacket()
{
//recycle
DatagramPacket returnValue = receivedPacket;
receivedPacket = null;
sock = null;
//return
return returnValue;
}
}

View File

@ -0,0 +1,339 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stack;
import junit.framework.*;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.DatagramPacket;
import java.io.*;
import java.util.Arrays;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* All unit stack tests should be provided later. I just don't have the time now.
*
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
public class ShallowStackTest extends TestCase {
private static final Logger logger =
Logger.getLogger(ShallowStackTest.class.getName());
private StunProvider stunProvider = null;
private StunStack stunStack = null;
private MsgFixture msgFixture = null;
private TransportAddress stun4jAddressOfDummyImpl = null;
private InetSocketAddress socketAddressOfStun4jStack = null;
private DatagramCollector dgramCollector = new DatagramCollector();
private NetAccessPointDescriptor apDescriptor = null;
private DatagramSocket dummyImplSocket = null;
private DatagramPacket bindingRequestPacket
= new DatagramPacket(new byte[4096], 4096);
public ShallowStackTest(String name) {
super(name);
}
protected void setUp()
throws Exception
{
super.setUp();
msgFixture = new MsgFixture();
msgFixture.setUp();
//Addresses
stun4jAddressOfDummyImpl =
new TransportAddress(InetAddress.getByName("127.0.0.1"), 6000);
socketAddressOfStun4jStack =
new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 5000);
//init the stack
stunStack = StunStack.getInstance();
stunProvider = stunStack.getProvider();
//access point
apDescriptor = new NetAccessPointDescriptor(
new TransportAddress(InetAddress.getByName("127.0.0.1"), 5000));
stunStack.installNetAccessPoint(apDescriptor);
//init the phoney stack
dummyImplSocket = new DatagramSocket( 6000 );
}
protected void tearDown()
throws Exception
{
msgFixture.tearDown();
dummyImplSocket.close();
msgFixture = null;
super.tearDown();
}
/**
* Sends a binding request using the stack to a phoney socket, and verifies
* that it is received and that the contents of the datagram corresponds to
* the request that was sent.
*
* @throws java.lang.Exception if we fail
*/
public void testSendRequest()
throws Exception
{
Request bindingRequest = MessageFactory.createBindingRequest();
dgramCollector.startListening(dummyImplSocket);
stunProvider.sendRequest(bindingRequest,
stun4jAddressOfDummyImpl,
apDescriptor,
new SimpleResponseCollector());
//wait for its arrival
try{ Thread.sleep(500); }catch (InterruptedException ex){}
DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not properly send a Binding Request",
(receivedPacket.getLength() > 0));
Request receivedRequest =
(Request)Request.decode(receivedPacket.getData(),
(char)0,
(char)receivedPacket.getLength());
assertEquals("The received request did not match the "
+"one that was sent.",
bindingRequest, //expected
receivedRequest); // actual
//wait for retransmissions
dgramCollector.startListening(dummyImplSocket);
try{ Thread.sleep(1000); }catch (InterruptedException ex){}
receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not retransmit a Binding Request",
(receivedPacket.getLength() > 0));
receivedRequest = (Request)Request.decode(
receivedPacket.getData(),
(char)0,
(char)receivedPacket.getLength());
assertEquals("The retransmitted request did not match the original.",
bindingRequest, //expected
receivedRequest); // actual
}
/**
* Sends a byte array containing a bindingRequest, through a datagram socket
* and verifies that the stack receives it alright.
*
* @throws java.lang.Exception if we fail
*/
public void testReceiveRequest()
throws Exception
{
SimpleRequestCollector requestCollector = new SimpleRequestCollector();
stunProvider.addRequestListener(requestCollector);
dummyImplSocket.send(new DatagramPacket(
msgFixture.bindingRequest2,
msgFixture.bindingRequest2.length,
socketAddressOfStun4jStack));
//wait for the packet to arrive
try{ Thread.sleep(500); }catch (InterruptedException ex){}
Request collectedRequest = requestCollector.collectedRequest;
assertNotNull("No request has been received", collectedRequest);
byte expectedReturn[] = msgFixture.bindingRequest2;
byte actualReturn[] = collectedRequest.encode();
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
}
/**
* Sends a byte array containing a bindingRequest, through a datagram socket,
* verifies that the stack receives it properly and then sends a response
* using the stack. Finally, the response is expected at the other end and
* compared with the sent one.
*
* @throws java.lang.Exception if we fail
*/
public void testSendResponse()
throws Exception
{
//---------- send & receive the request --------------------------------
SimpleRequestCollector requestCollector = new SimpleRequestCollector();
stunProvider.addRequestListener(requestCollector);
dummyImplSocket.send(new DatagramPacket(
msgFixture.bindingRequest,
msgFixture.bindingRequest.length,
socketAddressOfStun4jStack));
//wait for the packet to arrive
try{
synchronized(this)
{
wait(500);
}
}catch (InterruptedException ex){}
Request collectedRequest = requestCollector.collectedRequest;
byte expectedReturn[] = msgFixture.bindingRequest;
byte actualReturn[] = collectedRequest.encode();
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
//---------- create the response ---------------------------------------
Response bindingResponse = MessageFactory.createBindingResponse(
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
msgFixture.ADDRESS_ATTRIBUTE_PORT ),
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_2,
msgFixture.ADDRESS_ATTRIBUTE_PORT_2),
new TransportAddress( msgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,
msgFixture.ADDRESS_ATTRIBUTE_PORT_3));
//---------- send & receive the response -------------------------------
dgramCollector.startListening(dummyImplSocket);
stunProvider.sendResponse(collectedRequest.getTransactionID(),
bindingResponse,
apDescriptor,
stun4jAddressOfDummyImpl);
//wait for its arrival
try{ Thread.sleep(500); }catch (InterruptedException ex){}
DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not properly send a Binding Request",
(receivedPacket.getLength() > 0));
Response receivedResponse =
(Response) Response.decode(receivedPacket.getData(),
(char) 0,
(char) receivedPacket.getLength());
assertEquals(
"The received request did not match the one that was sent.",
bindingResponse, //expected
receivedResponse); // actual
}
public void testReceiveResponse()
throws Exception
{
SimpleResponseCollector collector = new SimpleResponseCollector();
//--------------- send the original request ----------------------------
Request bindingRequest = MessageFactory.createBindingRequest();
stunProvider.sendRequest(bindingRequest,
stun4jAddressOfDummyImpl,
apDescriptor,
collector);
//wait for its arrival
try{ Thread.sleep(500); }catch (InterruptedException ex){}
//create the right response
byte response[] = new byte[msgFixture.bindingResponse.length];
System.arraycopy(msgFixture.bindingResponse, 0, response, 0,
response.length);
//Set the valid tid.
System.arraycopy(bindingRequest.getTransactionID(),
0,
response,
8,
12);
//send the response
dummyImplSocket.send(new DatagramPacket(response,
response.length,
socketAddressOfStun4jStack));
//wait for the packet to arrive
try{ Thread.sleep(500); }catch (InterruptedException ex){}
Response collectedResponse = collector.collectedResponse;
byte expectedReturn[] = response;
byte actualReturn[] = collectedResponse.encode();
assertTrue("Received request was not the same as the one that was sent",
Arrays.equals(expectedReturn, actualReturn));
}
//--------------------------------------- listener implementations ---------
public class SimpleResponseCollector
implements ResponseCollector
{
Response collectedResponse = null;
public void processResponse(StunMessageEvent evt)
{
collectedResponse = (Response)evt.getMessage();
logger.info("Received response.");
}
public void processTimeout()
{
logger.info("Timeout");
}
}
public class SimpleRequestCollector
implements RequestListener
{
private Request collectedRequest = null;
public void requestReceived(StunMessageEvent evt)
{
collectedRequest = (Request)evt.getMessage();
stunProvider.removeRequestListener(this);
logger.info("Received request.");
}
}
/*
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new ShallowStackTest(
"testSendResponse"));
suite.addTest(new ShallowStackTest(
"testSendResponse"));
suite.addTest(new ShallowStackTest(
"testSendResponse"));
suite.addTest(new ShallowStackTest(
"testSendResponse"));
return suite;
}
*/
}

View File

@ -0,0 +1,134 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import java.util.Vector;
import java.util.logging.*;
import java.io.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* This class implements a programmable STUN server that sends predefined
* sequences of responses. It may be used to test whether a STUN client
* behaves correctly in different use cases.
*
*
* <p>Organisation: <p> Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
* @author Emil Ivov
* @version 0.1
*/
public class ResponseSequenceServer
implements RequestListener
{
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;
private StunProvider stunProvider = null;
private TransportAddress serverAddress = null;
private NetAccessPointDescriptor apDescriptor = null;
public ResponseSequenceServer(TransportAddress bindAddress)
{
this.serverAddress = bindAddress;
}
/**
* Initializes the underlying stack
* @throws StunException if something else fails
* @throws IOException if we fail to bind a local socket.
*/
public void start()
throws IOException, StunException
{
stunStack = StunStack.getInstance();
stunProvider = stunStack.getProvider();
apDescriptor = new NetAccessPointDescriptor(serverAddress);
stunStack.installNetAccessPoint(apDescriptor);
stunProvider.addRequestListener(apDescriptor, this);
}
/**
* Resets the server (deletes the sequence and stops the stack)
*/
public void shutDown()
{
messageSequence.removeAllElements();
stunStack = null;
stunProvider = null;
}
/**
* Adds the specified response to this sequence or marks a pause (i.e. do
* not respond) if response is null.
* @param response the response to add or null to mark a pause
*/
public void addMessage(Response response)
{
if (response == null)
{
//leave a mark to skip a message
messageSequence.add(new Boolean(false));
}
else
messageSequence.add(response);
}
/**
* Completely ignores the event that is passed and just sends the next
* message from the sequence - or does nothing if there's something
* different from a Response on the current position.
* @param evt the event being dispatched
*/
public void requestReceived(StunMessageEvent evt)
{
if(messageSequence.isEmpty())
return;
Object obj = messageSequence.remove(0);
if( !(obj instanceof Response) )
return;
Response res = (Response)obj;
try
{
stunProvider.sendResponse(evt.getMessage().getTransactionID(),
res,
apDescriptor,
evt.getRemoteAddress());
}
catch (Exception ex)
{
logger.log(Level.WARNING, "failed to send a response", ex);
}
}
/**
* Returns a string representation of this Server.
* @return the ip address and port where this server is bound
*/
public String toString()
{
return serverAddress == null?"null":serverAddress.toString();
}
}

View File

@ -0,0 +1,284 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import junit.framework.*;
import java.io.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stunclient.*;
/**
* 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
* operations for IPv4/IPv6 and mixed environments.
*
* <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class StunAddressDiscovererTest
extends TestCase
{
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private TransportAddress discovererAddress = new TransportAddress("127.0.0.1", 15555);
private ResponseSequenceServer responseServer = null;
private TransportAddress responseServerAddress
= new TransportAddress("127.0.0.1", 19999);
private TransportAddress mappedClientAddress
= new TransportAddress("212.56.4.10", 15612);
private TransportAddress mappedClientAddressPort2
= new TransportAddress("212.56.4.10", 15611);
public StunAddressDiscovererTest(String name)
throws StunException
{
super(name);
}
protected void setUp() throws Exception {
super.setUp();
responseServer = new ResponseSequenceServer(responseServerAddress);
stunAddressDiscoverer
= new NetworkConfigurationDiscoveryProcess(discovererAddress,
responseServerAddress);
stunAddressDiscoverer.start();
responseServer.start();
}
protected void tearDown() throws Exception {
responseServer.shutDown();
stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null;
super.tearDown();
}
/**
* Performs a test where no responces 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? ).
*/
public void testRecognizeBlockedUDP()
throws Exception
{
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.UDP_BLOCKING_FIREWALL);
expectedReturn.setPublicAddress(null);
StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a "
+"no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeSymmetricNat() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddressPort2,
responseServerAddress,
responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizePortRestrictedCone()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse4 = null;
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
responseServer.addMessage(testIResponse4);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.PORT_RESTRICTED_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeRestrictedCone() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse4 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
responseServer.addMessage(testIResponse4);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.RESTRICTED_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeFullCone()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.FULL_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a UDP Symmetric Firewall.
*
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeUdpSymmetricFirewall()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_UDP_FIREWALL);
expectedReturn.setPublicAddress(discovererAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Open Internet.
*
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeOpenInternet()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.OPEN_INTERNET);
expectedReturn.setPublicAddress(discovererAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,235 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stunclient.*;
import junit.framework.*;
/**
* Makes basic stun tests for cases where local network addresses and the public
* NAT address are using different IP versions. (e.g. Local addresses are v4
* public NAT address is v6 or vice versa)
*
*
* 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
* operations for IPv4/IPv6 and mixed environments.
*
* <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class StunAddressDiscovererTest_v4v6 extends TestCase {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6
= null;
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4
= null;
private TransportAddress discovererAddress_v4
= new TransportAddress("127.0.0.1", 17555);
private TransportAddress discovererAddress_v6
= new TransportAddress("::1", 17555);
private ResponseSequenceServer responseServer_v6 = null;
private ResponseSequenceServer responseServer_v4 = null;
private TransportAddress responseServerAddress_v6
= new TransportAddress("::1", 21999);
private TransportAddress responseServerAddress_v4
= new TransportAddress("127.0.0.1", 21999);
private TransportAddress mappedClientAddress_v6
= new TransportAddress("2001:660:4701:1001:ff::1", 17612);
private TransportAddress mappedClientAddress_v6_Port2
= new TransportAddress("2001:660:4701:1001:ff::1", 17611);
private TransportAddress mappedClientAddress_v4
= new TransportAddress("130.79.99.55", 17612);
private TransportAddress mappedClientAddress_v4_Port2
= new TransportAddress("130.79.99.55", 17611);
public StunAddressDiscovererTest_v4v6(String name)
throws StunException
{
super(name);
}
protected void setUp() throws Exception {
super.setUp();
responseServer_v6
= new ResponseSequenceServer(responseServerAddress_v6);
responseServer_v4
= new ResponseSequenceServer(responseServerAddress_v4);
stunAddressDiscoverer_v6 = new NetworkConfigurationDiscoveryProcess(
discovererAddress_v6, responseServerAddress_v6);
stunAddressDiscoverer_v4 = new NetworkConfigurationDiscoveryProcess(
discovererAddress_v4, responseServerAddress_v4);
stunAddressDiscoverer_v6.start();
stunAddressDiscoverer_v4.start();
responseServer_v6.start();
responseServer_v4.start();
}
protected void tearDown() throws Exception {
responseServer_v6.shutDown();
responseServer_v4.shutDown();
stunAddressDiscoverer_v6.shutDown();
stunAddressDiscoverer_v6 = null;
stunAddressDiscoverer_v4.shutDown();
stunAddressDiscoverer_v4 = null;
//give the sockets the time to clear out
Thread.currentThread().sleep(1000);
super.tearDown();
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeSymmetricNat_Local_v6_Public_v4()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress_v4,
responseServerAddress_v6,
responseServerAddress_v6);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress_v4_Port2,
responseServerAddress_v6,
responseServerAddress_v6);
responseServer_v6.addMessage(testIResponse1);
responseServer_v6.addMessage(testIResponse2);
responseServer_v6.addMessage(testIResponse3);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_NAT);
expectedReturn.setPublicAddress(mappedClientAddress_v4);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v6.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a v4-v6 sym env.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress_v6,
responseServerAddress_v4,
responseServerAddress_v4);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress_v6_Port2,
responseServerAddress_v4,
responseServerAddress_v4);
responseServer_v4.addMessage(testIResponse1);
responseServer_v4.addMessage(testIResponse2);
responseServer_v4.addMessage(testIResponse3);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_NAT);
expectedReturn.setPublicAddress(mappedClientAddress_v6);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v4.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress_v4,
responseServerAddress_v6,
responseServerAddress_v6);
Response testIResponse2 = MessageFactory.createBindingResponse(
mappedClientAddress_v4,
responseServerAddress_v6,
responseServerAddress_v6);
responseServer_v6.addMessage(testIResponse1);
responseServer_v6.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.FULL_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress_v4);
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress_v6,
responseServerAddress_v4,
responseServerAddress_v4);
Response testIResponse2 = MessageFactory.createBindingResponse(
mappedClientAddress_v6,
responseServerAddress_v4,
responseServerAddress_v4);
responseServer_v4.addMessage(testIResponse1);
responseServer_v4.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.FULL_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress_v6);
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
}

View File

@ -0,0 +1,286 @@
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.stunclient;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.stunclient.*;
import junit.framework.*;
/**
* 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
* operations for IPv4/IPv6 and mixed environments.
*
* <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov
*/
public class StunAddressDiscovererTest_v6 extends TestCase {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private TransportAddress discovererAddress = new TransportAddress("::1", 16555);
private ResponseSequenceServer responseServer = null;
private TransportAddress responseServerAddress = new TransportAddress("::1", 20999);
private TransportAddress mappedClientAddress
= new TransportAddress("2001:660:4701:1001:ff::1", 16612);
private TransportAddress mappedClientAddressPort2
= new TransportAddress("2001:660:4701:1001:ff::1", 16611);
public StunAddressDiscovererTest_v6(String name)
throws StunException
{
super(name);
}
protected void setUp() throws Exception {
super.setUp();
responseServer = new ResponseSequenceServer(responseServerAddress);
stunAddressDiscoverer
= new NetworkConfigurationDiscoveryProcess(
discovererAddress,
responseServerAddress);
stunAddressDiscoverer.start();
responseServer.start();
}
protected void tearDown() throws Exception {
responseServer.shutDown();
stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null;
super.tearDown();
}
/**
* Performs a test where no responces 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? ).
*/
public void testRecognizeBlockedUDP()
throws Exception
{
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.UDP_BLOCKING_FIREWALL);
expectedReturn.setPublicAddress(null);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT.
*
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeSymmetricNat()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddressPort2,
responseServerAddress,
responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a "
+"no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizePortRestrictedCone()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse4 = null;
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
responseServer.addMessage(testIResponse4);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.PORT_RESTRICTED_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for"
+" a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeRestrictedCone()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
Response testIResponse3 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse4 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
responseServer.addMessage(testIResponse3);
responseServer.addMessage(testIResponse4);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.RESTRICTED_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeFullCone() throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = MessageFactory.createBindingResponse(
mappedClientAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.FULL_CONE_NAT);
expectedReturn.setPublicAddress(mappedClientAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a UDP Symmetric Firewall.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeUdpSymmetricFirewall()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = null;
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.SYMMETRIC_UDP_FIREWALL);
expectedReturn.setPublicAddress(discovererAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
/**
* Performs a test where no responces are given the stun client so that
* it concludes it is behind a Open Internet.
* @throws Exception if anything goes wrong ( surprised? ).
*/
public void testRecognizeOpenInternet()
throws Exception
{
//define the server response sequence
Response testIResponse1 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
Response testIResponse2 = MessageFactory.createBindingResponse(
discovererAddress, responseServerAddress, responseServerAddress);
responseServer.addMessage(testIResponse1);
responseServer.addMessage(testIResponse2);
StunDiscoveryReport expectedReturn = new StunDiscoveryReport();
expectedReturn.setNatType(StunDiscoveryReport.OPEN_INTERNET);
expectedReturn.setPublicAddress(discovererAddress);
StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress();
assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
}
}

149
test/test/Ice.java Normal file
View File

@ -0,0 +1,149 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package test;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.ice.*;
/**
* Simple ice4j testing scenarios.
*
* @author Emil Ivov
*/
public class Ice
{
/**
* Runs the test
* @param args cmd line args
*
* @throws Throwable if bad stuff happens.
*/
public static void main(String[] args) throws Throwable
{
Agent agent = new Agent();
IceMediaStream stream = agent.createMediaStream("audio");
//rtp
Component rtpComp = agent.createComponent(
stream, Transport.UDP, 9090, 9090, 10000);
System.out.println("rtpComp:" + rtpComp);
//rtcpComp
Component rtcpComp = agent.createComponent(
stream, Transport.UDP, 9091, 9090, 10000);
System.out.println("rtcpComp:" + rtcpComp);
}
/**
* Runs the test
* @param args cmd line args
*
* @throws Throwable if bad stuff happens.
*/
public static void main2(String[] args) throws Throwable
{
//Agent agent = new Agent();
//IceMediaStream stream = agent.createMediaStream("audio");
//rtp
//Component rtpComp = stream.createComponent(Transport.UDP, 9090);
//rtcpComp
//Component rtcpComp = stream.createComponent(Transport.UDP, 9091);
// find a loopback interface
Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface iface = interfaces.nextElement();
System.out.println(iface.getName()
+ " isLoopback=" + isLoop(iface));
System.out.println(iface.getName()
+ " isUp=" + isUp(iface));
System.out.println(iface.getName()
+ " isVirtual=" + isVirtual(iface));
}
}
public static boolean isLoop(NetworkInterface iface)
{
try
{
Method method
= iface.getClass().getMethod("isLoopback", new Class[]{});
System.out.println("It works!");
return ((Boolean)method.invoke(iface, new Object[]{}))
.booleanValue();
}
catch(Throwable t)
{
//apparently we are not running in a JVM that supports the
//is Loopback method. we'll try another approach.
System.out.println("Doesn't work");
}
Enumeration<InetAddress> addresses = iface.getInetAddresses();
return addresses.hasMoreElements()
&& addresses.nextElement().isLoopbackAddress();
}
public static boolean isUp(NetworkInterface iface)
{
try
{
Method method
= iface.getClass().getMethod("isUp", new Class[]{});
System.out.println("It works!");
return ((Boolean)method.invoke(iface, new Object[]{}))
.booleanValue();
}
catch(Throwable t)
{
//apparently we are not running in a JVM that supports the
//is Loopback method. we'll try another approach.
System.out.println("Doesn't work");
}
return true;
}
public static boolean isVirtual(NetworkInterface iface)
{
try
{
Method method
= iface.getClass().getMethod("isVirtual", new Class[]{});
System.out.println("It works!");
return ((Boolean)method.invoke(iface, new Object[]{}))
.booleanValue();
}
catch(Throwable t)
{
//apparently we are not running in a JVM that supports the
//is Loopback method. we'll try another approach.
System.out.println("Doesn't work");
}
return false;
}
}