Fix line endings in PseudoTCP code

This commit is contained in:
Ingo Bauersachs 2015-10-28 15:36:09 +01:00
parent 10b4e911ef
commit da2194444c
22 changed files with 6245 additions and 6245 deletions

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,172 +15,172 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
/** /**
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public abstract class IceControlAttribute public abstract class IceControlAttribute
extends Attribute extends Attribute
{ {
/** /**
* The length of the data contained in this attribute * The length of the data contained in this attribute
*/ */
static final char DATA_LENGTH_ICE_CONTROL = 8; static final char DATA_LENGTH_ICE_CONTROL = 8;
/** /**
* The tie-breaker value stored in this attribute * The tie-breaker value stored in this attribute
*/ */
long tieBreaker; long tieBreaker;
/** /**
* Indicates whether this is an <tt>ICE-CONTROLLING</tt> or an * Indicates whether this is an <tt>ICE-CONTROLLING</tt> or an
* <tt>ICE-CONTROLLED</tt> attribute. * <tt>ICE-CONTROLLED</tt> attribute.
*/ */
boolean isControlling; boolean isControlling;
/** /**
* Constructs an ICE-CONTROLLING or an ICE-CONTROLLED attribute depending * Constructs an ICE-CONTROLLING or an ICE-CONTROLLED attribute depending
* on the value of <tt>isControlling</tt>. * on the value of <tt>isControlling</tt>.
* *
* @param isControlling indicates the kind of attribute we are trying to * @param isControlling indicates the kind of attribute we are trying to
* create * create
*/ */
IceControlAttribute(boolean isControlling) IceControlAttribute(boolean isControlling)
{ {
super(isControlling ? ICE_CONTROLLING : ICE_CONTROLLED); super(isControlling ? ICE_CONTROLLING : ICE_CONTROLLED);
this.isControlling = isControlling; this.isControlling = isControlling;
} }
/** /**
* Sets this attribute's fields according to attributeValue array. * Sets this attribute's fields according to attributeValue array.
* *
* @param attributeValue a binary array containing this attribute's field * @param attributeValue a binary array containing this attribute's field
* values and NOT containing the attribute header. * values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often * @param offset the position where attribute values begin (most often
* offset is equal to the index of the first byte after * offset is equal to the index of the first byte after
* length) * length)
* @param length the length of the attribute data. * @param length the length of the attribute data.
* *
* @throws StunException if attrubteValue contains invalid data. * @throws StunException if attrubteValue contains invalid data.
*/ */
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
// array used to hold the intermediate long values reconstructed from // array used to hold the intermediate long values reconstructed from
// the attributeValue array // the attributeValue array
// Reading in the network byte order (Big-Endian) // Reading in the network byte order (Big-Endian)
tieBreaker = ((attributeValue[offset++] & 0xffl) << 56) tieBreaker = ((attributeValue[offset++] & 0xffl) << 56)
| ((attributeValue[offset++] & 0xffl) << 48) | ((attributeValue[offset++] & 0xffl) << 48)
| ((attributeValue[offset++] & 0xffl) << 40) | ((attributeValue[offset++] & 0xffl) << 40)
| ((attributeValue[offset++] & 0xffl) << 32) | ((attributeValue[offset++] & 0xffl) << 32)
| ((attributeValue[offset++] & 0xffl) << 24) | ((attributeValue[offset++] & 0xffl) << 24)
| ((attributeValue[offset++] & 0xffl) << 16) | ((attributeValue[offset++] & 0xffl) << 16)
| ((attributeValue[offset++] & 0xffl) << 8) | ((attributeValue[offset++] & 0xffl) << 8)
| (attributeValue[offset++] & 0xffl); | (attributeValue[offset++] & 0xffl);
} }
/** /**
* Returns a binary representation of this attribute. * Returns a binary representation of this attribute.
* *
* @return a binary representation of this attribute. * @return a binary representation of this attribute.
*/ */
public byte[] encode() public byte[] encode()
{ {
char type = getAttributeType(); char type = getAttributeType();
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()]; byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
//Type //Type
binValue[0] = (byte)(type >> 8); binValue[0] = (byte)(type >> 8);
binValue[1] = (byte)(type & 0x00FF); binValue[1] = (byte)(type & 0x00FF);
//Length //Length
binValue[2] = (byte)(getDataLength() >> 8); binValue[2] = (byte)(getDataLength() >> 8);
binValue[3] = (byte)(getDataLength() & 0x00FF); binValue[3] = (byte)(getDataLength() & 0x00FF);
//Tie-Breaker //Tie-Breaker
binValue[4] = (byte)((tieBreaker & 0xFF00000000000000L) >> 56); binValue[4] = (byte)((tieBreaker & 0xFF00000000000000L) >> 56);
binValue[5] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48); binValue[5] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48);
binValue[6] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40); binValue[6] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40);
binValue[7] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32); binValue[7] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32);
binValue[8] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24); binValue[8] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24);
binValue[9] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16); binValue[9] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16);
binValue[10] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8); binValue[10] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8);
binValue[11] = (byte)( tieBreaker & 0x00000000000000FFL); binValue[11] = (byte)( tieBreaker & 0x00000000000000FFL);
return binValue; return binValue;
} }
/** /**
* Compares two STUN Attributes. Attributes are considered equal when their * Compares two STUN Attributes. Attributes are considered equal when their
* type, length, and all data are the same. * type, length, and all data are the same.
* *
* @param obj the object to compare this attribute with. * @param obj the object to compare this attribute with.
* *
* @return true if the attributes are equal and false otherwise. * @return true if the attributes are equal and false otherwise.
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof IceControlAttribute) if(!(obj instanceof IceControlAttribute)
|| obj == null) || obj == null)
return false; return false;
if(obj == this) if(obj == this)
return true; return true;
IceControlAttribute iceControlAtt = (IceControlAttribute)obj; IceControlAttribute iceControlAtt = (IceControlAttribute)obj;
if(iceControlAtt.getAttributeType() != getAttributeType() if(iceControlAtt.getAttributeType() != getAttributeType()
|| iceControlAtt.isControlling != isControlling || iceControlAtt.isControlling != isControlling
|| iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL || iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL
|| getTieBreaker() != iceControlAtt.getTieBreaker()) || getTieBreaker() != iceControlAtt.getTieBreaker())
{ {
return false; return false;
} }
return true; return true;
} }
/** /**
* Returns the data length of this attribute * Returns the data length of this attribute
* *
* @return the data length of this attribute * @return the data length of this attribute
*/ */
public char getDataLength() public char getDataLength()
{ {
return DATA_LENGTH_ICE_CONTROL; return DATA_LENGTH_ICE_CONTROL;
} }
/** /**
* Returns the human readable name of this attribute. * Returns the human readable name of this attribute.
* *
* @return this attribute's name. * @return this attribute's name.
*/ */
public String getName() public String getName()
{ {
return isControlling ? "ICE-CONTROLLING" : "ICE-CONTROLLED"; return isControlling ? "ICE-CONTROLLING" : "ICE-CONTROLLED";
} }
/** /**
* Sets the tie-breaker value. * Sets the tie-breaker value.
* *
* @param tieBreaker the the tie-breaker value * @param tieBreaker the the tie-breaker value
*/ */
public void setTieBreaker(long tieBreaker) public void setTieBreaker(long tieBreaker)
{ {
this.tieBreaker = tieBreaker; this.tieBreaker = tieBreaker;
} }
/** /**
* Returns the value of the tie-breaker. * Returns the value of the tie-breaker.
* *
* @return the value of the tie-breaker. * @return the value of the tie-breaker.
*/ */
public long getTieBreaker() public long getTieBreaker()
{ {
return tieBreaker; return tieBreaker;
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,172 +15,172 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
/** /**
* This class is used to represent the PRIORITY attribute used for ICE processing * This class is used to represent the PRIORITY attribute used for ICE processing
* This attribute is not in the original specification of STUN * This attribute is not in the original specification of STUN
* It is added as an extension to STUN to be used for ICE implementations * It is added as an extension to STUN to be used for ICE implementations
* *
* PRIORITY attribute contains a 32 bit priority value * PRIORITY attribute contains a 32 bit priority value
* It is used in stun binding requests sent from ICE-Agents to their * It is used in stun binding requests sent from ICE-Agents to their
* peers * peers
* *
* @author Namal Senarathne * @author Namal Senarathne
*/ */
public class PriorityAttribute public class PriorityAttribute
extends Attribute extends Attribute
{ {
/** /**
* The length of the Data contained in the Priority Attribute * The length of the Data contained in the Priority Attribute
*/ */
private static final char DATA_LENGTH_PRIORITY = 4; private static final char DATA_LENGTH_PRIORITY = 4;
/** /**
* The priority value specified in the attribute. An int should be enough * 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 * to store this value, but long is used, since candidate and candidate-pair
* classes use long to store priority values * classes use long to store priority values
*/ */
private long priority = 0; private long priority = 0;
/** /**
* Creates a priority attribute. * Creates a priority attribute.
*/ */
public PriorityAttribute() public PriorityAttribute()
{ {
super(PRIORITY); super(PRIORITY);
} }
/** /**
* Reconstructs the priority value from the given byte array * Reconstructs the priority value from the given byte array
* and stores it in the 'long' variable * and stores it in the 'long' variable
* *
* @param attributeValue a binary array containing this attribute's * @param attributeValue a binary array containing this attribute's
* field values and NOT containing the attribute header. * field values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often * @param offset the position where attribute values begin (most often
* offset is equal to the index of the first byte after length) * offset is equal to the index of the first byte after length)
* @param length the length of the binary array. * @param length the length of the binary array.
* @throws StunException if attrubteValue contains invalid data. * @throws StunException if attrubteValue contains invalid data.
*/ */
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
// array used to hold the intermediate long values reconstructed from // array used to hold the intermediate long values reconstructed from
// the attributeValue array // the attributeValue array
long[] values = new long[4]; long[] values = new long[4];
// Reading in the network byte order (Big-Endian) // Reading in the network byte order (Big-Endian)
values[0] = (long)((attributeValue[offset++] & 0xff) << 24); values[0] = (long)((attributeValue[offset++] & 0xff) << 24);
values[1] = (long)((attributeValue[offset++] & 0xff) << 16); values[1] = (long)((attributeValue[offset++] & 0xff) << 16);
values[2] = (long)((attributeValue[offset++] & 0xff) << 8); values[2] = (long)((attributeValue[offset++] & 0xff) << 8);
values[3] = (long)(attributeValue[offset++] & 0xff); values[3] = (long)(attributeValue[offset++] & 0xff);
// reconstructing the priority value // reconstructing the priority value
this.priority = values[0] | values[1] | values[2] | values[3]; this.priority = values[0] | values[1] | values[2] | values[3];
} }
/** /**
* Returns a binary representation of this attribute. * Returns a binary representation of this attribute.
* *
* @return a binary representation of this attribute. * @return a binary representation of this attribute.
*/ */
public byte[] encode() public byte[] encode()
{ {
char type = getAttributeType(); char type = getAttributeType();
byte[] binValue = new byte[HEADER_LENGTH + getDataLength()]; byte[] binValue = new byte[HEADER_LENGTH + getDataLength()];
//Type //Type
binValue[0] = (byte)(type >> 8); binValue[0] = (byte)(type >> 8);
binValue[1] = (byte)(type & 0x00FF); binValue[1] = (byte)(type & 0x00FF);
//Length //Length
binValue[2] = (byte)(getDataLength() >> 8); binValue[2] = (byte)(getDataLength() >> 8);
binValue[3] = (byte)(getDataLength() & 0x00FF); binValue[3] = (byte)(getDataLength() & 0x00FF);
//Priority //Priority
binValue[4] = (byte)((priority & 0xFF000000L) >> 24); binValue[4] = (byte)((priority & 0xFF000000L) >> 24);
binValue[5] = (byte)((priority & 0x00FF0000L) >> 16); binValue[5] = (byte)((priority & 0x00FF0000L) >> 16);
binValue[6] = (byte)((priority & 0x0000FF00L) >> 8); binValue[6] = (byte)((priority & 0x0000FF00L) >> 8);
binValue[7] = (byte)(priority & 0x000000FFL); binValue[7] = (byte)(priority & 0x000000FFL);
return binValue; return binValue;
} }
/** /**
* Compares two STUN Attributes. Two attributes are considered equal when * Compares two STUN Attributes. Two attributes are considered equal when
* they have the same type length and value. * they have the same type length and value.
* *
* @param obj the object to compare this attribute with. * @param obj the object to compare this attribute with.
* @return true if the attributes are equal and false otherwise. * @return true if the attributes are equal and false otherwise.
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if (! (obj instanceof PriorityAttribute) if (! (obj instanceof PriorityAttribute)
|| obj == null) || obj == null)
return false; return false;
if (obj == this) if (obj == this)
return true; return true;
PriorityAttribute att = (PriorityAttribute) obj; PriorityAttribute att = (PriorityAttribute) obj;
if (att.getAttributeType() != getAttributeType() if (att.getAttributeType() != getAttributeType()
|| att.getDataLength() != getDataLength() || att.getDataLength() != getDataLength()
|| (priority != att.priority)) || (priority != att.priority))
return false; return false;
return true; return true;
} }
/** /**
* Returns the length of this attribute's body. * Returns the length of this attribute's body.
* *
* @return the length of this attribute's value. * @return the length of this attribute's value.
*/ */
public char getDataLength() public char getDataLength()
{ {
return DATA_LENGTH_PRIORITY; return DATA_LENGTH_PRIORITY;
} }
/** /**
* Returns the human readable name of this attribute. * Returns the human readable name of this attribute.
* *
* @return this attribute's name. * @return this attribute's name.
*/ */
public String getName() public String getName()
{ {
return "PRIORITY"; return "PRIORITY";
} }
/** /**
* Returns the priority specified in the PRIORITY Attribute * Returns the priority specified in the PRIORITY Attribute
* *
* @return long specifying the priority * @return long specifying the priority
*/ */
public long getPriority() public long getPriority()
{ {
return priority; return priority;
} }
/** /**
* Sets the priority of the PRIORITY Attribute with the specified value * Sets the priority of the PRIORITY Attribute with the specified value
* *
* @param priority the long variable specifying the priority value * @param priority the long variable specifying the priority value
* *
* @throws IllegalArgumentException if indicated priority value is illegal. * @throws IllegalArgumentException if indicated priority value is illegal.
*/ */
public void setPriority(long priority) public void setPriority(long priority)
throws IllegalArgumentException throws IllegalArgumentException
{ {
/* Priority must be between 1 and (2^31 - 1) */ /* Priority must be between 1 and (2^31 - 1) */
if(priority <= 0 || priority > 0x7FFFFFFFL) if(priority <= 0 || priority > 0x7FFFFFFFL)
{ {
throw new IllegalArgumentException("Priority must be " + throw new IllegalArgumentException("Priority must be " +
"between 0 and (2**31 - 1)"); "between 0 and (2**31 - 1)");
} }
else else
this.priority = priority; this.priority = priority;
} }
} }

