Fix line endings in PseudoTCP code
This commit is contained in:
parent
10b4e911ef
commit
da2194444c
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,172 +15,172 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public abstract class IceControlAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* The length of the data contained in this attribute
|
||||
*/
|
||||
static final char DATA_LENGTH_ICE_CONTROL = 8;
|
||||
|
||||
/**
|
||||
* The tie-breaker value stored in this attribute
|
||||
*/
|
||||
long tieBreaker;
|
||||
|
||||
/**
|
||||
* Indicates whether this is an <tt>ICE-CONTROLLING</tt> or an
|
||||
* <tt>ICE-CONTROLLED</tt> attribute.
|
||||
*/
|
||||
boolean isControlling;
|
||||
|
||||
/**
|
||||
* Constructs an ICE-CONTROLLING or an ICE-CONTROLLED attribute depending
|
||||
* on the value of <tt>isControlling</tt>.
|
||||
*
|
||||
* @param isControlling indicates the kind of attribute we are trying to
|
||||
* create
|
||||
*/
|
||||
IceControlAttribute(boolean isControlling)
|
||||
{
|
||||
super(isControlling ? ICE_CONTROLLING : ICE_CONTROLLED);
|
||||
this.isControlling = isControlling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this attribute's fields according to attributeValue array.
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's field
|
||||
* values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after
|
||||
* length)
|
||||
* @param length the length of the attribute data.
|
||||
*
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// array used to hold the intermediate long values reconstructed from
|
||||
// the attributeValue array
|
||||
|
||||
// Reading in the network byte order (Big-Endian)
|
||||
tieBreaker = ((attributeValue[offset++] & 0xffl) << 56)
|
||||
| ((attributeValue[offset++] & 0xffl) << 48)
|
||||
| ((attributeValue[offset++] & 0xffl) << 40)
|
||||
| ((attributeValue[offset++] & 0xffl) << 32)
|
||||
| ((attributeValue[offset++] & 0xffl) << 24)
|
||||
| ((attributeValue[offset++] & 0xffl) << 16)
|
||||
| ((attributeValue[offset++] & 0xffl) << 8)
|
||||
| (attributeValue[offset++] & 0xffl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
|
||||
|
||||
//Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
//Length
|
||||
binValue[2] = (byte)(getDataLength() >> 8);
|
||||
binValue[3] = (byte)(getDataLength() & 0x00FF);
|
||||
|
||||
//Tie-Breaker
|
||||
binValue[4] = (byte)((tieBreaker & 0xFF00000000000000L) >> 56);
|
||||
binValue[5] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48);
|
||||
binValue[6] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40);
|
||||
binValue[7] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32);
|
||||
binValue[8] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24);
|
||||
binValue[9] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16);
|
||||
binValue[10] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8);
|
||||
binValue[11] = (byte)( tieBreaker & 0x00000000000000FFL);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Attributes are considered equal when their
|
||||
* type, length, and all data are the same.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
*
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof IceControlAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
IceControlAttribute iceControlAtt = (IceControlAttribute)obj;
|
||||
if(iceControlAtt.getAttributeType() != getAttributeType()
|
||||
|| iceControlAtt.isControlling != isControlling
|
||||
|| iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL
|
||||
|| getTieBreaker() != iceControlAtt.getTieBreaker())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data length of this attribute
|
||||
*
|
||||
* @return the data length of this attribute
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_ICE_CONTROL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return isControlling ? "ICE-CONTROLLING" : "ICE-CONTROLLED";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the tie-breaker value.
|
||||
*
|
||||
* @param tieBreaker the the tie-breaker value
|
||||
*/
|
||||
public void setTieBreaker(long tieBreaker)
|
||||
{
|
||||
this.tieBreaker = tieBreaker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the tie-breaker.
|
||||
*
|
||||
* @return the value of the tie-breaker.
|
||||
*/
|
||||
public long getTieBreaker()
|
||||
{
|
||||
return tieBreaker;
|
||||
}
|
||||
}
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Emil Ivov
|
||||
*/
|
||||
public abstract class IceControlAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* The length of the data contained in this attribute
|
||||
*/
|
||||
static final char DATA_LENGTH_ICE_CONTROL = 8;
|
||||
|
||||
/**
|
||||
* The tie-breaker value stored in this attribute
|
||||
*/
|
||||
long tieBreaker;
|
||||
|
||||
/**
|
||||
* Indicates whether this is an <tt>ICE-CONTROLLING</tt> or an
|
||||
* <tt>ICE-CONTROLLED</tt> attribute.
|
||||
*/
|
||||
boolean isControlling;
|
||||
|
||||
/**
|
||||
* Constructs an ICE-CONTROLLING or an ICE-CONTROLLED attribute depending
|
||||
* on the value of <tt>isControlling</tt>.
|
||||
*
|
||||
* @param isControlling indicates the kind of attribute we are trying to
|
||||
* create
|
||||
*/
|
||||
IceControlAttribute(boolean isControlling)
|
||||
{
|
||||
super(isControlling ? ICE_CONTROLLING : ICE_CONTROLLED);
|
||||
this.isControlling = isControlling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this attribute's fields according to attributeValue array.
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's field
|
||||
* values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after
|
||||
* length)
|
||||
* @param length the length of the attribute data.
|
||||
*
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// array used to hold the intermediate long values reconstructed from
|
||||
// the attributeValue array
|
||||
|
||||
// Reading in the network byte order (Big-Endian)
|
||||
tieBreaker = ((attributeValue[offset++] & 0xffl) << 56)
|
||||
| ((attributeValue[offset++] & 0xffl) << 48)
|
||||
| ((attributeValue[offset++] & 0xffl) << 40)
|
||||
| ((attributeValue[offset++] & 0xffl) << 32)
|
||||
| ((attributeValue[offset++] & 0xffl) << 24)
|
||||
| ((attributeValue[offset++] & 0xffl) << 16)
|
||||
| ((attributeValue[offset++] & 0xffl) << 8)
|
||||
| (attributeValue[offset++] & 0xffl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
|
||||
|
||||
//Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
//Length
|
||||
binValue[2] = (byte)(getDataLength() >> 8);
|
||||
binValue[3] = (byte)(getDataLength() & 0x00FF);
|
||||
|
||||
//Tie-Breaker
|
||||
binValue[4] = (byte)((tieBreaker & 0xFF00000000000000L) >> 56);
|
||||
binValue[5] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48);
|
||||
binValue[6] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40);
|
||||
binValue[7] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32);
|
||||
binValue[8] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24);
|
||||
binValue[9] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16);
|
||||
binValue[10] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8);
|
||||
binValue[11] = (byte)( tieBreaker & 0x00000000000000FFL);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Attributes are considered equal when their
|
||||
* type, length, and all data are the same.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
*
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof IceControlAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
IceControlAttribute iceControlAtt = (IceControlAttribute)obj;
|
||||
if(iceControlAtt.getAttributeType() != getAttributeType()
|
||||
|| iceControlAtt.isControlling != isControlling
|
||||
|| iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL
|
||||
|| getTieBreaker() != iceControlAtt.getTieBreaker())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data length of this attribute
|
||||
*
|
||||
* @return the data length of this attribute
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_ICE_CONTROL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return isControlling ? "ICE-CONTROLLING" : "ICE-CONTROLLED";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the tie-breaker value.
|
||||
*
|
||||
* @param tieBreaker the the tie-breaker value
|
||||
*/
|
||||
public void setTieBreaker(long tieBreaker)
|
||||
{
|
||||
this.tieBreaker = tieBreaker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the tie-breaker.
|
||||
*
|
||||
* @return the value of the tie-breaker.
|
||||
*/
|
||||
public long getTieBreaker()
|
||||
{
|
||||
return tieBreaker;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,172 +15,172 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* This class is used to represent the PRIORITY attribute used for ICE processing
|
||||
* This attribute is not in the original specification of STUN
|
||||
* It is added as an extension to STUN to be used for ICE implementations
|
||||
*
|
||||
* PRIORITY attribute contains a 32 bit priority value
|
||||
* It is used in stun binding requests sent from ICE-Agents to their
|
||||
* peers
|
||||
*
|
||||
* @author Namal Senarathne
|
||||
*/
|
||||
public class PriorityAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* The length of the Data contained in the Priority Attribute
|
||||
*/
|
||||
private static final char DATA_LENGTH_PRIORITY = 4;
|
||||
|
||||
/**
|
||||
* The priority value specified in the attribute. An int should be enough
|
||||
* to store this value, but long is used, since candidate and candidate-pair
|
||||
* classes use long to store priority values
|
||||
*/
|
||||
private long priority = 0;
|
||||
|
||||
/**
|
||||
* Creates a priority attribute.
|
||||
*/
|
||||
public PriorityAttribute()
|
||||
{
|
||||
super(PRIORITY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs the priority value from the given byte array
|
||||
* and stores it in the 'long' variable
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's
|
||||
* field values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after length)
|
||||
* @param length the length of the binary array.
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
|
||||
// array used to hold the intermediate long values reconstructed from
|
||||
// the attributeValue array
|
||||
long[] values = new long[4];
|
||||
|
||||
// Reading in the network byte order (Big-Endian)
|
||||
values[0] = (long)((attributeValue[offset++] & 0xff) << 24);
|
||||
values[1] = (long)((attributeValue[offset++] & 0xff) << 16);
|
||||
values[2] = (long)((attributeValue[offset++] & 0xff) << 8);
|
||||
values[3] = (long)(attributeValue[offset++] & 0xff);
|
||||
|
||||
// reconstructing the priority value
|
||||
this.priority = values[0] | values[1] | values[2] | values[3];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
|
||||
|
||||
//Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
//Length
|
||||
binValue[2] = (byte)(getDataLength() >> 8);
|
||||
binValue[3] = (byte)(getDataLength() & 0x00FF);
|
||||
|
||||
//Priority
|
||||
binValue[4] = (byte)((priority & 0xFF000000L) >> 24);
|
||||
binValue[5] = (byte)((priority & 0x00FF0000L) >> 16);
|
||||
binValue[6] = (byte)((priority & 0x0000FF00L) >> 8);
|
||||
binValue[7] = (byte)(priority & 0x000000FFL);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Two attributes are considered equal when
|
||||
* they have the same type length and value.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (! (obj instanceof PriorityAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
PriorityAttribute att = (PriorityAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
|| (priority != att.priority))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
*
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_PRIORITY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "PRIORITY";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the priority specified in the PRIORITY Attribute
|
||||
*
|
||||
* @return long specifying the priority
|
||||
*/
|
||||
public long getPriority()
|
||||
{
|
||||
return priority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the priority of the PRIORITY Attribute with the specified value
|
||||
*
|
||||
* @param priority the long variable specifying the priority value
|
||||
*
|
||||
* @throws IllegalArgumentException if indicated priority value is illegal.
|
||||
*/
|
||||
public void setPriority(long priority)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
/* Priority must be between 1 and (2^31 - 1) */
|
||||
if(priority <= 0 || priority > 0x7FFFFFFFL)
|
||||
{
|
||||
throw new IllegalArgumentException("Priority must be " +
|
||||
"between 0 and (2**31 - 1)");
|
||||
}
|
||||
else
|
||||
this.priority = priority;
|
||||
}
|
||||
}
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* This class is used to represent the PRIORITY attribute used for ICE processing
|
||||
* This attribute is not in the original specification of STUN
|
||||
* It is added as an extension to STUN to be used for ICE implementations
|
||||
*
|
||||
* PRIORITY attribute contains a 32 bit priority value
|
||||
* It is used in stun binding requests sent from ICE-Agents to their
|
||||
* peers
|
||||
*
|
||||
* @author Namal Senarathne
|
||||
*/
|
||||
public class PriorityAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* The length of the Data contained in the Priority Attribute
|
||||
*/
|
||||
private static final char DATA_LENGTH_PRIORITY = 4;
|
||||
|
||||
/**
|
||||
* The priority value specified in the attribute. An int should be enough
|
||||
* to store this value, but long is used, since candidate and candidate-pair
|
||||
* classes use long to store priority values
|
||||
*/
|
||||
private long priority = 0;
|
||||
|
||||
/**
|
||||
* Creates a priority attribute.
|
||||
*/
|
||||
public PriorityAttribute()
|
||||
{
|
||||
super(PRIORITY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs the priority value from the given byte array
|
||||
* and stores it in the 'long' variable
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's
|
||||
* field values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after length)
|
||||
* @param length the length of the binary array.
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
|
||||
// array used to hold the intermediate long values reconstructed from
|
||||
// the attributeValue array
|
||||
long[] values = new long[4];
|
||||
|
||||
// Reading in the network byte order (Big-Endian)
|
||||
values[0] = (long)((attributeValue[offset++] & 0xff) << 24);
|
||||
values[1] = (long)((attributeValue[offset++] & 0xff) << 16);
|
||||
values[2] = (long)((attributeValue[offset++] & 0xff) << 8);
|
||||
values[3] = (long)(attributeValue[offset++] & 0xff);
|
||||
|
||||
// reconstructing the priority value
|
||||
this.priority = values[0] | values[1] | values[2] | values[3];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
|
||||
|
||||
//Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
//Length
|
||||
binValue[2] = (byte)(getDataLength() >> 8);
|
||||
binValue[3] = (byte)(getDataLength() & 0x00FF);
|
||||
|
||||
//Priority
|
||||
binValue[4] = (byte)((priority & 0xFF000000L) >> 24);
|
||||
binValue[5] = (byte)((priority & 0x00FF0000L) >> 16);
|
||||
binValue[6] = (byte)((priority & 0x0000FF00L) >> 8);
|
||||
binValue[7] = (byte)(priority & 0x000000FFL);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Two attributes are considered equal when
|
||||
* they have the same type length and value.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (! (obj instanceof PriorityAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if (obj == this)
|
||||
return true;
|
||||
|
||||
PriorityAttribute att = (PriorityAttribute) obj;
|
||||
if (att.getAttributeType() != getAttributeType()
|
||||
|| att.getDataLength() != getDataLength()
|
||||
|| (priority != att.priority))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
*
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_PRIORITY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "PRIORITY";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the priority specified in the PRIORITY Attribute
|
||||
*
|
||||
* @return long specifying the priority
|
||||
*/
|
||||
public long getPriority()
|
||||
{
|
||||
return priority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the priority of the PRIORITY Attribute with the specified value
|
||||
*
|
||||
* @param priority the long variable specifying the priority value
|
||||
*
|
||||
* @throws IllegalArgumentException if indicated priority value is illegal.
|
||||
*/
|
||||
public void setPriority(long priority)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
/* Priority must be between 1 and (2^31 - 1) */
|
||||
if(priority <= 0 || priority > 0x7FFFFFFFL)
|
||||
{
|
||||
throw new IllegalArgumentException("Priority must be " +
|
||||
"between 0 and (2**31 - 1)");
|
||||
}
|
||||
else
|
||||
this.priority = priority;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,126 +1,126 @@
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* This class implements the USE-CANDIDATE attribute
|
||||
* This attribute is an extension to the original STUN protocol
|
||||
* This is used only during an ICE implementation
|
||||
*
|
||||
* This attribute serves as only a flag, it does not have any data
|
||||
* so the data length is zero
|
||||
*/
|
||||
public class UseCandidateAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* Data length.
|
||||
*/
|
||||
private static final char DATA_LENGTH_USE_CANDIDATE = 0;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
protected UseCandidateAttribute()
|
||||
{
|
||||
super(USE_CANDIDATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes the USE-CANDIDATE attribute's body, which is empty
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's
|
||||
* field values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after length)
|
||||
* @param length the length of the binary array.
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// Do nothing, empty attribute body
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + DATA_LENGTH_USE_CANDIDATE];
|
||||
|
||||
// Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
// Length
|
||||
binValue[2] = (byte)(DATA_LENGTH_USE_CANDIDATE >> 8);
|
||||
binValue[3] = (byte)(DATA_LENGTH_USE_CANDIDATE & 0x00FF);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Two attributes are considered equal when
|
||||
* they have the same type, length and value.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof UseCandidateAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj;
|
||||
if(useCandidateAtt.getAttributeType() != getAttributeType()
|
||||
|| useCandidateAtt.getDataLength() != getDataLength())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
*
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_USE_CANDIDATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "USE-CANDIDATE";
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.attribute;
|
||||
|
||||
import org.ice4j.*;
|
||||
|
||||
/**
|
||||
* This class implements the USE-CANDIDATE attribute
|
||||
* This attribute is an extension to the original STUN protocol
|
||||
* This is used only during an ICE implementation
|
||||
*
|
||||
* This attribute serves as only a flag, it does not have any data
|
||||
* so the data length is zero
|
||||
*/
|
||||
public class UseCandidateAttribute
|
||||
extends Attribute
|
||||
{
|
||||
/**
|
||||
* Data length.
|
||||
*/
|
||||
private static final char DATA_LENGTH_USE_CANDIDATE = 0;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
protected UseCandidateAttribute()
|
||||
{
|
||||
super(USE_CANDIDATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes the USE-CANDIDATE attribute's body, which is empty
|
||||
*
|
||||
* @param attributeValue a binary array containing this attribute's
|
||||
* field values and NOT containing the attribute header.
|
||||
* @param offset the position where attribute values begin (most often
|
||||
* offset is equal to the index of the first byte after length)
|
||||
* @param length the length of the binary array.
|
||||
* @throws StunException if attrubteValue contains invalid data.
|
||||
*/
|
||||
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
|
||||
throws StunException
|
||||
{
|
||||
// Do nothing, empty attribute body
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a binary representation of this attribute.
|
||||
*
|
||||
* @return a binary representation of this attribute.
|
||||
*/
|
||||
public byte[] encode()
|
||||
{
|
||||
char type = getAttributeType();
|
||||
byte[] binValue = new byte[HEADER_LENGTH + DATA_LENGTH_USE_CANDIDATE];
|
||||
|
||||
// Type
|
||||
binValue[0] = (byte)(type >> 8);
|
||||
binValue[1] = (byte)(type & 0x00FF);
|
||||
|
||||
// Length
|
||||
binValue[2] = (byte)(DATA_LENGTH_USE_CANDIDATE >> 8);
|
||||
binValue[3] = (byte)(DATA_LENGTH_USE_CANDIDATE & 0x00FF);
|
||||
|
||||
return binValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two STUN Attributes. Two attributes are considered equal when
|
||||
* they have the same type, length and value.
|
||||
*
|
||||
* @param obj the object to compare this attribute with.
|
||||
* @return true if the attributes are equal and false otherwise.
|
||||
*/
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if(!(obj instanceof UseCandidateAttribute)
|
||||
|| obj == null)
|
||||
return false;
|
||||
|
||||
if(obj == this)
|
||||
return true;
|
||||
|
||||
UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj;
|
||||
if(useCandidateAtt.getAttributeType() != getAttributeType()
|
||||
|| useCandidateAtt.getDataLength() != getDataLength())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this attribute's body.
|
||||
*
|
||||
* @return the length of this attribute's value.
|
||||
*/
|
||||
public char getDataLength()
|
||||
{
|
||||
return DATA_LENGTH_USE_CANDIDATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the human readable name of this attribute.
|
||||
*
|
||||
* @return this attribute's name.
|
||||
*/
|
||||
public String getName()
|
||||
{
|
||||
return "USE-CANDIDATE";
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,25 +15,25 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* <tt>EnShutdown</tt> enumeration used internally
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
enum EnShutdown
|
||||
{
|
||||
/**
|
||||
* There was no shutdown
|
||||
*/
|
||||
SD_NONE,
|
||||
/**
|
||||
* There was a graceful shutdown
|
||||
*/
|
||||
SD_GRACEFUL,
|
||||
/**
|
||||
* There was a forceful shutdown
|
||||
*/
|
||||
SD_FORCEFUL
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* <tt>EnShutdown</tt> enumeration used internally
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
enum EnShutdown
|
||||
{
|
||||
/**
|
||||
* There was no shutdown
|
||||
*/
|
||||
SD_NONE,
|
||||
/**
|
||||
* There was a graceful shutdown
|
||||
*/
|
||||
SD_GRACEFUL,
|
||||
/**
|
||||
* There was a forceful shutdown
|
||||
*/
|
||||
SD_FORCEFUL
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,48 +15,48 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* Notification of tcp events.
|
||||
* Is implemented by @link(PseudoTcpSocket) to expose stream functionality.
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
interface IPseudoTcpNotify
|
||||
{
|
||||
/**
|
||||
* Called when tcp enters opened state
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpOpen(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when any data is available in read buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpReadable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when there is free space available in the send buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpWriteable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when tcp enters closed state
|
||||
* @param tcp
|
||||
* @param e null means no error
|
||||
*/
|
||||
void OnTcpClosed(PseudoTCPBase tcp, IOException e);
|
||||
|
||||
/**
|
||||
* Called when protocol requests packet transfer through the network.
|
||||
* @param tcp
|
||||
* @param buffer data
|
||||
* @param len data length
|
||||
* @return the result, see {@link WriteResult} description for more info
|
||||
*/
|
||||
WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* Notification of tcp events.
|
||||
* Is implemented by @link(PseudoTcpSocket) to expose stream functionality.
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
interface IPseudoTcpNotify
|
||||
{
|
||||
/**
|
||||
* Called when tcp enters opened state
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpOpen(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when any data is available in read buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpReadable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when there is free space available in the send buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void OnTcpWriteable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when tcp enters closed state
|
||||
* @param tcp
|
||||
* @param e null means no error
|
||||
*/
|
||||
void OnTcpClosed(PseudoTCPBase tcp, IOException e);
|
||||
|
||||
/**
|
||||
* Called when protocol requests packet transfer through the network.
|
||||
* @param tcp
|
||||
* @param buffer data
|
||||
* @param len data length
|
||||
* @return the result, see {@link WriteResult} description for more info
|
||||
*/
|
||||
WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,37 +15,37 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Options used in PseudoTCP
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum Option
|
||||
{
|
||||
/**
|
||||
* Whether to enable Nagle's algorithm (0 == off)
|
||||
*/
|
||||
OPT_NODELAY,
|
||||
/**
|
||||
* The Delayed ACK timeout (0 == off).
|
||||
*/
|
||||
OPT_ACKDELAY,
|
||||
/**
|
||||
* Set the receive buffer size, in bytes.
|
||||
*/
|
||||
OPT_RCVBUF,
|
||||
/**
|
||||
* Set the send buffer size, in bytes.
|
||||
*/
|
||||
OPT_SNDBUF,
|
||||
/**
|
||||
* Timeout in ms for read operations(0 - no timeout)
|
||||
*/
|
||||
OPT_READ_TIMEOUT,
|
||||
/**
|
||||
* Timeout in ms for write operations(0 - no timeout)
|
||||
*/
|
||||
OPT_WRITE_TIMEOUT
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Options used in PseudoTCP
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum Option
|
||||
{
|
||||
/**
|
||||
* Whether to enable Nagle's algorithm (0 == off)
|
||||
*/
|
||||
OPT_NODELAY,
|
||||
/**
|
||||
* The Delayed ACK timeout (0 == off).
|
||||
*/
|
||||
OPT_ACKDELAY,
|
||||
/**
|
||||
* Set the receive buffer size, in bytes.
|
||||
*/
|
||||
OPT_RCVBUF,
|
||||
/**
|
||||
* Set the send buffer size, in bytes.
|
||||
*/
|
||||
OPT_SNDBUF,
|
||||
/**
|
||||
* Timeout in ms for read operations(0 - no timeout)
|
||||
*/
|
||||
OPT_READ_TIMEOUT,
|
||||
/**
|
||||
* Timeout in ms for write operations(0 - no timeout)
|
||||
*/
|
||||
OPT_WRITE_TIMEOUT
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,49 +15,49 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* Notification of tcp events.
|
||||
* Is implemented by <tt>PseudoTcpSocketImpl</tt> to expose stream functionality.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public interface PseudoTcpNotify
|
||||
{
|
||||
/**
|
||||
* Called when TCP enters opened state
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpOpen(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when any data is available in read buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpReadable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when there is free space available in the send buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpWriteable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when tcp enters closed state
|
||||
* @param tcp
|
||||
* @param e null means no error
|
||||
*/
|
||||
void onTcpClosed(PseudoTCPBase tcp, IOException e);
|
||||
|
||||
/**
|
||||
* Called when protocol requests packet transfer through the network.
|
||||
* @param tcp
|
||||
* @param buffer data
|
||||
* @param len data length
|
||||
* @return the result, see {@link WriteResult} description for more info
|
||||
*/
|
||||
WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* Notification of tcp events.
|
||||
* Is implemented by <tt>PseudoTcpSocketImpl</tt> to expose stream functionality.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public interface PseudoTcpNotify
|
||||
{
|
||||
/**
|
||||
* Called when TCP enters opened state
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpOpen(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when any data is available in read buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpReadable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when there is free space available in the send buffer
|
||||
* @param tcp
|
||||
*/
|
||||
void onTcpWriteable(PseudoTCPBase tcp);
|
||||
|
||||
/**
|
||||
* Called when tcp enters closed state
|
||||
* @param tcp
|
||||
* @param e null means no error
|
||||
*/
|
||||
void onTcpClosed(PseudoTCPBase tcp, IOException e);
|
||||
|
||||
/**
|
||||
* Called when protocol requests packet transfer through the network.
|
||||
* @param tcp
|
||||
* @param buffer data
|
||||
* @param len data length
|
||||
* @return the result, see {@link WriteResult} description for more info
|
||||
*/
|
||||
WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
|
||||
}
|
||||
|
||||
@ -1,149 +1,149 @@
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import javax.net.*;
|
||||
|
||||
public class PseudoTcpSocketFactory
|
||||
extends SocketFactory
|
||||
implements SocketImplFactory
|
||||
{
|
||||
/**
|
||||
* Default conversation ID
|
||||
*/
|
||||
public static final long DEFAULT_CONVERSATION_ID=0;
|
||||
|
||||
/**
|
||||
* Default timeout for connect operation
|
||||
*/
|
||||
public static final int DEFAULT_CONNECT_TIMEOUT=5000;
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified
|
||||
* port number at the specified address.
|
||||
*/
|
||||
public Socket createSocket(String host, int port)
|
||||
throws IOException,
|
||||
UnknownHostException
|
||||
{
|
||||
Socket socket = createSocket();
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connect it to the specified remote address
|
||||
* on the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(InetAddress host, int port) throws IOException
|
||||
{
|
||||
Socket socket = createSocket();
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
private void connectSocket(Socket socket, InetSocketAddress remoteSockAddr)
|
||||
throws IOException
|
||||
{
|
||||
socket.connect(remoteSockAddr, DEFAULT_CONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates socket bound to local <tt>sockAddr</tt>
|
||||
* @param sockAddr
|
||||
* @return socket bound to local address
|
||||
* @throws IOException
|
||||
*/
|
||||
public Socket createBoundSocket(InetSocketAddress sockAddr)
|
||||
throws IOException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID,
|
||||
new DatagramSocket(sockAddr)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified remote host at the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(String host,
|
||||
int port,
|
||||
InetAddress localHost,
|
||||
int localPort)
|
||||
throws IOException,
|
||||
UnknownHostException
|
||||
{
|
||||
Socket socket = createBoundSocket(
|
||||
new InetSocketAddress(localHost, localPort));
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified remote host on the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(InetAddress address, int port,
|
||||
InetAddress localAddress, int localPort) throws IOException
|
||||
{
|
||||
Socket socket = createBoundSocket(
|
||||
new InetSocketAddress(localAddress, localPort));
|
||||
connectSocket(socket, new InetSocketAddress(address, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket that will run on given <tt>datagramSocket</tt>
|
||||
*
|
||||
* @param datagramSocket
|
||||
* @return new socket running on given <tt>datagramSocket</tt>
|
||||
* @throws SocketException
|
||||
*/
|
||||
public PseudoTcpSocket createSocket(DatagramSocket datagramSocket)
|
||||
throws SocketException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, datagramSocket));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the PseudoTcp socket and binds it to any available port
|
||||
* on the local host machine. The socket will be bound to the
|
||||
* {@link InetAddress#isAnyLocalAddress wildcard} address,
|
||||
* an IP address chosen by the kernel.
|
||||
*/
|
||||
@Override
|
||||
public PseudoTcpSocket createSocket()
|
||||
throws SocketException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID));
|
||||
}
|
||||
|
||||
public SocketImpl createSocketImpl()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID);
|
||||
}
|
||||
catch (SocketException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import javax.net.*;
|
||||
|
||||
public class PseudoTcpSocketFactory
|
||||
extends SocketFactory
|
||||
implements SocketImplFactory
|
||||
{
|
||||
/**
|
||||
* Default conversation ID
|
||||
*/
|
||||
public static final long DEFAULT_CONVERSATION_ID=0;
|
||||
|
||||
/**
|
||||
* Default timeout for connect operation
|
||||
*/
|
||||
public static final int DEFAULT_CONNECT_TIMEOUT=5000;
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified
|
||||
* port number at the specified address.
|
||||
*/
|
||||
public Socket createSocket(String host, int port)
|
||||
throws IOException,
|
||||
UnknownHostException
|
||||
{
|
||||
Socket socket = createSocket();
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connect it to the specified remote address
|
||||
* on the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(InetAddress host, int port) throws IOException
|
||||
{
|
||||
Socket socket = createSocket();
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
private void connectSocket(Socket socket, InetSocketAddress remoteSockAddr)
|
||||
throws IOException
|
||||
{
|
||||
socket.connect(remoteSockAddr, DEFAULT_CONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates socket bound to local <tt>sockAddr</tt>
|
||||
* @param sockAddr
|
||||
* @return socket bound to local address
|
||||
* @throws IOException
|
||||
*/
|
||||
public Socket createBoundSocket(InetSocketAddress sockAddr)
|
||||
throws IOException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID,
|
||||
new DatagramSocket(sockAddr)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified remote host at the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(String host,
|
||||
int port,
|
||||
InetAddress localHost,
|
||||
int localPort)
|
||||
throws IOException,
|
||||
UnknownHostException
|
||||
{
|
||||
Socket socket = createBoundSocket(
|
||||
new InetSocketAddress(localHost, localPort));
|
||||
connectSocket(socket, new InetSocketAddress(host, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket and connects it to the specified remote host on the specified remote port.
|
||||
*/
|
||||
public Socket createSocket(InetAddress address, int port,
|
||||
InetAddress localAddress, int localPort) throws IOException
|
||||
{
|
||||
Socket socket = createBoundSocket(
|
||||
new InetSocketAddress(localAddress, localPort));
|
||||
connectSocket(socket, new InetSocketAddress(address, port));
|
||||
return socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket that will run on given <tt>datagramSocket</tt>
|
||||
*
|
||||
* @param datagramSocket
|
||||
* @return new socket running on given <tt>datagramSocket</tt>
|
||||
* @throws SocketException
|
||||
*/
|
||||
public PseudoTcpSocket createSocket(DatagramSocket datagramSocket)
|
||||
throws SocketException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, datagramSocket));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the PseudoTcp socket and binds it to any available port
|
||||
* on the local host machine. The socket will be bound to the
|
||||
* {@link InetAddress#isAnyLocalAddress wildcard} address,
|
||||
* an IP address chosen by the kernel.
|
||||
*/
|
||||
@Override
|
||||
public PseudoTcpSocket createSocket()
|
||||
throws SocketException
|
||||
{
|
||||
return new PseudoTcpSocket(
|
||||
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID));
|
||||
}
|
||||
|
||||
public SocketImpl createSocketImpl()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID);
|
||||
}
|
||||
catch (SocketException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,34 +15,34 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* TCP states defined for pseudoTCP
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum PseudoTcpState
|
||||
{
|
||||
/**
|
||||
* Initial state, can accept connection
|
||||
*/
|
||||
TCP_LISTEN,// = 0,
|
||||
/**
|
||||
* SYN sent to remote peer, wits for SYN
|
||||
*/
|
||||
TCP_SYN_SENT,// = 1,
|
||||
/**
|
||||
* SYN received from remote peer, sends back SYN
|
||||
*/
|
||||
TCP_SYN_RECEIVED,// = 2;
|
||||
/**
|
||||
* SYN sent and received - connection established
|
||||
*/
|
||||
TCP_ESTABLISHED,// = 3;
|
||||
/**
|
||||
* Closed state. In current implementation reached on error
|
||||
* or explicite by close method with force option
|
||||
* TODO: closing procedure
|
||||
*/
|
||||
TCP_CLOSED// = 4;
|
||||
};
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* TCP states defined for pseudoTCP
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum PseudoTcpState
|
||||
{
|
||||
/**
|
||||
* Initial state, can accept connection
|
||||
*/
|
||||
TCP_LISTEN,// = 0,
|
||||
/**
|
||||
* SYN sent to remote peer, wits for SYN
|
||||
*/
|
||||
TCP_SYN_SENT,// = 1,
|
||||
/**
|
||||
* SYN received from remote peer, sends back SYN
|
||||
*/
|
||||
TCP_SYN_RECEIVED,// = 2;
|
||||
/**
|
||||
* SYN sent and received - connection established
|
||||
*/
|
||||
TCP_ESTABLISHED,// = 3;
|
||||
/**
|
||||
* Closed state. In current implementation reached on error
|
||||
* or explicite by close method with force option
|
||||
* TODO: closing procedure
|
||||
*/
|
||||
TCP_CLOSED// = 4;
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,21 +15,21 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
|
||||
/**
|
||||
* Class used internally as a structure for receive segments
|
||||
*
|
||||
* @author Pawel
|
||||
*/
|
||||
class RSegment
|
||||
{
|
||||
public long seq, len;
|
||||
|
||||
public RSegment(long seq, long len)
|
||||
{
|
||||
this.seq = seq;
|
||||
this.len = len;
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
|
||||
/**
|
||||
* Class used internally as a structure for receive segments
|
||||
*
|
||||
* @author Pawel
|
||||
*/
|
||||
class RSegment
|
||||
{
|
||||
public long seq, len;
|
||||
|
||||
public RSegment(long seq, long len)
|
||||
{
|
||||
this.seq = seq;
|
||||
this.len = len;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,25 +15,25 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Class used internally as a structure for send segments
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
class SSegment
|
||||
{
|
||||
long seq, len;
|
||||
//uint32 tstamp;
|
||||
short xmit;
|
||||
boolean bCtrl;
|
||||
|
||||
SSegment(long s, long l, boolean c)
|
||||
{
|
||||
seq = s;
|
||||
len = l;
|
||||
xmit = 0;
|
||||
bCtrl = c;
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Class used internally as a structure for send segments
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
class SSegment
|
||||
{
|
||||
long seq, len;
|
||||
//uint32 tstamp;
|
||||
short xmit;
|
||||
boolean bCtrl;
|
||||
|
||||
SSegment(long s, long l, boolean c)
|
||||
{
|
||||
seq = s;
|
||||
len = l;
|
||||
xmit = 0;
|
||||
bCtrl = c;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,23 +15,23 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
|
||||
/**
|
||||
* Class used as a segment structure
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class Segment
|
||||
{
|
||||
long conv;
|
||||
long seq;
|
||||
long ack;
|
||||
byte flags;
|
||||
int wnd;
|
||||
long tsval;
|
||||
long tsecr;
|
||||
byte[] data;
|
||||
int len;
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
|
||||
/**
|
||||
* Class used as a segment structure
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class Segment
|
||||
{
|
||||
long conv;
|
||||
long seq;
|
||||
long ack;
|
||||
byte flags;
|
||||
int wnd;
|
||||
long tsval;
|
||||
long tsecr;
|
||||
byte[] data;
|
||||
int len;
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,14 +15,14 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Send flags used internally
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
enum SendFlags
|
||||
{
|
||||
sfNone, sfImmediateAck, sfDelayedAck;
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* Send flags used internally
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
enum SendFlags
|
||||
{
|
||||
sfNone, sfImmediateAck, sfDelayedAck;
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,24 +15,24 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* The result of write packet operations
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum WriteResult
|
||||
{
|
||||
/**
|
||||
* Packet successfully transmitted
|
||||
*/
|
||||
WR_SUCCESS,
|
||||
/**
|
||||
* Packet was too large
|
||||
*/
|
||||
WR_TOO_LARGE,
|
||||
/**
|
||||
* Write failed
|
||||
*/
|
||||
WR_FAIL
|
||||
};
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
/**
|
||||
* The result of write packet operations
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public enum WriteResult
|
||||
{
|
||||
/**
|
||||
* Packet successfully transmitted
|
||||
*/
|
||||
WR_SUCCESS,
|
||||
/**
|
||||
* Packet was too large
|
||||
*/
|
||||
WR_TOO_LARGE,
|
||||
/**
|
||||
* Write failed
|
||||
*/
|
||||
WR_FAIL
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,381 +15,381 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp.util;
|
||||
|
||||
import java.nio.*;
|
||||
|
||||
/**
|
||||
* First in - first out byte buffer
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class ByteFifoBuffer
|
||||
{
|
||||
/**
|
||||
* Backing byte array
|
||||
*/
|
||||
private byte[] array;
|
||||
/**
|
||||
* Current write position
|
||||
*/
|
||||
private int write_pos = 0;
|
||||
/**
|
||||
* Stored bytes count
|
||||
*/
|
||||
private int buffered = 0;
|
||||
/**
|
||||
* Current read position
|
||||
*/
|
||||
private int read_pos = 0;
|
||||
|
||||
/**
|
||||
* Creates buffer of specified size
|
||||
*
|
||||
* @param len buffer's size
|
||||
*/
|
||||
public ByteFifoBuffer(int len)
|
||||
{
|
||||
array = new byte[len];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return buffer's capacity
|
||||
*/
|
||||
public int length()
|
||||
{
|
||||
return array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method reads <tt>count</tt> bytes into <tt>out_buffer</tt>.
|
||||
* Current read position is incremented by count of bytes
|
||||
* that has been successfully read.
|
||||
*
|
||||
* @param out_buffer
|
||||
* @param count
|
||||
* @return bytes successfully read
|
||||
*/
|
||||
public int read(byte[] out_buffer, int count)
|
||||
{
|
||||
return read(out_buffer, 0, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read with buffer offset
|
||||
* @param out_buffer
|
||||
* @param buff_offset
|
||||
* @param count bytes to read
|
||||
* @return read byte count
|
||||
*/
|
||||
public int read(byte[] out_buffer, int buff_offset, int count) {
|
||||
count = readLimit(count);
|
||||
if (count > 0)
|
||||
{
|
||||
readOp(out_buffer, buff_offset, count, array, read_pos, array.length);
|
||||
read_pos = (read_pos + count) % array.length;
|
||||
buffered -= count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits <tt>desiredReadCount</tt> to count that is actually available
|
||||
* @param desiredReadCount
|
||||
* @return
|
||||
*/
|
||||
private int readLimit(int desiredReadCount)
|
||||
{
|
||||
return desiredReadCount > buffered ? buffered : desiredReadCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method used for read operations
|
||||
* @param outBuffer
|
||||
* @param dst_buff_offset
|
||||
* @param count
|
||||
* @param srcBuffer
|
||||
* @param read_pos
|
||||
* @param buff_len
|
||||
*/
|
||||
private static void readOp(byte[] outBuffer, int dst_buff_offset, int count,
|
||||
byte[] srcBuffer, int read_pos, int buff_len)
|
||||
{
|
||||
if (read_pos + count <= buff_len)
|
||||
{
|
||||
//single operation
|
||||
System.arraycopy(srcBuffer, read_pos, outBuffer, dst_buff_offset,
|
||||
count);
|
||||
}
|
||||
else
|
||||
{
|
||||
//two operations
|
||||
int tillEndCount = buff_len - read_pos;
|
||||
System.arraycopy(srcBuffer, read_pos, outBuffer,
|
||||
dst_buff_offset, tillEndCount);
|
||||
int fromStartCount = count - tillEndCount;
|
||||
System.arraycopy(srcBuffer, 0, outBuffer,
|
||||
dst_buff_offset + tillEndCount, fromStartCount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return space left in buffer for write
|
||||
*/
|
||||
public int getWriteRemaining()
|
||||
{
|
||||
return array.length - buffered;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return bytes stored in buffer and available for reading
|
||||
*/
|
||||
public int getBuffered()
|
||||
{
|
||||
return buffered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes <tt>count</tt> of bytes from the <tt>buffer</tt>
|
||||
*
|
||||
* @param buffer
|
||||
* @param count
|
||||
* @return bytes successfully written to buffer
|
||||
*/
|
||||
public int write(byte[] buffer, int count)
|
||||
{
|
||||
return write(buffer, 0, count);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param data source data
|
||||
* @param offset source buffer's offset
|
||||
* @param count
|
||||
* @return byte count actually read
|
||||
*/
|
||||
public int write(byte[] data, int offset, int count)
|
||||
{
|
||||
/*
|
||||
* System.out.println("----write " + this + " " + len + " buffered " +
|
||||
* GetBuffered() + " buff avail: " + GetWriteRemaining());
|
||||
*/
|
||||
count = writeLimit(count);
|
||||
writeOp(data, offset, count, array, write_pos, array.length);
|
||||
write_pos = (write_pos + count) % array.length;
|
||||
buffered += count;
|
||||
/*
|
||||
* System.out.println("----write "+this+" "+len+" buffered
|
||||
* "+GetBuffered()); for(int i=0; i < len; i++){
|
||||
* System.out.println("WDATA: "+data[i]); }
|
||||
*/
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for write operations
|
||||
* @param inBuffer
|
||||
* @param inOffset
|
||||
* @param count
|
||||
* @param outBuffer
|
||||
* @param write_pos
|
||||
* @param buff_len
|
||||
*/
|
||||
private static void writeOp(byte[] inBuffer,
|
||||
int inOffset,
|
||||
int count,
|
||||
byte[] outBuffer,
|
||||
int write_pos,
|
||||
int buff_len)
|
||||
{
|
||||
if ((write_pos + count) <= buff_len)
|
||||
{
|
||||
//single op
|
||||
System.arraycopy(inBuffer, inOffset, outBuffer, write_pos, count);
|
||||
}
|
||||
else
|
||||
{
|
||||
//till end and from beginning
|
||||
int tillEndCount;
|
||||
int fromStartCount;
|
||||
tillEndCount = buff_len - write_pos;
|
||||
fromStartCount = count - tillEndCount;
|
||||
System.arraycopy(inBuffer, inOffset, outBuffer,
|
||||
write_pos, tillEndCount);
|
||||
System.arraycopy(inBuffer, inOffset + tillEndCount,
|
||||
outBuffer, 0, fromStartCount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits <tt>desiredWriteCount</tt> to what's actually available
|
||||
* @param desiredWriteCount
|
||||
* @return
|
||||
*/
|
||||
private int writeLimit(int desiredWriteCount)
|
||||
{
|
||||
return desiredWriteCount > (array.length - buffered) ?
|
||||
(array.length - buffered) : desiredWriteCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if new write position is correct
|
||||
*
|
||||
* @param newWrPos new write position
|
||||
*/
|
||||
private void assertWriteLimit(int newWrPos)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
int spaceReq;
|
||||
int availSpace = getWriteRemaining();
|
||||
if (newWrPos < write_pos)
|
||||
{
|
||||
spaceReq = newWrPos + (array.length - write_pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
spaceReq = newWrPos - write_pos;
|
||||
}
|
||||
|
||||
if (spaceReq > availSpace)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances current buffer's write position by <tt>count</tt> bytes
|
||||
*
|
||||
* @param count
|
||||
*/
|
||||
public void consumeWriteBuffer(int count)
|
||||
throws IllegalArgumentException,
|
||||
BufferOverflowException
|
||||
{
|
||||
if (count > getWriteRemaining())
|
||||
{
|
||||
throw new BufferOverflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int newPos = (write_pos + count) % array.length;
|
||||
assertWriteLimit(newPos);
|
||||
|
||||
write_pos = newPos;
|
||||
buffered += count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets new buffer's capacity
|
||||
*
|
||||
* @param new_size
|
||||
* @return <tt>true</tt> if operation is possible to perform, that is if new
|
||||
* buffered data fits into new buffer
|
||||
*/
|
||||
public boolean setCapacity(int new_size)
|
||||
{
|
||||
if (new_size < getBuffered())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
byte[] newBuff = new byte[new_size];
|
||||
readOp(newBuff, 0, buffered, array, read_pos, array.length);
|
||||
this.array = newBuff;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns current read position by <tt>count</tt>
|
||||
*
|
||||
* @param count
|
||||
* @throws BufferUnderflowException if new position exceeds buffered data
|
||||
* count
|
||||
*/
|
||||
public void consumeReadData(int count)
|
||||
throws IllegalArgumentException,
|
||||
BufferUnderflowException
|
||||
{
|
||||
/*
|
||||
* System.out.println("Consume read " + this + " " + count + " read pos:
|
||||
* " + read_pos);
|
||||
*/
|
||||
if (count > buffered)
|
||||
{
|
||||
throw new BufferUnderflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
this.read_pos = (read_pos + count) % array.length;
|
||||
buffered -= count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads <tt>count</tt> bytes from buffer without storing new read position
|
||||
*
|
||||
* @param dst_buff
|
||||
* @param dst_buff_offset offset of destination buffer
|
||||
* @param count bytes to read
|
||||
* @param offset from current read position
|
||||
* @return bytes successfully read
|
||||
*/
|
||||
public int readOffset(byte[] dst_buff,
|
||||
int dst_buff_offset,
|
||||
int count,
|
||||
int offset)
|
||||
{
|
||||
//TODO: not sure if should decrease read count or throw an exception
|
||||
/*
|
||||
* System.out.println("Read dst offset " + dst_buff_offset + " offset "
|
||||
* + offset + " len " + count + " " + this);
|
||||
*/
|
||||
int read_offset = (this.read_pos + offset) % array.length;
|
||||
readOp(dst_buff, dst_buff_offset, count, array, read_offset, array.length);
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes <tt>count</tt> bytes from <tt>data</tt> to the buffer without
|
||||
* affecting buffer's write position
|
||||
*
|
||||
* @param data
|
||||
* @param count
|
||||
* @param nOffset from buffer's write position
|
||||
* @return bytes successfully written
|
||||
*/
|
||||
public int writeOffset(byte[] data, int count, int nOffset)
|
||||
throws BufferOverflowException
|
||||
{
|
||||
if (count > getWriteRemaining())
|
||||
{
|
||||
throw new BufferOverflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int offWritePos = (this.write_pos + nOffset) % array.length;
|
||||
count = writeLimit(count);
|
||||
assertWriteLimit(offWritePos + count);
|
||||
writeOp(data, 0, count, array, offWritePos, array.length);
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public void resetReadPosition()
|
||||
{
|
||||
this.read_pos = 0;
|
||||
}
|
||||
|
||||
public void resetWritePosition()
|
||||
{
|
||||
this.write_pos = 0;
|
||||
this.buffered = 0;
|
||||
}
|
||||
}
|
||||
package org.ice4j.pseudotcp.util;
|
||||
|
||||
import java.nio.*;
|
||||
|
||||
/**
|
||||
* First in - first out byte buffer
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class ByteFifoBuffer
|
||||
{
|
||||
/**
|
||||
* Backing byte array
|
||||
*/
|
||||
private byte[] array;
|
||||
/**
|
||||
* Current write position
|
||||
*/
|
||||
private int write_pos = 0;
|
||||
/**
|
||||
* Stored bytes count
|
||||
*/
|
||||
private int buffered = 0;
|
||||
/**
|
||||
* Current read position
|
||||
*/
|
||||
private int read_pos = 0;
|
||||
|
||||
/**
|
||||
* Creates buffer of specified size
|
||||
*
|
||||
* @param len buffer's size
|
||||
*/
|
||||
public ByteFifoBuffer(int len)
|
||||
{
|
||||
array = new byte[len];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return buffer's capacity
|
||||
*/
|
||||
public int length()
|
||||
{
|
||||
return array.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method reads <tt>count</tt> bytes into <tt>out_buffer</tt>.
|
||||
* Current read position is incremented by count of bytes
|
||||
* that has been successfully read.
|
||||
*
|
||||
* @param out_buffer
|
||||
* @param count
|
||||
* @return bytes successfully read
|
||||
*/
|
||||
public int read(byte[] out_buffer, int count)
|
||||
{
|
||||
return read(out_buffer, 0, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read with buffer offset
|
||||
* @param out_buffer
|
||||
* @param buff_offset
|
||||
* @param count bytes to read
|
||||
* @return read byte count
|
||||
*/
|
||||
public int read(byte[] out_buffer, int buff_offset, int count) {
|
||||
count = readLimit(count);
|
||||
if (count > 0)
|
||||
{
|
||||
readOp(out_buffer, buff_offset, count, array, read_pos, array.length);
|
||||
read_pos = (read_pos + count) % array.length;
|
||||
buffered -= count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits <tt>desiredReadCount</tt> to count that is actually available
|
||||
* @param desiredReadCount
|
||||
* @return
|
||||
*/
|
||||
private int readLimit(int desiredReadCount)
|
||||
{
|
||||
return desiredReadCount > buffered ? buffered : desiredReadCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method used for read operations
|
||||
* @param outBuffer
|
||||
* @param dst_buff_offset
|
||||
* @param count
|
||||
* @param srcBuffer
|
||||
* @param read_pos
|
||||
* @param buff_len
|
||||
*/
|
||||
private static void readOp(byte[] outBuffer, int dst_buff_offset, int count,
|
||||
byte[] srcBuffer, int read_pos, int buff_len)
|
||||
{
|
||||
if (read_pos + count <= buff_len)
|
||||
{
|
||||
//single operation
|
||||
System.arraycopy(srcBuffer, read_pos, outBuffer, dst_buff_offset,
|
||||
count);
|
||||
}
|
||||
else
|
||||
{
|
||||
//two operations
|
||||
int tillEndCount = buff_len - read_pos;
|
||||
System.arraycopy(srcBuffer, read_pos, outBuffer,
|
||||
dst_buff_offset, tillEndCount);
|
||||
int fromStartCount = count - tillEndCount;
|
||||
System.arraycopy(srcBuffer, 0, outBuffer,
|
||||
dst_buff_offset + tillEndCount, fromStartCount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return space left in buffer for write
|
||||
*/
|
||||
public int getWriteRemaining()
|
||||
{
|
||||
return array.length - buffered;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return bytes stored in buffer and available for reading
|
||||
*/
|
||||
public int getBuffered()
|
||||
{
|
||||
return buffered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes <tt>count</tt> of bytes from the <tt>buffer</tt>
|
||||
*
|
||||
* @param buffer
|
||||
* @param count
|
||||
* @return bytes successfully written to buffer
|
||||
*/
|
||||
public int write(byte[] buffer, int count)
|
||||
{
|
||||
return write(buffer, 0, count);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param data source data
|
||||
* @param offset source buffer's offset
|
||||
* @param count
|
||||
* @return byte count actually read
|
||||
*/
|
||||
public int write(byte[] data, int offset, int count)
|
||||
{
|
||||
/*
|
||||
* System.out.println("----write " + this + " " + len + " buffered " +
|
||||
* GetBuffered() + " buff avail: " + GetWriteRemaining());
|
||||
*/
|
||||
count = writeLimit(count);
|
||||
writeOp(data, offset, count, array, write_pos, array.length);
|
||||
write_pos = (write_pos + count) % array.length;
|
||||
buffered += count;
|
||||
/*
|
||||
* System.out.println("----write "+this+" "+len+" buffered
|
||||
* "+GetBuffered()); for(int i=0; i < len; i++){
|
||||
* System.out.println("WDATA: "+data[i]); }
|
||||
*/
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for write operations
|
||||
* @param inBuffer
|
||||
* @param inOffset
|
||||
* @param count
|
||||
* @param outBuffer
|
||||
* @param write_pos
|
||||
* @param buff_len
|
||||
*/
|
||||
private static void writeOp(byte[] inBuffer,
|
||||
int inOffset,
|
||||
int count,
|
||||
byte[] outBuffer,
|
||||
int write_pos,
|
||||
int buff_len)
|
||||
{
|
||||
if ((write_pos + count) <= buff_len)
|
||||
{
|
||||
//single op
|
||||
System.arraycopy(inBuffer, inOffset, outBuffer, write_pos, count);
|
||||
}
|
||||
else
|
||||
{
|
||||
//till end and from beginning
|
||||
int tillEndCount;
|
||||
int fromStartCount;
|
||||
tillEndCount = buff_len - write_pos;
|
||||
fromStartCount = count - tillEndCount;
|
||||
System.arraycopy(inBuffer, inOffset, outBuffer,
|
||||
write_pos, tillEndCount);
|
||||
System.arraycopy(inBuffer, inOffset + tillEndCount,
|
||||
outBuffer, 0, fromStartCount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits <tt>desiredWriteCount</tt> to what's actually available
|
||||
* @param desiredWriteCount
|
||||
* @return
|
||||
*/
|
||||
private int writeLimit(int desiredWriteCount)
|
||||
{
|
||||
return desiredWriteCount > (array.length - buffered) ?
|
||||
(array.length - buffered) : desiredWriteCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if new write position is correct
|
||||
*
|
||||
* @param newWrPos new write position
|
||||
*/
|
||||
private void assertWriteLimit(int newWrPos)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
int spaceReq;
|
||||
int availSpace = getWriteRemaining();
|
||||
if (newWrPos < write_pos)
|
||||
{
|
||||
spaceReq = newWrPos + (array.length - write_pos);
|
||||
}
|
||||
else
|
||||
{
|
||||
spaceReq = newWrPos - write_pos;
|
||||
}
|
||||
|
||||
if (spaceReq > availSpace)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances current buffer's write position by <tt>count</tt> bytes
|
||||
*
|
||||
* @param count
|
||||
*/
|
||||
public void consumeWriteBuffer(int count)
|
||||
throws IllegalArgumentException,
|
||||
BufferOverflowException
|
||||
{
|
||||
if (count > getWriteRemaining())
|
||||
{
|
||||
throw new BufferOverflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int newPos = (write_pos + count) % array.length;
|
||||
assertWriteLimit(newPos);
|
||||
|
||||
write_pos = newPos;
|
||||
buffered += count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets new buffer's capacity
|
||||
*
|
||||
* @param new_size
|
||||
* @return <tt>true</tt> if operation is possible to perform, that is if new
|
||||
* buffered data fits into new buffer
|
||||
*/
|
||||
public boolean setCapacity(int new_size)
|
||||
{
|
||||
if (new_size < getBuffered())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
byte[] newBuff = new byte[new_size];
|
||||
readOp(newBuff, 0, buffered, array, read_pos, array.length);
|
||||
this.array = newBuff;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns current read position by <tt>count</tt>
|
||||
*
|
||||
* @param count
|
||||
* @throws BufferUnderflowException if new position exceeds buffered data
|
||||
* count
|
||||
*/
|
||||
public void consumeReadData(int count)
|
||||
throws IllegalArgumentException,
|
||||
BufferUnderflowException
|
||||
{
|
||||
/*
|
||||
* System.out.println("Consume read " + this + " " + count + " read pos:
|
||||
* " + read_pos);
|
||||
*/
|
||||
if (count > buffered)
|
||||
{
|
||||
throw new BufferUnderflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
this.read_pos = (read_pos + count) % array.length;
|
||||
buffered -= count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads <tt>count</tt> bytes from buffer without storing new read position
|
||||
*
|
||||
* @param dst_buff
|
||||
* @param dst_buff_offset offset of destination buffer
|
||||
* @param count bytes to read
|
||||
* @param offset from current read position
|
||||
* @return bytes successfully read
|
||||
*/
|
||||
public int readOffset(byte[] dst_buff,
|
||||
int dst_buff_offset,
|
||||
int count,
|
||||
int offset)
|
||||
{
|
||||
//TODO: not sure if should decrease read count or throw an exception
|
||||
/*
|
||||
* System.out.println("Read dst offset " + dst_buff_offset + " offset "
|
||||
* + offset + " len " + count + " " + this);
|
||||
*/
|
||||
int read_offset = (this.read_pos + offset) % array.length;
|
||||
readOp(dst_buff, dst_buff_offset, count, array, read_offset, array.length);
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes <tt>count</tt> bytes from <tt>data</tt> to the buffer without
|
||||
* affecting buffer's write position
|
||||
*
|
||||
* @param data
|
||||
* @param count
|
||||
* @param nOffset from buffer's write position
|
||||
* @return bytes successfully written
|
||||
*/
|
||||
public int writeOffset(byte[] data, int count, int nOffset)
|
||||
throws BufferOverflowException
|
||||
{
|
||||
if (count > getWriteRemaining())
|
||||
{
|
||||
throw new BufferOverflowException();
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
int offWritePos = (this.write_pos + nOffset) % array.length;
|
||||
count = writeLimit(count);
|
||||
assertWriteLimit(offWritePos + count);
|
||||
writeOp(data, 0, count, array, offWritePos, array.length);
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public void resetReadPosition()
|
||||
{
|
||||
this.read_pos = 0;
|
||||
}
|
||||
|
||||
public void resetWritePosition()
|
||||
{
|
||||
this.write_pos = 0;
|
||||
this.buffered = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,92 +1,92 @@
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
/**
|
||||
* This class enables multi thread tests where main thread waits in loop
|
||||
* for specified condition to be met, while others perform some operations.
|
||||
* For example until the connection is established or closed.
|
||||
* It also registers default uncaught exception handler to catch exceptions
|
||||
* from other threads.
|
||||
*
|
||||
* Condition checks are passed as IWaitUntilDone interface.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class MultiThreadSupportTest
|
||||
extends TestCase
|
||||
implements Thread.UncaughtExceptionHandler
|
||||
{
|
||||
private volatile Throwable testError;
|
||||
private volatile Thread errorThread;
|
||||
private final Object testLock = new Object();
|
||||
|
||||
public MultiThreadSupportTest()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uncaughtException(Thread t, Throwable e)
|
||||
{
|
||||
synchronized (testLock)
|
||||
{
|
||||
testError = e;
|
||||
errorThread = t;
|
||||
testLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
private long assertWaitInterval = 100;
|
||||
protected interface WaitUntilDone
|
||||
{
|
||||
public boolean isDone();
|
||||
}
|
||||
|
||||
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
long start = System.currentTimeMillis();
|
||||
while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs)
|
||||
{
|
||||
synchronized (testLock)
|
||||
{
|
||||
testLock.wait(assertWaitInterval);
|
||||
if (testError != null)
|
||||
{
|
||||
testError.printStackTrace();
|
||||
fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return wait.isDone();
|
||||
}
|
||||
catch (InterruptedException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
fail("assert_wait - interrupted");
|
||||
//return is unreachable
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
/**
|
||||
* This class enables multi thread tests where main thread waits in loop
|
||||
* for specified condition to be met, while others perform some operations.
|
||||
* For example until the connection is established or closed.
|
||||
* It also registers default uncaught exception handler to catch exceptions
|
||||
* from other threads.
|
||||
*
|
||||
* Condition checks are passed as IWaitUntilDone interface.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class MultiThreadSupportTest
|
||||
extends TestCase
|
||||
implements Thread.UncaughtExceptionHandler
|
||||
{
|
||||
private volatile Throwable testError;
|
||||
private volatile Thread errorThread;
|
||||
private final Object testLock = new Object();
|
||||
|
||||
public MultiThreadSupportTest()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uncaughtException(Thread t, Throwable e)
|
||||
{
|
||||
synchronized (testLock)
|
||||
{
|
||||
testError = e;
|
||||
errorThread = t;
|
||||
testLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
private long assertWaitInterval = 100;
|
||||
protected interface WaitUntilDone
|
||||
{
|
||||
public boolean isDone();
|
||||
}
|
||||
|
||||
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
long start = System.currentTimeMillis();
|
||||
while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs)
|
||||
{
|
||||
synchronized (testLock)
|
||||
{
|
||||
testLock.wait(assertWaitInterval);
|
||||
if (testError != null)
|
||||
{
|
||||
testError.printStackTrace();
|
||||
fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return wait.isDone();
|
||||
}
|
||||
catch (InterruptedException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
fail("assert_wait - interrupted");
|
||||
//return is unreachable
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,353 +15,353 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.pseudotcp.util.*;
|
||||
|
||||
/**
|
||||
* This class implements test for two way transfers
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class PseudoTcpTestPingPong extends PseudoTcpTestBase
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(PseudoTCPBase.class.getName());
|
||||
/**
|
||||
* The sender
|
||||
*/
|
||||
private PseudoTCPBase sender;
|
||||
/**
|
||||
* The receiver
|
||||
*/
|
||||
private PseudoTCPBase receiver;
|
||||
/**
|
||||
* How much data is sent per ping
|
||||
*/
|
||||
private int bytesPerSend;
|
||||
/**
|
||||
* Iterations count
|
||||
*/
|
||||
private int iterationsRemaining;
|
||||
|
||||
public PseudoTcpTestPingPong()
|
||||
{
|
||||
}
|
||||
|
||||
public void setBytesPerSend(int bytes_per_send)
|
||||
{
|
||||
this.bytesPerSend = bytes_per_send;
|
||||
}
|
||||
/**
|
||||
* The send stream buffer
|
||||
*/
|
||||
ByteFifoBuffer send_stream;
|
||||
/**
|
||||
* The receive stream buffer
|
||||
*/
|
||||
ByteFifoBuffer recv_stream;
|
||||
|
||||
/**
|
||||
* Performs ping-pong test for <tt>iterations</tt> with packets of
|
||||
* <tt>size</tt> bytes
|
||||
*
|
||||
* @param size
|
||||
* @param iterations
|
||||
*/
|
||||
public void doTestPingPong(int size, int iterations)
|
||||
{
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
long start;
|
||||
iterationsRemaining = iterations;
|
||||
receiver = getRemoteTcp();
|
||||
sender = getLocalTcp();
|
||||
// Create some dummy data
|
||||
byte[] dummy = createDummyData(size);
|
||||
send_stream = new ByteFifoBuffer(size);
|
||||
send_stream.write(dummy, size);
|
||||
//Prepare the receive stream
|
||||
recv_stream = new ByteFifoBuffer(size);
|
||||
//Connect and wait until connected
|
||||
start = PseudoTCPBase.now();
|
||||
startClocks();
|
||||
try
|
||||
{
|
||||
connect();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
fail(ex.getMessage());
|
||||
}
|
||||
//assert Connect() == 0;
|
||||
assert_Connected_wait(kConnectTimeoutMs);
|
||||
// Sending will start from OnTcpWriteable and stop when the required
|
||||
// number of iterations have completed.
|
||||
assert_Disconnected_wait(kMinTransferRate);
|
||||
long elapsed = PseudoTCPBase.now() - start;
|
||||
stopClocks();
|
||||
logger.log(Level.INFO,
|
||||
"Performed " + iterations + " pings in " + elapsed + " ms");
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches onTcpReadable event for receiver
|
||||
*
|
||||
* @param tcp
|
||||
*/
|
||||
@Override
|
||||
public void onTcpReadable(PseudoTCPBase tcp)
|
||||
{
|
||||
assertEquals("Unexpected onTcpReadable", receiver, tcp);
|
||||
try
|
||||
{
|
||||
// Stream bytes to the recv stream as they arrive.
|
||||
readData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
//will be caught by default handler and test will fail
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
// If we've received the desired amount of data, rewind things
|
||||
// and send it back the other way!
|
||||
int recvd = recv_stream.getBuffered();
|
||||
int required = send_stream.length();
|
||||
if (logger.isLoggable(Level.FINER))
|
||||
{
|
||||
logger.log(Level.FINER,
|
||||
"test - receivied: " + recvd + " required: " + required);
|
||||
}
|
||||
|
||||
if (recvd == required)
|
||||
{
|
||||
if (receiver == getLocalTcp() && --iterationsRemaining == 0)
|
||||
{
|
||||
close();
|
||||
// TODO: Fake OnTcpClosed() on the receiver for now.
|
||||
onTcpClosed(getRemoteTcp(), null);
|
||||
return;
|
||||
}
|
||||
//switches receivier with sender and performs test the other way
|
||||
PseudoTCPBase tmp = receiver;
|
||||
receiver = sender;
|
||||
sender = tmp;
|
||||
send_stream.resetReadPosition();
|
||||
send_stream.consumeWriteBuffer(send_stream.getWriteRemaining());
|
||||
recv_stream.resetWritePosition();
|
||||
onTcpWriteable(sender);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches the ontcpWriteable event for sender
|
||||
*
|
||||
* @param tcp
|
||||
*/
|
||||
@Override
|
||||
public void onTcpWriteable(PseudoTCPBase tcp)
|
||||
{
|
||||
if (tcp != sender)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Write bytes from the send stream when we can.
|
||||
// Shut down when we've sent everything.
|
||||
logger.log(Level.FINER, "Flow Control Lifted");
|
||||
try
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the data in loop until is something available
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readData() throws IOException
|
||||
{
|
||||
byte[] block = new byte[kBlockSize];
|
||||
int rcvd = 0;
|
||||
do
|
||||
{
|
||||
rcvd = receiver.recv(block, block.length);
|
||||
if (rcvd > 0)
|
||||
{
|
||||
recv_stream.write(block, rcvd);
|
||||
if (logger.isLoggable(Level.FINE))
|
||||
{
|
||||
logger.log(Level.FINE,
|
||||
"Receivied: " + recv_stream.getBuffered());
|
||||
}
|
||||
}
|
||||
}
|
||||
while (rcvd > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes all data to the receiver
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
private void writeData() throws IOException
|
||||
{
|
||||
int tosend;
|
||||
int sent = 0;
|
||||
byte[] block = new byte[kBlockSize];
|
||||
do
|
||||
{
|
||||
tosend = bytesPerSend != 0 ? bytesPerSend : block.length;
|
||||
tosend = send_stream.read(block, tosend);
|
||||
if (tosend > 0)
|
||||
{
|
||||
sent = sender.send(block, tosend);
|
||||
updateLocalClock();
|
||||
if (sent != -1)
|
||||
{
|
||||
if(logger.isLoggable(Level.FINE))
|
||||
{
|
||||
logger.log(Level.FINE, "Sent: " + sent);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.FINE, "Flow controlled");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sent = tosend = 0;
|
||||
}
|
||||
}
|
||||
while (sent > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Ping-pong (request/response) tests
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* Test sending <= 1x MTU of data in each ping/pong. Should take <10ms.
|
||||
*/
|
||||
public void testPingPong1xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 1xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(100, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms.
|
||||
*/
|
||||
public void testPingPong3xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 3xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(400, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to
|
||||
* interaction between Nagling and Delayed ACK.
|
||||
*/
|
||||
public void testPingPong2xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(2000, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off.
|
||||
* Should take <10ms.
|
||||
*/
|
||||
public void testPingPong2xMtuWithAckDelayOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestPingPong(2000, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should
|
||||
* take <10ms.
|
||||
*/
|
||||
public void testPingPong2xMtuWithNaglingOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.doTestPingPong(2000, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending a ping as pair of short (non-full) segments. Should take
|
||||
* ~1s, due to Delayed ACK interaction with Nagling.
|
||||
*/
|
||||
public void testPingPongShortSegments()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptAckDelay(5000);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending ping as a pair of short (non-full) segments, with Nagling
|
||||
* off. Should take <10ms.
|
||||
*/
|
||||
public void testPingPongShortSegmentsWithNaglingOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed
|
||||
* ACK. Should take ~1s.
|
||||
*/
|
||||
public void testPingPongShortSegmentsWithAckDelayOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.pseudotcp.util.*;
|
||||
|
||||
/**
|
||||
* This class implements test for two way transfers
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class PseudoTcpTestPingPong extends PseudoTcpTestBase
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(PseudoTCPBase.class.getName());
|
||||
/**
|
||||
* The sender
|
||||
*/
|
||||
private PseudoTCPBase sender;
|
||||
/**
|
||||
* The receiver
|
||||
*/
|
||||
private PseudoTCPBase receiver;
|
||||
/**
|
||||
* How much data is sent per ping
|
||||
*/
|
||||
private int bytesPerSend;
|
||||
/**
|
||||
* Iterations count
|
||||
*/
|
||||
private int iterationsRemaining;
|
||||
|
||||
public PseudoTcpTestPingPong()
|
||||
{
|
||||
}
|
||||
|
||||
public void setBytesPerSend(int bytes_per_send)
|
||||
{
|
||||
this.bytesPerSend = bytes_per_send;
|
||||
}
|
||||
/**
|
||||
* The send stream buffer
|
||||
*/
|
||||
ByteFifoBuffer send_stream;
|
||||
/**
|
||||
* The receive stream buffer
|
||||
*/
|
||||
ByteFifoBuffer recv_stream;
|
||||
|
||||
/**
|
||||
* Performs ping-pong test for <tt>iterations</tt> with packets of
|
||||
* <tt>size</tt> bytes
|
||||
*
|
||||
* @param size
|
||||
* @param iterations
|
||||
*/
|
||||
public void doTestPingPong(int size, int iterations)
|
||||
{
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
long start;
|
||||
iterationsRemaining = iterations;
|
||||
receiver = getRemoteTcp();
|
||||
sender = getLocalTcp();
|
||||
// Create some dummy data
|
||||
byte[] dummy = createDummyData(size);
|
||||
send_stream = new ByteFifoBuffer(size);
|
||||
send_stream.write(dummy, size);
|
||||
//Prepare the receive stream
|
||||
recv_stream = new ByteFifoBuffer(size);
|
||||
//Connect and wait until connected
|
||||
start = PseudoTCPBase.now();
|
||||
startClocks();
|
||||
try
|
||||
{
|
||||
connect();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
ex.printStackTrace();
|
||||
fail(ex.getMessage());
|
||||
}
|
||||
//assert Connect() == 0;
|
||||
assert_Connected_wait(kConnectTimeoutMs);
|
||||
// Sending will start from OnTcpWriteable and stop when the required
|
||||
// number of iterations have completed.
|
||||
assert_Disconnected_wait(kMinTransferRate);
|
||||
long elapsed = PseudoTCPBase.now() - start;
|
||||
stopClocks();
|
||||
logger.log(Level.INFO,
|
||||
"Performed " + iterations + " pings in " + elapsed + " ms");
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches onTcpReadable event for receiver
|
||||
*
|
||||
* @param tcp
|
||||
*/
|
||||
@Override
|
||||
public void onTcpReadable(PseudoTCPBase tcp)
|
||||
{
|
||||
assertEquals("Unexpected onTcpReadable", receiver, tcp);
|
||||
try
|
||||
{
|
||||
// Stream bytes to the recv stream as they arrive.
|
||||
readData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
//will be caught by default handler and test will fail
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
// If we've received the desired amount of data, rewind things
|
||||
// and send it back the other way!
|
||||
int recvd = recv_stream.getBuffered();
|
||||
int required = send_stream.length();
|
||||
if (logger.isLoggable(Level.FINER))
|
||||
{
|
||||
logger.log(Level.FINER,
|
||||
"test - receivied: " + recvd + " required: " + required);
|
||||
}
|
||||
|
||||
if (recvd == required)
|
||||
{
|
||||
if (receiver == getLocalTcp() && --iterationsRemaining == 0)
|
||||
{
|
||||
close();
|
||||
// TODO: Fake OnTcpClosed() on the receiver for now.
|
||||
onTcpClosed(getRemoteTcp(), null);
|
||||
return;
|
||||
}
|
||||
//switches receivier with sender and performs test the other way
|
||||
PseudoTCPBase tmp = receiver;
|
||||
receiver = sender;
|
||||
sender = tmp;
|
||||
send_stream.resetReadPosition();
|
||||
send_stream.consumeWriteBuffer(send_stream.getWriteRemaining());
|
||||
recv_stream.resetWritePosition();
|
||||
onTcpWriteable(sender);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches the ontcpWriteable event for sender
|
||||
*
|
||||
* @param tcp
|
||||
*/
|
||||
@Override
|
||||
public void onTcpWriteable(PseudoTCPBase tcp)
|
||||
{
|
||||
if (tcp != sender)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Write bytes from the send stream when we can.
|
||||
// Shut down when we've sent everything.
|
||||
logger.log(Level.FINER, "Flow Control Lifted");
|
||||
try
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the data in loop until is something available
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readData() throws IOException
|
||||
{
|
||||
byte[] block = new byte[kBlockSize];
|
||||
int rcvd = 0;
|
||||
do
|
||||
{
|
||||
rcvd = receiver.recv(block, block.length);
|
||||
if (rcvd > 0)
|
||||
{
|
||||
recv_stream.write(block, rcvd);
|
||||
if (logger.isLoggable(Level.FINE))
|
||||
{
|
||||
logger.log(Level.FINE,
|
||||
"Receivied: " + recv_stream.getBuffered());
|
||||
}
|
||||
}
|
||||
}
|
||||
while (rcvd > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes all data to the receiver
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
private void writeData() throws IOException
|
||||
{
|
||||
int tosend;
|
||||
int sent = 0;
|
||||
byte[] block = new byte[kBlockSize];
|
||||
do
|
||||
{
|
||||
tosend = bytesPerSend != 0 ? bytesPerSend : block.length;
|
||||
tosend = send_stream.read(block, tosend);
|
||||
if (tosend > 0)
|
||||
{
|
||||
sent = sender.send(block, tosend);
|
||||
updateLocalClock();
|
||||
if (sent != -1)
|
||||
{
|
||||
if(logger.isLoggable(Level.FINE))
|
||||
{
|
||||
logger.log(Level.FINE, "Sent: " + sent);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.FINE, "Flow controlled");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sent = tosend = 0;
|
||||
}
|
||||
}
|
||||
while (sent > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Ping-pong (request/response) tests
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* Test sending <= 1x MTU of data in each ping/pong. Should take <10ms.
|
||||
*/
|
||||
public void testPingPong1xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 1xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(100, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms.
|
||||
*/
|
||||
public void testPingPong3xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 3xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(400, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to
|
||||
* interaction between Nagling and Delayed ACK.
|
||||
*/
|
||||
public void testPingPong2xMtu()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.doTestPingPong(2000, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off.
|
||||
* Should take <10ms.
|
||||
*/
|
||||
public void testPingPong2xMtuWithAckDelayOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestPingPong(2000, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should
|
||||
* take <10ms.
|
||||
*/
|
||||
public void testPingPong2xMtuWithNaglingOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.doTestPingPong(2000, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending a ping as pair of short (non-full) segments. Should take
|
||||
* ~1s, due to Delayed ACK interaction with Nagling.
|
||||
*/
|
||||
public void testPingPongShortSegments()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptAckDelay(5000);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending ping as a pair of short (non-full) segments, with Nagling
|
||||
* off. Should take <10ms.
|
||||
*/
|
||||
public void testPingPongShortSegmentsWithNaglingOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed
|
||||
* ACK. Should take ~1s.
|
||||
*/
|
||||
public void testPingPongShortSegmentsWithAckDelayOff()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test ping - pong short segments nagling off");
|
||||
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setBytesPerSend(50); // i.e. two Send calls per payload
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestPingPong(100, 5);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,399 +15,399 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.pseudotcp.util.*;
|
||||
|
||||
/**
|
||||
* Fill the receiver window until it is full, drain it and then fill it with the
|
||||
* same amount. This is to test that receiver window contracts and enlarges
|
||||
* correctly.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(PseudoTCPBase.class.getName());
|
||||
/**
|
||||
* Send data buffer
|
||||
*/
|
||||
private ByteFifoBuffer send_stream;
|
||||
/**
|
||||
* List which stores stream position after each write cycle
|
||||
*/
|
||||
private List<Integer> send_position;
|
||||
/**
|
||||
* Receive data buffer
|
||||
*/
|
||||
private ByteFifoBuffer recv_stream;
|
||||
/**
|
||||
* List which stores stream position after each read cycle
|
||||
*/
|
||||
private List<Integer> recv_position;
|
||||
/**
|
||||
* Times used for write operations scheduling
|
||||
*/
|
||||
private Timer writeTimer = new Timer("WriteTimer");
|
||||
/**
|
||||
* Stores data length used for the test.
|
||||
*/
|
||||
private int testDataSize;
|
||||
|
||||
public void doTestTransfer(int size)
|
||||
{
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
testDataSize = size;
|
||||
long start, elapsed;
|
||||
send_position = new ArrayList<Integer>();
|
||||
recv_position = new ArrayList<Integer>();
|
||||
// Create some dummy data
|
||||
byte[] dummy = createDummyData(size);
|
||||
send_stream = new ByteFifoBuffer(size);
|
||||
send_stream.write(dummy, size);
|
||||
//Prepare the receive stream
|
||||
recv_stream = new ByteFifoBuffer(size);
|
||||
//Connect and wait until connected
|
||||
start = PseudoTCPBase.now();
|
||||
startClocks();
|
||||
try
|
||||
{
|
||||
connect();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
fail(ex.getMessage());
|
||||
}
|
||||
//assert Connect() == 0;
|
||||
//TODO: check assert result and fail
|
||||
// Connect and wait until connected.
|
||||
assert_Connected_wait(kConnectTimeoutMs);
|
||||
|
||||
scheduleWriteAction(0);
|
||||
|
||||
long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
|
||||
boolean transfferInTime = assert_Disconnected_wait(transferTout);
|
||||
elapsed = PseudoTCPBase.now() - start;
|
||||
stopClocks();
|
||||
int received = recv_stream.getBuffered();
|
||||
assertEquals("Transfer timeout, transferred: " + received
|
||||
+ " required: " + dummy.length
|
||||
+ " elapsed: "
|
||||
+ elapsed + " limit: " + transferTout,
|
||||
true, transfferInTime);
|
||||
|
||||
assert 2 == send_position.size();
|
||||
assert 2 == recv_position.size();
|
||||
|
||||
int estimated_recv_window = estimateReceiveWindowSize();
|
||||
|
||||
// The difference in consecutive send positions should equal the
|
||||
// receive window size or match very closely. This verifies that receive
|
||||
// window is open after receiver drained all the data.
|
||||
int send_position_diff = send_position.get(1) - send_position.get(0);
|
||||
assertTrue(estimated_recv_window - send_position_diff <= 1024);
|
||||
|
||||
// Receiver drained the receive window twice.(+-2 because of window scaling)
|
||||
assert ((recv_position.get(1) - 2 * estimated_recv_window)
|
||||
<= getShadowedBytes(getRemoteScaleFactor()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This function calculates amount of bytes witch may introduce error to
|
||||
* estimation of receive window size caused by scale factor. This is because
|
||||
* data is being sent until all sent data is available in remote side's
|
||||
* buffer. But because of scale factor window size 0 is reached earlier than
|
||||
* expected and some data may still wait for window to open in the send
|
||||
* queue.
|
||||
*
|
||||
* For example: m_rcv_scale == 1 and m_rcv_wnd < 2 then rcv_wnd == 0 (1 byte
|
||||
* may block) m_rcv_scale == 2 and m_rcv_wnd < 4 then rcv_wnd == 0 (3 bytes
|
||||
* may block) m_rcv_scale == 3 and m_rcv_wnd < 8 then rcv_wnd == 0 (7 bytes
|
||||
* may block) and so on...
|
||||
*
|
||||
* In normal operation something would read data on remote side causing
|
||||
* window to expand.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
|
||||
*
|
||||
* @param scaleFactor
|
||||
* @return count bytes shadowed by scale actor
|
||||
*/
|
||||
static int getShadowedBytes(int scaleFactor)
|
||||
{
|
||||
return (int) (Math.pow(2, scaleFactor) - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all data available at the buffer
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
void readUntilIOPending() throws IOException
|
||||
{
|
||||
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
|
||||
int position = recv_stream.getBuffered();
|
||||
int rcvd, total = 0;
|
||||
do
|
||||
{
|
||||
rcvd = remoteRecv(block, block.length);
|
||||
if (rcvd > 0)
|
||||
{
|
||||
recv_stream.write(block, rcvd);
|
||||
total += rcvd;
|
||||
position += rcvd;
|
||||
}
|
||||
}
|
||||
while (rcvd > 0 && total != 0);
|
||||
recv_position.add(position);
|
||||
|
||||
// Disconnect if we have done two transfers.
|
||||
if (recv_position.size() == 2)
|
||||
{
|
||||
close();
|
||||
onTcpClosed(getRemoteTcp(), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules write operation with <tt>delay</tt> given in ms
|
||||
*
|
||||
* @param delay
|
||||
*/
|
||||
void scheduleWriteAction(long delay)
|
||||
{
|
||||
writeTimer.schedule(new TimerTask()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
//it will get cought by
|
||||
//deafult exception handler in PseudoTcpTestBase
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the data
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
void writeData() throws IOException
|
||||
{
|
||||
//writeOpCount++;
|
||||
int tosend;
|
||||
int sent;
|
||||
int totalSent = 0;
|
||||
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
|
||||
int position = testDataSize - send_stream.getBuffered();
|
||||
synchronized (getLocalTcp())
|
||||
{
|
||||
do
|
||||
{
|
||||
tosend = send_stream.readOffset(block, 0, block.length, 0);
|
||||
if (tosend > 0)
|
||||
{
|
||||
sent = localSend(block, tosend);
|
||||
updateLocalClock();
|
||||
if (sent > 0)
|
||||
{
|
||||
totalSent += sent;
|
||||
send_stream.consumeReadData(sent);
|
||||
position += sent;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.FINE, "Flow Controlled");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sent = tosend = 0;
|
||||
}
|
||||
}
|
||||
while (sent > 0);
|
||||
//position = send_stream.GetBuffered();
|
||||
|
||||
}
|
||||
// Measured with precision according to window scale option used
|
||||
if (totalSent - getRemoteTcp().getAvailable()
|
||||
> getShadowedBytes(getRemoteScaleFactor()))
|
||||
{
|
||||
//send buffer was fully filled
|
||||
//waits until it will be received by remote peer
|
||||
while (totalSent - getRemoteTcp().getAvailable()
|
||||
> getShadowedBytes(getRemoteScaleFactor())
|
||||
&& !getRemoteTcp().isReceiveBufferFull())
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(50);
|
||||
if (logger.isLoggable(Level.FINER))
|
||||
{
|
||||
logger.log(Level.FINER,
|
||||
"Waiting... sent: " + totalSent + " avail: "
|
||||
+ getRemoteTcp().getAvailable() + " buffered not sent: "
|
||||
+ getLocalTcp().getBytesBufferedNotSent()
|
||||
+ " isFull? " + getRemoteTcp().isReceiveBufferFull());
|
||||
}
|
||||
}
|
||||
catch (InterruptedException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
send_position.add(position);
|
||||
writeTimer.schedule(new TimerTask()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
readUntilIOPending();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return estimated receive window size
|
||||
*/
|
||||
int estimateReceiveWindowSize()
|
||||
{
|
||||
return recv_position.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return estimated send window size
|
||||
*/
|
||||
int estimateSendWindowSize()
|
||||
{
|
||||
return send_position.get(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTcpReadable(PseudoTCPBase tcp)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTcpWriteable(PseudoTCPBase tcp)
|
||||
{
|
||||
}
|
||||
|
||||
void setLocalOptSndBuf(int len)
|
||||
{
|
||||
getLocalTcp().setOption(Option.OPT_SNDBUF, len);
|
||||
}
|
||||
|
||||
int getRemoteScaleFactor()
|
||||
{
|
||||
return getRemoteTcp().getM_rwnd_scale();
|
||||
}
|
||||
|
||||
public void testGetShadowedBytes()
|
||||
{
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(1) == 1);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(2) == 3);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(3) == 7);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(4) == 15);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(11) == 2047);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(14) == 16383);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that receive window expands and contract correctly.
|
||||
*/
|
||||
public void testReceiveWindow()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test receive window");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestTransfer(1024 * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test setting send window size to a very small value.
|
||||
*/
|
||||
public void testSetVerySmallSendWindowSize()
|
||||
{
|
||||
//TODO: finish test
|
||||
logger.log(Level.INFO, "Test very small receive window");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
test.setOptSndBuf(900);
|
||||
test.doTestTransfer(1024 * 1000);
|
||||
assertEquals(900, test.estimateSendWindowSize());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test setting receive window size to a value other than default.
|
||||
*/
|
||||
public void testSetReceiveWindowSize()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test set receive window size");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
int wndSize = 300000;
|
||||
test.setRemoteOptRcvBuf(wndSize);
|
||||
test.setLocalOptSndBuf(wndSize);
|
||||
int wndScale = test.getRemoteScaleFactor();
|
||||
//logger.log(Level.INFO, "Using scale factor: {0}", wndScale);
|
||||
test.doTestTransfer(1024 * 3000);
|
||||
//beacuse there may be situations
|
||||
//when 1 byte may be waiting in send queue
|
||||
//before
|
||||
//scaling factor == 1 not allows to determine exact window size (+-1)
|
||||
assert (wndSize - test.estimateReceiveWindowSize()
|
||||
<= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale));
|
||||
}
|
||||
|
||||
/*
|
||||
* Test sending data with mismatched MTUs. We should detect this and reduce
|
||||
* // our packet size accordingly. // TODO: This doesn't actually work right
|
||||
* now. The current code // doesn't detect if the MTU is set too high on
|
||||
* either side. TEST_F(PseudoTcpTest, TestSendWithMismatchedMtus) {
|
||||
* SetLocalMtu(1500); SetRemoteMtu(1280); TestTransfer(1000000); }
|
||||
*/
|
||||
}
|
||||
package org.ice4j.pseudotcp;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.pseudotcp.util.*;
|
||||
|
||||
/**
|
||||
* Fill the receiver window until it is full, drain it and then fill it with the
|
||||
* same amount. This is to test that receiver window contracts and enlarges
|
||||
* correctly.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(PseudoTCPBase.class.getName());
|
||||
/**
|
||||
* Send data buffer
|
||||
*/
|
||||
private ByteFifoBuffer send_stream;
|
||||
/**
|
||||
* List which stores stream position after each write cycle
|
||||
*/
|
||||
private List<Integer> send_position;
|
||||
/**
|
||||
* Receive data buffer
|
||||
*/
|
||||
private ByteFifoBuffer recv_stream;
|
||||
/**
|
||||
* List which stores stream position after each read cycle
|
||||
*/
|
||||
private List<Integer> recv_position;
|
||||
/**
|
||||
* Times used for write operations scheduling
|
||||
*/
|
||||
private Timer writeTimer = new Timer("WriteTimer");
|
||||
/**
|
||||
* Stores data length used for the test.
|
||||
*/
|
||||
private int testDataSize;
|
||||
|
||||
public void doTestTransfer(int size)
|
||||
{
|
||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||
testDataSize = size;
|
||||
long start, elapsed;
|
||||
send_position = new ArrayList<Integer>();
|
||||
recv_position = new ArrayList<Integer>();
|
||||
// Create some dummy data
|
||||
byte[] dummy = createDummyData(size);
|
||||
send_stream = new ByteFifoBuffer(size);
|
||||
send_stream.write(dummy, size);
|
||||
//Prepare the receive stream
|
||||
recv_stream = new ByteFifoBuffer(size);
|
||||
//Connect and wait until connected
|
||||
start = PseudoTCPBase.now();
|
||||
startClocks();
|
||||
try
|
||||
{
|
||||
connect();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
fail(ex.getMessage());
|
||||
}
|
||||
//assert Connect() == 0;
|
||||
//TODO: check assert result and fail
|
||||
// Connect and wait until connected.
|
||||
assert_Connected_wait(kConnectTimeoutMs);
|
||||
|
||||
scheduleWriteAction(0);
|
||||
|
||||
long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
|
||||
boolean transfferInTime = assert_Disconnected_wait(transferTout);
|
||||
elapsed = PseudoTCPBase.now() - start;
|
||||
stopClocks();
|
||||
int received = recv_stream.getBuffered();
|
||||
assertEquals("Transfer timeout, transferred: " + received
|
||||
+ " required: " + dummy.length
|
||||
+ " elapsed: "
|
||||
+ elapsed + " limit: " + transferTout,
|
||||
true, transfferInTime);
|
||||
|
||||
assert 2 == send_position.size();
|
||||
assert 2 == recv_position.size();
|
||||
|
||||
int estimated_recv_window = estimateReceiveWindowSize();
|
||||
|
||||
// The difference in consecutive send positions should equal the
|
||||
// receive window size or match very closely. This verifies that receive
|
||||
// window is open after receiver drained all the data.
|
||||
int send_position_diff = send_position.get(1) - send_position.get(0);
|
||||
assertTrue(estimated_recv_window - send_position_diff <= 1024);
|
||||
|
||||
// Receiver drained the receive window twice.(+-2 because of window scaling)
|
||||
assert ((recv_position.get(1) - 2 * estimated_recv_window)
|
||||
<= getShadowedBytes(getRemoteScaleFactor()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This function calculates amount of bytes witch may introduce error to
|
||||
* estimation of receive window size caused by scale factor. This is because
|
||||
* data is being sent until all sent data is available in remote side's
|
||||
* buffer. But because of scale factor window size 0 is reached earlier than
|
||||
* expected and some data may still wait for window to open in the send
|
||||
* queue.
|
||||
*
|
||||
* For example: m_rcv_scale == 1 and m_rcv_wnd < 2 then rcv_wnd == 0 (1 byte
|
||||
* may block) m_rcv_scale == 2 and m_rcv_wnd < 4 then rcv_wnd == 0 (3 bytes
|
||||
* may block) m_rcv_scale == 3 and m_rcv_wnd < 8 then rcv_wnd == 0 (7 bytes
|
||||
* may block) and so on...
|
||||
*
|
||||
* In normal operation something would read data on remote side causing
|
||||
* window to expand.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
|
||||
*
|
||||
* @param scaleFactor
|
||||
* @return count bytes shadowed by scale actor
|
||||
*/
|
||||
static int getShadowedBytes(int scaleFactor)
|
||||
{
|
||||
return (int) (Math.pow(2, scaleFactor) - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all data available at the buffer
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
void readUntilIOPending() throws IOException
|
||||
{
|
||||
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
|
||||
int position = recv_stream.getBuffered();
|
||||
int rcvd, total = 0;
|
||||
do
|
||||
{
|
||||
rcvd = remoteRecv(block, block.length);
|
||||
if (rcvd > 0)
|
||||
{
|
||||
recv_stream.write(block, rcvd);
|
||||
total += rcvd;
|
||||
position += rcvd;
|
||||
}
|
||||
}
|
||||
while (rcvd > 0 && total != 0);
|
||||
recv_position.add(position);
|
||||
|
||||
// Disconnect if we have done two transfers.
|
||||
if (recv_position.size() == 2)
|
||||
{
|
||||
close();
|
||||
onTcpClosed(getRemoteTcp(), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules write operation with <tt>delay</tt> given in ms
|
||||
*
|
||||
* @param delay
|
||||
*/
|
||||
void scheduleWriteAction(long delay)
|
||||
{
|
||||
writeTimer.schedule(new TimerTask()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
writeData();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
//it will get cought by
|
||||
//deafult exception handler in PseudoTcpTestBase
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the data
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
void writeData() throws IOException
|
||||
{
|
||||
//writeOpCount++;
|
||||
int tosend;
|
||||
int sent;
|
||||
int totalSent = 0;
|
||||
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
|
||||
int position = testDataSize - send_stream.getBuffered();
|
||||
synchronized (getLocalTcp())
|
||||
{
|
||||
do
|
||||
{
|
||||
tosend = send_stream.readOffset(block, 0, block.length, 0);
|
||||
if (tosend > 0)
|
||||
{
|
||||
sent = localSend(block, tosend);
|
||||
updateLocalClock();
|
||||
if (sent > 0)
|
||||
{
|
||||
totalSent += sent;
|
||||
send_stream.consumeReadData(sent);
|
||||
position += sent;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.FINE, "Flow Controlled");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sent = tosend = 0;
|
||||
}
|
||||
}
|
||||
while (sent > 0);
|
||||
//position = send_stream.GetBuffered();
|
||||
|
||||
}
|
||||
// Measured with precision according to window scale option used
|
||||
if (totalSent - getRemoteTcp().getAvailable()
|
||||
> getShadowedBytes(getRemoteScaleFactor()))
|
||||
{
|
||||
//send buffer was fully filled
|
||||
//waits until it will be received by remote peer
|
||||
while (totalSent - getRemoteTcp().getAvailable()
|
||||
> getShadowedBytes(getRemoteScaleFactor())
|
||||
&& !getRemoteTcp().isReceiveBufferFull())
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(50);
|
||||
if (logger.isLoggable(Level.FINER))
|
||||
{
|
||||
logger.log(Level.FINER,
|
||||
"Waiting... sent: " + totalSent + " avail: "
|
||||
+ getRemoteTcp().getAvailable() + " buffered not sent: "
|
||||
+ getLocalTcp().getBytesBufferedNotSent()
|
||||
+ " isFull? " + getRemoteTcp().isReceiveBufferFull());
|
||||
}
|
||||
}
|
||||
catch (InterruptedException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
send_position.add(position);
|
||||
writeTimer.schedule(new TimerTask()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
readUntilIOPending();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return estimated receive window size
|
||||
*/
|
||||
int estimateReceiveWindowSize()
|
||||
{
|
||||
return recv_position.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return estimated send window size
|
||||
*/
|
||||
int estimateSendWindowSize()
|
||||
{
|
||||
return send_position.get(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTcpReadable(PseudoTCPBase tcp)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTcpWriteable(PseudoTCPBase tcp)
|
||||
{
|
||||
}
|
||||
|
||||
void setLocalOptSndBuf(int len)
|
||||
{
|
||||
getLocalTcp().setOption(Option.OPT_SNDBUF, len);
|
||||
}
|
||||
|
||||
int getRemoteScaleFactor()
|
||||
{
|
||||
return getRemoteTcp().getM_rwnd_scale();
|
||||
}
|
||||
|
||||
public void testGetShadowedBytes()
|
||||
{
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(1) == 1);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(2) == 3);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(3) == 7);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(4) == 15);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(11) == 2047);
|
||||
assert (PseudoTcpTestRecvWindow.getShadowedBytes(14) == 16383);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that receive window expands and contract correctly.
|
||||
*/
|
||||
public void testReceiveWindow()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test receive window");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
test.doTestTransfer(1024 * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test setting send window size to a very small value.
|
||||
*/
|
||||
public void testSetVerySmallSendWindowSize()
|
||||
{
|
||||
//TODO: finish test
|
||||
logger.log(Level.INFO, "Test very small receive window");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
test.setOptSndBuf(900);
|
||||
test.doTestTransfer(1024 * 1000);
|
||||
assertEquals(900, test.estimateSendWindowSize());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test setting receive window size to a value other than default.
|
||||
*/
|
||||
public void testSetReceiveWindowSize()
|
||||
{
|
||||
//logger.log(Level.INFO, "Test set receive window size");
|
||||
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
|
||||
test.setLocalMtu(1500);
|
||||
test.setRemoteMtu(1500);
|
||||
test.setOptNagling(false);
|
||||
test.setOptAckDelay(0);
|
||||
int wndSize = 300000;
|
||||
test.setRemoteOptRcvBuf(wndSize);
|
||||
test.setLocalOptSndBuf(wndSize);
|
||||
int wndScale = test.getRemoteScaleFactor();
|
||||
//logger.log(Level.INFO, "Using scale factor: {0}", wndScale);
|
||||
test.doTestTransfer(1024 * 3000);
|
||||
//beacuse there may be situations
|
||||
//when 1 byte may be waiting in send queue
|
||||
//before
|
||||
//scaling factor == 1 not allows to determine exact window size (+-1)
|
||||
assert (wndSize - test.estimateReceiveWindowSize()
|
||||
<= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale));
|
||||
}
|
||||
|
||||
/*
|
||||
* Test sending data with mismatched MTUs. We should detect this and reduce
|
||||
* // our packet size accordingly. // TODO: This doesn't actually work right
|
||||
* now. The current code // doesn't detect if the MTU is set too high on
|
||||
* either side. TEST_F(PseudoTcpTest, TestSendWithMismatchedMtus) {
|
||||
* SetLocalMtu(1500); SetRemoteMtu(1280); TestTransfer(1000000); }
|
||||
*/
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,341 +15,341 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.ice4j.pseudotcp.util;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.nio.*;
|
||||
import java.util.*;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class ByteFifoBufferTest
|
||||
extends TestCase
|
||||
{
|
||||
public ByteFifoBufferTest()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Length method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testLength()
|
||||
{
|
||||
int expResult = 1000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(expResult);
|
||||
assertEquals(expResult, instance.length());
|
||||
int wSize = 100;
|
||||
instance.write(getWData(wSize), wSize);
|
||||
int result = instance.length();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Read method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testRead()
|
||||
{
|
||||
int count = 1024;
|
||||
byte[] wData = getWData(count);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(count);
|
||||
instance.write(wData, count);
|
||||
|
||||
byte[] readBuff = new byte[count];
|
||||
int expResult = count;
|
||||
int result = instance.read(readBuff, count);
|
||||
assertEquals(expResult, result);
|
||||
assertArrayEquals(wData, readBuff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests reading with an offset for destination buffer
|
||||
*/
|
||||
public void testReadWithOffset()
|
||||
{
|
||||
int count = 1024;
|
||||
byte[] wData = getWData(count);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(count);
|
||||
instance.write(wData, count);
|
||||
|
||||
byte[] readBuff = new byte[count];
|
||||
int expResult = count / 2;
|
||||
int result = instance.read(readBuff, count / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
result = instance.read(readBuff, count / 2, count / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
assertArrayEquals(wData, readBuff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* return some random array
|
||||
*
|
||||
* @param count array size
|
||||
* @return
|
||||
*/
|
||||
private byte[] getWData(int count)
|
||||
{
|
||||
Random r = new Random();
|
||||
byte[] res = new byte[count];
|
||||
r.nextBytes(res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of GetWriteRemaining method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testGetWriteRemaining()
|
||||
{
|
||||
int len = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
int result = instance.getWriteRemaining();
|
||||
assertEquals(expResult, result);
|
||||
|
||||
int w_size = 23;
|
||||
byte[] w_data = getWData(w_size);
|
||||
instance.write(w_data, w_size);
|
||||
|
||||
expResult = len - w_size;
|
||||
result = instance.getWriteRemaining();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of GetBuffered method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testGetBuffered()
|
||||
{
|
||||
int len = 1000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int w_len = 100;
|
||||
byte[] w_data = getWData(w_len);
|
||||
|
||||
instance.write(w_data, w_len);
|
||||
|
||||
int expResult = w_len;
|
||||
int result = instance.getBuffered();
|
||||
assertEquals(expResult, result);
|
||||
int consume = 5;
|
||||
expResult = w_len + consume;
|
||||
instance.consumeWriteBuffer(consume);
|
||||
result = instance.getBuffered();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Write method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testWrite()
|
||||
{
|
||||
int len = 2048;
|
||||
byte[] data = getWData(len);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
int result = instance.write(data, len);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
byte[] read = new byte[len];
|
||||
int readCount = instance.read(read, len);
|
||||
assertEquals(result, readCount);
|
||||
assertArrayEquals(data, read);
|
||||
}
|
||||
|
||||
public void testWriteWithOffset()
|
||||
{
|
||||
int len = 2048;
|
||||
byte[] data = getWData(len);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len / 2;
|
||||
int result = instance.write(data, 0, len / 2);
|
||||
assertEquals(expResult, result);
|
||||
result = instance.write(data, len / 2, len / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
byte[] read = new byte[len];
|
||||
int readCount = instance.read(read, len);
|
||||
assertEquals(len, readCount);
|
||||
assertArrayEquals(data, read);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ConsumeWriteBuffer method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testConsumeWriteBuffer()
|
||||
{
|
||||
int len = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
instance.consumeWriteBuffer(len / 2);
|
||||
instance.consumeWriteBuffer(len / 2);
|
||||
try
|
||||
{
|
||||
instance.consumeWriteBuffer(1);
|
||||
fail();
|
||||
}
|
||||
catch (BufferOverflowException e)
|
||||
{
|
||||
}
|
||||
|
||||
instance = new ByteFifoBuffer(len);
|
||||
instance.consumeWriteBuffer(95);
|
||||
instance.consumeReadData(40);
|
||||
instance.consumeWriteBuffer(20);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of SetCapacity method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testSetCapacity()
|
||||
{
|
||||
int old_size = 100;
|
||||
int new_size = 200;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(old_size);
|
||||
boolean expResult = true;
|
||||
instance.write(getWData(old_size), old_size);
|
||||
boolean result = instance.setCapacity(new_size);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
expResult = false;
|
||||
instance.resetWritePosition();
|
||||
instance.write(getWData(new_size), new_size);
|
||||
result = instance.setCapacity(old_size);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ConsumeReadData method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testConsumeReadData()
|
||||
{
|
||||
int lCount = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(lCount);
|
||||
instance.write(getWData(lCount), lCount);
|
||||
instance.consumeReadData(lCount / 2);
|
||||
instance.consumeReadData(lCount / 2);
|
||||
try
|
||||
{
|
||||
instance.consumeReadData(1);
|
||||
fail();
|
||||
}
|
||||
catch (BufferUnderflowException e)
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ReadOffset method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testReadOffset()
|
||||
{
|
||||
int dst_buff_offset = 0;
|
||||
int len = 100;
|
||||
byte[] src_buff = getWData(len);
|
||||
byte[] dst_buff = new byte[len];
|
||||
int offset = 0;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
instance.write(src_buff, len);
|
||||
int result =
|
||||
instance.readOffset(dst_buff, dst_buff_offset, len, offset);
|
||||
assertEquals(expResult, result);
|
||||
assertArrayEquals(dst_buff, src_buff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of WriteOffset method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testWriteOffset()
|
||||
{
|
||||
int len = 200;
|
||||
int dataLen = 100;
|
||||
byte[] srcData = getWData(dataLen);
|
||||
byte[] data = new byte[dataLen];
|
||||
int nOffset = 10;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int result = instance.writeOffset(srcData, dataLen, nOffset);
|
||||
int readCount = instance.readOffset(data, 0, dataLen, nOffset);
|
||||
assertEquals(result, readCount);
|
||||
assertArrayEquals(srcData, data);
|
||||
|
||||
byte[] halfFilled = new byte[dataLen * 2];
|
||||
System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen);
|
||||
byte[] halfFilledRead = new byte[dataLen * 2];
|
||||
instance.readOffset(halfFilledRead, dataLen, dataLen, nOffset);
|
||||
assertArrayEquals(halfFilled, halfFilledRead);
|
||||
|
||||
// case when w_pos+offset exceeds current backing array length
|
||||
instance = new ByteFifoBuffer(len);
|
||||
instance.write(srcData, dataLen);
|
||||
instance.write(srcData, dataLen / 2);// current writePos = 150
|
||||
instance.read(data, dataLen);// curretn readPos = 100
|
||||
instance.writeOffset(srcData, dataLen, 50);
|
||||
|
||||
instance = new ByteFifoBuffer(61440);
|
||||
instance.writeOffset(getWData(1384), 1384, 31832);
|
||||
|
||||
}
|
||||
|
||||
public void testWriteReadWriteRead()
|
||||
{
|
||||
int len = 2000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
byte[] wrData = getWData(len * 2);
|
||||
int written = 0;
|
||||
byte[] readBuff = new byte[wrData.length];
|
||||
int read = 0;
|
||||
do
|
||||
{
|
||||
int wrRemaining = instance.getWriteRemaining();
|
||||
if (wrRemaining > 0 && written < wrData.length)
|
||||
{
|
||||
int wrCount = instance.writeOffset(wrData, wrRemaining, 0);
|
||||
instance.consumeWriteBuffer(wrCount);
|
||||
written += wrCount;
|
||||
}
|
||||
int readAvailable = instance.getBuffered();
|
||||
if (readAvailable > 0)
|
||||
{
|
||||
int rCount =
|
||||
instance.readOffset(readBuff, read, readAvailable, 0);
|
||||
instance.consumeReadData(rCount);
|
||||
read += rCount;
|
||||
}
|
||||
}
|
||||
while ((read != wrData.length) || (written != wrData.length));
|
||||
}
|
||||
|
||||
public void testSomeMultiTest()
|
||||
{
|
||||
int Alen = 16;
|
||||
int Blen = 32;
|
||||
int Clen = 64;
|
||||
int Dlen = 256;
|
||||
int len = Alen + Blen + Clen + Dlen;
|
||||
ByteFifoBuffer fifo = new ByteFifoBuffer(len);
|
||||
byte[] A = getWData(Alen);
|
||||
/*byte[] B =*/ getWData(Blen);
|
||||
/*byte[] C =*/ getWData(Clen);
|
||||
/*byte[] D =*/ getWData(Dlen);
|
||||
byte[] Aread = getWData(Alen);
|
||||
/*byte[] Bread =*/ getWData(Blen);
|
||||
/*byte[] Cread =*/ getWData(Clen);
|
||||
/*byte[] Dread =*/ getWData(Dlen);
|
||||
|
||||
fifo.writeOffset(A, Alen, 0);
|
||||
fifo.consumeWriteBuffer(Alen);
|
||||
fifo.readOffset(Aread, 0, Alen, 0);
|
||||
assertArrayEquals(A, Aread);
|
||||
}
|
||||
}
|
||||
package org.ice4j.pseudotcp.util;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.nio.*;
|
||||
import java.util.*;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class ByteFifoBufferTest
|
||||
extends TestCase
|
||||
{
|
||||
public ByteFifoBufferTest()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Length method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testLength()
|
||||
{
|
||||
int expResult = 1000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(expResult);
|
||||
assertEquals(expResult, instance.length());
|
||||
int wSize = 100;
|
||||
instance.write(getWData(wSize), wSize);
|
||||
int result = instance.length();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Read method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testRead()
|
||||
{
|
||||
int count = 1024;
|
||||
byte[] wData = getWData(count);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(count);
|
||||
instance.write(wData, count);
|
||||
|
||||
byte[] readBuff = new byte[count];
|
||||
int expResult = count;
|
||||
int result = instance.read(readBuff, count);
|
||||
assertEquals(expResult, result);
|
||||
assertArrayEquals(wData, readBuff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests reading with an offset for destination buffer
|
||||
*/
|
||||
public void testReadWithOffset()
|
||||
{
|
||||
int count = 1024;
|
||||
byte[] wData = getWData(count);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(count);
|
||||
instance.write(wData, count);
|
||||
|
||||
byte[] readBuff = new byte[count];
|
||||
int expResult = count / 2;
|
||||
int result = instance.read(readBuff, count / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
result = instance.read(readBuff, count / 2, count / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
assertArrayEquals(wData, readBuff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* return some random array
|
||||
*
|
||||
* @param count array size
|
||||
* @return
|
||||
*/
|
||||
private byte[] getWData(int count)
|
||||
{
|
||||
Random r = new Random();
|
||||
byte[] res = new byte[count];
|
||||
r.nextBytes(res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of GetWriteRemaining method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testGetWriteRemaining()
|
||||
{
|
||||
int len = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
int result = instance.getWriteRemaining();
|
||||
assertEquals(expResult, result);
|
||||
|
||||
int w_size = 23;
|
||||
byte[] w_data = getWData(w_size);
|
||||
instance.write(w_data, w_size);
|
||||
|
||||
expResult = len - w_size;
|
||||
result = instance.getWriteRemaining();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of GetBuffered method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testGetBuffered()
|
||||
{
|
||||
int len = 1000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int w_len = 100;
|
||||
byte[] w_data = getWData(w_len);
|
||||
|
||||
instance.write(w_data, w_len);
|
||||
|
||||
int expResult = w_len;
|
||||
int result = instance.getBuffered();
|
||||
assertEquals(expResult, result);
|
||||
int consume = 5;
|
||||
expResult = w_len + consume;
|
||||
instance.consumeWriteBuffer(consume);
|
||||
result = instance.getBuffered();
|
||||
assertEquals(expResult, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of Write method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testWrite()
|
||||
{
|
||||
int len = 2048;
|
||||
byte[] data = getWData(len);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
int result = instance.write(data, len);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
byte[] read = new byte[len];
|
||||
int readCount = instance.read(read, len);
|
||||
assertEquals(result, readCount);
|
||||
assertArrayEquals(data, read);
|
||||
}
|
||||
|
||||
public void testWriteWithOffset()
|
||||
{
|
||||
int len = 2048;
|
||||
byte[] data = getWData(len);
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len / 2;
|
||||
int result = instance.write(data, 0, len / 2);
|
||||
assertEquals(expResult, result);
|
||||
result = instance.write(data, len / 2, len / 2);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
byte[] read = new byte[len];
|
||||
int readCount = instance.read(read, len);
|
||||
assertEquals(len, readCount);
|
||||
assertArrayEquals(data, read);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ConsumeWriteBuffer method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testConsumeWriteBuffer()
|
||||
{
|
||||
int len = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
instance.consumeWriteBuffer(len / 2);
|
||||
instance.consumeWriteBuffer(len / 2);
|
||||
try
|
||||
{
|
||||
instance.consumeWriteBuffer(1);
|
||||
fail();
|
||||
}
|
||||
catch (BufferOverflowException e)
|
||||
{
|
||||
}
|
||||
|
||||
instance = new ByteFifoBuffer(len);
|
||||
instance.consumeWriteBuffer(95);
|
||||
instance.consumeReadData(40);
|
||||
instance.consumeWriteBuffer(20);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of SetCapacity method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testSetCapacity()
|
||||
{
|
||||
int old_size = 100;
|
||||
int new_size = 200;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(old_size);
|
||||
boolean expResult = true;
|
||||
instance.write(getWData(old_size), old_size);
|
||||
boolean result = instance.setCapacity(new_size);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
expResult = false;
|
||||
instance.resetWritePosition();
|
||||
instance.write(getWData(new_size), new_size);
|
||||
result = instance.setCapacity(old_size);
|
||||
assertEquals(expResult, result);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ConsumeReadData method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testConsumeReadData()
|
||||
{
|
||||
int lCount = 100;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(lCount);
|
||||
instance.write(getWData(lCount), lCount);
|
||||
instance.consumeReadData(lCount / 2);
|
||||
instance.consumeReadData(lCount / 2);
|
||||
try
|
||||
{
|
||||
instance.consumeReadData(1);
|
||||
fail();
|
||||
}
|
||||
catch (BufferUnderflowException e)
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of ReadOffset method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testReadOffset()
|
||||
{
|
||||
int dst_buff_offset = 0;
|
||||
int len = 100;
|
||||
byte[] src_buff = getWData(len);
|
||||
byte[] dst_buff = new byte[len];
|
||||
int offset = 0;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int expResult = len;
|
||||
instance.write(src_buff, len);
|
||||
int result =
|
||||
instance.readOffset(dst_buff, dst_buff_offset, len, offset);
|
||||
assertEquals(expResult, result);
|
||||
assertArrayEquals(dst_buff, src_buff);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of WriteOffset method, of class ByteFifoBuffer.
|
||||
*/
|
||||
public void testWriteOffset()
|
||||
{
|
||||
int len = 200;
|
||||
int dataLen = 100;
|
||||
byte[] srcData = getWData(dataLen);
|
||||
byte[] data = new byte[dataLen];
|
||||
int nOffset = 10;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
int result = instance.writeOffset(srcData, dataLen, nOffset);
|
||||
int readCount = instance.readOffset(data, 0, dataLen, nOffset);
|
||||
assertEquals(result, readCount);
|
||||
assertArrayEquals(srcData, data);
|
||||
|
||||
byte[] halfFilled = new byte[dataLen * 2];
|
||||
System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen);
|
||||
byte[] halfFilledRead = new byte[dataLen * 2];
|
||||
instance.readOffset(halfFilledRead, dataLen, dataLen, nOffset);
|
||||
assertArrayEquals(halfFilled, halfFilledRead);
|
||||
|
||||
// case when w_pos+offset exceeds current backing array length
|
||||
instance = new ByteFifoBuffer(len);
|
||||
instance.write(srcData, dataLen);
|
||||
instance.write(srcData, dataLen / 2);// current writePos = 150
|
||||
instance.read(data, dataLen);// curretn readPos = 100
|
||||
instance.writeOffset(srcData, dataLen, 50);
|
||||
|
||||
instance = new ByteFifoBuffer(61440);
|
||||
instance.writeOffset(getWData(1384), 1384, 31832);
|
||||
|
||||
}
|
||||
|
||||
public void testWriteReadWriteRead()
|
||||
{
|
||||
int len = 2000;
|
||||
ByteFifoBuffer instance = new ByteFifoBuffer(len);
|
||||
byte[] wrData = getWData(len * 2);
|
||||
int written = 0;
|
||||
byte[] readBuff = new byte[wrData.length];
|
||||
int read = 0;
|
||||
do
|
||||
{
|
||||
int wrRemaining = instance.getWriteRemaining();
|
||||
if (wrRemaining > 0 && written < wrData.length)
|
||||
{
|
||||
int wrCount = instance.writeOffset(wrData, wrRemaining, 0);
|
||||
instance.consumeWriteBuffer(wrCount);
|
||||
written += wrCount;
|
||||
}
|
||||
int readAvailable = instance.getBuffered();
|
||||
if (readAvailable > 0)
|
||||
{
|
||||
int rCount =
|
||||
instance.readOffset(readBuff, read, readAvailable, 0);
|
||||
instance.consumeReadData(rCount);
|
||||
read += rCount;
|
||||
}
|
||||
}
|
||||
while ((read != wrData.length) || (written != wrData.length));
|
||||
}
|
||||
|
||||
public void testSomeMultiTest()
|
||||
{
|
||||
int Alen = 16;
|
||||
int Blen = 32;
|
||||
int Clen = 64;
|
||||
int Dlen = 256;
|
||||
int len = Alen + Blen + Clen + Dlen;
|
||||
ByteFifoBuffer fifo = new ByteFifoBuffer(len);
|
||||
byte[] A = getWData(Alen);
|
||||
/*byte[] B =*/ getWData(Blen);
|
||||
/*byte[] C =*/ getWData(Clen);
|
||||
/*byte[] D =*/ getWData(Dlen);
|
||||
byte[] Aread = getWData(Alen);
|
||||
/*byte[] Bread =*/ getWData(Blen);
|
||||
/*byte[] Cread =*/ getWData(Clen);
|
||||
/*byte[] Dread =*/ getWData(Dlen);
|
||||
|
||||
fifo.writeOffset(A, Alen, 0);
|
||||
fifo.consumeWriteBuffer(Alen);
|
||||
fifo.readOffset(Aread, 0, Alen, 0);
|
||||
assertArrayEquals(A, Aread);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||
*
|
||||
* Copyright @ 2015 Atlassian Pty Ltd
|
||||
@ -15,465 +15,465 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package test;
|
||||
|
||||
import java.beans.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.ice.*;
|
||||
import org.ice4j.ice.harvest.*;
|
||||
import org.ice4j.pseudotcp.*;
|
||||
import org.ice4j.security.*;
|
||||
|
||||
/**
|
||||
* Sample program which first uses ICE to discover UDP connectivity. After that
|
||||
* selected cadidates are used by "remote" and "local" pseudoTCP peers to
|
||||
* transfer some test data.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class IcePseudoTcp
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(IcePseudoTcp.class.getName());
|
||||
private static long startTime;
|
||||
/**
|
||||
* Local job thread variable
|
||||
*/
|
||||
private static LocalPseudoTcpJob localJob = null;
|
||||
/**
|
||||
* Remote job thread variable
|
||||
*/
|
||||
private static RemotePseudoTcpJob remoteJob = null;
|
||||
/**
|
||||
* Test data size
|
||||
*/
|
||||
private static final int TEST_BYTES_COUNT = 15000000;
|
||||
/**
|
||||
* Flag inidcates if STUN should be used
|
||||
*/
|
||||
private static final boolean USE_STUN = true;
|
||||
/**
|
||||
* Flag inidcates if TURN should be used
|
||||
*/
|
||||
private static final boolean USE_TURN = true;
|
||||
/**
|
||||
* Monitor object used to wait for remote agent to finish it's job
|
||||
*/
|
||||
private static final Object remoteAgentMonitor = new Object();
|
||||
/**
|
||||
* Monitor object used to wait for local agent to finish it's job
|
||||
*/
|
||||
private static final Object localAgentMonitor = new Object();
|
||||
/**
|
||||
* Timeout for ICE discovery
|
||||
*/
|
||||
private static long agentJobTimeout = 15000;
|
||||
|
||||
protected static Agent createAgent(int pTcpPort)
|
||||
throws Throwable
|
||||
{
|
||||
Agent agent = new Agent();
|
||||
// STUN
|
||||
if (USE_STUN)
|
||||
{
|
||||
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
|
||||
new TransportAddress("sip-communicator.net",
|
||||
3478, Transport.UDP));
|
||||
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
|
||||
new TransportAddress("ipv6.sip-communicator.net",
|
||||
3478, Transport.UDP));
|
||||
|
||||
agent.addCandidateHarvester(stunHarv);
|
||||
agent.addCandidateHarvester(stun6Harv);
|
||||
}
|
||||
// TURN
|
||||
if (USE_TURN)
|
||||
{
|
||||
String[] hostnames = new String[]
|
||||
{
|
||||
"130.79.90.150",
|
||||
"2001:660:4701:1001:230:5ff:fe1a:805f"
|
||||
};
|
||||
int port = 3478;
|
||||
LongTermCredential longTermCredential = new LongTermCredential(
|
||||
"guest", "anonymouspower!!");
|
||||
|
||||
for (String hostname : hostnames)
|
||||
{
|
||||
agent.addCandidateHarvester(new TurnCandidateHarvester(
|
||||
new TransportAddress(hostname, port,
|
||||
Transport.UDP), longTermCredential));
|
||||
}
|
||||
}
|
||||
//STREAM
|
||||
createStream(pTcpPort, "data", agent);
|
||||
|
||||
return agent;
|
||||
}
|
||||
|
||||
private static IceMediaStream createStream(int pTcpPort,
|
||||
String streamName,
|
||||
Agent agent)
|
||||
throws Throwable
|
||||
{
|
||||
IceMediaStream stream = agent.createMediaStream(streamName);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
//udp component
|
||||
agent.createComponent(
|
||||
stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
logger.log(Level.INFO,
|
||||
"UDP Component created in " + (endTime - startTime) + " ms");
|
||||
startTime = endTime;
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static final class LocalIceProcessingListener
|
||||
implements PropertyChangeListener
|
||||
{
|
||||
/**
|
||||
* System.exit()s as soon as ICE processing enters a final state.
|
||||
*
|
||||
* @param evt the {@link PropertyChangeEvent} containing the old and new
|
||||
* states of ICE processing.
|
||||
*/
|
||||
public void propertyChange(PropertyChangeEvent evt)
|
||||
{
|
||||
long processingEndTime = System.currentTimeMillis();
|
||||
|
||||
Object iceProcessingState = evt.getNewValue();
|
||||
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Local agent entered the " + iceProcessingState
|
||||
+ " state.");
|
||||
if (iceProcessingState == IceProcessingState.COMPLETED)
|
||||
{
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Local - Total ICE processing time: "
|
||||
+ (processingEndTime - startTime) + "ms");
|
||||
Agent agent = (Agent) evt.getSource();
|
||||
logger.log(Level.INFO, "Local: Create pseudo tcp stream");
|
||||
IceMediaStream dataStream = agent.getStream("data");
|
||||
Component udpComponent = dataStream.getComponents().get(0);
|
||||
CandidatePair selectedPair = udpComponent.getSelectedPair();
|
||||
if (selectedPair != null)
|
||||
{
|
||||
LocalCandidate localCandidate
|
||||
= selectedPair.getLocalCandidate();
|
||||
Candidate<?> remoteCandidate
|
||||
= selectedPair.getRemoteCandidate();
|
||||
logger.log(Level.INFO, "Local: " + localCandidate);
|
||||
logger.log(Level.INFO, "Remote: " + remoteCandidate);
|
||||
try
|
||||
{
|
||||
localJob = new LocalPseudoTcpJob(
|
||||
selectedPair.getDatagramSocket());
|
||||
}
|
||||
catch (UnknownHostException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Error while trying to create"
|
||||
+ " local pseudotcp thread " + ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Failed to select any candidate pair");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iceProcessingState == IceProcessingState.TERMINATED
|
||||
|| iceProcessingState == IceProcessingState.FAILED)
|
||||
{
|
||||
/*
|
||||
* Though the process will be instructed to die, demonstrate
|
||||
* that Agent instances are to be explicitly prepared for
|
||||
* garbage collection.
|
||||
*/
|
||||
if ((localJob != null)
|
||||
&& (iceProcessingState
|
||||
== IceProcessingState.TERMINATED))
|
||||
{
|
||||
localJob.start();
|
||||
}
|
||||
synchronized (localAgentMonitor)
|
||||
{
|
||||
localAgentMonitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RemoteIceProcessingListener
|
||||
implements PropertyChangeListener
|
||||
{
|
||||
/**
|
||||
* System.exit()s as soon as ICE processing enters a final state.
|
||||
*
|
||||
* @param evt the {@link PropertyChangeEvent} containing the old and new
|
||||
* states of ICE processing.
|
||||
*/
|
||||
public void propertyChange(PropertyChangeEvent evt)
|
||||
{
|
||||
long processingEndTime = System.currentTimeMillis();
|
||||
|
||||
Object iceProcessingState = evt.getNewValue();
|
||||
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Remote agent entered the " + iceProcessingState
|
||||
+ " state.");
|
||||
if (iceProcessingState == IceProcessingState.COMPLETED)
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Total ICE processing time: "
|
||||
+ (processingEndTime - startTime) + " ms ");
|
||||
Agent agent = (Agent) evt.getSource();
|
||||
|
||||
logger.log(Level.INFO, "Remote: Create pseudo tcp stream");
|
||||
IceMediaStream dataStream = agent.getStream("data");
|
||||
Component udpComponent = dataStream.getComponents().get(0);
|
||||
CandidatePair usedPair = udpComponent.getSelectedPair();
|
||||
if (usedPair != null)
|
||||
{
|
||||
LocalCandidate localCandidate
|
||||
= usedPair.getLocalCandidate();
|
||||
Candidate<?> remoteCandidate
|
||||
= usedPair.getRemoteCandidate();
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Local address " + localCandidate);
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Peer address " + remoteCandidate);
|
||||
try
|
||||
{
|
||||
remoteJob = new RemotePseudoTcpJob(
|
||||
usedPair.getDatagramSocket(),
|
||||
remoteCandidate.getTransportAddress());
|
||||
}
|
||||
catch (UnknownHostException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Error while trying to create"
|
||||
+ " remote pseudotcp thread " + ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Remote: Failed to select any candidate pair");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iceProcessingState == IceProcessingState.TERMINATED
|
||||
|| iceProcessingState == IceProcessingState.FAILED)
|
||||
{
|
||||
/*
|
||||
* Though the process will be instructed to die, demonstrate
|
||||
* that Agent instances are to be explicitly prepared for
|
||||
* garbage collection.
|
||||
*/
|
||||
if ((remoteJob != null)
|
||||
&& (iceProcessingState
|
||||
== IceProcessingState.TERMINATED))
|
||||
{
|
||||
remoteJob.start();
|
||||
}
|
||||
synchronized (remoteAgentMonitor)
|
||||
{
|
||||
remoteAgentMonitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable
|
||||
{
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int localPort = 7999;
|
||||
int remotePort = 6000;
|
||||
|
||||
Agent localAgent = createAgent(localPort);
|
||||
localAgent.setNominationStrategy(
|
||||
NominationStrategy.NOMINATE_HIGHEST_PRIO);
|
||||
Agent remotePeer =
|
||||
createAgent(remotePort);
|
||||
|
||||
localAgent.addStateChangeListener(
|
||||
new IcePseudoTcp.LocalIceProcessingListener());
|
||||
remotePeer.addStateChangeListener(
|
||||
new IcePseudoTcp.RemoteIceProcessingListener());
|
||||
|
||||
//let them fight ... fights forge character.
|
||||
localAgent.setControlling(true);
|
||||
remotePeer.setControlling(false);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
|
||||
Ice.transferRemoteCandidates(localAgent, remotePeer);
|
||||
for (IceMediaStream stream : localAgent.getStreams())
|
||||
{
|
||||
stream.setRemoteUfrag(remotePeer.getLocalUfrag());
|
||||
stream.setRemotePassword(remotePeer.getLocalPassword());
|
||||
}
|
||||
|
||||
Ice.transferRemoteCandidates(remotePeer, localAgent);
|
||||
|
||||
for (IceMediaStream stream : remotePeer.getStreams())
|
||||
{
|
||||
stream.setRemoteUfrag(localAgent.getLocalUfrag());
|
||||
stream.setRemotePassword(localAgent.getLocalPassword());
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "Total candidate gathering time: {0} ms",
|
||||
(endTime - startTime));
|
||||
logger.log(Level.INFO, "LocalAgent: {0}",
|
||||
localAgent);
|
||||
|
||||
localAgent.startConnectivityEstablishment();
|
||||
|
||||
//if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER)
|
||||
remotePeer.startConnectivityEstablishment();
|
||||
|
||||
|
||||
IceMediaStream dataStream = localAgent.getStream("data");
|
||||
|
||||
if (dataStream != null)
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Local data clist:" + dataStream.getCheckList());
|
||||
}
|
||||
//wait for one of the agents to complete it's job
|
||||
synchronized (remoteAgentMonitor)
|
||||
{
|
||||
remoteAgentMonitor.wait(agentJobTimeout);
|
||||
}
|
||||
if (remoteJob != null)
|
||||
{
|
||||
logger.log(Level.FINEST, "Remote thread join started");
|
||||
remoteJob.join();
|
||||
logger.log(Level.FINEST, "Remote thread joined");
|
||||
}
|
||||
remotePeer.free();
|
||||
if (localJob != null)
|
||||
{
|
||||
logger.log(Level.FINEST, "Local thread join started");
|
||||
localJob.join();
|
||||
logger.log(Level.FINEST, "Local thread joined");
|
||||
}
|
||||
localAgent.free();
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
private static class LocalPseudoTcpJob extends Thread implements Runnable
|
||||
{
|
||||
private DatagramSocket dgramSocket;
|
||||
|
||||
public LocalPseudoTcpJob(DatagramSocket socket)
|
||||
throws UnknownHostException
|
||||
{
|
||||
this.dgramSocket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
logger.log(Level.FINEST, "Local pseudotcp worker started");
|
||||
try
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Local pseudotcp is using: "
|
||||
+ dgramSocket.getLocalSocketAddress()+dgramSocket);
|
||||
|
||||
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
|
||||
createSocket(dgramSocket);
|
||||
socket.setConversationID(1073741824);
|
||||
socket.setMTU(1500);
|
||||
socket.setDebugName("L");
|
||||
socket.accept(5000);
|
||||
byte[] buffer = new byte[TEST_BYTES_COUNT];
|
||||
int read = 0;
|
||||
while (read != TEST_BYTES_COUNT)
|
||||
{
|
||||
read += socket.getInputStream().read(buffer);
|
||||
logger.log(Level.FINEST, "Local job read: " + read);
|
||||
}
|
||||
//TODO: close when all received data is acked
|
||||
//socket.close();
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logger.log(Level.FINEST, "Local pseudotcp worker finished");
|
||||
}
|
||||
}
|
||||
|
||||
private static class RemotePseudoTcpJob extends Thread implements Runnable
|
||||
{
|
||||
private DatagramSocket dgramSocket;
|
||||
private InetSocketAddress peerAddr;
|
||||
|
||||
public RemotePseudoTcpJob(DatagramSocket socket,
|
||||
InetSocketAddress peerAddr)
|
||||
throws UnknownHostException
|
||||
{
|
||||
this.dgramSocket = socket;
|
||||
this.peerAddr = peerAddr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
logger.log(Level.FINEST, "Remote pseudotcp worker started");
|
||||
try
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Remote pseudotcp is using: " +
|
||||
dgramSocket.getLocalSocketAddress()
|
||||
+" and will comunicate with: " + peerAddr);
|
||||
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
|
||||
createSocket(dgramSocket);
|
||||
socket.setConversationID(1073741824);
|
||||
socket.setMTU(1500);
|
||||
socket.setDebugName("R");
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
socket.connect(peerAddr, 5000);
|
||||
byte[] buffer = new byte[TEST_BYTES_COUNT];
|
||||
socket.getOutputStream().write(buffer);
|
||||
socket.getOutputStream().flush();
|
||||
//Socket will be closed by the iceAgent
|
||||
//socket.close();
|
||||
end = System.currentTimeMillis();
|
||||
logger.log(Level.INFO,
|
||||
"Transferred " + TEST_BYTES_COUNT
|
||||
+ " bytes in " + ((end - start) / 1000) + " sec");
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logger.log(Level.FINEST, "Remote pseudotcp worker finished");
|
||||
}
|
||||
}
|
||||
}
|
||||
package test;
|
||||
|
||||
import java.beans.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.logging.*;
|
||||
|
||||
import org.ice4j.*;
|
||||
import org.ice4j.ice.*;
|
||||
import org.ice4j.ice.harvest.*;
|
||||
import org.ice4j.pseudotcp.*;
|
||||
import org.ice4j.security.*;
|
||||
|
||||
/**
|
||||
* Sample program which first uses ICE to discover UDP connectivity. After that
|
||||
* selected cadidates are used by "remote" and "local" pseudoTCP peers to
|
||||
* transfer some test data.
|
||||
*
|
||||
* @author Pawel Domas
|
||||
*/
|
||||
public class IcePseudoTcp
|
||||
{
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private static final Logger logger =
|
||||
Logger.getLogger(IcePseudoTcp.class.getName());
|
||||
private static long startTime;
|
||||
/**
|
||||
* Local job thread variable
|
||||
*/
|
||||
private static LocalPseudoTcpJob localJob = null;
|
||||
/**
|
||||
* Remote job thread variable
|
||||
*/
|
||||
private static RemotePseudoTcpJob remoteJob = null;
|
||||
/**
|
||||
* Test data size
|
||||
*/
|
||||
private static final int TEST_BYTES_COUNT = 15000000;
|
||||
/**
|
||||
* Flag inidcates if STUN should be used
|
||||
*/
|
||||
private static final boolean USE_STUN = true;
|
||||
/**
|
||||
* Flag inidcates if TURN should be used
|
||||
*/
|
||||
private static final boolean USE_TURN = true;
|
||||
/**
|
||||
* Monitor object used to wait for remote agent to finish it's job
|
||||
*/
|
||||
private static final Object remoteAgentMonitor = new Object();
|
||||
/**
|
||||
* Monitor object used to wait for local agent to finish it's job
|
||||
*/
|
||||
private static final Object localAgentMonitor = new Object();
|
||||
/**
|
||||
* Timeout for ICE discovery
|
||||
*/
|
||||
private static long agentJobTimeout = 15000;
|
||||
|
||||
protected static Agent createAgent(int pTcpPort)
|
||||
throws Throwable
|
||||
{
|
||||
Agent agent = new Agent();
|
||||
// STUN
|
||||
if (USE_STUN)
|
||||
{
|
||||
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
|
||||
new TransportAddress("sip-communicator.net",
|
||||
3478, Transport.UDP));
|
||||
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
|
||||
new TransportAddress("ipv6.sip-communicator.net",
|
||||
3478, Transport.UDP));
|
||||
|
||||
agent.addCandidateHarvester(stunHarv);
|
||||
agent.addCandidateHarvester(stun6Harv);
|
||||
}
|
||||
// TURN
|
||||
if (USE_TURN)
|
||||
{
|
||||
String[] hostnames = new String[]
|
||||
{
|
||||
"130.79.90.150",
|
||||
"2001:660:4701:1001:230:5ff:fe1a:805f"
|
||||
};
|
||||
int port = 3478;
|
||||
LongTermCredential longTermCredential = new LongTermCredential(
|
||||
"guest", "anonymouspower!!");
|
||||
|
||||
for (String hostname : hostnames)
|
||||
{
|
||||
agent.addCandidateHarvester(new TurnCandidateHarvester(
|
||||
new TransportAddress(hostname, port,
|
||||
Transport.UDP), longTermCredential));
|
||||
}
|
||||
}
|
||||
//STREAM
|
||||
createStream(pTcpPort, "data", agent);
|
||||
|
||||
return agent;
|
||||
}
|
||||
|
||||
private static IceMediaStream createStream(int pTcpPort,
|
||||
String streamName,
|
||||
Agent agent)
|
||||
throws Throwable
|
||||
{
|
||||
IceMediaStream stream = agent.createMediaStream(streamName);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
//udp component
|
||||
agent.createComponent(
|
||||
stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
logger.log(Level.INFO,
|
||||
"UDP Component created in " + (endTime - startTime) + " ms");
|
||||
startTime = endTime;
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static final class LocalIceProcessingListener
|
||||
implements PropertyChangeListener
|
||||
{
|
||||
/**
|
||||
* System.exit()s as soon as ICE processing enters a final state.
|
||||
*
|
||||
* @param evt the {@link PropertyChangeEvent} containing the old and new
|
||||
* states of ICE processing.
|
||||
*/
|
||||
public void propertyChange(PropertyChangeEvent evt)
|
||||
{
|
||||
long processingEndTime = System.currentTimeMillis();
|
||||
|
||||
Object iceProcessingState = evt.getNewValue();
|
||||
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Local agent entered the " + iceProcessingState
|
||||
+ " state.");
|
||||
if (iceProcessingState == IceProcessingState.COMPLETED)
|
||||
{
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Local - Total ICE processing time: "
|
||||
+ (processingEndTime - startTime) + "ms");
|
||||
Agent agent = (Agent) evt.getSource();
|
||||
logger.log(Level.INFO, "Local: Create pseudo tcp stream");
|
||||
IceMediaStream dataStream = agent.getStream("data");
|
||||
Component udpComponent = dataStream.getComponents().get(0);
|
||||
CandidatePair selectedPair = udpComponent.getSelectedPair();
|
||||
if (selectedPair != null)
|
||||
{
|
||||
LocalCandidate localCandidate
|
||||
= selectedPair.getLocalCandidate();
|
||||
Candidate<?> remoteCandidate
|
||||
= selectedPair.getRemoteCandidate();
|
||||
logger.log(Level.INFO, "Local: " + localCandidate);
|
||||
logger.log(Level.INFO, "Remote: " + remoteCandidate);
|
||||
try
|
||||
{
|
||||
localJob = new LocalPseudoTcpJob(
|
||||
selectedPair.getDatagramSocket());
|
||||
}
|
||||
catch (UnknownHostException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Error while trying to create"
|
||||
+ " local pseudotcp thread " + ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Failed to select any candidate pair");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iceProcessingState == IceProcessingState.TERMINATED
|
||||
|| iceProcessingState == IceProcessingState.FAILED)
|
||||
{
|
||||
/*
|
||||
* Though the process will be instructed to die, demonstrate
|
||||
* that Agent instances are to be explicitly prepared for
|
||||
* garbage collection.
|
||||
*/
|
||||
if ((localJob != null)
|
||||
&& (iceProcessingState
|
||||
== IceProcessingState.TERMINATED))
|
||||
{
|
||||
localJob.start();
|
||||
}
|
||||
synchronized (localAgentMonitor)
|
||||
{
|
||||
localAgentMonitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RemoteIceProcessingListener
|
||||
implements PropertyChangeListener
|
||||
{
|
||||
/**
|
||||
* System.exit()s as soon as ICE processing enters a final state.
|
||||
*
|
||||
* @param evt the {@link PropertyChangeEvent} containing the old and new
|
||||
* states of ICE processing.
|
||||
*/
|
||||
public void propertyChange(PropertyChangeEvent evt)
|
||||
{
|
||||
long processingEndTime = System.currentTimeMillis();
|
||||
|
||||
Object iceProcessingState = evt.getNewValue();
|
||||
|
||||
logger.log(
|
||||
Level.INFO,
|
||||
"Remote agent entered the " + iceProcessingState
|
||||
+ " state.");
|
||||
if (iceProcessingState == IceProcessingState.COMPLETED)
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Total ICE processing time: "
|
||||
+ (processingEndTime - startTime) + " ms ");
|
||||
Agent agent = (Agent) evt.getSource();
|
||||
|
||||
logger.log(Level.INFO, "Remote: Create pseudo tcp stream");
|
||||
IceMediaStream dataStream = agent.getStream("data");
|
||||
Component udpComponent = dataStream.getComponents().get(0);
|
||||
CandidatePair usedPair = udpComponent.getSelectedPair();
|
||||
if (usedPair != null)
|
||||
{
|
||||
LocalCandidate localCandidate
|
||||
= usedPair.getLocalCandidate();
|
||||
Candidate<?> remoteCandidate
|
||||
= usedPair.getRemoteCandidate();
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Local address " + localCandidate);
|
||||
logger.log(Level.INFO,
|
||||
"Remote: Peer address " + remoteCandidate);
|
||||
try
|
||||
{
|
||||
remoteJob = new RemotePseudoTcpJob(
|
||||
usedPair.getDatagramSocket(),
|
||||
remoteCandidate.getTransportAddress());
|
||||
}
|
||||
catch (UnknownHostException ex)
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Error while trying to create"
|
||||
+ " remote pseudotcp thread " + ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.log(Level.SEVERE,
|
||||
"Remote: Failed to select any candidate pair");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iceProcessingState == IceProcessingState.TERMINATED
|
||||
|| iceProcessingState == IceProcessingState.FAILED)
|
||||
{
|
||||
/*
|
||||
* Though the process will be instructed to die, demonstrate
|
||||
* that Agent instances are to be explicitly prepared for
|
||||
* garbage collection.
|
||||
*/
|
||||
if ((remoteJob != null)
|
||||
&& (iceProcessingState
|
||||
== IceProcessingState.TERMINATED))
|
||||
{
|
||||
remoteJob.start();
|
||||
}
|
||||
synchronized (remoteAgentMonitor)
|
||||
{
|
||||
remoteAgentMonitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable
|
||||
{
|
||||
startTime = System.currentTimeMillis();
|
||||
|
||||
int localPort = 7999;
|
||||
int remotePort = 6000;
|
||||
|
||||
Agent localAgent = createAgent(localPort);
|
||||
localAgent.setNominationStrategy(
|
||||
NominationStrategy.NOMINATE_HIGHEST_PRIO);
|
||||
Agent remotePeer =
|
||||
createAgent(remotePort);
|
||||
|
||||
localAgent.addStateChangeListener(
|
||||
new IcePseudoTcp.LocalIceProcessingListener());
|
||||
remotePeer.addStateChangeListener(
|
||||
new IcePseudoTcp.RemoteIceProcessingListener());
|
||||
|
||||
//let them fight ... fights forge character.
|
||||
localAgent.setControlling(true);
|
||||
remotePeer.setControlling(false);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
|
||||
Ice.transferRemoteCandidates(localAgent, remotePeer);
|
||||
for (IceMediaStream stream : localAgent.getStreams())
|
||||
{
|
||||
stream.setRemoteUfrag(remotePeer.getLocalUfrag());
|
||||
stream.setRemotePassword(remotePeer.getLocalPassword());
|
||||
}
|
||||
|
||||
Ice.transferRemoteCandidates(remotePeer, localAgent);
|
||||
|
||||
for (IceMediaStream stream : remotePeer.getStreams())
|
||||
{
|
||||
stream.setRemoteUfrag(localAgent.getLocalUfrag());
|
||||
stream.setRemotePassword(localAgent.getLocalPassword());
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, "Total candidate gathering time: {0} ms",
|
||||
(endTime - startTime));
|
||||
logger.log(Level.INFO, "LocalAgent: {0}",
|
||||
localAgent);
|
||||
|
||||
localAgent.startConnectivityEstablishment();
|
||||
|
||||
//if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER)
|
||||
remotePeer.startConnectivityEstablishment();
|
||||
|
||||
|
||||
IceMediaStream dataStream = localAgent.getStream("data");
|
||||
|
||||
if (dataStream != null)
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Local data clist:" + dataStream.getCheckList());
|
||||
}
|
||||
//wait for one of the agents to complete it's job
|
||||
synchronized (remoteAgentMonitor)
|
||||
{
|
||||
remoteAgentMonitor.wait(agentJobTimeout);
|
||||
}
|
||||
if (remoteJob != null)
|
||||
{
|
||||
logger.log(Level.FINEST, "Remote thread join started");
|
||||
remoteJob.join();
|
||||
logger.log(Level.FINEST, "Remote thread joined");
|
||||
}
|
||||
remotePeer.free();
|
||||
if (localJob != null)
|
||||
{
|
||||
logger.log(Level.FINEST, "Local thread join started");
|
||||
localJob.join();
|
||||
logger.log(Level.FINEST, "Local thread joined");
|
||||
}
|
||||
localAgent.free();
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
private static class LocalPseudoTcpJob extends Thread implements Runnable
|
||||
{
|
||||
private DatagramSocket dgramSocket;
|
||||
|
||||
public LocalPseudoTcpJob(DatagramSocket socket)
|
||||
throws UnknownHostException
|
||||
{
|
||||
this.dgramSocket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
logger.log(Level.FINEST, "Local pseudotcp worker started");
|
||||
try
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Local pseudotcp is using: "
|
||||
+ dgramSocket.getLocalSocketAddress()+dgramSocket);
|
||||
|
||||
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
|
||||
createSocket(dgramSocket);
|
||||
socket.setConversationID(1073741824);
|
||||
socket.setMTU(1500);
|
||||
socket.setDebugName("L");
|
||||
socket.accept(5000);
|
||||
byte[] buffer = new byte[TEST_BYTES_COUNT];
|
||||
int read = 0;
|
||||
while (read != TEST_BYTES_COUNT)
|
||||
{
|
||||
read += socket.getInputStream().read(buffer);
|
||||
logger.log(Level.FINEST, "Local job read: " + read);
|
||||
}
|
||||
//TODO: close when all received data is acked
|
||||
//socket.close();
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logger.log(Level.FINEST, "Local pseudotcp worker finished");
|
||||
}
|
||||
}
|
||||
|
||||
private static class RemotePseudoTcpJob extends Thread implements Runnable
|
||||
{
|
||||
private DatagramSocket dgramSocket;
|
||||
private InetSocketAddress peerAddr;
|
||||
|
||||
public RemotePseudoTcpJob(DatagramSocket socket,
|
||||
InetSocketAddress peerAddr)
|
||||
throws UnknownHostException
|
||||
{
|
||||
this.dgramSocket = socket;
|
||||
this.peerAddr = peerAddr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
logger.log(Level.FINEST, "Remote pseudotcp worker started");
|
||||
try
|
||||
{
|
||||
logger.log(Level.INFO,
|
||||
"Remote pseudotcp is using: " +
|
||||
dgramSocket.getLocalSocketAddress()
|
||||
+" and will comunicate with: " + peerAddr);
|
||||
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
|
||||
createSocket(dgramSocket);
|
||||
socket.setConversationID(1073741824);
|
||||
socket.setMTU(1500);
|
||||
socket.setDebugName("R");
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
socket.connect(peerAddr, 5000);
|
||||
byte[] buffer = new byte[TEST_BYTES_COUNT];
|
||||
socket.getOutputStream().write(buffer);
|
||||
socket.getOutputStream().flush();
|
||||
//Socket will be closed by the iceAgent
|
||||
//socket.close();
|
||||
end = System.currentTimeMillis();
|
||||
logger.log(Level.INFO,
|
||||
"Transferred " + TEST_BYTES_COUNT
|
||||
+ " bytes in " + ((end - start) / 1000) + " sec");
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
logger.log(Level.FINEST, "Remote pseudotcp worker finished");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user