diff --git a/src/org/ice4j/NetAccessPointDescriptor.java b/src/org/ice4j/NetAccessPointDescriptor.java new file mode 100644 index 0000000..9d4366a --- /dev/null +++ b/src/org/ice4j/NetAccessPointDescriptor.java @@ -0,0 +1,119 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ + +package org.ice4j; + +/** + * The class is used to represent an [address]:[port] couple where the Stun4J + * stack is to listen for incoming messages. We need such a class so that we + * could identify and manage (add, remove, etc.) DatagramListeners. + * + * @author Emil Ivov + */ + +public class NetAccessPointDescriptor +{ + + /** + * The address string representing the host (interface) where the stack + * should bind. + */ + protected TransportAddress stunAddr = null; + + + /** + * Creates a net access point that will bind to the specified address. + * + * @param address a valid Stun Address. + */ + public NetAccessPointDescriptor(TransportAddress address) + { + stunAddr = address; + } + + /** + * Attempts to automatically detect the address of local host and binds + * on the specified port. + * + * @param port the port where to bind. + */ +/* public NetAccessPointDescriptor(int port) + { + stunAddr = new StunAddress(port); + } + */ + + /** + * Compares this object against the specified object. The result is true if + * and only if the argument is not null and it represents the same address + * as this object. + * + * Two instances of InetSocketAddress represent the same address if both the + * InetAddresses (or hostnames if it is unresolved) and port numbers are + * equal. If both addresses are unresolved, then the hostname & the port + * number are compared. + * + * @param obj the object to compare against. + * @return true if the objects are the same; false otherwise. + */ + public final boolean equals(Object obj) + { + if(obj == null + || !(obj instanceof NetAccessPointDescriptor)) + return false; + + if (obj == this) + return true; + + return stunAddr.equals( ((NetAccessPointDescriptor)obj).stunAddr ); + } + + /** + * Returns the socket address wrapped by this class. + * @return an InetSocketAddress instance. + */ + public TransportAddress getAddress() + { + return stunAddr; + } + + /** + * Clones the NetAccessPointDescriptor. + * + * @return a copy of this NetAccessPointDescriptor. + */ + public Object clone() + { + NetAccessPointDescriptor napd = new NetAccessPointDescriptor(stunAddr); + + return napd; + } + + + /** + * Returns the hashcode of this NetAccessPointDescriptor so that it could + * be used as a key in hashtables. + * + * @return the hashcode of this NetAccessPointDescriptor + */ + public int hashCode(){ + //we could actually simply return the hashcode of the socket address + //since it identifies us more or less uniquely + return stunAddr.getSocketAddress().hashCode(); + } + + /** + * Returns a string representation of this NetAccessPointDescriptor. + * + * @return a string representation of the object. + */ + public String toString() + { + + return "StunAddress=" + ( (stunAddr==null)? "null":stunAddr.toString()); + } +} diff --git a/src/org/ice4j/ResponseCollector.java b/src/org/ice4j/ResponseCollector.java new file mode 100644 index 0000000..76cbbd8 --- /dev/null +++ b/src/org/ice4j/ResponseCollector.java @@ -0,0 +1,35 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +import org.ice4j.*; + +/** + * The interface is used as a callback when sending a request. The response + * collector is then used as a means of dispatching the response. + * + *
Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public interface ResponseCollector +{ + /** + * Dispatch the specified response. + * @param response the response to dispatch. + */ + public void processResponse(StunMessageEvent response); + + /** + * Notify the collector that no response had been received + * after repeated retransmissions of the original request (as described + * by rfc3489) and that the request should be considered unanswered. + */ + public void processTimeout(); +} diff --git a/src/org/ice4j/StackProperties.java b/src/org/ice4j/StackProperties.java new file mode 100644 index 0000000..f2637a4 --- /dev/null +++ b/src/org/ice4j/StackProperties.java @@ -0,0 +1,105 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +import java.util.logging.*; + +/** + * The class contains a number of property names and their default values that + * we use to configure the behavior of the ice4j stack. + * @author Emil Ivov + */ +public class StackProperties +{ + /** + * Our class logger. + */ + private static final Logger logger + = Logger.getLogger(StackProperties.class.getName()); + + /** + * The name of the property containing the number of binds that we should + * should execute in case a port is already bound to (each retry would be on + * a new random port). + */ + public static final String BIND_RETRIES_PROPERTY_NAME + = "org.ice4j.BIND_RETRIES"; + + /** + * The default number of binds that we would try + * implementation should execute in case a port is already bound to (each + * retry would be on a different port). + */ + public static final int BIND_RETRIES_DEFAULT_VALUE = 50; + + /** + * Returns the String value of the specified property (minus all + * encompassing whitespaces)and null in case no property value was mapped + * against the specified propertyName, or in case the returned property + * string had zero length or contained whitespaces only. + * + * @param propertyName the name of the property that is being queried. + * + * @return the result of calling the property's toString method and null in + * case there was no value mapped against the specified + * propertyName, or the returned string had zero length or + * contained whitespaces only. + */ + public static String getString(String propertyName) + { + Object propValue = System.getProperty(propertyName); + if (propValue == null) + return null; + + String propStrValue = propValue.toString().trim(); + + return (propStrValue.length() > 0) + ? propStrValue + : null; + } + + /** + * Returns the value of a specific property as a signed decimal integer. If + * a property with the specified property name exists, its string + * representation is parsed into a signed decimal integer according to the + * rules of {@link Integer#parseInt(String)}. If parsing the value as a + * signed decimal integer fails or there is no value associated with the + * specified property name, defaultValue is returned. + * + * @param propertyName the name of the property to get the value of as a + * signed decimal integer + * @param defaultValue the value to be returned if parsing the value of the + * specified property name as a signed decimal integer fails or there is no + * value associated with the specified property name in the System + * properties. + * @return the value of the property with the specified name in the System + * properties as a signed decimal integer; + * defaultValue if parsing the value of the specified property name + * fails or no value is associated among the System properties. + */ + public static int getInt(String propertyName, int defaultValue) + { + String stringValue = getString(propertyName); + int intValue = defaultValue; + + if ((stringValue != null) && (stringValue.length() > 0)) + { + try + { + intValue = Integer.parseInt(stringValue); + } + catch (NumberFormatException ex) + { + logger.log(Level.FINE, propertyName + + " does not appear to be an integer. " + "Defaulting to " + + defaultValue + ".", ex); + } + } + return intValue; + } +} diff --git a/src/org/ice4j/StunException.java b/src/org/ice4j/StunException.java new file mode 100644 index 0000000..dc8ed14 --- /dev/null +++ b/src/org/ice4j/StunException.java @@ -0,0 +1,157 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +/** + * A StunException is thrown when a general STUN exception is encountered. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class StunException extends Exception +{ + /** + * Serial version UID for this Serializable class. + */ + private static final long serialVersionUID = 35367793L; + + /** + * Error ID. + */ + private int errorID = 0; + + /** + * Means that the the reason that caused the exception was unclear. + */ + public static final int UNKNOWN_ERROR = 0; + + /** + * Indicates that the attempted operation is not possible in the current + * state of the object. + */ + public static final int ILLEGAL_STATE = 1; + + /** + * Indicates that one or more of the passed arguments had invalid values. + */ + public static final int ILLEGAL_ARGUMENT = 2; + + /** + * Indicates that an unexpected error has occurred.. + */ + public static final int INTERNAL_ERROR = 3; + + /** + * Thrown when trying to send responses through a non-existant transaction + * That may happen when a corresponding request has already been responded + * to or when no such request has been received. + */ + public static final int TRANSACTION_DOES_NOT_EXIST = 3; + + + /** + * Indicates that an unexpected error has occurred.. + */ + public static final int NETWORK_ERROR = 4; + + + /** + * Identifies the exception. + */ + private int id = 0; + + /** + * Creates a StunException. + */ + public StunException() + { + + } + + /** + * Creates a StunException setting id as its identifier. + * @param id an error ID + */ + public StunException(int id) + { + setID(id); + } + + /** + * Creates a StunException, setting an error message. + * @param message an error message. + */ + public StunException(String message) + { + super(message); + } + + /** + * Creates a StunException, setting an error message and an error id. + * @param message an error message. + * @param id an error id. + */ + public StunException(int id, String message) + { + super(message); + setID(id); + } + + /** + * Creates a StunException, setting an error message an error id and a cause. + * @param message an error message. + * @param id an error id. + * @param cause the error that caused this exception. + */ + public StunException(int id, String message, Throwable cause) + { + super(message, cause); + setID(id); + } + + /** + * Creates a StunException, setting an error message and a cause object. + * @param message an error message. + * @param cause the error object that caused this exception. + */ + public StunException(String message, Throwable cause) + { + super(message, cause); + } + + /** + * Creates an exception, setting the Throwable object, that caused it. + * @param cause the error that caused this exception. + */ + public StunException(Throwable cause) + { + super(cause); + } + + /** + * Sets the identifier of the error that caused the exception. + * @param id the identifier of the error that caused the exception. + */ + public void setID(int id) + { + this.id = id; + } + + /** + * Returns this exception's identifier. + * @return this exception's identifier; + */ + public int getID() + { + return id; + } + +} diff --git a/src/org/ice4j/StunMessageEvent.java b/src/org/ice4j/StunMessageEvent.java new file mode 100644 index 0000000..0f59bc7 --- /dev/null +++ b/src/org/ice4j/StunMessageEvent.java @@ -0,0 +1,89 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +import java.util.EventObject; +import java.net.InetSocketAddress; + +import org.ice4j.message.*; +import org.ice4j.stack.*; + + +/** + * The class is used to dispatch incoming stun messages. Apart from the message + * itself one could also obtain the address from where the message is coming + * (used by a server implementation to determine the mapped address) + * as well as the Descriptor of the NetAccessPoint that received it (In case the + * stack is used on more than one ports/addresses). + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class StunMessageEvent + extends EventObject +{ + /** + * Serial version UID for this Serializable class. + */ + private static final long serialVersionUID = 41267843L; + + /** + * The message itself. + */ + private Message message = null; + + /** + * The sending address. + */ + private TransportAddress remoteAddress = null; + + /** + * Constructs a StunMessageEvent according to the specified message. + * @param source the access point that received the message + * @param message the message itself + * @param remoteAddress the address that sent the message + */ + public StunMessageEvent(NetAccessPointDescriptor source, + Message message, + TransportAddress remoteAddress) + { + super(source); + this.message = message; + this.remoteAddress = remoteAddress; + } + + /** + * Returns a NetAccessPointDescriptor referencing the access point where the + * message was received. + * @return a descriptor of the access point where the message arrived. + */ + public NetAccessPointDescriptor getSourceAccessPoint() + { + return (NetAccessPointDescriptor)getSource(); + } + + /** + * Returns the message being dispatched. + * @return the message that caused the event. + */ + public Message getMessage() + { + return message; + } + + /** + * Returns the address that sent the message. + * @return the address that sent the message. + */ + public TransportAddress getRemoteAddress() + { + return remoteAddress; + } +} diff --git a/src/org/ice4j/Transport.java b/src/org/ice4j/Transport.java new file mode 100644 index 0000000..852f835 --- /dev/null +++ b/src/org/ice4j/Transport.java @@ -0,0 +1,71 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +/** + * The Transport enumeration contains all currently known transports + * that ICE may be interacting with (but not necessarily support). + * + * @author Emil Ivov + */ +public enum Transport +{ + /** + * Represents a TCP transport. + */ + TCP("tcp"), + + /** + * Represents a UDP transport. + */ + UDP("udp"), + + /** + * Represents a TLS transport. + */ + TLS("tls"), + + /** + * Represents a datagram TLS (DTLS) transport. + */ + DTLS("dtls"), + + /** + * Represents an SCTP transport. + */ + SCTP("sctp"); + + /** + * The name of this Transport. + */ + private final String transportName; + + /** + * Creates a Transport instance with the specified name. + * + * @param transportName the name of the Transport instance we'd + * like to create. + */ + private Transport(String transportName) + { + this.transportName = transportName; + } + + /** + * Returns the name of this Transport (e.g. "udp" or + * "tcp"). + * + * @return the name of this Transport (e.g. "udp" or + * "tcp"). + */ + @Override + public String toString() + { + return transportName; + } +} diff --git a/src/org/ice4j/TransportAddress.java b/src/org/ice4j/TransportAddress.java new file mode 100644 index 0000000..f1f6997 --- /dev/null +++ b/src/org/ice4j/TransportAddress.java @@ -0,0 +1,264 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j; + +import java.net.*; + +import org.ice4j.ice.*; + +/** + * The Address class is used to define destinations to outgoing Stun Packets. + * + * @author Emil Ivov + */ + +public class TransportAddress +{ + /** + * The socket address instance that we use for saving address and port. + */ + private InetSocketAddress socketAddress = null; + + /** + * The variable that we are using to store the transport that this address + * is pertaining to. + */ + private final Transport transport; + + /** + * Creates an address instance address from an IP address and a port number + * and UDP transport. + *
+ * A valid port value is between 0 and 65535.
+ * A port number of zero will let the system pick up an
+ * ephemeral port in a bind operation.
+ *
+ * A null address will assign the wildcard address.
+ *
+ * @param hostname The IP address + * @param port The port number + * @throws IllegalArgumentException if the port parameter is outside the + * specified range of valid port values. + */ + public TransportAddress(String hostname, int port) + { + this(hostname, port, Transport.UDP); + } + + /** + * Creates an address instance address from an IP address and a port number. + *
+ * A valid port value is between 0 and 65535.
+ * A port number of zero will let the system pick up an
+ * ephemeral port in a bind operation.
+ *
+ * A null address will assign the wildcard address.
+ *
+ * @param hostname The IP address + * @param port The port number + * @param transport The transport that this address would be bound to. + * @throws IllegalArgumentException if the port parameter is outside the + * specified range of valid port values. + */ + public TransportAddress(String hostname, int port, Transport transport) + { + socketAddress = new InetSocketAddress(hostname, port); + this.transport = Transport.UDP; + } + + /** + * Creates an address instance address from a byte array containing an IP + * address and a port number. + *
+ * A valid port value is between 0 and 65535.
+ * A port number of zero will let the system pick up an
+ * ephemeral port in a bind operation.
+ *
+ * A null address will assign the wildcard address.
+ *
+ * @param ipAddress The IP address + * @param port The port number + * @throws IllegalArgumentException if the port parameter is outside the + * specified range of valid port values or if ipAddress is not a valid ip + * address. + */ + public TransportAddress(byte[] ipAddress, int port) + { + + try + { + socketAddress = new InetSocketAddress(InetAddress.getByAddress( + ipAddress), port); + } + catch (UnknownHostException ex) + { + //Unknown Host - Let's skip resolution + socketAddress = new InetSocketAddress((ipAddress[0]&0xFF) + "." + +(ipAddress[1]&0xFF) + "." + +(ipAddress[2]&0xFF) + "." + +(ipAddress[3]&0xFF) + ".", + port); + } + + transport = Transport.UDP; + } + + + /** + * Creates an address instance from a hostname and a port number. + *
+ * An attempt will be made to resolve the hostname into an InetAddress. + * If that attempt fails, the address will be flagged as unresolved. + *
+ * A valid port value is between 0 and 65535.
+ * A port number of zero will let the system pick up an
+ * ephemeral port in a bind operation.
+ *
+ * @param address the address itself + * @param port the port number + * @throws IllegalArgumentException if the port parameter is outside the + * range of valid port values, or if the hostname parmeter is null. + */ + public TransportAddress(InetAddress address, int port) + { + socketAddress = new InetSocketAddress(address, port); + transport = Transport.UDP; + } + + /** + * Creates an address instance from the localhost amd a port number. + *
+ * Addresses created with this constructor should be used cautiously as + * they won't be trated as equal to address created from the localhost + * address even though the represent the same thing. In other words - use + * this constructor only if you're not going to compare the resulting + * instance with other addresses. + * + * @param port the port number + * @throws IllegalArgumentException if the port parameter is outside the + * range of valid port values, or if the hostname parmeter is null. + */ + public TransportAddress(int port) + { + socketAddress = new InetSocketAddress(port); + transport = Transport.UDP; + } + + + /** + * Returns the raw IP address of this Address object. The result is in + * network byte order: the highest order byte of the address is in + * getAddress()[0]. + * @return the raw IP address of this object. + */ + public byte[] getAddressBytes() + { + return (socketAddress == null + ?null + :socketAddress.getAddress().getAddress()); + } + + /** + * Returns the port number or 0 if the addres has not been initialized. + * @return the port number. + */ + public int getPort() + { + return (socketAddress == null + ? 0 + : socketAddress.getPort()); + } + + /** + * Returns the encapsulated InetSocketAddress instance. + * @return the encapsulated InetSocketAddress instance. + */ + public InetSocketAddress getSocketAddress() + { + return socketAddress; + } + + /** + * Constructs a string representation of this InetSocketAddress. This String + * is constructed by calling toString() on the InetAddress and concatenating + * the port number (with a colon). If the address is unresolved then the + * part before the colon will only contain the hostname. + * + * @return a string representation of this object. + */ + public String toString() + { + return socketAddress.toString() + " transport="+getTransport(); + } + + /** + * Compares this object against the specified object. The result is true if + * and only if the argument is not null and it represents the same address + * as this object. + *
+ * Two instances of InetSocketAddress represent the same address if both the + * InetAddresses (or hostnames if it is unresolved) and port numbers are + * equal. + * + * If both addresses are unresolved, then the hostname & the port number are + * compared. + * @param obj the object to compare against. + * @return true if the objects are the same; false otherwise. + */ + public boolean equals(Object obj) + { + if(!(obj instanceof TransportAddress)) + return false; + + TransportAddress target = (TransportAddress)obj; + if( target.socketAddress == null + && socketAddress ==null) + return true; + + return socketAddress.equals(target.getSocketAddress()); + } + + /** + * Returns the host address. + * + * @return a String part of the address + */ + public String getHostAddress() + { + InetAddress addr = socketAddress.getAddress(); + + String addressStr = socketAddress.getAddress().getHostAddress(); + + if(addr instanceof Inet6Address) + addressStr = NetworkUtils.stripScopeID(addressStr); + + return addressStr; + } + + /** + * Returns the InetAddress encapsulated by this + * TransportAddress. + * + * @return the InetAddress encapsulated by this + * TransportAddress. + */ + public InetAddress getInetAddress() + { + return socketAddress.getAddress(); + } + + /** + * The transport that this transport address is suggesting. + * + * @return one of the transport strings (UDP/TCP/...) defined as contants + * in this class. + */ + public Transport getTransport() + { + return transport; + } +} diff --git a/src/org/ice4j/attribute/AddressAttribute.java b/src/org/ice4j/attribute/AddressAttribute.java new file mode 100644 index 0000000..08432dd --- /dev/null +++ b/src/org/ice4j/attribute/AddressAttribute.java @@ -0,0 +1,301 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.Arrays; +import java.net.*; + +import org.ice4j.*; + +/** + * This class is used to represent Stun attributes that contain an address. Such + * attributes are: + * + * MAPPED-ADDRESSOrganisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ +abstract class AddressAttribute extends Attribute +{ + static final byte ADDRESS_FAMILY_IPV4 = 0x01; + static final byte ADDRESS_FAMILY_IPV6 = 0x02; + + /** + * The address represented by this message; + */ + protected TransportAddress address = null; + + /** + * The length of the data contained by this attribute in the case of an + * IPv6 address. + */ + private static final char DATA_LENGTH_FOR_IPV6 = 20; + + /** + * The length of the data contained by this attribute in the case of an + * IPv4 address. + */ + private static final char DATA_LENGTH_FOR_IPV4 = 8; + + /** + * Constructs an address attribute with the specified type. + * + * @param attributeType the type of the address attribute. + */ + AddressAttribute(char attributeType) + { + super(attributeType); + } + /** + * Verifies that type is a valid address attribute type. + * @param type the type to test + * @return true if the type is a valid address attribute type and false + * otherwise + */ + private boolean isTypeValid(char type) + { + return (type == MAPPED_ADDRESS || type == RESPONSE_ADDRESS + || type == SOURCE_ADDRESS || type == CHANGED_ADDRESS + || type == REFLECTED_FROM || type == XOR_MAPPED_ADDRESS + || type == ALTERNATE_SERVER || type == XOR_PEER_ADDRESS + || type == XOR_RELAYED_ADDRESS); + } + + /** + * Sets it as this attribute's type. + * + * @param type the new type of the attribute. + */ + protected void setAttributeType(char type) + { + if (!isTypeValid(type)) + throw new IllegalArgumentException(((int)type) + "is not a valid address attribute!"); + + super.setAttributeType(type); + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + switch(getAttributeType()) + { + case MAPPED_ADDRESS: return MappedAddressAttribute.NAME; + case RESPONSE_ADDRESS: return ResponseAddressAttribute.NAME; + case SOURCE_ADDRESS: return SourceAddressAttribute.NAME; + case CHANGED_ADDRESS: return ChangedAddressAttribute.NAME; + case REFLECTED_FROM: return ReflectedFromAttribute.NAME; + case XOR_MAPPED_ADDRESS: return XorMappedAddressAttribute.NAME; + case ALTERNATE_SERVER: return AlternateServerAttribute.NAME; + case XOR_PEER_ADDRESS: return XorPeerAddressAttribute.NAME; + case XOR_RELAYED_ADDRESS:return XorRelayedAddressAttribute.NAME; + } + + return "UNKNOWN ATTRIBUTE"; + } + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof AddressAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + AddressAttribute att = (AddressAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + //compare data + || att.getFamily() != getFamily() + || (att.getAddress() != null + && !address.equals(att.getAddress())) + ) + return false; + + //addresses + if( att.getAddress() == null && getAddress() == null) + return true; + + return true; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value (8 bytes). + */ + public char getDataLength() + { + if (getFamily() == ADDRESS_FAMILY_IPV6) + return DATA_LENGTH_FOR_IPV6; + else + return DATA_LENGTH_FOR_IPV4; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + if (!isTypeValid(type)) + throw new IllegalStateException(((int)type) + "is not a valid address attribute!"); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength()]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + //Not used + binValue[4] = 0x00; + //Family + binValue[5] = getFamily(); + //port + binValue[6] = (byte)(getPort()>>8); + binValue[7] = (byte)(getPort()&0x00FF); + + //address + if(getFamily() == ADDRESS_FAMILY_IPV6){ + System.arraycopy(getAddressBytes(), 0, binValue, 8, 16); + } + else{ + System.arraycopy(getAddressBytes(), 0, binValue, 8, 4); + } + + return binValue; + } + + /** + * Sets address to be the address transported by this attribute. + * @param address that this attribute should encapsulate. + */ + public void setAddress(TransportAddress address) + { + this.address = address; + } + + /** + * Returns the address encapsulated by this attribute. + * @return the address encapsulated by this attribute. + */ + public TransportAddress getAddress() + { + return address; + } + + public byte[] getAddressBytes() + { + return address.getAddressBytes(); + } + + /** + * Returns the family that the this.address belongs to. + * @return the family that the this.address belongs to. + */ + public byte getFamily() + { + if ( address.getSocketAddress().getAddress() instanceof Inet6Address ) + return ADDRESS_FAMILY_IPV6; + else + return ADDRESS_FAMILY_IPV4; + + } + + /** + * Returns the port associated with the address contained by the attribute. + * @return the port associated with the address contained by the attribute. + */ + public int getPort() + { + return address.getPort(); + } + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) + throws StunException + { + //skip through padding + offset ++; + + //get family + byte family = attributeValue[offset++]; + + //port + char port = ((char)((attributeValue[offset++] << 8 ) | (attributeValue[offset++]&0xFF) )); + + //address + byte address[] = null; + if(family == ADDRESS_FAMILY_IPV6){ + address = new byte[16]; + } + else{ + //ipv4 + address = new byte[4]; + } + + System.arraycopy(attributeValue, offset, address, 0, address.length); + setAddress(new TransportAddress(address, port)); + + } + +} diff --git a/src/org/ice4j/attribute/AlternateServerAttribute.java b/src/org/ice4j/attribute/AlternateServerAttribute.java new file mode 100644 index 0000000..6cb8ed8 --- /dev/null +++ b/src/org/ice4j/attribute/AlternateServerAttribute.java @@ -0,0 +1,53 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +/** + * The ALTERNATE-SERVER attribute indicates the IP address and + * port of an alternate server the client could use. For example, + * alternate servers may contains special capabilities. + * + * It consists of an eight bit address family, and a sixteen bit + * port, followed by a fixed length value representing the IP address. + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * |x x x x x x x x| Family | Port | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Address | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + * The port is a network byte ordered representation of the mapped port. + * The address family is always 0x01, corresponding to IPv4. The first + * 8 bits of the ALTERNATE-SERVER are ignored, for the purposes of + * aligning parameters on natural boundaries. The IPv4 address is 32 + * bits. + * + *Copyright: Copyright (c) 2008
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Sebastien Vincent + * @version 0.1 + */ + +public class AlternateServerAttribute extends AddressAttribute +{ + /** + * Attribute name. + */ + public static final String NAME = "ALTERNATE-SERVER"; + + /** + * Constructor. + */ + AlternateServerAttribute() + { + super(ALTERNATE_SERVER); + } +} + diff --git a/src/org/ice4j/attribute/Attribute.java b/src/org/ice4j/attribute/Attribute.java new file mode 100644 index 0000000..d29cabf --- /dev/null +++ b/src/org/ice4j/attribute/Attribute.java @@ -0,0 +1,191 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * After the header are 0 or more attributes. Each attribute is TLV + * encoded, with a 16 bit type, 16 bit length, and variable value: + * + * 0 1 2 3Copyright: Copyright (c) 2003-2008
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @author Sebastien Vincent + * @author Namal Senarathne + * @version 0.1 + */ +public abstract class Attribute +{ + /* STUN attributes */ + public static final char MAPPED_ADDRESS = 0x0001; + public static final char RESPONSE_ADDRESS = 0x0002; + public static final char CHANGE_REQUEST = 0x0003; + public static final char SOURCE_ADDRESS = 0x0004; + public static final char CHANGED_ADDRESS = 0x0005; + public static final char USERNAME = 0x0006; + public static final char PASSWORD = 0x0007; + public static final char MESSAGE_INTEGRITY = 0x0008; + public static final char ERROR_CODE = 0x0009; + public static final char UNKNOWN_ATTRIBUTES = 0x000a; + public static final char REFLECTED_FROM = 0x000b; + public static final char REALM = 0x0014; + public static final char NONCE = 0x0015; + public static final char XOR_MAPPED_ADDRESS = 0x0020; + public static final char XOR_ONLY = 0x0021; + public static final char SOFTWARE = 0x8022; + public static final char ALTERNATE_SERVER = 0x8023; + public static final char FINGERPRINT = 0x8028; + public static final char UNKNOWN_OPTIONAL_ATTRIBUTE = 0x8000; + + /* TURN attributes */ + public static final char CHANNEL_NUMBER = 0x000c; + public static final char LIFETIME = 0x000d; + public static final char XOR_PEER_ADDRESS = 0x0012; + public static final char DATA = 0x0013; + public static final char XOR_RELAYED_ADDRESS = 0x0016; + public static final char EVEN_PORT = 0x0018; + public static final char REQUESTED_TRANSPORT = 0x0019; + public static final char DONT_FRAGMENT = 0x001a; + public static final char RESERVATION_TOKEN = 0x0022; + + /* ICE attributes */ + public static final char PRIORITY = 0x0024; + public static final char USE_CANDIDATE = 0x0025; + public static final char ICE_CONTROLLED = 0x8029; + public static final char ICE_CONTROLLING = 0x802a; + + /** + * The type of the attribute. + */ + protected char attributeType = 0; + + /** + * The size of an atribute header in bytes = len(TYPE) + len(LENGTH) = 4 + */ + public static final char HEADER_LENGTH = 4; + + /** + * Creates an empty STUN message attribute. + * + * @param attributeType the type of the attribute. + */ + protected Attribute(char attributeType) + { + setAttributeType(attributeType); + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public abstract char getDataLength(); + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public abstract String getName(); + + /** + * Returns the attribute's type. + * @return the type of this attribute. + */ + public char getAttributeType() + { + return attributeType; + } + + /** + * Sets the attribute's type. + * @param type the new type of this attribute + */ + protected void setAttributeType(char type) + { + this.attributeType = type; + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + + public abstract boolean equals(Object obj); + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public abstract byte[] encode(); + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + abstract void decodeAttributeBody(byte[] attributeValue, char offset, char length) + throws StunException; + +} diff --git a/src/org/ice4j/attribute/AttributeDecoder.java b/src/org/ice4j/attribute/AttributeDecoder.java new file mode 100644 index 0000000..f0a9505 --- /dev/null +++ b/src/org/ice4j/attribute/AttributeDecoder.java @@ -0,0 +1,132 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; +import org.ice4j.message.*; + +/** + * The class provides utilities for decoding a binary stream into an Attribute + * class. + * + *Copyright: Copyright (c) 2003-2008
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @author Sebastien Vincent + * @version 0.1 + */ +public class AttributeDecoder +{ + /** + * Decodes the specified binary array and returns the corresponding + * attribute object. + * @param bytes the binary array that should be decoded. + * @param offset the index where the message starts. + * @param length the number of bytes that the message is long. + * @return An object representing the attribute encoded in bytes or null if + * the attribute was not recognized. + * @throws StunException if bytes does is not a valid STUN attribute. + */ + public static Attribute decode(byte bytes[], + char offset, + char length) + throws StunException + { + if(bytes == null || bytes.length < Attribute.HEADER_LENGTH) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + "Could not decode the specified binary array."); + + //Discover attribute type + char attributeType = (char)((bytes[offset]<<8)|bytes[offset + 1]); + char attributeLength = (char)((bytes[offset + 2]<<8)|bytes[offset + 3]); + + if((attributeLength % 4) > 0) + { + attributeLength += (4 - (attributeLength % 4)); + } + + if(attributeLength > bytes.length - offset ) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + "The indicated attribute length ("+attributeLength+") " + +"does not match the length of the passed binary array"); + + Attribute decodedAttribute = null; + + switch(attributeType) + { + /* STUN attributes */ + case Attribute.CHANGE_REQUEST: + decodedAttribute = new ChangeRequestAttribute(); break; + case Attribute.CHANGED_ADDRESS: + decodedAttribute = new ChangedAddressAttribute(); break; + case Attribute.MAPPED_ADDRESS: + decodedAttribute = new MappedAddressAttribute(); break; + case Attribute.ERROR_CODE: + decodedAttribute = new ErrorCodeAttribute(); break; + case Attribute.MESSAGE_INTEGRITY: + throw new UnsupportedOperationException( + "The MESSAGE-INTEGRITY Attribute is not yet implemented."); + case Attribute.PASSWORD: + throw new UnsupportedOperationException( + "The PASSWORD Attribute is not yet implemented."); + case Attribute.REFLECTED_FROM: + decodedAttribute = new ReflectedFromAttribute(); break; + case Attribute.RESPONSE_ADDRESS: + decodedAttribute = new ResponseAddressAttribute(); break; + case Attribute.SOURCE_ADDRESS: + decodedAttribute = new SourceAddressAttribute(); break; + case Attribute.UNKNOWN_ATTRIBUTES: + decodedAttribute = new UnknownAttributesAttribute(); break; + case Attribute.XOR_MAPPED_ADDRESS: + decodedAttribute = new XorMappedAddressAttribute(); break; + case Attribute.XOR_ONLY: + decodedAttribute = new XorOnlyAttribute(); break; + case Attribute.SOFTWARE: + decodedAttribute = new SoftwareAttribute(); break; + case Attribute.USERNAME: + decodedAttribute = new UsernameAttribute(); break; + case Attribute.REALM: + decodedAttribute = new RealmAttribute(); break; + case Attribute.NONCE: + decodedAttribute = new NonceAttribute(); break; + case Attribute.FINGERPRINT: + decodedAttribute = new FingerprintAttribute(); break; + case Attribute.ALTERNATE_SERVER: + decodedAttribute = new AlternateServerAttribute(); break; + case Attribute.CHANNEL_NUMBER: + decodedAttribute = new ChannelNumberAttribute(); break; + case Attribute.LIFETIME: + decodedAttribute = new LifetimeAttribute(); break; + case Attribute.XOR_PEER_ADDRESS: + decodedAttribute = new XorPeerAddressAttribute(); break; + case Attribute.DATA: + decodedAttribute = new DataAttribute(); break; + case Attribute.XOR_RELAYED_ADDRESS: + decodedAttribute = new XorRelayedAddressAttribute(); break; + case Attribute.EVEN_PORT: + decodedAttribute = new EvenPortAttribute(); break; + case Attribute.REQUESTED_TRANSPORT: + decodedAttribute = new RequestedTransportAttribute(); break; + case Attribute.DONT_FRAGMENT: + decodedAttribute = new DontFragmentAttribute(); break; + case Attribute.RESERVATION_TOKEN: + decodedAttribute = new ReservationTokenAttribute(); break; + + //According to rfc3489 we should silently ignore unknown attributes. + default: decodedAttribute = new OptionalAttribute(Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE); + break; + } + + decodedAttribute.setAttributeType(attributeType); + + decodedAttribute.decodeAttributeBody(bytes, (char)(Attribute.HEADER_LENGTH + offset), attributeLength); + + return decodedAttribute; + } + +} diff --git a/src/org/ice4j/attribute/AttributeFactory.java b/src/org/ice4j/attribute/AttributeFactory.java new file mode 100644 index 0000000..583c135 --- /dev/null +++ b/src/org/ice4j/attribute/AttributeFactory.java @@ -0,0 +1,518 @@ +/** Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * + * This class provides factory methods to allow an application to create + * STUN / TURN / ICE Attributes from a particular implementation. + * + *Copyright: Copyright (c) 2003-2008
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @author Sebastien Vincent + * @author Namal Senarathne + * @version 0.1 + */ +public class AttributeFactory +{ + private AttributeFactory() + { + } + +//------------------------------------ CHANGE REQUEST -------------------------- + + /** + * Creates a ChangeRequestAttribute with "false" values for the changeIP and + * changePort flags. + * @return the newly created ChangeRequestAttribute. + */ + public static ChangeRequestAttribute + createChangeRequestAttribute() + { + return createChangeRequestAttribute(false, false); + }; + + /** + * Creates a ChangeRequestAttribute with the specified flag values. + * @param changeIP the value of the changeIP flag. + * @param changePort the value of the changePort flag. + * @return the newly created ChangeRequestAttribute. + */ + public static ChangeRequestAttribute + createChangeRequestAttribute(boolean changeIP, + boolean changePort) + { + ChangeRequestAttribute attribute = new ChangeRequestAttribute(); + + attribute.setChangeIpFlag(changeIP); + attribute.setChangePortFlag(changePort); + + return attribute; + }; + +//------------------------------------ CHANGED ADDRESS ------------------------- + + /** + * Creates a changedAddressAttribute of the specified type and with the + * specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static ChangedAddressAttribute + createChangedAddressAttribute(TransportAddress address) + { + ChangedAddressAttribute attribute= new ChangedAddressAttribute(); + + attribute.setAddress(address); + + return attribute; + + }; + +//------------------------------------ ERROR CODE ------------------------------ + /** + * Creates an ErrorCodeAttribute with the specified error class and number + * and a default reason phrase. + * @param errorClass a valid error class. + * @param errorNumber a valid error number. + * @return the newly created attribute. + * @throws StunException if the error class or number have invalid values + * according to rfc3489. + */ + public static ErrorCodeAttribute createErrorCodeAttribute( + byte errorClass, + byte errorNumber + ) + throws StunException + { + return createErrorCodeAttribute(errorClass, errorNumber, null); + }; + + /** + * Creates an ErrorCodeAttribute with the specified error class, number and + * reason phrase. + * @param errorClass a valid error class. + * @param errorNumber a valid error number. + * @param reasonPhrase a human readable reason phrase. A null reason phrase + * would be replaced (if possible) by a default one + * as defined byte the rfc3489. + * @return the newly created attribute. + * @throws StunException if the error class or number have invalid values + * according to rfc3489. + */ + public static ErrorCodeAttribute createErrorCodeAttribute( + byte errorClass, + byte errorNumber, + String reasonPhrase + ) + throws StunException + { + ErrorCodeAttribute attribute = new ErrorCodeAttribute(); + + attribute.setErrorClass(errorClass); + attribute.setErrorNumber(errorNumber); + + attribute.setReasonPhrase(reasonPhrase==null? + ErrorCodeAttribute.getDefaultReasonPhrase(attribute.getErrorCode()) + :reasonPhrase); + + return attribute; + }; + + /** + * Creates an ErrorCodeAttribute with the specified error code and a default + * reason phrase. + * @param errorCode a valid error code. + * @return the newly created attribute. + * @throws StunException if errorCode is not a valid error code as defined + * by rfc3489 + */ + public static ErrorCodeAttribute createErrorCodeAttribute(char errorCode) + throws StunException + { + return createErrorCodeAttribute(errorCode, null); + }; + + /** + * Creates an ErrorCodeAttribute with the specified error code and reason + * phrase. + * @param errorCode a valid error code. + * @param reasonPhrase a human readable reason phrase. A null reason phrase + * would be replaced (if possible) by a default one + * as defined byte the rfc3489. + + * @return the newly created attribute. + * @throws StunException if errorCode is not a valid error code as defined + * by rfc3489 + */ + public static ErrorCodeAttribute createErrorCodeAttribute( + char errorCode, + String reasonPhrase) + throws StunException + { + ErrorCodeAttribute attribute = new ErrorCodeAttribute(); + + attribute.setErrorCode(errorCode); + attribute.setReasonPhrase(reasonPhrase==null? + ErrorCodeAttribute.getDefaultReasonPhrase(attribute.getErrorCode()) + :reasonPhrase); + + + return attribute; + }; + +//------------------------------------ MAPPED ADDRESS -------------------------- + + /** + * Creates a MappedAddressAttribute of the specified type and with the + * specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static MappedAddressAttribute createMappedAddressAttribute( + TransportAddress address) + { + MappedAddressAttribute attribute = new MappedAddressAttribute(); + + attribute.setAddress(address); + + return attribute; + + }; + +//------------------------------------ REFLECTED FROM -------------------------- + + /** + * Creates a ReflectedFromAddressAttribute of the specified type and with + * the specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static ReflectedFromAttribute createReflectedFromAttribute( + TransportAddress address) + { + ReflectedFromAttribute attribute = new ReflectedFromAttribute(); + + attribute.setAddress(address); + + return attribute; + + }; + +//------------------------------------ RESPONSE ADRESS ------------------------- + /** + * Creates a ResponseFromAddressAttribute of the specified type and with + * the specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static ResponseAddressAttribute createResponseAddressAttribute( + TransportAddress address) + { + ResponseAddressAttribute attribute = new ResponseAddressAttribute(); + + attribute.setAddress(address); + + return attribute; + + }; + +//------------------------------------ SOURCE ADDRESS -------------------------- + /** + * Creates a SourceFromAddressAttribute of the specified type and with + * the specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static SourceAddressAttribute createSourceAddressAttribute( + TransportAddress address) + { + SourceAddressAttribute attribute = new SourceAddressAttribute(); + + attribute.setAddress(address); + + return attribute; + + }; + +//------------------------------------ UNKNOWN ATTRIBUTES ---------------------- + /** + * Creates an empty UnknownAttributesAttribute. + * @return the newly created UnknownAttributesAttribute + */ + public static UnknownAttributesAttribute createUnknownAttributesAttribute() + { + UnknownAttributesAttribute attribute = new UnknownAttributesAttribute(); + + return attribute; + }; + +/* ------------------------------------ XOR-RELAYED-ADRESS attribute ------------------------ */ + /** + * Creates a XorRelayedAddressAttribute of the specified type and with + * the specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static XorRelayedAddressAttribute createXorRelayedAddressAttribute(TransportAddress address) + { + XorRelayedAddressAttribute attribute = new XorRelayedAddressAttribute(); + + attribute.setAddress(address); + return attribute; + } + +/* ------------------------------------ XOR-PEER-ADRESS attribute ------------------------ */ + /** + * Creates a XorPeerAddressAttribute of the specified type and with + * the specified address and port + * @param address the address value of the address attribute + * @return the newly created address attribute. + */ + public static XorPeerAddressAttribute createXorPeerAddressAttribute(TransportAddress address) + { + XorPeerAddressAttribute attribute = new XorPeerAddressAttribute(); + + attribute.setAddress(address); + return attribute; + } + +/* --------------------------------- USERNAME attribute ----------------------------- */ + /** + * Create a UsernameAttribute. + * @param username username value + * @return newly created UsernameAttribute + */ + public static UsernameAttribute createUsernameAttribute(byte username[]) + { + UsernameAttribute attribute = new UsernameAttribute(); + + attribute.setUsername(username); + return attribute; + } + +/* --------------------------------- CHANNEL-NUMBER attribute ----------------------------- */ + /** + * Create a ChannelNumberAttribute. + * @param channelNumber channel number + * @return newly created ChannelNumberAttribute + */ + public static ChannelNumberAttribute createChannelNumberAttribute(char channelNumber) + { + ChannelNumberAttribute attribute = new ChannelNumberAttribute(); + + attribute.setChannelNumber(channelNumber); + return attribute; + } + +/* --------------------------------- REALM attribute ----------------------------- */ + /** + * Create a RealmAttribute. + * @param realm realm value + * @return newly created RealmAttribute + */ + public static RealmAttribute createRealmAttribute(byte realm[]) + { + RealmAttribute attribute = new RealmAttribute(); + + attribute.setRealm(realm); + return attribute; + } + +/* --------------------------------- NONCE attribute ----------------------------- */ + /** + * Create a NonceAttribute. + * @param nonce nonce value + * @return newly created NonceAttribute + */ + public static NonceAttribute createNonceAttribute(byte nonce[]) + { + NonceAttribute attribute = new NonceAttribute(); + + attribute.setNonce(nonce); + return attribute; + } + +/* --------------------------------- SOFTWARE attribute ----------------------------- */ + /** + * Create a SoftwareAttribute. + * @param software software value + * @return newly created SoftwareAttribute + */ + public static SoftwareAttribute createSoftwareAttribute(byte software[]) + { + SoftwareAttribute attribute = new SoftwareAttribute(); + + attribute.setSoftware(software); + return attribute; + } + + +/* --------------------------------- EVEN-PORT attribute ---------------- */ + /** + * Create a EventAttribute. + * @param rFlag R flag + * @return the newly created EventPortAttribute + */ + public static EvenPortAttribute createEvenPortAttribute(boolean rFlag) + { + EvenPortAttribute attribute = new EvenPortAttribute(); + + attribute.setRFlag(rFlag); + return attribute; + } + +/* --------------------------------- LIFETIME attribute --------------------------- */ + /** + * Create a LifetimeAttribute. + * @param lifetime lifetime value + * @return newly created LifetimeAttribute + */ + public static LifetimeAttribute createLifetimeAttribute(int lifetime) + { + LifetimeAttribute attribute = new LifetimeAttribute(); + + attribute.setLifetime(lifetime); + return attribute; + } + +/* --------------------------------- REQUESTED-TRANSPORT attribute ---------------- */ + + /** + * Create a RequestedTransportAttribute. + * @param protocol transport protocol requested + * @return newly created RequestedTransportAttribute + */ + public static RequestedTransportAttribute createRequestedTransportAttribute(byte protocol) + { + RequestedTransportAttribute attribute = new RequestedTransportAttribute(); + + attribute.setRequestedTransport(protocol); + return attribute; + } + +/* -------------------------------- RESERVATION-TOKEN attribute -------------------- */ + /** + * Create a ReservationTokenAttribute. + * @param token the token + * @return newly created RequestedTransportAttribute + */ + public static ReservationTokenAttribute createReservationTokenAttribute(byte token[]) + { + ReservationTokenAttribute attribute = new ReservationTokenAttribute(); + + attribute.setReservationToken(token); + return attribute; + } + +/* -------------------------------- DATA attribute --------------------------------- */ + /** + * Create a DataAtttribute. + * @param data the data + * @return newly created DataAttribute + */ + public static DataAttribute createDataAttribute(byte data[]) + { + DataAttribute attribute = new DataAttribute(); + + attribute.setData(data); + return attribute; + } + +//-------------------------------- ICE-CONTROLLED ATTRIBUTE ----------------------- + /** + * Creates an IceControlledAttribute object with the specified tie-breaker value + * + * @param tieBreaker the tie-breaker value to be used + * @return the created IceControlledAttribute + * @throws StunException if the value in tie-breaker is not valid + */ + public static IceControlledAttribute createIceControlledAttribute(long tieBreaker) + throws StunException + { + // generating the network ordered byte stream of the tieBreaker long variable + byte[] tieBreakerBytes = new byte[8]; + tieBreakerBytes[0] = (byte)(tieBreaker>>56); + tieBreakerBytes[1] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48); + tieBreakerBytes[2] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40); + tieBreakerBytes[3] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32); + tieBreakerBytes[4] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24); + tieBreakerBytes[5] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16); + tieBreakerBytes[6] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8); + tieBreakerBytes[7] = (byte)((tieBreaker & 0x00000000000000FFL)); + + IceControlledAttribute attribute = new IceControlledAttribute(); + attribute.setTieBreaker(tieBreakerBytes); + + return attribute; + } + + //---------------------------------- PRIORITY ATTRIBUTE ----------------------- + + /** + * Creates a Priority attribute with the specified priority value + * + * @param priority the priority value + * @return the created PriorityAttribute + * @throws StunException if priority < 0 or priority > (2^31 - 1) + */ + public static PriorityAttribute createPriorityAttribute(long priority) + throws StunException + { + PriorityAttribute attribute = new PriorityAttribute(); + + attribute.setPriority(priority); + + return attribute; + } + +//--------------------------------- USE-CANDIDATE ATTRIBUTE --------------------- + + /** + * Creates a UseCandidateAttribute + * + * @return the created UseCandidateAttribute + */ + public static UseCandidateAttribute createUseCandidateAttribute() + { + UseCandidateAttribute attribute = new UseCandidateAttribute(); + + return attribute; + } + + /** + * Creates an IceControllingAttribute with the specified tie-breaker value + * + * @param tieBreaker the tie-breaker value to be used + * + * @return the created IceControllingAttribute + * @throws StunException of tie-breaker value is not valid + */ + public static IceControllingAttribute createIceControllingAttribute(long tieBreaker) + throws StunException + { + // generating the network ordered byte stream of the tieBreaker long variable + byte[] tieBreakerBytes = new byte[8]; + tieBreakerBytes[0] = (byte)(tieBreaker>>56); + tieBreakerBytes[1] = (byte)((tieBreaker & 0x00FF000000000000L) >> 48); + tieBreakerBytes[2] = (byte)((tieBreaker & 0x0000FF0000000000L) >> 40); + tieBreakerBytes[3] = (byte)((tieBreaker & 0x000000FF00000000L) >> 32); + tieBreakerBytes[4] = (byte)((tieBreaker & 0x00000000FF000000L) >> 24); + tieBreakerBytes[5] = (byte)((tieBreaker & 0x0000000000FF0000L) >> 16); + tieBreakerBytes[6] = (byte)((tieBreaker & 0x000000000000FF00L) >> 8); + tieBreakerBytes[7] = (byte)((tieBreaker & 0x00000000000000FFL)); + + IceControllingAttribute attribute = new IceControllingAttribute(); + attribute.setTieBreaker(tieBreakerBytes); + + return attribute; + } +} + diff --git a/src/org/ice4j/attribute/ChangeRequestAttribute.java b/src/org/ice4j/attribute/ChangeRequestAttribute.java new file mode 100644 index 0000000..733e1d3 --- /dev/null +++ b/src/org/ice4j/attribute/ChangeRequestAttribute.java @@ -0,0 +1,215 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * This class represents the STUN CHANGE-REQUEST attribute. The CHANGE-REQUEST + * attribute is used by the client to request that the server use a different + * address and/or port when sending the response. The attribute is 32 bits + * long, although only two bits (A and B) are used: + * + * 0 1 2 3Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class ChangeRequestAttribute + extends org.ice4j.attribute.Attribute +{ + /** + * This is the "change IP" flag. If true, it requests the server + * to send the Binding Response with a different IP address than the + * one the Binding Request was received on. + */ + private boolean changeIpFlag = false; + + /** + * This is the "change port" flag. If true, it requests the + * server to send the Binding Response with a different port than the + * one the Binding Request was received on. + */ + private boolean changePortFlag = false; + + /** + * The length of the data contained by this attribute. + */ + public static final char DATA_LENGTH = 4; + + + /** + * Creates an empty ChangeRequestAttribute. + */ + ChangeRequestAttribute() + { + super(CHANGE_REQUEST); + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + public static final String NAME = "CHANGE-REQUEST"; + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof ChangeRequestAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + ChangeRequestAttribute att = (ChangeRequestAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + //compare data + || att.getChangeIpFlag() != getChangeIpFlag() + || att.getChangePortFlag() != getChangePortFlag() + ) + return false; + + return true; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value (8 bytes). + */ + public char getDataLength() + { + return DATA_LENGTH; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH]; + + //Type + binValue[0] = (byte)(getAttributeType()>>8); + binValue[1] = (byte)(getAttributeType()&0x00FF); + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + //Data + binValue[4] = 0x00; + binValue[5] = 0x00; + binValue[6] = 0x00; + binValue[7] = (byte)((getChangeIpFlag()?4:0) + (getChangePortFlag()?2:0)); + + return binValue; + } + + + //========================= set/get methods + /** + * Sets the value of the changeIpFlag. The "change IP" flag, if true, + * requests the server to send the Binding Response with a different IP + * address than the one the Binding Request was received on. + * + * @param changeIP the new value of the changeIpFlag. + */ + public void setChangeIpFlag(boolean changeIP) + { + this.changeIpFlag = changeIP; + } + + /** + * Returns tha value of the changeIpFlag. The "change IP" flag, if true, + * requests the server to send the Binding Response with a different IP + * address than the one the Binding Request was received on. + * + * @return the value of the changeIpFlag. + */ + public boolean getChangeIpFlag() + { + return changeIpFlag; + } + + /** + * Sets the value of the changePortFlag. The "change port" flag. If true, + * requests the server to send the Binding Response with a different port + * than the one the Binding Request was received on. + * + * @param changePort the new value of the changePort flag. + */ + public void setChangePortFlag(boolean changePort) + { + this.changePortFlag = changePort; + } + + /** + * Returns the value of the changePortFlag. The "change port" flag. If true, + * requests the server to send the Binding Response with a different port + * than the one the Binding Request was received on. + * + * @return the value of the changePort flag. + */ + public boolean getChangePortFlag() + { + return changePortFlag; + } + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + offset += 3; // first three bytes of change req att are not used + setChangeIpFlag((attributeValue[offset]&4)>0); + setChangePortFlag((attributeValue[offset] & 0x2)>0); + + } + + +} diff --git a/src/org/ice4j/attribute/ChangedAddressAttribute.java b/src/org/ice4j/attribute/ChangedAddressAttribute.java new file mode 100644 index 0000000..914892b --- /dev/null +++ b/src/org/ice4j/attribute/ChangedAddressAttribute.java @@ -0,0 +1,37 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + + +/** + * The CHANGED-ADDRESS attribute indicates the IP address and port where + * responses would have been sent from if the "change IP" and "change + * port" flags had been set in the CHANGE-REQUEST attribute of the + * Binding Request. The attribute is always present in a Binding + * Response, independent of the value of the flags. Its syntax is + * identical to MAPPED-ADDRESS. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class ChangedAddressAttribute extends AddressAttribute +{ + public static final String NAME = "CHANGED-ADDRESS"; + + /** + * Creates a CHANGED_ADDRESS attribute + */ + public ChangedAddressAttribute() + { + super(CHANGED_ADDRESS); + } + +} diff --git a/src/org/ice4j/attribute/ChannelNumberAttribute.java b/src/org/ice4j/attribute/ChannelNumberAttribute.java new file mode 100644 index 0000000..673815c --- /dev/null +++ b/src/org/ice4j/attribute/ChannelNumberAttribute.java @@ -0,0 +1,152 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.lang.*; + +import org.ice4j.*; + +/** + * The CHANNEL-NUMBER attribute is used to known on which + * channel the TURN client want to send data. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class ChannelNumberAttribute extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "CHANNEL-NUMBER"; + + /** + * The length of the data contained by this attribute. + */ + public static final char DATA_LENGTH = 4; + + /** + * Channel number. + */ + private char channelNumber = 0; + + /** + * Constructor. + */ + ChannelNumberAttribute() + { + super(CHANNEL_NUMBER); + } + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof ChannelNumberAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + ChannelNumberAttribute att = (ChannelNumberAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + /* compare data */ + || att.channelNumber != channelNumber + ) + return false; + + return true; + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value (8 bytes). + */ + public char getDataLength() + { + return DATA_LENGTH; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH]; + + //Type + binValue[0] = (byte)(getAttributeType()>>8); + binValue[1] = (byte)(getAttributeType()&0x00FF); + //Length + binValue[2] = (byte)(getDataLength() >> 8); + binValue[3] = (byte)(getDataLength() & 0x00FF); + //Data + binValue[4] = (byte)((channelNumber >> 8) & 0xff); + binValue[5] = (byte)((channelNumber) & 0xff); + binValue[6] = 0x00; + binValue[7] = 0x00; + + return binValue; + } + + /** + * Sets this attribute's fields according to attributeValue array. + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws StunException + { + if(length != 4) + { + throw new StunException("length invalid"); + } + + channelNumber = ((char)((attributeValue[0] << 8 ) | (attributeValue[1]&0xFF) )); + } + + /** + * Set the channel number. + * @param channelNumber channel number + */ + public void setChannelNumber(char channelNumber) + { + this.channelNumber = channelNumber; + } + + /** + * Get the channel number. + * @return channel number + */ + public char getChannelNumber() + { + return channelNumber; + } +} + diff --git a/src/org/ice4j/attribute/DataAttribute.java b/src/org/ice4j/attribute/DataAttribute.java new file mode 100644 index 0000000..4c56fae --- /dev/null +++ b/src/org/ice4j/attribute/DataAttribute.java @@ -0,0 +1,162 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The DATA attribute contains the data the client wants to relay to the TURN + * server or the TURN server to forward the response data. + * + * The value of DATA is variable length. Its length MUST be a + * multiple of 4 (measured in bytes) in order to guarantee alignment of + * attributes on word boundaries. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class DataAttribute + extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "DATA"; + + /** + * Data value. + */ + private byte data[] = null; + + /** + * Constructor. + */ + protected DataAttribute () + { + super(DATA); + } + + /** + * Copies the value of the data attribute from the specified + * attributeValue. + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attributeValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + data = new byte[length]; + System.arraycopy(attributeValue, offset, data, 0, length); + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + (getDataLength() % 4)]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + //data + System.arraycopy(data, 0, binValue, 4, getDataLength()); + + return binValue; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)data.length; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns a (cloned) byte array containg the data value of the data + * attribute. + * @return the binary array containing the data. + */ + public byte[] getData() + { + if (data == null) + return null; + + byte[] copy = new byte[data.length]; + System.arraycopy(data, 0, copy, 0, data.length); + return data; + } + + /** + * Copies the specified binary array into the the data value of the data + * attribute. + * + * @param data the binary array containing the data. + */ + public void setData(byte[] data) + { + if (data == null) + { + this.data = null; + return; + } + + this.data = new byte[data.length]; + System.arraycopy(data, 0, this.data, 0, data.length); + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + + public boolean equals(Object obj) + { + if (! (obj instanceof DataAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + DataAttribute att = (DataAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || !Arrays.equals( att.data, data)) + return false; + + return true; + } +} + diff --git a/src/org/ice4j/attribute/DontFragmentAttribute.java b/src/org/ice4j/attribute/DontFragmentAttribute.java new file mode 100644 index 0000000..8b4115f --- /dev/null +++ b/src/org/ice4j/attribute/DontFragmentAttribute.java @@ -0,0 +1,115 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.lang.*; + +import org.ice4j.*; + +/** + * The DONT-FRAGMENT attribute is used to inform TURN + * server (if it supports this attribute) that it should set DF bit to 1 + * in IPv4 headers when relaying client data. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class DontFragmentAttribute extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "DONT-FRAGMENT"; + + /** + * The length of the data contained by this attribute. + */ + public static final char DATA_LENGTH = 0; + + /** + * Constructor. + */ + DontFragmentAttribute() + { + super(DONT_FRAGMENT); + } + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof DontFragmentAttribute) + || obj == null) + { + return false; + } + + return true; + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value (8 bytes). + */ + public char getDataLength() + { + return DATA_LENGTH; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + /* there is no data */ + byte binValue[] = new byte[HEADER_LENGTH]; + + //Type + binValue[0] = (byte)(getAttributeType()>>8); + binValue[1] = (byte)(getAttributeType()&0x00FF); + //Length + binValue[2] = (byte)(getDataLength() >> 8); + binValue[3] = (byte)(getDataLength() & 0x00FF); + + return binValue; + } + + /** + * Sets this attribute's fields according to attributeValue array. + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws StunException + { + if(length != 0) + { + throw new StunException("length invalid"); + } + } +} + diff --git a/src/org/ice4j/attribute/ErrorCodeAttribute.java b/src/org/ice4j/attribute/ErrorCodeAttribute.java new file mode 100644 index 0000000..8cc3188 --- /dev/null +++ b/src/org/ice4j/attribute/ErrorCodeAttribute.java @@ -0,0 +1,398 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.Hashtable; + +import org.ice4j.*; + +/** + * The ERROR-CODE attribute is present in the Binding Error Response and + * Shared Secret Error Response. It is a numeric value in the range of + * 100 to 699 plus a textual reason phrase encoded in UTF-8, and is + * consistent in its code assignments and semantics with SIP [10] and + * HTTP [15]. The reason phrase is meant for user consumption, and can + * be anything appropriate for the response code. The lengths of the + * reason phrases MUST be a multiple of 4 (measured in bytes). This can + * be accomplished by added spaces to the end of the text, if necessary. + * Recommended reason phrases for the defined response codes are + * presented below. + * + * To facilitate processing, the class of the error code (the hundreds + * digit) is encoded separately from the rest of the code. + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | 0 |Class| Number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Reason Phrase (variable) .. + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + * The class represents the hundreds digit of the response code. The + * value MUST be between 1 and 6. The number represents the response + * code modulo 100, and its value MUST be between 0 and 99. + * + * The following response codes, along with their recommended reason + * phrases (in brackets) are defined at this time: + * + * 400 (Bad Request): The request was malformed. The client should not + * retry the request without modification from the previous + * attempt. + * + * 401 (Unauthorized): The Binding Request did not contain a MESSAGE- + * INTEGRITY attribute. + * + * 420 (Unknown Attribute): The server did not understand a mandatory + * attribute in the request. + * + * 430 (Stale Credentials): The Binding Request did contain a MESSAGE- + * INTEGRITY attribute, but it used a shared secret that has + * expired. The client should obtain a new shared secret and try + * again. + * + * 431 (Integrity Check Failure): The Binding Request contained a + * MESSAGE-INTEGRITY attribute, but the HMAC failed verification. + * This could be a sign of a potential attack, or client + * implementation error. + * + * 432 (Missing Username): The Binding Request contained a MESSAGE- + * INTEGRITY attribute, but not a USERNAME attribute. Both must be + * present for integrity checks. + * + * 433 (Use TLS): The Shared Secret request has to be sent over TLS, but + * was not received over TLS. + * + * 500 (Server Error): The server has suffered a temporary error. The + * client should try again. + * + * 600 (Global Failure:) The server is refusing to fulfill the request. + * The client should not retry. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ +public class ErrorCodeAttribute extends Attribute +{ + // Common error codes + public static final char BAD_REQUEST = 400; + public static final char UNAUTHORIZED = 401; + public static final char UNKNOWN_ATTRIBUTE = 420; + public static final char STALE_CREDENTIALS = 430; + public static final char INTEGRITY_CHECK_FAILURE = 431; + public static final char MISSING_USERNAME = 432; + public static final char USE_TLS = 433; + public static final char SERVER_ERROR = 500; + public static final char GLOBAL_FAILURE = 600; + + + /** + * The class represents the hundreds digit of the response code. The + * value MUST be between 1 and 6. + */ + private byte errorClass = 0; + + /** + * The number represents the response + * code modulo 100, and its value MUST be between 0 and 99. + */ + private byte errorNumber = 0; + + /** + * The reason phrase is meant for user consumption, and can + * be anything appropriate for the response code. The lengths of the + * reason phrases MUST be a multiple of 4 (measured in bytes). + */ + private String reasonPhrase = null; + + /** + * Constructs a new ERROR-CODE attribute + */ + ErrorCodeAttribute() + { + super(ERROR_CODE); + } + + /** + * A convenience method that sets error class and number according to the + * specified errorCode.The class represents the hundreds digit of the error code. + * The value MUST be between 1 and 6. The number represents the response + * code modulo 100, and its value MUST be between 0 and 99. + * + * @param errorCode the errorCode that this class encapsulates. + * @throws StunException if errorCode is not a valid error code. + */ + public void setErrorCode(char errorCode) + throws StunException + { + setErrorClass((byte)(errorCode/100)); + setErrorNumber((byte)(errorCode % 100)); + } + + /** + * A convenience method that constructs an error code from this Attribute's + * class and number. + * @return the code of the error this attribute represents. + */ + public char getErrorCode() + { + return (char)(getErrorClass()*100 + getErrorNumber()); + } + + + /** + * Sets this attribute's error number. + * @param errorNumber the error number to assign this attribute. + * @throws StunException if errorNumber is not a valid error number. + */ + public void setErrorNumber(byte errorNumber) + throws StunException + { + if(errorNumber < 0 || errorNumber > 99) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + errorNumber + " is not a valid error number!"); + this.errorNumber = errorNumber; + } + + /** + * Returns this attribute's error number. + * @return this attribute's error number. + */ + public byte getErrorNumber() + { + return this.errorNumber; + } + + /** + * Sets this error's error class. + * @param errorClass this error's error class. + * @throws StunException if errorClass is not a valid error class. + */ + public void setErrorClass(byte errorClass) + throws StunException + { + if(errorClass < 0 || errorClass > 99) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + errorClass + " is not a valid error number!"); + this.errorClass = errorClass; + } + + /** + * Returns this error's error class. + * @return this error's error class. + */ + public byte getErrorClass() + { + return errorClass; + } + + + /** + * Returns a default reason phrase corresponding to the specified error + * code, as described by rfc 3489. + * @param errorCode the code of the error that the reason phrase must + * describe. + * @return a default reason phrase corresponding to the specified error + * code, as described by rfc 3489. + */ + public static String getDefaultReasonPhrase(char errorCode) + { + switch(errorCode) + { + case 400: return "(Bad Request): The request was malformed. The client should not " + +"retry the request without modification from the previous attempt."; + case 401: return "(Unauthorized): The Binding Request did not contain a MESSAGE-" + +"INTEGRITY attribute."; + case 420: return "(Unknown Attribute): The server did not understand a mandatory " + +"attribute in the request."; + case 430: return "(Stale Credentials): The Binding Request did contain a MESSAGE-" + +"INTEGRITY attribute, but it used a shared secret that has " + +"expired. The client should obtain a new shared secret and try" + +"again"; + case 431: return "(Integrity Check Failure): The Binding Request contained a " + +"MESSAGE-INTEGRITY attribute, but the HMAC failed verification. " + +"This could be a sign of a potential attack, or client " + +"implementation error."; + case 432: return "(Missing Username): The Binding Request contained a MESSAGE-" + +"INTEGRITY attribute, but not a USERNAME attribute. Both must be" + +"present for integrity checks."; + case 433: return "(Use TLS): The Shared Secret request has to be sent over TLS, but" + +"was not received over TLS."; + case 500: return "(Server Error): The server has suffered a temporary error. The" + +"client should try again."; + case 600: return "(Global Failure:) The server is refusing to fulfill the request." + +"The client should not retry."; + + default: return "Unknown Error"; + } + } + + /** + * Set's a reason phrase. The reason phrase is meant for user consumption, + * and can be anything appropriate for the response code. The lengths of + * the reason phrases MUST be a multiple of 4 (measured in bytes). + * + * @param reasonPhrase a reason phrase that describes this error. + */ + public void setReasonPhrase(String reasonPhrase) + { + this.reasonPhrase = reasonPhrase; + } + + /** + * Returns the reason phrase. The reason phrase is meant for user consumption, + * and can be anything appropriate for the response code. The lengths of + * the reason phrases MUST be a multiple of 4 (measured in bytes). + * + * @return reasonPhrase a reason phrase that describes this error. + */ + public String getReasonPhrase() + { + return this.reasonPhrase; + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + public static final String NAME = "ERROR-CODE"; + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public char getDataLength() + { + char len = (char)( 4 //error code numbers + + (char)( + reasonPhrase == null? 0 + :reasonPhrase.length()*2 + )); + + /* + * According to rfc 3489 The length of the + * reason phrases MUST be a multiple of 4 (measured in bytes) + */ + len += 4 - (len%4); + return len; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + byte binValue[] = new byte[HEADER_LENGTH + getDataLength()]; + + //Type + binValue[0] = (byte) (getAttributeType() >> 8); + binValue[1] = (byte) (getAttributeType() & 0x00FF); + //Length + binValue[2] = (byte) (getDataLength() >> 8); + binValue[3] = (byte) (getDataLength() & 0x00FF); + + //Not used + binValue[4] = 0x00; + binValue[5] = 0x00; + + //Error code + binValue[6] = getErrorClass(); + binValue[7] = getErrorNumber(); + + int offset = 8; + char chars[] = reasonPhrase.toCharArray(); + for (int i = 0; i < reasonPhrase.length(); i++, offset += 2) { + binValue[offset] = (byte)(chars[i]>>8); + binValue[offset+1] = (byte)(chars[i] & 0xFF); + } + + //The lengths of the reason phrases MUST be a multiple of 4 (measured + //in bytes) + if( reasonPhrase.length()%4 != 0) + { + binValue[binValue.length - 2] = (byte) ( ( (int) ' ') >> 8); + binValue[binValue.length - 1] = (byte) ( ( (int) ' ') & 0x00FF); + } + + return binValue; + } + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof ErrorCodeAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + ErrorCodeAttribute att = (ErrorCodeAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + //compare data + || att.getErrorClass() != getErrorClass() + || att.getErrorNumber()!= getErrorNumber() + || ( att.getReasonPhrase() != null + && !att.getReasonPhrase().equals(getReasonPhrase())) + ) + return false; + + return true; + } + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + + offset += 2; //skip the 0s + + //Error code + setErrorClass(attributeValue[offset++]); + setErrorNumber(attributeValue[offset++]); + + //Reason Phrase + char reasonPhrase[] = new char[(length-4)/2]; + + for (int i = 0; i < reasonPhrase.length; i++, offset+=2) { + reasonPhrase[i] = + (char)(attributeValue[offset] | attributeValue[offset+1]); + } + setReasonPhrase(new String(reasonPhrase).trim()); + + } + + +} diff --git a/src/org/ice4j/attribute/EvenPortAttribute.java b/src/org/ice4j/attribute/EvenPortAttribute.java new file mode 100644 index 0000000..15233d2 --- /dev/null +++ b/src/org/ice4j/attribute/EvenPortAttribute.java @@ -0,0 +1,156 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.lang.*; + +import org.ice4j.*; + +/** + * The EVEN-PORT attribute is used to ask the TURN + * server to allocate an even port and optionnaly allocate + * the next higher port number. + * + * There are one flag supported :Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class MappedAddressAttribute extends AddressAttribute +{ + public static final String NAME = "MAPPED-ADDRESS"; + + MappedAddressAttribute() + { + super(MAPPED_ADDRESS); + } + +} diff --git a/src/org/ice4j/attribute/NonceAttribute.java b/src/org/ice4j/attribute/NonceAttribute.java new file mode 100644 index 0000000..75f6913 --- /dev/null +++ b/src/org/ice4j/attribute/NonceAttribute.java @@ -0,0 +1,151 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The NONCE attribute is used for authentification. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class NonceAttribute extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "NONCE"; + + /** + * Nonce value. + */ + private byte nonce[] = null; + + /** + * Constructor. + */ + NonceAttribute() + { + super(NONCE); + } + + /** + * Copies the value of the nonce attribute from the specified + * attributeValue. + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attributeValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws StunException + { + nonce = new byte[length]; + System.arraycopy(attributeValue, offset, nonce, 0, length); + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + (getDataLength() % 4)]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + /* nonce */ + System.arraycopy(nonce, 0, binValue, 4, (int)getDataLength()); + + return binValue; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)nonce.length; + } + + /** + * Returns the human readable name of this attribute. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns a (cloned) byte array containg the data value of the nonce + * attribute. + * @return the binary array containing the nonce. + */ + public byte[] getNonce() + { + if (nonce == null) + return null; + + byte[] copy = new byte[nonce.length]; + System.arraycopy(nonce, 0, copy, 0, nonce.length); + return copy; + } + + /** + * Copies the specified binary array into the the data value of the nonce + * attribute. + * @param nonce the binary array containing the nonce. + */ + public void setNonce(byte[] nonce) + { + if (nonce == null) + { + this.nonce = null; + return; + } + + this.nonce = new byte[nonce.length]; + System.arraycopy(nonce, 0, this.nonce, 0, nonce.length); + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof NonceAttribute) || obj == null) + return false; + + if (obj == this) + return true; + + NonceAttribute att = (NonceAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || !Arrays.equals( att.nonce, nonce)) + return false; + + return true; + } +} + diff --git a/src/org/ice4j/attribute/OptionalAttribute.java b/src/org/ice4j/attribute/OptionalAttribute.java new file mode 100644 index 0000000..77adc69 --- /dev/null +++ b/src/org/ice4j/attribute/OptionalAttribute.java @@ -0,0 +1,140 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * This class is used for representing attributes not explicitly supported by + * the stack. Such attributes will generally be kept in binary form and won't be + * subdued to any processing by the stack. One could use this class for both + * dealing with attributes in received messages, and generating messages + * containing attributes not explicitly supported by the stack. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + * + */ +public class OptionalAttribute + extends Attribute +{ + byte[] attributeValue = null; + + protected OptionalAttribute(char attributeType) + { + super(attributeType); + } + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) + throws StunException + { + this.attributeValue = new byte[length]; + System.arraycopy(attributeValue, offset, this.attributeValue, 0, length); + } + + /** + * Returns a binary representation of this attribute. + * + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + + byte binValue[] = new byte[HEADER_LENGTH + attributeValue.length]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + System.arraycopy(attributeValue, 0, + binValue, HEADER_LENGTH, attributeValue.length); + + return binValue; + } + + /** + * Returns the length of this attribute's body. + * + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)attributeValue.length; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return "Unknown Attribute"; + } + + /** + * Returns a reference to the unparsed body of this attribute. + * + * @return a reference to this attribute's unparsed value. + */ + public byte[] getBody() + { + return attributeValue; + } + + /** + * Copies the speicified byte array segment as the body of this attribute. + * + * @param body the body to copy + * @param offset the position to start + * @param length the length to copy + */ + public void setBody(byte[] body, int offset, int length) + { + this.attributeValue = new byte[length]; + System.arraycopy(body, offset, this.attributeValue, 0, length); + } + + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if(obj == null + || !(obj instanceof OptionalAttribute) ) + return false; + + return + (obj == this + || Arrays.equals(((OptionalAttribute)obj). + attributeValue, attributeValue)); + } +} diff --git a/src/org/ice4j/attribute/PriorityAttribute.java b/src/org/ice4j/attribute/PriorityAttribute.java new file mode 100644 index 0000000..ce512a9 --- /dev/null +++ b/src/org/ice4j/attribute/PriorityAttribute.java @@ -0,0 +1,171 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * This class is used to represent the PRIORITY attribute used for ICE processing + * This attribute is not in the original specification of STUN + * It is added as an extension to STUN to be used for ICE implementations + * + * PRIORITY attribute contains a 32 bit priority value + * It is used in stun binding requests sent from ICE-Agents to their + * peers + * + * @author Namal Senarathne + */ +public class PriorityAttribute + extends Attribute +{ + /** + * The length of the Data contained in the Priority Attribute + */ + private static final char DATA_LENGTH_PRIORITY = 4; + + /** + * The priority value specified in the attribute + */ + private long priority = 0; // int is enough to store this value, but long is used, since + // candidate and candidate-pair classes use long to store priority values + + public PriorityAttribute() + { + super(PRIORITY); + } + + /** + * Reconstructs the priority value from the given byte array + * and stores it in the 'long' variable + * + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) + throws StunException + { + + // array used to hold the intermediate long values reconstructed from the + // attributeValue array + long[] values = new long[4]; + + // Reading in the network byte order (Big-Endian) + values[0] = (long)((attributeValue[offset++] & 0xff) << 24); + values[1] = (long)((attributeValue[offset++] & 0xff) << 16); + values[2] = (long)((attributeValue[offset++] & 0xff) << 8); + values[3] = (long)(attributeValue[offset++] & 0xff); + + // reconstructing the priority value + this.priority = values[0] | values[1] | values[2] | values[3]; + } + + /** + * Returns a binary representation of this attribute. + * + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte[] binValue = new byte[HEADER_LENGTH + getDataLength()]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + //Priority + binValue[4] = (byte)((priority & 0xFF000000L) >> 24); + binValue[5] = (byte)((priority & 0x00FF0000L) >> 16); + binValue[6] = (byte)((priority & 0x0000FF00L) >> 8); + binValue[7] = (byte)(priority & 0x000000FFL); + + return binValue; + + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof PriorityAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + PriorityAttribute att = (PriorityAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || (priority != att.priority)) + return false; + + return true; + } + + /** + * Returns the length of this attribute's body. + * + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return DATA_LENGTH_PRIORITY; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return "PRIORITY"; + } + + /** + * Returns the priority specified in the PRIORITY Attribute + * + * @return long specifying the priority + */ + public long getPriority() + { + return priority; + } + + /** + * Sets the priority of the PRIORITY Attribute with the specified value + * + * @param priority the long variable specifying the priority value + * + * @throws StunException throws StunException if indicated priority value is illegal + */ + public void setPriority(long priority) + throws StunException + { + /* Priority must be between 1 and (2^31 - 1) */ + if(priority <= 0 || priority > 0x7FFFFFFFL) + throw new StunException(StunException.ILLEGAL_ARGUMENT, "Priority must be " + + "between 0 and (2**31 - 1)"); + else + this.priority = priority; + } + +} diff --git a/src/org/ice4j/attribute/RealmAttribute.java b/src/org/ice4j/attribute/RealmAttribute.java new file mode 100644 index 0000000..2b5e6bd --- /dev/null +++ b/src/org/ice4j/attribute/RealmAttribute.java @@ -0,0 +1,153 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The REALM attribute contains a text whcih meets the grammar for + * "realm value" as described in RFC3261 but without the double quotes. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class RealmAttribute extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "REALM"; + + /** + * Realm value. + */ + private byte realm[] = null; + + /** + * Constructor. + */ + RealmAttribute() + { + super(REALM); + } + + /** + * Copies the value of the realm attribute from the specified + * attributeValue. + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attributeValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + realm = new byte[length]; + System.arraycopy(attributeValue, offset, realm, 0, length); + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + (getDataLength() % 4)]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + /* realm */ + System.arraycopy(realm, 0, binValue, 4, getDataLength()); + + return binValue; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)realm.length; + } + + /** + * Returns the human readable name of this attribute. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns a (cloned) byte array containg the data value of the realm + * attribute. + * @return the binary array containing the realm. + */ + public byte[] getRealm() + { + if (realm == null) + return null; + + byte[] copy = new byte[realm.length]; + System.arraycopy(realm, 0, copy, 0, realm.length); + return copy; + } + + /** + * Copies the specified binary array into the the data value of the realm + * attribute. + * @param realm the binary array containing the realm. + */ + public void setRealm(byte[] realm) + { + if (realm == null) + { + this.realm = null; + return; + } + + this.realm = new byte[realm.length]; + System.arraycopy(realm, 0, this.realm, 0, realm.length); + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof RealmAttribute) || obj == null) + return false; + + if (obj == this) + return true; + + RealmAttribute att = (RealmAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || !Arrays.equals( att.realm, realm)) + return false; + + return true; + } +} + diff --git a/src/org/ice4j/attribute/ReflectedFromAttribute.java b/src/org/ice4j/attribute/ReflectedFromAttribute.java new file mode 100644 index 0000000..dd1ac83 --- /dev/null +++ b/src/org/ice4j/attribute/ReflectedFromAttribute.java @@ -0,0 +1,39 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +/** + * The REFLECTED-FROM attribute is present only in Binding Responses, + * when the Binding Request contained a RESPONSE-ADDRESS attribute. The + * attribute contains the identity (in terms of IP address) of the + * source where the request came from. Its purpose is to provide + * traceability, so that a STUN server cannot be used as a reflector for + * denial-of-service attacks. + * + * Its syntax is identical to the MAPPED-ADDRESS attribute. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class ReflectedFromAttribute extends AddressAttribute +{ + + public static final String NAME = "REFLECTED-FROM"; + + /** + * Creates a REFLECTED-FROM attribute + */ + public ReflectedFromAttribute() + { + super(REFLECTED_FROM); + } + +} diff --git a/src/org/ice4j/attribute/RequestedTransportAttribute.java b/src/org/ice4j/attribute/RequestedTransportAttribute.java new file mode 100644 index 0000000..b0143b8 --- /dev/null +++ b/src/org/ice4j/attribute/RequestedTransportAttribute.java @@ -0,0 +1,158 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.lang.*; + +import org.ice4j.*; + +/** + * The REQUESTED-TRANSPORT attribute is used to allocate a + * TURN address of certain transport protocol. + * + * In the original TURN specification, only UDP is supported. + * Support of TCP is detailled in draft-ietf-behave-turn-tcp-05. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class RequestedTransportAttribute extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "REQUESTED-TRANSPORT"; + + /** + * The length of the data contained by this attribute. + */ + public static final char DATA_LENGTH = 4; + + /** + * Transport protocol. + * + * 17 = UDP; + * 6 = TCP. + */ + byte transportProtocol = 17; + + /** + * Constructor. + */ + RequestedTransportAttribute() + { + super(REQUESTED_TRANSPORT); + } + + /** + * Compares two STUN Attributes. Attributes are considered equal when their + * type, length, and all data are the same. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if (! (obj instanceof RequestedTransportAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + RequestedTransportAttribute att = (RequestedTransportAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + /* compare data */ + || att.transportProtocol != transportProtocol + ) + return false; + + return true; + } + + /** + * Returns the human readable name of this attribute. Attribute names do + * not really matter from the protocol point of view. They are only used + * for debugging and readability. + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value (8 bytes). + */ + public char getDataLength() + { + return DATA_LENGTH; + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH]; + + //Type + binValue[0] = (byte)(getAttributeType()>>8); + binValue[1] = (byte)(getAttributeType()&0x00FF); + //Length + binValue[2] = (byte)(getDataLength() >> 8); + binValue[3] = (byte)(getDataLength() & 0x00FF); + //Data + binValue[4] = transportProtocol; + binValue[5] = 0x00; + binValue[6] = 0x00; + binValue[7] = 0x00; + + return binValue; + } + + /** + * Sets this attribute's fields according to attributeValue array. + * @param attributeValue a binary array containing this attribute's field + * values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after + * length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws StunException + { + if(length != 4) + { + throw new StunException("length invalid"); + } + + transportProtocol = attributeValue[0]; + } + + /** + * Set the transport protocol. + * @param transportProtocol transport protocol + */ + public void setRequestedTransport(byte transportProtocol) + { + this.transportProtocol = transportProtocol; + } + + /** + * Get the transport protocol. + * @return transport protocol + */ + public int getRequestedTransport() + { + return transportProtocol; + } +} + diff --git a/src/org/ice4j/attribute/ReservationTokenAttribute.java b/src/org/ice4j/attribute/ReservationTokenAttribute.java new file mode 100644 index 0000000..902ad1d --- /dev/null +++ b/src/org/ice4j/attribute/ReservationTokenAttribute.java @@ -0,0 +1,163 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The RESERVATION-TOKEN attribute contains a token that identifie a reservation port + * on a TURN server. The value is on 64 bits (8 bytes). + * + *Organization Network Research Team, Louis Pasteur University
+ * @author Sebastien Vincent + * @version 0.1 + */ +public class ReservationTokenAttribute +extends Attribute +{ + /** + * Attribute name. + */ + public static final String NAME = "RESERVATION-TOKEN"; + + /** + * ReservationToken value. + */ + private byte reservationToken[] = null; + + /** + * Constructor. + */ + protected ReservationTokenAttribute () + { + super(RESERVATION_TOKEN); + } + + /** + * Copies the value of the reservationToken attribute from the specified + * attributeValue. + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attributeValue contains invalid reservationToken. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + if(length != 8) + { + throw new StunException("Length mismatch!"); + } + + reservationToken = new byte[8]; + System.arraycopy(attributeValue, offset, reservationToken, 0, 8); + } + + /** + * Returns a binary representation of this attribute. + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + 8]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(8 >> 8); + binValue[3] = (byte)(8 & 0x00FF); + + //reservationToken + System.arraycopy(reservationToken, 0, binValue, 4, 8); + + return binValue; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return NAME; + } + + /** + * Returns a (cloned) byte array containg the reservationToken value of the reservationToken + * attribute. + * @return the binary array containing the reservationToken. + */ + public byte[] getReservationToken() + { + if (reservationToken == null) + return null; + + byte[] copy = new byte[reservationToken.length]; + System.arraycopy(reservationToken, 0, copy, 0, reservationToken.length); + return reservationToken; + } + + /** + * Copies the specified binary array into the the reservationToken value of the reservationToken + * attribute. + * @param reservationToken the binary array containing the reservationToken. + */ + public void setReservationToken(byte[] reservationToken) + { + if (reservationToken == null) + { + this.reservationToken = null; + return; + } + + this.reservationToken = new byte[reservationToken.length]; + System.arraycopy(reservationToken, 0, this.reservationToken, 0, reservationToken.length); + } + + /** + * Returns the length of this attribute's body. + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)reservationToken.length; + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + + public boolean equals(Object obj) + { + if (! (obj instanceof ReservationTokenAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + ReservationTokenAttribute att = (ReservationTokenAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || !Arrays.equals( att.reservationToken, reservationToken)) + return false; + + return true; + } +} + diff --git a/src/org/ice4j/attribute/ResponseAddressAttribute.java b/src/org/ice4j/attribute/ResponseAddressAttribute.java new file mode 100644 index 0000000..6e89d29 --- /dev/null +++ b/src/org/ice4j/attribute/ResponseAddressAttribute.java @@ -0,0 +1,33 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +/** + * The RESPONSE-ADDRESS attribute indicates where the response to a + * Binding Request should be sent. Its syntax is identical to MAPPED- + * ADDRESS. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class ResponseAddressAttribute extends AddressAttribute +{ + public static final String NAME = "RESPONSE-ADDRESS"; + + /** + * Creates a RESPONSE_ADDRESS attribute + */ + public ResponseAddressAttribute() + { + super(RESPONSE_ADDRESS); + } + +} diff --git a/src/org/ice4j/attribute/SoftwareAttribute.java b/src/org/ice4j/attribute/SoftwareAttribute.java new file mode 100644 index 0000000..f704bad --- /dev/null +++ b/src/org/ice4j/attribute/SoftwareAttribute.java @@ -0,0 +1,158 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The SOFTWARE attribute contains a textual description of the software + * being used by the software or the client, including manufacturer and version number. + * The attribute has no impact on operation of the protocol, and serves + * only as a tool for diagnostic and debugging purposes. + * The value of SOFTWARE is variable length. Its length MUST be a + * multiple of 4 (measured in bytes) in order to guarantee alignment of + * attributes on word boundaries. + * + *Organization Network Research Team, Louis Pasteur University
+ * @author Emil Ivov + * @author Sebastien Vincent + * @version 0.1 + */ +public class SoftwareAttribute + extends Attribute +{ + private byte[] software = null; + + protected SoftwareAttribute () + { + super(SOFTWARE); + } + + /** + * Copies the value of the software attribute from the specified + * attributeValue. + * + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attributeValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws + StunException + { + software = new byte[length]; + System.arraycopy(attributeValue, offset, software, 0, length); + } + + /** + * Returns a binary representation of this attribute. + * + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + (getDataLength() % 4)]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + //software + System.arraycopy(software, 0, binValue, 4, getDataLength()); + + return binValue; + } + + /** + * Returns the length of this attribute's body. + * + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return (char)software.length; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return "SOFTWARE"; + } + + /** + * Returns a (cloned) byte array containg the data value of the software + * attribute. + * @return the binary array containing the software. + */ + public byte[] getSoftware() + { + if (software == null) + return null; + + byte[] copy = new byte[software.length]; + System.arraycopy(software, 0, copy, 0, software.length); + return software; + } + + /** + * Copies the specified binary array into the the data value of the software + * attribute. + * + * @param software the binary array containing the software. + */ + public void setSoftware(byte[] software) + { + if (software == null) + { + this.software = null; + return; + } + + this.software = new byte[software.length]; + System.arraycopy(software, 0, this.software, 0, software.length); + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when they + * have the same type length and value. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + + public boolean equals(Object obj) + { + if (! (obj instanceof SoftwareAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + SoftwareAttribute att = (SoftwareAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength() + || !Arrays.equals( att.software, software)) + return false; + + return true; + } + +} diff --git a/src/org/ice4j/attribute/SourceAddressAttribute.java b/src/org/ice4j/attribute/SourceAddressAttribute.java new file mode 100644 index 0000000..8742a40 --- /dev/null +++ b/src/org/ice4j/attribute/SourceAddressAttribute.java @@ -0,0 +1,32 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +/** + * The SOURCE-ADDRESS attribute is present in Binding Responses. It + * indicates the source IP address and port that the server is sending + * the response from. Its syntax is identical to that of MAPPED-ADDRESS. + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class SourceAddressAttribute extends AddressAttribute +{ + public static final String NAME = "SOURCE-ADDRESS"; + + /** + * Creates a SOURCE-ADDRESS attribute + */ + SourceAddressAttribute() + { + super(SOURCE_ADDRESS); + } +} diff --git a/src/org/ice4j/attribute/UnknownAttributesAttribute.java b/src/org/ice4j/attribute/UnknownAttributesAttribute.java new file mode 100644 index 0000000..505979d --- /dev/null +++ b/src/org/ice4j/attribute/UnknownAttributesAttribute.java @@ -0,0 +1,230 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import java.util.*; + +import org.ice4j.*; + +/** + * The UNKNOWN-ATTRIBUTES attribute is present only in a Binding Error + * Response or Shared Secret Error Response when the response code in + * the ERROR-CODE attribute is 420. + * + * The attribute contains a list of 16 bit values, each of which + * represents an attribute type that was not understood by the server. + * If the number of unknown attributes is an odd number, one of the + * attributes MUST be repeated in the list, so that the total length of + * the list is a multiple of 4 bytes. + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Attribute 1 Type | Attribute 2 Type | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Attribute 3 Type | Attribute 4 Type ... + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + *Copyright: Copyright (c) 2003
+ *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class UnknownAttributesAttribute extends Attribute +{ + /** + * A list of attribute types that were not understood by the server. + */ + private ArrayListCopyright: Copyright (c) 2005.
+ *Organization: Network Research Team, Louis Pasteur University
+ * @author Emil Ivov + * @version 1.0 + */ +public class XorMappedAddressAttribute + extends AddressAttribute +{ + public static final String NAME = "XOR-MAPPED-ADDRESS"; + + XorMappedAddressAttribute() + { + super(XOR_MAPPED_ADDRESS); + } + + /** + * Constructor. + * @param type other type than XOR-MAPPED-ADDRESS + */ + XorMappedAddressAttribute(char type) + { + super(type); + } + + /** + * Returns the result of applying XOR on the specified attribute's address. + * The method may be used for both encoding and decoding XorMappedAddresses. + * @param address the address on which XOR should be applied + * @param transactionID the transaction id to use for the XOR + * @return the XOR-ed address. + */ + public static TransportAddress applyXor(TransportAddress address, + byte[] transactionID) + { + byte[] addressBytes = address.getAddressBytes(); + char port = (char)address.getPort(); + + char portModifier = (char)( (transactionID[0] << 8 & 0x0000FF00) + | (transactionID[1] & 0x000000FF)); + + port ^= portModifier; + + for(int i = 0; i < addressBytes.length; i++) + addressBytes[i] ^= transactionID[i]; + + TransportAddress xoredAdd = new TransportAddress(addressBytes, port); + + return xoredAdd; + } + + /** + * Returns the result of applying XOR on this attribute's address, using the + * specified transaction identifier. The method may be used for both + * encoding and decoding XorMappedAddresses. + * @param transactionID the transaction id to use for the XOR + * @return the XOR-ed address. + */ + public TransportAddress applyXor(byte[] transactionID) + { + return applyXor(getAddress(), transactionID); + } +} diff --git a/src/org/ice4j/attribute/XorOnlyAttribute.java b/src/org/ice4j/attribute/XorOnlyAttribute.java new file mode 100644 index 0000000..3629d59 --- /dev/null +++ b/src/org/ice4j/attribute/XorOnlyAttribute.java @@ -0,0 +1,117 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * This attribute is present in a Binding Request. It is used by a + * client to request that a server compliant to this specification omit + * the MAPPED-ADDRESS from a Binding Response, and include only the XOR- + * MAPPED-ADDRESS. This is necessary in cases where a Binding Response + * is failing integrity checks because a NAT is rewriting the contents + * of a MAPPED-ADDRESS in the Binding Response. + * + * This attribute has a length of zero, and therefore contains no other + * information past the common attribute header. + * + *Organization: Net Research Team, Louis Pasteur University
+ * @author Emil Ivov + * @version 0.1 + */ +public class XorOnlyAttribute + extends Attribute +{ + + protected XorOnlyAttribute() + { + super(Attribute.XOR_ONLY); + } + + /** + * Sets this attribute's fields according to attributeValue array. + * + * @param attributeValue a binary array containing this attribute's + * field values and NOT containing the attribute header. + * @param offset the position where attribute values begin (most often + * offset is equal to the index of the first byte after length) + * @param length the length of the binary array. + * @throws StunException if attrubteValue contains invalid data. + */ + void decodeAttributeBody(byte[] attributeValue, char offset, char length) + throws StunException + { + //nothing to do cause we have 0 length + } + + /** + * Returns a binary representation of this attribute. + * + * @return a binary representation of this attribute. + */ + public byte[] encode() + { + char type = getAttributeType(); + byte binValue[] = new byte[HEADER_LENGTH + getDataLength()]; + + //Type + binValue[0] = (byte)(type>>8); + binValue[1] = (byte)(type&0x00FF); + + //Length + binValue[2] = (byte)(getDataLength()>>8); + binValue[3] = (byte)(getDataLength()&0x00FF); + + return binValue; + } + + /** + * Returns the length of this attribute's body. (Which in the case of the + * XOR-ONLY attribute is 0); + * + * @return the length of this attribute's value. + */ + public char getDataLength() + { + return 0; + } + + /** + * Returns the human readable name of this attribute. + * + * @return this attribute's name. + */ + public String getName() + { + return "XOR-ONLY"; + } + + /** + * Compares two STUN Attributes. Two attributes are considered equal when + * they have the same type length and value. + * + * @param obj the object to compare this attribute with. + * @return true if the attributes are equal and false otherwise. + */ + + public boolean equals(Object obj) + { + if (! (obj instanceof XorOnlyAttribute) + || obj == null) + return false; + + if (obj == this) + return true; + + XorOnlyAttribute att = (XorOnlyAttribute) obj; + if (att.getAttributeType() != getAttributeType() + || att.getDataLength() != getDataLength()) + return false; + + return true; + } +} diff --git a/src/org/ice4j/attribute/XorPeerAddressAttribute.java b/src/org/ice4j/attribute/XorPeerAddressAttribute.java new file mode 100644 index 0000000..9be3679 --- /dev/null +++ b/src/org/ice4j/attribute/XorPeerAddressAttribute.java @@ -0,0 +1,35 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * The XOR-PEER-ADDRESS attribute is given by a TURN client to + * indicates the peer destination address of its relayed packet. + * + * It has the same format as XOR-MAPPED-ADDRESS. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class XorPeerAddressAttribute extends XorMappedAddressAttribute +{ + /** + * Attribute name. + */ + public static final String NAME = "XOR-PEER-ADDRESS"; + + /** + * Constructor. + */ + XorPeerAddressAttribute() + { + super(XOR_PEER_ADDRESS); + } +} + diff --git a/src/org/ice4j/attribute/XorRelayedAddressAttribute.java b/src/org/ice4j/attribute/XorRelayedAddressAttribute.java new file mode 100644 index 0000000..681f702 --- /dev/null +++ b/src/org/ice4j/attribute/XorRelayedAddressAttribute.java @@ -0,0 +1,35 @@ +/* + * Ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.attribute; + +import org.ice4j.*; + +/** + * The XOR-RELAYED-ADDRESS attribute is given by a TURN server to + * indicates the client its relayed address. + * + * It has the same format as XOR-MAPPED-ADDRESS. + * + * @author Sebastien Vincent + * @version 0.1 + */ +public class XorRelayedAddressAttribute extends XorMappedAddressAttribute +{ + /** + * Attribute name. + */ + public static final String NAME = "XOR-RELAYED-ADDRESS"; + + /** + * Constructor. + */ + XorRelayedAddressAttribute() + { + super(XOR_RELAYED_ADDRESS); + } +} + diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java new file mode 100644 index 0000000..532c3e1 --- /dev/null +++ b/src/org/ice4j/ice/Agent.java @@ -0,0 +1,203 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.ice; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.oldice.*; + +/** + * An IceAgent could be described as the main class (i.e. the chef d'orchestre) + * of an ICE implementation. + *+ * As defined in RFC 3264, an agent is the protocol implementation involved in + * the offer/answer exchange. There are two agents involved in an offer/answer + * exchange. + *
+ *
+ * @author Emil Ivov
+ * @author Namal Senarathne
+ */
+public class Agent
+{
+ /**
+ * Our class logger.
+ */
+ private final Logger logger
+ = Logger.getLogger(Agent.class.getName());
+
+ /**
+ * The LinkedHashMap used to store the media streams
+ * This map preserves the insertion order of the media streams.
+ */
+ private Map
+ * Not that the method would only use existing harvesters so make sure
+ * you've registered all harvesters that you would want to use before
+ * calling it.
+ *
+ * At this point this class only supports UDP candidates. Implementation of
+ * support for other transport protocols should mean that this class should
+ * become abstract and some transport specific components like to socket for
+ * example should be brought down the inheritance chain.
+ *
+ * @param obj the reference object with which to compare.
+ *
+ * @return
+ * The local preference MUST be an integer from 0 to 65535
+ * inclusive. It represents a preference for the particular IP address from
+ * which the candidate was obtained, in cases where an agent is multihomed.
+ * 65535 represents the highest preference, and a zero, the lowest.
+ * When there is only a single IP address, this value SHOULD be set to
+ * 65535. More generally, if there are multiple candidates for a
+ * particular component for a particular media stream which have the same
+ * type, the local preference MUST be unique for each one. In this
+ * specification, this only happens for multihomed hosts. If a host is
+ * multihomed because it is dual stacked, the local preference SHOULD be
+ * set equal to the precedence value for IP addresses described in RFC 3484.
+ *
+ *
+ * @author Emil Ivov
+ * @author Namal Senarathne
+ */
+public class Component
+{
+ /**
+ * A component id is a positive integer between 1 and 256 which identifies
+ * the specific component of the media stream for which this is a candidate.
+ * It MUST start at 1 and MUST increment by 1 for each component of a
+ * particular candidate. For media streams based on RTP, candidates for the
+ * actual RTP media MUST have a component ID of 1, and candidates for RTCP
+ * MUST have a component ID of 2. Other types of media streams which
+ * require multiple components MUST develop specifications which define the
+ * mapping of components to component IDs. See Section 14 for additional
+ * discussion on extending ICE to new media streams.
+ */
+ private int componentID = -1;
+
+ /**
+ * The component ID to use with RTP streams.
+ */
+ public static final int RTP = 1;
+
+ /**
+ * The component ID to use with RTCP streams.
+ */
+ public static final int RTCP = 2;
+
+ /**
+ * The transport that this component is using.
+ */
+ private final Transport transport;
+
+ /**
+ * The IceMediaStream that this Component belongs to.
+ */
+ private final IceMediaStream parentStream;
+
+ /**
+ * The list locally gathered candidates for this media stream.
+ */
+ private List
+ * At this point this class only supports UDP candidates. Implementation of
+ * support for other transport protocols should mean that this class should
+ * become abstract and some transport specific components like to socket for
+ * example should be brought down the inheritance chain.
+ * Organisation: Louis Pasteur University, Strasbourg, France Network Research Team (http://www-r2.u-strasbg.fr) Organisation: Louis Pasteur University, Strasbourg, France Network Research Team (http://www-r2.u-strasbg.fr)true if this Candidate is equal to the
+ * obj argument; false otherwise.
+ *
+ * @throws java.lang.NullPointerException if obj is null;
+ */
+ public boolean equals(Object obj)
+ throws NullPointerException
+ {
+ if(obj == this)
+ return true;
+
+ if( ! (obj instanceof Candidate))
+ return false;
+
+ Candidate targetCandidate = (Candidate)obj;
+
+ //compare candidate addresses
+ if( ! targetCandidate.getTransportAddress()
+ .equals(getTransportAddress()))
+ return false;
+
+ //compare bases
+ if( getBase() == null )
+ {
+ if (targetCandidate.getBase() != null)
+ return false;
+ }
+
+ //compare other properties
+ if(getBase().equals(targetCandidate.getBase())
+ && getPriority() == targetCandidate.getPriority()
+ && getType() == targetCandidate.getType()
+ && getFoundation().equals(targetCandidate.getFoundation()))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns a reference to the Component that this candidate belongs
+ * to.
+ *
+ * @return a reference to the Component that this candidate belongs
+ * to.
+ */
+ public Component getParentComponent()
+ {
+ return parentComponent;
+ }
+
+ /**
+ * Computes the priority for this Candidate based on the procedures
+ * defined in the ICE specification..
+ *
+ * @return the priority for this Candidate as per the procedures
+ * defined in the ICE specification..
+ */
+ public long computePriority()
+ {
+ //According to the ICE speck we compute priority this way:
+ //priority = (2^24)*(type preference) +
+ // (2^8)*(local preference) +
+ // (2^0)*(256 - component ID)
+
+ this.priority = (long)( getTypePreference() << 24 )+
+ (long)( getLocalPreference() << 8 )+
+ (long) (256 - getParentComponent().getComponentID());
+
+ return priority;
+ }
+
+ /**
+ * Returns the type preference for this candidate according to its type.
+ * The type preference MUST be an integer from 0 to 126
+ * inclusive, and represents the preference for the type of the candidate
+ * (where the types are local, server reflexive, peer reflexive and
+ * relayed). A 126 is the highest preference, and a 0 is
+ * the lowest. Setting the value to a 0 means that candidates of
+ * this type will only be used as a last resort. The type preference MUST
+ * be identical for all candidates of the same type and MUST be different
+ * for candidates of different types. The type preference for peer
+ * reflexive candidates MUST be higher than that of server reflexive
+ * candidates.
+ *
+ * @return the type preference for this Candidate as per the
+ * procedures in the ICE specification.
+ */
+ private int getTypePreference()
+ {
+ int typePreference;
+ CandidateType candidateType = getType();
+ if(candidateType == CandidateType.HOST_CANDIDATE)
+ {
+ typePreference = MAX_TYPE_PREFERENCE; // 126
+ }
+ else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
+ {
+ typePreference = 110;
+ }
+ else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
+ {
+ typePreference = 100;
+ }
+ else //relayed candidates
+ {
+ typePreference = MIN_TYPE_PREFERENCE; // 0
+ }
+
+ return typePreference;
+ }
+
+ /**
+ * Calculates and returns the local preference for this Candidate
+ *
Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @author Sebastien Vincent + * @version 0.1 + */ +public abstract class Message +{ + /* general declaration */ + public static final char STUN_REQUEST = 0x0000; + public static final char STUN_INDICATION = 0x0010; + public static final char STUN_SUCCESS_RESP = 0x0100; + public static final char STUN_ERROR_RESP = 0x0110; + + /* STUN methods */ + public static final char STUN_METHOD_BINDING = 0x0001; + + public static final char BINDING_REQUEST = (STUN_METHOD_BINDING | STUN_REQUEST); + public static final char BINDING_RESPONSE = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP); + public static final char BINDING_ERROR_RESPONSE = (STUN_METHOD_BINDING | STUN_ERROR_RESP); + public static final char SHARED_SECRET_REQUEST = 0x0002; + public static final char SHARED_SECRET_RESPONSE = 0x0102; + public static final char SHARED_SECRET_ERROR_RESPONSE = 0x0112; + + /* TURN methods */ + public static final char TURN_METHOD_ALLOCATE = 0x0003; + public static final char TURN_METHOD_REFRESH = 0x0004; + public static final char TURN_METHOD_SEND = 0x0006;; + public static final char TURN_METHOD_DATA = 0x0007;; + public static final char TURN_METHOD_CHANNELBIND = 0x0009; + + public static final char ALLOCATE_REQUEST = (TURN_METHOD_ALLOCATE | STUN_REQUEST); + public static final char ALLOCATE_RESPONSE = (TURN_METHOD_ALLOCATE | STUN_SUCCESS_RESP); + public static final char ALLOCATE_ERROR_RESPONSE = (TURN_METHOD_ALLOCATE | STUN_ERROR_RESP); + public static final char REFRESH_REQUEST = (TURN_METHOD_REFRESH | STUN_REQUEST); + public static final char REFRESH_RESPONSE = (TURN_METHOD_REFRESH | STUN_SUCCESS_RESP); + public static final char REFRESH_ERROR_RESPONSE = (TURN_METHOD_REFRESH | STUN_ERROR_RESP); + public static final char CHANNELBIND_REQUEST = (TURN_METHOD_CHANNELBIND | STUN_REQUEST); + public static final char CHANNELBIND_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_SUCCESS_RESP); + public static final char CHANNELBIND_ERROR_RESPONSE = (TURN_METHOD_CHANNELBIND | STUN_ERROR_RESP); + public static final char SEND_INDICATION = (TURN_METHOD_SEND | STUN_INDICATION); + public static final char DATA_INDICATION = (TURN_METHOD_DATA | STUN_INDICATION); + + //Message fields + /** + * The length of Stun Message Headers in bytes + * = len(Type) + len(DataLength) + len(Transaction ID). + */ + public static final byte HEADER_LENGTH = 20; + + /** + * Indicates the type of the message. The message type can be Binding Request, + * Binding Response, Binding Error Response, Shared Secret Request, Shared + * Secret Response, or Shared Secret Error Response. + */ + protected char messageType = 0x0000; + + /** + * The transaction ID is used to correlate requests and responses. + */ + protected byte[] transactionID = null; + + /** + * The magic cookie (0x2112A442). + */ + public static final byte[] MAGIC_COOKIE = { 0x21, 0x12, (byte)0xA4, 0x42 }; + + /** + * The length of the transaction id (in bytes). + */ + public static final byte TRANSACTION_ID_LENGTH = 12; + + /** + * The list of attributes contained by the message. We are using a hastable + * rather than a uni-dimensional list, in order to facilitate attribute + * search (even though it introduces some redundancies). Order is important + * so we'll be using a LinkedHashMap + */ + //not sure this is the best solution but I'm trying to keep entry order + protected LinkedHashMapOrganisation: Louis Pasteur University, Strasbourg, France.
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @author Sebastien Vincent + * @version 0.1 + */ + +public class MessageFactory +{ + private static final Logger logger = + Logger.getLogger(MessageFactory.class.getName()); + + /** + * Creates a default binding request. + * The request DOES NOT contains a ChangeRequest attribute + * with zero change ip and change port flags. + * @return a default binding request. + */ + public static Request createBindingRequest() + { + Request bindingRequest = new Request(); + try + { + bindingRequest.setMessageType(Message.BINDING_REQUEST); + } + catch (StunException ex) + { + //there should be no exc here since we're the creators. + logger.log(Level.FINE, "Failed to set message type.", ex); + } + + /* do not add this by default */ +/* + //add a change request attribute + ChangeRequestAttribute attribute + = AttributeFactory.createChangeRequestAttribute(); + + try + { + bindingRequest.addAttribute(attribute); + } + catch (StunException ex) + { + //shouldn't happen + throw new RuntimeException("Failed to add a change request attribute to a binding request!"); + } +*/ + return bindingRequest; + } + + /** + * Creates a default binding request. The request contains a ChangeReqeust + * attribute with zero change ip and change port flags. + * It also contains the PRIORITY attribute used for ICE processing + * + * @param priority + * @return a BindingRequest header with ICE PRIORITY attribute + * @throws StunException + */ + public static Request createBindingRequest(long priority) + throws StunException + { + Request bindingRequest = createBindingRequest(); + + PriorityAttribute attribute + = AttributeFactory.createPriorityAttribute(priority); + bindingRequest.addAttribute(attribute); + + return bindingRequest; + } + + /** + * Creates a default binding request. The request contains a ChangeReqeust + * attribute with zero change ip and change port flags. + * It contains the PRIORITY, ICE-CONTROLLED or ICE-CONTROLLING attributes + * used for ICE processing + * + * @param priority + * @param controlling + * @param tieBreaker + * @return a BindingRequest header with some ICE attributes (PRIORITY, ICE-CONTROLLING / ICE-CONTROLLED) + * @throws StunException + */ + public static Request createBindingRequest(long priority, boolean controlling, long tieBreaker) + throws StunException + { + Request bindingRequest = createBindingRequest(); + + PriorityAttribute attribute + = AttributeFactory.createPriorityAttribute(priority); + bindingRequest.addAttribute(attribute); + + if(controlling) + { + IceControllingAttribute iceControllingAttribute + = AttributeFactory.createIceControllingAttribute(tieBreaker); + bindingRequest.addAttribute(iceControllingAttribute); + } + else + { + IceControlledAttribute iceControlledAttribute + = AttributeFactory.createIceControlledAttribute(tieBreaker); + bindingRequest.addAttribute(iceControlledAttribute); + } + + return bindingRequest; + } + + /** + * Creates a BindingResponse assigning the specified values to mandatory + * headers. + * + * @param mappedAddress the address to assign the mappedAddressAttribute + * @param sourceAddress the address to assign the sourceAddressAttribute + * @param changedAddress the address to assign the changedAddressAttribute + * @return a BindingResponse assigning the specified values to mandatory + * headers. + * @throws StunException ILLEGAL_ARGUMENT + */ + public static Response createBindingResponse(TransportAddress mappedAddress, + TransportAddress sourceAddress, + TransportAddress changedAddress) + throws StunException + { + Response bindingResponse = new Response(); + bindingResponse.setMessageType(Message.BINDING_RESPONSE); + + //mapped address + MappedAddressAttribute mappedAddressAttribute = + AttributeFactory.createMappedAddressAttribute(mappedAddress); + + //source address + SourceAddressAttribute sourceAddressAttribute = + AttributeFactory.createSourceAddressAttribute(sourceAddress); + + //changed address + ChangedAddressAttribute changedAddressAttribute = + AttributeFactory.createChangedAddressAttribute(changedAddress); + + try + { + bindingResponse.addAttribute(mappedAddressAttribute); + bindingResponse.addAttribute(sourceAddressAttribute); + bindingResponse.addAttribute(changedAddressAttribute); + } + catch (StunException ex) + { + throw new StunException(StunException.INTERNAL_ERROR, + "Failed to add a mandatory attribute to the binding response."); + } + + return bindingResponse; + } + + + /** + * Creates a binding error response according to the specified error code + * and unknown attributes. + * + * @param errorCode the error code to encapsulate in this message + * @param reasonPhrase a human readable description of the error + * @param unknownAttributes a char[] array containing the ids of one or more + * attributes that had not been recognized. + * @throws StunException INVALID_ARGUMENTS if one or more of the given + * parameters had an invalid value. + * + * @return a binding error response message containing an error code and a + * UNKNOWN-ATTRIBUTES header + */ + private static Response createBindingErrorResponse(char errorCode, + String reasonPhrase, + char[] unknownAttributes) + throws StunException + { + Response bindingErrorResponse = new Response(); + bindingErrorResponse.setMessageType(Message.BINDING_ERROR_RESPONSE); + + //init attributes + UnknownAttributesAttribute unknownAttributesAttribute = null; + ErrorCodeAttribute errorCodeAttribute = + AttributeFactory.createErrorCodeAttribute(errorCode,reasonPhrase); + + bindingErrorResponse.addAttribute(errorCodeAttribute); + + if(unknownAttributes != null) + { + unknownAttributesAttribute = AttributeFactory. + createUnknownAttributesAttribute(); + for (int i = 0; i < unknownAttributes.length; i++) + { + unknownAttributesAttribute.addAttributeID(unknownAttributes[i]); + } + bindingErrorResponse.addAttribute(unknownAttributesAttribute); + } + + return bindingErrorResponse; + } + + /** + * Creates a binding error response with UNKNOWN_ATTRIBUTES error code + * and the specified unknown attributes. + * + * @param unknownAttributes a char[] array containing the ids of one or more + * attributes that had not been recognized. + * @throws StunException INVALID_ARGUMENTS if one or more of the given + * parameters had an invalid value. + * @return a binding error response message containing an error code and a + * UNKNOWN-ATTRIBUTES header + */ + public static Response createBindingErrorResponseUnknownAttributes( + char[] unknownAttributes) + throws StunException + { + return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, + null, + unknownAttributes); + } + + /** + * Creates a binding error response with UNKNOWN_ATTRIBUTES error code + * and the specified unknown attributes and reason phrase. + * + * @param reasonPhrase a short description of the error. + * @param unknownAttributes a char[] array containing the ids of one or more + * attributes that had not been recognized. + * @throws StunException INVALID_ARGUMENTS if one or more of the given + * parameters had an invalid value. + * @return a binding error response message containing an error code and a + * UNKNOWN-ATTRIBUTES header + */ + public static Response createBindingErrorResponseUnknownAttributes( + String reasonPhrase, + char[] unknownAttributes) + throws StunException + { + return createBindingErrorResponse(ErrorCodeAttribute.UNKNOWN_ATTRIBUTE, + reasonPhrase, + unknownAttributes); + } + + + /** + * Creates a binding error response with an ERROR-CODE attribute. + * + * @param errorCode the error code to encapsulate in this message + * @param reasonPhrase a human readable description of the error. + * @throws StunException INVALID_ARGUMENTS if one or more of the given + * parameters had an invalid value. + * + * @return a binding error response message containing an error code and a + * UNKNOWN-ATTRIBUTES header + */ + public static Response createBindingErrorResponse(char errorCode, + String reasonPhrase) + throws StunException + { + return createBindingErrorResponse(errorCode, reasonPhrase, null); + } + + /** + * Creates a binding error response according to the specified error code. + * + * @param errorCode the error code to encapsulate in this message + * attributes that had not been recognized. + * @throws StunException INVALID_ARGUMENTS if one or more of the given + * parameters had an invalid value. + * + * @return a binding error response message containing an error code and a + * UNKNOWN-ATTRIBUTES header + */ + public static Response createBindingErrorResponse(char errorCode) throws + StunException + { + return createBindingErrorResponse(errorCode, null, null); + } + + /** + * Create an allocate request without attribute. + * @return an allocate request + */ + public static Request createAllocateRequest() throws StunException + { + Request allocateRequest = new Request(); + try + { + allocateRequest.setMessageType(Message.ALLOCATE_REQUEST); + } + catch (StunException ex) + { + //there should be no exc here since we're the creators. + logger.log(Level.FINE, "Failed to set message type.", ex); + } + + return allocateRequest; + } + + /** + * Create an allocate request to allocate an even port. + * Attention this does not have attributes for long-term + * authentication. + * @param protocol requested protocol number + * @param rFlag R flag for the EVEN-PORT + * @return an allocation request + */ + public static Request createAllocateRequest(byte protocol, boolean rFlag) throws StunException + { + Request allocateRequest = new Request(); + + try + { + allocateRequest.setMessageType(Message.ALLOCATE_REQUEST); + + + /* XXX add enum somewhere for transport number */ + if(protocol != 6 && protocol != 17) + { + throw new StunException("Protocol not valid!"); + } + + /* add a REQUESTED-TRANSPORT attribute */ + RequestedTransportAttribute reqTransport = AttributeFactory.createRequestedTransportAttribute(protocol); + allocateRequest.addAttribute(reqTransport); + + /* add EVEN-PORT attribute */ + EvenPortAttribute reqProps = AttributeFactory.createEvenPortAttribute(rFlag); + allocateRequest.addAttribute(reqProps); + } + catch(StunException ex) + { + logger.log(Level.FINE, "Failed to set message type.", ex); + } + + return allocateRequest; + } + + /** + * Add the required attributes for long-term authentication.Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class Request extends Message +{ + + /** + * Constructor. + */ + Request() + { + + } + + /** + * Checks whether requestType is a valid request type and if yes sets it + * as the type of the current instance. + * @param requestType the type to set + * @throws StunException ILLEGAL_ARGUMENT if requestType is not a valid + * request type + */ + public void setMessageType(char requestType) + throws StunException + { + if(!isRequestType(requestType)) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + (int)(requestType) + + " - is not a valid request type."); + + + super.setMessageType(requestType); + } + +} diff --git a/src/org/ice4j/message/Response.java b/src/org/ice4j/message/Response.java new file mode 100644 index 0000000..f5e629c --- /dev/null +++ b/src/org/ice4j/message/Response.java @@ -0,0 +1,52 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.message; + +import org.ice4j.*; + +/** + * A response descendant of the message class. The primary purpose of the + * Response class is to allow better functional definition of the classes in the + * stack package. + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class Response extends Message +{ + + /** + * Constructor. + */ + Response() + { + + } + + /** + * Checks whether responseType is a valid response type and if yes sets it + * as the type of the current instance. + * @param responseType the type to set + * @throws StunException ILLEGAL_ARGUMENT if responseType is not a valid + * response type + */ + public void setMessageType(char responseType) + throws StunException + { + if(!isResponseType(responseType)) + throw new StunException(StunException.ILLEGAL_ARGUMENT, + (int)(responseType) + + " - is not a valid response type."); + + + super.setMessageType(responseType); + } + +} diff --git a/src/org/ice4j/stack/ErrorHandler.java b/src/org/ice4j/stack/ErrorHandler.java new file mode 100644 index 0000000..5186b01 --- /dev/null +++ b/src/org/ice4j/stack/ErrorHandler.java @@ -0,0 +1,36 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +/** + * Generic Error Handler. + * + *Organisation:
Louis Pasteur University, Strasbourg, France.
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ +interface ErrorHandler +{ + /** + * Called when an error has occurred which may have caused data loss but the + * calling thread is still running. + * + * @param message A message describing the error + * @param error The error itself. + */ + public void handleError(String message, Throwable error); + + /** + * Called when a fatal error has occurred and the calling thread will exit. + * + * @param callingThread the thread where the error has occurred + * @param message a message describing the error. + * @param error the error itself. + */ + public void handleFatalError(Runnable callingThread, String message, Throwable error); +} diff --git a/src/org/ice4j/stack/EventDispatcher.java b/src/org/ice4j/stack/EventDispatcher.java new file mode 100644 index 0000000..1451442 --- /dev/null +++ b/src/org/ice4j/stack/EventDispatcher.java @@ -0,0 +1,205 @@ + +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.*; + +import org.ice4j.*; + + +/** + * This is a utility class used for dispatching incoming request events. We use + * this class mainly (and probably solely) for its ability to handle listener + * proxies (i.e. listeners interested in requests recevied on a particular + * NetAccessPoint only). + * + * @author Emil Ivov + */ +public class EventDispatcher +{ + + /** + * All property change listeners registered so far. + */ + private VectorEventDispatcher object.
+ */
+ public EventDispatcher()
+ {
+ }
+
+ /**
+ * Add a RequestListener to the listener list. The listener is registered
+ * for requests coming from no matter which NetAccessPoint.
+ *
+ * @param listener The ReuqestListener to be added
+ */
+ public synchronized void addRequestListener(RequestListener listener)
+ {
+ if (requestListeners == null)
+ {
+ requestListeners = new VectorOrganisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +interface MessageEventHandler +{ + /** + * Called when an incoming message has been received, parsed and is ready + * for delivery. + * @param evt the Event object that encapsulates the newly received message. + */ + public void handleMessageEvent(StunMessageEvent evt); +} diff --git a/src/org/ice4j/stack/MessageProcessor.java b/src/org/ice4j/stack/MessageProcessor.java new file mode 100644 index 0000000..d2d14ec --- /dev/null +++ b/src/org/ice4j/stack/MessageProcessor.java @@ -0,0 +1,172 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.message.*; + +/** + * The class is used to parse and dispatch incoming messages in a multithreaded + * manner. + * + *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +class MessageProcessor + implements Runnable +{ + private static final Logger logger = + Logger.getLogger(MessageProcessor.class.getName()); + + private MessageQueue messageQueue = null; + private MessageEventHandler messageHandler = null; + private ErrorHandler errorHandler = null; + + private boolean isRunning = false; + private Thread runningThread = null; + + /** + * Creates a Message processor. + * + * @param queue the MessageQueue where we'll be storing incoming + * messages. + * @param messageHandler MessageEventHandler + * @param errorHandler the ErrorHandler that should handle + * exceptions in this processor + * + * @throws IllegalArgumentException if either of the parameters is null. + */ + MessageProcessor(MessageQueue queue, + MessageEventHandler messageHandler, + ErrorHandler errorHandler) + throws IllegalArgumentException + { + if(queue == null) + throw new IllegalArgumentException( + "The message queue may not be " + null); + + if(messageHandler == null) + throw new IllegalArgumentException( + "The message handler may not be " + null); + + if(errorHandler == null) + throw new IllegalArgumentException( + "The error handler may not be " + null); + + + + this.messageQueue = queue; + this.messageHandler = messageHandler; + this.errorHandler = errorHandler; + } + + /** + * Does the message parsing. + */ + public void run() + { + //add an extra try/catch block that handles uncatched errors and helps avoid + //having dead threads in our pools. + try + { + while (isRunning) + { + RawMessage rawMessage = null; + try + { + rawMessage = messageQueue.remove(); + } + catch (InterruptedException ex) + { + if(isRunning()) + logger.log(Level.WARNING, + "A net access point has gone useless:", + ex); + //nothing to do here since we test whether we are running + //just beneath ... + } + + // were we asked to stop? + if (!isRunning()){ + return; + } + //anything to parse? + if (rawMessage == null) + continue; + + Message stunMessage = null; + try + { + stunMessage = + Message.decode(rawMessage.getBytes(), + (char) 0, + (char) rawMessage.getMessageLength()); + } + catch (StunException ex) + { + errorHandler.handleError("Failed to decode a stun mesage!", + ex); + continue; //let this one go and for better luck next time. + } + + logger.finest("Dispatching a StunMessageEvent."); + + StunMessageEvent stunMessageEvent = + new StunMessageEvent( + rawMessage.getNetAccessPoint(), + stunMessage, + new TransportAddress( + rawMessage.getRemoteAddress().getAddress(), + rawMessage.getRemoteAddress().getPort() )); + messageHandler.handleMessageEvent(stunMessageEvent); + } + } + catch(Throwable err) + { + //notify and bail + errorHandler.handleFatalError(this, "Unexpected Error!", err); + } + } + + /** + * Start the message processing thread. + */ + void start() + { + this.isRunning = true; + + runningThread = new Thread(this, "Stun4J Message Processor"); + runningThread.setDaemon(true); + runningThread.start(); + } + + + /** + * Shut down the message processor. + */ + void stop() + { + this.isRunning = false; + runningThread.interrupt(); + } + + /** + * Determines whether the processor is still running; + * + * @return true if the processor is still authorised to run, and false + * otherwise. + */ + boolean isRunning() + { + return isRunning; + } +} diff --git a/src/org/ice4j/stack/MessageQueue.java b/src/org/ice4j/stack/MessageQueue.java new file mode 100644 index 0000000..8eefbd2 --- /dev/null +++ b/src/org/ice4j/stack/MessageQueue.java @@ -0,0 +1,109 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.*; +import java.util.logging.Logger; + +/** + * The class is used as a part of the stack's thread pooling strategy. Method + * access is synchronized and message delivery ( remove() ) is blocking in the + * case of an empty queue. + * + *Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * + * @author Emil Ivov + * @version 0.1 + */ +class MessageQueue +{ + private static final Logger logger = + Logger.getLogger(MessageQueue.class.getName()); + + // not sure whether Vector is the best choice here since we explicitly + //sync all methods ... review later + private VectorOrganisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +class NetAccessManager + implements ErrorHandler +{ + private static final Logger logger = + Logger.getLogger(NetAccessManager.class.getName()); + /** + * All access points currently in use. The table maps NetAccessPointDescriptor-s + * to NetAccessPoint-s + */ + private HashtableOrganisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +class NetAccessPoint + implements Runnable +{ + private static final Logger logger = + Logger.getLogger(NetAccessPoint.class.getName()); + NetAccessPoint() + { + } + + /** + * Max datagram size. + */ + private static final int MAX_DATAGRAM_SIZE = 8 * 1024; + + + /** + * The message queue is where incoming messages are added. + */ + private MessageQueue messageQueue = null; + + /** + * The socket object that used by this access point to access the network. + */ + protected DatagramSocket sock; + + /** + * Indicates whether the access point is using a socket that was created + * by someone else. The variable is set to true when the AP's socket is + * set using theuseExternalSocket() method and is consulted
+ * inside the stop method. When its value is true, the AP's socket is not
+ * closed when stop()ing the AP.
+ *
+ * This variable is part of bug fix reported by Dave Stuart - SipQuest
+ */
+ private boolean isUsingExternalSocket = false;
+
+ /**
+ * A flag that is set to false to exit the message processor.
+ */
+ private boolean isRunning;
+
+ /**
+ * The descriptor used to create this access point.
+ */
+ private NetAccessPointDescriptor apDescriptor = null;
+
+ /**
+ * The instance to be notified if errors occur in the network listening
+ * thread.
+ */
+ private ErrorHandler errorHandler = null;
+
+ /**
+ * Used for locking socket operations
+ */
+ private Object socketLock = new Object();
+
+ /**
+ * Creates a network access point.
+ * @param apDescriptor the address and port where to bind.
+ * @param messageQueue the FIFO list where incoming messages should be queued
+ * @param errorHandler the instance to notify when errors occur.
+ */
+ NetAccessPoint(NetAccessPointDescriptor apDescriptor,
+ MessageQueue messageQueue,
+ ErrorHandler errorHandler)
+ {
+ this.apDescriptor = apDescriptor;
+ this.messageQueue = messageQueue;
+ this.errorHandler = errorHandler;
+ }
+
+
+ /**
+ * Start the network listening thread.
+ *
+ * @throws IOException if we fail to setup the socket.
+ */
+ void start()
+ throws IOException
+ {
+ synchronized(socketLock){
+
+ //do not create the socket earlier as someone might want to set an
+ // existing one was != null fixed (Ranga)
+ if (sock == null)
+ {
+ this.sock = new DatagramSocket(getDescriptor().getAddress().
+ getSocketAddress());
+ this.isUsingExternalSocket = false;
+ logger.info("Bound a socket on ap: " + toString());
+ }
+
+ sock.setReceiveBufferSize(MAX_DATAGRAM_SIZE);
+ this.isRunning = true;
+ Thread thread = new Thread(this);
+ thread.start();
+ }
+ }
+
+ /**
+ * Returns the NetAccessPointDescriptor that contains the port and address
+ * associated with this accesspoint.
+ * @return the NetAccessPointDescriptor associated with this AP.
+ */
+ NetAccessPointDescriptor getDescriptor()
+ {
+ return apDescriptor;
+ }
+
+ /**
+ * The listening thread's run method.
+ */
+ public void run()
+ {
+ while (this.isRunning)
+ {
+ try
+ {
+ int bufsize = sock.getReceiveBufferSize();
+ byte message[] = new byte[bufsize];
+ DatagramPacket packet = new DatagramPacket(message, bufsize);
+
+ sock.receive(packet);
+ logger.finest("received datagram");
+
+ RawMessage rawMessage = new RawMessage( message,
+ packet.getLength(), packet.getAddress(), packet.getPort(),
+ getDescriptor());
+
+ messageQueue.add(rawMessage);
+ }
+ catch (SocketException ex)
+ {
+ if (isRunning)
+ {
+ logger.log(Level.WARNING,
+ "A net access point has gone useless:", ex);
+
+ stop();
+ //Something wrong has happened
+ errorHandler.handleFatalError(
+ this,
+ "A socket exception was thrown while trying to "
+ + "receive a message.",
+ ex);
+ }
+ else
+ {
+ //The exception was most probably caused by calling this.stop()
+ // ....
+ }
+ }
+ catch (IOException ex)
+ {
+ logger.log(Level.WARNING,
+ "A net access point has gone useless:", ex);
+
+ errorHandler.handleError(ex.getMessage(), ex);
+ //do not stop the thread;
+ }
+ catch (Throwable ex)
+ {
+ logger.log(Level.WARNING,
+ "A net access point has gone useless:", ex);
+
+ stop();
+ errorHandler.handleFatalError(
+ this,
+ "Unknown error occurred while listening for messages!",
+ ex);
+ }
+ }
+ }
+
+
+ /**
+ * Shut down the access point. Close the socket for recieving
+ * incoming messages. The method won't close the socket if it was created
+ * outside the stack (Bug Report - Dave Stuart - SipQuest). It also seems
+ * that sometimes sockets don't immdeiately free their port and trying
+ * to bind to that port immediately after gets us an exception. We therefore
+ * null the socket, wait for 200 miliseconds and call the garbage collector
+ * this seems to be working fine but is not what one could call neat
+ * behaviour, so if you'd like to disable it - set the
+ * org.ice4j.stack.HARD_SOCK_CLOSE property to anything different from
+ * true. If you'd want us to wait more or less - set
+ * org.ice4j.stack.WAIT_FOR_SOCK_CLOSE to the appropriate number of
+ * miliseconds.
+ *
+ */
+ synchronized void stop()
+ {
+ this.isRunning = false;
+
+ //avoid a needless null pointer exception
+ if (sock != null
+ && isUsingExternalSocket == false)
+ {
+ synchronized (socketLock)
+ {
+ sock.close();
+
+ logger.info("Closed socket on ap " + toString());
+ sock = null;
+ String hardSocketClose =
+ System.getProperty("org.ice4j.stack.HARD_SOCK_CLOSE");
+
+ //sometimes sockts stay open even after closing them. make sure
+ //this doesn't happen here. (unless the user doesn't want us to)
+ if (hardSocketClose == null
+ || hardSocketClose.equalsIgnoreCase("true"))
+ {
+
+ int waitForSockClose = 200;
+ try
+ {
+ String waitForSockCloseStr =
+ System.getProperty(
+ "org.ice4j.stack.WAIT_FOR_SOCK_CLOSE");
+ if (waitForSockCloseStr != null &&
+ waitForSockCloseStr.length() > 0){
+
+ waitForSockClose =
+ Integer.parseInt(System.getProperty(
+ waitForSockCloseStr));
+ }
+ }
+ catch (Throwable t)
+ {
+ logger.log(
+ Level.WARNING,
+ "Failed to parse wait_for_sock_close prop", t);
+
+ if (waitForSockClose < 0)
+ {
+ waitForSockClose = 200;
+ }
+ }
+
+ //wait
+ try
+ {
+ wait(waitForSockClose);
+ }
+ catch (InterruptedException t)
+ {
+ logger.warning("Interrupted waiting for sock close.");
+ }
+ System.gc();
+ }
+ }
+ }
+ }
+
+ /**
+ * Sends message through this access point's socket.
+ * @param message the bytes to send.
+ * @param address message destination.
+ * @throws IOException if an exception occurs while sending the message.
+ */
+ void sendMessage(byte[] message, TransportAddress address)
+ throws IOException
+ {
+ DatagramPacket datagramPacket = new DatagramPacket(
+ message,
+ 0,
+ message.length,
+ address.getSocketAddress());
+ synchronized(socketLock){
+ sock.send(datagramPacket);
+ }
+ }
+
+ /**
+ * Returns a String representation of the object.
+ * @return a String representation of the object.
+ */
+ public String toString()
+ {
+ return "org.ice4j.stack.AccessPoint@"
+ +apDescriptor.getAddress()
+ +" status: "
+ + (isRunning? "not":"")
+ +" running";
+ }
+
+ /**
+ * Sets a socket for the access point to use. This socket will not be closed
+ * when the AP is stop()ed (Bug Report - Dave Stuart - SipQuest).
+ * @param socket the socket that the AP should use.
+ */
+ void useExternalSocket(DatagramSocket socket)
+ {
+ this.sock = socket;
+ this.isUsingExternalSocket = true;
+ }
+}
diff --git a/src/org/ice4j/stack/RawMessage.java b/src/org/ice4j/stack/RawMessage.java
new file mode 100644
index 0000000..a7b6a86
--- /dev/null
+++ b/src/org/ice4j/stack/RawMessage.java
@@ -0,0 +1,113 @@
+/*
+ * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.ice4j.stack;
+
+import java.net.*;
+
+import org.ice4j.*;
+
+/**
+ * The class represents a binary STUN message as well as the address and port
+ * of the host that sent it and the address and port where it was received
+ * (locally).
+ *
+ * Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * + * @author Emil Ivov + * @version 0.1 + */ +class RawMessage +{ + /** + * The message itself. + */ + private byte[] messageBytes = null; + + /** + * The length of the message. + */ + private int messageLength = -1; + /** + * The addres and port where the message was sent from. + */ + private InetSocketAddress remoteAddress = null; + + + /** + * The descriptor of the net access point that received the message. + */ + private NetAccessPointDescriptor receivingAccessPoint = null; + + /** + * Constructs a raw message with the specified field values. All parameters + * are cloned before being assigned to class members. + * + * @param messageBytes the message itself. + * @param remoteAddress the address where the message came from. + * @param remotePort the port where the message came from. + * @param netApDescriptor the access point the received the message.s + * + * @throws NullPointerException if one or more of the parameters were null. + */ + RawMessage(byte[] messageBytes, + int messageLength, + InetAddress remoteAddress, + int remotePort, + NetAccessPointDescriptor netApDescriptor) + { + //... don't do a null check - let it throw an NP exception + + this.messageBytes = new byte[messageBytes.length]; + this.messageLength = messageLength; + System.arraycopy(messageBytes, 0, this.messageBytes, + 0, messageBytes.length); + + this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort); + this.receivingAccessPoint = + (NetAccessPointDescriptor)netApDescriptor.clone(); + } + + /** + * Returns the message itself. + * + * @return a binary array containing the message data. + */ + byte[] getBytes() + { + return messageBytes; + } + + /** + * Returns the message length. + * + * @return a the length of the message. + */ + int getMessageLength() + { + return messageLength; + } + + + /** + * Returns the address and port of the host that sent the message + * @return the [address]:[port] pair that sent the message. + */ + InetSocketAddress getRemoteAddress() + { + return this.remoteAddress; + } + + /** + * Returns a descriptor of the access point that received the message. + * @return a descriptor of the access point that received the message. + */ + NetAccessPointDescriptor getNetAccessPoint() + { + return this.receivingAccessPoint; + } +} diff --git a/src/org/ice4j/stack/RequestListener.java b/src/org/ice4j/stack/RequestListener.java new file mode 100644 index 0000000..81a2547 --- /dev/null +++ b/src/org/ice4j/stack/RequestListener.java @@ -0,0 +1,24 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import org.ice4j.*; + +/** + *Title: Stun4J.
+ *Description: Simple Traversal of UDP Through NAT.
+ *Copyright: Copyright (c) 2003.
+ *Organisation:
Louis Pasteur University, Strasbourg, France.
+ *Network Research Team (http://www-r2.u-strasbg.fr).
+ * @author Emil Ivov + * @version 0.1 + */ + +public interface RequestListener +{ + public void requestReceived(StunMessageEvent evt); +} diff --git a/src/org/ice4j/stack/StunClientTransaction.java b/src/org/ice4j/stack/StunClientTransaction.java new file mode 100644 index 0000000..335fbfe --- /dev/null +++ b/src/org/ice4j/stack/StunClientTransaction.java @@ -0,0 +1,400 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.logging.*; +import java.io.*; + +import org.ice4j.*; +import org.ice4j.message.*; + +/** + * The ClientTransaction class retransmits (what a surprise) requests as + * specified by rfc 3489. + * + * Once formulated and sent, the client sends the Binding Request. Reliability + * is accomplished through request retransmissions. The ClientTransaction + * retransmits the request starting with an interval of 100ms, doubling + * every retransmit until the interval reaches 1.6s. Retransmissions + * continue with intervals of 1.6s until a response is received, or a + * total of 9 requests have been sent. If no response is received by 1.6 + * seconds after the last request has been sent, the client SHOULD + * consider the transaction to have failed. In other words, requests + * would be sent at times 0ms, 100ms, 300ms, 700ms, 1500ms, 3100ms, + * 4700ms, 6300ms, and 7900ms. At 9500ms, the client considers the + * transaction to have failed if no response has been received. + * + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov. + * @author Pascal Mogeri (contributed configuration of client transactions). + * @version 0.1 + */ + +class StunClientTransaction + implements Runnable +{ + private static final Logger logger = + Logger.getLogger(StunClientTransaction.class.getName()); + + /** + * The number of times to retransmit a request if no explicit value has been + * specified by org.ice4j.MAX_RETRANSMISSIONS. + */ + public static final int DEFAULT_MAX_RETRANSMISSIONS = 6; + + /** + * Maximum number of retransmissions. Once this number is reached and if no + * response is received after MAX_WAIT_INTERVAL miliseconds the request is + * considered unanswered. + */ + public int maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS; + + /** + * The number of miliseconds a client should wait before retransmitting, + * after it has sent a request for the first time. + */ + public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100; + + /** + * The number of miliseconds to wait before the first retansmission of the + * request. + */ + public int originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL; + + /** + * The maximum number of miliseconds a client should wait between + * consecutive retransmissionse, after it has sent a request for the first + * time. + */ + public static final int DEFAULT_MAX_WAIT_INTERVAL = 1600; + + /** + * The maximum wait interval. Once this interval is reached we should stop + * doubling its value. + */ + public int maxWaitInterval = DEFAULT_MAX_WAIT_INTERVAL; + + /** + * Indicates how many times we have retransmitted so fat. + */ + private int retransmissionCounter = 0; + + /** + * How much did we wait after our last retransmission. + */ + private int nextWaitInterval = originalWaitInterval; + + /** + * The StunProvider that created us. + */ + private StunProvider providerCallback = null; + + /** + * The request that we are retransmitting. + */ + private Request request = null; + + /** + * The destination of the request. + */ + private TransportAddress requestDestination= null; + + + /** + * The id of the transaction. + */ + private TransactionID transactionID = null; + + /** + * The NetAccessPoint through which the original request was sent an where + * we are supposed to be retransmitting. + */ + private NetAccessPointDescriptor apDescriptor = null; + + /** + * The instance to notify when a response has been received in the current + * transaction or when it has timed out. + */ + private ResponseCollector responseCollector = null; + + /** + * Specifies whether the transaction is active or not. + */ + private boolean cancelled = false; + + /** + * The date (in millis) when the next retransmission should follow. + */ + private long nextRetransmissionDate = -1; + + /** + * The thread that this transaction runs in. + */ + private Thread runningThread = null; + + /** + * Creates a client transaction + * @param providerCallback the provider that created us. + * @param request the request that we are living for. + * @param requestDestination the destination of the request. + * @param apDescriptor the access point through which we are supposed to + * @param responseCollector the instance that should receive this request's + * response. + * retransmit. + */ + public StunClientTransaction(StunProvider providerCallback, + Request request, + TransportAddress requestDestination, + NetAccessPointDescriptor apDescriptor, + ResponseCollector responseCollector) + { + this.providerCallback = providerCallback; + this.request = request; + this.apDescriptor = apDescriptor; + this.responseCollector = responseCollector; + this.requestDestination = requestDestination; + + initTransactionConfiguration(); + + this.transactionID = TransactionID.createTransactionID(); + try + { + request.setTransactionID(transactionID.getTransactionID()); + } + catch (StunException ex) + { + //Shouldn't happen so lets just through a runtime exception in + //case anything is real messed up + throw new IllegalArgumentException("The TransactionID class " + +"generated an invalid transaction ID"); + } + + runningThread = new Thread(this); + } + + /** + * Implements the retransmissions algorithm. Retransmits the request + * starting with an interval of 100ms, doubling every retransmit until the + * interval reaches 1.6s. Retransmissions continue with intervals of 1.6s + * until a response is received, or a total of 7 requests have been sent. + * If no response is received by 1.6 seconds after the last request has been + * sent, we consider the transaction to have failed. + */ + public void run() + { + runningThread.setName("CliTran"); + nextWaitInterval = originalWaitInterval; + + for (retransmissionCounter = 0; + retransmissionCounter < maxRetransmissions; + retransmissionCounter ++) + { + waitFor(nextWaitInterval); + //did someone tell us to get lost? + + if(cancelled) + return; + + if(nextWaitInterval < maxWaitInterval) + nextWaitInterval *= 2; + + try + { + sendRequest0(); + } + catch (Exception ex) + { + //I wonder whether we should notify anyone that a retransmission + //has failed + logger.log(Level.WARNING, + "A client tran retransmission failed", ex); + }; + } + + //before stating that a transaction has timeout-ed we should first wait + //for a reception of the response + if(nextWaitInterval < maxWaitInterval) + nextWaitInterval *= 2; + + waitFor(nextWaitInterval); + + responseCollector.processTimeout(); + providerCallback.removeClientTransaction(this); + + } + + /** + * Sends the request and schedules the first retransmission for after + * ORIGINAL_WAIT_INTERVAL and thus starts the retransmission algorithm. + * + * @throws IOException if an error occurs while sending message bytes + * through the network socket. + * @throws IllegalArgumentException if the apDescriptor references an + * access point that had not been installed, + * @throws StunException if message encoding fails, + * + */ + void sendRequest() + throws StunException, IllegalArgumentException, IOException + { + sendRequest0(); + + runningThread.start(); + } + + /** + * Simply calls the sendMessage method of the accessmanager. + * + * @throws IOException if an error occurs while sending message bytes + * through the network socket. + * @throws IllegalArgumentException if the apDescriptor references an + * access point that had not been installed, + * @throws StunException if message encoding fails, + */ + private void sendRequest0() + throws StunException, IllegalArgumentException, IOException + { + if(cancelled) + { + logger.finer("Trying to resend a cancelled transaction."); + return; + } + providerCallback.getNetAccessManager().sendMessage( + this.request, + apDescriptor, + requestDestination); + } + + /** + * Returns the request that was the reason for creating this transaction. + * @return the request that was the reason for creating this transaction. + */ + Request getRequest() + { + return this.request; + } + + /** + * Waits until next retransmission is due or until the transaction is + * cancelled (whichever comes first). + * + * @param millis the number of milliseconds to wait for. + */ + synchronized void waitFor(long millis) + { + try + { + wait(millis); + } + catch (InterruptedException ex) + { + logger.log(Level.FINE, "Interrupted", ex); + } + } + + + /** + * Cancels the transaction. Once this method is called the transaction is + * considered terminated and will stop retransmissions. + */ + synchronized void cancel() + { + this.cancelled = true; + notifyAll(); + } + + /** + * Dispatches the response then cancels itself and notifies the StunProvider + * for its termination. + * @param evt the event that contains the newly received message + */ + void handleResponse(StunMessageEvent evt) + { + String keepTran = System.getProperty( + "org.ice4j.KEEP_CLIENT_TRANS_AFTER_A_RESPONSE"); + + if( keepTran == null || !keepTran.trim().equalsIgnoreCase("true")) + this.cancel(); + + this.responseCollector.processResponse(evt); + } + + /** + * Returns the ID of the current transaction. + * + * @return the ID of the transaction. + */ + TransactionID getTransactionID() + { + return this.transactionID; + } + + /** + * Init transaction duration/retransmission parameters. + * (Mostly, contributed by Pascal Maugeri). + */ + private void initTransactionConfiguration() + { + //Max Retransmissions + String maxRetransmissionsStr = + System.getProperty("org.ice4j.MAX_RETRANSMISSIONS"); + + if(maxRetransmissionsStr != null + && maxRetransmissionsStr.trim().length() > 0){ + try + { + maxRetransmissions = Integer.parseInt(maxRetransmissionsStr); + } + catch (NumberFormatException e) + { + logger.log(Level.FINE, + "Failed to parse MAX_RETRANSMISSIONS", + e); + maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS; + } + } + + //Original Wait Interval + String originalWaitIntervalStr = + System.getProperty("org.ice4j.ORIGINAL_WAIT_INTERVAL"); + + if(originalWaitIntervalStr != null + && originalWaitIntervalStr.trim().length() > 0){ + try + { + originalWaitInterval + = Integer.parseInt(originalWaitIntervalStr); + } + catch (NumberFormatException e) + { + logger.log(Level.FINE, + "Failed to parse ORIGINAL_WAIT_INTERVAL", + e); + originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL; + } + } + + //Max Wait Interval + String maxWaitIntervalStr = + System.getProperty("org.ice4j.MAX_WAIT_INTERVAL"); + + if(maxWaitIntervalStr != null + && maxWaitIntervalStr.trim().length() > 0){ + try + { + maxWaitInterval = Integer.parseInt(maxWaitIntervalStr); + } + catch (NumberFormatException e) + { + logger.log(Level.FINE, "Failed to parse MAX_WAIT_INTERVAL", e); + maxWaitInterval = DEFAULT_MAX_WAIT_INTERVAL; + } + } + } +} diff --git a/src/org/ice4j/stack/StunProvider.java b/src/org/ice4j/stack/StunProvider.java new file mode 100644 index 0000000..3b44fbc --- /dev/null +++ b/src/org/ice4j/stack/StunProvider.java @@ -0,0 +1,322 @@ + +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.*; +import java.util.logging.*; +import java.io.*; + +import org.ice4j.*; +import org.ice4j.message.*; + +/** + * The StunProvider class is an implementation of a Stun Transaction Layer. STUN + * transactions are extremely simple and are only used to correlate requests and + * responses. In the Stun4J implementation it is the transaction layer that + * ensures reliable delivery. + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class StunProvider + implements MessageEventHandler +{ + private static final Logger logger = + Logger.getLogger(StunProvider.class.getName()); + + /** + * Stores active client transactions mapped against TransactionID-s. + */ + private HashtableOrganisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +class StunServerTransaction + implements Runnable +{ + /** + * The time that we keep server transactions active. + */ + private long transactionLifetime = 16000; + + /** + * The StunProvider that created us. + */ + private StunProvider providerCallback = null; + + /** + * The source of the transaction request. + */ + private TransportAddress responseDestination = null; + + /** + * The response sent in response to the request. + */ + private Response response = null; + + /** + * The ap descriptor used when sending the response + */ + private NetAccessPointDescriptor apDescriptor = null; + + /** + * The id of the transaction. + */ + private TransactionID transactionID = null; + + /** + * The date (in millis) when the next retransmission should follow. + */ + private long expirationDate = -1; + + /** + * The thread that this transaction runs in. + */ + private Thread runningThread = null; + + /** + * Determines whether or not the transaction has expired. + */ + private boolean expired = true; + + /** + * Determines whether or not the transaction is in a retransmitting state. + * In other words whether a response has already been sent once to the + * transaction request. + */ + private boolean isRetransmitting = false; + + /** + * Creates a server transaction + * @param providerCallback the provider that created us. + * @param tranID the transaction id contained by the request that was the + * cause for this transaction. + */ + public StunServerTransaction(StunProvider providerCallback, + TransactionID tranID) + { + this.providerCallback = providerCallback; + + this.transactionID = tranID; + + runningThread = new Thread(this); + } + + /** + * Start the transaction. This launches the countdown to the moment the + * transaction would expire. + */ + public void start() + { + expired = false; + runningThread.start(); + } + + /** + * Actually this method is simply a timer waiting for the server transaction + * lifetime to come to an end. + */ + public void run() + { + runningThread.setName("ServTran"); + + schedule(transactionLifetime); + waitNextScheduledDate(); + + //let's get lost + expire(); + providerCallback.removeServerTransaction(this); + } + + /** + * Sends the specified response through thesendThrough
+ * NetAccessPoint descriptor to the specified destination and changes
+ * the transaction's state to retransmitting.
+ *
+ * @param response the response to send the transaction to.
+ * @param sendThrough the NetAccessPoint through which the response is to
+ * be sent
+ * @param sendTo the destination of the response.
+ *
+ * @throws IOException if an error occurs while sending message bytes
+ * through the network socket.
+ * @throws IllegalArgumentException if the apDescriptor references an
+ * access point that had not been installed,
+ * @throws StunException if message encoding fails,
+ */
+ void sendResponse(Response response,
+ NetAccessPointDescriptor sendThrough,
+ TransportAddress sendTo)
+ throws StunException,
+ IOException,
+ IllegalArgumentException
+ {
+ if(!isRetransmitting){
+ this.response = response;
+ //the transaction id might already have been set, but its our job
+ //to make sure of that
+ response.setTransactionID(this.transactionID.getTransactionID());
+ this.apDescriptor = sendThrough;
+ this.responseDestination = sendTo;
+ }
+
+ isRetransmitting = true;
+ retransmitResponse();
+ }
+
+ /**
+ * Retransmits the response that was originally sent to the request that
+ * caused this transaction.
+ *
+ * @throws IOException if an error occurs while sending message bytes
+ * through the network socket.
+ * @throws IllegalArgumentException if the apDescriptor references an
+ * access point that had not been installed,
+ * @throws StunException if message encoding fails,
+ */
+ void retransmitResponse()
+ throws StunException,
+ IOException,
+ IllegalArgumentException
+ {
+ //don't retransmit if we are expired or if the user application
+ //hasn't yet transmitted a first response
+ if(expired || !isRetransmitting)
+ return;
+
+ providerCallback.getNetAccessManager().sendMessage(response,
+ apDescriptor,
+ responseDestination);
+ }
+
+ /**
+ * Waits until next retransmission is due or until the transaction is
+ * cancelled (whichever comes first).
+ */
+ synchronized void waitNextScheduledDate()
+ {
+ long current = System.currentTimeMillis();
+ while(expirationDate - current > 0)
+ {
+ try
+ {
+ wait(expirationDate - current);
+ }
+ catch (InterruptedException ex)
+ {
+ }
+
+ //did someone ask us to get lost?
+ if(expired)
+ return;
+ current = System.currentTimeMillis();
+ }
+ }
+
+ /**
+ * Sets the expiration date for this server transaction.
+ * @param timeout the number of millis to wait before expiration.
+ */
+ void schedule(long timeout)
+ {
+ this.expirationDate = System.currentTimeMillis() + timeout;
+ }
+
+ /**
+ * Cancels the transaction. Once this method is called the transaction is
+ * considered terminated and will stop retransmissions.
+ */
+ synchronized void expire()
+ {
+ this.expired = true;
+ notifyAll();
+ }
+
+
+ /**
+ * Returns the ID of the current transaction.
+ *
+ * @return the ID of the transaction.
+ */
+ TransactionID getTransactionID()
+ {
+ return this.transactionID;
+ }
+
+ /**
+ * Specifies whether this server transaction is in the retransmitting state.
+ * Or in other words - has it already sent a first response or not?
+ * @return boolean
+ */
+ boolean isReransmitting()
+ {
+ return isRetransmitting;
+ }
+}
diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java
new file mode 100644
index 0000000..203cb20
--- /dev/null
+++ b/src/org/ice4j/stack/StunStack.java
@@ -0,0 +1,142 @@
+/*
+ * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.ice4j.stack;
+
+import java.net.DatagramSocket;
+import java.io.*;
+
+import org.ice4j.*;
+import org.ice4j.message.*;
+
+/**
+ * The entry point to the Stun4J stack. The class is used to start, stop and
+ * configure the stack.
+ *
+ * Organisation: Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ +public class StunStack +{ + /** + * We shouldn't need more than one stack in the same application. + */ + private static StunStack stackInstance = null; + + /** + * Our network gateway. + */ + private NetAccessManager netAccessManager = null; + + /** + * The number of threads to split our flow in. + */ + public static final int DEFAULT_THREAD_POOL_SIZE = 3; + + private StunProvider stunProvider = null; + + /** + * Returns a reference to the singleton StunStack insance. If the stack + * had not yet been initialised, a new instance will be created. + * + * @return a reference to the StunStack. + */ + public static synchronized StunStack getInstance() + { + if (stackInstance == null) + stackInstance = new StunStack(); + + return stackInstance; + } + + //----------------------- PUBLIC INTERFACE --------------------------------- + + + /** + * Sets the number of Message processors running in the same time. + * + * @param threadPoolSize the number of message process threads to run. + * @throws StunException + */ + public void setThreadPoolSize(int threadPoolSize) + throws StunException + { + netAccessManager.setThreadPoolSize(threadPoolSize); + } + + /** + * Creates and starts the specified Network Access Point. + * + * @param apDescriptor A descriptor containing the address and port of the + * STUN server that the newly created access point will communicate with. + * @throws IOException if we fail to bind a datagram socket on the specified + * address and port (NetAccessPointDescriptor) + */ + public void installNetAccessPoint(NetAccessPointDescriptor apDescriptor) + throws IOException + { + netAccessManager.installNetAccessPoint(apDescriptor); + } + + /** + * Creates and starts the specified Network Access Point based on the specified + * socket and returns a relevant descriptor. + * + * @param sock The socket that the new access point should represent. + * @throws IOException if we fail to setup the socket. + * @return a descriptor of the newly created access point. + */ + public NetAccessPointDescriptor installNetAccessPoint(DatagramSocket sock) + throws IOException + { + return netAccessManager.installNetAccessPoint(sock); + } + + + /** + * Stops and deletes the specified access point. + * @param apDescriptor the access point to remove + */ + public void removeNetAccessPoint(NetAccessPointDescriptor apDescriptor) + { + netAccessManager.removeNetAccessPoint(apDescriptor); + } + + + + /** + * Returns a StunProvider instance to be used for sending and receiving + * mesages. + * + * @return an instance of StunProvider + */ + public StunProvider getProvider() + { + return stunProvider; + } + + //-------------------- internal stuff -------------------------------------- + /** + * Private constructor as we want a singleton pattern. + */ + private StunStack() + { + stunProvider = new StunProvider(this); + + netAccessManager = new NetAccessManager(stunProvider); + } + + /** + * Returns the currently active instance of NetAccessManager. + * @return the currently active instance of NetAccessManager. + */ + NetAccessManager getNetAccessManager() + { + return netAccessManager; + } +} diff --git a/src/org/ice4j/stack/TransactionID.java b/src/org/ice4j/stack/TransactionID.java new file mode 100644 index 0000000..a85e2a3 --- /dev/null +++ b/src/org/ice4j/stack/TransactionID.java @@ -0,0 +1,172 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stack; + +import java.util.Random; +import java.util.Arrays; + +/** + * This class encapsulates a STUN transaction ID. It is useful for storing + * transaction ids in collection objects as it implements the equals method. + * It also provies a utility for creating unique transaction ids. + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +class TransactionID +{ + /** + * The id itself + */ + private byte transactionID[] = new byte[12]; + + /** + * The object to use to generate the rightmost 8 bytes of the id. + */ + private static Random random = new Random(System.currentTimeMillis()); + + /** + * A hashcode for hashtable storage. + */ + private int hashCode = 0; + + private TransactionID() + { + } + + /** + * Creates a transaction id object.The transaction id itself is genereated + * using the folloing algorithm: + * + * The first 6 bytes of the id are given the value of System.currentTimeMillis() + * Putting the right most bits first so that we get a more optimized equals() + * method. + * + * @return A TransactionID object with a unique transaction id. + */ + static TransactionID createTransactionID() + { + TransactionID tid = new TransactionID(); + + long left = System.currentTimeMillis();//the first 6 bytes of the id + long right = random.nextLong();//the last 6 bytes of the id + + for(int i = 0; i < 6; i++) + { + tid.transactionID[i] = (byte)((left >> (i*8))& 0xFFl); + tid.transactionID[i+6] = (byte)((right >> (i*8))& 0xFFl); + } + + //calculate hashcode for Hashtable storage. + tid.hashCode = (tid.transactionID[3] << 24 & 0xFF000000) + | (tid.transactionID[2] << 16 & 0x00FF0000) + | (tid.transactionID[1] << 8 & 0x0000FF00) + | (tid.transactionID[0] & 0x000000FF); + + return tid; + } + + /** + * Creates a transaction identifier object with the specified id. + * @param transactionID the id to give to the new TransactionID + * @return a new TransactionID object with the specified id value; + */ + static TransactionID createTransactionID(byte[] transactionID) + { + TransactionID tid = new TransactionID(); + + System.arraycopy(transactionID, 0, tid.transactionID, 0, 12); + + //calculate hashcode for Hashtable storage. + tid.hashCode = (tid.transactionID[3] << 24 & 0xFF000000) + | (tid.transactionID[2] << 16 & 0x00FF0000) + | (tid.transactionID[1] << 8 & 0x0000FF00) + | (tid.transactionID[0] & 0x000000FF); + + + return tid; + } + + + /** + * Returns the transaction id byte array (length 12). + * @return the transaction ID byte array. + */ + public byte[] getTransactionID() + { + return transactionID; + } + + /** + * Compares two TransactionID objects. + * @param obj the object to compare with. + * @return true if the objects are equal and false otherwise. + */ + public boolean equals(Object obj) + { + + if( obj == null + || !(obj instanceof TransactionID)) + return false; + + if(this == obj) + return true; + + byte targetBytes[] = ((TransactionID)obj).transactionID; + + return Arrays.equals(transactionID, targetBytes); + } + + /** + * Compares the specified byte array with this transaction id. + * @param targetID the id to compare with ours. + * @return true if targetID matches this transaction id. + */ + public boolean equals(byte[] targetID) + { + return Arrays.equals(transactionID, targetID); + } + + /** + * Returns the first four bytes of the transactionID to ensure proper + * retrieval from hashtables; + * @return the hashcode of this object - as advised by the Java Platform + * Specification + */ + public int hashCode() + { + return hashCode; + } + + /** + * Returns a string representation of the ID + * @return a hex string representing the id + */ + public String toString() + { + StringBuffer idStr = new StringBuffer(); + + for(int i = 0; i < transactionID.length; i++) + { + idStr.append("0x"); + if((transactionID[i]&0xFF) <= 15) + { + idStr.append("0"); + } + + idStr.append(Integer.toHexString(transactionID[i]&0xff).toUpperCase()); + + if(i < transactionID.length) + idStr.append(" "); + } + + return idStr.toString(); + } +} diff --git a/src/org/ice4j/stunclient/BlockingRequestSender.java b/src/org/ice4j/stunclient/BlockingRequestSender.java new file mode 100644 index 0000000..f73fc97 --- /dev/null +++ b/src/org/ice4j/stunclient/BlockingRequestSender.java @@ -0,0 +1,126 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stunclient; + +import java.util.logging.*; +import java.io.*; + +import org.ice4j.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; + +/** + * A utility used to flatten the multithreaded architecture of the Stack + * and execute the discovery process in a synchronized manner. Roughly what + * happens here is: + * + * ApplicationThread: + * sendMessage() + * wait(); + * + * StackThread: + * processMessage/Timeout() + * { + * saveMessage(); + * notify(); + * } + * + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ +class BlockingRequestSender + implements ResponseCollector +{ + private static final Logger logger = + Logger.getLogger(BlockingRequestSender.class.getName()); + + private StunProvider stunProvider = null; + private NetAccessPointDescriptor apDescriptor = null; + + StunMessageEvent responseEvent = null; + + private boolean ended = false; + private Object sendLock = new Object(); + + BlockingRequestSender(StunProvider stunProvider, + NetAccessPointDescriptor apDescriptor) + { + this.stunProvider = stunProvider; + this.apDescriptor = apDescriptor; + } + + /** + * Saves the message event and notifies the discoverer thread so that + * it may resume. + * @param evt the newly arrived message event. + */ + public synchronized void processResponse(StunMessageEvent evt) + { + synchronized(sendLock){ + this.responseEvent = evt; + ended = true; + notifyAll(); + } + } + + /** + * Notifies the discoverer thread when a message has timeouted so that + * it may resume and consider it as unanswered. + */ + public synchronized void processTimeout() + { + synchronized(sendLock){ + ended = true; + notifyAll(); + } + } + + /** + * Sends the specified request and blocks until a response has been + * received or the request transaction has timed out. + * @param request the reuqest to send + * @param serverAddress the request destination address + * @return the event encapsulating the response or null if no response + * has been received. + * + * @throws IOException if an error occurs while sending message bytes + * through the network socket. + * @throws IllegalArgumentException if the apDescriptor references an + * access point that had not been installed, + * @throws StunException if message encoding fails, + */ + public synchronized StunMessageEvent sendRequestAndWaitForResponse( + Request request, + TransportAddress serverAddress) + throws StunException, + IOException + { + synchronized(sendLock){ + stunProvider.sendRequest(request, serverAddress, apDescriptor, + BlockingRequestSender.this); + } + + ended = false; + while(!ended){ + try + { + wait(); + } + catch (InterruptedException ex) + { + logger.log(Level.WARNING, "Interrupted", ex); + } + } + StunMessageEvent res = responseEvent; + responseEvent = null; //prepare for next message + + return res; + } +} diff --git a/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java new file mode 100644 index 0000000..10c3591 --- /dev/null +++ b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java @@ -0,0 +1,482 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stunclient; + +import java.net.*; + +import java.util.logging.*; +import java.io.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; + +/** + *+ * This class implements the STUN Discovery Process as described by section 10.1 + * of rfc 3489. + *
+ * The flow makes use of three tests. In test I, the client sends a + * STUN Binding Request to a server, without any flags set in the + * CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. + * This causes the server to send the response back to the address and + * port that the request came from. In test II, the client sends a + * Binding Request with both the "change IP" and "change port" flags + * from the CHANGE-REQUEST attribute set. In test III, the client sends + * a Binding Request with only the "change port" flag set. + *
+ * The client begins by initiating test I. If this test yields no + * response, the client knows right away that it is not capable of UDP + * connectivity. If the test produces a response, the client examines + * the MAPPED-ADDRESS attribute. If this address and port are the same + * as the local IP address and port of the socket used to send the + * request, the client knows that it is not natted. It executes test + * II. + *
+ * If a response is received, the client knows that it has open access + * to the Internet (or, at least, its behind a firewall that behaves + * like a full-cone NAT, but without the translation). If no response + * is received, the client knows its behind a symmetric UDP firewall. + *
+ * In the event that the IP address and port of the socket did not match + * the MAPPED-ADDRESS attribute in the response to test I, the client + * knows that it is behind a NAT. It performs test II. If a response + * is received, the client knows that it is behind a full-cone NAT. If + * no response is received, it performs test I again, but this time, + * does so to the address and port from the CHANGED-ADDRESS attribute + * from the response to test I. If the IP address and port returned in + * the MAPPED-ADDRESS attribute are not the same as the ones from the + * first test I, the client knows its behind a symmetric NAT. If the + * address and port are the same, the client is either behind a + * restricted or port restricted NAT. To make a determination about + * which one it is behind, the client initiates test III. If a response + * is received, its behind a restricted NAT, and if no response is + * received, its behind a port restricted NAT. + *
+ * This procedure yields substantial information about the operating + * condition of the client application. In the event of multiple NATs + * between the client and the Internet, the type that is discovered will + * be the type of the most restrictive NAT between the client and the + * Internet. The types of NAT, in order of restrictiveness, from most + * to least, are symmetric, port restricted cone, restricted cone, and + * full cone. + *
+ * Typically, a client will re-do this discovery process periodically to + * detect changes, or look for inconsistent results. It is important to + * note that when the discovery process is redone, it should not + * generally be done from the same local address and port used in the + * previous discovery process. If the same local address and port are + * reused, bindings from the previous test may still be in existence, + * and these will invalidate the results of the test. Using a different + * local address and port for subsequent tests resolves this problem. + * An alternative is to wait sufficiently long to be confident that the + * old bindings have expired (half an hour should more than suffice). + *
+ *
Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class NetworkConfigurationDiscoveryProcess +{ + private static final Logger logger = + Logger.getLogger(NetworkConfigurationDiscoveryProcess.class.getName()); + /** + * Indicates whether the underlying stack has been initialized and started + * and that the discoverer is operational. + */ + private boolean started = false; + + /** + * The stack to use for STUN communication. + */ + private StunStack stunStack = null; + + /** + * The provider to send our messages through + */ + private StunProvider stunProvider = null; + + /** + * The point where we'll be listening. + */ + private NetAccessPointDescriptor apDescriptor = null; + + /** + * The address of the stun server + */ + private TransportAddress serverAddress = null; + + /** + * A utility used to flatten the multithreaded architecture of the Stack + * and execute the discovery process in a synchronized manner + */ + private BlockingRequestSender requestSender = null; + + /** + * Creates a StunAddressDiscoverer. In order to use it one must start the + * discoverer. + * @param localAddress the address where the stach should bind. + * @param serverAddress the address of the server to interrogate. + */ + public NetworkConfigurationDiscoveryProcess(TransportAddress localAddress, + TransportAddress serverAddress) + { + apDescriptor = new NetAccessPointDescriptor(localAddress); + this.serverAddress = serverAddress; + } + + /** + * Creates a StunAddressDiscoverer. In order to use it one must start the + * discoverer. + * @param apDescriptor the address where the stach should bind. + * @param serverAddress the address of the server to interrogate. + */ + public NetworkConfigurationDiscoveryProcess(NetAccessPointDescriptor apDescriptor, + TransportAddress serverAddress) + { + this.apDescriptor = apDescriptor; + this.serverAddress = serverAddress; + + } + + /** + * Shuts down the underlying stack and prepares the object for garbage + * collection. + */ + public void shutDown() + { + stunStack = null; + stunProvider = null; + apDescriptor = null; + requestSender = null; + + this.started = false; + + } + + /** + * Puts the discoverer into an operational state. + * @throws IOException if we fail to bind. + * @throws StunException if the stun4j stack fails start for some reason. + */ + public void start() + throws IOException, StunException + { + stunStack = StunStack.getInstance(); + + stunStack.installNetAccessPoint(apDescriptor); + + stunProvider = stunStack.getProvider(); + + requestSender = new BlockingRequestSender(stunProvider, apDescriptor); + + started = true; + } + + /** + * Implements the discovery process itself (see class description). + * @return a StunDiscoveryReport containing details about the network + * configuration of the host where the class is executed. + * + * @throws StunException ILLEGAL_STATE if the discoverer has not been started + * @throws IOException if a failure occurs while executing the discovery + * algorithm. + */ + public StunDiscoveryReport determineAddress() + throws StunException, IOException + { + checkStarted(); + StunDiscoveryReport report = new StunDiscoveryReport(); + StunMessageEvent evt = doTestI(serverAddress); + + if(evt == null) + { + //UDP Blocked + report.setNatType(StunDiscoveryReport.UDP_BLOCKING_FIREWALL); + return report; + } + else + { + TransportAddress mappedAddress + =((MappedAddressAttribute)evt.getMessage() + .getAttribute(Attribute.MAPPED_ADDRESS)).getAddress(); + + if(mappedAddress == null) + { + /* maybe we contact a STUNbis server and which do not + * understand our request. + */ + logger.info("Failed to do the network discovery"); + return null; + } + + logger.info("mapped address is="+mappedAddress + +", name=" + mappedAddress.getHostAddress()); + + TransportAddress backupServerAddress + =((ChangedAddressAttribute) evt.getMessage() + .getAttribute(Attribute.CHANGED_ADDRESS)).getAddress(); + + logger.info("backup server address is="+backupServerAddress + + ", name=" + backupServerAddress.getHostAddress()); + + report.setPublicAddress(mappedAddress); + if (mappedAddress.equals(apDescriptor.getAddress())) + { + evt = doTestII(serverAddress); + if (evt == null) + { + //Sym UDP Firewall + report.setNatType(StunDiscoveryReport + .SYMMETRIC_UDP_FIREWALL); + return report; + } + else + { + //open internet + report.setNatType(StunDiscoveryReport.OPEN_INTERNET); + return report; + + } + } + else + { + evt = doTestII(serverAddress); + if (evt == null) + { + evt = doTestI(backupServerAddress); + if(evt == null) + { + logger.info("Failed to receive a response from " + +"backup stun server!"); + return report; + } + TransportAddress mappedAddress2 = + ((MappedAddressAttribute)evt.getMessage(). + getAttribute(Attribute.MAPPED_ADDRESS)).getAddress(); + if(mappedAddress.equals(mappedAddress2)) + { + evt = doTestIII(serverAddress); + if(evt == null) + { + //port restricted cone + report.setNatType(StunDiscoveryReport + .PORT_RESTRICTED_CONE_NAT); + return report; + } + else + { + //restricted cone + report.setNatType(StunDiscoveryReport + .RESTRICTED_CONE_NAT); + return report; + + } + } + else + { + //Symmetric NAT + report.setNatType(StunDiscoveryReport.SYMMETRIC_NAT); + return report; + } + } + else + { + //full cone + report.setNatType(StunDiscoveryReport.FULL_CONE_NAT); + return report; + } + } + } + + } + + /** + * Sends a binding request to the specified server address. Both change IP + * and change port flags are set to false. + * @param serverAddress the address where to send the bindingRequest. + * @return The returned message encapsulating event or null if no message + * was received. + * + * @throws StunException if an exception occurs while sending the messge + * @throws IOException if an error occurs while sending bytes through + * the socket. + */ + private StunMessageEvent doTestI(TransportAddress serverAddress) + throws IOException, StunException + { + Request request = MessageFactory.createBindingRequest(); + +/* + ChangeRequestAttribute changeRequest + = (ChangeRequestAttribute)request + .getAttribute(Attribute.CHANGE_REQUEST); + changeRequest.setChangeIpFlag(false); + changeRequest.setChangePortFlag(false); +*/ + /* add a change request attribute */ + ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute(); + changeRequest.setChangeIpFlag(false); + changeRequest.setChangePortFlag(false); + request.addAttribute(changeRequest); + + StunMessageEvent evt = null; + try + { + evt + = requestSender.sendRequestAndWaitForResponse( + request, serverAddress); + } + catch (StunException ex) + { + //this shouldn't happen since we are the ones that created the + //request + logger.log(Level.SEVERE, + "Internal Error. Failed to encode a message", + ex); + return null; + } + + if(evt != null) + logger.info("TEST I res="+evt.getRemoteAddress().toString() + +" - "+ evt.getRemoteAddress().getHostAddress()); + else + logger.info("NO RESPONSE received to TEST I."); + return evt; + } + + /** + * Sends a binding request to the specified server address with both change + * IP and change port flags are set to true. + * @param serverAddress the address where to send the bindingRequest. + * @return The returned message encapsulating event or null if no message + * was received. + * + * @throws StunException if an exception occurs while sending the messge + * @throws IOException if an exception occurs while executing the algorithm. + */ + private StunMessageEvent doTestII(TransportAddress serverAddress) + throws StunException, IOException + { + Request request = MessageFactory.createBindingRequest(); + + /* ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */ + /* add a change request attribute */ + ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute(); + changeRequest.setChangeIpFlag(true); + changeRequest.setChangePortFlag(true); + request.addAttribute(changeRequest); + + StunMessageEvent evt + = requestSender.sendRequestAndWaitForResponse(request, + serverAddress); + if(evt != null) + logger.info("Test II res="+evt.getRemoteAddress().toString() + +" - "+ evt.getRemoteAddress().getHostAddress()); + else + logger.info("NO RESPONSE received to Test II."); + + return evt; + } + + /** + * Sends a binding request to the specified server address with only change + * port flag set to true and change IP flag - to false. + * @param serverAddress the address where to send the bindingRequest. + * @return The returned message encapsulating event or null if no message + * was received. + * @throws StunException if an exception occurs while sending the messge + * @throws IOException if an exception occurs while sending bytes through + * the socket. + */ + private StunMessageEvent doTestIII(TransportAddress serverAddress) + throws StunException, IOException + { + Request request = MessageFactory.createBindingRequest(); + + /* ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */ + /* add a change request attribute */ + ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute(); + changeRequest.setChangeIpFlag(false); + changeRequest.setChangePortFlag(true); + request.addAttribute(changeRequest); + + StunMessageEvent evt = requestSender.sendRequestAndWaitForResponse( + request, serverAddress); + if(evt != null) + logger.info("Test III res="+evt.getRemoteAddress().toString() + +" - "+ evt.getRemoteAddress().getHostAddress()); + else + logger.info("NO RESPONSE received to Test III."); + + return evt; + } + + /** + * Makes shure the discoverer is operational and throws an + * StunException.ILLEGAL_STATE if that is not the case. + * @throws StunException ILLEGAL_STATE if the discoverer is not operational. + */ + private void checkStarted() + throws StunException + { + if(!started) + throw new StunException(StunException.ILLEGAL_STATE, + "The Discoverer must be started before " + +"launching the discovery process!"); + } + + //---------- main + /** + * Runs the discoverer and shows a message dialog with the returned report. + * @param args args[0] - stun server address, args[1] - port. in the case of + * no args - defaults are provided. + * @throws java.lang.Exception if an exception occurrs during the discovery + * process. + */ +/* + public static void main(String[] args) + throws Exception + { + StunAddress localAddr = null; + StunAddress serverAddr = null; + if(args.length == 4) + { + localAddr = new StunAddress(args[2], + Integer.valueOf(args[3]).intValue()); + serverAddr = new StunAddress(args[0], + Integer.valueOf(args[1]).intValue()); + } + else + { + localAddr = new StunAddress(InetAddress.getLocalHost(), 5678); + serverAddr = new StunAddress("stun01bak.sipphone.com.", 3479); + } + NetworkConfigurationDiscoveryProcess addressDiscovery + = new NetworkConfigurationDiscoveryProcess(localAddr, serverAddr); + + addressDiscovery.start(); + StunDiscoveryReport report = addressDiscovery.determineAddress(); + System.out.println(report); + } +*/ +} +/** + * Sample run results. + * + * TEST I res=/69.0.209.22:3478 - stun01bak.sipphone.com + * mapped address is=193.108.24.226./193.108.24.226:5678, name=193.108.24.226. + * backup server address is=69.0.208.27./69.0.208.27:3478, name=69.0.208.27. + * NO RESPONSE received to Test II. + * TEST I res=/69.0.208.27:3478 - stun01.sipphone.com + * NO RESPONSE received to Test III. + * The detected network configuration is: Port Restricted Cone NAT + * Your mapped public address is: 193.108.24.226./193. + */ diff --git a/src/org/ice4j/stunclient/SimpleAddressDetector.java b/src/org/ice4j/stunclient/SimpleAddressDetector.java new file mode 100644 index 0000000..bb13dd3 --- /dev/null +++ b/src/org/ice4j/stunclient/SimpleAddressDetector.java @@ -0,0 +1,269 @@ +/* + * Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.stunclient; + +import java.net.DatagramSocket; +import java.io.*; +import java.util.logging.*; +import java.net.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; + +/** + * The class provides basic means of discovering a public IP address. All it + * does is send a binding request through a specified port and return the + * mapped address it got back or null if there was no reponse. + * + *Organisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class SimpleAddressDetector +{ + private static final Logger logger + = Logger.getLogger(SimpleAddressDetector.class.getName()); + /** + * The stack to use for STUN communication. + */ + private StunStack stunStack = null; + + /** + * The provider to send our messages through + */ + private StunProvider stunProvider = null; + + /** + * The address of the stun server + */ + private TransportAddress serverAddress = null; + + /** + * A utility used to flatten the multithreaded architecture of the Stack + * and execute the discovery process in a synchronized manner + */ + private BlockingRequestSender requestSender = null; + + /** + * Creates a StunAddressDiscoverer. In order to use it one must start the + * discoverer. + * @param serverAddress the address of the server to interrogate. + */ + public SimpleAddressDetector(TransportAddress serverAddress) + { + this.serverAddress = serverAddress; + } + + /** + * Returns the server address that this detector is using to run stun + * queries. + * + * @return StunAddress the address of the stun server that we are running + * stun queries against. + */ + public TransportAddress getServerAddress() + { + return serverAddress; + } + + /** + * Shuts down the underlying stack and prepares the object for garbage + * collection. + */ + public void shutDown() + { + stunStack = null; + stunProvider = null; + requestSender = null; + } + + /** + * Puts the discoverer into an operational state. + */ + public void start() + { + stunStack = StunStack.getInstance(); + + stunProvider = stunStack.getProvider(); + } + + + /** + * Creates a listening point from the following address and attempts to + * discover how it is mapped so that using inside the application is possible. + * @param address the [address]:[port] pair where ther request should be + * sent from. + * @return a StunAddress object containing the mapped address or null if + * discovery failed. + * @throws IOException if address is already bound. + */ + public TransportAddress getMappingFor(TransportAddress address) + throws IOException + { + NetAccessPointDescriptor apDesc = new NetAccessPointDescriptor(address); + + stunStack.installNetAccessPoint(apDesc); + + requestSender = new BlockingRequestSender(stunProvider, apDesc); + StunMessageEvent evt = null; + try + { + try + { + evt = requestSender.sendRequestAndWaitForResponse( + MessageFactory.createBindingRequest(), serverAddress); + } + catch (StunException ex) + { + //a stun exception is thrown if there is a problem with + //the message. The message here is constructed by ourselves + //so we don't need to tell the user ... just log and throw + //a runtime exception + logger.log( Level.SEVERE, + "Internal Error. Apparently we did not properly " + +"construct a message", + ex); + } + } + finally + { + //free the port to allow the application to use it. + stunStack.removeNetAccessPoint(apDesc); + } + + if(evt != null) + { + Response res = (Response)evt.getMessage(); + + /* in classic STUN, the response contains a MAPPED-ADDRESS */ + MappedAddressAttribute maAtt = + (MappedAddressAttribute) + res.getAttribute(Attribute.MAPPED_ADDRESS); + if(maAtt != null) + { + return maAtt.getAddress(); + } + + /* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */ + XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res.getAttribute(Attribute.XOR_MAPPED_ADDRESS); + if(xorAtt != null) + { + byte xoring[] = new byte[16]; + + System.arraycopy(Message.MAGIC_COOKIE, 0, xoring, 0, 4); + System.arraycopy(res.getTransactionID(), 0, xoring, 4, 12); + + return xorAtt.applyXor(xoring); + } + } + + return null; + } + + /** + * Creates a listening point for the specified socket and attempts to + * discover how its local address is NAT mapped. + * @param socket the socket whose address needs to be resolved. + * @return a StunAddress object containing the mapped address or null if + * discovery failed. + * + * @throws IOException if something fails along the way. + * @throws BindException if we cannot bind the socket. + */ + public TransportAddress getMappingFor(DatagramSocket socket) + throws IOException, BindException + { + NetAccessPointDescriptor apDesc + = stunStack.installNetAccessPoint(socket); + + requestSender = new BlockingRequestSender(stunProvider, apDesc); + StunMessageEvent evt = null; + try + { + evt = requestSender.sendRequestAndWaitForResponse( + MessageFactory.createBindingRequest(), serverAddress); + } + catch(StunException exc) + { + //this shouldn't be happening since we are the one that constructed + //the request, so let's catch it here and not oblige users to handle + //exception they are not responsible for. + logger.log(Level.SEVERE, "Internal Error. We apparently " + +"constructed a faulty request.", exc); + return null; + } + finally + { + stunStack.removeNetAccessPoint(apDesc); + } + + if(evt != null) + { + Response res = (Response)evt.getMessage(); + + /* in classic STUN, the response contains a MAPPED-ADDRESS */ + MappedAddressAttribute maAtt = + (MappedAddressAttribute) + res.getAttribute(Attribute.MAPPED_ADDRESS); + if(maAtt != null) + { + return maAtt.getAddress(); + } + + /* in STUN bis, the response contains a XOR-MAPPED-ADDRESS */ + XorMappedAddressAttribute xorAtt = (XorMappedAddressAttribute)res.getAttribute(Attribute.XOR_MAPPED_ADDRESS); + if(xorAtt != null) + { + byte xoring[] = new byte[16]; + + System.arraycopy(Message.MAGIC_COOKIE, 0, xoring, 0, 4); + System.arraycopy(res.getTransactionID(), 0, xoring, 4, 12); + + return xorAtt.applyXor(xoring); + } + } + + return null; + } + + + /** + * Creates a listening point from the specified port and attempts to + * discover how it is being mapped. + * + * @param port the local port where to send the request from. + * @return a StunAddress object containing the mapped address or null if + * discovery failed. + * + * @throws IOException if the port is already bound. + */ + public TransportAddress getMappingFor(int port) + throws IOException + { + return getMappingFor(new TransportAddress(port)); + } + + +/* + public static void main(String[] args) + throws Exception + { + SimpleAddressDetector detector = new SimpleAddressDetector( + new StunAddress("stun01.sipphone.com", 3478)); + detector.start(); + StunAddress mappedAddr = detector.getMappingFor(5060); + + System.out.println("address is " + mappedAddr); + + detector.shutDown(); + } +*/ +} diff --git a/src/org/ice4j/stunclient/StunClient.java b/src/org/ice4j/stunclient/StunClient.java new file mode 100755 index 0000000..8220661 --- /dev/null +++ b/src/org/ice4j/stunclient/StunClient.java @@ -0,0 +1,203 @@ +package org.ice4j.stunclient; + +import java.io.IOException; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; +import org.ice4j.stunclient.*; + + +/** + * The interface given to the ICE agent to send STUN requests + * and receive responses + * + * @author Namal Senarathne + * + * TODO : The constructor must have a reference to ICE Agent + */ +public class StunClient + implements ResponseCollector +{ + + private final Logger logger = + Logger.getLogger(StunClient.class.getName()); + + /** + * The STUN stack + */ + private StunStack stunStack = null; + + /** + * The Stun Provider from the stack + */ + private StunProvider stunProvider = null; + + /** + * The HashMap used to store the sent requests and correlate between + * the responses and the requests. + * This data structure is used only when sendStunRequest message is invoked + */ + private HashMapOrganisation:
Louis Pasteur University, Strasbourg, France
+ *Network Research Team (http://www-r2.u-strasbg.fr)
+ * @author Emil Ivov + * @version 0.1 + */ + +public class StunDiscoveryReport +{ + /** + * Indicates that NAT detection has failed or not yet initiated. + */ + public static final String UNKNOWN = "Unknown Network Configuration"; + + /** + * Means, there's no NAT or firewall. + */ + public static final String OPEN_INTERNET = "Open Internet Configuration"; + + /** + * Indicates that UDP communication is not possible. + */ + public static final String UDP_BLOCKING_FIREWALL = "UDP Blocking Firewall"; + + /** + * Means we are behind a symmetric udp firewall. + */ + public static final String SYMMETRIC_UDP_FIREWALL= "Symmetric UDP Firewall"; + + /** + * NAT type is full cone. + */ + public static final String FULL_CONE_NAT = "Full Cone NAT"; + + /** + * We are behind a symmetric nat. + */ + public static final String SYMMETRIC_NAT = "Symmetric NAT"; + + /** + * NAT type is Restricted Cone. + */ + public static final String RESTRICTED_CONE_NAT = "Restricted Cone NAT"; + + /** + * NAT type is port restricted cone. + */ + public static final String PORT_RESTRICTED_CONE_NAT= "Port Restricted Cone NAT"; + + private String natType = UNKNOWN; + + + private TransportAddress publicAddress = null; + + /** + * Creates a discovery report with natType = UNKNOWN and a null public + * address. + */ + StunDiscoveryReport() + { + } + + /** + * Returns the type of the NAT described in the report. + * @return the type of the NAT that this report is about. + */ + public String getNatType() + { + return natType; + } + + /** + * Sets the type of the NAT indicated by the report. + * @param natType the type of the NAT. + */ + void setNatType(String natType) + { + this.natType = natType; + } + + /** + * Returns the public addressed discovered by a discovery process. + * @return an Inetner address for public use. + */ + public TransportAddress getPublicAddress() + { + return publicAddress; + } + + /** + * Sets a public address. + * @param stunAddress An address that's accesible from everywhere. + */ + void setPublicAddress(TransportAddress stunAddress) + { + this.publicAddress = stunAddress; + } + + + /** + * Compares this object with obj. Two reports are considered equal if and + * only if both have the same nat type and their public addresses are + * equal or are both null. + * @param obj the object to compare against. + * @return true if the two objects are equal and false otherwise. + */ + public boolean equals(Object obj) + { + if(obj == null + || !(obj instanceof StunDiscoveryReport)) + return false; + + if(obj == this) + return true; + + StunDiscoveryReport target = (StunDiscoveryReport)obj; + + return ( target.getNatType() == getNatType() + && ( getPublicAddress() == null && target.getPublicAddress() == null + || target.getPublicAddress().equals(getPublicAddress()))); + } + + /** + * Returns a readable representation of the report. + * @return a readable representation of the report. + */ + public String toString() + { + return "The detected network configuration is: " + getNatType() + "\n" + + "Your mapped public address is: " + getPublicAddress(); + } + + +}