View File

@ -1,126 +1,126 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
/** /**
* This class implements the USE-CANDIDATE attribute * This class implements the USE-CANDIDATE attribute
* This attribute is an extension to the original STUN protocol * This attribute is an extension to the original STUN protocol
* This is used only during an ICE implementation * This is used only during an ICE implementation
* *
* This attribute serves as only a flag, it does not have any data * This attribute serves as only a flag, it does not have any data
* so the data length is zero * so the data length is zero
*/ */
public class UseCandidateAttribute public class UseCandidateAttribute
extends Attribute extends Attribute
{ {
/** /**
* Data length. * Data length.
*/ */
private static final char DATA_LENGTH_USE_CANDIDATE = 0; private static final char DATA_LENGTH_USE_CANDIDATE = 0;
/** /**
* Constructor. * Constructor.
*/ */
protected UseCandidateAttribute() protected UseCandidateAttribute()
{ {
super(USE_CANDIDATE); super(USE_CANDIDATE);
} }
/** /**
* Decodes the USE-CANDIDATE attribute's body, which is empty * Decodes the USE-CANDIDATE attribute's body, which is empty
* *
* @param attributeValue a binary array containing this attribute's * @param attributeValue a binary array containing this attribute's
* field values and NOT containing the attribute header. * field values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often * @param offset the position where attribute values begin (most often
* offset is equal to the index of the first byte after length) * offset is equal to the index of the first byte after length)
* @param length the length of the binary array. * @param length the length of the binary array.
* @throws StunException if attrubteValue contains invalid data. * @throws StunException if attrubteValue contains invalid data.
*/ */
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
// Do nothing, empty attribute body // Do nothing, empty attribute body
} }
/** /**
* Returns a binary representation of this attribute. * Returns a binary representation of this attribute.
* *
* @return a binary representation of this attribute. * @return a binary representation of this attribute.
*/ */
public byte[] encode() public byte[] encode()
{ {
char type = getAttributeType(); char type = getAttributeType();
byte[] binValue = new byte[HEADER_LENGTH + DATA_LENGTH_USE_CANDIDATE]; byte[] binValue = new byte[HEADER_LENGTH + DATA_LENGTH_USE_CANDIDATE];
// Type // Type
binValue[0] = (byte)(type >> 8); binValue[0] = (byte)(type >> 8);
binValue[1] = (byte)(type & 0x00FF); binValue[1] = (byte)(type & 0x00FF);
// Length // Length
binValue[2] = (byte)(DATA_LENGTH_USE_CANDIDATE >> 8); binValue[2] = (byte)(DATA_LENGTH_USE_CANDIDATE >> 8);
binValue[3] = (byte)(DATA_LENGTH_USE_CANDIDATE & 0x00FF); binValue[3] = (byte)(DATA_LENGTH_USE_CANDIDATE & 0x00FF);
return binValue; return binValue;
} }
/** /**
* Compares two STUN Attributes. Two attributes are considered equal when * Compares two STUN Attributes. Two attributes are considered equal when
* they have the same type, length and value. * they have the same type, length and value.
* *
* @param obj the object to compare this attribute with. * @param obj the object to compare this attribute with.
* @return true if the attributes are equal and false otherwise. * @return true if the attributes are equal and false otherwise.
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof UseCandidateAttribute) if(!(obj instanceof UseCandidateAttribute)
|| obj == null) || obj == null)
return false; return false;
if(obj == this) if(obj == this)
return true; return true;
UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj; UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj;
if(useCandidateAtt.getAttributeType() != getAttributeType() if(useCandidateAtt.getAttributeType() != getAttributeType()
|| useCandidateAtt.getDataLength() != getDataLength()) || useCandidateAtt.getDataLength() != getDataLength())
return false; return false;
return true; return true;
} }
/** /**
* Returns the length of this attribute's body. * Returns the length of this attribute's body.
* *
* @return the length of this attribute's value. * @return the length of this attribute's value.
*/ */
public char getDataLength() public char getDataLength()
{ {
return DATA_LENGTH_USE_CANDIDATE; return DATA_LENGTH_USE_CANDIDATE;
} }
/** /**
* Returns the human readable name of this attribute. * Returns the human readable name of this attribute.
* *
* @return this attribute's name. * @return this attribute's name.
*/ */
public String getName() public String getName()
{ {
return "USE-CANDIDATE"; return "USE-CANDIDATE";
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,25 +15,25 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* <tt>EnShutdown</tt> enumeration used internally * <tt>EnShutdown</tt> enumeration used internally
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
enum EnShutdown enum EnShutdown
{ {
/** /**
* There was no shutdown * There was no shutdown
*/ */
SD_NONE, SD_NONE,
/** /**
* There was a graceful shutdown * There was a graceful shutdown
*/ */
SD_GRACEFUL, SD_GRACEFUL,
/** /**
* There was a forceful shutdown * There was a forceful shutdown
*/ */
SD_FORCEFUL SD_FORCEFUL
}; };

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,48 +15,48 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
/** /**
* Notification of tcp events. * Notification of tcp events.
* Is implemented by @link(PseudoTcpSocket) to expose stream functionality. * Is implemented by @link(PseudoTcpSocket) to expose stream functionality.
* @author Pawel Domas * @author Pawel Domas
*/ */
interface IPseudoTcpNotify interface IPseudoTcpNotify
{ {
/** /**
* Called when tcp enters opened state * Called when tcp enters opened state
* @param tcp * @param tcp
*/ */
void OnTcpOpen(PseudoTCPBase tcp); void OnTcpOpen(PseudoTCPBase tcp);
/** /**
* Called when any data is available in read buffer * Called when any data is available in read buffer
* @param tcp * @param tcp
*/ */
void OnTcpReadable(PseudoTCPBase tcp); void OnTcpReadable(PseudoTCPBase tcp);
/** /**
* Called when there is free space available in the send buffer * Called when there is free space available in the send buffer
* @param tcp * @param tcp
*/ */
void OnTcpWriteable(PseudoTCPBase tcp); void OnTcpWriteable(PseudoTCPBase tcp);
/** /**
* Called when tcp enters closed state * Called when tcp enters closed state
* @param tcp * @param tcp
* @param e null means no error * @param e null means no error
*/ */
void OnTcpClosed(PseudoTCPBase tcp, IOException e); void OnTcpClosed(PseudoTCPBase tcp, IOException e);
/** /**
* Called when protocol requests packet transfer through the network. * Called when protocol requests packet transfer through the network.
* @param tcp * @param tcp
* @param buffer data * @param buffer data
* @param len data length * @param len data length
* @return the result, see {@link WriteResult} description for more info * @return the result, see {@link WriteResult} description for more info
*/ */
WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len); WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,37 +15,37 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* Options used in PseudoTCP * Options used in PseudoTCP
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public enum Option public enum Option
{ {
/** /**
* Whether to enable Nagle's algorithm (0 == off) * Whether to enable Nagle's algorithm (0 == off)
*/ */
OPT_NODELAY, OPT_NODELAY,
/** /**
* The Delayed ACK timeout (0 == off). * The Delayed ACK timeout (0 == off).
*/ */
OPT_ACKDELAY, OPT_ACKDELAY,
/** /**
* Set the receive buffer size, in bytes. * Set the receive buffer size, in bytes.
*/ */
OPT_RCVBUF, OPT_RCVBUF,
/** /**
* Set the send buffer size, in bytes. * Set the send buffer size, in bytes.
*/ */
OPT_SNDBUF, OPT_SNDBUF,
/** /**
* Timeout in ms for read operations(0 - no timeout) * Timeout in ms for read operations(0 - no timeout)
*/ */
OPT_READ_TIMEOUT, OPT_READ_TIMEOUT,
/** /**
* Timeout in ms for write operations(0 - no timeout) * Timeout in ms for write operations(0 - no timeout)
*/ */
OPT_WRITE_TIMEOUT OPT_WRITE_TIMEOUT
}; };

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,49 +15,49 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
/** /**
* Notification of tcp events. * Notification of tcp events.
* Is implemented by <tt>PseudoTcpSocketImpl</tt> to expose stream functionality. * Is implemented by <tt>PseudoTcpSocketImpl</tt> to expose stream functionality.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public interface PseudoTcpNotify public interface PseudoTcpNotify
{ {
/** /**
* Called when TCP enters opened state * Called when TCP enters opened state
* @param tcp * @param tcp
*/ */
void onTcpOpen(PseudoTCPBase tcp); void onTcpOpen(PseudoTCPBase tcp);
/** /**
* Called when any data is available in read buffer * Called when any data is available in read buffer
* @param tcp * @param tcp
*/ */
void onTcpReadable(PseudoTCPBase tcp); void onTcpReadable(PseudoTCPBase tcp);
/** /**
* Called when there is free space available in the send buffer * Called when there is free space available in the send buffer
* @param tcp * @param tcp
*/ */
void onTcpWriteable(PseudoTCPBase tcp); void onTcpWriteable(PseudoTCPBase tcp);
/** /**
* Called when tcp enters closed state * Called when tcp enters closed state
* @param tcp * @param tcp
* @param e null means no error * @param e null means no error
*/ */
void onTcpClosed(PseudoTCPBase tcp, IOException e); void onTcpClosed(PseudoTCPBase tcp, IOException e);
/** /**
* Called when protocol requests packet transfer through the network. * Called when protocol requests packet transfer through the network.
* @param tcp * @param tcp
* @param buffer data * @param buffer data
* @param len data length * @param len data length
* @return the result, see {@link WriteResult} description for more info * @return the result, see {@link WriteResult} description for more info
*/ */
WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len); WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
} }

View File

@ -1,149 +1,149 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import javax.net.*; import javax.net.*;
public class PseudoTcpSocketFactory public class PseudoTcpSocketFactory
extends SocketFactory extends SocketFactory
implements SocketImplFactory implements SocketImplFactory
{ {
/** /**
* Default conversation ID * Default conversation ID
*/ */
public static final long DEFAULT_CONVERSATION_ID=0; public static final long DEFAULT_CONVERSATION_ID=0;
/** /**
* Default timeout for connect operation * Default timeout for connect operation
*/ */
public static final int DEFAULT_CONNECT_TIMEOUT=5000; public static final int DEFAULT_CONNECT_TIMEOUT=5000;
/** /**
* Creates a socket and connects it to the specified * Creates a socket and connects it to the specified
* port number at the specified address. * port number at the specified address.
*/ */
public Socket createSocket(String host, int port) public Socket createSocket(String host, int port)
throws IOException, throws IOException,
UnknownHostException UnknownHostException
{ {
Socket socket = createSocket(); Socket socket = createSocket();
connectSocket(socket, new InetSocketAddress(host, port)); connectSocket(socket, new InetSocketAddress(host, port));
return socket; return socket;
} }
/** /**
* Creates a socket and connect it to the specified remote address * Creates a socket and connect it to the specified remote address
* on the specified remote port. * on the specified remote port.
*/ */
public Socket createSocket(InetAddress host, int port) throws IOException public Socket createSocket(InetAddress host, int port) throws IOException
{ {
Socket socket = createSocket(); Socket socket = createSocket();
connectSocket(socket, new InetSocketAddress(host, port)); connectSocket(socket, new InetSocketAddress(host, port));
return socket; return socket;
} }
private void connectSocket(Socket socket, InetSocketAddress remoteSockAddr) private void connectSocket(Socket socket, InetSocketAddress remoteSockAddr)
throws IOException throws IOException
{ {
socket.connect(remoteSockAddr, DEFAULT_CONNECT_TIMEOUT); socket.connect(remoteSockAddr, DEFAULT_CONNECT_TIMEOUT);
} }
/** /**
* Creates socket bound to local <tt>sockAddr</tt> * Creates socket bound to local <tt>sockAddr</tt>
* @param sockAddr * @param sockAddr
* @return socket bound to local address * @return socket bound to local address
* @throws IOException * @throws IOException
*/ */
public Socket createBoundSocket(InetSocketAddress sockAddr) public Socket createBoundSocket(InetSocketAddress sockAddr)
throws IOException throws IOException
{ {
return new PseudoTcpSocket( return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID,
new DatagramSocket(sockAddr))); new DatagramSocket(sockAddr)));
} }
/** /**
* Creates a socket and connects it to the specified remote host at the specified remote port. * Creates a socket and connects it to the specified remote host at the specified remote port.
*/ */
public Socket createSocket(String host, public Socket createSocket(String host,
int port, int port,
InetAddress localHost, InetAddress localHost,
int localPort) int localPort)
throws IOException, throws IOException,
UnknownHostException UnknownHostException
{ {
Socket socket = createBoundSocket( Socket socket = createBoundSocket(
new InetSocketAddress(localHost, localPort)); new InetSocketAddress(localHost, localPort));
connectSocket(socket, new InetSocketAddress(host, port)); connectSocket(socket, new InetSocketAddress(host, port));
return socket; return socket;
} }
/** /**
* Creates a socket and connects it to the specified remote host on the specified remote port. * Creates a socket and connects it to the specified remote host on the specified remote port.
*/ */
public Socket createSocket(InetAddress address, int port, public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException InetAddress localAddress, int localPort) throws IOException
{ {
Socket socket = createBoundSocket( Socket socket = createBoundSocket(
new InetSocketAddress(localAddress, localPort)); new InetSocketAddress(localAddress, localPort));
connectSocket(socket, new InetSocketAddress(address, port)); connectSocket(socket, new InetSocketAddress(address, port));
return socket; return socket;
} }
/** /**
* Creates a socket that will run on given <tt>datagramSocket</tt> * Creates a socket that will run on given <tt>datagramSocket</tt>
* *
* @param datagramSocket * @param datagramSocket
* @return new socket running on given <tt>datagramSocket</tt> * @return new socket running on given <tt>datagramSocket</tt>
* @throws SocketException * @throws SocketException
*/ */
public PseudoTcpSocket createSocket(DatagramSocket datagramSocket) public PseudoTcpSocket createSocket(DatagramSocket datagramSocket)
throws SocketException throws SocketException
{ {
return new PseudoTcpSocket( return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, datagramSocket)); new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, datagramSocket));
} }
/** /**
* Creates the PseudoTcp socket and binds it to any available port * Creates the PseudoTcp socket and binds it to any available port
* on the local host machine. The socket will be bound to the * on the local host machine. The socket will be bound to the
* {@link InetAddress#isAnyLocalAddress wildcard} address, * {@link InetAddress#isAnyLocalAddress wildcard} address,
* an IP address chosen by the kernel. * an IP address chosen by the kernel.
*/ */
@Override @Override
public PseudoTcpSocket createSocket() public PseudoTcpSocket createSocket()
throws SocketException throws SocketException
{ {
return new PseudoTcpSocket( return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID)); new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID));
} }
public SocketImpl createSocketImpl() public SocketImpl createSocketImpl()
{ {
try try
{ {
return new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID); return new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID);
} }
catch (SocketException e) catch (SocketException e)
{ {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,34 +15,34 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* TCP states defined for pseudoTCP * TCP states defined for pseudoTCP
* @author Pawel Domas * @author Pawel Domas
*/ */
public enum PseudoTcpState public enum PseudoTcpState
{ {
/** /**
* Initial state, can accept connection * Initial state, can accept connection
*/ */
TCP_LISTEN,// = 0, TCP_LISTEN,// = 0,
/** /**
* SYN sent to remote peer, wits for SYN * SYN sent to remote peer, wits for SYN
*/ */
TCP_SYN_SENT,// = 1, TCP_SYN_SENT,// = 1,
/** /**
* SYN received from remote peer, sends back SYN * SYN received from remote peer, sends back SYN
*/ */
TCP_SYN_RECEIVED,// = 2; TCP_SYN_RECEIVED,// = 2;
/** /**
* SYN sent and received - connection established * SYN sent and received - connection established
*/ */
TCP_ESTABLISHED,// = 3; TCP_ESTABLISHED,// = 3;
/** /**
* Closed state. In current implementation reached on error * Closed state. In current implementation reached on error
* or explicite by close method with force option * or explicite by close method with force option
* TODO: closing procedure * TODO: closing procedure
*/ */
TCP_CLOSED// = 4; TCP_CLOSED// = 4;
}; };

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,21 +15,21 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* Class used internally as a structure for receive segments * Class used internally as a structure for receive segments
* *
* @author Pawel * @author Pawel
*/ */
class RSegment class RSegment
{ {
public long seq, len; public long seq, len;
public RSegment(long seq, long len) public RSegment(long seq, long len)
{ {
this.seq = seq; this.seq = seq;
this.len = len; this.len = len;
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,25 +15,25 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* Class used internally as a structure for send segments * Class used internally as a structure for send segments
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
class SSegment class SSegment
{ {
long seq, len; long seq, len;
//uint32 tstamp; //uint32 tstamp;
short xmit; short xmit;
boolean bCtrl; boolean bCtrl;
SSegment(long s, long l, boolean c) SSegment(long s, long l, boolean c)
{ {
seq = s; seq = s;
len = l; len = l;
xmit = 0; xmit = 0;
bCtrl = c; bCtrl = c;
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,23 +15,23 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* Class used as a segment structure * Class used as a segment structure
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class Segment public class Segment
{ {
long conv; long conv;
long seq; long seq;
long ack; long ack;
byte flags; byte flags;
int wnd; int wnd;
long tsval; long tsval;
long tsecr; long tsecr;
byte[] data; byte[] data;
int len; int len;
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,14 +15,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* Send flags used internally * Send flags used internally
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
enum SendFlags enum SendFlags
{ {
sfNone, sfImmediateAck, sfDelayedAck; sfNone, sfImmediateAck, sfDelayedAck;
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,24 +15,24 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
/** /**
* The result of write packet operations * The result of write packet operations
* @author Pawel Domas * @author Pawel Domas
*/ */
public enum WriteResult public enum WriteResult
{ {
/** /**
* Packet successfully transmitted * Packet successfully transmitted
*/ */
WR_SUCCESS, WR_SUCCESS,
/** /**
* Packet was too large * Packet was too large
*/ */
WR_TOO_LARGE, WR_TOO_LARGE,
/** /**
* Write failed * Write failed
*/ */
WR_FAIL WR_FAIL
}; };

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,381 +15,381 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp.util; package org.ice4j.pseudotcp.util;
import java.nio.*; import java.nio.*;
/** /**
* First in - first out byte buffer * First in - first out byte buffer
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class ByteFifoBuffer public class ByteFifoBuffer
{ {
/** /**
* Backing byte array * Backing byte array
*/ */
private byte[] array; private byte[] array;
/** /**
* Current write position * Current write position
*/ */
private int write_pos = 0; private int write_pos = 0;
/** /**
* Stored bytes count * Stored bytes count
*/ */
private int buffered = 0; private int buffered = 0;
/** /**
* Current read position * Current read position
*/ */
private int read_pos = 0; private int read_pos = 0;
/** /**
* Creates buffer of specified size * Creates buffer of specified size
* *
* @param len buffer's size * @param len buffer's size
*/ */
public ByteFifoBuffer(int len) public ByteFifoBuffer(int len)
{ {
array = new byte[len]; array = new byte[len];
} }
/** /**
* @return buffer's capacity * @return buffer's capacity
*/ */
public int length() public int length()
{ {
return array.length; return array.length;
} }
/** /**
* Method reads <tt>count</tt> bytes into <tt>out_buffer</tt>. * Method reads <tt>count</tt> bytes into <tt>out_buffer</tt>.
* Current read position is incremented by count of bytes * Current read position is incremented by count of bytes
* that has been successfully read. * that has been successfully read.
* *
* @param out_buffer * @param out_buffer
* @param count * @param count
* @return bytes successfully read * @return bytes successfully read
*/ */
public int read(byte[] out_buffer, int count) public int read(byte[] out_buffer, int count)
{ {
return read(out_buffer, 0, count); return read(out_buffer, 0, count);
} }
/** /**
* Read with buffer offset * Read with buffer offset
* @param out_buffer * @param out_buffer
* @param buff_offset * @param buff_offset
* @param count bytes to read * @param count bytes to read
* @return read byte count * @return read byte count
*/ */
public int read(byte[] out_buffer, int buff_offset, int count) { public int read(byte[] out_buffer, int buff_offset, int count) {
count = readLimit(count); count = readLimit(count);
if (count > 0) if (count > 0)
{ {
readOp(out_buffer, buff_offset, count, array, read_pos, array.length); readOp(out_buffer, buff_offset, count, array, read_pos, array.length);
read_pos = (read_pos + count) % array.length; read_pos = (read_pos + count) % array.length;
buffered -= count; buffered -= count;
} }
return count; return count;
} }
/** /**
* Limits <tt>desiredReadCount</tt> to count that is actually available * Limits <tt>desiredReadCount</tt> to count that is actually available
* @param desiredReadCount * @param desiredReadCount
* @return * @return
*/ */
private int readLimit(int desiredReadCount) private int readLimit(int desiredReadCount)
{ {
return desiredReadCount > buffered ? buffered : desiredReadCount; return desiredReadCount > buffered ? buffered : desiredReadCount;
} }
/** /**
* Utility method used for read operations * Utility method used for read operations
* @param outBuffer * @param outBuffer
* @param dst_buff_offset * @param dst_buff_offset
* @param count * @param count
* @param srcBuffer * @param srcBuffer
* @param read_pos * @param read_pos
* @param buff_len * @param buff_len
*/ */
private static void readOp(byte[] outBuffer, int dst_buff_offset, int count, private static void readOp(byte[] outBuffer, int dst_buff_offset, int count,
byte[] srcBuffer, int read_pos, int buff_len) byte[] srcBuffer, int read_pos, int buff_len)
{ {
if (read_pos + count <= buff_len) if (read_pos + count <= buff_len)
{ {
//single operation //single operation
System.arraycopy(srcBuffer, read_pos, outBuffer, dst_buff_offset, System.arraycopy(srcBuffer, read_pos, outBuffer, dst_buff_offset,
count); count);
} }
else else
{ {
//two operations //two operations
int tillEndCount = buff_len - read_pos; int tillEndCount = buff_len - read_pos;
System.arraycopy(srcBuffer, read_pos, outBuffer, System.arraycopy(srcBuffer, read_pos, outBuffer,
dst_buff_offset, tillEndCount); dst_buff_offset, tillEndCount);
int fromStartCount = count - tillEndCount; int fromStartCount = count - tillEndCount;
System.arraycopy(srcBuffer, 0, outBuffer, System.arraycopy(srcBuffer, 0, outBuffer,
dst_buff_offset + tillEndCount, fromStartCount); dst_buff_offset + tillEndCount, fromStartCount);
} }
} }
/** /**
* *
* @return space left in buffer for write * @return space left in buffer for write
*/ */
public int getWriteRemaining() public int getWriteRemaining()
{ {
return array.length - buffered; return array.length - buffered;
} }
/** /**
* *
* @return bytes stored in buffer and available for reading * @return bytes stored in buffer and available for reading
*/ */
public int getBuffered() public int getBuffered()
{ {
return buffered; return buffered;
} }
/** /**
* Writes <tt>count</tt> of bytes from the <tt>buffer</tt> * Writes <tt>count</tt> of bytes from the <tt>buffer</tt>
* *
* @param buffer * @param buffer
* @param count * @param count
* @return bytes successfully written to buffer * @return bytes successfully written to buffer
*/ */
public int write(byte[] buffer, int count) public int write(byte[] buffer, int count)
{ {
return write(buffer, 0, count); return write(buffer, 0, count);
} }
/** /**
* *
* @param data source data * @param data source data
* @param offset source buffer's offset * @param offset source buffer's offset
* @param count * @param count
* @return byte count actually read * @return byte count actually read
*/ */
public int write(byte[] data, int offset, int count) public int write(byte[] data, int offset, int count)
{ {
/* /*
* System.out.println("----write " + this + " " + len + " buffered " + * System.out.println("----write " + this + " " + len + " buffered " +
* GetBuffered() + " buff avail: " + GetWriteRemaining()); * GetBuffered() + " buff avail: " + GetWriteRemaining());
*/ */
count = writeLimit(count); count = writeLimit(count);
writeOp(data, offset, count, array, write_pos, array.length); writeOp(data, offset, count, array, write_pos, array.length);
write_pos = (write_pos + count) % array.length; write_pos = (write_pos + count) % array.length;
buffered += count; buffered += count;
/* /*
* System.out.println("----write "+this+" "+len+" buffered * System.out.println("----write "+this+" "+len+" buffered
* "+GetBuffered()); for(int i=0; i < len; i++){ * "+GetBuffered()); for(int i=0; i < len; i++){
* System.out.println("WDATA: "+data[i]); } * System.out.println("WDATA: "+data[i]); }
*/ */
return count; return count;
} }
/** /**
* Utility method for write operations * Utility method for write operations
* @param inBuffer * @param inBuffer
* @param inOffset * @param inOffset
* @param count * @param count
* @param outBuffer * @param outBuffer
* @param write_pos * @param write_pos
* @param buff_len * @param buff_len
*/ */
private static void writeOp(byte[] inBuffer, private static void writeOp(byte[] inBuffer,
int inOffset, int inOffset,
int count, int count,
byte[] outBuffer, byte[] outBuffer,
int write_pos, int write_pos,
int buff_len) int buff_len)
{ {
if ((write_pos + count) <= buff_len) if ((write_pos + count) <= buff_len)
{ {
//single op //single op
System.arraycopy(inBuffer, inOffset, outBuffer, write_pos, count); System.arraycopy(inBuffer, inOffset, outBuffer, write_pos, count);
} }
else else
{ {
//till end and from beginning //till end and from beginning
int tillEndCount; int tillEndCount;
int fromStartCount; int fromStartCount;
tillEndCount = buff_len - write_pos; tillEndCount = buff_len - write_pos;
fromStartCount = count - tillEndCount; fromStartCount = count - tillEndCount;
System.arraycopy(inBuffer, inOffset, outBuffer, System.arraycopy(inBuffer, inOffset, outBuffer,
write_pos, tillEndCount); write_pos, tillEndCount);
System.arraycopy(inBuffer, inOffset + tillEndCount, System.arraycopy(inBuffer, inOffset + tillEndCount,
outBuffer, 0, fromStartCount); outBuffer, 0, fromStartCount);
} }
} }
/** /**
* Limits <tt>desiredWriteCount</tt> to what's actually available * Limits <tt>desiredWriteCount</tt> to what's actually available
* @param desiredWriteCount * @param desiredWriteCount
* @return * @return
*/ */
private int writeLimit(int desiredWriteCount) private int writeLimit(int desiredWriteCount)
{ {
return desiredWriteCount > (array.length - buffered) ? return desiredWriteCount > (array.length - buffered) ?
(array.length - buffered) : desiredWriteCount; (array.length - buffered) : desiredWriteCount;
} }
/** /**
* Checks if new write position is correct * Checks if new write position is correct
* *
* @param newWrPos new write position * @param newWrPos new write position
*/ */
private void assertWriteLimit(int newWrPos) private void assertWriteLimit(int newWrPos)
throws IllegalArgumentException throws IllegalArgumentException
{ {
int spaceReq; int spaceReq;
int availSpace = getWriteRemaining(); int availSpace = getWriteRemaining();
if (newWrPos < write_pos) if (newWrPos < write_pos)
{ {
spaceReq = newWrPos + (array.length - write_pos); spaceReq = newWrPos + (array.length - write_pos);
} }
else else
{ {
spaceReq = newWrPos - write_pos; spaceReq = newWrPos - write_pos;
} }
if (spaceReq > availSpace) if (spaceReq > availSpace)
{ {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
/** /**
* Advances current buffer's write position by <tt>count</tt> bytes * Advances current buffer's write position by <tt>count</tt> bytes
* *
* @param count * @param count
*/ */
public void consumeWriteBuffer(int count) public void consumeWriteBuffer(int count)
throws IllegalArgumentException, throws IllegalArgumentException,
BufferOverflowException BufferOverflowException
{ {
if (count > getWriteRemaining()) if (count > getWriteRemaining())
{ {
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
if (count < 0) if (count < 0)
{ {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
int newPos = (write_pos + count) % array.length; int newPos = (write_pos + count) % array.length;
assertWriteLimit(newPos); assertWriteLimit(newPos);
write_pos = newPos; write_pos = newPos;
buffered += count; buffered += count;
} }
/** /**
* Sets new buffer's capacity * Sets new buffer's capacity
* *
* @param new_size * @param new_size
* @return <tt>true</tt> if operation is possible to perform, that is if new * @return <tt>true</tt> if operation is possible to perform, that is if new
* buffered data fits into new buffer * buffered data fits into new buffer
*/ */
public boolean setCapacity(int new_size) public boolean setCapacity(int new_size)
{ {
if (new_size < getBuffered()) if (new_size < getBuffered())
{ {
return false; return false;
} }
byte[] newBuff = new byte[new_size]; byte[] newBuff = new byte[new_size];
readOp(newBuff, 0, buffered, array, read_pos, array.length); readOp(newBuff, 0, buffered, array, read_pos, array.length);
this.array = newBuff; this.array = newBuff;
return true; return true;
} }
/** /**
* Aligns current read position by <tt>count</tt> * Aligns current read position by <tt>count</tt>
* *
* @param count * @param count
* @throws BufferUnderflowException if new position exceeds buffered data * @throws BufferUnderflowException if new position exceeds buffered data
* count * count
*/ */
public void consumeReadData(int count) public void consumeReadData(int count)
throws IllegalArgumentException, throws IllegalArgumentException,
BufferUnderflowException BufferUnderflowException
{ {
/* /*
* System.out.println("Consume read " + this + " " + count + " read pos: * System.out.println("Consume read " + this + " " + count + " read pos:
* " + read_pos); * " + read_pos);
*/ */
if (count > buffered) if (count > buffered)
{ {
throw new BufferUnderflowException(); throw new BufferUnderflowException();
} }
if (count < 0) if (count < 0)
{ {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
this.read_pos = (read_pos + count) % array.length; this.read_pos = (read_pos + count) % array.length;
buffered -= count; buffered -= count;
} }
/** /**
* Reads <tt>count</tt> bytes from buffer without storing new read position * Reads <tt>count</tt> bytes from buffer without storing new read position
* *
* @param dst_buff * @param dst_buff
* @param dst_buff_offset offset of destination buffer * @param dst_buff_offset offset of destination buffer
* @param count bytes to read * @param count bytes to read
* @param offset from current read position * @param offset from current read position
* @return bytes successfully read * @return bytes successfully read
*/ */
public int readOffset(byte[] dst_buff, public int readOffset(byte[] dst_buff,
int dst_buff_offset, int dst_buff_offset,
int count, int count,
int offset) int offset)
{ {
//TODO: not sure if should decrease read count or throw an exception //TODO: not sure if should decrease read count or throw an exception
/* /*
* System.out.println("Read dst offset " + dst_buff_offset + " offset " * System.out.println("Read dst offset " + dst_buff_offset + " offset "
* + offset + " len " + count + " " + this); * + offset + " len " + count + " " + this);
*/ */
int read_offset = (this.read_pos + offset) % array.length; int read_offset = (this.read_pos + offset) % array.length;
readOp(dst_buff, dst_buff_offset, count, array, read_offset, array.length); readOp(dst_buff, dst_buff_offset, count, array, read_offset, array.length);
return count; return count;
} }
/** /**
* Writes <tt>count</tt> bytes from <tt>data</tt> to the buffer without * Writes <tt>count</tt> bytes from <tt>data</tt> to the buffer without
* affecting buffer's write position * affecting buffer's write position
* *
* @param data * @param data
* @param count * @param count
* @param nOffset from buffer's write position * @param nOffset from buffer's write position
* @return bytes successfully written * @return bytes successfully written
*/ */
public int writeOffset(byte[] data, int count, int nOffset) public int writeOffset(byte[] data, int count, int nOffset)
throws BufferOverflowException throws BufferOverflowException
{ {
if (count > getWriteRemaining()) if (count > getWriteRemaining())
{ {
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
if (count < 0) if (count < 0)
{ {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
int offWritePos = (this.write_pos + nOffset) % array.length; int offWritePos = (this.write_pos + nOffset) % array.length;
count = writeLimit(count); count = writeLimit(count);
assertWriteLimit(offWritePos + count); assertWriteLimit(offWritePos + count);
writeOp(data, 0, count, array, offWritePos, array.length); writeOp(data, 0, count, array, offWritePos, array.length);
return count; return count;
} }
public void resetReadPosition() public void resetReadPosition()
{ {
this.read_pos = 0; this.read_pos = 0;
} }
public void resetWritePosition() public void resetWritePosition()
{ {
this.write_pos = 0; this.write_pos = 0;
this.buffered = 0; this.buffered = 0;
} }
} }

View File

@ -1,92 +1,92 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import junit.framework.*; import junit.framework.*;
/** /**
* This class enables multi thread tests where main thread waits in loop * This class enables multi thread tests where main thread waits in loop
* for specified condition to be met, while others perform some operations. * for specified condition to be met, while others perform some operations.
* For example until the connection is established or closed. * For example until the connection is established or closed.
* It also registers default uncaught exception handler to catch exceptions * It also registers default uncaught exception handler to catch exceptions
* from other threads. * from other threads.
* *
* Condition checks are passed as IWaitUntilDone interface. * Condition checks are passed as IWaitUntilDone interface.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class MultiThreadSupportTest public class MultiThreadSupportTest
extends TestCase extends TestCase
implements Thread.UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler
{ {
private volatile Throwable testError; private volatile Throwable testError;
private volatile Thread errorThread; private volatile Thread errorThread;
private final Object testLock = new Object(); private final Object testLock = new Object();
public MultiThreadSupportTest() public MultiThreadSupportTest()
{ {
} }
@Override @Override
public void uncaughtException(Thread t, Throwable e) public void uncaughtException(Thread t, Throwable e)
{ {
synchronized (testLock) synchronized (testLock)
{ {
testError = e; testError = e;
errorThread = t; errorThread = t;
testLock.notifyAll(); testLock.notifyAll();
} }
} }
private long assertWaitInterval = 100; private long assertWaitInterval = 100;
protected interface WaitUntilDone protected interface WaitUntilDone
{ {
public boolean isDone(); public boolean isDone();
} }
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs) protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
{ {
try try
{ {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs) while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs)
{ {
synchronized (testLock) synchronized (testLock)
{ {
testLock.wait(assertWaitInterval); testLock.wait(assertWaitInterval);
if (testError != null) if (testError != null)
{ {
testError.printStackTrace(); testError.printStackTrace();
fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage()); fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage());
} }
} }
} }
return wait.isDone(); return wait.isDone();
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
ex.printStackTrace(); ex.printStackTrace();
fail("assert_wait - interrupted"); fail("assert_wait - interrupted");
//return is unreachable //return is unreachable
return false; return false;
} }
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,353 +15,353 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
/** /**
* This class implements test for two way transfers * This class implements test for two way transfers
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class PseudoTcpTestPingPong extends PseudoTcpTestBase public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
/** /**
* The logger. * The logger.
*/ */
private static final Logger logger = private static final Logger logger =
Logger.getLogger(PseudoTCPBase.class.getName()); Logger.getLogger(PseudoTCPBase.class.getName());
/** /**
* The sender * The sender
*/ */
private PseudoTCPBase sender; private PseudoTCPBase sender;
/** /**
* The receiver * The receiver
*/ */
private PseudoTCPBase receiver; private PseudoTCPBase receiver;
/** /**
* How much data is sent per ping * How much data is sent per ping
*/ */
private int bytesPerSend; private int bytesPerSend;
/** /**
* Iterations count * Iterations count
*/ */
private int iterationsRemaining; private int iterationsRemaining;
public PseudoTcpTestPingPong() public PseudoTcpTestPingPong()
{ {
} }
public void setBytesPerSend(int bytes_per_send) public void setBytesPerSend(int bytes_per_send)
{ {
this.bytesPerSend = bytes_per_send; this.bytesPerSend = bytes_per_send;
} }
/** /**
* The send stream buffer * The send stream buffer
*/ */
ByteFifoBuffer send_stream; ByteFifoBuffer send_stream;
/** /**
* The receive stream buffer * The receive stream buffer
*/ */
ByteFifoBuffer recv_stream; ByteFifoBuffer recv_stream;
/** /**
* Performs ping-pong test for <tt>iterations</tt> with packets of * Performs ping-pong test for <tt>iterations</tt> with packets of
* <tt>size</tt> bytes * <tt>size</tt> bytes
* *
* @param size * @param size
* @param iterations * @param iterations
*/ */
public void doTestPingPong(int size, int iterations) public void doTestPingPong(int size, int iterations)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start; long start;
iterationsRemaining = iterations; iterationsRemaining = iterations;
receiver = getRemoteTcp(); receiver = getRemoteTcp();
sender = getLocalTcp(); sender = getLocalTcp();
// Create some dummy data // Create some dummy data
byte[] dummy = createDummyData(size); byte[] dummy = createDummyData(size);
send_stream = new ByteFifoBuffer(size); send_stream = new ByteFifoBuffer(size);
send_stream.write(dummy, size); send_stream.write(dummy, size);
//Prepare the receive stream //Prepare the receive stream
recv_stream = new ByteFifoBuffer(size); recv_stream = new ByteFifoBuffer(size);
//Connect and wait until connected //Connect and wait until connected
start = PseudoTCPBase.now(); start = PseudoTCPBase.now();
startClocks(); startClocks();
try try
{ {
connect(); connect();
} }
catch (IOException ex) catch (IOException ex)
{ {
ex.printStackTrace(); ex.printStackTrace();
fail(ex.getMessage()); fail(ex.getMessage());
} }
//assert Connect() == 0; //assert Connect() == 0;
assert_Connected_wait(kConnectTimeoutMs); assert_Connected_wait(kConnectTimeoutMs);
// Sending will start from OnTcpWriteable and stop when the required // Sending will start from OnTcpWriteable and stop when the required
// number of iterations have completed. // number of iterations have completed.
assert_Disconnected_wait(kMinTransferRate); assert_Disconnected_wait(kMinTransferRate);
long elapsed = PseudoTCPBase.now() - start; long elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
logger.log(Level.INFO, logger.log(Level.INFO,
"Performed " + iterations + " pings in " + elapsed + " ms"); "Performed " + iterations + " pings in " + elapsed + " ms");
} }
/** /**
* Catches onTcpReadable event for receiver * Catches onTcpReadable event for receiver
* *
* @param tcp * @param tcp
*/ */
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
assertEquals("Unexpected onTcpReadable", receiver, tcp); assertEquals("Unexpected onTcpReadable", receiver, tcp);
try try
{ {
// Stream bytes to the recv stream as they arrive. // Stream bytes to the recv stream as they arrive.
readData(); readData();
} }
catch (IOException ex) catch (IOException ex)
{ {
//will be caught by default handler and test will fail //will be caught by default handler and test will fail
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
// If we've received the desired amount of data, rewind things // If we've received the desired amount of data, rewind things
// and send it back the other way! // and send it back the other way!
int recvd = recv_stream.getBuffered(); int recvd = recv_stream.getBuffered();
int required = send_stream.length(); int required = send_stream.length();
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(Level.FINER,
"test - receivied: " + recvd + " required: " + required); "test - receivied: " + recvd + " required: " + required);
} }
if (recvd == required) if (recvd == required)
{ {
if (receiver == getLocalTcp() && --iterationsRemaining == 0) if (receiver == getLocalTcp() && --iterationsRemaining == 0)
{ {
close(); close();
// TODO: Fake OnTcpClosed() on the receiver for now. // TODO: Fake OnTcpClosed() on the receiver for now.
onTcpClosed(getRemoteTcp(), null); onTcpClosed(getRemoteTcp(), null);
return; return;
} }
//switches receivier with sender and performs test the other way //switches receivier with sender and performs test the other way
PseudoTCPBase tmp = receiver; PseudoTCPBase tmp = receiver;
receiver = sender; receiver = sender;
sender = tmp; sender = tmp;
send_stream.resetReadPosition(); send_stream.resetReadPosition();
send_stream.consumeWriteBuffer(send_stream.getWriteRemaining()); send_stream.consumeWriteBuffer(send_stream.getWriteRemaining());
recv_stream.resetWritePosition(); recv_stream.resetWritePosition();
onTcpWriteable(sender); onTcpWriteable(sender);
} }
} }
/** /**
* Catches the ontcpWriteable event for sender * Catches the ontcpWriteable event for sender
* *
* @param tcp * @param tcp
*/ */
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
if (tcp != sender) if (tcp != sender)
{ {
return; return;
} }
// Write bytes from the send stream when we can. // Write bytes from the send stream when we can.
// Shut down when we've sent everything. // Shut down when we've sent everything.
logger.log(Level.FINER, "Flow Control Lifted"); logger.log(Level.FINER, "Flow Control Lifted");
try try
{ {
writeData(); writeData();
} }
catch (IOException ex) catch (IOException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
/** /**
* Reads the data in loop until is something available * Reads the data in loop until is something available
* *
* @throws IOException * @throws IOException
*/ */
private void readData() throws IOException private void readData() throws IOException
{ {
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
int rcvd = 0; int rcvd = 0;
do do
{ {
rcvd = receiver.recv(block, block.length); rcvd = receiver.recv(block, block.length);
if (rcvd > 0) if (rcvd > 0)
{ {
recv_stream.write(block, rcvd); recv_stream.write(block, rcvd);
if (logger.isLoggable(Level.FINE)) if (logger.isLoggable(Level.FINE))
{ {
logger.log(Level.FINE, logger.log(Level.FINE,
"Receivied: " + recv_stream.getBuffered()); "Receivied: " + recv_stream.getBuffered());
} }
} }
} }
while (rcvd > 0); while (rcvd > 0);
} }
/** /**
* Writes all data to the receiver * Writes all data to the receiver
* *
* @throws IOException * @throws IOException
*/ */
private void writeData() throws IOException private void writeData() throws IOException
{ {
int tosend; int tosend;
int sent = 0; int sent = 0;
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
do do
{ {
tosend = bytesPerSend != 0 ? bytesPerSend : block.length; tosend = bytesPerSend != 0 ? bytesPerSend : block.length;
tosend = send_stream.read(block, tosend); tosend = send_stream.read(block, tosend);
if (tosend > 0) if (tosend > 0)
{ {
sent = sender.send(block, tosend); sent = sender.send(block, tosend);
updateLocalClock(); updateLocalClock();
if (sent != -1) if (sent != -1)
{ {
if(logger.isLoggable(Level.FINE)) if(logger.isLoggable(Level.FINE))
{ {
logger.log(Level.FINE, "Sent: " + sent); logger.log(Level.FINE, "Sent: " + sent);
} }
} }
else else
{ {
logger.log(Level.FINE, "Flow controlled"); logger.log(Level.FINE, "Flow controlled");
} }
} }
else else
{ {
sent = tosend = 0; sent = tosend = 0;
} }
} }
while (sent > 0); while (sent > 0);
} }
/** /**
* *
* Ping-pong (request/response) tests * Ping-pong (request/response) tests
* *
*/ */
/** /**
* Test sending <= 1x MTU of data in each ping/pong. Should take <10ms. * Test sending <= 1x MTU of data in each ping/pong. Should take <10ms.
*/ */
public void testPingPong1xMtu() public void testPingPong1xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 1xMTU"); //logger.log(Level.INFO, "Test ping - pong 1xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.doTestPingPong(100, 100); test.doTestPingPong(100, 100);
} }
/** /**
* Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms. * Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms.
*/ */
public void testPingPong3xMtu() public void testPingPong3xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 3xMTU"); //logger.log(Level.INFO, "Test ping - pong 3xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.doTestPingPong(400, 100); test.doTestPingPong(400, 100);
} }
/** /**
* Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to * Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to
* interaction between Nagling and Delayed ACK. * interaction between Nagling and Delayed ACK.
*/ */
public void testPingPong2xMtu() public void testPingPong2xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU"); //logger.log(Level.INFO, "Test ping - pong 2xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.doTestPingPong(2000, 5); test.doTestPingPong(2000, 5);
} }
/** /**
* Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off. * Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off.
* Should take <10ms. * Should take <10ms.
*/ */
public void testPingPong2xMtuWithAckDelayOff() public void testPingPong2xMtuWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptAckDelay(0); test.setOptAckDelay(0);
test.doTestPingPong(2000, 100); test.doTestPingPong(2000, 100);
} }
/** /**
* Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should * Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should
* take <10ms. * take <10ms.
*/ */
public void testPingPong2xMtuWithNaglingOff() public void testPingPong2xMtuWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptNagling(false); test.setOptNagling(false);
test.doTestPingPong(2000, 5); test.doTestPingPong(2000, 5);
} }
/** /**
* Test sending a ping as pair of short (non-full) segments. Should take * Test sending a ping as pair of short (non-full) segments. Should take
* ~1s, due to Delayed ACK interaction with Nagling. * ~1s, due to Delayed ACK interaction with Nagling.
*/ */
public void testPingPongShortSegments() public void testPingPongShortSegments()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments"); //logger.log(Level.INFO, "Test ping - pong short segments");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptAckDelay(5000); test.setOptAckDelay(5000);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.doTestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
/** /**
* Test sending ping as a pair of short (non-full) segments, with Nagling * Test sending ping as a pair of short (non-full) segments, with Nagling
* off. Should take <10ms. * off. Should take <10ms.
*/ */
public void testPingPongShortSegmentsWithNaglingOff() public void testPingPongShortSegmentsWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptNagling(false); test.setOptNagling(false);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.doTestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
/** /**
* Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed * Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed
* ACK. Should take ~1s. * ACK. Should take ~1s.
*/ */
public void testPingPongShortSegmentsWithAckDelayOff() public void testPingPongShortSegmentsWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.setOptAckDelay(0); test.setOptAckDelay(0);
test.doTestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,399 +15,399 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
/** /**
* Fill the receiver window until it is full, drain it and then fill it with the * 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 * same amount. This is to test that receiver window contracts and enlarges
* correctly. * correctly.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
/** /**
* The logger. * The logger.
*/ */
private static final Logger logger = private static final Logger logger =
Logger.getLogger(PseudoTCPBase.class.getName()); Logger.getLogger(PseudoTCPBase.class.getName());
/** /**
* Send data buffer * Send data buffer
*/ */
private ByteFifoBuffer send_stream; private ByteFifoBuffer send_stream;
/** /**
* List which stores stream position after each write cycle * List which stores stream position after each write cycle
*/ */
private List<Integer> send_position; private List<Integer> send_position;
/** /**
* Receive data buffer * Receive data buffer
*/ */
private ByteFifoBuffer recv_stream; private ByteFifoBuffer recv_stream;
/** /**
* List which stores stream position after each read cycle * List which stores stream position after each read cycle
*/ */
private List<Integer> recv_position; private List<Integer> recv_position;
/** /**
* Times used for write operations scheduling * Times used for write operations scheduling
*/ */
private Timer writeTimer = new Timer("WriteTimer"); private Timer writeTimer = new Timer("WriteTimer");
/** /**
* Stores data length used for the test. * Stores data length used for the test.
*/ */
private int testDataSize; private int testDataSize;
public void doTestTransfer(int size) public void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
testDataSize = size; testDataSize = size;
long start, elapsed; long start, elapsed;
send_position = new ArrayList<Integer>(); send_position = new ArrayList<Integer>();
recv_position = new ArrayList<Integer>(); recv_position = new ArrayList<Integer>();
// Create some dummy data // Create some dummy data
byte[] dummy = createDummyData(size); byte[] dummy = createDummyData(size);
send_stream = new ByteFifoBuffer(size); send_stream = new ByteFifoBuffer(size);
send_stream.write(dummy, size); send_stream.write(dummy, size);
//Prepare the receive stream //Prepare the receive stream
recv_stream = new ByteFifoBuffer(size); recv_stream = new ByteFifoBuffer(size);
//Connect and wait until connected //Connect and wait until connected
start = PseudoTCPBase.now(); start = PseudoTCPBase.now();
startClocks(); startClocks();
try try
{ {
connect(); connect();
} }
catch (IOException ex) catch (IOException ex)
{ {
fail(ex.getMessage()); fail(ex.getMessage());
} }
//assert Connect() == 0; //assert Connect() == 0;
//TODO: check assert result and fail //TODO: check assert result and fail
// Connect and wait until connected. // Connect and wait until connected.
assert_Connected_wait(kConnectTimeoutMs); assert_Connected_wait(kConnectTimeoutMs);
scheduleWriteAction(0); scheduleWriteAction(0);
long transferTout = maxTransferTime(dummy.length, kMinTransferRate); long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
boolean transfferInTime = assert_Disconnected_wait(transferTout); boolean transfferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.now() - start; elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
int received = recv_stream.getBuffered(); int received = recv_stream.getBuffered();
assertEquals("Transfer timeout, transferred: " + received assertEquals("Transfer timeout, transferred: " + received
+ " required: " + dummy.length + " required: " + dummy.length
+ " elapsed: " + " elapsed: "
+ elapsed + " limit: " + transferTout, + elapsed + " limit: " + transferTout,
true, transfferInTime); true, transfferInTime);
assert 2 == send_position.size(); assert 2 == send_position.size();
assert 2 == recv_position.size(); assert 2 == recv_position.size();
int estimated_recv_window = estimateReceiveWindowSize(); int estimated_recv_window = estimateReceiveWindowSize();
// The difference in consecutive send positions should equal the // The difference in consecutive send positions should equal the
// receive window size or match very closely. This verifies that receive // receive window size or match very closely. This verifies that receive
// window is open after receiver drained all the data. // window is open after receiver drained all the data.
int send_position_diff = send_position.get(1) - send_position.get(0); int send_position_diff = send_position.get(1) - send_position.get(0);
assertTrue(estimated_recv_window - send_position_diff <= 1024); assertTrue(estimated_recv_window - send_position_diff <= 1024);
// Receiver drained the receive window twice.(+-2 because of window scaling) // Receiver drained the receive window twice.(+-2 because of window scaling)
assert ((recv_position.get(1) - 2 * estimated_recv_window) assert ((recv_position.get(1) - 2 * estimated_recv_window)
<= getShadowedBytes(getRemoteScaleFactor())); <= getShadowedBytes(getRemoteScaleFactor()));
} }
/** /**
* This function calculates amount of bytes witch may introduce error to * This function calculates amount of bytes witch may introduce error to
* estimation of receive window size caused by scale factor. This is because * 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 * 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 * 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 * expected and some data may still wait for window to open in the send
* queue. * queue.
* *
* For example: m_rcv_scale == 1 and m_rcv_wnd < 2 then rcv_wnd == 0 (1 byte * 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 == 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) m_rcv_scale == 3 and m_rcv_wnd < 8 then rcv_wnd == 0 (7 bytes
* may block) and so on... * may block) and so on...
* *
* In normal operation something would read data on remote side causing * In normal operation something would read data on remote side causing
* window to expand. * window to expand.
* *
* *
* *
* *
* *
* @param scaleFactor * @param scaleFactor
* @return count bytes shadowed by scale actor * @return count bytes shadowed by scale actor
*/ */
static int getShadowedBytes(int scaleFactor) static int getShadowedBytes(int scaleFactor)
{ {
return (int) (Math.pow(2, scaleFactor) - 1); return (int) (Math.pow(2, scaleFactor) - 1);
} }
/** /**
* Reads all data available at the buffer * Reads all data available at the buffer
* *
* @throws IOException * @throws IOException
*/ */
void readUntilIOPending() throws IOException void readUntilIOPending() throws IOException
{ {
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2]; byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
int position = recv_stream.getBuffered(); int position = recv_stream.getBuffered();
int rcvd, total = 0; int rcvd, total = 0;
do do
{ {
rcvd = remoteRecv(block, block.length); rcvd = remoteRecv(block, block.length);
if (rcvd > 0) if (rcvd > 0)
{ {
recv_stream.write(block, rcvd); recv_stream.write(block, rcvd);
total += rcvd; total += rcvd;
position += rcvd; position += rcvd;
} }
} }
while (rcvd > 0 && total != 0); while (rcvd > 0 && total != 0);
recv_position.add(position); recv_position.add(position);
// Disconnect if we have done two transfers. // Disconnect if we have done two transfers.
if (recv_position.size() == 2) if (recv_position.size() == 2)
{ {
close(); close();
onTcpClosed(getRemoteTcp(), null); onTcpClosed(getRemoteTcp(), null);
} }
else else
{ {
writeData(); writeData();
} }
} }
/** /**
* Schedules write operation with <tt>delay</tt> given in ms * Schedules write operation with <tt>delay</tt> given in ms
* *
* @param delay * @param delay
*/ */
void scheduleWriteAction(long delay) void scheduleWriteAction(long delay)
{ {
writeTimer.schedule(new TimerTask() writeTimer.schedule(new TimerTask()
{ {
@Override @Override
public void run() public void run()
{ {
try try
{ {
writeData(); writeData();
} }
catch (IOException ex) catch (IOException ex)
{ {
//it will get cought by //it will get cought by
//deafult exception handler in PseudoTcpTestBase //deafult exception handler in PseudoTcpTestBase
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
}, delay); }, delay);
} }
/** /**
* Writes the data * Writes the data
* *
* @throws IOException * @throws IOException
*/ */
void writeData() throws IOException void writeData() throws IOException
{ {
//writeOpCount++; //writeOpCount++;
int tosend; int tosend;
int sent; int sent;
int totalSent = 0; int totalSent = 0;
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2]; byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
int position = testDataSize - send_stream.getBuffered(); int position = testDataSize - send_stream.getBuffered();
synchronized (getLocalTcp()) synchronized (getLocalTcp())
{ {
do do
{ {
tosend = send_stream.readOffset(block, 0, block.length, 0); tosend = send_stream.readOffset(block, 0, block.length, 0);
if (tosend > 0) if (tosend > 0)
{ {
sent = localSend(block, tosend); sent = localSend(block, tosend);
updateLocalClock(); updateLocalClock();
if (sent > 0) if (sent > 0)
{ {
totalSent += sent; totalSent += sent;
send_stream.consumeReadData(sent); send_stream.consumeReadData(sent);
position += sent; position += sent;
} }
else else
{ {
logger.log(Level.FINE, "Flow Controlled"); logger.log(Level.FINE, "Flow Controlled");
} }
} }
else else
{ {
sent = tosend = 0; sent = tosend = 0;
} }
} }
while (sent > 0); while (sent > 0);
//position = send_stream.GetBuffered(); //position = send_stream.GetBuffered();
} }
// Measured with precision according to window scale option used // Measured with precision according to window scale option used
if (totalSent - getRemoteTcp().getAvailable() if (totalSent - getRemoteTcp().getAvailable()
> getShadowedBytes(getRemoteScaleFactor())) > getShadowedBytes(getRemoteScaleFactor()))
{ {
//send buffer was fully filled //send buffer was fully filled
//waits until it will be received by remote peer //waits until it will be received by remote peer
while (totalSent - getRemoteTcp().getAvailable() while (totalSent - getRemoteTcp().getAvailable()
> getShadowedBytes(getRemoteScaleFactor()) > getShadowedBytes(getRemoteScaleFactor())
&& !getRemoteTcp().isReceiveBufferFull()) && !getRemoteTcp().isReceiveBufferFull())
{ {
try try
{ {
Thread.sleep(50); Thread.sleep(50);
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(Level.FINER,
"Waiting... sent: " + totalSent + " avail: " "Waiting... sent: " + totalSent + " avail: "
+ getRemoteTcp().getAvailable() + " buffered not sent: " + getRemoteTcp().getAvailable() + " buffered not sent: "
+ getLocalTcp().getBytesBufferedNotSent() + getLocalTcp().getBytesBufferedNotSent()
+ " isFull? " + getRemoteTcp().isReceiveBufferFull()); + " isFull? " + getRemoteTcp().isReceiveBufferFull());
} }
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
} }
send_position.add(position); send_position.add(position);
writeTimer.schedule(new TimerTask() writeTimer.schedule(new TimerTask()
{ {
@Override @Override
public void run() public void run()
{ {
try try
{ {
readUntilIOPending(); readUntilIOPending();
} }
catch (IOException ex) catch (IOException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} }
}, 10); }, 10);
} }
/** /**
* *
* @return estimated receive window size * @return estimated receive window size
*/ */
int estimateReceiveWindowSize() int estimateReceiveWindowSize()
{ {
return recv_position.get(0); return recv_position.get(0);
} }
/** /**
* *
* @return estimated send window size * @return estimated send window size
*/ */
int estimateSendWindowSize() int estimateSendWindowSize()
{ {
return send_position.get(0); return send_position.get(0);
} }
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
} }
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
} }
void setLocalOptSndBuf(int len) void setLocalOptSndBuf(int len)
{ {
getLocalTcp().setOption(Option.OPT_SNDBUF, len); getLocalTcp().setOption(Option.OPT_SNDBUF, len);
} }
int getRemoteScaleFactor() int getRemoteScaleFactor()
{ {
return getRemoteTcp().getM_rwnd_scale(); return getRemoteTcp().getM_rwnd_scale();
} }
public void testGetShadowedBytes() public void testGetShadowedBytes()
{ {
assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0); assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(1) == 1); assert (PseudoTcpTestRecvWindow.getShadowedBytes(1) == 1);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(2) == 3); assert (PseudoTcpTestRecvWindow.getShadowedBytes(2) == 3);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(3) == 7); assert (PseudoTcpTestRecvWindow.getShadowedBytes(3) == 7);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(4) == 15); assert (PseudoTcpTestRecvWindow.getShadowedBytes(4) == 15);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(11) == 2047); assert (PseudoTcpTestRecvWindow.getShadowedBytes(11) == 2047);
assert (PseudoTcpTestRecvWindow.getShadowedBytes(14) == 16383); assert (PseudoTcpTestRecvWindow.getShadowedBytes(14) == 16383);
} }
/** /**
* Test that receive window expands and contract correctly. * Test that receive window expands and contract correctly.
*/ */
public void testReceiveWindow() public void testReceiveWindow()
{ {
//logger.log(Level.INFO, "Test receive window"); //logger.log(Level.INFO, "Test receive window");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptNagling(false); test.setOptNagling(false);
test.setOptAckDelay(0); test.setOptAckDelay(0);
test.doTestTransfer(1024 * 1000); test.doTestTransfer(1024 * 1000);
} }
/** /**
* Test setting send window size to a very small value. * Test setting send window size to a very small value.
*/ */
public void testSetVerySmallSendWindowSize() public void testSetVerySmallSendWindowSize()
{ {
//TODO: finish test //TODO: finish test
logger.log(Level.INFO, "Test very small receive window"); logger.log(Level.INFO, "Test very small receive window");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptNagling(false); test.setOptNagling(false);
test.setOptAckDelay(0); test.setOptAckDelay(0);
test.setOptSndBuf(900); test.setOptSndBuf(900);
test.doTestTransfer(1024 * 1000); test.doTestTransfer(1024 * 1000);
assertEquals(900, test.estimateSendWindowSize()); assertEquals(900, test.estimateSendWindowSize());
} }
/** /**
* Test setting receive window size to a value other than default. * Test setting receive window size to a value other than default.
*/ */
public void testSetReceiveWindowSize() public void testSetReceiveWindowSize()
{ {
//logger.log(Level.INFO, "Test set receive window size"); //logger.log(Level.INFO, "Test set receive window size");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.setLocalMtu(1500); test.setLocalMtu(1500);
test.setRemoteMtu(1500); test.setRemoteMtu(1500);
test.setOptNagling(false); test.setOptNagling(false);
test.setOptAckDelay(0); test.setOptAckDelay(0);
int wndSize = 300000; int wndSize = 300000;
test.setRemoteOptRcvBuf(wndSize); test.setRemoteOptRcvBuf(wndSize);
test.setLocalOptSndBuf(wndSize); test.setLocalOptSndBuf(wndSize);
int wndScale = test.getRemoteScaleFactor(); int wndScale = test.getRemoteScaleFactor();
//logger.log(Level.INFO, "Using scale factor: {0}", wndScale); //logger.log(Level.INFO, "Using scale factor: {0}", wndScale);
test.doTestTransfer(1024 * 3000); test.doTestTransfer(1024 * 3000);
//beacuse there may be situations //beacuse there may be situations
//when 1 byte may be waiting in send queue //when 1 byte may be waiting in send queue
//before //before
//scaling factor == 1 not allows to determine exact window size (+-1) //scaling factor == 1 not allows to determine exact window size (+-1)
assert (wndSize - test.estimateReceiveWindowSize() assert (wndSize - test.estimateReceiveWindowSize()
<= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale)); <= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale));
} }
/* /*
* Test sending data with mismatched MTUs. We should detect this and reduce * Test sending data with mismatched MTUs. We should detect this and reduce
* // our packet size accordingly. // TODO: This doesn't actually work right * // 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 * now. The current code // doesn't detect if the MTU is set too high on
* either side. TEST_F(PseudoTcpTest, TestSendWithMismatchedMtus) { * either side. TEST_F(PseudoTcpTest, TestSendWithMismatchedMtus) {
* SetLocalMtu(1500); SetRemoteMtu(1280); TestTransfer(1000000); } * SetLocalMtu(1500); SetRemoteMtu(1280); TestTransfer(1000000); }
*/ */
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,341 +15,341 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.pseudotcp.util; package org.ice4j.pseudotcp.util;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.nio.*; import java.nio.*;
import java.util.*; import java.util.*;
import junit.framework.*; import junit.framework.*;
/** /**
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class ByteFifoBufferTest public class ByteFifoBufferTest
extends TestCase extends TestCase
{ {
public ByteFifoBufferTest() public ByteFifoBufferTest()
{ {
} }
/** /**
* Test of Length method, of class ByteFifoBuffer. * Test of Length method, of class ByteFifoBuffer.
*/ */
public void testLength() public void testLength()
{ {
int expResult = 1000; int expResult = 1000;
ByteFifoBuffer instance = new ByteFifoBuffer(expResult); ByteFifoBuffer instance = new ByteFifoBuffer(expResult);
assertEquals(expResult, instance.length()); assertEquals(expResult, instance.length());
int wSize = 100; int wSize = 100;
instance.write(getWData(wSize), wSize); instance.write(getWData(wSize), wSize);
int result = instance.length(); int result = instance.length();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/** /**
* Test of Read method, of class ByteFifoBuffer. * Test of Read method, of class ByteFifoBuffer.
*/ */
public void testRead() public void testRead()
{ {
int count = 1024; int count = 1024;
byte[] wData = getWData(count); byte[] wData = getWData(count);
ByteFifoBuffer instance = new ByteFifoBuffer(count); ByteFifoBuffer instance = new ByteFifoBuffer(count);
instance.write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count; int expResult = count;
int result = instance.read(readBuff, count); int result = instance.read(readBuff, count);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
} }
/** /**
* Tests reading with an offset for destination buffer * Tests reading with an offset for destination buffer
*/ */
public void testReadWithOffset() public void testReadWithOffset()
{ {
int count = 1024; int count = 1024;
byte[] wData = getWData(count); byte[] wData = getWData(count);
ByteFifoBuffer instance = new ByteFifoBuffer(count); ByteFifoBuffer instance = new ByteFifoBuffer(count);
instance.write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count / 2; int expResult = count / 2;
int result = instance.read(readBuff, count / 2); int result = instance.read(readBuff, count / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
result = instance.read(readBuff, count / 2, count / 2); result = instance.read(readBuff, count / 2, count / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
} }
/** /**
* return some random array * return some random array
* *
* @param count array size * @param count array size
* @return * @return
*/ */
private byte[] getWData(int count) private byte[] getWData(int count)
{ {
Random r = new Random(); Random r = new Random();
byte[] res = new byte[count]; byte[] res = new byte[count];
r.nextBytes(res); r.nextBytes(res);
return res; return res;
} }
/** /**
* Test of GetWriteRemaining method, of class ByteFifoBuffer. * Test of GetWriteRemaining method, of class ByteFifoBuffer.
*/ */
public void testGetWriteRemaining() public void testGetWriteRemaining()
{ {
int len = 100; int len = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
int result = instance.getWriteRemaining(); int result = instance.getWriteRemaining();
assertEquals(expResult, result); assertEquals(expResult, result);
int w_size = 23; int w_size = 23;
byte[] w_data = getWData(w_size); byte[] w_data = getWData(w_size);
instance.write(w_data, w_size); instance.write(w_data, w_size);
expResult = len - w_size; expResult = len - w_size;
result = instance.getWriteRemaining(); result = instance.getWriteRemaining();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/** /**
* Test of GetBuffered method, of class ByteFifoBuffer. * Test of GetBuffered method, of class ByteFifoBuffer.
*/ */
public void testGetBuffered() public void testGetBuffered()
{ {
int len = 1000; int len = 1000;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int w_len = 100; int w_len = 100;
byte[] w_data = getWData(w_len); byte[] w_data = getWData(w_len);
instance.write(w_data, w_len); instance.write(w_data, w_len);
int expResult = w_len; int expResult = w_len;
int result = instance.getBuffered(); int result = instance.getBuffered();
assertEquals(expResult, result); assertEquals(expResult, result);
int consume = 5; int consume = 5;
expResult = w_len + consume; expResult = w_len + consume;
instance.consumeWriteBuffer(consume); instance.consumeWriteBuffer(consume);
result = instance.getBuffered(); result = instance.getBuffered();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/** /**
* Test of Write method, of class ByteFifoBuffer. * Test of Write method, of class ByteFifoBuffer.
*/ */
public void testWrite() public void testWrite()
{ {
int len = 2048; int len = 2048;
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
int result = instance.write(data, len); int result = instance.write(data, len);
assertEquals(expResult, result); assertEquals(expResult, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.read(read, len); int readCount = instance.read(read, len);
assertEquals(result, readCount); assertEquals(result, readCount);
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
public void testWriteWithOffset() public void testWriteWithOffset()
{ {
int len = 2048; int len = 2048;
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len / 2; int expResult = len / 2;
int result = instance.write(data, 0, len / 2); int result = instance.write(data, 0, len / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
result = instance.write(data, len / 2, len / 2); result = instance.write(data, len / 2, len / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.read(read, len); int readCount = instance.read(read, len);
assertEquals(len, readCount); assertEquals(len, readCount);
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
/** /**
* Test of ConsumeWriteBuffer method, of class ByteFifoBuffer. * Test of ConsumeWriteBuffer method, of class ByteFifoBuffer.
*/ */
public void testConsumeWriteBuffer() public void testConsumeWriteBuffer()
{ {
int len = 100; int len = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
instance.consumeWriteBuffer(len / 2); instance.consumeWriteBuffer(len / 2);
instance.consumeWriteBuffer(len / 2); instance.consumeWriteBuffer(len / 2);
try try
{ {
instance.consumeWriteBuffer(1); instance.consumeWriteBuffer(1);
fail(); fail();
} }
catch (BufferOverflowException e) catch (BufferOverflowException e)
{ {
} }
instance = new ByteFifoBuffer(len); instance = new ByteFifoBuffer(len);
instance.consumeWriteBuffer(95); instance.consumeWriteBuffer(95);
instance.consumeReadData(40); instance.consumeReadData(40);
instance.consumeWriteBuffer(20); instance.consumeWriteBuffer(20);
} }
/** /**
* Test of SetCapacity method, of class ByteFifoBuffer. * Test of SetCapacity method, of class ByteFifoBuffer.
*/ */
public void testSetCapacity() public void testSetCapacity()
{ {
int old_size = 100; int old_size = 100;
int new_size = 200; int new_size = 200;
ByteFifoBuffer instance = new ByteFifoBuffer(old_size); ByteFifoBuffer instance = new ByteFifoBuffer(old_size);
boolean expResult = true; boolean expResult = true;
instance.write(getWData(old_size), old_size); instance.write(getWData(old_size), old_size);
boolean result = instance.setCapacity(new_size); boolean result = instance.setCapacity(new_size);
assertEquals(expResult, result); assertEquals(expResult, result);
expResult = false; expResult = false;
instance.resetWritePosition(); instance.resetWritePosition();
instance.write(getWData(new_size), new_size); instance.write(getWData(new_size), new_size);
result = instance.setCapacity(old_size); result = instance.setCapacity(old_size);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/** /**
* Test of ConsumeReadData method, of class ByteFifoBuffer. * Test of ConsumeReadData method, of class ByteFifoBuffer.
*/ */
public void testConsumeReadData() public void testConsumeReadData()
{ {
int lCount = 100; int lCount = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(lCount); ByteFifoBuffer instance = new ByteFifoBuffer(lCount);
instance.write(getWData(lCount), lCount); instance.write(getWData(lCount), lCount);
instance.consumeReadData(lCount / 2); instance.consumeReadData(lCount / 2);
instance.consumeReadData(lCount / 2); instance.consumeReadData(lCount / 2);
try try
{ {
instance.consumeReadData(1); instance.consumeReadData(1);
fail(); fail();
} }
catch (BufferUnderflowException e) catch (BufferUnderflowException e)
{ {
} }
} }
/** /**
* Test of ReadOffset method, of class ByteFifoBuffer. * Test of ReadOffset method, of class ByteFifoBuffer.
*/ */
public void testReadOffset() public void testReadOffset()
{ {
int dst_buff_offset = 0; int dst_buff_offset = 0;
int len = 100; int len = 100;
byte[] src_buff = getWData(len); byte[] src_buff = getWData(len);
byte[] dst_buff = new byte[len]; byte[] dst_buff = new byte[len];
int offset = 0; int offset = 0;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
instance.write(src_buff, len); instance.write(src_buff, len);
int result = int result =
instance.readOffset(dst_buff, dst_buff_offset, len, offset); instance.readOffset(dst_buff, dst_buff_offset, len, offset);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(dst_buff, src_buff); assertArrayEquals(dst_buff, src_buff);
} }
/** /**
* Test of WriteOffset method, of class ByteFifoBuffer. * Test of WriteOffset method, of class ByteFifoBuffer.
*/ */
public void testWriteOffset() public void testWriteOffset()
{ {
int len = 200; int len = 200;
int dataLen = 100; int dataLen = 100;
byte[] srcData = getWData(dataLen); byte[] srcData = getWData(dataLen);
byte[] data = new byte[dataLen]; byte[] data = new byte[dataLen];
int nOffset = 10; int nOffset = 10;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int result = instance.writeOffset(srcData, dataLen, nOffset); int result = instance.writeOffset(srcData, dataLen, nOffset);
int readCount = instance.readOffset(data, 0, dataLen, nOffset); int readCount = instance.readOffset(data, 0, dataLen, nOffset);
assertEquals(result, readCount); assertEquals(result, readCount);
assertArrayEquals(srcData, data); assertArrayEquals(srcData, data);
byte[] halfFilled = new byte[dataLen * 2]; byte[] halfFilled = new byte[dataLen * 2];
System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen); System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen);
byte[] halfFilledRead = new byte[dataLen * 2]; byte[] halfFilledRead = new byte[dataLen * 2];
instance.readOffset(halfFilledRead, dataLen, dataLen, nOffset); instance.readOffset(halfFilledRead, dataLen, dataLen, nOffset);
assertArrayEquals(halfFilled, halfFilledRead); assertArrayEquals(halfFilled, halfFilledRead);
// case when w_pos+offset exceeds current backing array length // case when w_pos+offset exceeds current backing array length
instance = new ByteFifoBuffer(len); instance = new ByteFifoBuffer(len);
instance.write(srcData, dataLen); instance.write(srcData, dataLen);
instance.write(srcData, dataLen / 2);// current writePos = 150 instance.write(srcData, dataLen / 2);// current writePos = 150
instance.read(data, dataLen);// curretn readPos = 100 instance.read(data, dataLen);// curretn readPos = 100
instance.writeOffset(srcData, dataLen, 50); instance.writeOffset(srcData, dataLen, 50);
instance = new ByteFifoBuffer(61440); instance = new ByteFifoBuffer(61440);
instance.writeOffset(getWData(1384), 1384, 31832); instance.writeOffset(getWData(1384), 1384, 31832);
} }
public void testWriteReadWriteRead() public void testWriteReadWriteRead()
{ {
int len = 2000; int len = 2000;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
byte[] wrData = getWData(len * 2); byte[] wrData = getWData(len * 2);
int written = 0; int written = 0;
byte[] readBuff = new byte[wrData.length]; byte[] readBuff = new byte[wrData.length];
int read = 0; int read = 0;
do do
{ {
int wrRemaining = instance.getWriteRemaining(); int wrRemaining = instance.getWriteRemaining();
if (wrRemaining > 0 && written < wrData.length) if (wrRemaining > 0 && written < wrData.length)
{ {
int wrCount = instance.writeOffset(wrData, wrRemaining, 0); int wrCount = instance.writeOffset(wrData, wrRemaining, 0);
instance.consumeWriteBuffer(wrCount); instance.consumeWriteBuffer(wrCount);
written += wrCount; written += wrCount;
} }
int readAvailable = instance.getBuffered(); int readAvailable = instance.getBuffered();
if (readAvailable > 0) if (readAvailable > 0)
{ {
int rCount = int rCount =
instance.readOffset(readBuff, read, readAvailable, 0); instance.readOffset(readBuff, read, readAvailable, 0);
instance.consumeReadData(rCount); instance.consumeReadData(rCount);
read += rCount; read += rCount;
} }
} }
while ((read != wrData.length) || (written != wrData.length)); while ((read != wrData.length) || (written != wrData.length));
} }
public void testSomeMultiTest() public void testSomeMultiTest()
{ {
int Alen = 16; int Alen = 16;
int Blen = 32; int Blen = 32;
int Clen = 64; int Clen = 64;
int Dlen = 256; int Dlen = 256;
int len = Alen + Blen + Clen + Dlen; int len = Alen + Blen + Clen + Dlen;
ByteFifoBuffer fifo = new ByteFifoBuffer(len); ByteFifoBuffer fifo = new ByteFifoBuffer(len);
byte[] A = getWData(Alen); byte[] A = getWData(Alen);
/*byte[] B =*/ getWData(Blen); /*byte[] B =*/ getWData(Blen);
/*byte[] C =*/ getWData(Clen); /*byte[] C =*/ getWData(Clen);
/*byte[] D =*/ getWData(Dlen); /*byte[] D =*/ getWData(Dlen);
byte[] Aread = getWData(Alen); byte[] Aread = getWData(Alen);
/*byte[] Bread =*/ getWData(Blen); /*byte[] Bread =*/ getWData(Blen);
/*byte[] Cread =*/ getWData(Clen); /*byte[] Cread =*/ getWData(Clen);
/*byte[] Dread =*/ getWData(Dlen); /*byte[] Dread =*/ getWData(Dlen);
fifo.writeOffset(A, Alen, 0); fifo.writeOffset(A, Alen, 0);
fifo.consumeWriteBuffer(Alen); fifo.consumeWriteBuffer(Alen);
fifo.readOffset(Aread, 0, Alen, 0); fifo.readOffset(Aread, 0, Alen, 0);
assertArrayEquals(A, Aread); assertArrayEquals(A, Aread);
} }
} }

View File

@ -1,4 +1,4 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2015 Atlassian Pty Ltd * Copyright @ 2015 Atlassian Pty Ltd
@ -15,465 +15,465 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package test; package test;
import java.beans.*; import java.beans.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.ice.harvest.*; import org.ice4j.ice.harvest.*;
import org.ice4j.pseudotcp.*; import org.ice4j.pseudotcp.*;
import org.ice4j.security.*; import org.ice4j.security.*;
/** /**
* Sample program which first uses ICE to discover UDP connectivity. After that * Sample program which first uses ICE to discover UDP connectivity. After that
* selected cadidates are used by "remote" and "local" pseudoTCP peers to * selected cadidates are used by "remote" and "local" pseudoTCP peers to
* transfer some test data. * transfer some test data.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class IcePseudoTcp public class IcePseudoTcp
{ {
/** /**
* The logger. * The logger.
*/ */
private static final Logger logger = private static final Logger logger =
Logger.getLogger(IcePseudoTcp.class.getName()); Logger.getLogger(IcePseudoTcp.class.getName());
private static long startTime; private static long startTime;
/** /**
* Local job thread variable * Local job thread variable
*/ */
private static LocalPseudoTcpJob localJob = null; private static LocalPseudoTcpJob localJob = null;
/** /**
* Remote job thread variable * Remote job thread variable
*/ */
private static RemotePseudoTcpJob remoteJob = null; private static RemotePseudoTcpJob remoteJob = null;
/** /**
* Test data size * Test data size
*/ */
private static final int TEST_BYTES_COUNT = 15000000; private static final int TEST_BYTES_COUNT = 15000000;
/** /**
* Flag inidcates if STUN should be used * Flag inidcates if STUN should be used
*/ */
private static final boolean USE_STUN = true; private static final boolean USE_STUN = true;
/** /**
* Flag inidcates if TURN should be used * Flag inidcates if TURN should be used
*/ */
private static final boolean USE_TURN = true; private static final boolean USE_TURN = true;
/** /**
* Monitor object used to wait for remote agent to finish it's job * Monitor object used to wait for remote agent to finish it's job
*/ */
private static final Object remoteAgentMonitor = new Object(); private static final Object remoteAgentMonitor = new Object();
/** /**
* Monitor object used to wait for local agent to finish it's job * Monitor object used to wait for local agent to finish it's job
*/ */
private static final Object localAgentMonitor = new Object(); private static final Object localAgentMonitor = new Object();
/** /**
* Timeout for ICE discovery * Timeout for ICE discovery
*/ */
private static long agentJobTimeout = 15000; private static long agentJobTimeout = 15000;
protected static Agent createAgent(int pTcpPort) protected static Agent createAgent(int pTcpPort)
throws Throwable throws Throwable
{ {
Agent agent = new Agent(); Agent agent = new Agent();
// STUN // STUN
if (USE_STUN) if (USE_STUN)
{ {
StunCandidateHarvester stunHarv = new StunCandidateHarvester( StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("sip-communicator.net", new TransportAddress("sip-communicator.net",
3478, Transport.UDP)); 3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester( StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("ipv6.sip-communicator.net", new TransportAddress("ipv6.sip-communicator.net",
3478, Transport.UDP)); 3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv); agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv); agent.addCandidateHarvester(stun6Harv);
} }
// TURN // TURN
if (USE_TURN) if (USE_TURN)
{ {
String[] hostnames = new String[] String[] hostnames = new String[]
{ {
"130.79.90.150", "130.79.90.150",
"2001:660:4701:1001:230:5ff:fe1a:805f" "2001:660:4701:1001:230:5ff:fe1a:805f"
}; };
int port = 3478; int port = 3478;
LongTermCredential longTermCredential = new LongTermCredential( LongTermCredential longTermCredential = new LongTermCredential(
"guest", "anonymouspower!!"); "guest", "anonymouspower!!");
for (String hostname : hostnames) for (String hostname : hostnames)
{ {
agent.addCandidateHarvester(new TurnCandidateHarvester( agent.addCandidateHarvester(new TurnCandidateHarvester(
new TransportAddress(hostname, port, new TransportAddress(hostname, port,
Transport.UDP), longTermCredential)); Transport.UDP), longTermCredential));
} }
} }
//STREAM //STREAM
createStream(pTcpPort, "data", agent); createStream(pTcpPort, "data", agent);
return agent; return agent;
} }
private static IceMediaStream createStream(int pTcpPort, private static IceMediaStream createStream(int pTcpPort,
String streamName, String streamName,
Agent agent) Agent agent)
throws Throwable throws Throwable
{ {
IceMediaStream stream = agent.createMediaStream(streamName); IceMediaStream stream = agent.createMediaStream(streamName);
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
//udp component //udp component
agent.createComponent( agent.createComponent(
stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100); stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100);
long endTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis();
logger.log(Level.INFO, logger.log(Level.INFO,
"UDP Component created in " + (endTime - startTime) + " ms"); "UDP Component created in " + (endTime - startTime) + " ms");
startTime = endTime; startTime = endTime;
return stream; return stream;
} }
private static final class LocalIceProcessingListener private static final class LocalIceProcessingListener
implements PropertyChangeListener implements PropertyChangeListener
{ {
/** /**
* System.exit()s as soon as ICE processing enters a final state. * System.exit()s as soon as ICE processing enters a final state.
* *
* @param evt the {@link PropertyChangeEvent} containing the old and new * @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing. * states of ICE processing.
*/ */
public void propertyChange(PropertyChangeEvent evt) public void propertyChange(PropertyChangeEvent evt)
{ {
long processingEndTime = System.currentTimeMillis(); long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue(); Object iceProcessingState = evt.getNewValue();
logger.log( logger.log(
Level.INFO, Level.INFO,
"Local agent entered the " + iceProcessingState "Local agent entered the " + iceProcessingState
+ " state."); + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED) if (iceProcessingState == IceProcessingState.COMPLETED)
{ {
logger.log( logger.log(
Level.INFO, Level.INFO,
"Local - Total ICE processing time: " "Local - Total ICE processing time: "
+ (processingEndTime - startTime) + "ms"); + (processingEndTime - startTime) + "ms");
Agent agent = (Agent) evt.getSource(); Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Local: Create pseudo tcp stream"); logger.log(Level.INFO, "Local: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data"); IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0); Component udpComponent = dataStream.getComponents().get(0);
CandidatePair selectedPair = udpComponent.getSelectedPair(); CandidatePair selectedPair = udpComponent.getSelectedPair();
if (selectedPair != null) if (selectedPair != null)
{ {
LocalCandidate localCandidate LocalCandidate localCandidate
= selectedPair.getLocalCandidate(); = selectedPair.getLocalCandidate();
Candidate<?> remoteCandidate Candidate<?> remoteCandidate
= selectedPair.getRemoteCandidate(); = selectedPair.getRemoteCandidate();
logger.log(Level.INFO, "Local: " + localCandidate); logger.log(Level.INFO, "Local: " + localCandidate);
logger.log(Level.INFO, "Remote: " + remoteCandidate); logger.log(Level.INFO, "Remote: " + remoteCandidate);
try try
{ {
localJob = new LocalPseudoTcpJob( localJob = new LocalPseudoTcpJob(
selectedPair.getDatagramSocket()); selectedPair.getDatagramSocket());
} }
catch (UnknownHostException ex) catch (UnknownHostException ex)
{ {
logger.log(Level.SEVERE, logger.log(Level.SEVERE,
"Error while trying to create" "Error while trying to create"
+ " local pseudotcp thread " + ex); + " local pseudotcp thread " + ex);
} }
} }
else else
{ {
logger.log( logger.log(
Level.INFO, Level.INFO,
"Failed to select any candidate pair"); "Failed to select any candidate pair");
} }
} }
else else
{ {
if (iceProcessingState == IceProcessingState.TERMINATED if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED) || iceProcessingState == IceProcessingState.FAILED)
{ {
/* /*
* Though the process will be instructed to die, demonstrate * Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for * that Agent instances are to be explicitly prepared for
* garbage collection. * garbage collection.
*/ */
if ((localJob != null) if ((localJob != null)
&& (iceProcessingState && (iceProcessingState
== IceProcessingState.TERMINATED)) == IceProcessingState.TERMINATED))
{ {
localJob.start(); localJob.start();
} }
synchronized (localAgentMonitor) synchronized (localAgentMonitor)
{ {
localAgentMonitor.notifyAll(); localAgentMonitor.notifyAll();
} }
} }
} }
} }
} }
private static final class RemoteIceProcessingListener private static final class RemoteIceProcessingListener
implements PropertyChangeListener implements PropertyChangeListener
{ {
/** /**
* System.exit()s as soon as ICE processing enters a final state. * System.exit()s as soon as ICE processing enters a final state.
* *
* @param evt the {@link PropertyChangeEvent} containing the old and new * @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing. * states of ICE processing.
*/ */
public void propertyChange(PropertyChangeEvent evt) public void propertyChange(PropertyChangeEvent evt)
{ {
long processingEndTime = System.currentTimeMillis(); long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue(); Object iceProcessingState = evt.getNewValue();
logger.log( logger.log(
Level.INFO, Level.INFO,
"Remote agent entered the " + iceProcessingState "Remote agent entered the " + iceProcessingState
+ " state."); + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED) if (iceProcessingState == IceProcessingState.COMPLETED)
{ {
logger.log(Level.INFO, logger.log(Level.INFO,
"Remote: Total ICE processing time: " "Remote: Total ICE processing time: "
+ (processingEndTime - startTime) + " ms "); + (processingEndTime - startTime) + " ms ");
Agent agent = (Agent) evt.getSource(); Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Remote: Create pseudo tcp stream"); logger.log(Level.INFO, "Remote: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data"); IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0); Component udpComponent = dataStream.getComponents().get(0);
CandidatePair usedPair = udpComponent.getSelectedPair(); CandidatePair usedPair = udpComponent.getSelectedPair();
if (usedPair != null) if (usedPair != null)
{ {
LocalCandidate localCandidate LocalCandidate localCandidate
= usedPair.getLocalCandidate(); = usedPair.getLocalCandidate();
Candidate<?> remoteCandidate Candidate<?> remoteCandidate
= usedPair.getRemoteCandidate(); = usedPair.getRemoteCandidate();
logger.log(Level.INFO, logger.log(Level.INFO,
"Remote: Local address " + localCandidate); "Remote: Local address " + localCandidate);
logger.log(Level.INFO, logger.log(Level.INFO,
"Remote: Peer address " + remoteCandidate); "Remote: Peer address " + remoteCandidate);
try try
{ {
remoteJob = new RemotePseudoTcpJob( remoteJob = new RemotePseudoTcpJob(
usedPair.getDatagramSocket(), usedPair.getDatagramSocket(),
remoteCandidate.getTransportAddress()); remoteCandidate.getTransportAddress());
} }
catch (UnknownHostException ex) catch (UnknownHostException ex)
{ {
logger.log(Level.SEVERE, logger.log(Level.SEVERE,
"Error while trying to create" "Error while trying to create"
+ " remote pseudotcp thread " + ex); + " remote pseudotcp thread " + ex);
} }
} }
else else
{ {
logger.log(Level.SEVERE, logger.log(Level.SEVERE,
"Remote: Failed to select any candidate pair"); "Remote: Failed to select any candidate pair");
} }
} }
else else
{ {
if (iceProcessingState == IceProcessingState.TERMINATED if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED) || iceProcessingState == IceProcessingState.FAILED)
{ {
/* /*
* Though the process will be instructed to die, demonstrate * Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for * that Agent instances are to be explicitly prepared for
* garbage collection. * garbage collection.
*/ */
if ((remoteJob != null) if ((remoteJob != null)
&& (iceProcessingState && (iceProcessingState
== IceProcessingState.TERMINATED)) == IceProcessingState.TERMINATED))
{ {
remoteJob.start(); remoteJob.start();
} }
synchronized (remoteAgentMonitor) synchronized (remoteAgentMonitor)
{ {
remoteAgentMonitor.notifyAll(); remoteAgentMonitor.notifyAll();
} }
} }
} }
} }
} }
public static void main(String[] args) throws Throwable public static void main(String[] args) throws Throwable
{ {
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
int localPort = 7999; int localPort = 7999;
int remotePort = 6000; int remotePort = 6000;
Agent localAgent = createAgent(localPort); Agent localAgent = createAgent(localPort);
localAgent.setNominationStrategy( localAgent.setNominationStrategy(
NominationStrategy.NOMINATE_HIGHEST_PRIO); NominationStrategy.NOMINATE_HIGHEST_PRIO);
Agent remotePeer = Agent remotePeer =
createAgent(remotePort); createAgent(remotePort);
localAgent.addStateChangeListener( localAgent.addStateChangeListener(
new IcePseudoTcp.LocalIceProcessingListener()); new IcePseudoTcp.LocalIceProcessingListener());
remotePeer.addStateChangeListener( remotePeer.addStateChangeListener(
new IcePseudoTcp.RemoteIceProcessingListener()); new IcePseudoTcp.RemoteIceProcessingListener());
//let them fight ... fights forge character. //let them fight ... fights forge character.
localAgent.setControlling(true); localAgent.setControlling(true);
remotePeer.setControlling(false); remotePeer.setControlling(false);
long endTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis();
Ice.transferRemoteCandidates(localAgent, remotePeer); Ice.transferRemoteCandidates(localAgent, remotePeer);
for (IceMediaStream stream : localAgent.getStreams()) for (IceMediaStream stream : localAgent.getStreams())
{ {
stream.setRemoteUfrag(remotePeer.getLocalUfrag()); stream.setRemoteUfrag(remotePeer.getLocalUfrag());
stream.setRemotePassword(remotePeer.getLocalPassword()); stream.setRemotePassword(remotePeer.getLocalPassword());
} }
Ice.transferRemoteCandidates(remotePeer, localAgent); Ice.transferRemoteCandidates(remotePeer, localAgent);
for (IceMediaStream stream : remotePeer.getStreams()) for (IceMediaStream stream : remotePeer.getStreams())
{ {
stream.setRemoteUfrag(localAgent.getLocalUfrag()); stream.setRemoteUfrag(localAgent.getLocalUfrag());
stream.setRemotePassword(localAgent.getLocalPassword()); stream.setRemotePassword(localAgent.getLocalPassword());
} }
logger.log(Level.INFO, "Total candidate gathering time: {0} ms", logger.log(Level.INFO, "Total candidate gathering time: {0} ms",
(endTime - startTime)); (endTime - startTime));
logger.log(Level.INFO, "LocalAgent: {0}", logger.log(Level.INFO, "LocalAgent: {0}",
localAgent); localAgent);
localAgent.startConnectivityEstablishment(); localAgent.startConnectivityEstablishment();
//if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER) //if (START_CONNECTIVITY_ESTABLISHMENT_OF_REMOTE_PEER)
remotePeer.startConnectivityEstablishment(); remotePeer.startConnectivityEstablishment();
IceMediaStream dataStream = localAgent.getStream("data"); IceMediaStream dataStream = localAgent.getStream("data");
if (dataStream != null) if (dataStream != null)
{ {
logger.log(Level.INFO, logger.log(Level.INFO,
"Local data clist:" + dataStream.getCheckList()); "Local data clist:" + dataStream.getCheckList());
} }
//wait for one of the agents to complete it's job //wait for one of the agents to complete it's job
synchronized (remoteAgentMonitor) synchronized (remoteAgentMonitor)
{ {
remoteAgentMonitor.wait(agentJobTimeout); remoteAgentMonitor.wait(agentJobTimeout);
} }
if (remoteJob != null) if (remoteJob != null)
{ {
logger.log(Level.FINEST, "Remote thread join started"); logger.log(Level.FINEST, "Remote thread join started");
remoteJob.join(); remoteJob.join();
logger.log(Level.FINEST, "Remote thread joined"); logger.log(Level.FINEST, "Remote thread joined");
} }
remotePeer.free(); remotePeer.free();
if (localJob != null) if (localJob != null)
{ {
logger.log(Level.FINEST, "Local thread join started"); logger.log(Level.FINEST, "Local thread join started");
localJob.join(); localJob.join();
logger.log(Level.FINEST, "Local thread joined"); logger.log(Level.FINEST, "Local thread joined");
} }
localAgent.free(); localAgent.free();
System.exit(0); System.exit(0);
} }
private static class LocalPseudoTcpJob extends Thread implements Runnable private static class LocalPseudoTcpJob extends Thread implements Runnable
{ {
private DatagramSocket dgramSocket; private DatagramSocket dgramSocket;
public LocalPseudoTcpJob(DatagramSocket socket) public LocalPseudoTcpJob(DatagramSocket socket)
throws UnknownHostException throws UnknownHostException
{ {
this.dgramSocket = socket; this.dgramSocket = socket;
} }
@Override @Override
public void run() public void run()
{ {
logger.log(Level.FINEST, "Local pseudotcp worker started"); logger.log(Level.FINEST, "Local pseudotcp worker started");
try try
{ {
logger.log(Level.INFO, logger.log(Level.INFO,
"Local pseudotcp is using: " "Local pseudotcp is using: "
+ dgramSocket.getLocalSocketAddress()+dgramSocket); + dgramSocket.getLocalSocketAddress()+dgramSocket);
PseudoTcpSocket socket = new PseudoTcpSocketFactory(). PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket); createSocket(dgramSocket);
socket.setConversationID(1073741824); socket.setConversationID(1073741824);
socket.setMTU(1500); socket.setMTU(1500);
socket.setDebugName("L"); socket.setDebugName("L");
socket.accept(5000); socket.accept(5000);
byte[] buffer = new byte[TEST_BYTES_COUNT]; byte[] buffer = new byte[TEST_BYTES_COUNT];
int read = 0; int read = 0;
while (read != TEST_BYTES_COUNT) while (read != TEST_BYTES_COUNT)
{ {
read += socket.getInputStream().read(buffer); read += socket.getInputStream().read(buffer);
logger.log(Level.FINEST, "Local job read: " + read); logger.log(Level.FINEST, "Local job read: " + read);
} }
//TODO: close when all received data is acked //TODO: close when all received data is acked
//socket.close(); //socket.close();
} }
catch (IOException e) catch (IOException e)
{ {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
logger.log(Level.FINEST, "Local pseudotcp worker finished"); logger.log(Level.FINEST, "Local pseudotcp worker finished");
} }
} }
private static class RemotePseudoTcpJob extends Thread implements Runnable private static class RemotePseudoTcpJob extends Thread implements Runnable
{ {
private DatagramSocket dgramSocket; private DatagramSocket dgramSocket;
private InetSocketAddress peerAddr; private InetSocketAddress peerAddr;
public RemotePseudoTcpJob(DatagramSocket socket, public RemotePseudoTcpJob(DatagramSocket socket,
InetSocketAddress peerAddr) InetSocketAddress peerAddr)
throws UnknownHostException throws UnknownHostException
{ {
this.dgramSocket = socket; this.dgramSocket = socket;
this.peerAddr = peerAddr; this.peerAddr = peerAddr;
} }
@Override @Override
public void run() public void run()
{ {
logger.log(Level.FINEST, "Remote pseudotcp worker started"); logger.log(Level.FINEST, "Remote pseudotcp worker started");
try try
{ {
logger.log(Level.INFO, logger.log(Level.INFO,
"Remote pseudotcp is using: " + "Remote pseudotcp is using: " +
dgramSocket.getLocalSocketAddress() dgramSocket.getLocalSocketAddress()
+" and will comunicate with: " + peerAddr); +" and will comunicate with: " + peerAddr);
PseudoTcpSocket socket = new PseudoTcpSocketFactory(). PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket); createSocket(dgramSocket);
socket.setConversationID(1073741824); socket.setConversationID(1073741824);
socket.setMTU(1500); socket.setMTU(1500);
socket.setDebugName("R"); socket.setDebugName("R");
long start, end; long start, end;
start = System.currentTimeMillis(); start = System.currentTimeMillis();
socket.connect(peerAddr, 5000); socket.connect(peerAddr, 5000);
byte[] buffer = new byte[TEST_BYTES_COUNT]; byte[] buffer = new byte[TEST_BYTES_COUNT];
socket.getOutputStream().write(buffer); socket.getOutputStream().write(buffer);
socket.getOutputStream().flush(); socket.getOutputStream().flush();
//Socket will be closed by the iceAgent //Socket will be closed by the iceAgent
//socket.close(); //socket.close();
end = System.currentTimeMillis(); end = System.currentTimeMillis();
logger.log(Level.INFO, logger.log(Level.INFO,
"Transferred " + TEST_BYTES_COUNT "Transferred " + TEST_BYTES_COUNT
+ " bytes in " + ((end - start) / 1000) + " sec"); + " bytes in " + ((end - start) / 1000) + " sec");
} }
catch (IOException e) catch (IOException e)
{ {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
logger.log(Level.FINEST, "Remote pseudotcp worker finished"); logger.log(Level.FINEST, "Remote pseudotcp worker finished");
} }
} }
} }